Fix CVE-2017-6891 in minitasn1 code
[platform/upstream/gnutls.git] / doc / gnutls.info-1
1 This is gnutls.info, produced by makeinfo version 6.3 from gnutls.texi.
2
3 This manual is last updated 23 March 2015 for version 3.3.27 of GnuTLS.
4
5 Copyright (C) 2001-2013 Free Software Foundation, Inc.\\ Copyright (C)
6 2001-2013 Nikos Mavrogiannopoulos
7
8      Permission is granted to copy, distribute and/or modify this
9      document under the terms of the GNU Free Documentation License,
10      Version 1.3 or any later version published by the Free Software
11      Foundation; with no Invariant Sections, no Front-Cover Texts, and
12      no Back-Cover Texts.  A copy of the license is included in the
13      section entitled "GNU Free Documentation License".
14 INFO-DIR-SECTION Software libraries
15 START-INFO-DIR-ENTRY
16 * GnuTLS: (gnutls).             GNU Transport Layer Security Library.
17 END-INFO-DIR-ENTRY
18
19 INFO-DIR-SECTION System Administration
20 START-INFO-DIR-ENTRY
21 * certtool: (gnutls)Invoking certtool.  Manipulate certificates and keys.
22 * gnutls-serv: (gnutls)Invoking gnutls-serv.    GnuTLS test server.
23 * gnutls-cli: (gnutls)Invoking gnutls-cli.      GnuTLS test client.
24 * gnutls-cli-debug: (gnutls)Invoking gnutls-cli-debug.  GnuTLS debug client.
25 * psktool: (gnutls)Invoking psktool.    Simple TLS-Pre-Shared-Keys manager.
26 * srptool: (gnutls)Invoking srptool.    Simple SRP password tool.
27 END-INFO-DIR-ENTRY
28
29 \1f
30 File: gnutls.info,  Node: Top,  Next: Preface,  Up: (dir)
31
32 GnuTLS
33 ******
34
35 This manual is last updated 23 March 2015 for version 3.3.27 of GnuTLS.
36
37 Copyright (C) 2001-2013 Free Software Foundation, Inc.\\ Copyright (C)
38 2001-2013 Nikos Mavrogiannopoulos
39
40      Permission is granted to copy, distribute and/or modify this
41      document under the terms of the GNU Free Documentation License,
42      Version 1.3 or any later version published by the Free Software
43      Foundation; with no Invariant Sections, no Front-Cover Texts, and
44      no Back-Cover Texts.  A copy of the license is included in the
45      section entitled "GNU Free Documentation License".
46
47 * Menu:
48
49 * Preface::
50 * Introduction to GnuTLS::
51 * Introduction to TLS::
52 * Authentication methods::
53 * Hardware security modules and abstract key types::
54 * How to use GnuTLS in applications::
55 * GnuTLS application examples::
56 * Using GnuTLS as a cryptographic library::
57 * Other included programs::
58 * Internal architecture of GnuTLS::
59 * Upgrading from previous versions::
60 * Support::
61 * Error codes::
62 * Supported ciphersuites::
63 * API reference::
64 * Copying Information::
65 * Bibliography::
66 * Function and Data Index::
67 * Concept Index::
68
69 \1f
70 File: gnutls.info,  Node: Preface,  Next: Introduction to GnuTLS,  Prev: Top,  Up: Top
71
72 1 Preface
73 *********
74
75 This document demonstrates and explains the GnuTLS library API. A brief
76 introduction to the protocols and the technology involved is also
77 included so that an application programmer can better understand the
78 GnuTLS purpose and actual offerings.  Even if GnuTLS is a typical
79 library software, it operates over several security and cryptographic
80 protocols which require the programmer to make careful and correct usage
81 of them.  Otherwise it is likely to only obtain a false sense of
82 security.  The term of security is very broad even if restricted to
83 computer software, and cannot be confined to a single cryptographic
84 library.  For that reason, do not consider any program secure just
85 because it uses GnuTLS; there are several ways to compromise a program
86 or a communication line and GnuTLS only helps with some of them.
87
88 Although this document tries to be self contained, basic network
89 programming and public key infrastructure (PKI) knowledge is assumed in
90 most of it.  A good introduction to networking can be found in
91 [_STEVENS_], to public key infrastructure in [_GUTPKI_] and to security
92 engineering in [_ANDERSON_].
93
94 Updated versions of the GnuTLS software and this document will be
95 available from <http://www.gnutls.org/>.
96
97 \1f
98 File: gnutls.info,  Node: Introduction to GnuTLS,  Next: Introduction to TLS,  Prev: Preface,  Up: Top
99
100 2 Introduction to GnuTLS
101 ************************
102
103 In brief GnuTLS can be described as a library which offers an API to
104 access secure communication protocols.  These protocols provide privacy
105 over insecure lines, and were designed to prevent eavesdropping,
106 tampering, or message forgery.
107
108 Technically GnuTLS is a portable ANSI C based library which implements
109 the protocols ranging from SSL 3.0 to TLS 1.2 (see *note Introduction to
110 TLS::, for a detailed description of the protocols), accompanied with
111 the required framework for authentication and public key infrastructure.
112 Important features of the GnuTLS library include:
113
114    * Support for TLS 1.2, TLS 1.1, TLS 1.0 and SSL 3.0 protocols.
115
116    * Support for Datagram TLS 1.0 and 1.2.
117
118    * Support for handling and verification of X.509 and OpenPGP
119      certificates.
120
121    * Support for password authentication using TLS-SRP.
122
123    * Support for keyed authentication using TLS-PSK.
124
125    * Support for TPM, PKCS #11 tokens and smart-cards.
126
127 The GnuTLS library consists of three independent parts, namely the "TLS
128 protocol part", the "Certificate part", and the "Cryptographic back-end"
129 part.  The "TLS protocol part" is the actual protocol implementation,
130 and is entirely implemented within the GnuTLS library.  The "Certificate
131 part" consists of the certificate parsing, and verification functions
132 and it uses functionality from the libtasn1 library.  The "Cryptographic
133 back-end" is provided by the nettle and gmplib libraries.
134
135 * Menu:
136
137 * Downloading and installing::
138 * Document overview::
139
140 \1f
141 File: gnutls.info,  Node: Downloading and installing,  Next: Document overview,  Up: Introduction to GnuTLS
142
143 2.1 Downloading and installing
144 ==============================
145
146 GnuTLS is available for download at:
147 <http://www.gnutls.org/download.html>
148
149 GnuTLS uses a development cycle where even minor version numbers
150 indicate a stable release and a odd minor version number indicate a
151 development release.  For example, GnuTLS 1.6.3 denote a stable release
152 since 6 is even, and GnuTLS 1.7.11 denote a development release since 7
153 is odd.
154
155 GnuTLS depends on 'nettle' and 'gmplib', and you will need to install it
156 before installing GnuTLS. The 'nettle' library is available from
157 <http://www.lysator.liu.se/~nisse/nettle/>, while 'gmplib' is available
158 from <http://www.gmplib.org/>.  Don't forget to verify the cryptographic
159 signature after downloading source code packages.
160
161 The package is then extracted, configured and built like many other
162 packages that use Autoconf.  For detailed information on configuring and
163 building it, refer to the 'INSTALL' file that is part of the
164 distribution archive.  Typically you invoke './configure' and then 'make
165 check install'.  There are a number of compile-time parameters, as
166 discussed below.
167
168 Several parts of GnuTLS require ASN.1 functionality, which is provided
169 by a library called libtasn1.  A copy of libtasn1 is included in GnuTLS.
170 If you want to install it separately (e.g., to make it possibly to use
171 libtasn1 in other programs), you can get it from
172 <http://www.gnu.org/software/libtasn1/>.
173
174 The compression library, 'libz', the PKCS #11 helper library 'p11-kit',
175 as well as the TPM library 'trousers', are optional dependencies.  You
176 may get libz from <http://www.zlib.net/>, p11-kit from
177 <http://p11-glue.freedesktop.org/> and trousers from
178 <http://trousers.sourceforge.net/>.
179
180 A few 'configure' options may be relevant, summarized below.  They
181 disable or enable particular features, to create a smaller library with
182 only the required features.  Note however, that although a smaller
183 library is generated, the included programs are not guaranteed to
184 compile if some of these options are given.
185
186 --disable-srp-authentication
187 --disable-psk-authentication
188 --disable-anon-authentication
189 --disable-openpgp-authentication
190 --disable-dhe
191 --disable-ecdhe
192 --disable-openssl-compatibility
193 --disable-dtls-srtp-support
194 --disable-alpn-support
195 --disable-heartbeat-support
196 --disable-libdane
197 --without-p11-kit
198 --without-tpm
199 --without-zlib
200
201
202 For the complete list, refer to the output from 'configure --help'.
203
204 \1f
205 File: gnutls.info,  Node: Document overview,  Prev: Downloading and installing,  Up: Introduction to GnuTLS
206
207 2.2 Overview
208 ============
209
210 In this document we present an overview of the supported security
211 protocols in *note Introduction to TLS::, and continue by providing more
212 information on the certificate authentication in *note Certificate
213 authentication::, and shared-key as well anonymous authentication in
214 *note Shared-key and anonymous authentication::.  We elaborate on
215 certificate authentication by demonstrating advanced usage of the API in
216 *note More on certificate authentication::.  The core of the TLS library
217 is presented in *note How to use GnuTLS in applications:: and example
218 applications are listed in *note GnuTLS application examples::.  In
219 *note Other included programs:: the usage of few included programs that
220 may assist debugging is presented.  The last chapter is *note Internal
221 architecture of GnuTLS:: that provides a short introduction to GnuTLS'
222 internal architecture.
223
224 \1f
225 File: gnutls.info,  Node: Introduction to TLS,  Next: Authentication methods,  Prev: Introduction to GnuTLS,  Up: Top
226
227 3 Introduction to TLS and DTLS
228 ******************************
229
230 TLS stands for "Transport Layer Security" and is the successor of SSL,
231 the Secure Sockets Layer protocol [_SSL3_] designed by Netscape.  TLS is
232 an Internet protocol, defined by IETF(1), described in [_RFC5246_].  The
233 protocol provides confidentiality, and authentication layers over any
234 reliable transport layer.  The description, above, refers to TLS 1.0 but
235 applies to all other TLS versions as the differences between the
236 protocols are not major.
237
238 The DTLS protocol, or "Datagram TLS" [_RFC4347_] is a protocol with
239 identical goals as TLS, but can operate under unreliable transport
240 layers such as UDP.  The discussions below apply to this protocol as
241 well, except when noted otherwise.
242
243 * Menu:
244
245 * TLS layers::
246 * The transport layer::
247 * The TLS record protocol::
248 * The TLS Alert Protocol::
249 * The TLS Handshake Protocol::
250 * TLS Extensions::
251 * How to use TLS in application protocols::
252 * On SSL 2 and older protocols::
253
254    ---------- Footnotes ----------
255
256    (1) IETF, or Internet Engineering Task Force, is a large open
257 international community of network designers, operators, vendors, and
258 researchers concerned with the evolution of the Internet architecture
259 and the smooth operation of the Internet.  It is open to any interested
260 individual.
261
262 \1f
263 File: gnutls.info,  Node: TLS layers,  Next: The transport layer,  Up: Introduction to TLS
264
265 3.1 TLS layers
266 ==============
267
268 TLS is a layered protocol, and consists of the record protocol, the
269 handshake protocol and the alert protocol.  The record protocol is to
270 serve all other protocols and is above the transport layer.  The record
271 protocol offers symmetric encryption, data authenticity, and optionally
272 compression.  The alert protocol offers some signaling to the other
273 protocols.  It can help informing the peer for the cause of failures and
274 other error conditions.  *Note The Alert Protocol::, for more
275 information.  The alert protocol is above the record protocol.
276
277 The handshake protocol is responsible for the security parameters'
278 negotiation, the initial key exchange and authentication.  *Note The
279 Handshake Protocol::, for more information about the handshake protocol.
280 The protocol layering in TLS is shown in *note Figure 3.1:
281 fig-tls-layers.
282
283 \0\b[image src="gnutls-layers.png"\0\b]
284
285 Figure 3.1: The TLS protocol layers.
286
287 \1f
288 File: gnutls.info,  Node: The transport layer,  Next: The TLS record protocol,  Prev: TLS layers,  Up: Introduction to TLS
289
290 3.2 The transport layer
291 =======================
292
293 TLS is not limited to any transport layer and can be used above any
294 transport layer, as long as it is a reliable one.  DTLS can be used over
295 reliable and unreliable transport layers.  GnuTLS supports TCP and UDP
296 layers transparently using the Berkeley sockets API. However, any
297 transport layer can be used by providing callbacks for GnuTLS to access
298 the transport layer (for details see *note Setting up the transport
299 layer::).
300
301 \1f
302 File: gnutls.info,  Node: The TLS record protocol,  Next: The TLS Alert Protocol,  Prev: The transport layer,  Up: Introduction to TLS
303
304 3.3 The TLS record protocol
305 ===========================
306
307 The record protocol is the secure communications provider.  Its purpose
308 is to encrypt, authenticate and --optionally-- compress packets.  The
309 record layer functions can be called at any time after the handshake
310 process is finished, when there is need to receive or send data.  In
311 DTLS however, due to re-transmission timers used in the handshake
312 out-of-order handshake data might be received for some time (maximum 60
313 seconds) after the handshake process is finished.
314
315 The functions to access the record protocol are limited to send and
316 receive functions, which might, given the importance of this protocol in
317 TLS, seem awkward.  This is because the record protocol's parameters are
318 all set by the handshake protocol.  The record protocol initially starts
319 with NULL parameters, which means no encryption, and no MAC is used.
320 Encryption and authentication begin just after the handshake protocol
321 has finished.
322
323 * Menu:
324
325 * Encryption algorithms used in the record layer::
326 * Compression algorithms used in the record layer::
327 * Weaknesses and countermeasures::
328 * On Record Padding::
329
330 \1f
331 File: gnutls.info,  Node: Encryption algorithms used in the record layer,  Next: Compression algorithms used in the record layer,  Up: The TLS record protocol
332
333 3.3.1 Encryption algorithms used in the record layer
334 ----------------------------------------------------
335
336 Confidentiality in the record layer is achieved by using symmetric block
337 encryption algorithms like '3DES', 'AES' or stream algorithms like
338 'ARCFOUR_128'.  Ciphers are encryption algorithms that use a single,
339 secret, key to encrypt and decrypt data.  Block algorithms in CBC mode
340 also provide protection against statistical analysis of the data.  Thus,
341 if you're using the TLS protocol, a random number of blocks will be
342 appended to data, to prevent eavesdroppers from guessing the actual data
343 size.
344
345 The supported in GnuTLS ciphers and MAC algorithms are shown in *note
346 Table 3.1: tab:ciphers. and *note Table 3.2: tab:macs.
347
348 Algorithm      Description
349 ------------------------------------------------------------------
350 3DES_CBC       This is the DES block cipher algorithm used with
351                triple encryption (EDE). Has 64 bits block size
352                and is used in CBC mode.
353                
354 ARCFOUR_128    ARCFOUR_128 is a compatible algorithm with RSA's
355                RC4 algorithm, which is considered to be a trade
356                secret.  It is a fast cipher but considered weak
357                today.
358                
359 AES_CBC        AES or RIJNDAEL is the block cipher algorithm
360                that replaces the old DES algorithm.  Has 128
361                bits block size and is used in CBC mode.
362                
363 AES_GCM        This is the AES algorithm in the authenticated
364                encryption GCM mode.  This mode combines message
365                authentication and encryption and can be
366                extremely fast on CPUs that support hardware
367                acceleration.
368                
369 CAMELLIA_CBC   This is an 128-bit block cipher developed by
370                Mitsubishi and NTT. It is one of the approved
371                ciphers of the European NESSIE and Japanese
372                CRYPTREC projects.
373                
374
375 Table 3.1: Supported ciphers.
376
377 Algorithm      Description
378 ------------------------------------------------------------------
379 MAC_MD5        This is an HMAC based on MD5 a cryptographic
380                hash algorithm designed by Ron Rivest.  Outputs
381                128 bits of data.
382                
383 MAC_SHA1       An HMAC based on the SHA1 cryptographic hash
384                algorithm designed by NSA. Outputs 160 bits of
385                data.
386                
387 MAC_SHA256     An HMAC based on SHA256.  Outputs 256 bits of
388                data.
389                
390 MAC_AEAD       This indicates that an authenticated encryption
391                algorithm, such as GCM, is in use.
392                
393
394 Table 3.2: Supported MAC algorithms.
395
396 \1f
397 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
398
399 3.3.2 Compression algorithms used in the record layer
400 -----------------------------------------------------
401
402 The TLS record layer also supports compression.  The algorithms
403 implemented in GnuTLS can be found in the table below.  The included
404 algorithms perform really good when text, or other compressible data are
405 to be transferred, but offer nothing on already compressed data, such as
406 compressed images, zipped archives etc.  These compression algorithms,
407 may be useful in high bandwidth TLS tunnels, and in cases where network
408 usage has to be minimized.  It should be noted however that compression
409 increases latency.
410
411 The record layer compression in GnuTLS is implemented based on
412 [_RFC3749_].  The supported algorithms are shown below.
413
414 'GNUTLS_COMP_UNKNOWN'
415      Unknown compression method.
416 'GNUTLS_COMP_NULL'
417      The NULL compression method (no compression).
418 'GNUTLS_COMP_DEFLATE'
419      The DEFLATE compression method from zlib.
420 'GNUTLS_COMP_ZLIB'
421      Same as 'GNUTLS_COMP_DEFLATE' .
422
423 Figure 3.2: Supported compression algorithms
424
425 Note that compression enables attacks such as traffic analysis, or even
426 plaintext recovery under certain circumstances.  To avoid some of these
427 attacks GnuTLS allows each record to be compressed independently (i.e.,
428 stateless compression), by using the "%STATELESS_COMPRESSION" priority
429 string, in order to be used in cases where the attacker controlled data
430 are pt in separate records.
431
432 \1f
433 File: gnutls.info,  Node: Weaknesses and countermeasures,  Next: On Record Padding,  Prev: Compression algorithms used in the record layer,  Up: The TLS record protocol
434
435 3.3.3 Weaknesses and countermeasures
436 ------------------------------------
437
438 Some weaknesses that may affect the security of the record layer have
439 been found in TLS 1.0 protocol.  These weaknesses can be exploited by
440 active attackers, and exploit the facts that
441
442   1. TLS has separate alerts for "decryption_failed" and
443      "bad_record_mac"
444
445   2. The decryption failure reason can be detected by timing the
446      response time.
447
448   3. The IV for CBC encrypted packets is the last block of the previous
449      encrypted packet.
450
451 Those weaknesses were solved in TLS 1.1 [_RFC4346_] which is implemented
452 in GnuTLS.  For this reason we suggest to always negotiate the highest
453 supported TLS version with the peer(1).  For a detailed discussion of
454 the issues see the archives of the TLS Working Group mailing list and
455 [_CBCATT_].
456
457    ---------- Footnotes ----------
458
459    (1) If this is not possible then please consult *note
460 Interoperability::.
461
462 \1f
463 File: gnutls.info,  Node: On Record Padding,  Prev: Weaknesses and countermeasures,  Up: The TLS record protocol
464
465 3.3.4 On record padding
466 -----------------------
467
468 The TLS protocol allows for extra padding of records in CBC ciphers, to
469 prevent statistical analysis based on the length of exchanged messages
470 (see [_RFC5246_] section 6.2.3.2).  GnuTLS appears to be one of few
471 implementations that take advantage of this feature: the user can
472 provide some plaintext data with a range of lengths she wishes to hide,
473 and GnuTLS adds extra padding to make sure the attacker cannot tell the
474 real plaintext length is in a range smaller than the user-provided one.
475 Use *note gnutls_record_send_range:: to send length-hidden messages and
476 *note gnutls_record_can_use_length_hiding:: to check whether the current
477 session supports length hiding.  Using the standard *note
478 gnutls_record_send:: will only add minimal padding.
479
480 The TLS implementation in the Symbian operating system, frequently used
481 by Nokia and Sony-Ericsson mobile phones, cannot handle non-minimal
482 record padding.  What happens when one of these clients handshake with a
483 GnuTLS server is that the client will fail to compute the correct MAC
484 for the record.  The client sends a TLS alert ('bad_record_mac') and
485 disconnects.  Typically this will result in error messages such as 'A
486 TLS fatal alert has been received', 'Bad record MAC', or both, on the
487 GnuTLS server side.
488
489 If compatibility with such devices is a concern, not sending
490 length-hidden messages solves the problem by using minimal padding.
491
492 If you implement an application that has a configuration file, we
493 recommend that you make it possible for users or administrators to
494 specify a GnuTLS protocol priority string, which is used by your
495 application via *note gnutls_priority_set::.  To allow the best
496 flexibility, make it possible to have a different priority string for
497 different incoming IP addresses.
498
499 \1f
500 File: gnutls.info,  Node: The TLS Alert Protocol,  Next: The TLS Handshake Protocol,  Prev: The TLS record protocol,  Up: Introduction to TLS
501
502 3.4 The TLS alert protocol
503 ==========================
504
505 The alert protocol is there to allow signals to be sent between peers.
506 These signals are mostly used to inform the peer about the cause of a
507 protocol failure.  Some of these signals are used internally by the
508 protocol and the application protocol does not have to cope with them
509 (e.g.  'GNUTLS_A_CLOSE_NOTIFY'), and others refer to the application
510 protocol solely (e.g.  'GNUTLS_A_USER_CANCELLED').  An alert signal
511 includes a level indication which may be either fatal or warning.  Fatal
512 alerts always terminate the current connection, and prevent future
513 re-negotiations using the current session ID. All alert messages are
514 summarized in the table below.
515
516 The alert messages are protected by the record protocol, thus the
517 information that is included does not leak.  You must take extreme care
518 for the alert information not to leak to a possible attacker, via public
519 log files etc.
520
521 Alert                                    ID      Description
522 ------------------------------------------------------------------------
523 GNUTLS_A_CLOSE_NOTIFY                    0       Close notify
524 GNUTLS_A_UNEXPECTED_MESSAGE              10      Unexpected message
525 GNUTLS_A_BAD_RECORD_MAC                  20      Bad record MAC
526 GNUTLS_A_DECRYPTION_FAILED               21      Decryption failed
527 GNUTLS_A_RECORD_OVERFLOW                 22      Record overflow
528 GNUTLS_A_DECOMPRESSION_FAILURE           30      Decompression failed
529 GNUTLS_A_HANDSHAKE_FAILURE               40      Handshake failed
530 GNUTLS_A_SSL3_NO_CERTIFICATE             41      No certificate (SSL
531                                                  3.0)
532 GNUTLS_A_BAD_CERTIFICATE                 42      Certificate is bad
533 GNUTLS_A_UNSUPPORTED_CERTIFICATE         43      Certificate is not
534                                                  supported
535 GNUTLS_A_CERTIFICATE_REVOKED             44      Certificate was
536                                                  revoked
537 GNUTLS_A_CERTIFICATE_EXPIRED             45      Certificate is
538                                                  expired
539 GNUTLS_A_CERTIFICATE_UNKNOWN             46      Unknown certificate
540 GNUTLS_A_ILLEGAL_PARAMETER               47      Illegal parameter
541 GNUTLS_A_UNKNOWN_CA                      48      CA is unknown
542 GNUTLS_A_ACCESS_DENIED                   49      Access was denied
543 GNUTLS_A_DECODE_ERROR                    50      Decode error
544 GNUTLS_A_DECRYPT_ERROR                   51      Decrypt error
545 GNUTLS_A_EXPORT_RESTRICTION              60      Export restriction
546 GNUTLS_A_PROTOCOL_VERSION                70      Error in protocol
547                                                  version
548 GNUTLS_A_INSUFFICIENT_SECURITY           71      Insufficient
549                                                  security
550 GNUTLS_A_INTERNAL_ERROR                  80      Internal error
551 GNUTLS_A_USER_CANCELED                   90      User canceled
552 GNUTLS_A_NO_RENEGOTIATION                100     No renegotiation is
553                                                  allowed
554 GNUTLS_A_UNSUPPORTED_EXTENSION           110     An unsupported
555                                                  extension was sent
556 GNUTLS_A_CERTIFICATE_UNOBTAINABLE        111     Could not retrieve
557                                                  the specified
558                                                  certificate
559 GNUTLS_A_UNRECOGNIZED_NAME               112     The server name sent
560                                                  was not recognized
561 GNUTLS_A_UNKNOWN_PSK_IDENTITY            115     The SRP/PSK username
562                                                  is missing or not
563                                                  known
564 GNUTLS_A_NO_APPLICATION_PROTOCOL         120     No supported
565                                                  application protocol
566                                                  could be negotiated
567
568 \1f
569 File: gnutls.info,  Node: The TLS Handshake Protocol,  Next: TLS Extensions,  Prev: The TLS Alert Protocol,  Up: Introduction to TLS
570
571 3.5 The TLS handshake protocol
572 ==============================
573
574 The handshake protocol is responsible for the ciphersuite negotiation,
575 the initial key exchange, and the authentication of the two peers.  This
576 is fully controlled by the application layer, thus your program has to
577 set up the required parameters.  The main handshake function is *note
578 gnutls_handshake::.  In the next paragraphs we elaborate on the
579 handshake protocol, i.e., the ciphersuite negotiation.
580
581 * Menu:
582
583 * TLS Cipher Suites::           TLS session parameters.
584 * Authentication::              TLS authentication.
585 * Client Authentication::       Requesting a certificate from the client.
586 * Resuming Sessions::           Reusing previously established keys.
587
588 \1f
589 File: gnutls.info,  Node: TLS Cipher Suites,  Next: Authentication,  Up: The TLS Handshake Protocol
590
591 3.5.1 TLS ciphersuites
592 ----------------------
593
594 The handshake protocol of TLS negotiates cipher suites of a special form
595 illustrated by the 'TLS_DHE_RSA_WITH_3DES_CBC_SHA' cipher suite name.  A
596 typical cipher suite contains these parameters:
597
598    * The key exchange algorithm.  'DHE_RSA' in the example.
599
600    * The Symmetric encryption algorithm and mode '3DES_CBC' in this
601      example.
602
603    * The MAC(1) algorithm used for authentication.  'MAC_SHA' is used in
604      the above example.
605
606 The cipher suite negotiated in the handshake protocol will affect the
607 record protocol, by enabling encryption and data authentication.  Note
608 that you should not over rely on TLS to negotiate the strongest
609 available cipher suite.  Do not enable ciphers and algorithms that you
610 consider weak.
611
612 All the supported ciphersuites are listed in *note ciphersuites::.
613
614    ---------- Footnotes ----------
615
616    (1) MAC stands for Message Authentication Code.  It can be described
617 as a keyed hash algorithm.  See RFC2104.
618
619 \1f
620 File: gnutls.info,  Node: Authentication,  Next: Client Authentication,  Prev: TLS Cipher Suites,  Up: The TLS Handshake Protocol
621
622 3.5.2 Authentication
623 --------------------
624
625 The key exchange algorithms of the TLS protocol offer authentication,
626 which is a prerequisite for a secure connection.  The available
627 authentication methods in GnuTLS follow.
628
629    * Certificate authentication: Authenticated key exchange using public
630      key infrastructure and certificates (X.509 or OpenPGP).
631    * SRP authentication: Authenticated key exchange using a password.
632    * PSK authentication: Authenticated key exchange using a pre-shared
633      key.
634    * Anonymous authentication: Key exchange without peer authentication.
635
636 \1f
637 File: gnutls.info,  Node: Client Authentication,  Next: Resuming Sessions,  Prev: Authentication,  Up: The TLS Handshake Protocol
638
639 3.5.3 Client authentication
640 ---------------------------
641
642 In the case of ciphersuites that use certificate authentication, the
643 authentication of the client is optional in TLS.  A server may request a
644 certificate from the client using the *note
645 gnutls_certificate_server_set_request:: function.  We elaborate in *note
646 Certificate credentials::.
647
648 \1f
649 File: gnutls.info,  Node: Resuming Sessions,  Prev: Client Authentication,  Up: The TLS Handshake Protocol
650
651 3.5.4 Resuming sessions
652 -----------------------
653
654 The TLS handshake process performs expensive calculations and a busy
655 server might easily be put under load.  To reduce the load, session
656 resumption may be used.  This is a feature of the TLS protocol which
657 allows a client to connect to a server after a successful handshake,
658 without the expensive calculations.  This is achieved by re-using the
659 previously established keys, meaning the server needs to store the state
660 of established connections (unless session tickets are used - *note
661 Session tickets::).
662
663 Session resumption is an integral part of GnuTLS, and *note Session
664 resumption::, *note ex-resume-client:: illustrate typical uses of it.
665
666 \1f
667 File: gnutls.info,  Node: TLS Extensions,  Next: How to use TLS in application protocols,  Prev: The TLS Handshake Protocol,  Up: Introduction to TLS
668
669 3.6 TLS extensions
670 ==================
671
672 A number of extensions to the TLS protocol have been proposed mainly in
673 [_TLSEXT_]. The extensions supported in GnuTLS are discussed in the
674 subsections that follow.
675
676 * Menu:
677
678 * Maximum fragment length negotiation::
679 * Server name indication::
680 * Session tickets::
681 * HeartBeat::
682 * Safe renegotiation::
683 * OCSP status request::
684 * SRTP::
685 * Application Layer Protocol Negotiation (ALPN)::
686
687 \1f
688 File: gnutls.info,  Node: Maximum fragment length negotiation,  Next: Server name indication,  Up: TLS Extensions
689
690 3.6.1 Maximum fragment length negotiation
691 -----------------------------------------
692
693 This extension allows a TLS implementation to negotiate a smaller value
694 for record packet maximum length.  This extension may be useful to
695 clients with constrained capabilities.  The functions shown below can be
696 used to control this extension.
697
698 'SIZE_T *note gnutls_record_get_max_size:: (gnutls_session_t SESSION)'
699 'SSIZE_T *note gnutls_record_set_max_size:: (gnutls_session_t SESSION, size_t SIZE)'
700
701 \1f
702 File: gnutls.info,  Node: Server name indication,  Next: Session tickets,  Prev: Maximum fragment length negotiation,  Up: TLS Extensions
703
704 3.6.2 Server name indication
705 ----------------------------
706
707 A common problem in HTTPS servers is the fact that the TLS protocol is
708 not aware of the hostname that a client connects to, when the handshake
709 procedure begins.  For that reason the TLS server has no way to know
710 which certificate to send.
711
712 This extension solves that problem within the TLS protocol, and allows a
713 client to send the HTTP hostname before the handshake begins within the
714 first handshake packet.  The functions *note gnutls_server_name_set::
715 and *note gnutls_server_name_get:: can be used to enable this extension,
716 or to retrieve the name sent by a client.
717
718 'INT *note gnutls_server_name_set:: (gnutls_session_t SESSION, gnutls_server_name_type_t TYPE, const void * NAME, size_t NAME_LENGTH)'
719 'INT *note gnutls_server_name_get:: (gnutls_session_t SESSION, void * DATA, size_t * DATA_LENGTH, unsigned int * TYPE, unsigned int INDX)'
720
721 \1f
722 File: gnutls.info,  Node: Session tickets,  Next: HeartBeat,  Prev: Server name indication,  Up: TLS Extensions
723
724 3.6.3 Session tickets
725 ---------------------
726
727 To resume a TLS session, the server normally stores session parameters.
728 This complicates deployment, and can be avoided by delegating the
729 storage to the client.  Because session parameters are sensitive they
730 are encrypted and authenticated with a key only known to the server and
731 then sent to the client.  The Session Tickets extension is described in
732 RFC 5077 [_TLSTKT_].
733
734 A disadvantage of session tickets is that they eliminate the effects of
735 forward secrecy when a server uses the same key for long time.  That is,
736 the secrecy of all sessions on a server using tickets depends on the
737 ticket key being kept secret.  For that reason server keys should be
738 rotated and discarded regularly.
739
740 Since version 3.1.3 GnuTLS clients transparently support session
741 tickets.
742
743 \1f
744 File: gnutls.info,  Node: HeartBeat,  Next: Safe renegotiation,  Prev: Session tickets,  Up: TLS Extensions
745
746 3.6.4 HeartBeat
747 ---------------
748
749 This is a TLS extension that allows to ping and receive confirmation
750 from the peer, and is described in [_RFC6520_].  The extension is
751 disabled by default and *note gnutls_heartbeat_enable:: can be used to
752 enable it.  A policy may be negotiated to only allow sending heartbeat
753 messages or sending and receiving.  The current session policy can be
754 checked with *note gnutls_heartbeat_allowed::.  The requests coming from
755 the peer result to 'GNUTLS_E_HERTBEAT_PING_RECEIVED' being returned from
756 the receive function.  Ping requests to peer can be send via *note
757 gnutls_heartbeat_ping::.
758
759 'INT *note gnutls_heartbeat_allowed:: (gnutls_session_t SESSION, unsigned int TYPE)'
760 'VOID *note gnutls_heartbeat_enable:: (gnutls_session_t SESSION, unsigned int TYPE)'
761
762 'INT *note gnutls_heartbeat_ping:: (gnutls_session_t SESSION, size_t DATA_SIZE, unsigned int MAX_TRIES, unsigned int FLAGS)'
763 'INT *note gnutls_heartbeat_pong:: (gnutls_session_t SESSION, unsigned int FLAGS)'
764 'VOID *note gnutls_heartbeat_set_timeouts:: (gnutls_session_t SESSION, unsigned int RETRANS_TIMEOUT, unsigned int TOTAL_TIMEOUT)'
765 'UNSIGNED INT *note gnutls_heartbeat_get_timeout:: (gnutls_session_t SESSION)'
766
767 \1f
768 File: gnutls.info,  Node: Safe renegotiation,  Next: OCSP status request,  Prev: HeartBeat,  Up: TLS Extensions
769
770 3.6.5 Safe renegotiation
771 ------------------------
772
773 TLS gives the option to two communicating parties to renegotiate and
774 update their security parameters.  One useful example of this feature
775 was for a client to initially connect using anonymous negotiation to a
776 server, and the renegotiate using some authenticated ciphersuite.  This
777 occurred to avoid having the client sending its credentials in the
778 clear.
779
780 However this renegotiation, as initially designed would not ensure that
781 the party one is renegotiating is the same as the one in the initial
782 negotiation.  For example one server could forward all renegotiation
783 traffic to an other server who will see this traffic as an initial
784 negotiation attempt.
785
786 This might be seen as a valid design decision, but it seems it was not
787 widely known or understood, thus today some application protocols use
788 the TLS renegotiation feature in a manner that enables a malicious
789 server to insert content of his choice in the beginning of a TLS
790 session.
791
792 The most prominent vulnerability was with HTTPS. There servers request a
793 renegotiation to enforce an anonymous user to use a certificate in order
794 to access certain parts of a web site.  The attack works by having the
795 attacker simulate a client and connect to a server, with server-only
796 authentication, and send some data intended to cause harm.  The server
797 will then require renegotiation from him in order to perform the
798 request.  When the proper client attempts to contact the server, the
799 attacker hijacks that connection and forwards traffic to the initial
800 server that requested renegotiation.  The attacker will not be able to
801 read the data exchanged between the client and the server.  However, the
802 server will (incorrectly) assume that the initial request sent by the
803 attacker was sent by the now authenticated client.  The result is a
804 prefix plain-text injection attack.
805
806 The above is just one example.  Other vulnerabilities exists that do not
807 rely on the TLS renegotiation to change the client's authenticated
808 status (either TLS or application layer).
809
810 While fixing these application protocols and implementations would be
811 one natural reaction, an extension to TLS has been designed that
812 cryptographically binds together any renegotiated handshakes with the
813 initial negotiation.  When the extension is used, the attack is detected
814 and the session can be terminated.  The extension is specified in
815 [_RFC5746_].
816
817 GnuTLS supports the safe renegotiation extension.  The default behavior
818 is as follows.  Clients will attempt to negotiate the safe renegotiation
819 extension when talking to servers.  Servers will accept the extension
820 when presented by clients.  Clients and servers will permit an initial
821 handshake to complete even when the other side does not support the safe
822 renegotiation extension.  Clients and servers will refuse renegotiation
823 attempts when the extension has not been negotiated.
824
825 Note that permitting clients to connect to servers when the safe
826 renegotiation extension is not enabled, is open up for attacks.
827 Changing this default behavior would prevent interoperability against
828 the majority of deployed servers out there.  We will reconsider this
829 default behavior in the future when more servers have been upgraded.
830 Note that it is easy to configure clients to always require the safe
831 renegotiation extension from servers.
832
833 To modify the default behavior, we have introduced some new priority
834 strings (see *note Priority Strings::).  The '%UNSAFE_RENEGOTIATION'
835 priority string permits (re-)handshakes even when the safe renegotiation
836 extension was not negotiated.  The default behavior is
837 '%PARTIAL_RENEGOTIATION' that will prevent renegotiation with clients
838 and servers not supporting the extension.  This is secure for servers
839 but leaves clients vulnerable to some attacks, but this is a trade-off
840 between security and compatibility with old servers.  The
841 '%SAFE_RENEGOTIATION' priority string makes clients and servers require
842 the extension for every handshake.  The latter is the most secure option
843 for clients, at the cost of not being able to connect to legacy servers.
844 Servers will also deny clients that do not support the extension from
845 connecting.
846
847 It is possible to disable use of the extension completely, in both
848 clients and servers, by using the '%DISABLE_SAFE_RENEGOTIATION' priority
849 string however we strongly recommend you to only do this for debugging
850 and test purposes.
851
852 The default values if the flags above are not specified are:
853
854 'Server:'
855      %PARTIAL_RENEGOTIATION
856
857 'Client:'
858      %PARTIAL_RENEGOTIATION
859
860 For applications we have introduced a new API related to safe
861 renegotiation.  The *note gnutls_safe_renegotiation_status:: function is
862 used to check if the extension has been negotiated on a session, and can
863 be used both by clients and servers.
864
865 \1f
866 File: gnutls.info,  Node: OCSP status request,  Next: SRTP,  Prev: Safe renegotiation,  Up: TLS Extensions
867
868 3.6.6 OCSP status request
869 -------------------------
870
871 The Online Certificate Status Protocol (OCSP) is a protocol that allows
872 the client to verify the server certificate for revocation without
873 messing with certificate revocation lists.  Its drawback is that it
874 requires the client to connect to the server's CA OCSP server and
875 request the status of the certificate.  This extension however, enables
876 a TLS server to include its CA OCSP server response in the handshake.
877 That is an HTTPS server may periodically run 'ocsptool' (see *note
878 ocsptool Invocation::) to obtain its certificate revocation status and
879 serve it to the clients.  That way a client avoids an additional
880 connection to the OCSP server.
881
882 'VOID *note gnutls_certificate_set_ocsp_status_request_function:: (gnutls_certificate_credentials_t SC, gnutls_status_request_ocsp_func OCSP_FUNC, void * PTR)'
883 'INT *note gnutls_certificate_set_ocsp_status_request_file:: (gnutls_certificate_credentials_t SC, const char * RESPONSE_FILE, unsigned int FLAGS)'
884 '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)'
885 'INT *note gnutls_ocsp_status_request_is_checked:: (gnutls_session_t SESSION, unsigned int FLAGS)'
886
887 A server is required to provide the OCSP server's response using the
888 *note gnutls_certificate_set_ocsp_status_request_file::.  The response
889 may be obtained periodically using the following command.
890
891      ocsptool --ask --load-cert server_cert.pem --load-issuer the_issuer.pem
892               --load-signer the_issuer.pem --outfile ocsp.response
893
894 Since version 3.1.3 GnuTLS clients transparently support the certificate
895 status request.
896
897 \1f
898 File: gnutls.info,  Node: SRTP,  Next: Application Layer Protocol Negotiation (ALPN),  Prev: OCSP status request,  Up: TLS Extensions
899
900 3.6.7 SRTP
901 ----------
902
903 The TLS protocol was extended in [_RFC5764_] to provide keying material
904 to the Secure RTP (SRTP) protocol.  The SRTP protocol provides an
905 encapsulation of encrypted data that is optimized for voice data.  With
906 the SRTP TLS extension two peers can negotiate keys using TLS or DTLS
907 and obtain keying material for use with SRTP. The available SRTP
908 profiles are listed below.
909
910 'GNUTLS_SRTP_AES128_CM_HMAC_SHA1_80'
911      128 bit AES with a 80 bit HMAC-SHA1
912 'GNUTLS_SRTP_AES128_CM_HMAC_SHA1_32'
913      128 bit AES with a 32 bit HMAC-SHA1
914 'GNUTLS_SRTP_NULL_HMAC_SHA1_80'
915      NULL cipher with a 80 bit HMAC-SHA1
916 'GNUTLS_SRTP_NULL_HMAC_SHA1_32'
917      NULL cipher with a 32 bit HMAC-SHA1
918
919 Figure 3.3: Supported SRTP profiles
920
921 To enable use the following functions.
922
923 'INT *note gnutls_srtp_set_profile:: (gnutls_session_t SESSION, gnutls_srtp_profile_t PROFILE)'
924 'INT *note gnutls_srtp_set_profile_direct:: (gnutls_session_t SESSION, const char * PROFILES, const char ** ERR_POS)'
925
926 To obtain the negotiated keys use the function below.
927
928  -- Function: int gnutls_srtp_get_keys (gnutls_session_t SESSION, void *
929           KEY_MATERIAL, unsigned int KEY_MATERIAL_SIZE, gnutls_datum_t *
930           CLIENT_KEY, gnutls_datum_t * CLIENT_SALT, gnutls_datum_t *
931           SERVER_KEY, gnutls_datum_t * SERVER_SALT)
932      SESSION: is a 'gnutls_session_t' structure.
933
934      KEY_MATERIAL: Space to hold the generated key material
935
936      KEY_MATERIAL_SIZE: The maximum size of the key material
937
938      CLIENT_KEY: The master client write key, pointing inside the key
939      material
940
941      CLIENT_SALT: The master client write salt, pointing inside the key
942      material
943
944      SERVER_KEY: The master server write key, pointing inside the key
945      material
946
947      SERVER_SALT: The master server write salt, pointing inside the key
948      material
949
950      This is a helper function to generate the keying material for SRTP.
951      It requires the space of the key material to be pre-allocated
952      (should be at least 2x the maximum key size and salt size).  The
953      'client_key' , 'client_salt' , 'server_key' and 'server_salt' are
954      convenience datums that point inside the key material.  They may be
955      'NULL' .
956
957      *Returns:* On success the size of the key material is returned,
958      otherwise, 'GNUTLS_E_SHORT_MEMORY_BUFFER' if the buffer given is
959      not sufficient, or a negative error code.
960
961      Since 3.1.4
962
963 Other helper functions are listed below.
964
965 'INT *note gnutls_srtp_get_selected_profile:: (gnutls_session_t SESSION, gnutls_srtp_profile_t * PROFILE)'
966 'CONST CHAR * *note gnutls_srtp_get_profile_name:: (gnutls_srtp_profile_t PROFILE)'
967 'INT *note gnutls_srtp_get_profile_id:: (const char * NAME, gnutls_srtp_profile_t * PROFILE)'
968
969 \1f
970 File: gnutls.info,  Node: Application Layer Protocol Negotiation (ALPN),  Prev: SRTP,  Up: TLS Extensions
971
972 3.6.8 Application Layer Protocol Negotiation (ALPN)
973 ---------------------------------------------------
974
975 The TLS protocol was extended in 'draft-ietf-tls-applayerprotoneg-00' to
976 provide the application layer a method of negotiating the application
977 protocol version.  This allows for negotiation of the application
978 protocol during the TLS handshake, thus reducing round-trips.  The
979 application protocol is described by an opaque string.  To enable, use
980 the following functions.
981
982 'INT *note gnutls_alpn_set_protocols:: (gnutls_session_t SESSION, const gnutls_datum_t * PROTOCOLS, unsigned PROTOCOLS_SIZE, unsigned int FLAGS)'
983 'INT *note gnutls_alpn_get_selected_protocol:: (gnutls_session_t SESSION, gnutls_datum_t * PROTOCOL)'
984
985 Note that these functions are intended to be used with protocols that
986 are registered in the Application Layer Protocol Negotiation IANA
987 registry.  While you can use them for other protocols (at the risk of
988 collisions), it is preferable to register them.
989
990 \1f
991 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
992
993 3.7 How to use TLS in application protocols
994 ===========================================
995
996 This chapter is intended to provide some hints on how to use TLS over
997 simple custom made application protocols.  The discussion below mainly
998 refers to the TCP/IP transport layer but may be extended to other ones
999 too.
1000
1001 * Menu:
1002
1003 * Separate ports::
1004 * Upward negotiation::
1005
1006 \1f
1007 File: gnutls.info,  Node: Separate ports,  Next: Upward negotiation,  Up: How to use TLS in application protocols
1008
1009 3.7.1 Separate ports
1010 --------------------
1011
1012 Traditionally SSL was used in application protocols by assigning a new
1013 port number for the secure services.  By doing this two separate ports
1014 were assigned, one for the non-secure sessions, and one for the secure
1015 sessions.  This method ensures that if a user requests a secure session
1016 then the client will attempt to connect to the secure port and fail
1017 otherwise.  The only possible attack with this method is to perform a
1018 denial of service attack.  The most famous example of this method is
1019 "HTTP over TLS" or HTTPS protocol [_RFC2818_].
1020
1021 Despite its wide use, this method has several issues.  This approach
1022 starts the TLS Handshake procedure just after the client connects on the
1023 --so called-- secure port.  That way the TLS protocol does not know
1024 anything about the client, and popular methods like the host advertising
1025 in HTTP do not work(1).  There is no way for the client to say "I
1026 connected to YYY server" before the Handshake starts, so the server
1027 cannot possibly know which certificate to use.
1028
1029 Other than that it requires two separate ports to run a single service,
1030 which is unnecessary complication.  Due to the fact that there is a
1031 limitation on the available privileged ports, this approach was soon
1032 deprecated in favor of upward negotiation.
1033
1034    ---------- Footnotes ----------
1035
1036    (1) See also the Server Name Indication extension on *note
1037 serverind::.
1038
1039 \1f
1040 File: gnutls.info,  Node: Upward negotiation,  Prev: Separate ports,  Up: How to use TLS in application protocols
1041
1042 3.7.2 Upward negotiation
1043 ------------------------
1044
1045 Other application protocols(1) use a different approach to enable the
1046 secure layer.  They use something often called as the "TLS upgrade"
1047 method.  This method is quite tricky but it is more flexible.  The idea
1048 is to extend the application protocol to have a "STARTTLS" request,
1049 whose purpose it to start the TLS protocols just after the client
1050 requests it.  This approach does not require any extra port to be
1051 reserved.  There is even an extension to HTTP protocol to support this
1052 method [_RFC2817_].
1053
1054 The tricky part, in this method, is that the "STARTTLS" request is sent
1055 in the clear, thus is vulnerable to modifications.  A typical attack is
1056 to modify the messages in a way that the client is fooled and thinks
1057 that the server does not have the "STARTTLS" capability.  See a typical
1058 conversation of a hypothetical protocol:
1059
1060      (client connects to the server)
1061
1062      CLIENT: HELLO I'M MR. XXX
1063
1064      SERVER: NICE TO MEET YOU XXX
1065
1066      CLIENT: PLEASE START TLS
1067
1068      SERVER: OK
1069
1070      *** TLS STARTS
1071
1072      CLIENT: HERE ARE SOME CONFIDENTIAL DATA
1073
1074 And an example of a conversation where someone is acting in between:
1075
1076      (client connects to the server)
1077
1078      CLIENT: HELLO I'M MR. XXX
1079
1080      SERVER: NICE TO MEET YOU XXX
1081
1082      CLIENT: PLEASE START TLS
1083
1084      (here someone inserts this message)
1085
1086      SERVER: SORRY I DON'T HAVE THIS CAPABILITY
1087
1088      CLIENT: HERE ARE SOME CONFIDENTIAL DATA
1089
1090 As you can see above the client was fooled, and was nai"ve enough to
1091 send the confidential data in the clear, despite the server telling the
1092 client that it does not support "STARTTLS".
1093
1094 How do we avoid the above attack?  As you may have already noticed this
1095 situation is easy to avoid.  The client has to ask the user before it
1096 connects whether the user requests TLS or not.  If the user answered
1097 that he certainly wants the secure layer the last conversation should
1098 be:
1099
1100      (client connects to the server)
1101
1102      CLIENT: HELLO I'M MR. XXX
1103
1104      SERVER: NICE TO MEET YOU XXX
1105
1106      CLIENT: PLEASE START TLS
1107
1108      (here someone inserts this message)
1109
1110      SERVER: SORRY I DON'T HAVE THIS CAPABILITY
1111
1112      CLIENT: BYE
1113
1114      (the client notifies the user that the secure connection was not
1115      possible)
1116
1117 This method, if implemented properly, is far better than the traditional
1118 method, and the security properties remain the same, since only denial
1119 of service is possible.  The benefit is that the server may request
1120 additional data before the TLS Handshake protocol starts, in order to
1121 send the correct certificate, use the correct password file, or anything
1122 else!
1123
1124    ---------- Footnotes ----------
1125
1126    (1) See LDAP, IMAP etc.
1127
1128 \1f
1129 File: gnutls.info,  Node: On SSL 2 and older protocols,  Prev: How to use TLS in application protocols,  Up: Introduction to TLS
1130
1131 3.8 On SSL 2 and older protocols
1132 ================================
1133
1134 One of the initial decisions in the GnuTLS development was to implement
1135 the known security protocols for the transport layer.  Initially TLS 1.0
1136 was implemented since it was the latest at that time, and was considered
1137 to be the most advanced in security properties.  Later the SSL 3.0
1138 protocol was implemented since it is still the only protocol supported
1139 by several servers and there are no serious security vulnerabilities
1140 known.
1141
1142 One question that may arise is why we didn't implement SSL 2.0 in the
1143 library.  There are several reasons, most important being that it has
1144 serious security flaws, unacceptable for a modern security library.
1145 Other than that, this protocol is barely used by anyone these days since
1146 it has been deprecated since 1996.  The security problems in SSL 2.0
1147 include:
1148
1149    * Message integrity compromised.  The SSLv2 message authentication
1150      uses the MD5 function, and is insecure.
1151
1152    * Man-in-the-middle attack.  There is no protection of the handshake
1153      in SSLv2, which permits a man-in-the-middle attack.
1154
1155    * Truncation attack.  SSLv2 relies on TCP FIN to close the session,
1156      so the attacker can forge a TCP FIN, and the peer cannot tell if it
1157      was a legitimate end of data or not.
1158
1159    * Weak message integrity for export ciphers.  The cryptographic keys
1160      in SSLv2 are used for both message authentication and encryption,
1161      so if weak encryption schemes are negotiated (say 40-bit keys) the
1162      message authentication code uses the same weak key, which isn't
1163      necessary.
1164
1165 Other protocols such as Microsoft's PCT 1 and PCT 2 were not implemented
1166 because they were also abandoned and deprecated by SSL 3.0 and later TLS
1167 1.0.
1168
1169 \1f
1170 File: gnutls.info,  Node: Authentication methods,  Next: Hardware security modules and abstract key types,  Prev: Introduction to TLS,  Up: Top
1171
1172 4 Authentication methods
1173 ************************
1174
1175 The initial key exchange of the TLS protocol performs authentication of
1176 the peers.  In typical scenarios the server is authenticated to the
1177 client, and optionally the client to the server.
1178
1179 While many associate TLS with X.509 certificates and public key
1180 authentication, the protocol supports various authentication methods,
1181 including pre-shared keys, and passwords.  In this chapter a description
1182 of the existing authentication methods is provided, as well as some
1183 guidance on which use-cases each method can be used at.
1184
1185 * Menu:
1186
1187 * Certificate authentication::
1188 * More on certificate authentication::
1189 * Shared-key and anonymous authentication::
1190 * Selecting an appropriate authentication method::
1191
1192 \1f
1193 File: gnutls.info,  Node: Certificate authentication,  Next: More on certificate authentication,  Up: Authentication methods
1194
1195 4.1 Certificate authentication
1196 ==============================
1197
1198 The most known authentication method of TLS are certificates.  The PKIX
1199 [_PKIX_] public key infrastructure is daily used by anyone using a
1200 browser today.  GnuTLS supports both X.509 certificates [_PKIX_] and
1201 OpenPGP certificates using a common API.
1202
1203 The key exchange algorithms supported by certificate authentication are
1204 shown in *note Table 4.1: tab:key-exchange.
1205
1206 Key exchange   Description
1207                
1208 ------------------------------------------------------------------
1209 RSA            The RSA algorithm is used to encrypt a key and
1210                send it to the peer.  The certificate must allow
1211                the key to be used for encryption.
1212                
1213 DHE_RSA        The RSA algorithm is used to sign ephemeral
1214                Diffie-Hellman parameters which are sent to the
1215                peer.  The key in the certificate must allow the
1216                key to be used for signing.  Note that key
1217                exchange algorithms which use ephemeral
1218                Diffie-Hellman parameters, offer perfect forward
1219                secrecy.  That means that even if the private
1220                key used for signing is compromised, it cannot
1221                be used to reveal past session data.
1222                
1223 ECDHE_RSA      The RSA algorithm is used to sign ephemeral
1224                elliptic curve Diffie-Hellman parameters which
1225                are sent to the peer.  The key in the
1226                certificate must allow the key to be used for
1227                signing.  It also offers perfect forward
1228                secrecy.  That means that even if the private
1229                key used for signing is compromised, it cannot
1230                be used to reveal past session data.
1231                
1232 DHE_DSS        The DSA algorithm is used to sign ephemeral
1233                Diffie-Hellman parameters which are sent to the
1234                peer.  The certificate must contain DSA
1235                parameters to use this key exchange algorithm.
1236                DSA is the algorithm of the Digital Signature
1237                Standard (DSS).
1238                
1239 ECDHE_ECDSA    The Elliptic curve DSA algorithm is used to sign
1240                ephemeral elliptic curve Diffie-Hellman
1241                parameters which are sent to the peer.  The
1242                certificate must contain ECDSA parameters (i.e.,
1243                EC and marked for signing) to use this key
1244                exchange algorithm.
1245                
1246
1247 Table 4.1: Supported key exchange algorithms.
1248
1249 * Menu:
1250
1251 * X.509 certificates::
1252 * OpenPGP certificates::
1253 * Advanced certificate verification::
1254 * Digital signatures::
1255
1256 \1f
1257 File: gnutls.info,  Node: X.509 certificates,  Next: OpenPGP certificates,  Up: Certificate authentication
1258
1259 4.1.1 X.509 certificates
1260 ------------------------
1261
1262 The X.509 protocols rely on a hierarchical trust model.  In this trust
1263 model Certification Authorities (CAs) are used to certify entities.
1264 Usually more than one certification authorities exist, and certification
1265 authorities may certify other authorities to issue certificates as well,
1266 following a hierarchical model.
1267
1268 \0\b[image src="gnutls-x509.png"\0\b]
1269
1270 Figure 4.1: An example of the X.509 hierarchical trust model.
1271
1272 One needs to trust one or more CAs for his secure communications.  In
1273 that case only the certificates issued by the trusted authorities are
1274 acceptable.  The framework is illustrated on *note Figure 4.1: fig-x509.
1275
1276 * Menu:
1277
1278 * X.509 certificate structure::
1279 * Importing an X.509 certificate::
1280 * X.509 distinguished names::
1281 * X.509 extensions::
1282 * X.509 public and private keys::
1283 * Verifying X.509 certificate paths::
1284 * Verifying a certificate in the context of TLS session::
1285 * Verification using PKCS11::
1286
1287 \1f
1288 File: gnutls.info,  Node: X.509 certificate structure,  Next: Importing an X.509 certificate,  Up: X.509 certificates
1289
1290 4.1.1.1 X.509 certificate structure
1291 ...................................
1292
1293 An X.509 certificate usually contains information about the certificate
1294 holder, the signer, a unique serial number, expiration dates and some
1295 other fields [_PKIX_] as shown in *note Table 4.2: tab:x509.
1296
1297 Field          Description
1298                
1299 ------------------------------------------------------------------
1300 version        The field that indicates the version of the
1301                certificate.
1302                
1303 serialNumber   This field holds a unique serial number per
1304                certificate.
1305                
1306 signature      The issuing authority's signature.
1307                
1308 issuer         Holds the issuer's distinguished name.
1309                
1310 validity       The activation and expiration dates.
1311                
1312 subject        The subject's distinguished name of the
1313                certificate.
1314                
1315 extensions     The extensions are fields only present in
1316                version 3 certificates.
1317                
1318
1319 Table 4.2: X.509 certificate fields.
1320
1321 The certificate's _subject or issuer name_ is not just a single string.
1322 It is a Distinguished name and in the ASN.1 notation is a sequence of
1323 several object identifiers with their corresponding values.  Some of
1324 available OIDs to be used in an X.509 distinguished name are defined in
1325 'gnutls/x509.h'.
1326
1327 The _Version_ field in a certificate has values either 1 or 3 for
1328 version 3 certificates.  Version 1 certificates do not support the
1329 extensions field so it is not possible to distinguish a CA from a
1330 person, thus their usage should be avoided.
1331
1332 The _validity_ dates are there to indicate the date that the specific
1333 certificate was activated and the date the certificate's key would be
1334 considered invalid.
1335
1336 In GnuTLS the X.509 certificate structures are handled using the
1337 'gnutls_x509_crt_t' type and the corresponding private keys with the
1338 'gnutls_x509_privkey_t' type.  All the available functions for X.509
1339 certificate handling have their prototypes in 'gnutls/x509.h'.  An
1340 example program to demonstrate the X.509 parsing capabilities can be
1341 found in *note ex-x509-info::.
1342
1343 \1f
1344 File: gnutls.info,  Node: Importing an X.509 certificate,  Next: X.509 distinguished names,  Prev: X.509 certificate structure,  Up: X.509 certificates
1345
1346 4.1.1.2 Importing an X.509 certificate
1347 ......................................
1348
1349 The certificate structure should be initialized using *note
1350 gnutls_x509_crt_init::, and a certificate structure can be imported
1351 using *note gnutls_x509_crt_import::.
1352
1353 'INT *note gnutls_x509_crt_init:: (gnutls_x509_crt_t * CERT)'
1354 'INT *note gnutls_x509_crt_import:: (gnutls_x509_crt_t CERT, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)'
1355 'VOID *note gnutls_x509_crt_deinit:: (gnutls_x509_crt_t CERT)'
1356
1357 In several functions an array of certificates is required.  To assist in
1358 initialization and import the following two functions are provided.
1359
1360 '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)'
1361 '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)'
1362
1363 In all cases after use a certificate must be deinitialized using *note
1364 gnutls_x509_crt_deinit::.  Note that although the functions above apply
1365 to 'gnutls_x509_crt_t' structure, similar functions exist for the CRL
1366 structure 'gnutls_x509_crl_t'.
1367
1368 \1f
1369 File: gnutls.info,  Node: X.509 distinguished names,  Next: X.509 extensions,  Prev: Importing an X.509 certificate,  Up: X.509 certificates
1370
1371 4.1.1.3 X.509 distinguished names
1372 .................................
1373
1374 The "subject" of an X.509 certificate is not described by a single name,
1375 but rather with a distinguished name.  This in X.509 terminology is a
1376 list of strings each associated an object identifier.  To make things
1377 simple GnuTLS provides *note gnutls_x509_crt_get_dn2:: which follows the
1378 rules in [_RFC4514_] and returns a single string.  Access to each string
1379 by individual object identifiers can be accessed using *note
1380 gnutls_x509_crt_get_dn_by_oid::.
1381
1382  -- Function: int gnutls_x509_crt_get_dn2 (gnutls_x509_crt_t CERT,
1383           gnutls_datum_t * DN)
1384      CERT: should contain a 'gnutls_x509_crt_t' structure
1385
1386      DN: a pointer to a structure to hold the name
1387
1388      This function will allocate buffer and copy the name of the
1389      Certificate.  The name will be in the form "C=xxxx,O=yyyy,CN=zzzz"
1390      as described in RFC4514.  The output string will be ASCII or UTF-8
1391      encoded, depending on the certificate data.
1392
1393      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
1394      otherwise a negative error value.  and a negative error code on
1395      error.
1396
1397      *Since:* 3.1.10
1398 'INT *note gnutls_x509_crt_get_dn:: (gnutls_x509_crt_t CERT, char * BUF, size_t * BUF_SIZE)'
1399 '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)'
1400 'INT *note gnutls_x509_crt_get_dn_oid:: (gnutls_x509_crt_t CERT, int INDX, void * OID, size_t * OID_SIZE)'
1401
1402 Similar functions exist to access the distinguished name of the issuer
1403 of the certificate.
1404
1405 'INT *note gnutls_x509_crt_get_issuer_dn:: (gnutls_x509_crt_t CERT, char * BUF, size_t * BUF_SIZE)'
1406 'INT *note gnutls_x509_crt_get_issuer_dn2:: (gnutls_x509_crt_t CERT, gnutls_datum_t * DN)'
1407 '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)'
1408 'INT *note gnutls_x509_crt_get_issuer_dn_oid:: (gnutls_x509_crt_t CERT, int INDX, void * OID, size_t * OID_SIZE)'
1409 'INT *note gnutls_x509_crt_get_issuer:: (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)'
1410
1411 The more powerful *note gnutls_x509_crt_get_subject:: and *note
1412 gnutls_x509_dn_get_rdn_ava:: provide efficient but low-level access to
1413 the contents of the distinguished name structure.
1414
1415 'INT *note gnutls_x509_crt_get_subject:: (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)'
1416 'INT *note gnutls_x509_crt_get_issuer:: (gnutls_x509_crt_t CERT, gnutls_x509_dn_t * DN)'
1417
1418  -- Function: int gnutls_x509_dn_get_rdn_ava (gnutls_x509_dn_t DN, int
1419           IRDN, int IAVA, gnutls_x509_ava_st * AVA)
1420      DN: a pointer to DN
1421
1422      IRDN: index of RDN
1423
1424      IAVA: index of AVA.
1425
1426      AVA: Pointer to structure which will hold output information.
1427
1428      Get pointers to data within the DN. The format of the 'ava'
1429      structure is shown below.
1430
1431      struct gnutls_x509_ava_st { gnutls_datum_t oid; gnutls_datum_t
1432      value; unsigned long value_tag; };
1433
1434      The X.509 distinguished name is a sequence of sequences of strings
1435      and this is what the 'irdn' and 'iava' indexes model.
1436
1437      Note that 'ava' will contain pointers into the 'dn' structure which
1438      in turns points to the original certificate.  Thus you should not
1439      modify any data or deallocate any of those.
1440
1441      This is a low-level function that requires the caller to do the
1442      value conversions when necessary (e.g.  from UCS-2).
1443
1444      *Returns:* Returns 0 on success, or an error code.
1445
1446 \1f
1447 File: gnutls.info,  Node: X.509 extensions,  Next: X.509 public and private keys,  Prev: X.509 distinguished names,  Up: X.509 certificates
1448
1449 4.1.1.4 X.509 extensions
1450 ........................
1451
1452 X.509 version 3 certificates include a list of extensions that can be
1453 used to obtain additional information on the subject or the issuer of
1454 the certificate.  Those may be e-mail addresses, flags that indicate
1455 whether the belongs to a CA etc.  All the supported X.509 version 3
1456 extensions are shown in *note Table 4.3: tab:x509-ext.
1457
1458 The certificate extensions access is split into two parts.  The first
1459 requires to retrieve the extension, and the second is the parsing part.
1460
1461 To enumerate and retrieve the DER-encoded extension data available in a
1462 certificate the following two functions are available.
1463 'INT *note gnutls_x509_crt_get_extension_info:: (gnutls_x509_crt_t CERT, int INDX, void * OID, size_t * OID_SIZE, unsigned int * CRITICAL)'
1464 'INT *note gnutls_x509_crt_get_extension_data2:: (gnutls_x509_crt_t CERT, unsigned INDX, gnutls_datum_t * DATA)'
1465 'INT *note gnutls_x509_crt_get_extension_by_oid2:: (gnutls_x509_crt_t CERT, const char * OID, int INDX, gnutls_datum_t * OUTPUT, unsigned int * CRITICAL)'
1466
1467 After a supported DER-encoded extension is retrieved it can be parsed
1468 using the APIs in 'x509-ext.h'.  Complex extensions may require
1469 initializing an intermediate structure that holds the parsed extension
1470 data.  Examples of simple parsing functions are shown below.
1471 'INT *note gnutls_x509_ext_import_basic_constraints:: (const gnutls_datum_t * EXT, unsigned int * CA, int * PATHLEN)'
1472 'INT *note gnutls_x509_ext_export_basic_constraints:: (unsigned int CA, int PATHLEN, gnutls_datum_t * EXT)'
1473 'INT *note gnutls_x509_ext_import_key_usage:: (const gnutls_datum_t * EXT, unsigned int * KEY_USAGE)'
1474 'INT *note gnutls_x509_ext_export_key_usage:: (unsigned int USAGE, gnutls_datum_t * EXT)'
1475
1476 More complex extensions, such as Name Constraints, require an
1477 intermediate structure, in that case 'gnutls_x509_name_constraints_t' to
1478 be initialized in order to store the parsed extension data.
1479 'INT *note gnutls_x509_ext_import_name_constraints:: (const gnutls_datum_t * EXT, gnutls_x509_name_constraints_t NC, unsigned int FLAGS)'
1480 'INT *note gnutls_x509_ext_export_name_constraints:: (gnutls_x509_name_constraints_t NC, gnutls_datum_t * EXT)'
1481
1482 After the name constraints are extracted in the structure, the following
1483 functions can be used to access them.
1484
1485 'INT *note gnutls_x509_name_constraints_get_permitted:: (gnutls_x509_name_constraints_t NC, unsigned IDX, unsigned * TYPE, gnutls_datum_t * NAME)'
1486 'INT *note gnutls_x509_name_constraints_get_excluded:: (gnutls_x509_name_constraints_t NC, unsigned IDX, unsigned * TYPE, gnutls_datum_t * NAME)'
1487 'INT *note gnutls_x509_name_constraints_add_permitted:: (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, const gnutls_datum_t * NAME)'
1488 'INT *note gnutls_x509_name_constraints_add_excluded:: (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, const gnutls_datum_t * NAME)'
1489 'UNSIGNED *note gnutls_x509_name_constraints_check:: (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, const gnutls_datum_t * NAME)'
1490 'UNSIGNED *note gnutls_x509_name_constraints_check_crt:: (gnutls_x509_name_constraints_t NC, gnutls_x509_subject_alt_name_t TYPE, gnutls_x509_crt_t CERT)'
1491
1492 Other utility functions are listed below.
1493 'INT *note gnutls_x509_name_constraints_init:: (gnutls_x509_name_constraints_t * NC)'
1494 'VOID *note gnutls_x509_name_constraints_deinit:: (gnutls_x509_name_constraints_t NC)'
1495
1496 Similar functions exist for all of the other supported extensions,
1497 listed in *note Table 4.3: tab:x509-ext.
1498
1499 Extension              OID            Description
1500                                       
1501 --------------------------------------------------------------------
1502 Subject key id         2.5.29.14      An identifier of the key of
1503                                       the subject.
1504                                       
1505 Key usage              2.5.29.15      Constraints the key's usage
1506                                       of the certificate.
1507                                       
1508 Private key usage      2.5.29.16      Constraints the validity
1509 period                                time of the private key.
1510                                       
1511 Subject alternative    2.5.29.17      Alternative names to
1512 name                                  subject's distinguished
1513                                       name.
1514                                       
1515 Issuer alternative     2.5.29.18      Alternative names to the
1516 name                                  issuer's distinguished
1517                                       name.
1518                                       
1519 Basic constraints      2.5.29.19      Indicates whether this is a
1520                                       CA certificate or not, and
1521                                       specify the maximum path
1522                                       lengths of certificate
1523                                       chains.
1524                                       
1525 Name constraints       2.5.29.30      A field in CA certificates
1526                                       that restricts the scope of
1527                                       the name of issued
1528                                       certificates.
1529                                       
1530 CRL distribution       2.5.29.31      This extension is set by
1531 points                                the CA, in order to inform
1532                                       about the issued CRLs.
1533                                       
1534 Certificate policy     2.5.29.32      This extension is set to
1535                                       indicate the certificate
1536                                       policy as object identifier
1537                                       and may contain a
1538                                       descriptive string or URL.
1539                                       
1540 Authority key          2.5.29.35      An identifier of the key of
1541 identifier                            the issuer of the
1542                                       certificate.  That is used
1543                                       to distinguish between
1544                                       different keys of the same
1545                                       issuer.
1546                                       
1547 Extended key usage     2.5.29.37      Constraints the purpose of
1548                                       the certificate.
1549                                       
1550 Authority              1.3.6.1.5.5.7.1.1Information on services by
1551 information access                    the issuer of the
1552                                       certificate.
1553                                       
1554 Proxy Certification    1.3.6.1.5.5.7.1.14Proxy Certificates includes
1555 Information                           this extension that
1556                                       contains the OID of the
1557                                       proxy policy language used,
1558                                       and can specify limits on
1559                                       the maximum lengths of
1560                                       proxy chains.  Proxy
1561                                       Certificates are specified
1562                                       in [_RFC3820_].
1563                                       
1564
1565 Table 4.3: Supported X.509 certificate extensions.
1566
1567 Note, that there are also direct APIs to access extensions that may be
1568 simpler to use for non-complex extensions.  They are available in
1569 'x509.h' and some examples are listed below.
1570 'INT *note gnutls_x509_crt_get_basic_constraints:: (gnutls_x509_crt_t CERT, unsigned int * CRITICAL, unsigned int * CA, int * PATHLEN)'
1571 'INT *note gnutls_x509_crt_set_basic_constraints:: (gnutls_x509_crt_t CRT, unsigned int CA, int PATHLENCONSTRAINT)'
1572 'INT *note gnutls_x509_crt_get_key_usage:: (gnutls_x509_crt_t CERT, unsigned int * KEY_USAGE, unsigned int * CRITICAL)'
1573 'INT *note gnutls_x509_crt_set_key_usage:: (gnutls_x509_crt_t CRT, unsigned int USAGE)'
1574
1575 \1f
1576 File: gnutls.info,  Node: X.509 public and private keys,  Next: Verifying X.509 certificate paths,  Prev: X.509 extensions,  Up: X.509 certificates
1577
1578 4.1.1.5 Accessing public and private keys
1579 .........................................
1580
1581 Each X.509 certificate contains a public key that corresponds to a
1582 private key.  To get a unique identifier of the public key the *note
1583 gnutls_x509_crt_get_key_id:: function is provided.  To export the public
1584 key or its parameters you may need to convert the X.509 structure to a
1585 'gnutls_pubkey_t'.  See *note Abstract public keys:: for more
1586 information.
1587
1588  -- Function: int gnutls_x509_crt_get_key_id (gnutls_x509_crt_t CRT,
1589           unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t *
1590           OUTPUT_DATA_SIZE)
1591      CRT: Holds the certificate
1592
1593      FLAGS: should be 0 for now
1594
1595      OUTPUT_DATA: will contain the key ID
1596
1597      OUTPUT_DATA_SIZE: holds the size of output_data (and will be
1598      replaced by the actual size of parameters)
1599
1600      This function will return a unique ID that depends on the public
1601      key parameters.  This ID can be used in checking whether a
1602      certificate corresponds to the given private key.
1603
1604      If the buffer provided is not long enough to hold the output, then
1605      *output_data_size is updated and GNUTLS_E_SHORT_MEMORY_BUFFER will
1606      be returned.  The output will normally be a SHA-1 hash output,
1607      which is 20 bytes.
1608
1609      *Returns:* In case of failure a negative error code will be
1610      returned, and 0 on success.
1611
1612 The private key parameters may be directly accessed by using one of the
1613 following functions.
1614
1615 'INT *note gnutls_x509_privkey_get_pk_algorithm2:: (gnutls_x509_privkey_t KEY, unsigned int * BITS)'
1616 '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)'
1617 '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)'
1618 '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)'
1619 '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)'
1620
1621 \1f
1622 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
1623
1624 4.1.1.6 Verifying X.509 certificate paths
1625 .........................................
1626
1627 Verifying certificate paths is important in X.509 authentication.  For
1628 this purpose the following functions are provided.
1629
1630  -- Function: int gnutls_x509_trust_list_add_cas
1631           (gnutls_x509_trust_list_t LIST, const gnutls_x509_crt_t *
1632           CLIST, unsigned CLIST_SIZE, unsigned int FLAGS)
1633      LIST: The structure of the list
1634
1635      CLIST: A list of CAs
1636
1637      CLIST_SIZE: The length of the CA list
1638
1639      FLAGS: should be 0 or an or'ed sequence of 'GNUTLS_TL' options.
1640
1641      This function will add the given certificate authorities to the
1642      trusted list.  The list of CAs must not be deinitialized during
1643      this structure's lifetime.
1644
1645      If the flag 'GNUTLS_TL_NO_DUPLICATES' is specified, then the
1646      provided 'clist' entries that are duplicates will not be added to
1647      the list and will be deinitialized.
1648
1649      *Returns:* The number of added elements is returned.
1650
1651      *Since:* 3.0.0
1652
1653  -- Function: int gnutls_x509_trust_list_add_named_crt
1654           (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t CERT, const
1655           void * NAME, size_t NAME_SIZE, unsigned int FLAGS)
1656      LIST: The structure of the list
1657
1658      CERT: A certificate
1659
1660      NAME: An identifier for the certificate
1661
1662      NAME_SIZE: The size of the identifier
1663
1664      FLAGS: should be 0.
1665
1666      This function will add the given certificate to the trusted list
1667      and associate it with a name.  The certificate will not be be used
1668      for verification with 'gnutls_x509_trust_list_verify_crt()' but
1669      only with 'gnutls_x509_trust_list_verify_named_crt()' .
1670
1671      In principle this function can be used to set individual "server"
1672      certificates that are trusted by the user for that specific server
1673      but for no other purposes.
1674
1675      The certificate must not be deinitialized during the lifetime of
1676      the trusted list.
1677
1678      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
1679      otherwise a negative error value.
1680
1681      *Since:* 3.0.0
1682
1683  -- Function: int gnutls_x509_trust_list_add_crls
1684           (gnutls_x509_trust_list_t LIST, const gnutls_x509_crl_t *
1685           CRL_LIST, int CRL_SIZE, unsigned int FLAGS, unsigned int
1686           VERIFICATION_FLAGS)
1687      LIST: The structure of the list
1688
1689      CRL_LIST: A list of CRLs
1690
1691      CRL_SIZE: The length of the CRL list
1692
1693      FLAGS: if GNUTLS_TL_VERIFY_CRL is given the CRLs will be verified
1694      before being added.
1695
1696      VERIFICATION_FLAGS: gnutls_certificate_verify_flags if flags
1697      specifies GNUTLS_TL_VERIFY_CRL
1698
1699      This function will add the given certificate revocation lists to
1700      the trusted list.  The list of CRLs must not be deinitialized
1701      during this structure's lifetime.
1702
1703      This function must be called after
1704      'gnutls_x509_trust_list_add_cas()' to allow verifying the CRLs for
1705      validity.  If the flag 'GNUTLS_TL_NO_DUPLICATES' is given, then any
1706      provided CRLs that are a duplicate, will be deinitialized and not
1707      added to the list (that assumes that
1708      'gnutls_x509_trust_list_deinit()' will be called with all=1).
1709
1710      *Returns:* The number of added elements is returned.
1711
1712      *Since:* 3.0
1713
1714  -- Function: int gnutls_x509_trust_list_verify_crt
1715           (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t * CERT_LIST,
1716           unsigned int CERT_LIST_SIZE, unsigned int FLAGS, unsigned int
1717           * VOUTPUT, gnutls_verify_output_function FUNC)
1718      LIST: The structure of the list
1719
1720      CERT_LIST: is the certificate list to be verified
1721
1722      CERT_LIST_SIZE: is the certificate list size
1723
1724      FLAGS: Flags that may be used to change the verification algorithm.
1725      Use OR of the gnutls_certificate_verify_flags enumerations.
1726
1727      VOUTPUT: will hold the certificate verification output.
1728
1729      FUNC: If non-null will be called on each chain element verification
1730      with the output.
1731
1732      This function will try to verify the given certificate and return
1733      its status.  The 'verify' parameter will hold an OR'ed sequence of
1734      'gnutls_certificate_status_t' flags.
1735
1736      Additionally a certificate verification profile can be specified
1737      from the ones in 'gnutls_certificate_verification_profiles_t' by
1738      ORing the result of 'GNUTLS_PROFILE_TO_VFLAGS()' to the
1739      verification flags.
1740
1741      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
1742      otherwise a negative error value.
1743
1744      *Since:* 3.0
1745
1746  -- Function: int gnutls_x509_trust_list_verify_crt2
1747           (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t * CERT_LIST,
1748           unsigned int CERT_LIST_SIZE, gnutls_typed_vdata_st * DATA,
1749           unsigned int ELEMENTS, unsigned int FLAGS, unsigned int *
1750           VOUTPUT, gnutls_verify_output_function FUNC)
1751      LIST: The structure of the list
1752
1753      CERT_LIST: is the certificate list to be verified
1754
1755      CERT_LIST_SIZE: is the certificate list size
1756
1757      DATA: an array of typed data
1758
1759      ELEMENTS: the number of data elements
1760
1761      FLAGS: Flags that may be used to change the verification algorithm.
1762      Use OR of the gnutls_certificate_verify_flags enumerations.
1763
1764      VOUTPUT: will hold the certificate verification output.
1765
1766      FUNC: If non-null will be called on each chain element verification
1767      with the output.
1768
1769      This function will try to verify the given certificate and return
1770      its status.  The 'verify' parameter will hold an OR'ed sequence of
1771      'gnutls_certificate_status_t' flags.
1772
1773      Additionally a certificate verification profile can be specified
1774      from the ones in 'gnutls_certificate_verification_profiles_t' by
1775      ORing the result of 'GNUTLS_PROFILE_TO_VFLAGS()' to the
1776      verification flags.
1777
1778      The acceptable 'data' types are 'GNUTLS_DT_DNS_HOSTNAME' and
1779      'GNUTLS_DT_KEY_PURPOSE_OID' .  The former accepts as data a
1780      null-terminated hostname, and the latter a null-terminated object
1781      identifier (e.g., 'GNUTLS_KP_TLS_WWW_SERVER' ).  If a DNS hostname
1782      is provided then this function will compare the hostname in the
1783      certificate against the given.  If names do not match the
1784      'GNUTLS_CERT_UNEXPECTED_OWNER' status flag will be set.  If a key
1785      purpose OID is provided and the end-certificate contains the
1786      extended key usage PKIX extension, it will be required to be have
1787      the provided key purpose or be marked for any purpose, otherwise
1788      verification will fail with
1789      'GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE' status.
1790
1791      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
1792      otherwise a negative error value.  Note that verification failure
1793      will not result to an error code, only 'voutput' will be updated.
1794
1795      *Since:* 3.3.8
1796
1797  -- Function: int gnutls_x509_trust_list_verify_named_crt
1798           (gnutls_x509_trust_list_t LIST, gnutls_x509_crt_t CERT, const
1799           void * NAME, size_t NAME_SIZE, unsigned int FLAGS, unsigned
1800           int * VOUTPUT, gnutls_verify_output_function FUNC)
1801      LIST: The structure of the list
1802
1803      CERT: is the certificate to be verified
1804
1805      NAME: is the certificate's name
1806
1807      NAME_SIZE: is the certificate's name size
1808
1809      FLAGS: Flags that may be used to change the verification algorithm.
1810      Use OR of the gnutls_certificate_verify_flags enumerations.
1811
1812      VOUTPUT: will hold the certificate verification output.
1813
1814      FUNC: If non-null will be called on each chain element verification
1815      with the output.
1816
1817      This function will try to find a certificate that is associated
1818      with the provided name -see
1819      'gnutls_x509_trust_list_add_named_crt()' .  If a match is found the
1820      certificate is considered valid.  In addition to that this function
1821      will also check CRLs.  The 'voutput' parameter will hold an OR'ed
1822      sequence of 'gnutls_certificate_status_t' flags.
1823
1824      Additionally a certificate verification profile can be specified
1825      from the ones in 'gnutls_certificate_verification_profiles_t' by
1826      ORing the result of 'GNUTLS_PROFILE_TO_VFLAGS()' to the
1827      verification flags.
1828
1829      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
1830      otherwise a negative error value.
1831
1832      *Since:* 3.0.0
1833
1834  -- Function: int gnutls_x509_trust_list_add_trust_file
1835           (gnutls_x509_trust_list_t LIST, const char * CA_FILE, const
1836           char * CRL_FILE, gnutls_x509_crt_fmt_t TYPE, unsigned int
1837           TL_FLAGS, unsigned int TL_VFLAGS)
1838      LIST: The structure of the list
1839
1840      CA_FILE: A file containing a list of CAs (optional)
1841
1842      CRL_FILE: A file containing a list of CRLs (optional)
1843
1844      TYPE: The format of the certificates
1845
1846      TL_FLAGS: GNUTLS_TL_*
1847
1848      TL_VFLAGS: gnutls_certificate_verify_flags if flags specifies
1849      GNUTLS_TL_VERIFY_CRL
1850
1851      This function will add the given certificate authorities to the
1852      trusted list.  PKCS '11' URLs are also accepted, instead of files,
1853      by this function.  A PKCS '11' URL implies a trust database (a
1854      specially marked module in p11-kit); the URL "pkcs11:" implies all
1855      trust databases in the system.  Only a single URL specifying trust
1856      databases can be set; they cannot be stacked with multiple calls.
1857
1858      *Returns:* The number of added elements is returned.
1859
1860      *Since:* 3.1
1861
1862  -- Function: int gnutls_x509_trust_list_add_trust_mem
1863           (gnutls_x509_trust_list_t LIST, const gnutls_datum_t * CAS,
1864           const gnutls_datum_t * CRLS, gnutls_x509_crt_fmt_t TYPE,
1865           unsigned int TL_FLAGS, unsigned int TL_VFLAGS)
1866      LIST: The structure of the list
1867
1868      CAS: A buffer containing a list of CAs (optional)
1869
1870      CRLS: A buffer containing a list of CRLs (optional)
1871
1872      TYPE: The format of the certificates
1873
1874      TL_FLAGS: GNUTLS_TL_*
1875
1876      TL_VFLAGS: gnutls_certificate_verify_flags if flags specifies
1877      GNUTLS_TL_VERIFY_CRL
1878
1879      This function will add the given certificate authorities to the
1880      trusted list.
1881
1882      *Returns:* The number of added elements is returned.
1883
1884      *Since:* 3.1
1885
1886  -- Function: int gnutls_x509_trust_list_add_system_trust
1887           (gnutls_x509_trust_list_t LIST, unsigned int TL_FLAGS,
1888           unsigned int TL_VFLAGS)
1889      LIST: The structure of the list
1890
1891      TL_FLAGS: GNUTLS_TL_*
1892
1893      TL_VFLAGS: gnutls_certificate_verify_flags if flags specifies
1894      GNUTLS_TL_VERIFY_CRL
1895
1896      This function adds the system's default trusted certificate
1897      authorities to the trusted list.  Note that on unsupported systems
1898      this function returns 'GNUTLS_E_UNIMPLEMENTED_FEATURE' .
1899
1900      This function implies the flag 'GNUTLS_TL_NO_DUPLICATES' .
1901
1902      *Returns:* The number of added elements or a negative error code on
1903      error.
1904
1905      *Since:* 3.1
1906
1907 The verification function will verify a given certificate chain against
1908 a list of certificate authorities and certificate revocation lists, and
1909 output a bit-wise OR of elements of the 'gnutls_certificate_status_t'
1910 enumeration shown in *note Figure 4.2: gnutls_certificate_status_t.  The
1911 'GNUTLS_CERT_INVALID' flag is always set on a verification error and
1912 more detailed flags will also be set when appropriate.
1913
1914 'GNUTLS_CERT_INVALID'
1915      The certificate is not signed by one of the known authorities or
1916      the signature is invalid (deprecated by the flags
1917      'GNUTLS_CERT_SIGNATURE_FAILURE' and 'GNUTLS_CERT_SIGNER_NOT_FOUND'
1918      ).
1919 'GNUTLS_CERT_REVOKED'
1920      Certificate is revoked by its authority.  In X.509 this will be set
1921      only if CRLs are checked.
1922 'GNUTLS_CERT_SIGNER_NOT_FOUND'
1923      The certificate's issuer is not known.  This is the case if the
1924      issuer is not included in the trusted certificate list.
1925 'GNUTLS_CERT_SIGNER_NOT_CA'
1926      The certificate's signer was not a CA. This may happen if this was
1927      a version 1 certificate, which is common with some CAs, or a
1928      version 3 certificate without the basic constrains extension.
1929 'GNUTLS_CERT_INSECURE_ALGORITHM'
1930      The certificate was signed using an insecure algorithm such as MD2
1931      or MD5.  These algorithms have been broken and should not be
1932      trusted.
1933 'GNUTLS_CERT_NOT_ACTIVATED'
1934      The certificate is not yet activated.
1935 'GNUTLS_CERT_EXPIRED'
1936      The certificate has expired.
1937 'GNUTLS_CERT_SIGNATURE_FAILURE'
1938      The signature verification failed.
1939 'GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED'
1940      The revocation data are old and have been superseded.
1941 'GNUTLS_CERT_UNEXPECTED_OWNER'
1942      The owner is not the expected one.
1943 'GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE'
1944      The revocation data have a future issue date.
1945 'GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE'
1946      The certificate's signer constraints were violated.
1947 'GNUTLS_CERT_MISMATCH'
1948      The certificate presented isn't the expected one (TOFU)
1949
1950 Figure 4.2: The 'gnutls_certificate_status_t' enumeration.
1951
1952 An example of certificate verification is shown in *note ex-verify2::.
1953 It is also possible to have a set of certificates that are trusted for a
1954 particular server but not to authorize other certificates.  This purpose
1955 is served by the functions *note gnutls_x509_trust_list_add_named_crt::
1956 and *note gnutls_x509_trust_list_verify_named_crt::.
1957
1958 \1f
1959 File: gnutls.info,  Node: Verifying a certificate in the context of TLS session,  Next: Verification using PKCS11,  Prev: Verifying X.509 certificate paths,  Up: X.509 certificates
1960
1961 4.1.1.7 Verifying a certificate in the context of TLS session
1962 .............................................................
1963
1964 When operating in the context of a TLS session, the trusted certificate
1965 authority list may also be set using:
1966 'INT *note gnutls_certificate_set_x509_trust_file:: (gnutls_certificate_credentials_t CRED, const char * CAFILE, gnutls_x509_crt_fmt_t TYPE)'
1967 'INT *note gnutls_certificate_set_x509_trust_dir:: (gnutls_certificate_credentials_t CRED, const char * CA_DIR, gnutls_x509_crt_fmt_t TYPE)'
1968 'INT *note gnutls_certificate_set_x509_crl_file:: (gnutls_certificate_credentials_t RES, const char * CRLFILE, gnutls_x509_crt_fmt_t TYPE)'
1969 'INT *note gnutls_certificate_set_x509_system_trust:: (gnutls_certificate_credentials_t CRED)'
1970
1971 These functions allow the specification of the trusted certificate
1972 authorities, either via a file, a directory or use the system-specified
1973 certificate authories.  Unless the authorities are application specific,
1974 it is generally recommended to use the system trust storage (see *note
1975 gnutls_certificate_set_x509_system_trust::).
1976
1977 Unlike the previous section it is not required to setup a trusted list,
1978 and the function *note gnutls_certificate_verify_peers3:: is used to
1979 verify the peer's certificate chain and identity.  The reported
1980 verification status is identical to the verification functions described
1981 in the previous section.  Note that in certain cases it is required to
1982 check the marked purpose of the end certificate (e.g.
1983 'GNUTLS_KP_TLS_WWW_SERVER'); in these cases the more advanced *note
1984 gnutls_certificate_verify_peers:: should be used instead.
1985
1986 There is also the possibility to pass some input to the verification
1987 functions in the form of flags.  For *note
1988 gnutls_x509_trust_list_verify_crt2:: the flags are passed directly, but
1989 for *note gnutls_certificate_verify_peers3::, the flags are set using
1990 *note gnutls_certificate_set_verify_flags::.  All the available flags
1991 are part of the enumeration 'gnutls_certificate_verify_flags' shown in
1992 *note Figure 4.3: gnutls_certificate_verify_flags.
1993
1994 'GNUTLS_VERIFY_DISABLE_CA_SIGN'
1995      If set a signer does not have to be a certificate authority.  This
1996      flag should normally be disabled, unless you know what this means.
1997 'GNUTLS_VERIFY_DO_NOT_ALLOW_SAME'
1998      If a certificate is not signed by anyone trusted but exists in the
1999      trusted CA list do not treat it as trusted.
2000 'GNUTLS_VERIFY_ALLOW_ANY_X509_V1_CA_CRT'
2001      Allow CA certificates that have version 1 (both root and
2002      intermediate).  This might be dangerous since those haven't the
2003      basicConstraints extension.
2004 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2'
2005      Allow certificates to be signed using the broken MD2 algorithm.
2006 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5'
2007      Allow certificates to be signed using the broken MD5 algorithm.
2008 'GNUTLS_VERIFY_DISABLE_TIME_CHECKS'
2009      Disable checking of activation and expiration validity periods of
2010      certificate chains.  Don't set this unless you understand the
2011      security implications.
2012 'GNUTLS_VERIFY_DISABLE_TRUSTED_TIME_CHECKS'
2013      If set a signer in the trusted list is never checked for expiration
2014      or activation.
2015 'GNUTLS_VERIFY_DO_NOT_ALLOW_X509_V1_CA_CRT'
2016      Do not allow trusted CA certificates that have version 1.  This
2017      option is to be used to deprecate all certificates of version 1.
2018 'GNUTLS_VERIFY_DISABLE_CRL_CHECKS'
2019      Disable checking for validity using certificate revocation lists or
2020      the available OCSP data.
2021 'GNUTLS_VERIFY_ALLOW_UNSORTED_CHAIN'
2022      A certificate chain is tolerated if unsorted (the case with many
2023      TLS servers out there).  This is the default since GnuTLS 3.1.4.
2024 'GNUTLS_VERIFY_DO_NOT_ALLOW_UNSORTED_CHAIN'
2025      Do not tolerate an unsorted certificate chain.
2026 'GNUTLS_VERIFY_DO_NOT_ALLOW_WILDCARDS'
2027      When including a hostname check in the verification, do not
2028      consider any wildcards.
2029
2030 Figure 4.3: The 'gnutls_certificate_verify_flags' enumeration.
2031
2032 \1f
2033 File: gnutls.info,  Node: Verification using PKCS11,  Prev: Verifying a certificate in the context of TLS session,  Up: X.509 certificates
2034
2035 4.1.1.8 Verifying a certificate using PKCS #11
2036 ..............................................
2037
2038 Some systems provide a system wide trusted certificate storage
2039 accessible using the PKCS #11 API. That is, the trusted certificates are
2040 queried and accessed using the PKCS #11 API, and trusted certificate
2041 properties, such as purpose, are marked using attached extensions.  One
2042 example is the p11-kit trust module(1).
2043
2044 These special PKCS #11 modules can be used for GnuTLS certificate
2045 verification if marked as trust policy modules, i.e., with
2046 'trust-policy: yes' in the p11-kit module file.  The way to use them is
2047 by specifying to the file verification function (e.g., *note
2048 gnutls_certificate_set_x509_trust_file::), a pkcs11 URL, or simply
2049 'pkcs11:' to use all the marked with trust policy modules.
2050
2051 The trust modules of p11-kit assign a purpose to trusted authorities
2052 using the extended key usage object identifiers.  The common purposes
2053 are shown in *note Table 4.4: tab:purposes.  Note that typically
2054 according to [_RFC5280_] the extended key usage object identifiers apply
2055 to end certificates.  Their application to CA certificates is an
2056 extension used by the trust modules.
2057
2058 Purpose        OID            Description
2059                               
2060 --------------------------------------------------------------------------
2061 GNUTLS_KP_TLS_WWW_SERVER1.3.6.1.5.5.7.3.1The certificate is to be used for TLS WWW
2062                               authentication.  When in a CA
2063                               certificate, it indicates that the CA is
2064                               allowed to sign certificates for TLS WWW
2065                               authentication.
2066                               
2067 GNUTLS_KP_TLS_WWW_CLIENT1.3.6.1.5.5.7.3.2The certificate is to be used for TLS WWW
2068                               client authentication.  When in a CA
2069                               certificate, it indicates that the CA is
2070                               allowed to sign certificates for TLS WWW
2071                               client authentication.
2072                               
2073 GNUTLS_KP_CODE_SIGNING1.3.6.1.5.5.7.3.3The certificate is to be used for code
2074                               signing.  When in a CA certificate, it
2075                               indicates that the CA is allowed to sign
2076                               certificates for code signing.
2077                               
2078 GNUTLS_KP_EMAIL_PROTECTION1.3.6.1.5.5.7.3.4The certificate is to be used for email
2079                               protection.  When in a CA certificate, it
2080                               indicates that the CA is allowed to sign
2081                               certificates for email users.
2082                               
2083 GNUTLS_KP_OCSP_SIGNING1.3.6.1.5.5.7.3.9The certificate is to be used for signing
2084                               OCSP responses.  When in a CA
2085                               certificate, it indicates that the CA is
2086                               allowed to sign certificates which sign
2087                               OCSP reponses.
2088                               
2089 GNUTLS_KP_ANY  2.5.29.37.0    The certificate is to be used for any
2090                               purpose.  When in a CA certificate, it
2091                               indicates that the CA is allowed to sign
2092                               any kind of certificates.
2093                               
2094
2095 Table 4.4: Key purpose object identifiers.
2096
2097 With such modules, it is recommended to use the verification functions
2098 *note gnutls_x509_trust_list_verify_crt2::, or *note
2099 gnutls_certificate_verify_peers::, which allow to explicitly specify the
2100 key purpose.  The other verification functions which do not allow
2101 setting a purpose, would operate as if 'GNUTLS_KP_TLS_WWW_SERVER' was
2102 requested from the trusted authorities.
2103
2104    ---------- Footnotes ----------
2105
2106    (1) see <http://p11-glue.freedesktop.org/trust-module.html>.
2107
2108 \1f
2109 File: gnutls.info,  Node: OpenPGP certificates,  Next: Advanced certificate verification,  Prev: X.509 certificates,  Up: Certificate authentication
2110
2111 4.1.2 OpenPGP certificates
2112 --------------------------
2113
2114 The OpenPGP key authentication relies on a distributed trust model,
2115 called the "web of trust".  The "web of trust" uses a decentralized
2116 system of trusted introducers, which are the same as a CA. OpenPGP
2117 allows anyone to sign anyone else's public key.  When Alice signs Bob's
2118 key, she is introducing Bob's key to anyone who trusts Alice.  If
2119 someone trusts Alice to introduce keys, then Alice is a trusted
2120 introducer in the mind of that observer.  For example in *note Figure
2121 4.4: fig-openpgp, David trusts Alice to be an introducer and Alice
2122 signed Bob's key thus Dave trusts Bob's key to be the real one.
2123
2124 \0\b[image src="gnutls-pgp.png"\0\b]
2125
2126 Figure 4.4: An example of the OpenPGP trust model.
2127
2128 There are some key points that are important in that model.  In the
2129 example Alice has to sign Bob's key, only if she is sure that the key
2130 belongs to Bob.  Otherwise she may also make Dave falsely believe that
2131 this is Bob's key.  Dave has also the responsibility to know who to
2132 trust.  This model is similar to real life relations.
2133
2134 Just see how Charlie behaves in the previous example.  Although he has
2135 signed Bob's key - because he knows, somehow, that it belongs to Bob -
2136 he does not trust Bob to be an introducer.  Charlie decided to trust
2137 only Kevin, for some reason.  A reason could be that Bob is lazy enough,
2138 and signs other people's keys without being sure that they belong to the
2139 actual owner.
2140
2141 Field          Description
2142                
2143 ------------------------------------------------------------------
2144 version        The field that indicates the version of the
2145                OpenPGP structure.
2146                
2147 user ID        An RFC 2822 string that identifies the owner of
2148                the key.  There may be multiple user identifiers
2149                in a key.
2150                
2151 public key     The main public key of the certificate.
2152                
2153 expiration     The expiration time of the main public key.
2154                
2155 public         An additional public key of the certificate.
2156 subkey         There may be multiple subkeys in a certificate.
2157                
2158 public         The expiration time of the subkey.
2159 subkey         
2160 expiration
2161
2162 Table 4.5: OpenPGP certificate fields.
2163
2164 4.1.2.1 OpenPGP certificate structure
2165 .....................................
2166
2167 In GnuTLS the OpenPGP certificate structures [_RFC2440_] are handled
2168 using the 'gnutls_openpgp_crt_t' type.  A typical certificate contains
2169 the user ID, which is an RFC 2822 mail and name address, a public key,
2170 possibly a number of additional public keys (called subkeys), and a
2171 number of signatures.  The various fields are shown in *note Table 4.5:
2172 tab:openpgp-certificate.
2173
2174 The additional subkeys may provide key for various different purposes,
2175 e.g.  one key to encrypt mail, and another to sign a TLS key exchange.
2176 Each subkey is identified by a unique key ID. The keys that are to be
2177 used in a TLS key exchange that requires signatures are called
2178 authentication keys in the OpenPGP jargon.  The mapping of TLS key
2179 exchange methods to public keys is shown in *note Table 4.6:
2180 tab:openpgp-key-exchange.
2181
2182 Key exchange   Public key requirements
2183                
2184 ------------------------------------------------------------------
2185 RSA            An RSA public key that allows encryption.
2186                
2187 DHE_RSA        An RSA public key that is marked for
2188                authentication.
2189                
2190 ECDHE_RSA      An RSA public key that is marked for
2191                authentication.
2192                
2193 DHE_DSS        A DSA public key that is marked for
2194                authentication.
2195                
2196
2197 Table 4.6: The types of (sub)keys required for the various TLS key
2198 exchange methods.
2199
2200 The corresponding private keys are stored in the
2201 'gnutls_openpgp_privkey_t' type.  All the prototypes for the key
2202 handling functions can be found in 'gnutls/openpgp.h'.
2203
2204 4.1.2.2 Verifying an OpenPGP certificate
2205 ........................................
2206
2207 The verification functions of OpenPGP keys, included in GnuTLS, are
2208 simple ones, and do not use the features of the "web of trust".  For
2209 that reason, if the verification needs are complex, the assistance of
2210 external tools like GnuPG and GPGME(1) is recommended.
2211
2212 In GnuTLS there is a verification function for OpenPGP certificates, the
2213 *note gnutls_openpgp_crt_verify_ring::.  This checks an OpenPGP key
2214 against a given set of public keys (keyring) and returns the key status.
2215 The key verification status is the same as in X.509 certificates,
2216 although the meaning and interpretation are different.  For example an
2217 OpenPGP key may be valid, if the self signature is ok, even if no
2218 signers were found.  The meaning of verification status flags is the
2219 same as in the X.509 certificates (see *note Figure 4.3:
2220 gnutls_certificate_verify_flags.).
2221
2222  -- Function: int gnutls_openpgp_crt_verify_ring (gnutls_openpgp_crt_t
2223           KEY, gnutls_openpgp_keyring_t KEYRING, unsigned int FLAGS,
2224           unsigned int * VERIFY)
2225      KEY: the structure that holds the key.
2226
2227      KEYRING: holds the keyring to check against
2228
2229      FLAGS: unused (should be 0)
2230
2231      VERIFY: will hold the certificate verification output.
2232
2233      Verify all signatures in the key, using the given set of keys
2234      (keyring).
2235
2236      The key verification output will be put in 'verify' and will be one
2237      or more of the 'gnutls_certificate_status_t' enumerated elements
2238      bitwise or'd.
2239
2240      Note that this function does not verify using any "web of trust".
2241      You may use GnuPG for that purpose, or any other external PGP
2242      application.
2243
2244      *Returns:* 'GNUTLS_E_SUCCESS' on success, or an error code.
2245
2246  -- Function: int gnutls_openpgp_crt_verify_self (gnutls_openpgp_crt_t
2247           KEY, unsigned int FLAGS, unsigned int * VERIFY)
2248      KEY: the structure that holds the key.
2249
2250      FLAGS: unused (should be 0)
2251
2252      VERIFY: will hold the key verification output.
2253
2254      Verifies the self signature in the key.  The key verification
2255      output will be put in 'verify' and will be one or more of the
2256      gnutls_certificate_status_t enumerated elements bitwise or'd.
2257
2258      *Returns:* 'GNUTLS_E_SUCCESS' on success, or an error code.
2259
2260 4.1.2.3 Verifying a certificate in the context of a TLS session
2261 ...............................................................
2262
2263 Similarly with X.509 certificates, one needs to specify the OpenPGP
2264 keyring file in the credentials structure.  The certificates in this
2265 file will be used by *note gnutls_certificate_verify_peers3:: to verify
2266 the signatures in the certificate sent by the peer.
2267
2268  -- Function: int gnutls_certificate_set_openpgp_keyring_file
2269           (gnutls_certificate_credentials_t C, const char * FILE,
2270           gnutls_openpgp_crt_fmt_t FORMAT)
2271      C: A certificate credentials structure
2272
2273      FILE: filename of the keyring.
2274
2275      FORMAT: format of keyring.
2276
2277      The function is used to set keyrings that will be used internally
2278      by various OpenPGP functions.  For example to find a key when it is
2279      needed for an operations.  The keyring will also be used at the
2280      verification functions.
2281
2282      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
2283      otherwise a negative error value.
2284
2285    ---------- Footnotes ----------
2286
2287    (1) <http://www.gnupg.org/related_software/gpgme/>
2288
2289 \1f
2290 File: gnutls.info,  Node: Advanced certificate verification,  Next: Digital signatures,  Prev: OpenPGP certificates,  Up: Certificate authentication
2291
2292 4.1.3 Advanced certificate verification
2293 ---------------------------------------
2294
2295 The verification of X.509 certificates in the HTTPS and other Internet
2296 protocols is typically done by loading a trusted list of commercial
2297 Certificate Authorities (see *note
2298 gnutls_certificate_set_x509_system_trust::), and using them as trusted
2299 anchors.  However, there are several examples (eg.  the Diginotar
2300 incident) where one of these authorities was compromised.  This risk can
2301 be mitigated by using in addition to CA certificate verification, other
2302 verification methods.  In this section we list the available in GnuTLS
2303 methods.
2304
2305 * Menu:
2306
2307 * Verifying a certificate using trust on first use authentication::
2308 * Verifying a certificate using DANE::
2309
2310 \1f
2311 File: gnutls.info,  Node: Verifying a certificate using trust on first use authentication,  Next: Verifying a certificate using DANE,  Up: Advanced certificate verification
2312
2313 4.1.3.1 Verifying a certificate using trust on first use authentication
2314 .......................................................................
2315
2316 It is possible to use a trust on first use (TOFU) authentication method
2317 in GnuTLS. That is the concept used by the SSH programs, where the
2318 public key of the peer is not verified, or verified in an out-of-bound
2319 way, but subsequent connections to the same peer require the public key
2320 to remain the same.  Such a system in combination with the typical CA
2321 verification of a certificate, and OCSP revocation checks, can help to
2322 provide multiple factor verification, where a single point of failure is
2323 not enough to compromise the system.  For example a server compromise
2324 may be detected using OCSP, and a CA compromise can be detected using
2325 the trust on first use method.  Such a hybrid system with X.509 and
2326 trust on first use authentication is shown in *note Simple client
2327 example with SSH-style certificate verification::.
2328
2329 See *note Certificate verification:: on how to use the available
2330 functionality.
2331
2332 \1f
2333 File: gnutls.info,  Node: Verifying a certificate using DANE,  Prev: Verifying a certificate using trust on first use authentication,  Up: Advanced certificate verification
2334
2335 4.1.3.2 Verifying a certificate using DANE (DNSSEC)
2336 ...................................................
2337
2338 The DANE protocol is a protocol that can be used to verify TLS
2339 certificates using the DNS (or better DNSSEC) protocols.  The DNS
2340 security extensions (DNSSEC) provide an alternative public key
2341 infrastructure to the commercial CAs that are typically used to sign TLS
2342 certificates.  The DANE protocol takes advantage of the DNSSEC
2343 infrastructure to verify TLS certificates.  This can be in addition to
2344 the verification by CA infrastructure or may even replace it where
2345 DNSSEC is fully deployed.  Note however, that DNSSEC deployment is
2346 fairly new and it would be better to use it as an additional
2347 verification method rather than the only one.
2348
2349 The DANE functionality is provided by the 'libgnutls-dane' library that
2350 is shipped with GnuTLS and the function prototypes are in
2351 'gnutls/dane.h'.  See *note Certificate verification:: for information
2352 on how to use the library.
2353
2354 Note however, that the DANE RFC mandates the verification methods one
2355 should use in addition to the validation via DNSSEC TLSA entries.
2356 GnuTLS doesn't follow that RFC requirement, and the term DANE
2357 verification in this manual refers to the TLSA entry verification.  In
2358 GnuTLS any other verification methods can be used (e.g., PKIX or TOFU)
2359 on top of DANE.
2360
2361 \1f
2362 File: gnutls.info,  Node: Digital signatures,  Prev: Advanced certificate verification,  Up: Certificate authentication
2363
2364 4.1.4 Digital signatures
2365 ------------------------
2366
2367 In this section we will provide some information about digital
2368 signatures, how they work, and give the rationale for disabling some of
2369 the algorithms used.
2370
2371 Digital signatures work by using somebody's secret key to sign some
2372 arbitrary data.  Then anybody else could use the public key of that
2373 person to verify the signature.  Since the data may be arbitrary it is
2374 not suitable input to a cryptographic digital signature algorithm.  For
2375 this reason and also for performance cryptographic hash algorithms are
2376 used to preprocess the input to the signature algorithm.  This works as
2377 long as it is difficult enough to generate two different messages with
2378 the same hash algorithm output.  In that case the same signature could
2379 be used as a proof for both messages.  Nobody wants to sign an innocent
2380 message of donating 1 euro to Greenpeace and find out that they donated
2381 1.000.000 euros to Bad Inc.
2382
2383 For a hash algorithm to be called cryptographic the following three
2384 requirements must hold:
2385
2386   1. Preimage resistance.  That means the algorithm must be one way and
2387      given the output of the hash function H(x), it is impossible to
2388      calculate x.
2389
2390   2. 2nd preimage resistance.  That means that given a pair x,y with
2391      y=H(x) it is impossible to calculate an x' such that y=H(x').
2392
2393   3. Collision resistance.  That means that it is impossible to
2394      calculate random x and x' such H(x')=H(x).
2395
2396 The last two requirements in the list are the most important in digital
2397 signatures.  These protect against somebody who would like to generate
2398 two messages with the same hash output.  When an algorithm is considered
2399 broken usually it means that the Collision resistance of the algorithm
2400 is less than brute force.  Using the birthday paradox the brute force
2401 attack takes 2^{((hash size) / 2)} operations.  Today colliding
2402 certificates using the MD5 hash algorithm have been generated as shown
2403 in [_WEGER_].
2404
2405 There has been cryptographic results for the SHA-1 hash algorithms as
2406 well, although they are not yet critical.  Before 2004, MD5 had a
2407 presumed collision strength of 2^{64}, but it has been showed to have a
2408 collision strength well under 2^{50}.  As of November 2005, it is
2409 believed that SHA-1's collision strength is around 2^{63}.  We consider
2410 this sufficiently hard so that we still support SHA-1.  We anticipate
2411 that SHA-256/386/512 will be used in publicly-distributed certificates
2412 in the future.  When 2^{63} can be considered too weak compared to the
2413 computer power available sometime in the future, SHA-1 will be disabled
2414 as well.  The collision attacks on SHA-1 may also get better, given the
2415 new interest in tools for creating them.
2416
2417 4.1.4.1 Trading security for interoperability
2418 .............................................
2419
2420 If you connect to a server and use GnuTLS' functions to verify the
2421 certificate chain, and get a 'GNUTLS_CERT_INSECURE_ALGORITHM' validation
2422 error (see *note Verifying X.509 certificate paths::), it means that
2423 somewhere in the certificate chain there is a certificate signed using
2424 'RSA-MD2' or 'RSA-MD5'.  These two digital signature algorithms are
2425 considered broken, so GnuTLS fails verifying the certificate.  In some
2426 situations, it may be useful to be able to verify the certificate chain
2427 anyway, assuming an attacker did not utilize the fact that these
2428 signatures algorithms are broken.  This section will give help on how to
2429 achieve that.
2430
2431 It is important to know that you do not have to enable any of the flags
2432 discussed here to be able to use trusted root CA certificates
2433 self-signed using 'RSA-MD2' or 'RSA-MD5'.  The certificates in the
2434 trusted list are considered trusted irrespective of the signature.
2435
2436 If you are using *note gnutls_certificate_verify_peers3:: to verify the
2437 certificate chain, you can call *note
2438 gnutls_certificate_set_verify_flags:: with the flags:
2439    * 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD2'
2440    * 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5'
2441 as in the following example:
2442
2443        gnutls_certificate_set_verify_flags (x509cred,
2444                                             GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5);
2445
2446 This will signal the verifier algorithm to enable 'RSA-MD5' when
2447 verifying the certificates.
2448
2449 If you are using *note gnutls_x509_crt_verify:: or *note
2450 gnutls_x509_crt_list_verify::, you can pass the
2451 'GNUTLS_VERIFY_ALLOW_SIGN_RSA_MD5' parameter directly in the 'flags'
2452 parameter.
2453
2454 If you are using these flags, it may also be a good idea to warn the
2455 user when verification failure occur for this reason.  The simplest is
2456 to not use the flags by default, and only fall back to using them after
2457 warning the user.  If you wish to inspect the certificate chain
2458 yourself, you can use *note gnutls_certificate_get_peers:: to extract
2459 the raw server's certificate chain, *note gnutls_x509_crt_list_import::
2460 to parse each of the certificates, and then *note
2461 gnutls_x509_crt_get_signature_algorithm:: to find out the signing
2462 algorithm used for each certificate.  If any of the intermediary
2463 certificates are using 'GNUTLS_SIGN_RSA_MD2' or 'GNUTLS_SIGN_RSA_MD5',
2464 you could present a warning.
2465
2466 \1f
2467 File: gnutls.info,  Node: More on certificate authentication,  Next: Shared-key and anonymous authentication,  Prev: Certificate authentication,  Up: Authentication methods
2468
2469 4.2 More on certificate authentication
2470 ======================================
2471
2472 Certificates are not the only structures involved in a public key
2473 infrastructure.  Several other structures that are used for certificate
2474 requests, encrypted private keys, revocation lists, GnuTLS abstract key
2475 structures, etc., are discussed in this chapter.
2476
2477 * Menu:
2478
2479 * PKCS 10 certificate requests::
2480 * PKIX certificate revocation lists::
2481 * OCSP certificate status checking::
2482 * Managing encrypted keys::
2483 * certtool Invocation::            Invoking certtool
2484 * ocsptool Invocation::            Invoking ocsptool
2485 * danetool Invocation::            Invoking danetool
2486
2487 \1f
2488 File: gnutls.info,  Node: PKCS 10 certificate requests,  Next: PKIX certificate revocation lists,  Up: More on certificate authentication
2489
2490 4.2.1 PKCS #10 certificate requests
2491 -----------------------------------
2492
2493 A certificate request is a structure, which contain information about an
2494 applicant of a certificate service.  It usually contains a private key,
2495 a distinguished name and secondary data such as a challenge password.
2496 GnuTLS supports the requests defined in PKCS #10 [_RFC2986_].  Other
2497 formats of certificate requests are not currently supported.
2498
2499 A certificate request can be generated by associating it with a private
2500 key, setting the subject's information and finally self signing it.  The
2501 last step ensures that the requester is in possession of the private
2502 key.
2503
2504 'INT *note gnutls_x509_crq_set_version:: (gnutls_x509_crq_t CRQ, unsigned int VERSION)'
2505 'INT *note gnutls_x509_crq_set_dn:: (gnutls_x509_crq_t CRQ, const char * DN, const char ** ERR)'
2506 '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)'
2507 'INT *note gnutls_x509_crq_set_key_usage:: (gnutls_x509_crq_t CRQ, unsigned int USAGE)'
2508 'INT *note gnutls_x509_crq_set_key_purpose_oid:: (gnutls_x509_crq_t CRQ, const void * OID, unsigned int CRITICAL)'
2509 'INT *note gnutls_x509_crq_set_basic_constraints:: (gnutls_x509_crq_t CRQ, unsigned int CA, int PATHLENCONSTRAINT)'
2510
2511 The *note gnutls_x509_crq_set_key:: and *note gnutls_x509_crq_sign2::
2512 functions associate the request with a private key and sign it.  If a
2513 request is to be signed with a key residing in a PKCS #11 token it is
2514 recommended to use the signing functions shown in *note Abstract key
2515 types::.
2516
2517  -- Function: int gnutls_x509_crq_set_key (gnutls_x509_crq_t CRQ,
2518           gnutls_x509_privkey_t KEY)
2519      CRQ: should contain a 'gnutls_x509_crq_t' structure
2520
2521      KEY: holds a private key
2522
2523      This function will set the public parameters from the given private
2524      key to the request.
2525
2526      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
2527      otherwise a negative error value.
2528
2529  -- Function: int gnutls_x509_crq_sign2 (gnutls_x509_crq_t CRQ,
2530           gnutls_x509_privkey_t KEY, gnutls_digest_algorithm_t DIG,
2531           unsigned int FLAGS)
2532      CRQ: should contain a 'gnutls_x509_crq_t' structure
2533
2534      KEY: holds a private key
2535
2536      DIG: The message digest to use, i.e., 'GNUTLS_DIG_SHA1'
2537
2538      FLAGS: must be 0
2539
2540      This function will sign the certificate request with a private key.
2541      This must be the same key as the one used in
2542      'gnutls_x509_crt_set_key()' since a certificate request is self
2543      signed.
2544
2545      This must be the last step in a certificate request generation
2546      since all the previously set parameters are now signed.
2547
2548      *Returns:* 'GNUTLS_E_SUCCESS' on success, otherwise a negative
2549      error code.  'GNUTLS_E_ASN1_VALUE_NOT_FOUND' is returned if you
2550      didn't set all information in the certificate request (e.g., the
2551      version using 'gnutls_x509_crq_set_version()' ).
2552
2553 The following example is about generating a certificate request, and a
2554 private key.  A certificate request can be later be processed by a CA
2555 which should return a signed certificate.
2556
2557 /* This example code is placed in the public domain. */
2558
2559 #ifdef HAVE_CONFIG_H
2560 #include <config.h>
2561 #endif
2562
2563 #include <stdio.h>
2564 #include <stdlib.h>
2565 #include <string.h>
2566 #include <gnutls/gnutls.h>
2567 #include <gnutls/x509.h>
2568 #include <gnutls/abstract.h>
2569 #include <time.h>
2570
2571 /* This example will generate a private key and a certificate
2572  * request.
2573  */
2574
2575 int main(void)
2576 {
2577         gnutls_x509_crq_t crq;
2578         gnutls_x509_privkey_t key;
2579         unsigned char buffer[10 * 1024];
2580         size_t buffer_size = sizeof(buffer);
2581         unsigned int bits;
2582
2583         gnutls_global_init();
2584
2585         /* Initialize an empty certificate request, and
2586          * an empty private key.
2587          */
2588         gnutls_x509_crq_init(&crq);
2589
2590         gnutls_x509_privkey_init(&key);
2591
2592         /* Generate an RSA key of moderate security.
2593          */
2594         bits =
2595             gnutls_sec_param_to_pk_bits(GNUTLS_PK_RSA,
2596                                         GNUTLS_SEC_PARAM_MEDIUM);
2597         gnutls_x509_privkey_generate(key, GNUTLS_PK_RSA, bits, 0);
2598
2599         /* Add stuff to the distinguished name
2600          */
2601         gnutls_x509_crq_set_dn_by_oid(crq, GNUTLS_OID_X520_COUNTRY_NAME,
2602                                       0, "GR", 2);
2603
2604         gnutls_x509_crq_set_dn_by_oid(crq, GNUTLS_OID_X520_COMMON_NAME,
2605                                       0, "Nikos", strlen("Nikos"));
2606
2607         /* Set the request version.
2608          */
2609         gnutls_x509_crq_set_version(crq, 1);
2610
2611         /* Set a challenge password.
2612          */
2613         gnutls_x509_crq_set_challenge_password(crq,
2614                                                "something to remember here");
2615
2616         /* Associate the request with the private key
2617          */
2618         gnutls_x509_crq_set_key(crq, key);
2619
2620         /* Self sign the certificate request.
2621          */
2622         gnutls_x509_crq_sign2(crq, key, GNUTLS_DIG_SHA1, 0);
2623
2624         /* Export the PEM encoded certificate request, and
2625          * display it.
2626          */
2627         gnutls_x509_crq_export(crq, GNUTLS_X509_FMT_PEM, buffer,
2628                                &buffer_size);
2629
2630         printf("Certificate Request: \n%s", buffer);
2631
2632
2633         /* Export the PEM encoded private key, and
2634          * display it.
2635          */
2636         buffer_size = sizeof(buffer);
2637         gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM, buffer,
2638                                    &buffer_size);
2639
2640         printf("\n\nPrivate key: \n%s", buffer);
2641
2642         gnutls_x509_crq_deinit(crq);
2643         gnutls_x509_privkey_deinit(key);
2644
2645         return 0;
2646
2647 }
2648
2649 \1f
2650 File: gnutls.info,  Node: PKIX certificate revocation lists,  Next: OCSP certificate status checking,  Prev: PKCS 10 certificate requests,  Up: More on certificate authentication
2651
2652 4.2.2 PKIX certificate revocation lists
2653 ---------------------------------------
2654
2655 A certificate revocation list (CRL) is a structure issued by an
2656 authority periodically containing a list of revoked certificates serial
2657 numbers.  The CRL structure is signed with the issuing authorities'
2658 keys.  A typical CRL contains the fields as shown in *note Table 4.7:
2659 tab:crl.  Certificate revocation lists are used to complement the
2660 expiration date of a certificate, in order to account for other reasons
2661 of revocation, such as compromised keys, etc.
2662
2663 Each CRL is valid for limited amount of time and is required to provide,
2664 except for the current issuing time, also the issuing time of the next
2665 update.
2666
2667 Field          Description
2668                
2669 ------------------------------------------------------------------
2670 version        The field that indicates the version of the CRL
2671                structure.
2672                
2673 signature      A signature by the issuing authority.
2674                
2675 issuer         Holds the issuer's distinguished name.
2676                
2677 thisUpdate     The issuing time of the revocation list.
2678                
2679 nextUpdate     The issuing time of the revocation list that
2680                will update that one.
2681                
2682 revokedCertificatesList of revoked certificates serial numbers.
2683                
2684 extensions     Optional CRL structure extensions.
2685                
2686
2687 Table 4.7: Certificate revocation list fields.
2688
2689 The basic CRL structure functions follow.
2690
2691 'INT *note gnutls_x509_crl_init:: (gnutls_x509_crl_t * CRL)'
2692 'INT *note gnutls_x509_crl_import:: (gnutls_x509_crl_t CRL, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)'
2693 '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)'
2694 '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)'
2695
2696 Reading a CRL
2697 .............
2698
2699 The most important function that extracts the certificate revocation
2700 information from a CRL is *note gnutls_x509_crl_get_crt_serial::.  Other
2701 functions that return other fields of the CRL structure are also
2702 provided.
2703
2704  -- Function: int gnutls_x509_crl_get_crt_serial (gnutls_x509_crl_t CRL,
2705           int INDX, unsigned char * SERIAL, size_t * SERIAL_SIZE, time_t
2706           * T)
2707      CRL: should contain a 'gnutls_x509_crl_t' structure
2708
2709      INDX: the index of the certificate to extract (starting from 0)
2710
2711      SERIAL: where the serial number will be copied
2712
2713      SERIAL_SIZE: initially holds the size of serial
2714
2715      T: if non null, will hold the time this certificate was revoked
2716
2717      This function will retrieve the serial number of the specified, by
2718      the index, revoked certificate.
2719
2720      Note that this function will have performance issues in large
2721      sequences of revoked certificates.  In that case use
2722      'gnutls_x509_crl_iter_crt_serial()' .
2723
2724      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
2725      otherwise a negative error value.
2726
2727 'INT *note gnutls_x509_crl_get_version:: (gnutls_x509_crl_t CRL)'
2728 'INT *note gnutls_x509_crl_get_issuer_dn:: (const gnutls_x509_crl_t CRL, char * BUF, size_t * SIZEOF_BUF)'
2729 'INT *note gnutls_x509_crl_get_issuer_dn2:: (gnutls_x509_crl_t CRL, gnutls_datum_t * DN)'
2730 'TIME_T *note gnutls_x509_crl_get_this_update:: (gnutls_x509_crl_t CRL)'
2731 'TIME_T *note gnutls_x509_crl_get_next_update:: (gnutls_x509_crl_t CRL)'
2732 'INT *note gnutls_x509_crl_get_crt_count:: (gnutls_x509_crl_t CRL)'
2733
2734 Generation of a CRL
2735 ...................
2736
2737 The following functions can be used to generate a CRL.
2738
2739 'INT *note gnutls_x509_crl_set_version:: (gnutls_x509_crl_t CRL, unsigned int VERSION)'
2740 'INT *note gnutls_x509_crl_set_crt_serial:: (gnutls_x509_crl_t CRL, const void * SERIAL, size_t SERIAL_SIZE, time_t REVOCATION_TIME)'
2741 'INT *note gnutls_x509_crl_set_crt:: (gnutls_x509_crl_t CRL, gnutls_x509_crt_t CRT, time_t REVOCATION_TIME)'
2742 'INT *note gnutls_x509_crl_set_next_update:: (gnutls_x509_crl_t CRL, time_t EXP_TIME)'
2743 'INT *note gnutls_x509_crl_set_this_update:: (gnutls_x509_crl_t CRL, time_t ACT_TIME)'
2744
2745 The *note gnutls_x509_crl_sign2:: and *note
2746 gnutls_x509_crl_privkey_sign:: functions sign the revocation list with a
2747 private key.  The latter function can be used to sign with a key
2748 residing in a PKCS #11 token.
2749
2750  -- Function: int gnutls_x509_crl_sign2 (gnutls_x509_crl_t CRL,
2751           gnutls_x509_crt_t ISSUER, gnutls_x509_privkey_t ISSUER_KEY,
2752           gnutls_digest_algorithm_t DIG, unsigned int FLAGS)
2753      CRL: should contain a gnutls_x509_crl_t structure
2754
2755      ISSUER: is the certificate of the certificate issuer
2756
2757      ISSUER_KEY: holds the issuer's private key
2758
2759      DIG: The message digest to use.  GNUTLS_DIG_SHA1 is the safe choice
2760      unless you know what you're doing.
2761
2762      FLAGS: must be 0
2763
2764      This function will sign the CRL with the issuer's private key, and
2765      will copy the issuer's information into the CRL.
2766
2767      This must be the last step in a certificate CRL since all the
2768      previously set parameters are now signed.
2769
2770      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
2771      otherwise a negative error value.
2772
2773  -- Function: int gnutls_x509_crl_privkey_sign (gnutls_x509_crl_t CRL,
2774           gnutls_x509_crt_t ISSUER, gnutls_privkey_t ISSUER_KEY,
2775           gnutls_digest_algorithm_t DIG, unsigned int FLAGS)
2776      CRL: should contain a gnutls_x509_crl_t structure
2777
2778      ISSUER: is the certificate of the certificate issuer
2779
2780      ISSUER_KEY: holds the issuer's private key
2781
2782      DIG: The message digest to use.  GNUTLS_DIG_SHA1 is the safe choice
2783      unless you know what you're doing.
2784
2785      FLAGS: must be 0
2786
2787      This function will sign the CRL with the issuer's private key, and
2788      will copy the issuer's information into the CRL.
2789
2790      This must be the last step in a certificate CRL since all the
2791      previously set parameters are now signed.
2792
2793      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
2794      otherwise a negative error value.
2795
2796      Since 2.12.0
2797
2798 Few extensions on the CRL structure are supported, including the CRL
2799 number extension and the authority key identifier.
2800
2801 'INT *note gnutls_x509_crl_set_number:: (gnutls_x509_crl_t CRL, const void * NR, size_t NR_SIZE)'
2802 'INT *note gnutls_x509_crl_set_authority_key_id:: (gnutls_x509_crl_t CRL, const void * ID, size_t ID_SIZE)'
2803
2804 \1f
2805 File: gnutls.info,  Node: OCSP certificate status checking,  Next: Managing encrypted keys,  Prev: PKIX certificate revocation lists,  Up: More on certificate authentication
2806
2807 4.2.3 OCSP certificate status checking
2808 --------------------------------------
2809
2810 Certificates may be revoked before their expiration time has been
2811 reached.  There are several reasons for revoking certificates, but a
2812 typical situation is when the private key associated with a certificate
2813 has been compromised.  Traditionally, Certificate Revocation Lists
2814 (CRLs) have been used by application to implement revocation checking,
2815 however, several problems with CRLs have been identified [_RIVESTCRL_].
2816
2817 The Online Certificate Status Protocol, or OCSP [_RFC2560_], is a widely
2818 implemented protocol which performs certificate revocation status
2819 checking.  An application that wish to verify the identity of a peer
2820 will verify the certificate against a set of trusted certificates and
2821 then check whether the certificate is listed in a CRL and/or perform an
2822 OCSP check for the certificate.
2823
2824 Note that in the context of a TLS session the server may provide an OCSP
2825 response that will be used during the TLS certificate verification (see
2826 *note gnutls_certificate_verify_peers2::).  You may obtain this response
2827 using *note gnutls_ocsp_status_request_get::.
2828
2829 Before performing the OCSP query, the application will need to figure
2830 out the address of the OCSP server.  The OCSP server address can be
2831 provided by the local user in manual configuration or may be stored in
2832 the certificate that is being checked.  When stored in a certificate the
2833 OCSP server is in the extension field called the Authority Information
2834 Access (AIA). The following function extracts this information from a
2835 certificate.
2836
2837 '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)'
2838
2839 There are several functions in GnuTLS for creating and manipulating OCSP
2840 requests and responses.  The general idea is that a client application
2841 creates an OCSP request object, stores some information about the
2842 certificate to check in the request, and then exports the request in DER
2843 format.  The request will then need to be sent to the OCSP responder,
2844 which needs to be done by the application (GnuTLS does not send and
2845 receive OCSP packets).  Normally an OCSP response is received that the
2846 application will need to import into an OCSP response object.  The
2847 digital signature in the OCSP response needs to be verified against a
2848 set of trust anchors before the information in the response can be
2849 trusted.
2850
2851 The ASN.1 structure of OCSP requests are briefly as follows.  It is
2852 useful to review the structures to get an understanding of which fields
2853 are modified by GnuTLS functions.
2854
2855      OCSPRequest     ::=     SEQUENCE {
2856          tbsRequest                  TBSRequest,
2857          optionalSignature   [0]     EXPLICIT Signature OPTIONAL }
2858
2859      TBSRequest      ::=     SEQUENCE {
2860          version             [0]     EXPLICIT Version DEFAULT v1,
2861          requestorName       [1]     EXPLICIT GeneralName OPTIONAL,
2862          requestList                 SEQUENCE OF Request,
2863          requestExtensions   [2]     EXPLICIT Extensions OPTIONAL }
2864
2865      Request         ::=     SEQUENCE {
2866          reqCert                     CertID,
2867          singleRequestExtensions     [0] EXPLICIT Extensions OPTIONAL }
2868
2869      CertID          ::=     SEQUENCE {
2870          hashAlgorithm       AlgorithmIdentifier,
2871          issuerNameHash      OCTET STRING, -- Hash of Issuer's DN
2872          issuerKeyHash       OCTET STRING, -- Hash of Issuers public key
2873          serialNumber        CertificateSerialNumber }
2874
2875 The basic functions to initialize, import, export and deallocate OCSP
2876 requests are the following.
2877
2878 'INT *note gnutls_ocsp_req_init:: (gnutls_ocsp_req_t * REQ)'
2879 'VOID *note gnutls_ocsp_req_deinit:: (gnutls_ocsp_req_t REQ)'
2880 'INT *note gnutls_ocsp_req_import:: (gnutls_ocsp_req_t REQ, const gnutls_datum_t * DATA)'
2881 'INT *note gnutls_ocsp_req_export:: (gnutls_ocsp_req_t REQ, gnutls_datum_t * DATA)'
2882 'INT *note gnutls_ocsp_req_print:: (gnutls_ocsp_req_t REQ, gnutls_ocsp_print_formats_t FORMAT, gnutls_datum_t * OUT)'
2883
2884 To generate an OCSP request the issuer name hash, issuer key hash, and
2885 the checked certificate's serial number are required.  There are two
2886 interfaces available for setting those in an OCSP request.  The is a
2887 low-level function when you have the issuer name hash, issuer key hash,
2888 and certificate serial number in binary form.  The second is more useful
2889 if you have the certificate (and its issuer) in a 'gnutls_x509_crt_t'
2890 type.  There is also a function to extract this information from
2891 existing an OCSP request.
2892
2893 '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)'
2894 '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)'
2895 '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)'
2896
2897 Each OCSP request may contain a number of extensions.  Extensions are
2898 identified by an Object Identifier (OID) and an opaque data buffer whose
2899 syntax and semantics is implied by the OID. You can extract or set those
2900 extensions using the following functions.
2901
2902 '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)'
2903 'INT *note gnutls_ocsp_req_set_extension:: (gnutls_ocsp_req_t REQ, const char * OID, unsigned int CRITICAL, const gnutls_datum_t * DATA)'
2904
2905 A common OCSP Request extension is the nonce extension (OID
2906 1.3.6.1.5.5.7.48.1.2), which is used to avoid replay attacks of earlier
2907 recorded OCSP responses.  The nonce extension carries a value that is
2908 intended to be sufficiently random and unique so that an attacker will
2909 not be able to give a stale response for the same nonce.
2910
2911 'INT *note gnutls_ocsp_req_get_nonce:: (gnutls_ocsp_req_t REQ, unsigned int * CRITICAL, gnutls_datum_t * NONCE)'
2912 'INT *note gnutls_ocsp_req_set_nonce:: (gnutls_ocsp_req_t REQ, unsigned int CRITICAL, const gnutls_datum_t * NONCE)'
2913 'INT *note gnutls_ocsp_req_randomize_nonce:: (gnutls_ocsp_req_t REQ)'
2914
2915 The OCSP response structures is a complex structure.  A simplified
2916 overview of it is in *note Table 4.8: tab:ocsp-response.  Note that a
2917 response may contain information on multiple certificates.
2918
2919 Field          Description
2920                
2921 ------------------------------------------------------------------
2922 version        The OCSP response version number (typically 1).
2923                
2924 responder ID   An identifier of the responder (DN name or a
2925                hash of its key).
2926                
2927 issue time     The time the response was generated.
2928                
2929 thisUpdate     The issuing time of the revocation information.
2930                
2931 nextUpdate     The issuing time of the revocation information
2932                that will update that one.
2933                
2934                Revoked certificates
2935                
2936 certificate    The status of the certificate.
2937 status         
2938 certificate    The certificate's serial number.
2939 serial         
2940 revocationTime The time the certificate was revoked.
2941                
2942 revocationReasonThe reason the certificate was revoked.
2943                
2944
2945 Table 4.8: The most important OCSP response fields.
2946
2947 We provide basic functions for initialization, importing, exporting and
2948 deallocating OCSP responses.
2949
2950 'INT *note gnutls_ocsp_resp_init:: (gnutls_ocsp_resp_t * RESP)'
2951 'VOID *note gnutls_ocsp_resp_deinit:: (gnutls_ocsp_resp_t RESP)'
2952 'INT *note gnutls_ocsp_resp_import:: (gnutls_ocsp_resp_t RESP, const gnutls_datum_t * DATA)'
2953 'INT *note gnutls_ocsp_resp_export:: (gnutls_ocsp_resp_t RESP, gnutls_datum_t * DATA)'
2954 'INT *note gnutls_ocsp_resp_print:: (gnutls_ocsp_resp_t RESP, gnutls_ocsp_print_formats_t FORMAT, gnutls_datum_t * OUT)'
2955
2956 The utility function that extracts the revocation as well as other
2957 information from a response is shown below.
2958
2959  -- Function: int gnutls_ocsp_resp_get_single (gnutls_ocsp_resp_t RESP,
2960           unsigned INDX, gnutls_digest_algorithm_t * DIGEST,
2961           gnutls_datum_t * ISSUER_NAME_HASH, gnutls_datum_t *
2962           ISSUER_KEY_HASH, gnutls_datum_t * SERIAL_NUMBER, unsigned int
2963           * CERT_STATUS, time_t * THIS_UPDATE, time_t * NEXT_UPDATE,
2964           time_t * REVOCATION_TIME, unsigned int * REVOCATION_REASON)
2965      RESP: should contain a 'gnutls_ocsp_resp_t' structure
2966
2967      INDX: Specifies response number to get.  Use (0) to get the first
2968      one.
2969
2970      DIGEST: output variable with 'gnutls_digest_algorithm_t' hash
2971      algorithm
2972
2973      ISSUER_NAME_HASH: output buffer with hash of issuer's DN
2974
2975      ISSUER_KEY_HASH: output buffer with hash of issuer's public key
2976
2977      SERIAL_NUMBER: output buffer with serial number of certificate to
2978      check
2979
2980      CERT_STATUS: a certificate status, a 'gnutls_ocsp_cert_status_t'
2981      enum.
2982
2983      THIS_UPDATE: time at which the status is known to be correct.
2984
2985      NEXT_UPDATE: when newer information will be available, or
2986      (time_t)-1 if unspecified
2987
2988      REVOCATION_TIME: when 'cert_status' is 'GNUTLS_OCSP_CERT_REVOKED' ,
2989      holds time of revocation.
2990
2991      REVOCATION_REASON: revocation reason, a 'gnutls_x509_crl_reason_t'
2992      enum.
2993
2994      This function will return the certificate information of the 'indx'
2995      'ed response in the Basic OCSP Response 'resp' .  The information
2996      returned corresponds to the OCSP SingleResponse structure except
2997      the final singleExtensions.
2998
2999      Each of the pointers to output variables may be NULL to indicate
3000      that the caller is not interested in that value.
3001
3002      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
3003      otherwise a negative error code is returned.  If you have reached
3004      the last CertID available 'GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE'
3005      will be returned.
3006
3007 The possible revocation reasons available in an OCSP response are shown
3008 below.
3009
3010 'GNUTLS_X509_CRLREASON_UNSPECIFIED'
3011      Unspecified reason.
3012 'GNUTLS_X509_CRLREASON_KEYCOMPROMISE'
3013      Private key compromised.
3014 'GNUTLS_X509_CRLREASON_CACOMPROMISE'
3015      CA compromised.
3016 'GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED'
3017      Affiliation has changed.
3018 'GNUTLS_X509_CRLREASON_SUPERSEDED'
3019      Certificate superseded.
3020 'GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION'
3021      Operation has ceased.
3022 'GNUTLS_X509_CRLREASON_CERTIFICATEHOLD'
3023      Certificate is on hold.
3024 'GNUTLS_X509_CRLREASON_REMOVEFROMCRL'
3025      Will be removed from delta CRL.
3026 'GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN'
3027      Privilege withdrawn.
3028 'GNUTLS_X509_CRLREASON_AACOMPROMISE'
3029      AA compromised.
3030
3031 Figure 4.5: The revocation reasons
3032
3033 Note, that the OCSP response needs to be verified against some set of
3034 trust anchors before it can be relied upon.  It is also important to
3035 check whether the received OCSP response corresponds to the certificate
3036 being checked.
3037
3038 'INT *note gnutls_ocsp_resp_verify:: (gnutls_ocsp_resp_t RESP, gnutls_x509_trust_list_t TRUSTLIST, unsigned int * VERIFY, unsigned int FLAGS)'
3039 'INT *note gnutls_ocsp_resp_verify_direct:: (gnutls_ocsp_resp_t RESP, gnutls_x509_crt_t ISSUER, unsigned int * VERIFY, unsigned int FLAGS)'
3040 'INT *note gnutls_ocsp_resp_check_crt:: (gnutls_ocsp_resp_t RESP, unsigned int INDX, gnutls_x509_crt_t CRT)'
3041
3042 \1f
3043 File: gnutls.info,  Node: Managing encrypted keys,  Next: certtool Invocation,  Prev: OCSP certificate status checking,  Up: More on certificate authentication
3044
3045 4.2.4 Managing encrypted keys
3046 -----------------------------
3047
3048 Transferring or storing private keys in plain may not be a good idea,
3049 since any compromise is irreparable.  Storing the keys in hardware
3050 security modules (see *note Smart cards and HSMs::) could solve the
3051 storage problem but it is not always practical or efficient enough.
3052 This section describes ways to store and transfer encrypted private
3053 keys.
3054
3055 There are methods for key encryption, namely the PKCS #8, PKCS #12 and
3056 OpenSSL's custom encrypted private key formats.  The PKCS #8 and the
3057 OpenSSL's method allow encryption of the private key, while the PKCS #12
3058 method allows, in addition, the bundling of accompanying data into the
3059 structure.  That is typically the corresponding certificate, as well as
3060 a trusted CA certificate.
3061
3062 High level functionality
3063 ........................
3064
3065 Generic and higher level private key import functions are available,
3066 that import plain or encrypted keys and will auto-detect the encrypted
3067 key format.
3068
3069  -- Function: int gnutls_privkey_import_x509_raw (gnutls_privkey_t PKEY,
3070           const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT,
3071           const char * PASSWORD, unsigned int FLAGS)
3072      PKEY: The private key
3073
3074      DATA: The private key data to be imported
3075
3076      FORMAT: The format of the private key
3077
3078      PASSWORD: A password (optional)
3079
3080      FLAGS: an ORed sequence of gnutls_pkcs_encrypt_flags_t
3081
3082      This function will import the given private key to the abstract
3083      'gnutls_privkey_t' structure.
3084
3085      The supported formats are basic unencrypted key, PKCS8, PKCS12, and
3086      the openssl format.
3087
3088      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
3089      otherwise a negative error value.
3090
3091      *Since:* 3.1.0
3092
3093  -- Function: int gnutls_x509_privkey_import2 (gnutls_x509_privkey_t
3094           KEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t
3095           FORMAT, const char * PASSWORD, unsigned int FLAGS)
3096      KEY: The structure to store the parsed key
3097
3098      DATA: The DER or PEM encoded key.
3099
3100      FORMAT: One of DER or PEM
3101
3102      PASSWORD: A password (optional)
3103
3104      FLAGS: an ORed sequence of gnutls_pkcs_encrypt_flags_t
3105
3106      This function will import the given DER or PEM encoded key, to the
3107      native 'gnutls_x509_privkey_t' format, irrespective of the input
3108      format.  The input format is auto-detected.
3109
3110      The supported formats are basic unencrypted key, PKCS8, PKCS12, and
3111      the openssl format.
3112
3113      If the provided key is encrypted but no password was given, then
3114      'GNUTLS_E_DECRYPTION_FAILED' is returned.
3115
3116      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
3117      otherwise a negative error value.
3118
3119 Any keys imported using those functions can be imported to a certificate
3120 credentials structure using *note gnutls_certificate_set_key::, or
3121 alternatively they can be directly imported using *note
3122 gnutls_certificate_set_x509_key_file2::.
3123
3124 PKCS #8 structures
3125 ..................
3126
3127 PKCS #8 keys can be imported and exported as normal private keys using
3128 the functions below.  An addition to the normal import functions, are a
3129 password and a flags argument.  The flags can be any element of the
3130 'gnutls_pkcs_encrypt_flags_t' enumeration.  Note however, that GnuTLS
3131 only supports the PKCS #5 PBES2 encryption scheme.  Keys encrypted with
3132 the obsolete PBES1 scheme cannot be decrypted.
3133
3134 '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)'
3135 '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)'
3136 '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)'
3137
3138 'GNUTLS_PKCS_PLAIN'
3139      Unencrypted private key.
3140 'GNUTLS_PKCS_PKCS12_3DES'
3141      PKCS-12 3DES.
3142 'GNUTLS_PKCS_PKCS12_ARCFOUR'
3143      PKCS-12 ARCFOUR.
3144 'GNUTLS_PKCS_PKCS12_RC2_40'
3145      PKCS-12 RC2-40.
3146 'GNUTLS_PKCS_PBES2_3DES'
3147      PBES2 3DES.
3148 'GNUTLS_PKCS_PBES2_AES_128'
3149      PBES2 AES-128.
3150 'GNUTLS_PKCS_PBES2_AES_192'
3151      PBES2 AES-192.
3152 'GNUTLS_PKCS_PBES2_AES_256'
3153      PBES2 AES-256.
3154 'GNUTLS_PKCS_NULL_PASSWORD'
3155      Some schemas distinguish between an empty and a NULL password.
3156 'GNUTLS_PKCS_PBES2_DES'
3157      PBES2 single DES.
3158
3159 Figure 4.6: Encryption flags
3160
3161 PKCS #12 structures
3162 ...................
3163
3164 A PKCS #12 structure [_PKCS12_] usually contains a user's private keys
3165 and certificates.  It is commonly used in browsers to export and import
3166 the user's identities.  A file containing such a key can be directly
3167 imported to a certificate credentials structure by using *note
3168 gnutls_certificate_set_x509_simple_pkcs12_file::.
3169
3170 In GnuTLS the PKCS #12 structures are handled using the
3171 'gnutls_pkcs12_t' type.  This is an abstract type that may hold several
3172 'gnutls_pkcs12_bag_t' types.  The bag types are the holders of the
3173 actual data, which may be certificates, private keys or encrypted data.
3174 A bag of type encrypted should be decrypted in order for its data to be
3175 accessed.
3176
3177 To reduce the complexity in parsing the structures the simple helper
3178 function *note gnutls_pkcs12_simple_parse:: is provided.  For more
3179 advanced uses, manual parsing of the structure is required using the
3180 functions below.
3181
3182 'INT *note gnutls_pkcs12_get_bag:: (gnutls_pkcs12_t PKCS12, int INDX, gnutls_pkcs12_bag_t BAG)'
3183 'INT *note gnutls_pkcs12_verify_mac:: (gnutls_pkcs12_t PKCS12, const char * PASS)'
3184 'INT *note gnutls_pkcs12_bag_decrypt:: (gnutls_pkcs12_bag_t BAG, const char * PASS)'
3185 'INT *note gnutls_pkcs12_bag_get_count:: (gnutls_pkcs12_bag_t BAG)'
3186
3187  -- Function: int gnutls_pkcs12_simple_parse (gnutls_pkcs12_t P12, const
3188           char * PASSWORD, gnutls_x509_privkey_t * KEY,
3189           gnutls_x509_crt_t ** CHAIN, unsigned int * CHAIN_LEN,
3190           gnutls_x509_crt_t ** EXTRA_CERTS, unsigned int *
3191           EXTRA_CERTS_LEN, gnutls_x509_crl_t * CRL, unsigned int FLAGS)
3192      P12: should contain a gnutls_pkcs12_t structure
3193
3194      PASSWORD: optional password used to decrypt the structure, bags and
3195      keys.
3196
3197      KEY: a structure to store the parsed private key.
3198
3199      CHAIN: the corresponding to key certificate chain (may be 'NULL' )
3200
3201      CHAIN_LEN: will be updated with the number of additional (may be
3202      'NULL' )
3203
3204      EXTRA_CERTS: optional pointer to receive an array of additional
3205      certificates found in the PKCS12 structure (may be 'NULL' ).
3206
3207      EXTRA_CERTS_LEN: will be updated with the number of additional
3208      certs (may be 'NULL' ).
3209
3210      CRL: an optional structure to store the parsed CRL (may be 'NULL'
3211      ).
3212
3213      FLAGS: should be zero or one of GNUTLS_PKCS12_SP_*
3214
3215      This function parses a PKCS12 structure in 'pkcs12' and extracts
3216      the private key, the corresponding certificate chain, any
3217      additional certificates and a CRL.
3218
3219      The 'extra_certs' and 'extra_certs_len' parameters are optional and
3220      both may be set to 'NULL' .  If either is non-'NULL' , then both
3221      must be set.  The value for 'extra_certs' is allocated using
3222      'gnutls_malloc()' .
3223
3224      Encrypted PKCS12 bags and PKCS8 private keys are supported, but
3225      only with password based security and the same password for all
3226      operations.
3227
3228      Note that a PKCS12 structure may contain many keys and/or
3229      certificates, and there is no way to identify which key/certificate
3230      pair you want.  For this reason this function is useful for PKCS12
3231      files that contain only one key/certificate pair and/or one CRL.
3232
3233      If the provided structure has encrypted fields but no password is
3234      provided then this function returns 'GNUTLS_E_DECRYPTION_FAILED' .
3235
3236      Note that normally the chain constructed does not include self
3237      signed certificates, to comply with TLS' requirements.  If,
3238      however, the flag 'GNUTLS_PKCS12_SP_INCLUDE_SELF_SIGNED' is
3239      specified then self signed certificates will be included in the
3240      chain.
3241
3242      Prior to using this function the PKCS '12' structure integrity must
3243      be verified using 'gnutls_pkcs12_verify_mac()' .
3244
3245      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
3246      otherwise a negative error value.
3247
3248      *Since:* 3.1.0
3249 'INT *note gnutls_pkcs12_bag_get_data:: (gnutls_pkcs12_bag_t BAG, int INDX, gnutls_datum_t * DATA)'
3250 'INT *note gnutls_pkcs12_bag_get_key_id:: (gnutls_pkcs12_bag_t BAG, int INDX, gnutls_datum_t * ID)'
3251 'INT *note gnutls_pkcs12_bag_get_friendly_name:: (gnutls_pkcs12_bag_t BAG, int INDX, char ** NAME)'
3252
3253 The functions below are used to generate a PKCS #12 structure.  An
3254 example of their usage is shown at *note PKCS12 structure generation
3255 example::.
3256
3257 'INT *note gnutls_pkcs12_set_bag:: (gnutls_pkcs12_t PKCS12, gnutls_pkcs12_bag_t BAG)'
3258 'INT *note gnutls_pkcs12_bag_encrypt:: (gnutls_pkcs12_bag_t BAG, const char * PASS, unsigned int FLAGS)'
3259 'INT *note gnutls_pkcs12_generate_mac:: (gnutls_pkcs12_t PKCS12, const char * PASS)'
3260 'INT *note gnutls_pkcs12_bag_set_data:: (gnutls_pkcs12_bag_t BAG, gnutls_pkcs12_bag_type_t TYPE, const gnutls_datum_t * DATA)'
3261 'INT *note gnutls_pkcs12_bag_set_crl:: (gnutls_pkcs12_bag_t BAG, gnutls_x509_crl_t CRL)'
3262 'INT *note gnutls_pkcs12_bag_set_crt:: (gnutls_pkcs12_bag_t BAG, gnutls_x509_crt_t CRT)'
3263 'INT *note gnutls_pkcs12_bag_set_key_id:: (gnutls_pkcs12_bag_t BAG, int INDX, const gnutls_datum_t * ID)'
3264 'INT *note gnutls_pkcs12_bag_set_friendly_name:: (gnutls_pkcs12_bag_t BAG, int INDX, const char * NAME)'
3265
3266 OpenSSL encrypted keys
3267 ......................
3268
3269 Unfortunately the structures discussed in the previous sections are not
3270 the only structures that may hold an encrypted private key.  For example
3271 the OpenSSL library offers a custom key encryption method.  Those
3272 structures are also supported in GnuTLS with *note
3273 gnutls_x509_privkey_import_openssl::.
3274
3275  -- Function: int gnutls_x509_privkey_import_openssl
3276           (gnutls_x509_privkey_t KEY, const gnutls_datum_t * DATA, const
3277           char * PASSWORD)
3278      KEY: The structure to store the parsed key
3279
3280      DATA: The DER or PEM encoded key.
3281
3282      PASSWORD: the password to decrypt the key (if it is encrypted).
3283
3284      This function will convert the given PEM encrypted to the native
3285      gnutls_x509_privkey_t format.  The output will be stored in 'key' .
3286
3287      The 'password' should be in ASCII. If the password is not provided
3288      or wrong then 'GNUTLS_E_DECRYPTION_FAILED' will be returned.
3289
3290      If the Certificate is PEM encoded it should have a header of
3291      "PRIVATE KEY" and the "DEK-Info" header.
3292
3293      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
3294      otherwise a negative error value.
3295
3296 \1f
3297 File: gnutls.info,  Node: certtool Invocation,  Next: ocsptool Invocation,  Prev: Managing encrypted keys,  Up: More on certificate authentication
3298
3299 4.2.5 Invoking certtool
3300 -----------------------
3301
3302 Tool to parse and generate X.509 certificates, requests and private
3303 keys.  It can be used interactively or non interactively by specifying
3304 the template command line option.
3305
3306 The tool accepts files or URLs supported by GnuTLS. In case PIN is
3307 required for the URL access you can provide it using the environment
3308 variables GNUTLS_PIN and GNUTLS_SO_PIN.
3309
3310 This section was generated by *AutoGen*, using the 'agtexi-cmd' template
3311 and the option descriptions for the 'certtool' program.  This software
3312 is released under the GNU General Public License, version 3 or later.
3313
3314 certtool help/usage ('--help')
3315 ..............................
3316
3317 This is the automatically generated usage text for certtool.
3318
3319 The text printed is the same whether selected with the 'help' option
3320 ('--help') or the 'more-help' option ('--more-help').  'more-help' will
3321 print the usage text by passing it through a pager program.  'more-help'
3322 is disabled on platforms without a working 'fork(2)' function.  The
3323 'PAGER' environment variable is used to select the program, defaulting
3324 to 'more'.  Both will exit with a status code of 0.
3325
3326      certtool - GnuTLS certificate tool
3327      Usage:  certtool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...
3328
3329         -d, --debug=num            Enable debugging
3330                                      - it must be in the range:
3331                                        0 to 9999
3332         -V, --verbose              More verbose output
3333                                      - may appear multiple times
3334             --infile=file          Input file
3335                                      - file must pre-exist
3336             --outfile=str          Output file
3337         -s, --generate-self-signed  Generate a self-signed certificate
3338         -c, --generate-certificate  Generate a signed certificate
3339             --generate-proxy       Generates a proxy certificate
3340             --generate-crl         Generate a CRL
3341         -u, --update-certificate   Update a signed certificate
3342         -p, --generate-privkey     Generate a private key
3343             --provable             Generate a private key or parameters from a seed using a provable method
3344             --verify-provable-privkey  Verify a private key generated from a seed using a provable method
3345             --seed=str             When generating a private key use the given hex-encoded seed
3346         -q, --generate-request     Generate a PKCS #10 certificate request
3347                                      - prohibits the option 'infile'
3348         -e, --verify-chain         Verify a PEM encoded certificate chain
3349             --verify               Verify a PEM encoded certificate chain using a trusted list
3350             --verify-crl           Verify a CRL using a trusted list
3351                                      - requires the option 'load-ca-certificate'
3352             --verify-hostname=str  Specify a hostname to be used for certificate chain verification
3353             --verify-email=str     Specify a email to be used for certificate chain verification
3354                                      - prohibits the option 'verify-hostname'
3355             --verify-purpose=str   Specify a purpose OID to be used for certificate chain verification
3356             --verify-allow-broken  Allow broken algorithms, such as MD5 for verification
3357             --generate-dh-params   Generate PKCS #3 encoded Diffie-Hellman parameters
3358             --get-dh-params        Get the included PKCS #3 encoded Diffie-Hellman parameters
3359             --dh-info              Print information PKCS #3 encoded Diffie-Hellman parameters
3360             --load-privkey=str     Loads a private key file
3361             --load-pubkey=str      Loads a public key file
3362             --load-request=str     Loads a certificate request file
3363             --load-certificate=str Loads a certificate file
3364             --load-ca-privkey=str  Loads the certificate authority's private key file
3365             --load-ca-certificate=str Loads the certificate authority's certificate file
3366             --load-crl=str         Loads the provided CRL
3367             --load-data=str        Loads auxiliary data
3368             --password=str         Password to use
3369             --null-password        Enforce a NULL password
3370             --empty-password       Enforce an empty password
3371             --hex-numbers          Print big number in an easier format to parse
3372             --cprint               In certain operations it prints the information in C-friendly format
3373         -i, --certificate-info     Print information on the given certificate
3374             --fingerprint          Print the fingerprint of the given certificate
3375             --key-id               Print the key ID of the given certificate
3376             --certificate-pubkey   Print certificate's public key
3377             --pgp-certificate-info  Print information on the given OpenPGP certificate
3378             --pgp-ring-info        Print information on the given OpenPGP keyring structure
3379         -l, --crl-info             Print information on the given CRL structure
3380             --crq-info             Print information on the given certificate request
3381             --no-crq-extensions    Do not use extensions in certificate requests
3382             --p12-info             Print information on a PKCS #12 structure
3383             --p12-name=str         The PKCS #12 friendly name to use
3384             --p7-generate          Generate a PKCS #7 structure
3385             --p7-sign              Signs using a PKCS #7 structure
3386             --p7-detached-sign     Signs using a detached PKCS #7 structure
3387             --p7-include-cert      The signer's certificate will be included in the cert list.
3388                                      - disabled as '--no-p7-include-cert'
3389                                      - enabled by default
3390             --p7-time              Will include a timestamp in the PKCS #7 structure
3391                                      - disabled as '--no-p7-time'
3392             --p7-show-data         Will show the embedded data in the PKCS #7 structure
3393                                      - disabled as '--no-p7-show-data'
3394             --p7-info              Print information on a PKCS #7 structure
3395             --p7-verify            Verify the provided PKCS #7 structure
3396             --p8-info              Print information on a PKCS #8 structure
3397             --smime-to-p7          Convert S/MIME to PKCS #7 structure
3398         -k, --key-info             Print information on a private key
3399             --pgp-key-info         Print information on an OpenPGP private key
3400             --pubkey-info          Print information on a public key
3401             --v1                   Generate an X.509 version 1 certificate (with no extensions)
3402             --to-p12               Generate a PKCS #12 structure
3403             --to-p8                Generate a PKCS #8 structure
3404         -8, --pkcs8                Use PKCS #8 format for private keys
3405             --rsa                  Generate RSA key
3406             --dsa                  Generate DSA key
3407             --ecc                  Generate ECC (ECDSA) key
3408             --ecdsa                an alias for the 'ecc' option
3409             --hash=str             Hash algorithm to use for signing
3410             --inder                Use DER format for input certificates, private keys, and DH parameters
3411                                      - disabled as '--no-inder'
3412             --inraw                an alias for the 'inder' option
3413             --outder               Use DER format for output certificates, private keys, and DH parameters
3414                                      - disabled as '--no-outder'
3415             --outraw               an alias for the 'outder' option
3416             --bits=num             Specify the number of bits for key generate
3417             --curve=str            Specify the curve used for EC key generation
3418             --sec-param=str        Specify the security level [low, legacy, medium, high, ultra]
3419             --disable-quick-random  No effect
3420             --template=str         Template file to use for non-interactive operation
3421             --stdout-info          Print information to stdout instead of stderr
3422             --ask-pass             Enable interaction for entering password when in batch mode.
3423             --pkcs-cipher=str      Cipher to use for PKCS #8 and #12 operations
3424             --provider=str         Specify the PKCS #11 provider library
3425         -v, --version[=arg]        output version information and exit
3426         -h, --help                 display extended usage information and exit
3427         -!, --more-help            extended usage information passed thru pager
3428
3429      Options are specified by doubled hyphens and their name or by a single
3430      hyphen and the flag character.
3431
3432      Tool to parse and generate X.509 certificates, requests and private keys.
3433      It can be used interactively or non interactively by specifying the
3434      template command line option.
3435
3436      The tool accepts files or URLs supported by GnuTLS.  In case PIN is
3437      required for the URL access you can provide it using the environment
3438      variables GNUTLS_PIN and GNUTLS_SO_PIN.
3439
3440
3441 debug option (-d)
3442 .................
3443
3444 This is the "enable debugging" option.  This option takes a number
3445 argument.  Specifies the debug level.
3446
3447 generate-request option (-q)
3448 ............................
3449
3450 This is the "generate a pkcs #10 certificate request" option.
3451
3452 This option has some usage constraints.  It:
3453    * must not appear in combination with any of the following options:
3454      infile.
3455
3456 Will generate a PKCS #10 certificate request.  To specify a private key
3457 use -load-privkey.
3458
3459 verify-chain option (-e)
3460 ........................
3461
3462 This is the "verify a pem encoded certificate chain" option.  The last
3463 certificate in the chain must be a self signed one.
3464
3465 verify option
3466 .............
3467
3468 This is the "verify a pem encoded certificate chain using a trusted
3469 list" option.  The trusted certificate list can be loaded with
3470 -load-ca-certificate.  If no certificate list is provided, then the
3471 system's certificate list is used.
3472
3473 verify-crl option
3474 .................
3475
3476 This is the "verify a crl using a trusted list" option.
3477
3478 This option has some usage constraints.  It:
3479    * must appear in combination with the following options:
3480      load-ca-certificate.
3481
3482 The trusted certificate list must be loaded with -load-ca-certificate.
3483
3484 get-dh-params option
3485 ....................
3486
3487 This is the "get the included pkcs #3 encoded diffie-hellman parameters"
3488 option.  Returns stored DH parameters in GnuTLS. Those parameters are
3489 used in the SRP protocol.  The parameters returned by fresh generation
3490 are more efficient since GnuTLS 3.0.9.
3491
3492 load-privkey option
3493 ...................
3494
3495 This is the "loads a private key file" option.  This option takes a
3496 string argument.  This can be either a file or a PKCS #11 URL
3497
3498 load-pubkey option
3499 ..................
3500
3501 This is the "loads a public key file" option.  This option takes a
3502 string argument.  This can be either a file or a PKCS #11 URL
3503
3504 load-request option
3505 ...................
3506
3507 This is the "loads a certificate request file" option.  This option
3508 takes a string argument.  This option can be used with a file
3509
3510 load-certificate option
3511 .......................
3512
3513 This is the "loads a certificate file" option.  This option takes a
3514 string argument.  This option can be used with a file
3515
3516 load-ca-privkey option
3517 ......................
3518
3519 This is the "loads the certificate authority's private key file" option.
3520 This option takes a string argument.  This can be either a file or a
3521 PKCS #11 URL
3522
3523 load-ca-certificate option
3524 ..........................
3525
3526 This is the "loads the certificate authority's certificate file" option.
3527 This option takes a string argument.  This option can be used with a
3528 file
3529
3530 password option
3531 ...............
3532
3533 This is the "password to use" option.  This option takes a string
3534 argument.  You can use this option to specify the password in the
3535 command line instead of reading it from the tty.  Note, that the command
3536 line arguments are available for view in others in the system.
3537 Specifying password as " is the same as specifying no password.
3538
3539 null-password option
3540 ....................
3541
3542 This is the "enforce a null password" option.  This option enforces a
3543 NULL password.  This is different than the empty or no password in
3544 schemas like PKCS #8.
3545
3546 empty-password option
3547 .....................
3548
3549 This is the "enforce an empty password" option.  This option enforces an
3550 empty password.  This is different than the NULL or no password in
3551 schemas like PKCS #8.
3552
3553 cprint option
3554 .............
3555
3556 This is the "in certain operations it prints the information in
3557 c-friendly format" option.  In certain operations it prints the
3558 information in C-friendly format, suitable for including into C
3559 programs.
3560
3561 p12-name option
3562 ...............
3563
3564 This is the "the pkcs #12 friendly name to use" option.  This option
3565 takes a string argument.  The name to be used for the primary
3566 certificate and private key in a PKCS #12 file.
3567
3568 pubkey-info option
3569 ..................
3570
3571 This is the "print information on a public key" option.  The option
3572 combined with -load-request, -load-pubkey, -load-privkey and
3573 -load-certificate will extract the public key of the object in question.
3574
3575 to-p12 option
3576 .............
3577
3578 This is the "generate a pkcs #12 structure" option.
3579
3580 This option has some usage constraints.  It:
3581    * must appear in combination with the following options:
3582      load-certificate.
3583
3584 It requires a certificate, a private key and possibly a CA certificate
3585 to be specified.
3586
3587 rsa option
3588 ..........
3589
3590 This is the "generate rsa key" option.  When combined with
3591 -generate-privkey generates an RSA private key.
3592
3593 dsa option
3594 ..........
3595
3596 This is the "generate dsa key" option.  When combined with
3597 -generate-privkey generates a DSA private key.
3598
3599 ecc option
3600 ..........
3601
3602 This is the "generate ecc (ecdsa) key" option.  When combined with
3603 -generate-privkey generates an elliptic curve private key to be used
3604 with ECDSA.
3605
3606 ecdsa option
3607 ............
3608
3609 This is an alias for the 'ecc' option, *note the ecc option
3610 documentation: certtool ecc.
3611
3612 hash option
3613 ...........
3614
3615 This is the "hash algorithm to use for signing" option.  This option
3616 takes a string argument.  Available hash functions are SHA1, RMD160,
3617 SHA256, SHA384, SHA512.
3618
3619 inder option
3620 ............
3621
3622 This is the "use der format for input certificates, private keys, and dh
3623 parameters " option.
3624
3625 This option has some usage constraints.  It:
3626    * can be disabled with -no-inder.
3627
3628 The input files will be assumed to be in DER or RAW format.  Unlike
3629 options that in PEM input would allow multiple input data (e.g.
3630 multiple certificates), when reading in DER format a single data
3631 structure is read.
3632
3633 inraw option
3634 ............
3635
3636 This is an alias for the 'inder' option, *note the inder option
3637 documentation: certtool inder.
3638
3639 outder option
3640 .............
3641
3642 This is the "use der format for output certificates, private keys, and
3643 dh parameters" option.
3644
3645 This option has some usage constraints.  It:
3646    * can be disabled with -no-outder.
3647
3648 The output will be in DER or RAW format.
3649
3650 outraw option
3651 .............
3652
3653 This is an alias for the 'outder' option, *note the outder option
3654 documentation: certtool outder.
3655
3656 curve option
3657 ............
3658
3659 This is the "specify the curve used for ec key generation" option.  This
3660 option takes a string argument.  Supported values are secp192r1,
3661 secp224r1, secp256r1, secp384r1 and secp521r1.
3662
3663 sec-param option
3664 ................
3665
3666 This is the "specify the security level [low, legacy, medium, high,
3667 ultra]" option.  This option takes a string argument 'Security
3668 parameter'.  This is alternative to the bits option.
3669
3670 ask-pass option
3671 ...............
3672
3673 This is the "enable interaction for entering password when in batch
3674 mode."  option.  This option will enable interaction to enter password
3675 when in batch mode.  That is useful when the template option has been
3676 specified.
3677
3678 pkcs-cipher option
3679 ..................
3680
3681 This is the "cipher to use for pkcs #8 and #12 operations" option.  This
3682 option takes a string argument 'Cipher'.  Cipher may be one of 3des,
3683 3des-pkcs12, aes-128, aes-192, aes-256, rc2-40, arcfour.
3684
3685 provider option
3686 ...............
3687
3688 This is the "specify the pkcs #11 provider library" option.  This option
3689 takes a string argument.  This will override the default options in
3690 /etc/gnutls/pkcs11.conf
3691
3692 certtool exit status
3693 ....................
3694
3695 One of the following exit values will be returned:
3696 '0 (EXIT_SUCCESS)'
3697      Successful program execution.
3698 '1 (EXIT_FAILURE)'
3699      The operation failed or the command syntax was not valid.
3700
3701 certtool See Also
3702 .................
3703
3704 p11tool (1)
3705
3706 certtool Examples
3707 .................
3708
3709 Generating private keys
3710 .......................
3711
3712 To create an RSA private key, run:
3713      $ certtool --generate-privkey --outfile key.pem --rsa
3714
3715 To create a DSA or elliptic curves (ECDSA) private key use the above
3716 command combined with 'dsa' or 'ecc' options.
3717
3718 Generating certificate requests
3719 ...............................
3720
3721 To create a certificate request (needed when the certificate is issued
3722 by another party), run:
3723      certtool --generate-request --load-privkey key.pem \
3724         --outfile request.pem
3725
3726 If the private key is stored in a smart card you can generate a request
3727 by specifying the private key object URL.
3728      $ ./certtool --generate-request --load-privkey "pkcs11:..." \
3729        --load-pubkey "pkcs11:..." --outfile request.pem
3730
3731 Generating a self-signed certificate
3732 ....................................
3733
3734 To create a self signed certificate, use the command:
3735      $ certtool --generate-privkey --outfile ca-key.pem
3736      $ certtool --generate-self-signed --load-privkey ca-key.pem \
3737         --outfile ca-cert.pem
3738
3739 Note that a self-signed certificate usually belongs to a certificate
3740 authority, that signs other certificates.
3741
3742 Generating a certificate
3743 ........................
3744
3745 To generate a certificate using the previous request, use the command:
3746      $ certtool --generate-certificate --load-request request.pem \
3747         --outfile cert.pem --load-ca-certificate ca-cert.pem \
3748         --load-ca-privkey ca-key.pem
3749
3750 To generate a certificate using the private key only, use the command:
3751      $ certtool --generate-certificate --load-privkey key.pem \
3752         --outfile cert.pem --load-ca-certificate ca-cert.pem \
3753         --load-ca-privkey ca-key.pem
3754
3755 Certificate information
3756 .......................
3757
3758 To view the certificate information, use:
3759      $ certtool --certificate-info --infile cert.pem
3760
3761 PKCS #12 structure generation
3762 .............................
3763
3764 To generate a PKCS #12 structure using the previous key and certificate,
3765 use the command:
3766      $ certtool --load-certificate cert.pem --load-privkey key.pem \
3767         --to-p12 --outder --outfile key.p12
3768
3769 Some tools (reportedly web browsers) have problems with that file
3770 because it does not contain the CA certificate for the certificate.  To
3771 work around that problem in the tool, you can use the
3772 -load-ca-certificate parameter as follows:
3773
3774      $ certtool --load-ca-certificate ca.pem \
3775        --load-certificate cert.pem --load-privkey key.pem \
3776        --to-p12 --outder --outfile key.p12
3777
3778 Diffie-Hellman parameter generation
3779 ...................................
3780
3781 To generate parameters for Diffie-Hellman key exchange, use the command:
3782      $ certtool --generate-dh-params --outfile dh.pem --sec-param medium
3783
3784 Proxy certificate generation
3785 ............................
3786
3787 Proxy certificate can be used to delegate your credential to a
3788 temporary, typically short-lived, certificate.  To create one from the
3789 previously created certificate, first create a temporary key and then
3790 generate a proxy certificate for it, using the commands:
3791
3792      $ certtool --generate-privkey > proxy-key.pem
3793      $ certtool --generate-proxy --load-ca-privkey key.pem \
3794        --load-privkey proxy-key.pem --load-certificate cert.pem \
3795        --outfile proxy-cert.pem
3796
3797 Certificate revocation list generation
3798 ......................................
3799
3800 To create an empty Certificate Revocation List (CRL) do:
3801
3802      $ certtool --generate-crl --load-ca-privkey x509-ca-key.pem \
3803                 --load-ca-certificate x509-ca.pem
3804
3805 To create a CRL that contains some revoked certificates, place the
3806 certificates in a file and use '--load-certificate' as follows:
3807
3808      $ certtool --generate-crl --load-ca-privkey x509-ca-key.pem \
3809        --load-ca-certificate x509-ca.pem --load-certificate revoked-certs.pem
3810
3811 To verify a Certificate Revocation List (CRL) do:
3812
3813      $ certtool --verify-crl --load-ca-certificate x509-ca.pem < crl.pem
3814
3815 certtool Files
3816 ..............
3817
3818 Certtool's template file format
3819 ...............................
3820
3821 A template file can be used to avoid the interactive questions of
3822 certtool.  Initially create a file named 'cert.cfg' that contains the
3823 information about the certificate.  The template can be used as below:
3824
3825      $ certtool --generate-certificate --load-privkey key.pem  \
3826         --template cert.cfg --outfile cert.pem \
3827         --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem
3828
3829 An example certtool template file that can be used to generate a
3830 certificate request or a self signed certificate follows.
3831
3832      # X.509 Certificate options
3833      #
3834      # DN options
3835
3836      # The organization of the subject.
3837      organization = "Koko inc."
3838
3839      # The organizational unit of the subject.
3840      unit = "sleeping dept."
3841
3842      # The locality of the subject.
3843      # locality =
3844
3845      # The state of the certificate owner.
3846      state = "Attiki"
3847
3848      # The country of the subject. Two letter code.
3849      country = GR
3850
3851      # The common name of the certificate owner.
3852      cn = "Cindy Lauper"
3853
3854      # A user id of the certificate owner.
3855      #uid = "clauper"
3856
3857      # Set domain components
3858      #dc = "name"
3859      #dc = "domain"
3860
3861      # If the supported DN OIDs are not adequate you can set
3862      # any OID here.
3863      # For example set the X.520 Title and the X.520 Pseudonym
3864      # by using OID and string pairs.
3865      #dn_oid = 2.5.4.12 Dr.
3866      #dn_oid = 2.5.4.65 jackal
3867
3868      # This is deprecated and should not be used in new
3869      # certificates.
3870      # pkcs9_email = "none@none.org"
3871
3872      # An alternative way to set the certificate's distinguished name directly
3873      # is with the "dn" option. The attribute names allowed are:
3874      # C (country), street, O (organization), OU (unit), title, CN (common name),
3875      # L (locality), ST (state), placeOfBirth, gender, countryOfCitizenship,
3876      # countryOfResidence, serialNumber, telephoneNumber, surName, initials,
3877      # generationQualifier, givenName, pseudonym, dnQualifier, postalCode, name,
3878      # businessCategory, DC, UID, jurisdictionOfIncorporationLocalityName,
3879      # jurisdictionOfIncorporationStateOrProvinceName,
3880      # jurisdictionOfIncorporationCountryName, XmppAddr, and numeric OIDs.
3881
3882      #dn = "cn=Nik,st=Attiki,C=GR,surName=Mavrogiannopoulos,2.5.4.9=Arkadias"
3883
3884      # The serial number of the certificate
3885      # Comment the field for a time-based serial number.
3886      serial = 007
3887
3888      # In how many days, counting from today, this certificate will expire.
3889      # Use -1 if there is no expiration date.
3890      expiration_days = 700
3891
3892      # Alternatively you may set concrete dates and time. The GNU date string
3893      # formats are accepted. See:
3894      # http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html
3895
3896      #activation_date = "2004-02-29 16:21:42"
3897      #expiration_date = "2025-02-29 16:24:41"
3898
3899      # X.509 v3 extensions
3900
3901      # A dnsname in case of a WWW server.
3902      #dns_name = "www.none.org"
3903      #dns_name = "www.morethanone.org"
3904
3905      # A subject alternative name URI
3906      #uri = "http://www.example.com"
3907
3908      # An IP address in case of a server.
3909      #ip_address = "192.168.1.1"
3910
3911      # An email in case of a person
3912      email = "none@none.org"
3913
3914      # Challenge password used in certificate requests
3915      challenge_password = 123456
3916
3917      # Password when encrypting a private key
3918      #password = secret
3919
3920      # An URL that has CRLs (certificate revocation lists)
3921      # available. Needed in CA certificates.
3922      #crl_dist_points = "http://www.getcrl.crl/getcrl/"
3923
3924      # Whether this is a CA certificate or not
3925      #ca
3926
3927      # Subject Unique ID (in hex)
3928      #subject_unique_id = 00153224
3929
3930      # Issuer Unique ID (in hex)
3931      #issuer_unique_id = 00153225
3932
3933      # for microsoft smart card logon
3934      # key_purpose_oid = 1.3.6.1.4.1.311.20.2.2
3935
3936      ### Other predefined key purpose OIDs
3937
3938      # Whether this certificate will be used for a TLS client
3939      #tls_www_client
3940
3941      # Whether this certificate will be used for a TLS server
3942      #tls_www_server
3943
3944      # Whether this certificate will be used to sign data (needed
3945      # in TLS DHE ciphersuites).
3946      signing_key
3947
3948      # Whether this certificate will be used to encrypt data (needed
3949      # in TLS RSA ciphersuites). Note that it is preferred to use different
3950      # keys for encryption and signing.
3951      encryption_key
3952
3953      # Whether this key will be used to sign other certificates.
3954      #cert_signing_key
3955
3956      # Whether this key will be used to sign CRLs.
3957      #crl_signing_key
3958
3959      # Whether this key will be used to sign code.
3960      #code_signing_key
3961
3962      # Whether this key will be used to sign OCSP data.
3963      #ocsp_signing_key
3964
3965      # Whether this key will be used for time stamping.
3966      #time_stamping_key
3967
3968      # Whether this key will be used for IPsec IKE operations.
3969      #ipsec_ike_key
3970
3971      ### end of key purpose OIDs
3972
3973      # When generating a certificate from a certificate
3974      # request, then honor the extensions stored in the request
3975      # and store them in the real certificate.
3976      #honor_crq_extensions
3977
3978      # Path length contraint. Sets the maximum number of
3979      # certificates that can be used to certify this certificate.
3980      # (i.e. the certificate chain length)
3981      #path_len = -1
3982      #path_len = 2
3983
3984      # OCSP URI
3985      # ocsp_uri = http://my.ocsp.server/ocsp
3986
3987      # CA issuers URI
3988      # ca_issuers_uri = http://my.ca.issuer
3989
3990      # Certificate policies
3991      #policy1 = 1.3.6.1.4.1.5484.1.10.99.1.0
3992      #policy1_txt = "This is a long policy to summarize"
3993      #policy1_url = http://www.example.com/a-policy-to-read
3994
3995      #policy2 = 1.3.6.1.4.1.5484.1.10.99.1.1
3996      #policy2_txt = "This is a short policy"
3997      #policy2_url = http://www.example.com/another-policy-to-read
3998
3999      # Name constraints
4000
4001      # DNS
4002      #nc_permit_dns = example.com
4003      #nc_exclude_dns = test.example.com
4004
4005      # EMAIL
4006      #nc_permit_email = "nmav@ex.net"
4007
4008      # Exclude subdomains of example.com
4009      #nc_exclude_email = .example.com
4010
4011      # Exclude all e-mail addresses of example.com
4012      #nc_exclude_email = example.com
4013
4014
4015      # Options for proxy certificates
4016      #proxy_policy_language = 1.3.6.1.5.5.7.21.1
4017
4018
4019      # Options for generating a CRL
4020
4021      # The number of days the next CRL update will be due.
4022      # next CRL update will be in 43 days
4023      #crl_next_update = 43
4024
4025      # this is the 5th CRL by this CA
4026      # Comment the field for a time-based number.
4027      #crl_number = 5
4028
4029
4030 \1f
4031 File: gnutls.info,  Node: ocsptool Invocation,  Next: danetool Invocation,  Prev: certtool Invocation,  Up: More on certificate authentication
4032
4033 4.2.6 Invoking ocsptool
4034 -----------------------
4035
4036 Ocsptool is a program that can parse and print information about OCSP
4037 requests/responses, generate requests and verify responses.
4038
4039 This section was generated by *AutoGen*, using the 'agtexi-cmd' template
4040 and the option descriptions for the 'ocsptool' program.  This software
4041 is released under the GNU General Public License, version 3 or later.
4042
4043 ocsptool help/usage ('--help')
4044 ..............................
4045
4046 This is the automatically generated usage text for ocsptool.
4047
4048 The text printed is the same whether selected with the 'help' option
4049 ('--help') or the 'more-help' option ('--more-help').  'more-help' will
4050 print the usage text by passing it through a pager program.  'more-help'
4051 is disabled on platforms without a working 'fork(2)' function.  The
4052 'PAGER' environment variable is used to select the program, defaulting
4053 to 'more'.  Both will exit with a status code of 0.
4054
4055      ocsptool - GnuTLS OCSP tool
4056      Usage:  ocsptool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...
4057
4058         -d, --debug=num            Enable debugging
4059                                      - it must be in the range:
4060                                        0 to 9999
4061         -V, --verbose              More verbose output
4062                                      - may appear multiple times
4063             --infile=file          Input file
4064                                      - file must pre-exist
4065             --outfile=str          Output file
4066             --ask[=arg]            Ask an OCSP/HTTP server on a certificate validity
4067                                      - requires these options:
4068                                      load-cert
4069                                      load-issuer
4070         -e, --verify-response      Verify response
4071         -i, --request-info         Print information on a OCSP request
4072         -j, --response-info        Print information on a OCSP response
4073         -q, --generate-request     Generate an OCSP request
4074             --nonce                Use (or not) a nonce to OCSP request
4075                                      - disabled as '--no-nonce'
4076             --load-issuer=file     Read issuer certificate from file
4077                                      - file must pre-exist
4078             --load-cert=file       Read certificate to check from file
4079                                      - file must pre-exist
4080             --load-trust=file      Read OCSP trust anchors from file
4081                                      - prohibits the option 'load-signer'
4082                                      - file must pre-exist
4083             --load-signer=file     Read OCSP response signer from file
4084                                      - prohibits the option 'load-trust'
4085                                      - file must pre-exist
4086             --inder                Use DER format for input certificates and private keys
4087                                      - disabled as '--no-inder'
4088         -Q, --load-request=file    Read DER encoded OCSP request from file
4089                                      - file must pre-exist
4090         -S, --load-response=file   Read DER encoded OCSP response from file
4091                                      - file must pre-exist
4092         -v, --version[=arg]        output version information and exit
4093         -h, --help                 display extended usage information and exit
4094         -!, --more-help            extended usage information passed thru pager
4095
4096      Options are specified by doubled hyphens and their name or by a single
4097      hyphen and the flag character.
4098
4099      Ocsptool is a program that can parse and print information about OCSP
4100      requests/responses, generate requests and verify responses.
4101
4102
4103 debug option (-d)
4104 .................
4105
4106 This is the "enable debugging" option.  This option takes a number
4107 argument.  Specifies the debug level.
4108
4109 ask option
4110 ..........
4111
4112 This is the "ask an ocsp/http server on a certificate validity" option.
4113 This option takes an optional string argument 'server name|url'.
4114
4115 This option has some usage constraints.  It:
4116    * must appear in combination with the following options: load-cert,
4117      load-issuer.
4118
4119 Connects to the specified HTTP OCSP server and queries on the validity
4120 of the loaded certificate.
4121
4122 ocsptool exit status
4123 ....................
4124
4125 One of the following exit values will be returned:
4126 '0 (EXIT_SUCCESS)'
4127      Successful program execution.
4128 '1 (EXIT_FAILURE)'
4129      The operation failed or the command syntax was not valid.
4130
4131 ocsptool See Also
4132 .................
4133
4134 certtool (1)
4135
4136 ocsptool Examples
4137 .................
4138
4139 Print information about an OCSP request
4140 .......................................
4141
4142 To parse an OCSP request and print information about the content, the
4143 '-i' or '--request-info' parameter may be used as follows.  The '-Q'
4144 parameter specify the name of the file containing the OCSP request, and
4145 it should contain the OCSP request in binary DER format.
4146
4147      $ ocsptool -i -Q ocsp-request.der
4148
4149 The input file may also be sent to standard input like this:
4150
4151      $ cat ocsp-request.der | ocsptool --request-info
4152
4153 Print information about an OCSP response
4154 ........................................
4155
4156 Similar to parsing OCSP requests, OCSP responses can be parsed using the
4157 '-j' or '--response-info' as follows.
4158
4159      $ ocsptool -j -Q ocsp-response.der
4160      $ cat ocsp-response.der | ocsptool --response-info
4161
4162 Generate an OCSP request
4163 ........................
4164
4165 The '-q' or '--generate-request' parameters are used to generate an OCSP
4166 request.  By default the OCSP request is written to standard output in
4167 binary DER format, but can be stored in a file using '--outfile'.  To
4168 generate an OCSP request the issuer of the certificate to check needs to
4169 be specified with '--load-issuer' and the certificate to check with
4170 '--load-cert'.  By default PEM format is used for these files, although
4171 '--inder' can be used to specify that the input files are in DER format.
4172
4173      $ ocsptool -q --load-issuer issuer.pem --load-cert client.pem \
4174                 --outfile ocsp-request.der
4175
4176 When generating OCSP requests, the tool will add an OCSP extension
4177 containing a nonce.  This behaviour can be disabled by specifying
4178 '--no-nonce'.
4179
4180 Verify signature in OCSP response
4181 .................................
4182
4183 To verify the signature in an OCSP response the '-e' or
4184 '--verify-response' parameter is used.  The tool will read an OCSP
4185 response in DER format from standard input, or from the file specified
4186 by '--load-response'.  The OCSP response is verified against a set of
4187 trust anchors, which are specified using '--load-trust'.  The trust
4188 anchors are concatenated certificates in PEM format.  The certificate
4189 that signed the OCSP response needs to be in the set of trust anchors,
4190 or the issuer of the signer certificate needs to be in the set of trust
4191 anchors and the OCSP Extended Key Usage bit has to be asserted in the
4192 signer certificate.
4193
4194      $ ocsptool -e --load-trust issuer.pem \
4195                 --load-response ocsp-response.der
4196
4197 The tool will print status of verification.
4198
4199 Verify signature in OCSP response against given certificate
4200 ...........................................................
4201
4202 It is possible to override the normal trust logic if you know that a
4203 certain certificate is supposed to have signed the OCSP response, and
4204 you want to use it to check the signature.  This is achieved using
4205 '--load-signer' instead of '--load-trust'.  This will load one
4206 certificate and it will be used to verify the signature in the OCSP
4207 response.  It will not check the Extended Key Usage bit.
4208
4209      $ ocsptool -e --load-signer ocsp-signer.pem \
4210                 --load-response ocsp-response.der
4211
4212 This approach is normally only relevant in two situations.  The first is
4213 when the OCSP response does not contain a copy of the signer
4214 certificate, so the '--load-trust' code would fail.  The second is if
4215 you want to avoid the indirect mode where the OCSP response signer
4216 certificate is signed by a trust anchor.
4217
4218 Real-world example
4219 ..................
4220
4221 Here is an example of how to generate an OCSP request for a certificate
4222 and to verify the response.  For illustration we'll use the
4223 'blog.josefsson.org' host, which (as of writing) uses a certificate from
4224 CACert.  First we'll use 'gnutls-cli' to get a copy of the server
4225 certificate chain.  The server is not required to send this information,
4226 but this particular one is configured to do so.
4227
4228      $ echo | gnutls-cli -p 443 blog.josefsson.org --print-cert > chain.pem
4229
4230 Use a text editor on 'chain.pem' to create three files for each separate
4231 certificates, called 'cert.pem' for the first certificate for the domain
4232 itself, secondly 'issuer.pem' for the intermediate certificate and
4233 'root.pem' for the final root certificate.
4234
4235 The domain certificate normally contains a pointer to where the OCSP
4236 responder is located, in the Authority Information Access Information
4237 extension.  For example, from 'certtool -i < cert.pem' there is this
4238 information:
4239
4240      Authority Information Access Information (not critical):
4241      Access Method: 1.3.6.1.5.5.7.48.1 (id-ad-ocsp)
4242      Access Location URI: http://ocsp.CAcert.org/
4243
4244 This means the CA support OCSP queries over HTTP. We are now ready to
4245 create a OCSP request for the certificate.
4246
4247      $ ocsptool --ask ocsp.CAcert.org --load-issuer issuer.pem \
4248                 --load-cert cert.pem --outfile ocsp-response.der
4249
4250 The request is sent via HTTP to the OCSP server address specified.  If
4251 the address is ommited ocsptool will use the address stored in the
4252 certificate.
4253
4254 \1f
4255 File: gnutls.info,  Node: danetool Invocation,  Prev: ocsptool Invocation,  Up: More on certificate authentication
4256
4257 4.2.7 Invoking danetool
4258 -----------------------
4259
4260 Tool to generate and check DNS resource records for the DANE protocol.
4261
4262 This section was generated by *AutoGen*, using the 'agtexi-cmd' template
4263 and the option descriptions for the 'danetool' program.  This software
4264 is released under the GNU General Public License, version 3 or later.
4265
4266 danetool help/usage ('--help')
4267 ..............................
4268
4269 This is the automatically generated usage text for danetool.
4270
4271 The text printed is the same whether selected with the 'help' option
4272 ('--help') or the 'more-help' option ('--more-help').  'more-help' will
4273 print the usage text by passing it through a pager program.  'more-help'
4274 is disabled on platforms without a working 'fork(2)' function.  The
4275 'PAGER' environment variable is used to select the program, defaulting
4276 to 'more'.  Both will exit with a status code of 0.
4277
4278      danetool is unavailable - no --help
4279
4280 debug option (-d)
4281 .................
4282
4283 This is the "enable debugging" option.  This option takes a number
4284 argument.  Specifies the debug level.
4285
4286 load-pubkey option
4287 ..................
4288
4289 This is the "loads a public key file" option.  This option takes a
4290 string argument.  This can be either a file or a PKCS #11 URL
4291
4292 load-certificate option
4293 .......................
4294
4295 This is the "loads a certificate file" option.  This option takes a
4296 string argument.  This can be either a file or a PKCS #11 URL
4297
4298 dlv option
4299 ..........
4300
4301 This is the "sets a dlv file" option.  This option takes a string
4302 argument.  This sets a DLV file to be used for DNSSEC verification.
4303
4304 hash option
4305 ...........
4306
4307 This is the "hash algorithm to use for signing" option.  This option
4308 takes a string argument.  Available hash functions are SHA1, RMD160,
4309 SHA256, SHA384, SHA512.
4310
4311 check option
4312 ............
4313
4314 This is the "check a host's dane tlsa entry" option.  This option takes
4315 a string argument.  Obtains the DANE TLSA entry from the given hostname
4316 and prints information.  Note that the actual certificate of the host
4317 can be provided using -load-certificate, otherwise danetool will connect
4318 to the server to obtain it.  The exit code on verification success will
4319 be zero.
4320
4321 check-ee option
4322 ...............
4323
4324 This is the "check only the end-entity's certificate" option.  Checks
4325 the end-entity's certificate only.  Trust anchors or CAs are not
4326 considered.
4327
4328 check-ca option
4329 ...............
4330
4331 This is the "check only the ca's certificate" option.  Checks the trust
4332 anchor's and CA's certificate only.  End-entities are not considered.
4333
4334 tlsa-rr option
4335 ..............
4336
4337 This is the "print the dane rr data on a certificate or public key"
4338 option.
4339
4340 This option has some usage constraints.  It:
4341    * must appear in combination with the following options: host.
4342
4343 This command prints the DANE RR data needed to enable DANE on a DNS
4344 server.
4345
4346 host option
4347 ...........
4348
4349 This is the "specify the hostname to be used in the dane rr" option.
4350 This option takes a string argument 'Hostname'.  This command sets the
4351 hostname for the DANE RR.
4352
4353 proto option
4354 ............
4355
4356 This is the "the protocol set for dane data (tcp, udp etc.)"  option.
4357 This option takes a string argument 'Protocol'.  This command specifies
4358 the protocol for the service set in the DANE data.
4359
4360 app-proto option
4361 ................
4362
4363 This is the "the application protocol to be used to obtain the server's
4364 certificate (https, ftp, smtp, imap)" option.  This option takes a
4365 string argument.  When the server's certificate isn't provided danetool
4366 will connect to the server to obtain the certificate.  In that case it
4367 is required to known the protocol to talk with the server prior to
4368 initiating the TLS handshake.
4369
4370 ca option
4371 .........
4372
4373 This is the "whether the provided certificate or public key is a
4374 certificate authority" option.  Marks the DANE RR as a CA certificate if
4375 specified.
4376
4377 x509 option
4378 ...........
4379
4380 This is the "use the hash of the x.509 certificate, rather than the
4381 public key" option.  This option forces the generated record to contain
4382 the hash of the full X.509 certificate.  By default only the hash of the
4383 public key is used.
4384
4385 local option
4386 ............
4387
4388 This is an alias for the 'domain' option, *note the domain option
4389 documentation: danetool domain.
4390
4391 domain option
4392 .............
4393
4394 This is the "the provided certificate or public key is issued by the
4395 local domain" option.
4396
4397 This option has some usage constraints.  It:
4398    * can be disabled with -no-domain.
4399    * It is enabled by default.
4400
4401 DANE distinguishes certificates and public keys offered via the DNSSEC
4402 to trusted and local entities.  This flag indicates that this is a
4403 domain-issued certificate, meaning that there could be no CA involved.
4404
4405 local-dns option
4406 ................
4407
4408 This is the "use the local dns server for dnssec resolving" option.
4409
4410 This option has some usage constraints.  It:
4411    * can be disabled with -no-local-dns.
4412
4413 This option will use the local DNS server for DNSSEC. This is disabled
4414 by default due to many servers not allowing DNSSEC.
4415
4416 insecure option
4417 ...............
4418
4419 This is the "do not verify any dnssec signature" option.  Ignores any
4420 DNSSEC signature verification results.
4421
4422 inder option
4423 ............
4424
4425 This is the "use der format for input certificates and private keys"
4426 option.
4427
4428 This option has some usage constraints.  It:
4429    * can be disabled with -no-inder.
4430
4431 The input files will be assumed to be in DER or RAW format.  Unlike
4432 options that in PEM input would allow multiple input data (e.g.
4433 multiple certificates), when reading in DER format a single data
4434 structure is read.
4435
4436 inraw option
4437 ............
4438
4439 This is an alias for the 'inder' option, *note the inder option
4440 documentation: danetool inder.
4441
4442 print-raw option
4443 ................
4444
4445 This is the "print the received dane data in raw format" option.
4446
4447 This option has some usage constraints.  It:
4448    * can be disabled with -no-print-raw.
4449
4450 This option will print the received DANE data.
4451
4452 quiet option
4453 ............
4454
4455 This is the "suppress several informational messages" option.  In that
4456 case on the exit code can be used as an indication of verification
4457 success
4458
4459 danetool exit status
4460 ....................
4461
4462 One of the following exit values will be returned:
4463 '0 (EXIT_SUCCESS)'
4464      Successful program execution.
4465 '1 (EXIT_FAILURE)'
4466      The operation failed or the command syntax was not valid.
4467
4468 danetool See Also
4469 .................
4470
4471 certtool (1)
4472
4473 danetool Examples
4474 .................
4475
4476 DANE TLSA RR generation
4477 .......................
4478
4479 To create a DANE TLSA resource record for a certificate (or public key)
4480 that was issued localy and may or may not be signed by a CA use the
4481 following command.
4482      $ danetool --tlsa-rr --host www.example.com --load-certificate cert.pem
4483
4484 To create a DANE TLSA resource record for a CA signed certificate, which
4485 will be marked as such use the following command.
4486      $ danetool --tlsa-rr --host www.example.com --load-certificate cert.pem \
4487        --no-domain
4488
4489 The former is useful to add in your DNS entry even if your certificate
4490 is signed by a CA. That way even users who do not trust your CA will be
4491 able to verify your certificate using DANE.
4492
4493 In order to create a record for the CA signer of your certificate use
4494 the following.
4495      $ danetool --tlsa-rr --host www.example.com --load-certificate cert.pem \
4496        --ca --no-domain
4497
4498 To read a server's DANE TLSA entry, use:
4499      $ danetool --check www.example.com --proto tcp --port 443
4500
4501 To verify a server's DANE TLSA entry, use:
4502      $ danetool --check www.example.com --proto tcp --port 443 --load-certificate chain.pem
4503
4504 \1f
4505 File: gnutls.info,  Node: Shared-key and anonymous authentication,  Next: Selecting an appropriate authentication method,  Prev: More on certificate authentication,  Up: Authentication methods
4506
4507 4.3 Shared-key and anonymous authentication
4508 ===========================================
4509
4510 In addition to certificate authentication, the TLS protocol may be used
4511 with password, shared-key and anonymous authentication methods.  The
4512 rest of this chapter discusses details of these methods.
4513
4514 * Menu:
4515
4516 * SRP authentication::
4517 * PSK authentication::
4518 * Anonymous authentication::
4519
4520 \1f
4521 File: gnutls.info,  Node: SRP authentication,  Next: PSK authentication,  Up: Shared-key and anonymous authentication
4522
4523 4.3.1 SRP authentication
4524 ------------------------
4525
4526 * Menu:
4527
4528 * Authentication using SRP::
4529 * srptool Invocation::             Invoking srptool
4530
4531 \1f
4532 File: gnutls.info,  Node: Authentication using SRP,  Next: srptool Invocation,  Up: SRP authentication
4533
4534 4.3.1.1 Authentication using SRP
4535 ................................
4536
4537 GnuTLS supports authentication via the Secure Remote Password or SRP
4538 protocol (see [_RFC2945,TOMSRP_] for a description).  The SRP key
4539 exchange is an extension to the TLS protocol, and it provides an
4540 authenticated with a password key exchange.  The peers can be identified
4541 using a single password, or there can be combinations where the client
4542 is authenticated using SRP and the server using a certificate.
4543
4544 The advantage of SRP authentication, over other proposed secure password
4545 authentication schemes, is that SRP is not susceptible to off-line
4546 dictionary attacks.  Moreover, SRP does not require the server to hold
4547 the user's password.  This kind of protection is similar to the one used
4548 traditionally in the UNIX '/etc/passwd' file, where the contents of this
4549 file did not cause harm to the system security if they were revealed.
4550 The SRP needs instead of the plain password something called a verifier,
4551 which is calculated using the user's password, and if stolen cannot be
4552 used to impersonate the user.
4553
4554 Typical conventions in SRP are a password file, called 'tpasswd' that
4555 holds the SRP verifiers (encoded passwords) and another file,
4556 'tpasswd.conf', which holds the allowed SRP parameters.  The included in
4557 GnuTLS helper follow those conventions.  The srptool program, discussed
4558 in the next section is a tool to manipulate the SRP parameters.
4559
4560 The implementation in GnuTLS is based on [_TLSSRP_]. The supported key
4561 exchange methods are shown below.
4562
4563 'SRP:'
4564      Authentication using the SRP protocol.
4565
4566 'SRP_DSS:'
4567      Client authentication using the SRP protocol.  Server is
4568      authenticated using a certificate with DSA parameters.
4569
4570 'SRP_RSA:'
4571      Client authentication using the SRP protocol.  Server is
4572      authenticated using a certificate with RSA parameters.
4573
4574  -- Function: int gnutls_srp_verifier (const char * USERNAME, const char
4575           * PASSWORD, const gnutls_datum_t * SALT, const gnutls_datum_t
4576           * GENERATOR, const gnutls_datum_t * PRIME, gnutls_datum_t *
4577           RES)
4578      USERNAME: is the user's name
4579
4580      PASSWORD: is the user's password
4581
4582      SALT: should be some randomly generated bytes
4583
4584      GENERATOR: is the generator of the group
4585
4586      PRIME: is the group's prime
4587
4588      RES: where the verifier will be stored.
4589
4590      This function will create an SRP verifier, as specified in RFC2945.
4591      The 'prime' and 'generator' should be one of the static parameters
4592      defined in gnutls/gnutls.h or may be generated.
4593
4594      The verifier will be allocated with 'gnutls_malloc' () and will be
4595      stored in 'res' using binary format.
4596
4597      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned, or an
4598      error code.
4599
4600 'INT *note gnutls_srp_base64_encode_alloc:: (const gnutls_datum_t * DATA, gnutls_datum_t * RESULT)'
4601 'INT *note gnutls_srp_base64_decode_alloc:: (const gnutls_datum_t * B64_DATA, gnutls_datum_t * RESULT)'
4602
4603 \1f
4604 File: gnutls.info,  Node: srptool Invocation,  Prev: Authentication using SRP,  Up: SRP authentication
4605
4606 4.3.1.2 Invoking srptool
4607 ........................
4608
4609 Simple program that emulates the programs in the Stanford SRP (Secure
4610 Remote Password) libraries using GnuTLS. It is intended for use in
4611 places where you don't expect SRP authentication to be the used for
4612 system users.
4613
4614 In brief, to use SRP you need to create two files.  These are the
4615 password file that holds the users and the verifiers associated with
4616 them and the configuration file to hold the group parameters (called
4617 tpasswd.conf).
4618
4619 This section was generated by *AutoGen*, using the 'agtexi-cmd' template
4620 and the option descriptions for the 'srptool' program.  This software is
4621 released under the GNU General Public License, version 3 or later.
4622
4623 srptool help/usage ('--help')
4624 .............................
4625
4626 This is the automatically generated usage text for srptool.
4627
4628 The text printed is the same whether selected with the 'help' option
4629 ('--help') or the 'more-help' option ('--more-help').  'more-help' will
4630 print the usage text by passing it through a pager program.  'more-help'
4631 is disabled on platforms without a working 'fork(2)' function.  The
4632 'PAGER' environment variable is used to select the program, defaulting
4633 to 'more'.  Both will exit with a status code of 0.
4634
4635      srptool - GnuTLS SRP tool
4636      Usage:  srptool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...
4637
4638         -d, --debug=num            Enable debugging
4639                                      - it must be in the range:
4640                                        0 to 9999
4641         -i, --index=num            specify the index of the group parameters in tpasswd.conf to use
4642         -u, --username=str         specify a username
4643         -p, --passwd=str           specify a password file
4644         -s, --salt=num             specify salt size
4645             --verify               just verify the password.
4646         -v, --passwd-conf=str      specify a password conf file.
4647             --create-conf=str      Generate a password configuration file.
4648         -v, --version[=arg]        output version information and exit
4649         -h, --help                 display extended usage information and exit
4650         -!, --more-help            extended usage information passed thru pager
4651
4652      Options are specified by doubled hyphens and their name or by a single
4653      hyphen and the flag character.
4654
4655      Simple program that emulates the programs in the Stanford SRP (Secure
4656      Remote Password) libraries using GnuTLS.  It is intended for use in places
4657      where you don't expect SRP authentication to be the used for system users.
4658
4659      In brief, to use SRP you need to create two files.  These are the password
4660      file that holds the users and the verifiers associated with them and the
4661      configuration file to hold the group parameters (called tpasswd.conf).
4662
4663
4664 debug option (-d)
4665 .................
4666
4667 This is the "enable debugging" option.  This option takes a number
4668 argument.  Specifies the debug level.
4669
4670 verify option
4671 .............
4672
4673 This is the "just verify the password."  option.  Verifies the password
4674 provided against the password file.
4675
4676 passwd-conf option (-v)
4677 .......................
4678
4679 This is the "specify a password conf file."  option.  This option takes
4680 a string argument.  Specify a filename or a PKCS #11 URL to read the CAs
4681 from.
4682
4683 create-conf option
4684 ..................
4685
4686 This is the "generate a password configuration file."  option.  This
4687 option takes a string argument.  This generates a password configuration
4688 file (tpasswd.conf) containing the required for TLS parameters.
4689
4690 srptool exit status
4691 ...................
4692
4693 One of the following exit values will be returned:
4694 '0 (EXIT_SUCCESS)'
4695      Successful program execution.
4696 '1 (EXIT_FAILURE)'
4697      The operation failed or the command syntax was not valid.
4698
4699 srptool See Also
4700 ................
4701
4702 gnutls-cli-debug (1), gnutls-serv (1), srptool (1), psktool (1),
4703 certtool (1)
4704
4705 srptool Examples
4706 ................
4707
4708 To create 'tpasswd.conf' which holds the g and n values for SRP protocol
4709 (generator and a large prime), run:
4710      $ srptool --create-conf /etc/tpasswd.conf
4711
4712 This command will create '/etc/tpasswd' and will add user 'test' (you
4713 will also be prompted for a password).  Verifiers are stored by default
4714 in the way libsrp expects.
4715      $ srptool --passwd /etc/tpasswd --passwd-conf /etc/tpasswd.conf -u test
4716
4717 This command will check against a password.  If the password matches the
4718 one in '/etc/tpasswd' you will get an ok.
4719      $ srptool --passwd /etc/tpasswd --passwd\-conf /etc/tpasswd.conf --verify -u test
4720
4721 \1f
4722 File: gnutls.info,  Node: PSK authentication,  Next: Anonymous authentication,  Prev: SRP authentication,  Up: Shared-key and anonymous authentication
4723
4724 4.3.2 PSK authentication
4725 ------------------------
4726
4727 * Menu:
4728
4729 * Authentication using PSK::
4730 * psktool Invocation::             Invoking psktool
4731
4732 \1f
4733 File: gnutls.info,  Node: Authentication using PSK,  Next: psktool Invocation,  Up: PSK authentication
4734
4735 4.3.2.1 Authentication using PSK
4736 ................................
4737
4738 Authentication using Pre-shared keys is a method to authenticate using
4739 usernames and binary keys.  This protocol avoids making use of public
4740 key infrastructure and expensive calculations, thus it is suitable for
4741 constraint clients.
4742
4743 The implementation in GnuTLS is based on [_TLSPSK_]. The supported PSK
4744 key exchange methods are:
4745
4746 'PSK:'
4747      Authentication using the PSK protocol.
4748
4749 'DHE-PSK:'
4750      Authentication using the PSK protocol and Diffie-Hellman key
4751      exchange.  This method offers perfect forward secrecy.
4752
4753 'ECDHE-PSK:'
4754      Authentication using the PSK protocol and Elliptic curve
4755      Diffie-Hellman key exchange.  This method offers perfect forward
4756      secrecy.
4757
4758 'RSA-PSK:'
4759      Authentication using the PSK protocol for the client and an RSA
4760      certificate for the server.
4761
4762 Helper functions to generate and maintain PSK keys are also included in
4763 GnuTLS.
4764
4765 'INT *note gnutls_key_generate:: (gnutls_datum_t * KEY, unsigned int KEY_SIZE)'
4766 'INT *note gnutls_hex_encode:: (const gnutls_datum_t * DATA, char * RESULT, size_t * RESULT_SIZE)'
4767 'INT *note gnutls_hex_decode:: (const gnutls_datum_t * HEX_DATA, void * RESULT, size_t * RESULT_SIZE)'
4768
4769 \1f
4770 File: gnutls.info,  Node: psktool Invocation,  Prev: Authentication using PSK,  Up: PSK authentication
4771
4772 4.3.2.2 Invoking psktool
4773 ........................
4774
4775 Program that generates random keys for use with TLS-PSK. The keys are
4776 stored in hexadecimal format in a key file.
4777
4778 This section was generated by *AutoGen*, using the 'agtexi-cmd' template
4779 and the option descriptions for the 'psktool' program.  This software is
4780 released under the GNU General Public License, version 3 or later.
4781
4782 psktool help/usage ('--help')
4783 .............................
4784
4785 This is the automatically generated usage text for psktool.
4786
4787 The text printed is the same whether selected with the 'help' option
4788 ('--help') or the 'more-help' option ('--more-help').  'more-help' will
4789 print the usage text by passing it through a pager program.  'more-help'
4790 is disabled on platforms without a working 'fork(2)' function.  The
4791 'PAGER' environment variable is used to select the program, defaulting
4792 to 'more'.  Both will exit with a status code of 0.
4793
4794      psktool - GnuTLS PSK tool
4795      Usage:  psktool [ -<flag> [<val>] | --<name>[{=| }<val>] ]...
4796
4797         -d, --debug=num            Enable debugging
4798                                      - it must be in the range:
4799                                        0 to 9999
4800         -s, --keysize=num          specify the key size in bytes
4801                                      - it must be in the range:
4802                                        0 to 512
4803         -u, --username=str         specify a username
4804         -p, --passwd=str           specify a password file
4805         -v, --version[=arg]        output version information and exit
4806         -h, --help                 display extended usage information and exit
4807         -!, --more-help            extended usage information passed thru pager
4808
4809      Options are specified by doubled hyphens and their name or by a single
4810      hyphen and the flag character.
4811
4812      Program that generates random keys for use with TLS-PSK.  The keys are
4813      stored in hexadecimal format in a key file.
4814
4815
4816 debug option (-d)
4817 .................
4818
4819 This is the "enable debugging" option.  This option takes a number
4820 argument.  Specifies the debug level.
4821
4822 psktool exit status
4823 ...................
4824
4825 One of the following exit values will be returned:
4826 '0 (EXIT_SUCCESS)'
4827      Successful program execution.
4828 '1 (EXIT_FAILURE)'
4829      The operation failed or the command syntax was not valid.
4830
4831 psktool See Also
4832 ................
4833
4834 gnutls-cli-debug (1), gnutls-serv (1), srptool (1), certtool (1)
4835
4836 psktool Examples
4837 ................
4838
4839 To add a user 'psk_identity' in 'passwd.psk' for use with GnuTLS run:
4840      $ ./psktool -u psk_identity -p passwd.psk
4841      Generating a random key for user 'psk_identity'
4842      Key stored to passwd.psk
4843      $ cat psks.txt
4844      psk_identity:88f3824b3e5659f52d00e959bacab954b6540344
4845      $
4846
4847 This command will create 'passwd.psk' if it does not exist and will add
4848 user 'psk_identity' (you will also be prompted for a password).
4849
4850 \1f
4851 File: gnutls.info,  Node: Anonymous authentication,  Prev: PSK authentication,  Up: Shared-key and anonymous authentication
4852
4853 4.3.3 Anonymous authentication
4854 ------------------------------
4855
4856 The anonymous key exchange offers encryption without any indication of
4857 the peer's identity.  This kind of authentication is vulnerable to a man
4858 in the middle attack, but can be used even if there is no prior
4859 communication or shared trusted parties with the peer.  It is useful to
4860 establish a session over which certificate authentication will occur in
4861 order to hide the indentities of the participants from passive
4862 eavesdroppers.
4863
4864 Unless in the above case, it is not recommended to use anonymous
4865 authentication.  In the cases where there is no prior communication with
4866 the peers, an alternative with better properties, such as key
4867 continuity, is trust on first use (see *note Verifying a certificate
4868 using trust on first use authentication::).
4869
4870 The available key exchange algorithms for anonymous authentication are
4871 shown below, but note that few public servers support them, and they
4872 have to be explicitly enabled.
4873
4874 'ANON_DH:'
4875      This algorithm exchanges Diffie-Hellman parameters.
4876
4877 'ANON_ECDH:'
4878      This algorithm exchanges elliptic curve Diffie-Hellman parameters.
4879      It is more efficient than ANON_DH on equivalent security levels.
4880
4881 \1f
4882 File: gnutls.info,  Node: Selecting an appropriate authentication method,  Prev: Shared-key and anonymous authentication,  Up: Authentication methods
4883
4884 4.4 Selecting an appropriate authentication method
4885 ==================================================
4886
4887 This section provides some guidance on how to use the available
4888 authentication methods in GnuTLS in various scenarios.
4889
4890 4.4.1 Two peers with an out-of-band channel
4891 -------------------------------------------
4892
4893 Let's consider two peers who need to communicate over an untrusted
4894 channel (the Internet), but have an out-of-band channel available.  The
4895 latter channel is considered safe from eavesdropping and message
4896 modification and thus can be used for an initial bootstrapping of the
4897 protocol.  The options available are:
4898    * Pre-shared keys (see *note PSK authentication::).  The server and a
4899      client communicate a shared randomly generated key over the trusted
4900      channel and use it to negotiate further sessions over the untrusted
4901      channel.
4902
4903    * Passwords (see *note SRP authentication::).  The client
4904      communicates to the server its username and password of choice and
4905      uses it to negotiate further sessions over the untrusted channel.
4906
4907    * Public keys (see *note Certificate authentication::).  The client
4908      and the server exchange their public keys (or fingerprints of them)
4909      over the trusted channel.  On future sessions over the untrusted
4910      channel they verify the key being the same (similar to *note
4911      Verifying a certificate using trust on first use authentication::).
4912
4913 Provided that the out-of-band channel is trusted all of the above
4914 provide a similar level of protection.  An out-of-band channel may be
4915 the initial bootstrapping of a user's PC in a corporate environment,
4916 in-person communication, communication over an alternative network (e.g.
4917 the phone network), etc.
4918
4919 4.4.2 Two peers without an out-of-band channel
4920 ----------------------------------------------
4921
4922 When an out-of-band channel is not available a peer cannot be reliably
4923 authenticated.  What can be done, however, is to allow some form of
4924 registration of users connecting for the first time and ensure that
4925 their keys remain the same after that initial connection.  This is
4926 termed key continuity or trust on first use (TOFU).
4927
4928 The available option is to use public key authentication (see *note
4929 Certificate authentication::).  The client and the server store each
4930 other's public keys (or fingerprints of them) and associate them with
4931 their identity.  On future sessions over the untrusted channel they
4932 verify the keys being the same (see *note Verifying a certificate using
4933 trust on first use authentication::).
4934
4935 To mitigate the uncertainty of the information exchanged in the first
4936 connection other channels over the Internet may be used, e.g., DNSSEC
4937 (see *note Verifying a certificate using DANE::).
4938
4939 4.4.3 Two peers and a trusted third party
4940 -----------------------------------------
4941
4942 When a trusted third party is available (or a certificate authority) the
4943 most suitable option is to use certificate authentication (see *note
4944 Certificate authentication::).  The client and the server obtain
4945 certificates that associate their identity and public keys using a
4946 digital signature by the trusted party and use them to on the subsequent
4947 communications with each other.  Each party verifies the peer's
4948 certificate using the trusted third party's signature.  The parameters
4949 of the third party's signature are present in its certificate which must
4950 be available to all communicating parties.
4951
4952 While the above is the typical authentication method for servers in the
4953 Internet by using the commercial CAs, the users that act as clients in
4954 the protocol rarely possess such certificates.  In that case a hybrid
4955 method can be used where the server is authenticated by the client using
4956 the commercial CAs and the client is authenticated based on some
4957 information the client provided over the initial server-authenticated
4958 channel.  The available options are:
4959    * Passwords (see *note SRP authentication::).  The client
4960      communicates to the server its username and password of choice on
4961      the initial server-authenticated connection and uses it to
4962      negotiate further sessions.  This is possible because the SRP
4963      protocol allows for the server to be authenticated using a
4964      certificate and the client using the password.
4965
4966    * Public keys (see *note Certificate authentication::).  The client
4967      sends its public key to the server (or a fingerprint of it) over
4968      the initial server-authenticated connection.  On future sessions
4969      the client verifies the server using the third party certificate
4970      and the server verifies that the client's public key remained the
4971      same (see *note Verifying a certificate using trust on first use
4972      authentication::).
4973
4974 \1f
4975 File: gnutls.info,  Node: Hardware security modules and abstract key types,  Next: How to use GnuTLS in applications,  Prev: Authentication methods,  Up: Top
4976
4977 5 Hardware security modules and abstract key types
4978 **************************************************
4979
4980 In several cases storing the long term cryptographic keys in a hard disk
4981 or even in memory poses a significant risk.  Once the system they are
4982 stored is compromised the keys must be replaced as the secrecy of future
4983 sessions is no longer guarranteed.  Moreover, past sessions that were
4984 not protected by a perfect forward secrecy offering ciphersuite are also
4985 to be assumed compromised.
4986
4987 If such threats need to be addressed, then it may be wise storing the
4988 keys in a security module such as a smart card, an HSM or the TPM chip.
4989 Those modules ensure the protection of the cryptographic keys by only
4990 allowing operations on them and preventing their extraction.  The
4991 purpose of the abstract key API is to provide an API that will allow the
4992 handle of keys in memory and files, as well as keys stored in such
4993 modules.
4994
4995 In GnuTLS the approach is to handle all keys transparently by the high
4996 level API, e.g., the API that loads a key or certificate from a file.
4997 The high-level API will accept URIs in addition to files that specify
4998 keys on an HSM or in TPM, and a callback function will be used to obtain
4999 any required keys.  The URI format is defined in [_TPMURI_] and
5000 [_PKCS11URI_], and is in the process of being standardized across
5001 systems.
5002
5003 More information on the API is provided in the next sections.  Examples
5004 of a URI of a certificate stored in an HSM, as well as a key stored in
5005 the TPM chip are shown below.  To discover the URIs of the objects the
5006 'p11tool' (see *note p11tool Invocation::), or 'tpmtool' (see *note
5007 tpmtool Invocation::) may be used.
5008
5009      pkcs11:token=Nikos;serial=307521161601031;model=PKCS%2315; \
5010      manufacturer=EnterSafe;object=test1;objecttype=cert
5011
5012      tpmkey:uuid=42309df8-d101-11e1-a89a-97bb33c23ad1;storage=user
5013
5014 * Menu:
5015
5016 * Abstract key types::
5017 * Smart cards and HSMs::
5018 * Trusted Platform Module::
5019
5020 \1f
5021 File: gnutls.info,  Node: Abstract key types,  Next: Smart cards and HSMs,  Up: Hardware security modules and abstract key types
5022
5023 5.1 Abstract key types
5024 ======================
5025
5026 Since there are many forms of a public or private keys supported by
5027 GnuTLS such as X.509, OpenPGP, PKCS #11 or TPM it is desirable to allow
5028 common operations on them.  For these reasons the abstract
5029 'gnutls_privkey_t' and 'gnutls_pubkey_t' were introduced in
5030 'gnutls/abstract.h' header.  Those types are initialized using a
5031 specific type of key and then can be used to perform operations in an
5032 abstract way.  For example in order to sign an X.509 certificate with a
5033 key that resides in a token the following steps can be used.
5034
5035      #inlude <gnutls/abstract.h>
5036
5037      void sign_cert( gnutls_x509_crt_t to_be_signed)
5038      {
5039      gnutls_x509_crt_t ca_cert;
5040      gnutls_privkey_t abs_key;
5041
5042        /* initialize the abstract key */
5043        gnutls_privkey_init(&abs_key);
5044
5045        /* keys stored in tokens are identified by URLs */
5046        gnutls_privkey_import_url(abs_key, key_url);
5047
5048        gnutls_x509_crt_init(&ca_cert);
5049        gnutls_x509_crt_import_pkcs11_url(&ca_cert, cert_url);
5050
5051        /* sign the certificate to be signed */
5052        gnutls_x509_crt_privkey_sign(to_be_signed, ca_cert, abs_key,
5053                                     GNUTLS_DIG_SHA256, 0);
5054      }
5055
5056 * Menu:
5057
5058 * Abstract public keys::
5059 * Abstract private keys::
5060 * Operations::
5061
5062 \1f
5063 File: gnutls.info,  Node: Abstract public keys,  Next: Abstract private keys,  Up: Abstract key types
5064
5065 5.1.1 Public keys
5066 -----------------
5067
5068 An abstract 'gnutls_pubkey_t' can be initialized using the functions
5069 below.  It can be imported through an existing structure like
5070 'gnutls_x509_crt_t', or through an ASN.1 encoding of the X.509
5071 'SubjectPublicKeyInfo' sequence.
5072
5073 'INT *note gnutls_pubkey_import_x509:: (gnutls_pubkey_t KEY, gnutls_x509_crt_t CRT, unsigned int FLAGS)'
5074 'INT *note gnutls_pubkey_import_openpgp:: (gnutls_pubkey_t KEY, gnutls_openpgp_crt_t CRT, unsigned int FLAGS)'
5075 'INT *note gnutls_pubkey_import_pkcs11:: (gnutls_pubkey_t KEY, gnutls_pkcs11_obj_t OBJ, unsigned int FLAGS)'
5076
5077 'INT *note gnutls_pubkey_import_url:: (gnutls_pubkey_t KEY, const char * URL, unsigned int FLAGS)'
5078 'INT *note gnutls_pubkey_import_privkey:: (gnutls_pubkey_t KEY, gnutls_privkey_t PKEY, unsigned int USAGE, unsigned int FLAGS)'
5079 'INT *note gnutls_pubkey_import:: (gnutls_pubkey_t KEY, const gnutls_datum_t * DATA, gnutls_x509_crt_fmt_t FORMAT)'
5080 'INT *note gnutls_pubkey_export:: (gnutls_pubkey_t KEY, gnutls_x509_crt_fmt_t FORMAT, void * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'
5081
5082  -- Function: int gnutls_pubkey_export2 (gnutls_pubkey_t KEY,
5083           gnutls_x509_crt_fmt_t FORMAT, gnutls_datum_t * OUT)
5084      KEY: Holds the certificate
5085
5086      FORMAT: the format of output params.  One of PEM or DER.
5087
5088      OUT: will contain a certificate PEM or DER encoded
5089
5090      This function will export the public key to DER or PEM format.  The
5091      contents of the exported data is the SubjectPublicKeyInfo X.509
5092      structure.
5093
5094      The output buffer will be allocated using 'gnutls_malloc()' .
5095
5096      If the structure is PEM encoded, it will have a header of "BEGIN
5097      CERTIFICATE".
5098
5099      *Returns:* In case of failure a negative error code will be
5100      returned, and 0 on success.
5101
5102      *Since:* 3.1.3
5103
5104 Other helper functions that allow directly importing from raw X.509 or
5105 OpenPGP structures are shown below.
5106
5107 '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)'
5108 '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)'
5109
5110 An important function is *note gnutls_pubkey_import_url:: which will
5111 import public keys from URLs that identify objects stored in tokens (see
5112 *note Smart cards and HSMs:: and *note Trusted Platform Module::).  A
5113 function to check for a supported by GnuTLS URL is *note
5114 gnutls_url_is_supported::.
5115
5116  -- Function: int gnutls_url_is_supported (const char * URL)
5117      URL: A PKCS 11 url
5118
5119      Check whether url is supported.  Depending on the system libraries
5120      GnuTLS may support pkcs11 or tpmkey URLs.
5121
5122      *Returns:* return non-zero if the given URL is supported, and zero
5123      if it is not known.
5124
5125      *Since:* 3.1.0
5126
5127 Additional functions are available that will return information over a
5128 public key, such as a unique key ID, as well as a function that given a
5129 public key fingerprint would provide a memorable sketch.
5130
5131 Note that *note gnutls_pubkey_get_key_id:: calculates a SHA1 digest of
5132 the public key as a DER-formatted, subjectPublicKeyInfo object.  Other
5133 implementations use different approaches, e.g., some use the "common
5134 method" described in section 4.2.1.2 of [_RFC5280_] which calculates a
5135 digest on a part of the subjectPublicKeyInfo object.
5136
5137 'INT *note gnutls_pubkey_get_pk_algorithm:: (gnutls_pubkey_t KEY, unsigned int * BITS)'
5138 'INT *note gnutls_pubkey_get_preferred_hash_algorithm:: (gnutls_pubkey_t KEY, gnutls_digest_algorithm_t * HASH, unsigned int * MAND)'
5139 'INT *note gnutls_pubkey_get_key_id:: (gnutls_pubkey_t KEY, unsigned int FLAGS, unsigned char * OUTPUT_DATA, size_t * OUTPUT_DATA_SIZE)'
5140 '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)'
5141
5142 To export the key-specific parameters, or obtain a unique key ID the
5143 following functions are provided.
5144
5145 'INT *note gnutls_pubkey_export_rsa_raw:: (gnutls_pubkey_t KEY, gnutls_datum_t * M, gnutls_datum_t * E)'
5146 'INT *note gnutls_pubkey_export_dsa_raw:: (gnutls_pubkey_t KEY, gnutls_datum_t * P, gnutls_datum_t * Q, gnutls_datum_t * G, gnutls_datum_t * Y)'
5147 'INT *note gnutls_pubkey_export_ecc_raw:: (gnutls_pubkey_t KEY, gnutls_ecc_curve_t * CURVE, gnutls_datum_t * X, gnutls_datum_t * Y)'
5148 'INT *note gnutls_pubkey_export_ecc_x962:: (gnutls_pubkey_t KEY, gnutls_datum_t * PARAMETERS, gnutls_datum_t * ECPOINT)'
5149
5150 \1f
5151 File: gnutls.info,  Node: Abstract private keys,  Next: Operations,  Prev: Abstract public keys,  Up: Abstract key types
5152
5153 5.1.2 Private keys
5154 ------------------
5155
5156 An abstract 'gnutls_privkey_t' can be initialized using the functions
5157 below.  It can be imported through an existing structure like
5158 'gnutls_x509_privkey_t', but unlike public keys it cannot be exported.
5159 That is to allow abstraction over keys stored in hardware that makes
5160 available only operations.
5161
5162 'INT *note gnutls_privkey_import_x509:: (gnutls_privkey_t PKEY, gnutls_x509_privkey_t KEY, unsigned int FLAGS)'
5163 'INT *note gnutls_privkey_import_openpgp:: (gnutls_privkey_t PKEY, gnutls_openpgp_privkey_t KEY, unsigned int FLAGS)'
5164 'INT *note gnutls_privkey_import_pkcs11:: (gnutls_privkey_t PKEY, gnutls_pkcs11_privkey_t KEY, unsigned int FLAGS)'
5165
5166 Other helper functions that allow directly importing from raw X.509 or
5167 OpenPGP structures are shown below.  Again, as with public keys, private
5168 keys can be imported from a hardware module using URLs.
5169
5170 '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)'
5171 '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)'
5172
5173  -- Function: int gnutls_privkey_import_url (gnutls_privkey_t KEY, const
5174           char * URL, unsigned int FLAGS)
5175      KEY: A key of type 'gnutls_privkey_t'
5176
5177      URL: A PKCS 11 url
5178
5179      FLAGS: should be zero
5180
5181      This function will import a PKCS11 or TPM URL as a private key.
5182      The supported URL types can be checked using
5183      'gnutls_url_is_supported()' .
5184
5185      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5186      otherwise a negative error value.
5187
5188      *Since:* 3.1.0
5189
5190 'INT *note gnutls_privkey_get_pk_algorithm:: (gnutls_privkey_t KEY, unsigned int * BITS)'
5191 'GNUTLS_PRIVKEY_TYPE_T *note gnutls_privkey_get_type:: (gnutls_privkey_t KEY)'
5192 'INT *note gnutls_privkey_status:: (gnutls_privkey_t KEY)'
5193
5194 In order to support cryptographic operations using an external API, the
5195 following function is provided.  This allows for a simple extensibility
5196 API without resorting to PKCS #11.
5197
5198  -- Function: int gnutls_privkey_import_ext2 (gnutls_privkey_t PKEY,
5199           gnutls_pk_algorithm_t PK, void * USERDATA,
5200           gnutls_privkey_sign_func SIGN_FUNC,
5201           gnutls_privkey_decrypt_func DECRYPT_FUNC,
5202           gnutls_privkey_deinit_func DEINIT_FUNC, unsigned int FLAGS)
5203      PKEY: The private key
5204
5205      PK: The public key algorithm
5206
5207      USERDATA: private data to be provided to the callbacks
5208
5209      SIGN_FUNC: callback for signature operations
5210
5211      DECRYPT_FUNC: callback for decryption operations
5212
5213      DEINIT_FUNC: a deinitialization function
5214
5215      FLAGS: Flags for the import
5216
5217      This function will associate the given callbacks with the
5218      'gnutls_privkey_t' structure.  At least one of the two callbacks
5219      must be non-null.  If a deinitialization function is provided then
5220      flags is assumed to contain 'GNUTLS_PRIVKEY_IMPORT_AUTO_RELEASE' .
5221
5222      Note that the signing function is supposed to "raw" sign data,
5223      i.e., without any hashing or preprocessing.  In case of RSA the
5224      DigestInfo will be provided, and the signing function is expected
5225      to do the PKCS '1' 1.5 padding and the exponentiation.
5226
5227      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5228      otherwise a negative error value.
5229
5230      *Since:* 3.1
5231
5232 \1f
5233 File: gnutls.info,  Node: Operations,  Prev: Abstract private keys,  Up: Abstract key types
5234
5235 5.1.3 Operations
5236 ----------------
5237
5238 The abstract key types can be used to access signing and signature
5239 verification operations with the underlying keys.
5240
5241  -- Function: int gnutls_pubkey_verify_data2 (gnutls_pubkey_t PUBKEY,
5242           gnutls_sign_algorithm_t ALGO, unsigned int FLAGS, const
5243           gnutls_datum_t * DATA, const gnutls_datum_t * SIGNATURE)
5244      PUBKEY: Holds the public key
5245
5246      ALGO: The signature algorithm used
5247
5248      FLAGS: Zero or one of 'gnutls_pubkey_flags_t'
5249
5250      DATA: holds the signed data
5251
5252      SIGNATURE: contains the signature
5253
5254      This function will verify the given signed data, using the
5255      parameters from the certificate.
5256
5257      *Returns:* In case of a verification failure
5258      'GNUTLS_E_PK_SIG_VERIFY_FAILED' is returned, and zero or positive
5259      code on success.
5260
5261      *Since:* 3.0
5262
5263  -- Function: int gnutls_pubkey_verify_hash2 (gnutls_pubkey_t KEY,
5264           gnutls_sign_algorithm_t ALGO, unsigned int FLAGS, const
5265           gnutls_datum_t * HASH, const gnutls_datum_t * SIGNATURE)
5266      KEY: Holds the public key
5267
5268      ALGO: The signature algorithm used
5269
5270      FLAGS: Zero or one of 'gnutls_pubkey_flags_t'
5271
5272      HASH: holds the hash digest to be verified
5273
5274      SIGNATURE: contains the signature
5275
5276      This function will verify the given signed digest, using the
5277      parameters from the public key.  Note that unlike
5278      'gnutls_privkey_sign_hash()' , this function accepts a signature
5279      algorithm instead of a digest algorithm.  You can use
5280      'gnutls_pk_to_sign()' to get the appropriate value.
5281
5282      *Returns:* In case of a verification failure
5283      'GNUTLS_E_PK_SIG_VERIFY_FAILED' is returned, and zero or positive
5284      code on success.
5285
5286      *Since:* 3.0
5287
5288  -- Function: int gnutls_pubkey_encrypt_data (gnutls_pubkey_t KEY,
5289           unsigned int FLAGS, const gnutls_datum_t * PLAINTEXT,
5290           gnutls_datum_t * CIPHERTEXT)
5291      KEY: Holds the public key
5292
5293      FLAGS: should be 0 for now
5294
5295      PLAINTEXT: The data to be encrypted
5296
5297      CIPHERTEXT: contains the encrypted data
5298
5299      This function will encrypt the given data, using the public key.
5300
5301      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5302      otherwise a negative error value.
5303
5304      *Since:* 3.0
5305
5306  -- Function: int gnutls_privkey_sign_data (gnutls_privkey_t SIGNER,
5307           gnutls_digest_algorithm_t HASH, unsigned int FLAGS, const
5308           gnutls_datum_t * DATA, gnutls_datum_t * SIGNATURE)
5309      SIGNER: Holds the key
5310
5311      HASH: should be a digest algorithm
5312
5313      FLAGS: Zero or one of 'gnutls_privkey_flags_t'
5314
5315      DATA: holds the data to be signed
5316
5317      SIGNATURE: will contain the signature allocate with
5318      'gnutls_malloc()'
5319
5320      This function will sign the given data using a signature algorithm
5321      supported by the private key.  Signature algorithms are always used
5322      together with a hash functions.  Different hash functions may be
5323      used for the RSA algorithm, but only the SHA family for the DSA
5324      keys.
5325
5326      You may use 'gnutls_pubkey_get_preferred_hash_algorithm()' to
5327      determine the hash algorithm.
5328
5329      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5330      otherwise a negative error value.
5331
5332      *Since:* 2.12.0
5333
5334  -- Function: int gnutls_privkey_sign_hash (gnutls_privkey_t SIGNER,
5335           gnutls_digest_algorithm_t HASH_ALGO, unsigned int FLAGS, const
5336           gnutls_datum_t * HASH_DATA, gnutls_datum_t * SIGNATURE)
5337      SIGNER: Holds the signer's key
5338
5339      HASH_ALGO: The hash algorithm used
5340
5341      FLAGS: Zero or one of 'gnutls_privkey_flags_t'
5342
5343      HASH_DATA: holds the data to be signed
5344
5345      SIGNATURE: will contain newly allocated signature
5346
5347      This function will sign the given hashed data using a signature
5348      algorithm supported by the private key.  Signature algorithms are
5349      always used together with a hash functions.  Different hash
5350      functions may be used for the RSA algorithm, but only SHA-XXX for
5351      the DSA keys.
5352
5353      You may use 'gnutls_pubkey_get_preferred_hash_algorithm()' to
5354      determine the hash algorithm.
5355
5356      Note that if 'GNUTLS_PRIVKEY_SIGN_FLAG_TLS1_RSA' flag is specified
5357      this function will ignore 'hash_algo' and perform a raw PKCS1
5358      signature.
5359
5360      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5361      otherwise a negative error value.
5362
5363      *Since:* 2.12.0
5364
5365  -- Function: int gnutls_privkey_decrypt_data (gnutls_privkey_t KEY,
5366           unsigned int FLAGS, const gnutls_datum_t * CIPHERTEXT,
5367           gnutls_datum_t * PLAINTEXT)
5368      KEY: Holds the key
5369
5370      FLAGS: zero for now
5371
5372      CIPHERTEXT: holds the data to be decrypted
5373
5374      PLAINTEXT: will contain the decrypted data, allocated with
5375      'gnutls_malloc()'
5376
5377      This function will decrypt the given data using the algorithm
5378      supported by the private key.
5379
5380      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5381      otherwise a negative error value.
5382
5383      *Since:* 2.12.0
5384
5385 Signing existing structures, such as certificates, CRLs, or certificate
5386 requests, as well as associating public keys with structures is also
5387 possible using the key abstractions.
5388
5389  -- Function: int gnutls_x509_crq_set_pubkey (gnutls_x509_crq_t CRQ,
5390           gnutls_pubkey_t KEY)
5391      CRQ: should contain a 'gnutls_x509_crq_t' structure
5392
5393      KEY: holds a public key
5394
5395      This function will set the public parameters from the given public
5396      key to the request.
5397
5398      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5399      otherwise a negative error value.
5400
5401      *Since:* 2.12.0
5402
5403  -- Function: int gnutls_x509_crt_set_pubkey (gnutls_x509_crt_t CRT,
5404           gnutls_pubkey_t KEY)
5405      CRT: should contain a 'gnutls_x509_crt_t' structure
5406
5407      KEY: holds a public key
5408
5409      This function will set the public parameters from the given public
5410      key to the request.
5411
5412      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5413      otherwise a negative error value.
5414
5415      *Since:* 2.12.0
5416 '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)'
5417 '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)'
5418 'INT *note gnutls_x509_crq_privkey_sign:: (gnutls_x509_crq_t CRQ, gnutls_privkey_t KEY, gnutls_digest_algorithm_t DIG, unsigned int FLAGS)'
5419
5420 \1f
5421 File: gnutls.info,  Node: Smart cards and HSMs,  Next: Trusted Platform Module,  Prev: Abstract key types,  Up: Hardware security modules and abstract key types
5422
5423 5.2 Smart cards and HSMs
5424 ========================
5425
5426 In this section we present the smart-card and hardware security module
5427 (HSM) support in GnuTLS using PKCS #11 [_PKCS11_].  Hardware security
5428 modules and smart cards provide a way to store private keys and perform
5429 operations on them without exposing them.  This decouples cryptographic
5430 keys from the applications that use them and provide an additional
5431 security layer against cryptographic key extraction.  Since this can
5432 also be achieved in software components such as in Gnome keyring, we
5433 will use the term security module to describe any cryptographic key
5434 separation subsystem.
5435
5436 PKCS #11 is plugin API allowing applications to access cryptographic
5437 operations on a security module, as well as to objects residing on it.
5438 PKCS #11 modules exist for hardware tokens such as smart cards(1),
5439 cryptographic tokens, as well as for software modules like Gnome
5440 Keyring.  The objects residing on a security module may be certificates,
5441 public keys, private keys or secret keys.  Of those certificates and
5442 public/private key pairs can be used with GnuTLS.  PKCS #11's main
5443 advantage is that it allows operations on private key objects such as
5444 decryption and signing without exposing the key.  In GnuTLS the PKCS #11
5445 functionality is available in 'gnutls/pkcs11.h'.
5446
5447 Moreover PKCS #11 can be (ab)used to allow all applications in the same
5448 operating system to access shared cryptographic keys and certificates in
5449 a uniform way, as in *note Figure 5.1: fig-pkcs11-vision.  That way
5450 applications could load their trusted certificate list, as well as user
5451 certificates from a common PKCS #11 module.  Such a provider is the
5452 p11-kit trust storage module(2).
5453
5454 \0\b[image src="pkcs11-vision.png"\0\b]
5455
5456 Figure 5.1: PKCS #11 module usage.
5457
5458 * Menu:
5459
5460 * PKCS11 Initialization::
5461 * Accessing objects that require a PIN::
5462 * Reading objects::
5463 * Writing objects::
5464 * Using a PKCS11 token with TLS::
5465 * p11tool Invocation::
5466
5467    ---------- Footnotes ----------
5468
5469    (1) <http://www.opensc-project.org>
5470
5471    (2) <http://p11-glue.freedesktop.org/trust-module.html>
5472
5473 \1f
5474 File: gnutls.info,  Node: PKCS11 Initialization,  Next: Accessing objects that require a PIN,  Up: Smart cards and HSMs
5475
5476 5.2.1 Initialization
5477 --------------------
5478
5479 To allow all GnuTLS applications to transparently access smard cards and
5480 tokens, PKCS #11 is automatically initialized during the global
5481 initialization (see *note gnutls_global_init::).  The initialization
5482 function, to select which modules to load reads certain module
5483 configuration files.  Those are stored in '/etc/pkcs11/modules/' and are
5484 the configuration files of p11-kit(1).  For example a file that will
5485 load the OpenSC module, could be named
5486 '/etc/pkcs11/modules/opensc.module' and contain the following:
5487
5488      module: /usr/lib/opensc-pkcs11.so
5489
5490 If you use these configuration files, then there is no need for other
5491 initialization in GnuTLS, except for the PIN and token functions (see
5492 next section).  In several cases, however, it is desirable to limit
5493 badly behaving modules (e.g., modules that add an unacceptable delay on
5494 initialization) to single applications.  That can be done using the
5495 "enable-in:" option followed by the base name of applications that this
5496 module should be used.
5497
5498 In all cases, you can also manually initialize the PKCS #11 subsystem if
5499 the default settings are not desirable.  To completely disable PKCS #11
5500 support you need to call *note gnutls_pkcs11_init:: with the flag
5501 'GNUTLS_PKCS11_FLAG_MANUAL' prior to *note gnutls_global_init::.
5502
5503  -- Function: int gnutls_pkcs11_init (unsigned int FLAGS, const char *
5504           DEPRECATED_CONFIG_FILE)
5505      FLAGS: An ORed sequence of 'GNUTLS_PKCS11_FLAG_' *
5506
5507      DEPRECATED_CONFIG_FILE: either NULL or the location of a deprecated
5508      configuration file
5509
5510      This function will initialize the PKCS 11 subsystem in gnutls.  It
5511      will read configuration files if 'GNUTLS_PKCS11_FLAG_AUTO' is used
5512      or allow you to independently load PKCS 11 modules using
5513      'gnutls_pkcs11_add_provider()' if 'GNUTLS_PKCS11_FLAG_MANUAL' is
5514      specified.
5515
5516      Normally you don't need to call this function since it is being
5517      called when the first PKCS 11 operation is requested using the
5518      'GNUTLS_PKCS11_FLAG_AUTO' flag.  If another flags are required then
5519      it must be called independently prior to any PKCS 11 operation.
5520
5521      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5522      otherwise a negative error value.
5523
5524      *Since:* 2.12.0
5525
5526 Note that PKCS #11 modules must be reinitialized on the child processes
5527 after a 'fork'.  In older versions of GnuTLS it was required to call
5528 *note gnutls_pkcs11_reinit::; since 3.3.0 this is no longer required, as
5529 reinitialization occurs automatically.
5530
5531    ---------- Footnotes ----------
5532
5533    (1) <http://p11-glue.freedesktop.org/>
5534
5535 \1f
5536 File: gnutls.info,  Node: Accessing objects that require a PIN,  Next: Reading objects,  Prev: PKCS11 Initialization,  Up: Smart cards and HSMs
5537
5538 5.2.2 Accessing objects that require a PIN
5539 ------------------------------------------
5540
5541 Objects stored in token such as a private keys are typically protected
5542 from access by a PIN or password.  This PIN may be required to either
5543 read the object (if allowed) or to perform operations with it.  To allow
5544 obtaining the PIN when accessing a protected object, as well as probe
5545 the user to insert the token the following functions allow to set a
5546 callback.
5547
5548 'VOID *note gnutls_pkcs11_set_token_function:: (gnutls_pkcs11_token_callback_t FN, void * USERDATA)'
5549 'VOID *note gnutls_pkcs11_set_pin_function:: (gnutls_pin_callback_t FN, void * USERDATA)'
5550 'INT *note gnutls_pkcs11_add_provider:: (const char * NAME, const char * PARAMS)'
5551 'GNUTLS_PIN_CALLBACK_T *note gnutls_pkcs11_get_pin_function:: (void ** USERDATA)'
5552
5553 The callback is of type 'gnutls_pin_callback_t' and will have as input
5554 the provided userdata, the PIN attempt number, a URL describing the
5555 token, a label describing the object and flags.  The PIN must be at most
5556 of 'pin_max' size and must be copied to pin variable.  The function must
5557 return 0 on success or a negative error code otherwise.
5558
5559 typedef int (*gnutls_pin_callback_t) (void *userdata, int attempt,
5560                                       const char *token_url,
5561                                       const char *token_label,
5562                                       unsigned int flags,
5563                                       char *pin, size_t pin_max);
5564
5565 The flags are of 'gnutls_pin_flag_t' type and are explained below.
5566
5567 'GNUTLS_PIN_USER'
5568      The PIN for the user.
5569 'GNUTLS_PIN_SO'
5570      The PIN for the security officer (admin).
5571 'GNUTLS_PIN_FINAL_TRY'
5572      This is the final try before blocking.
5573 'GNUTLS_PIN_COUNT_LOW'
5574      Few tries remain before token blocks.
5575 'GNUTLS_PIN_CONTEXT_SPECIFIC'
5576      The PIN is for a specific action and key like signing.
5577 'GNUTLS_PIN_WRONG'
5578      Last given PIN was not correct.
5579
5580 Figure 5.2: The 'gnutls_pin_flag_t' enumeration.
5581
5582 Note that due to limitations of PKCS #11 there are issues when multiple
5583 libraries are sharing a module.  To avoid this problem GnuTLS uses
5584 p11-kit that provides a middleware to control access to resources over
5585 the multiple users.
5586
5587 To avoid conflicts with multiple registered callbacks for PIN functions,
5588 *note gnutls_pkcs11_get_pin_function:: may be used to check for any
5589 previously set functions.  In addition context specific PIN functions
5590 are allowed, e.g., by using functions below.
5591
5592 'VOID *note gnutls_certificate_set_pin_function:: (gnutls_certificate_credentials_t CRED, gnutls_pin_callback_t FN, void * USERDATA)'
5593 'VOID *note gnutls_pubkey_set_pin_function:: (gnutls_pubkey_t KEY, gnutls_pin_callback_t FN, void * USERDATA)'
5594 'VOID *note gnutls_privkey_set_pin_function:: (gnutls_privkey_t KEY, gnutls_pin_callback_t FN, void * USERDATA)'
5595 'VOID *note gnutls_pkcs11_obj_set_pin_function:: (gnutls_pkcs11_obj_t OBJ, gnutls_pin_callback_t FN, void * USERDATA)'
5596 'VOID *note gnutls_x509_crt_set_pin_function:: (gnutls_x509_crt_t CRT, gnutls_pin_callback_t FN, void * USERDATA)'
5597
5598 \1f
5599 File: gnutls.info,  Node: Reading objects,  Next: Writing objects,  Prev: Accessing objects that require a PIN,  Up: Smart cards and HSMs
5600
5601 5.2.3 Reading objects
5602 ---------------------
5603
5604 All PKCS #11 objects are referenced by GnuTLS functions by URLs as
5605 described in [_PKCS11URI_]. This allows for a consistent naming of
5606 objects across systems and applications in the same system.  For example
5607 a public key on a smart card may be referenced as:
5608
5609      pkcs11:token=Nikos;serial=307521161601031;model=PKCS%2315; \
5610      manufacturer=EnterSafe;object=test1;objecttype=public;\
5611      id=32f153f3e37990b08624141077ca5dec2d15faed
5612
5613 while the smart card itself can be referenced as:
5614      pkcs11:token=Nikos;serial=307521161601031;model=PKCS%2315;manufacturer=EnterSafe
5615
5616 Objects stored in a PKCS #11 token can be extracted if they are not
5617 marked as sensitive.  Usually only private keys are marked as sensitive
5618 and cannot be extracted, while certificates and other data can be
5619 retrieved.  The functions that can be used to access objects are shown
5620 below.
5621
5622 'INT *note gnutls_pkcs11_obj_import_url:: (gnutls_pkcs11_obj_t OBJ, const char * URL, unsigned int FLAGS)'
5623 'INT *note gnutls_pkcs11_obj_export_url:: (gnutls_pkcs11_obj_t OBJ, gnutls_pkcs11_url_type_t DETAILED, char ** URL)'
5624
5625  -- Function: int gnutls_pkcs11_obj_get_info (gnutls_pkcs11_obj_t OBJ,
5626           gnutls_pkcs11_obj_info_t ITYPE, void * OUTPUT, size_t *
5627           OUTPUT_SIZE)
5628      OBJ: should contain a 'gnutls_pkcs11_obj_t' structure
5629
5630      ITYPE: Denotes the type of information requested
5631
5632      OUTPUT: where output will be stored
5633
5634      OUTPUT_SIZE: contains the maximum size of the output and will be
5635      overwritten with actual
5636
5637      This function will return information about the PKCS11 certificate
5638      such as the label, id as well as token information where the key is
5639      stored.  When output is text it returns null terminated string
5640      although 'output_size' contains the size of the actual data only.
5641
5642      *Returns:* 'GNUTLS_E_SUCCESS' (0) on success or a negative error
5643      code on error.
5644
5645      *Since:* 2.12.0
5646
5647 'INT *note gnutls_x509_crt_import_pkcs11:: (gnutls_x509_crt_t CRT, gnutls_pkcs11_obj_t PKCS11_CRT)'
5648 'INT *note gnutls_x509_crt_import_pkcs11_url:: (gnutls_x509_crt_t CRT, const char * URL, unsigned int FLAGS)'
5649 '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)'
5650
5651 Properties of the physical token can also be accessed and altered with
5652 GnuTLS.  For example data in a token can be erased (initialized), PIN
5653 can be altered, etc.
5654
5655 'INT *note gnutls_pkcs11_token_init:: (const char * TOKEN_URL, const char * SO_PIN, const char * LABEL)'
5656 'INT *note gnutls_pkcs11_token_get_url:: (unsigned int SEQ, gnutls_pkcs11_url_type_t DETAILED, char ** URL)'
5657 'INT *note gnutls_pkcs11_token_get_info:: (const char * URL, gnutls_pkcs11_token_info_t TTYPE, void * OUTPUT, size_t * OUTPUT_SIZE)'
5658 'INT *note gnutls_pkcs11_token_get_flags:: (const char * URL, unsigned int * FLAGS)'
5659 'INT *note gnutls_pkcs11_token_set_pin:: (const char * TOKEN_URL, const char * OLDPIN, const char * NEWPIN, unsigned int FLAGS)'
5660
5661 The following examples demonstrate the usage of the API. The first
5662 example will list all available PKCS #11 tokens in a system and the
5663 latter will list all certificates in a token that have a corresponding
5664 private key.
5665
5666      int i;
5667      char* url;
5668
5669      gnutls_global_init();
5670
5671      for (i=0;;i++)
5672        {
5673          ret = gnutls_pkcs11_token_get_url(i, &url);
5674          if (ret == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE)
5675            break;
5676
5677          if (ret < 0)
5678            exit(1);
5679
5680          fprintf(stdout, "Token[%d]: URL: %s\n", i, url);
5681          gnutls_free(url);
5682        }
5683      gnutls_global_deinit();
5684
5685 /* This example code is placed in the public domain. */
5686
5687 #include <config.h>
5688 #include <gnutls/gnutls.h>
5689 #include <gnutls/pkcs11.h>
5690 #include <stdio.h>
5691 #include <stdlib.h>
5692
5693 #define URL "pkcs11:URL"
5694
5695 int main(int argc, char **argv)
5696 {
5697         gnutls_pkcs11_obj_t *obj_list;
5698         gnutls_x509_crt_t xcrt;
5699         unsigned int obj_list_size = 0;
5700         gnutls_datum_t cinfo;
5701         int ret;
5702         unsigned int i;
5703
5704         obj_list_size = 0;
5705         ret = gnutls_pkcs11_obj_list_import_url(NULL, &obj_list_size, URL,
5706                                                 GNUTLS_PKCS11_OBJ_ATTR_CRT_WITH_PRIVKEY,
5707                                                 0);
5708         if (ret < 0 && ret != GNUTLS_E_SHORT_MEMORY_BUFFER)
5709                 return -1;
5710
5711 /* no error checking from now on */
5712         obj_list = malloc(sizeof(*obj_list) * obj_list_size);
5713
5714         gnutls_pkcs11_obj_list_import_url(obj_list, &obj_list_size, URL,
5715                                           GNUTLS_PKCS11_OBJ_ATTR_CRT_WITH_PRIVKEY,
5716                                           0);
5717
5718 /* now all certificates are in obj_list */
5719         for (i = 0; i < obj_list_size; i++) {
5720
5721                 gnutls_x509_crt_init(&xcrt);
5722
5723                 gnutls_x509_crt_import_pkcs11(xcrt, obj_list[i]);
5724
5725                 gnutls_x509_crt_print(xcrt, GNUTLS_CRT_PRINT_FULL, &cinfo);
5726
5727                 fprintf(stdout, "cert[%d]:\n %s\n\n", i, cinfo.data);
5728
5729                 gnutls_free(cinfo.data);
5730                 gnutls_x509_crt_deinit(xcrt);
5731         }
5732
5733         return 0;
5734 }
5735
5736 \1f
5737 File: gnutls.info,  Node: Writing objects,  Next: Using a PKCS11 token with TLS,  Prev: Reading objects,  Up: Smart cards and HSMs
5738
5739 5.2.4 Writing objects
5740 ---------------------
5741
5742 With GnuTLS you can copy existing private keys and certificates to a
5743 token.  Note that when copying private keys it is recommended to mark
5744 them as sensitive using the 'GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE' to
5745 prevent its extraction.  An object can be marked as private using the
5746 flag 'GNUTLS_PKCS11_OBJ_FLAG_MARK_PRIVATE', to require PIN to be entered
5747 before accessing the object (for operations or otherwise).
5748
5749  -- Function: int gnutls_pkcs11_copy_x509_privkey (const char *
5750           TOKEN_URL, gnutls_x509_privkey_t KEY, const char * LABEL,
5751           unsigned int KEY_USAGE, unsigned int FLAGS)
5752      TOKEN_URL: A PKCS '11' URL specifying a token
5753
5754      KEY: A private key
5755
5756      LABEL: A name to be used for the stored data
5757
5758      KEY_USAGE: One of GNUTLS_KEY_*
5759
5760      FLAGS: One of GNUTLS_PKCS11_OBJ_* flags
5761
5762      This function will copy a private key into a PKCS '11' token
5763      specified by a URL. It is highly recommended flags to contain
5764      'GNUTLS_PKCS11_OBJ_FLAG_MARK_SENSITIVE' unless there is a strong
5765      reason not to.
5766
5767      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5768      otherwise a negative error value.
5769
5770      *Since:* 2.12.0
5771
5772  -- Function: int gnutls_pkcs11_copy_x509_crt (const char * TOKEN_URL,
5773           gnutls_x509_crt_t CRT, const char * LABEL, unsigned int FLAGS)
5774      TOKEN_URL: A PKCS '11' URL specifying a token
5775
5776      CRT: The certificate to copy
5777
5778      LABEL: The name to be used for the stored data
5779
5780      FLAGS: One of GNUTLS_PKCS11_OBJ_FLAG_*
5781
5782      This function will copy a certificate into a PKCS '11' token
5783      specified by a URL. The certificate can be marked as trusted or
5784      not.
5785
5786      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
5787      otherwise a negative error value.
5788
5789      *Since:* 2.12.0
5790
5791  -- Function: int gnutls_pkcs11_delete_url (const char * OBJECT_URL,
5792           unsigned int FLAGS)
5793      OBJECT_URL: The URL of the object to delete.
5794
5795      FLAGS: One of GNUTLS_PKCS11_OBJ_* flags
5796
5797      This function will delete objects matching the given URL. Note that
5798      not all tokens support the delete operation.
5799
5800      *Returns:* On success, the number of objects deleted is returned,
5801      otherwise a negative error value.
5802
5803      *Since:* 2.12.0
5804
5805 \1f
5806 File: gnutls.info,  Node: Using a PKCS11 token with TLS,  Next: p11tool Invocation,  Prev: Writing objects,  Up: Smart cards and HSMs
5807
5808 5.2.5 Using a PKCS #11 token with TLS
5809 -------------------------------------
5810
5811 It is possible to use a PKCS #11 token to a TLS session, as shown in
5812 *note ex-pkcs11-client::.  In addition the following functions can be
5813 used to load PKCS #11 key and certificates by specifying a PKCS #11 URL
5814 instead of a filename.
5815
5816 'INT *note gnutls_certificate_set_x509_trust_file:: (gnutls_certificate_credentials_t CRED, const char * CAFILE, gnutls_x509_crt_fmt_t TYPE)'
5817 '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)'
5818
5819  -- Function: int gnutls_certificate_set_x509_system_trust
5820           (gnutls_certificate_credentials_t CRED)
5821      CRED: is a 'gnutls_certificate_credentials_t' structure.
5822
5823      This function adds the system's default trusted CAs in order to
5824      verify client or server certificates.
5825
5826      In the case the system is currently unsupported
5827      'GNUTLS_E_UNIMPLEMENTED_FEATURE' is returned.
5828
5829      *Returns:* the number of certificates processed or a negative error
5830      code on error.
5831
5832      *Since:* 3.0.20
5833
5834 \1f
5835 File: gnutls.info,  Node: p11tool Invocation,  Prev: Using a PKCS11 token with TLS,  Up: Smart cards and HSMs
5836
5837 5.2.6 Invoking p11tool
5838 ----------------------
5839
5840 Program that allows operations on PKCS #11 smart cards and security
5841 modules.
5842
5843 To use PKCS #11 tokens with GnuTLS the p11-kit configuration files need
5844 to be setup.  That is create a .module file in /etc/pkcs11/modules with
5845 the contents 'module: /path/to/pkcs11.so'.  Alternatively the
5846 configuration file /etc/gnutls/pkcs11.conf has to exist and contain a
5847 number of lines of the form 'load=/usr/lib/opensc-pkcs11.so'.
5848
5849 You can provide the PIN to be used for the PKCS #11 operations with the
5850 environment variables GNUTLS_PIN and GNUTLS_SO_PIN.
5851
5852 This section was generated by *AutoGen*, using the 'agtexi-cmd' template
5853 and the option descriptions for the 'p11tool' program.  This software is
5854 released under the GNU General Public License, version 3 or later.
5855
5856 5.2.7 p11tool help/usage ('--help')
5857 -----------------------------------
5858
5859 This is the automatically generated usage text for p11tool.
5860
5861 The text printed is the same whether selected with the 'help' option
5862 ('--help') or the 'more-help' option ('--more-help').  'more-help' will
5863 print the usage text by passing it through a pager program.  'more-help'
5864 is disabled on platforms without a working 'fork(2)' function.  The
5865 'PAGER' environment variable is used to select the program, defaulting
5866 to 'more'.  Both will exit with a status code of 0.
5867
5868      p11tool - GnuTLS PKCS #11 tool
5869      Usage:  p11tool [ -<flag> [<val>] | --<name>[{=| }<val>] ]... [url]
5870
5871
5872      Tokens:
5873
5874             --list-tokens          List all available tokens
5875             --list-token-urls      List the URLs available tokens
5876             --list-mechanisms      List all available mechanisms in a token
5877             --initialize           Initializes a PKCS #11 token
5878             --set-pin=str          Specify the PIN to use on token initialization
5879             --set-so-pin=str       Specify the Security Officer's PIN to use on token initialization
5880
5881      Object listing:
5882
5883             --list-all             List all available objects in a token
5884             --list-all-certs       List all available certificates in a token
5885             --list-certs           List all certificates that have an associated private key
5886             --list-all-privkeys    List all available private keys in a token
5887             --list-privkeys        an alias for the 'list-all-privkeys' option
5888             --list-keys            an alias for the 'list-all-privkeys' option
5889             --list-all-trusted     List all available certificates marked as trusted
5890             --export               Export the object specified by the URL
5891                                      - prohibits these options:
5892                                      export-stapled
5893                                      export-chain
5894                                      export-pubkey
5895             --export-stapled       Export the certificate object specified by the URL
5896                                      - prohibits these options:
5897                                      export
5898                                      export-chain
5899                                      export-pubkey
5900             --export-chain         Export the certificate specified by the URL and its chain of trust
5901                                      - prohibits these options:
5902                                      export-stapled
5903                                      export
5904                                      export-pubkey
5905             --export-pubkey        Export the public key for a private key
5906                                      - prohibits these options:
5907                                      export-stapled
5908                                      export
5909                                      export-chain
5910             --info                 List information on an available object in a token
5911             --trusted              an alias for the 'mark-trusted' option
5912             --distrusted           an alias for the 'mark-distrusted' option
5913
5914      Key generation:
5915
5916             --generate-rsa         Generate an RSA private-public key pair
5917             --generate-dsa         Generate a DSA private-public key pair
5918             --generate-ecc         Generate an ECDSA private-public key pair
5919             --bits=num             Specify the number of bits for the key generate
5920             --curve=str            Specify the curve used for EC key generation
5921             --sec-param=str        Specify the security level
5922
5923      Writing objects:
5924
5925             --set-id=str           Set the CKA_ID (in hex) for the specified by the URL object
5926                                      - prohibits the option 'write'
5927             --set-label=str        Set the CKA_LABEL for the specified by the URL object
5928                                      - prohibits these options:
5929                                      write
5930                                      set-id
5931             --write                Writes the loaded objects to a PKCS #11 token
5932             --delete               Deletes the objects matching the given PKCS #11 URL
5933             --label=str            Sets a label for the write operation
5934             --id=str               Sets an ID for the write operation
5935             --mark-wrap            Marks the generated key to be a wrapping key
5936                                      - disabled as '--no-mark-wrap'
5937             --mark-trusted         Marks the object to be written as trusted
5938                                      - prohibits the option 'mark-distrusted'
5939                                      - disabled as '--no-mark-trusted'
5940             --mark-distrusted      When retrieving objects, it requires the objects to be distrusted
5941      (blacklisted)
5942                                      - prohibits the option 'mark-trusted'
5943             --mark-decrypt         Marks the object to be written for decryption
5944                                      - disabled as '--no-mark-decrypt'
5945             --mark-sign            Marks the object to be written for signature generation
5946                                      - disabled as '--no-mark-sign'
5947             --mark-ca              Marks the object to be written as a CA
5948                                      - disabled as '--no-mark-ca'
5949             --mark-private         Marks the object to be written as private
5950                                      - disabled as '--no-mark-private'
5951             --ca                   an alias for the 'mark-ca' option
5952             --private              an alias for the 'mark-private' option
5953             --secret-key=str       Provide a hex encoded secret key
5954             --load-privkey=file    Private key file to use
5955                                      - file must pre-exist
5956             --load-pubkey=file     Public key file to use
5957                                      - file must pre-exist
5958             --load-certificate=file Certificate file to use
5959                                      - file must pre-exist
5960
5961      Other options:
5962
5963         -d, --debug=num            Enable debugging
5964                                      - it must be in the range:
5965                                        0 to 9999
5966             --outfile=str          Output file
5967             --login                Force (user) login to token
5968                                      - disabled as '--no-login'
5969             --so-login             Force security officer login to token
5970                                      - disabled as '--no-so-login'
5971             --admin-login          an alias for the 'so-login' option
5972             --test-sign            Tests the signature operation of the provided object
5973             --generate-random=num  Generate random data
5974         -8, --pkcs8                Use PKCS #8 format for private keys
5975             --inder                Use DER/RAW format for input
5976                                      - disabled as '--no-inder'
5977             --inraw                an alias for the 'inder' option
5978             --outder               Use DER format for output certificates, private keys, and DH parameters
5979                                      - disabled as '--no-outder'
5980             --outraw               an alias for the 'outder' option
5981             --provider=file        Specify the PKCS #11 provider library
5982             --detailed-url         Print detailed URLs
5983                                      - disabled as '--no-detailed-url'
5984             --only-urls            Print a compact listing using only the URLs
5985             --batch                Disable all interaction with the tool
5986
5987      Version, usage and configuration options:
5988
5989         -v, --version[=arg]        output version information and exit
5990         -h, --help                 display extended usage information and exit
5991         -!, --more-help            extended usage information passed thru pager
5992
5993      Options are specified by doubled hyphens and their name or by a single
5994      hyphen and the flag character.
5995      Operands and options may be intermixed.  They will be reordered.
5996
5997      Program that allows operations on PKCS #11 smart cards and security
5998      modules.
5999
6000      To use PKCS #11 tokens with GnuTLS the p11-kit configuration files need to
6001      be setup.  That is create a .module file in /etc/pkcs11/modules with the
6002      contents 'module: /path/to/pkcs11.so'.  Alternatively the configuration
6003      file /etc/gnutls/pkcs11.conf has to exist and contain a number of lines of
6004      the form 'load=/usr/lib/opensc-pkcs11.so'.
6005
6006      You can provide the PIN to be used for the PKCS #11 operations with the
6007      environment variables GNUTLS_PIN and GNUTLS_SO_PIN.
6008
6009
6010 5.2.8 debug option (-d)
6011 -----------------------
6012
6013 This is the "enable debugging" option.  This option takes a number
6014 argument.  Specifies the debug level.
6015
6016 5.2.9 export-chain option
6017 -------------------------
6018
6019 This is the "export the certificate specified by the url and its chain
6020 of trust" option.  Exports the certificate specified by the URL and
6021 generates its chain of trust based on the stored certificates in the
6022 module.
6023
6024 5.2.10 list-all-privkeys option
6025 -------------------------------
6026
6027 This is the "list all available private keys in a token" option.  Lists
6028 all the private keys in a token that match the specified URL.
6029
6030 5.2.11 list-privkeys option
6031 ---------------------------
6032
6033 This is an alias for the 'list-all-privkeys' option, *note the
6034 list-all-privkeys option documentation: p11tool list-all-privkeys.
6035
6036 5.2.12 list-keys option
6037 -----------------------
6038
6039 This is an alias for the 'list-all-privkeys' option, *note the
6040 list-all-privkeys option documentation: p11tool list-all-privkeys.
6041
6042 5.2.13 write option
6043 -------------------
6044
6045 This is the "writes the loaded objects to a pkcs #11 token" option.  It
6046 can be used to write private keys, certificates or secret keys to a
6047 token.
6048
6049 5.2.14 generate-random option
6050 -----------------------------
6051
6052 This is the "generate random data" option.  This option takes a number
6053 argument.  Asks the token to generate a number of bytes of random bytes.
6054
6055 5.2.15 generate-rsa option
6056 --------------------------
6057
6058 This is the "generate an rsa private-public key pair" option.  Generates
6059 an RSA private-public key pair on the specified token.
6060
6061 5.2.16 generate-dsa option
6062 --------------------------
6063
6064 This is the "generate a dsa private-public key pair" option.  Generates
6065 a DSA private-public key pair on the specified token.
6066
6067 5.2.17 generate-ecc option
6068 --------------------------
6069
6070 This is the "generate an ecdsa private-public key pair" option.
6071 Generates an ECDSA private-public key pair on the specified token.
6072
6073 5.2.18 export-pubkey option
6074 ---------------------------
6075
6076 This is the "export the public key for a private key" option.  Exports
6077 the public key for the specified private key
6078
6079 5.2.19 set-id option
6080 --------------------
6081
6082 This is the "set the cka_id (in hex) for the specified by the url
6083 object" option.  This option takes a string argument.  Sets the CKA_ID
6084 in the specified by the URL object.  The ID should be specified in
6085 hexadecimal format without a '0x' prefix.
6086
6087 5.2.20 set-label option
6088 -----------------------
6089
6090 This is the "set the cka_label for the specified by the url object"
6091 option.  This option takes a string argument.  Sets the CKA_LABEL in the
6092 specified by the URL object
6093
6094 5.2.21 id option
6095 ----------------
6096
6097 This is the "sets an id for the write operation" option.  This option
6098 takes a string argument.  Sets the CKA_ID to be set by the write
6099 operation.  The ID should be specified in hexadecimal format without a
6100 '0x' prefix.
6101
6102 5.2.22 mark-wrap option
6103 -----------------------
6104
6105 This is the "marks the generated key to be a wrapping key" option.
6106
6107 This option has some usage constraints.  It:
6108    * can be disabled with -no-mark-wrap.
6109
6110 Marks the generated key with the CKA_WRAP flag.
6111
6112 5.2.23 mark-trusted option
6113 --------------------------
6114
6115 This is the "marks the object to be written as trusted" option.
6116
6117 This option has some usage constraints.  It:
6118    * can be disabled with -no-mark-trusted.
6119
6120 Marks the object to be generated/copied with the CKA_TRUST flag.
6121
6122 5.2.24 mark-ca option
6123 ---------------------
6124
6125 This is the "marks the object to be written as a ca" option.
6126
6127 This option has some usage constraints.  It:
6128    * can be disabled with -no-mark-ca.
6129
6130 Marks the object to be generated/copied with the
6131 CKA_CERTIFICATE_CATEGORY as CA.
6132
6133 5.2.25 mark-private option
6134 --------------------------
6135
6136 This is the "marks the object to be written as private" option.
6137
6138 This option has some usage constraints.  It:
6139    * can be disabled with -no-mark-private.
6140    * It is enabled by default.
6141
6142 Marks the object to be generated/copied with the CKA_PRIVATE flag.  The
6143 written object will require a PIN to be used.
6144
6145 5.2.26 trusted option
6146 ---------------------
6147
6148 This is an alias for the 'mark-trusted' option, *note the mark-trusted
6149 option documentation: p11tool mark-trusted.
6150
6151 5.2.27 ca option
6152 ----------------
6153
6154 This is an alias for the 'mark-ca' option, *note the mark-ca option
6155 documentation: p11tool mark-ca.
6156
6157 5.2.28 private option
6158 ---------------------
6159
6160 This is an alias for the 'mark-private' option, *note the mark-private
6161 option documentation: p11tool mark-private.
6162
6163 5.2.29 so-login option
6164 ----------------------
6165
6166 This is the "force security officer login to token" option.
6167
6168 This option has some usage constraints.  It:
6169    * can be disabled with -no-so-login.
6170
6171 Forces login to the token as security officer (admin).
6172
6173 5.2.30 admin-login option
6174 -------------------------
6175
6176 This is an alias for the 'so-login' option, *note the so-login option
6177 documentation: p11tool so-login.
6178
6179 5.2.31 curve option
6180 -------------------
6181
6182 This is the "specify the curve used for ec key generation" option.  This
6183 option takes a string argument.  Supported values are secp192r1,
6184 secp224r1, secp256r1, secp384r1 and secp521r1.
6185
6186 5.2.32 sec-param option
6187 -----------------------
6188
6189 This is the "specify the security level" option.  This option takes a
6190 string argument 'Security parameter'.  This is alternative to the bits
6191 option.  Available options are [low, legacy, medium, high, ultra].
6192
6193 5.2.33 inder option
6194 -------------------
6195
6196 This is the "use der/raw format for input" option.
6197
6198 This option has some usage constraints.  It:
6199    * can be disabled with -no-inder.
6200
6201 Use DER/RAW format for input certificates and private keys.
6202
6203 5.2.34 inraw option
6204 -------------------
6205
6206 This is an alias for the 'inder' option, *note the inder option
6207 documentation: p11tool inder.
6208
6209 5.2.35 outder option
6210 --------------------
6211
6212 This is the "use der format for output certificates, private keys, and
6213 dh parameters" option.
6214
6215 This option has some usage constraints.  It:
6216    * can be disabled with -no-outder.
6217
6218 The output will be in DER or RAW format.
6219
6220 5.2.36 outraw option
6221 --------------------
6222
6223 This is an alias for the 'outder' option, *note the outder option
6224 documentation: p11tool outder.
6225
6226 5.2.37 set-pin option
6227 ---------------------
6228
6229 This is the "specify the pin to use on token initialization" option.
6230 This option takes a string argument.  Alternatively the GNUTLS_PIN
6231 environment variable may be used.
6232
6233 5.2.38 set-so-pin option
6234 ------------------------
6235
6236 This is the "specify the security officer's pin to use on token
6237 initialization" option.  This option takes a string argument.
6238 Alternatively the GNUTLS_SO_PIN environment variable may be used.
6239
6240 5.2.39 provider option
6241 ----------------------
6242
6243 This is the "specify the pkcs #11 provider library" option.  This option
6244 takes a file argument.  This will override the default options in
6245 /etc/gnutls/pkcs11.conf
6246
6247 5.2.40 p11tool exit status
6248 --------------------------
6249
6250 One of the following exit values will be returned:
6251 '0 (EXIT_SUCCESS)'
6252      Successful program execution.
6253 '1 (EXIT_FAILURE)'
6254      The operation failed or the command syntax was not valid.
6255
6256 5.2.41 p11tool See Also
6257 -----------------------
6258
6259 certtool (1)
6260
6261 5.2.42 p11tool Examples
6262 -----------------------
6263
6264 To view all tokens in your system use:
6265      $ p11tool --list-tokens
6266
6267 To view all objects in a token use:
6268      $ p11tool --login --list-all "pkcs11:TOKEN-URL"
6269
6270 To store a private key and a certificate in a token run:
6271      $ p11tool --login --write "pkcs11:URL" --load-privkey key.pem \
6272                --label "Mykey"
6273      $ p11tool --login --write "pkcs11:URL" --load-certificate cert.pem \
6274                --label "Mykey"
6275 Note that some tokens require the same label to be used for the
6276 certificate and its corresponding private key.
6277
6278 To generate an RSA private key inside the token use:
6279      $ p11tool --login --generate-rsa --bits 1024 --label "MyNewKey" \
6280                --outfile MyNewKey.pub "pkcs11:TOKEN-URL"
6281 The bits parameter in the above example is explicitly set because some
6282 tokens only support limited choices in the bit length.  The output file
6283 is the corresponding public key.  This key can be used to general a
6284 certificate request with certtool.
6285      certtool --generate-request --load-privkey "pkcs11:KEY-URL" \
6286         --load-pubkey MyNewKey.pub --outfile request.pem
6287
6288 \1f
6289 File: gnutls.info,  Node: Trusted Platform Module,  Prev: Smart cards and HSMs,  Up: Hardware security modules and abstract key types
6290
6291 5.3 Trusted Platform Module (TPM)
6292 =================================
6293
6294 In this section we present the Trusted Platform Module (TPM) support in
6295 GnuTLS.
6296
6297 There was a big hype when the TPM chip was introduced into computers.
6298 Briefly it is a co-processor in your PC that allows it to perform
6299 calculations independently of the main processor.  This has good and bad
6300 side-effects.  In this section we focus on the good ones; these are the
6301 fact that you can use the TPM chip to perform cryptographic operations
6302 on keys stored in it, without accessing them.  That is very similar to
6303 the operation of a PKCS #11 smart card.  The chip allows for storage and
6304 usage of RSA keys, but has quite some operational differences from PKCS
6305 #11 module, and thus require different handling.  The basic TPM
6306 operations supported and used by GnuTLS, are key generation and signing.
6307
6308 The next sections assume that the TPM chip in the system is already
6309 initialized and in a operational state.
6310
6311 In GnuTLS the TPM functionality is available in 'gnutls/tpm.h'.
6312
6313 * Menu:
6314
6315 * Keys in TPM::
6316 * Key generation::
6317 * Using keys::
6318 * tpmtool Invocation::
6319
6320 \1f
6321 File: gnutls.info,  Node: Keys in TPM,  Next: Key generation,  Up: Trusted Platform Module
6322
6323 5.3.1 Keys in TPM
6324 -----------------
6325
6326 The RSA keys in the TPM module may either be stored in a flash memory
6327 within TPM or stored in a file in disk.  In the former case the key can
6328 provide operations as with PKCS #11 and is identified by a URL. The URL
6329 is described in [_TPMURI_] and is of the following form.
6330 tpmkey:uuid=42309df8-d101-11e1-a89a-97bb33c23ad1;storage=user
6331
6332 It consists from a unique identifier of the key as well as the part of
6333 the flash memory the key is stored at.  The two options for the storage
6334 field are 'user' and 'system'.  The user keys are typically only
6335 available to the generating user and the system keys to all users.  The
6336 stored in TPM keys are called registered keys.
6337
6338 The keys that are stored in the disk are exported from the TPM but in an
6339 encrypted form.  To access them two passwords are required.  The first
6340 is the TPM Storage Root Key (SRK), and the other is a key-specific
6341 password.  Also those keys are identified by a URL of the form:
6342 tpmkey:file=/path/to/file
6343
6344 When objects require a PIN to be accessed the same callbacks as with
6345 PKCS #11 objects are expected (see *note Accessing objects that require
6346 a PIN::).  Note that the PIN function may be called multiple times to
6347 unlock the SRK and the specific key in use.  The label in the key
6348 function will then be set to 'SRK' when unlocking the SRK key, or to
6349 'TPM' when unlocking any other key.
6350
6351 \1f
6352 File: gnutls.info,  Node: Key generation,  Next: Using keys,  Prev: Keys in TPM,  Up: Trusted Platform Module
6353
6354 5.3.2 Key generation
6355 --------------------
6356
6357 All keys used by the TPM must be generated by the TPM. This can be done
6358 using *note gnutls_tpm_privkey_generate::.
6359
6360  -- Function: int gnutls_tpm_privkey_generate (gnutls_pk_algorithm_t PK,
6361           unsigned int BITS, const char * SRK_PASSWORD, const char *
6362           KEY_PASSWORD, gnutls_tpmkey_fmt_t FORMAT,
6363           gnutls_x509_crt_fmt_t PUB_FORMAT, gnutls_datum_t * PRIVKEY,
6364           gnutls_datum_t * PUBKEY, unsigned int FLAGS)
6365      PK: the public key algorithm
6366
6367      BITS: the security bits
6368
6369      SRK_PASSWORD: a password to protect the exported key (optional)
6370
6371      KEY_PASSWORD: the password for the TPM (optional)
6372
6373      FORMAT: the format of the private key
6374
6375      PUB_FORMAT: the format of the public key
6376
6377      PRIVKEY: the generated key
6378
6379      PUBKEY: the corresponding public key (may be null)
6380
6381      FLAGS: should be a list of GNUTLS_TPM_* flags
6382
6383      This function will generate a private key in the TPM chip.  The
6384      private key will be generated within the chip and will be exported
6385      in a wrapped with TPM's master key form.  Furthermore the wrapped
6386      key can be protected with the provided 'password' .
6387
6388      Note that bits in TPM is quantized value.  If the input value is
6389      not one of the allowed values, then it will be quantized to one of
6390      512, 1024, 2048, 4096, 8192 and 16384.
6391
6392      Allowed flags are:
6393
6394      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
6395      otherwise a negative error value.
6396
6397      *Since:* 3.1.0
6398
6399 'INT *note gnutls_tpm_get_registered:: (gnutls_tpm_key_list_t * LIST)'
6400 'VOID *note gnutls_tpm_key_list_deinit:: (gnutls_tpm_key_list_t LIST)'
6401 'INT *note gnutls_tpm_key_list_get_url:: (gnutls_tpm_key_list_t LIST, unsigned int IDX, char ** URL, unsigned int FLAGS)'
6402
6403  -- Function: int gnutls_tpm_privkey_delete (const char * URL, const
6404           char * SRK_PASSWORD)
6405      URL: the URL describing the key
6406
6407      SRK_PASSWORD: a password for the SRK key
6408
6409      This function will unregister the private key from the TPM chip.
6410
6411      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
6412      otherwise a negative error value.
6413
6414      *Since:* 3.1.0
6415
6416 \1f
6417 File: gnutls.info,  Node: Using keys,  Next: tpmtool Invocation,  Prev: Key generation,  Up: Trusted Platform Module
6418
6419 5.3.3 Using keys
6420 ----------------
6421
6422 Importing keys
6423 ..............
6424
6425 The TPM keys can be used directly by the abstract key types and do not
6426 require any special structures.  Moreover functions like *note
6427 gnutls_certificate_set_x509_key_file2:: can access TPM URLs.
6428
6429 '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)'
6430 '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)'
6431
6432  -- Function: int gnutls_privkey_import_tpm_url (gnutls_privkey_t PKEY,
6433           const char * URL, const char * SRK_PASSWORD, const char *
6434           KEY_PASSWORD, unsigned int FLAGS)
6435      PKEY: The private key
6436
6437      URL: The URL of the TPM key to be imported
6438
6439      SRK_PASSWORD: The password for the SRK key (optional)
6440
6441      KEY_PASSWORD: A password for the key (optional)
6442
6443      FLAGS: One of the GNUTLS_PRIVKEY_* flags
6444
6445      This function will import the given private key to the abstract
6446      'gnutls_privkey_t' structure.
6447
6448      Note that unless 'GNUTLS_PRIVKEY_DISABLE_CALLBACKS' is specified,
6449      if incorrect (or NULL) passwords are given the PKCS11 callback
6450      functions will be used to obtain the correct passwords.  Otherwise
6451      if the SRK password is wrong 'GNUTLS_E_TPM_SRK_PASSWORD_ERROR' is
6452      returned and if the key password is wrong or not provided then
6453      'GNUTLS_E_TPM_KEY_PASSWORD_ERROR' is returned.
6454
6455      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
6456      otherwise a negative error value.
6457
6458      *Since:* 3.1.0
6459
6460  -- Function: int gnutls_pubkey_import_tpm_url (gnutls_pubkey_t PKEY,
6461           const char * URL, const char * SRK_PASSWORD, unsigned int
6462           FLAGS)
6463      PKEY: The public key
6464
6465      URL: The URL of the TPM key to be imported
6466
6467      SRK_PASSWORD: The password for the SRK key (optional)
6468
6469      FLAGS: should be zero
6470
6471      This function will import the given private key to the abstract
6472      'gnutls_privkey_t' structure.
6473
6474      Note that unless 'GNUTLS_PUBKEY_DISABLE_CALLBACKS' is specified, if
6475      incorrect (or NULL) passwords are given the PKCS11 callback
6476      functions will be used to obtain the correct passwords.  Otherwise
6477      if the SRK password is wrong 'GNUTLS_E_TPM_SRK_PASSWORD_ERROR' is
6478      returned.
6479
6480      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
6481      otherwise a negative error value.
6482
6483      *Since:* 3.1.0
6484
6485 Listing and deleting keys
6486 .........................
6487
6488 The registered keys (that are stored in the TPM) can be listed using one
6489 of the following functions.  Those keys are unfortunately only
6490 identified by their UUID and have no label or other human friendly
6491 identifier.  Keys can be deleted from permament storage using *note
6492 gnutls_tpm_privkey_delete::.
6493
6494 'INT *note gnutls_tpm_get_registered:: (gnutls_tpm_key_list_t * LIST)'
6495 'VOID *note gnutls_tpm_key_list_deinit:: (gnutls_tpm_key_list_t LIST)'
6496 'INT *note gnutls_tpm_key_list_get_url:: (gnutls_tpm_key_list_t LIST, unsigned int IDX, char ** URL, unsigned int FLAGS)'
6497
6498  -- Function: int gnutls_tpm_privkey_delete (const char * URL, const
6499           char * SRK_PASSWORD)
6500      URL: the URL describing the key
6501
6502      SRK_PASSWORD: a password for the SRK key
6503
6504      This function will unregister the private key from the TPM chip.
6505
6506      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
6507      otherwise a negative error value.
6508
6509      *Since:* 3.1.0
6510
6511 \1f
6512 File: gnutls.info,  Node: tpmtool Invocation,  Prev: Using keys,  Up: Trusted Platform Module
6513
6514 5.3.4 Invoking tpmtool
6515 ----------------------
6516
6517 Program that allows handling cryptographic data from the TPM chip.
6518
6519 This section was generated by *AutoGen*, using the 'agtexi-cmd' template
6520 and the option descriptions for the 'tpmtool' program.  This software is
6521 released under the GNU General Public License, version 3 or later.
6522
6523 5.3.5 tpmtool help/usage ('--help')
6524 -----------------------------------
6525
6526 This is the automatically generated usage text for tpmtool.
6527
6528 The text printed is the same whether selected with the 'help' option
6529 ('--help') or the 'more-help' option ('--more-help').  'more-help' will
6530 print the usage text by passing it through a pager program.  'more-help'
6531 is disabled on platforms without a working 'fork(2)' function.  The
6532 'PAGER' environment variable is used to select the program, defaulting
6533 to 'more'.  Both will exit with a status code of 0.
6534
6535      tpmtool is unavailable - no --help
6536
6537 5.3.6 debug option (-d)
6538 -----------------------
6539
6540 This is the "enable debugging" option.  This option takes a number
6541 argument.  Specifies the debug level.
6542
6543 5.3.7 generate-rsa option
6544 -------------------------
6545
6546 This is the "generate an rsa private-public key pair" option.  Generates
6547 an RSA private-public key pair in the TPM chip.  The key may be stored
6548 in filesystem and protected by a PIN, or stored (registered) in the TPM
6549 chip flash.
6550
6551 5.3.8 user option
6552 -----------------
6553
6554 This is the "any registered key will be a user key" option.
6555
6556 This option has some usage constraints.  It:
6557    * must appear in combination with the following options: register.
6558    * must not appear in combination with any of the following options:
6559      system.
6560
6561 The generated key will be stored in a user specific persistent storage.
6562
6563 5.3.9 system option
6564 -------------------
6565
6566 This is the "any registred key will be a system key" option.
6567
6568 This option has some usage constraints.  It:
6569    * must appear in combination with the following options: register.
6570    * must not appear in combination with any of the following options:
6571      user.
6572
6573 The generated key will be stored in system persistent storage.
6574
6575 5.3.10 test-sign option
6576 -----------------------
6577
6578 This is the "tests the signature operation of the provided object"
6579 option.  This option takes a string argument 'url'.  It can be used to
6580 test the correct operation of the signature operation.  This operation
6581 will sign and verify the signed data.
6582
6583 5.3.11 sec-param option
6584 -----------------------
6585
6586 This is the "specify the security level [low, legacy, medium, high,
6587 ultra]."  option.  This option takes a string argument 'Security
6588 parameter'.  This is alternative to the bits option.  Note however that
6589 the values allowed by the TPM chip are quantized and given values may be
6590 rounded up.
6591
6592 5.3.12 inder option
6593 -------------------
6594
6595 This is the "use the der format for keys."  option.
6596
6597 This option has some usage constraints.  It:
6598    * can be disabled with -no-inder.
6599
6600 The input files will be assumed to be in the portable DER format of TPM.
6601 The default format is a custom format used by various TPM tools
6602
6603 5.3.13 outder option
6604 --------------------
6605
6606 This is the "use der format for output keys" option.
6607
6608 This option has some usage constraints.  It:
6609    * can be disabled with -no-outder.
6610
6611 The output will be in the TPM portable DER format.
6612
6613 5.3.14 tpmtool exit status
6614 --------------------------
6615
6616 One of the following exit values will be returned:
6617 '0 (EXIT_SUCCESS)'
6618      Successful program execution.
6619 '1 (EXIT_FAILURE)'
6620      The operation failed or the command syntax was not valid.
6621
6622 5.3.15 tpmtool See Also
6623 -----------------------
6624
6625 p11tool (1), certtool (1)
6626
6627 5.3.16 tpmtool Examples
6628 -----------------------
6629
6630 To generate a key that is to be stored in filesystem use:
6631      $ tpmtool --generate-rsa --bits 2048 --outfile tpmkey.pem
6632
6633 To generate a key that is to be stored in TPM's flash use:
6634      $ tpmtool --generate-rsa --bits 2048 --register --user
6635
6636 To get the public key of a TPM key use:
6637      $ tpmtool --pubkey tpmkey:uuid=58ad734b-bde6-45c7-89d8-756a55ad1891;storage=user \
6638                --outfile pubkey.pem
6639
6640 or if the key is stored in the filesystem:
6641      $ tpmtool --pubkey tpmkey:file=tmpkey.pem --outfile pubkey.pem
6642
6643 To list all keys stored in TPM use:
6644      $ tpmtool --list
6645
6646 \1f
6647 File: gnutls.info,  Node: How to use GnuTLS in applications,  Next: GnuTLS application examples,  Prev: Hardware security modules and abstract key types,  Up: Top
6648
6649 6 How to use GnuTLS in applications
6650 ***********************************
6651
6652 * Menu:
6653
6654 * Introduction to the library::
6655 * Preparation::
6656 * Session initialization::
6657 * Associating the credentials::
6658 * Setting up the transport layer::
6659 * TLS handshake::
6660 * Data transfer and termination::
6661 * Buffered data transfer::
6662 * Handling alerts::
6663 * Priority Strings::
6664 * Selecting cryptographic key sizes::
6665 * Advanced topics::
6666
6667 \1f
6668 File: gnutls.info,  Node: Introduction to the library,  Next: Preparation,  Up: How to use GnuTLS in applications
6669
6670 6.1 Introduction
6671 ================
6672
6673 This chapter tries to explain the basic functionality of the current
6674 GnuTLS library.  Note that there may be additional functionality not
6675 discussed here but included in the library.  Checking the header files
6676 in '/usr/include/gnutls/' and the manpages is recommended.
6677
6678 * Menu:
6679
6680 * General idea::
6681 * Error handling::
6682 * Common types::
6683 * Debugging and auditing::
6684 * Thread safety::
6685 * Sessions and fork::
6686 * Callback functions::
6687
6688 \1f
6689 File: gnutls.info,  Node: General idea,  Next: Error handling,  Up: Introduction to the library
6690
6691 6.1.1 General idea
6692 ------------------
6693
6694 A brief description of how GnuTLS sessions operate is shown at *note
6695 Figure 6.1: fig-gnutls-design.  This section will become more clear when
6696 it is completely read.  As shown in the figure, there is a read-only
6697 global state that is initialized once by the global initialization
6698 function.  This global structure, among others, contains the memory
6699 allocation functions used, structures needed for the ASN.1 parser and
6700 depending on the system's CPU, pointers to hardware accelerated
6701 encryption functions.  This structure is never modified by any GnuTLS
6702 function, except for the deinitialization function which frees all
6703 allocated memory and must be called after the program has permanently
6704 finished using GnuTLS.
6705
6706 \0\b[image src="gnutls-internals.png"\0\b]
6707
6708 Figure 6.1: High level design of GnuTLS.
6709
6710 The credentials structures are used by the authentication methods, such
6711 as certificate authentication.  They store certificates, privates keys,
6712 and other information that is needed to prove the identity to the peer,
6713 and/or verify the indentity of the peer.  The information stored in the
6714 credentials structures is initialized once and then can be shared by
6715 many TLS sessions.
6716
6717 A GnuTLS session contains all the required state and information to
6718 handle one secure connection.  The session communicates with the peers
6719 using the provided functions of the transport layer.  Every session has
6720 a unique session ID shared with the peer.
6721
6722 Since TLS sessions can be resumed, servers need a database back-end to
6723 hold the session's parameters.  Every GnuTLS session after a successful
6724 handshake calls the appropriate back-end function (see *note resume::)
6725 to store the newly negotiated session.  The session database is examined
6726 by the server just after having received the client hello(1), and if the
6727 session ID sent by the client, matches a stored session, the stored
6728 session will be retrieved, and the new session will be a resumed one,
6729 and will share the same session ID with the previous one.
6730
6731    ---------- Footnotes ----------
6732
6733    (1) The first message in a TLS handshake
6734
6735 \1f
6736 File: gnutls.info,  Node: Error handling,  Next: Common types,  Prev: General idea,  Up: Introduction to the library
6737
6738 6.1.2 Error handling
6739 --------------------
6740
6741 In GnuTLS most functions return an integer type as a result.  In almost
6742 all cases a zero or a positive number means success, and a negative
6743 number indicates failure, or a situation that some action has to be
6744 taken.  Thus negative error codes may be fatal or not.
6745
6746 Fatal errors terminate the connection immediately and further sends and
6747 receives will be disallowed.  Such an example is
6748 'GNUTLS_E_DECRYPTION_FAILED'.  Non-fatal errors may warn about
6749 something, i.e., a warning alert was received, or indicate the some
6750 action has to be taken.  This is the case with the error code
6751 'GNUTLS_E_REHANDSHAKE' returned by *note gnutls_record_recv::.  This
6752 error code indicates that the server requests a re-handshake.  The
6753 client may ignore this request, or may reply with an alert.  You can
6754 test if an error code is a fatal one by using the *note
6755 gnutls_error_is_fatal::.  All errors can be converted to a descriptive
6756 string using *note gnutls_strerror::.
6757
6758 If any non fatal errors, that require an action, are to be returned by a
6759 function, these error codes will be documented in the function's
6760 reference.  For example the error codes
6761 'GNUTLS_E_WARNING_ALERT_RECEIVED' and 'GNUTLS_E_FATAL_ALERT_RECEIVED'
6762 that may returned when receiving data, should be handled by notifying
6763 the user of the alert (as explained in *note Handling alerts::).  See
6764 *note Error codes::, for a description of the available error codes.
6765
6766 \1f
6767 File: gnutls.info,  Node: Common types,  Next: Debugging and auditing,  Prev: Error handling,  Up: Introduction to the library
6768
6769 6.1.3 Common types
6770 ------------------
6771
6772 All strings that are to provided as input to GnuTLS functions should be
6773 in UTF-8 unless otherwise specified.  Output strings are also in UTF-8
6774 format unless otherwise specified.
6775
6776 When data of a fixed size are provided to GnuTLS functions then the
6777 helper structure 'gnutls_datum_t' is often used.  Its definition is
6778 shown below.
6779   typedef struct
6780   {
6781     unsigned char *data;
6782     unsigned int size;
6783   } gnutls_datum_t;
6784
6785 Other functions that require data for scattered read use a structure
6786 similar to 'struct iovec' typically used by 'readv'.  It is shown below.
6787   typedef struct
6788   {
6789     void *iov_base;             /* Starting address */
6790     size_t iov_len;             /* Number of bytes to transfer */
6791   } giovec_t;
6792
6793 \1f
6794 File: gnutls.info,  Node: Debugging and auditing,  Next: Thread safety,  Prev: Common types,  Up: Introduction to the library
6795
6796 6.1.4 Debugging and auditing
6797 ----------------------------
6798
6799 In many cases things may not go as expected and further information, to
6800 assist debugging, from GnuTLS is desired.  Those are the cases where the
6801 *note gnutls_global_set_log_level:: and *note
6802 gnutls_global_set_log_function:: are to be used.  Those will print
6803 verbose information on the GnuTLS functions internal flow.
6804
6805 'VOID *note gnutls_global_set_log_level:: (int LEVEL)'
6806 'VOID *note gnutls_global_set_log_function:: (gnutls_log_func LOG_FUNC)'
6807
6808 Alternatively the environment variable 'GNUTLS_DEBUG_LEVEL' can be set
6809 to a logging level and GnuTLS will output debugging output to standard
6810 error.  Other available environment variables are shown in *note Table
6811 6.1: tab:environment.
6812
6813 Variable               Purpose
6814                        
6815 --------------------------------------------------------------------------
6816 'GNUTLS_DEBUG_LEVEL'   When set to a numeric value, it sets the default
6817                        debugging level for GnuTLS applications.
6818                        
6819 'GNUTLS_CPUID_OVERRIDE'That environment variable can be used to
6820                        explicitly enable/disable the use of certain CPU
6821                        capabilities.  Note that CPU detection cannot be
6822                        overriden, i.e., VIA options cannot be enabled
6823                        on an Intel CPU. The currently available options
6824                        are:
6825                           * 0x1: Disable all run-time detected
6826                             optimizations
6827                           * 0x2: Enable AES-NI
6828                           * 0x4: Enable SSSE3
6829                           * 0x8: Enable PCLMUL
6830                           * 0x100000: Enable VIA padlock
6831                           * 0x200000: Enable VIA PHE
6832                           * 0x400000: Enable VIA PHE SHA512
6833                        
6834 'GNUTLS_FORCE_FIPS_MODE'In setups where GnuTLS is compiled with support
6835                        for FIPS140-2 (see -enable-fips140-mode in
6836                        configure), that option if set to one enforces
6837                        the FIPS140 mode.
6838                        
6839
6840 Table 6.1: Environment variables used by the library.
6841
6842 When debugging is not required, important issues, such as detected
6843 attacks on the protocol still need to be logged.  This is provided by
6844 the logging function set by *note
6845 gnutls_global_set_audit_log_function::.  The provided function will
6846 receive an message and the corresponding TLS session.  The session
6847 information might be used to derive IP addresses or other information
6848 about the peer involved.
6849
6850  -- Function: void gnutls_global_set_audit_log_function
6851           (gnutls_audit_log_func LOG_FUNC)
6852      LOG_FUNC: it is the audit log function
6853
6854      This is the function to set the audit logging function.  This is a
6855      function to report important issues, such as possible attacks in
6856      the protocol.  This is different from
6857      'gnutls_global_set_log_function()' because it will report also
6858      session-specific events.  The session parameter will be null if
6859      there is no corresponding TLS session.
6860
6861      'gnutls_audit_log_func' is of the form, void
6862      (*gnutls_audit_log_func)( gnutls_session_t, const char*);
6863
6864      *Since:* 3.0
6865
6866 \1f
6867 File: gnutls.info,  Node: Thread safety,  Next: Sessions and fork,  Prev: Debugging and auditing,  Up: Introduction to the library
6868
6869 6.1.5 Thread safety
6870 -------------------
6871
6872 The GnuTLS library is thread safe by design, meaning that objects of the
6873 library such as TLS sessions, can be safely divided across threads as
6874 long as a single thread accesses a single object.  This is sufficient to
6875 support a server which handles several sessions per thread.  If,
6876 however, an object needs to be shared across threads then access must be
6877 protected with a mutex.  Read-only access to objects, for example the
6878 credentials holding structures, is also thread-safe.
6879
6880 A 'gnutls_session_t' object can be shared by two threads, one sending,
6881 the other receiving.  In that case rehandshakes, if required, must only
6882 be handled by a single thread being active.  The termination of a
6883 session should be handled, either by a single thread being active, or by
6884 the sender thread using *note gnutls_bye:: with 'GNUTLS_SHUT_WR' and the
6885 receiving thread waiting for a return value of zero.
6886
6887 The random generator of the cryptographic back-end, utilizes mutex locks
6888 (e.g., pthreads on GNU/Linux and CriticalSection on Windows) which are
6889 setup by GnuTLS on library initialization.  Prior to version 3.3.0 they
6890 were setup by calling *note gnutls_global_init::.  On special systems
6891 you could manually specify the locking system using the function *note
6892 gnutls_global_set_mutex:: before calling any other GnuTLS function.
6893 Setting mutexes manually is not recommended.  An example of non-native
6894 thread usage is shown below.
6895
6896      #include <gnutls/gnutls.h>
6897
6898      int main()
6899      {
6900         /* When the system mutexes are not to be used
6901          * gnutls_global_set_mutex() must be called explicitly
6902          */
6903         gnutls_global_set_mutex (mutex_init, mutex_deinit,
6904                                  mutex_lock, mutex_unlock);
6905      }
6906
6907  -- Function: void gnutls_global_set_mutex (mutex_init_func INIT,
6908           mutex_deinit_func DEINIT, mutex_lock_func LOCK,
6909           mutex_unlock_func UNLOCK)
6910      INIT: mutex initialization function
6911
6912      DEINIT: mutex deinitialization function
6913
6914      LOCK: mutex locking function
6915
6916      UNLOCK: mutex unlocking function
6917
6918      With this function you are allowed to override the default mutex
6919      locks used in some parts of gnutls and dependent libraries.  This
6920      function should be used if you have complete control of your
6921      program and libraries.  Do not call this function from a library,
6922      or preferrably from any application unless really needed to.
6923      GnuTLS will use the appropriate locks for the running system.
6924
6925      This function must be called prior to any other gnutls function.
6926
6927      *Since:* 2.12.0
6928
6929 \1f
6930 File: gnutls.info,  Node: Sessions and fork,  Next: Callback functions,  Prev: Thread safety,  Up: Introduction to the library
6931
6932 6.1.6 Sessions and fork
6933 -----------------------
6934
6935 A 'gnutls_session_t' object can be shared by two processes after a fork,
6936 one sending, the other receiving.  In that case rehandshakes, cannot and
6937 must not be performed.  As with threads, the termination of a session
6938 should be handled by the sender process using *note gnutls_bye:: with
6939 'GNUTLS_SHUT_WR' and the receiving process waiting for a return value of
6940 zero.
6941
6942 \1f
6943 File: gnutls.info,  Node: Callback functions,  Prev: Sessions and fork,  Up: Introduction to the library
6944
6945 6.1.7 Callback functions
6946 ------------------------
6947
6948 There are several cases where GnuTLS may need out of band input from
6949 your program.  This is now implemented using some callback functions,
6950 which your program is expected to register.
6951
6952 An example of this type of functions are the push and pull callbacks
6953 which are used to specify the functions that will retrieve and send data
6954 to the transport layer.
6955
6956 'VOID *note gnutls_transport_set_push_function:: (gnutls_session_t SESSION, gnutls_push_func PUSH_FUNC)'
6957 'VOID *note gnutls_transport_set_pull_function:: (gnutls_session_t SESSION, gnutls_pull_func PULL_FUNC)'
6958
6959 Other callback functions may require more complicated input and data to
6960 be allocated.  Such an example is *note
6961 gnutls_srp_set_server_credentials_function::.  All callbacks should
6962 allocate and free memory using 'gnutls_malloc' and 'gnutls_free'.
6963
6964 \1f
6965 File: gnutls.info,  Node: Preparation,  Next: Session initialization,  Prev: Introduction to the library,  Up: How to use GnuTLS in applications
6966
6967 6.2 Preparation
6968 ===============
6969
6970 To use GnuTLS, you have to perform some changes to your sources and your
6971 build system.  The necessary changes are explained in the following
6972 subsections.
6973
6974 * Menu:
6975
6976 * Headers::
6977 * Initialization::
6978 * Version check::
6979 * Building the source::
6980
6981 \1f
6982 File: gnutls.info,  Node: Headers,  Next: Initialization,  Up: Preparation
6983
6984 6.2.1 Headers
6985 -------------
6986
6987 All the data types and functions of the GnuTLS library are defined in
6988 the header file 'gnutls/gnutls.h'.  This must be included in all
6989 programs that make use of the GnuTLS library.
6990
6991 \1f
6992 File: gnutls.info,  Node: Initialization,  Next: Version check,  Prev: Headers,  Up: Preparation
6993
6994 6.2.2 Initialization
6995 --------------------
6996
6997 The GnuTLS library is initialized on load; prior to 3.3.0 was
6998 initialized by calling *note gnutls_global_init::(1).  The
6999 initialization typically enables CPU-specific acceleration, performs any
7000 required precalculations needed, opens any required system devices
7001 (e.g., /dev/urandom on Linux) and initializes subsystems that could be
7002 used later.
7003
7004 The resources allocated by the initialization process will be released
7005 on library deinitialization, or explictly by calling *note
7006 gnutls_global_deinit::.
7007
7008 Note that during initialization file descriptors may be kept open by
7009 GnuTLS (e.g.  /dev/urandom) on library load.  Applications closing all
7010 unknown file descriptors must immediately call *note
7011 gnutls_global_init::, after that, to ensure they don't disrupt GnuTLS'
7012 operation.
7013
7014    ---------- Footnotes ----------
7015
7016    (1) The original behavior of requiring explicit initialization can
7017 obtained by setting the GNUTLS_NO_EXPLICIT_INIT environment variable to
7018 1, or by using the macro GNUTLS_SKIP_GLOBAL_INIT in a global section of
7019 your program.
7020
7021 \1f
7022 File: gnutls.info,  Node: Version check,  Next: Building the source,  Prev: Initialization,  Up: Preparation
7023
7024 6.2.3 Version check
7025 -------------------
7026
7027 It is often desirable to check that the version of 'gnutls' used is
7028 indeed one which fits all requirements.  Even with binary compatibility
7029 new features may have been introduced but due to problem with the
7030 dynamic linker an old version is actually used.  So you may want to
7031 check that the version is okay right after program start-up.  See the
7032 function *note gnutls_check_version::.
7033
7034 On the other hand, it is often desirable to support more than one
7035 versions of the library.  In that case you could utilize compile-time
7036 feature checks using the the 'GNUTLS_VERSION_NUMBER' macro.  For
7037 example, to conditionally add code for GnuTLS 3.2.1 or later, you may
7038 use:
7039      #if GNUTLS_VERSION_NUMBER >= 0x030201
7040       ...
7041      #endif
7042
7043 \1f
7044 File: gnutls.info,  Node: Building the source,  Prev: Version check,  Up: Preparation
7045
7046 6.2.4 Building the source
7047 -------------------------
7048
7049 If you want to compile a source file including the 'gnutls/gnutls.h'
7050 header file, you must make sure that the compiler can find it in the
7051 directory hierarchy.  This is accomplished by adding the path to the
7052 directory in which the header file is located to the compilers include
7053 file search path (via the '-I' option).
7054
7055 However, the path to the include file is determined at the time the
7056 source is configured.  To solve this problem, the library uses the
7057 external package 'pkg-config' that knows the path to the include file
7058 and other configuration options.  The options that need to be added to
7059 the compiler invocation at compile time are output by the '--cflags'
7060 option to 'pkg-config gnutls'.  The following example shows how it can
7061 be used at the command line:
7062
7063      gcc -c foo.c `pkg-config gnutls --cflags`
7064
7065 Adding the output of 'pkg-config gnutls --cflags' to the compilers
7066 command line will ensure that the compiler can find the
7067 'gnutls/gnutls.h' header file.
7068
7069 A similar problem occurs when linking the program with the library.
7070 Again, the compiler has to find the library files.  For this to work,
7071 the path to the library files has to be added to the library search path
7072 (via the '-L' option).  For this, the option '--libs' to 'pkg-config
7073 gnutls' can be used.  For convenience, this option also outputs all
7074 other options that are required to link the program with the library
7075 (for instance, the '-ltasn1' option).  The example shows how to link
7076 'foo.o' with the library to a program 'foo'.
7077
7078      gcc -o foo foo.o `pkg-config gnutls --libs`
7079
7080 Of course you can also combine both examples to a single command by
7081 specifying both options to 'pkg-config':
7082
7083      gcc -o foo foo.c `pkg-config gnutls --cflags --libs`
7084
7085 When a program uses the GNU autoconf system, then the following line or
7086 similar can be used to detect the presence of GnuTLS.
7087
7088      PKG_CHECK_MODULES([LIBGNUTLS], [gnutls >= 3.3.0])
7089
7090      AC_SUBST([LIBGNUTLS_CFLAGS])
7091      AC_SUBST([LIBGNUTLS_LIBS])
7092
7093 \1f
7094 File: gnutls.info,  Node: Session initialization,  Next: Associating the credentials,  Prev: Preparation,  Up: How to use GnuTLS in applications
7095
7096 6.3 Session initialization
7097 ==========================
7098
7099 In the previous sections we have discussed the global initialization
7100 required for GnuTLS as well as the initialization required for each
7101 authentication method's credentials (see *note Authentication::).  In
7102 this section we elaborate on the TLS or DTLS session initiation.  Each
7103 session is initialized using *note gnutls_init:: which among others is
7104 used to specify the type of the connection (server or client), and the
7105 underlying protocol type, i.e., datagram (UDP) or reliable (TCP).
7106
7107  -- Function: int gnutls_init (gnutls_session_t * SESSION, unsigned int
7108           FLAGS)
7109      SESSION: is a pointer to a 'gnutls_session_t' structure.
7110
7111      FLAGS: indicate if this session is to be used for server or client.
7112
7113      This function initializes the current session to null.  Every
7114      session must be initialized before use, so internal structures can
7115      be allocated.  This function allocates structures which can only be
7116      free'd by calling 'gnutls_deinit()' .  Returns 'GNUTLS_E_SUCCESS'
7117      (0) on success.
7118
7119      'flags' can be one of 'GNUTLS_CLIENT' and 'GNUTLS_SERVER' .  For a
7120      DTLS entity, the flags 'GNUTLS_DATAGRAM' and 'GNUTLS_NONBLOCK' are
7121      also available.  The latter flag will enable a non-blocking
7122      operation of the DTLS timers.
7123
7124      The flag 'GNUTLS_NO_REPLAY_PROTECTION' will disable any replay
7125      protection in DTLS mode.  That must only used when replay
7126      protection is achieved using other means.
7127
7128      Note that since version 3.1.2 this function enables some common TLS
7129      extensions such as session tickets and OCSP certificate status
7130      request in client side by default.  To prevent that use the
7131      'GNUTLS_NO_EXTENSIONS' flag.
7132
7133      *Returns:* 'GNUTLS_E_SUCCESS' on success, or an error code.
7134
7135 After the session initialization details on the allowed ciphersuites and
7136 protocol versions should be set using the priority functions such as
7137 *note gnutls_priority_set_direct::.  We elaborate on them in *note
7138 Priority Strings::.  The credentials used for the key exchange method,
7139 such as certificates or usernames and passwords should also be
7140 associated with the session current session using *note
7141 gnutls_credentials_set::.
7142
7143  -- Function: int gnutls_credentials_set (gnutls_session_t SESSION,
7144           gnutls_credentials_type_t TYPE, void * CRED)
7145      SESSION: is a 'gnutls_session_t' structure.
7146
7147      TYPE: is the type of the credentials
7148
7149      CRED: is a pointer to a structure.
7150
7151      Sets the needed credentials for the specified type.  Eg username,
7152      password - or public and private keys etc.  The 'cred' parameter is
7153      a structure that depends on the specified type and on the current
7154      session (client or server).
7155
7156      In order to minimize memory usage, and share credentials between
7157      several threads gnutls keeps a pointer to cred, and not the whole
7158      cred structure.  Thus you will have to keep the structure allocated
7159      until you call 'gnutls_deinit()' .
7160
7161      For 'GNUTLS_CRD_ANON' , 'cred' should be
7162      'gnutls_anon_client_credentials_t' in case of a client.  In case of
7163      a server it should be 'gnutls_anon_server_credentials_t' .
7164
7165      For 'GNUTLS_CRD_SRP' , 'cred' should be
7166      'gnutls_srp_client_credentials_t' in case of a client, and
7167      'gnutls_srp_server_credentials_t' , in case of a server.
7168
7169      For 'GNUTLS_CRD_CERTIFICATE' , 'cred' should be
7170      'gnutls_certificate_credentials_t' .
7171
7172      *Returns:* On success, 'GNUTLS_E_SUCCESS' (0) is returned,
7173      otherwise a negative error code is returned.
7174
7175 \1f
7176 File: gnutls.info,  Node: Associating the credentials,  Next: Setting up the transport layer,  Prev: Session initialization,  Up: How to use GnuTLS in applications
7177
7178 6.4 Associating the credentials
7179 ===============================
7180
7181 * Menu:
7182
7183 * Certificate credentials::
7184 * SRP credentials::
7185 * PSK credentials::
7186 * Anonymous credentials::
7187
7188 Each authentication method is associated with a key exchange method, and
7189 a credentials type.  The contents of the credentials is
7190 method-dependent, e.g.  certificates for certificate authentication and
7191 should be initialized and associated with a session (see *note
7192 gnutls_credentials_set::).  A mapping of the key exchange methods with
7193 the credential types is shown in *note Table 6.2: tab:key-exchange-cred.
7194
7195 Authentication     Key exchange       Client         Server
7196 method                                credentials    credentials
7197                                                      
7198 --------------------------------------------------------------------
7199 Certificate        'KX_RSA',          'CRD_CERTIFICATE''CRD_CERTIFICATE'
7200                    'KX_DHE_RSA',                     
7201                    'KX_DHE_DSS',
7202                    'KX_ECDHE_RSA',
7203                    'KX_ECDHE_ECDSA',
7204                    'KX_RSA_EXPORT'
7205 Password and       'KX_SRP_RSA',      'CRD_SRP'      'CRD_CERTIFICATE',
7206 certificate        'KX_SRP_DSS'                      'CRD_SRP'
7207                                                      
7208 Password           'KX_SRP'           'CRD_SRP'      'CRD_SRP'
7209                                                      
7210 Anonymous          'KX_ANON_DH',      'CRD_ANON'     'CRD_ANON'
7211                    'KX_ANON_ECDH'                    
7212 Pre-shared key     'KX_PSK',          'CRD_PSK'      'CRD_PSK'
7213                    'KX_DHE_PSK',                     
7214                    'KX_ECDHE_PSK'
7215
7216 Table 6.2: Key exchange algorithms and the corresponding credential
7217 types.
7218
7219 \1f
7220 File: gnutls.info,  Node: Certificate credentials,  Next: SRP credentials,  Up: Associating the credentials
7221
7222 6.4.1 Certificates
7223 ------------------
7224
7225 Server certificate authentication
7226 .................................
7227
7228 When using certificates the server is required to have at least one
7229 certificate and private key pair.  Clients may not hold such a pair, but
7230 a server could require it.  In this section we discuss general issues
7231 applying to both client and server certificates.  The next section will
7232 elaborate on issues arising from client authentication only.
7233
7234 'INT *note gnutls_certificate_allocate_credentials:: (gnutls_certificate_credentials_t * RES)'
7235 'VOID *note gnutls_certificate_free_credentials:: (gnutls_certificate_credentials_t SC)'
7236
7237 After the credentials structures are initialized, the certificate and
7238 key pair must be loaded.  This occurs before any TLS session is
7239 initialized, and the same structures are reused for multiple sessions.
7240 Depending on the certificate type different loading functions are
7241 available, as shown below.  For X.509 certificates, the functions will
7242 accept and use a certificate chain that leads to a trusted authority.
7243 The certificate chain must be ordered in such way that every certificate
7244 certifies the one before it.  The trusted authority's certificate need
7245 not to be included since the peer should possess it already.
7246
7247 '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)'
7248 '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)'
7249 '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)'
7250
7251 '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)'
7252 'INT *note gnutls_certificate_set_openpgp_key:: (gnutls_certificate_credentials_t RES, gnutls_openpgp_crt_t CRT, gnutls_openpgp_privkey_t PKEY)'
7253 '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)'
7254
7255 Note however, that since functions like *note
7256 gnutls_certificate_set_x509_key_file2:: may accept URLs that specify
7257 objects stored in token, another important function is *note
7258 gnutls_certificate_set_pin_function::.  That allows setting a callback
7259 function to retrieve a PIN if the input keys are protected by PIN by the
7260 token.
7261
7262  -- Function: void gnutls_certificate_set_pin_function
7263           (gnutls_certificate_credentials_t CRED, gnutls_pin_callback_t
7264           FN, void * USERDATA)
7265      CRED: is a 'gnutls_certificate_credentials_t' structure.
7266
7267      FN: A PIN callback
7268
7269      USERDATA: Data to be passed in the callback
7270
7271      This function will set a callback function to be used when required
7272      to access a protected object.  This function overrides any other
7273      global PIN functions.
7274
7275      Note that this function must be called right after initialization
7276      to have effect.
7277
7278      *Since:* 3.1.0
7279
7280 If the imported keys and certificates need to be accessed before any TLS
7281 session is established, it is convenient to use *note
7282 gnutls_certificate_set_key:: in combination with *note
7283 gnutls_pcert_import_x509_raw:: and *note
7284 gnutls_privkey_import_x509_raw::.
7285
7286  -- Function: int gnutls_certificate_set_key
7287           (gnutls_certificate_credentials_t RES, const char ** NAMES,
7288           int NAMES_SIZE, gnutls_pcert_st * PCERT_LIST, int
7289           PCERT_LIST_SIZE, gnutls_privkey_t KEY)
7290      RES: is a 'gnutls_certificate_credentials_t' structure.
7291
7292      NAMES: is an array of DNS name of the certificate (NULL if none)
7293
7294      NAMES_SIZE: holds the size of the names list
7295
7296      PCERT_LIST: contains a certificate list (path) for the specified
7297      private key
7298
7299      PCERT_LIST_SIZE: holds the size of the certificate list
7300
7301      KEY: is a 'gnutls_privkey_t' key
7302
7303      This function sets a certificate/private key pair in the
7304      gnutls_certificate_credentials_t structure.  This function may be
7305      called more than once, in case multiple keys/certificates exist for
7306      the server.  For clients that wants to send more than its own end
7307      entity certificate (e.g., also an intermediate CA cert) then put
7308      the certificate chain in 'pcert_list' .
7309
7310      Note that the 'pcert_list' and 'key' will become part of the
7311      credentials structure and must not be deallocated.  They will be
7312      automatically deallocated when the 'res' structure is
7313      deinitialized.
7314
7315      If that function fails to load the 'res' structure is at an
7316      undefined state, it must not be reused to load other keys or
7317      certificates.
7318
7319      *Returns:* 'GNUTLS_E_SUCCESS' (0) on success, or a negative error
7320      code.
7321
7322      *Since:* 3.0
7323
7324 If multiple certificates are used with the functions above each client's
7325 request will be served with the certificate that matches the requested
7326 name (see *note Server name indication::).
7327
7328 As an alternative to loading from files or buffers, a callback may be
7329 used for the server or the client to specify the certificate and the key
7330 at the handshake time.  In that case a certificate should be selected
7331 according the peer's signature algorithm preferences.  To get those
7332 preferences use *note gnutls_sign_algorithm_get_requested::.  Both
7333 functions are shown below.
7334
7335 'VOID *note gnutls_certificate_set_retrieve_function:: (gnutls_certificate_credentials_t CRED, gnutls_certificate_retrieve_function * FUNC)'
7336 'VOID *note gnutls_certificate_set_retrieve_function2:: (gnutls_certificate_credentials_t CRED, gnutls_certificate_retrieve_function2 * FUNC)'
7337 'INT *note gnutls_sign_algorithm_get_requested:: (gnutls_session_t SESSION, size_t INDX, gnutls_sign_algorithm_t * ALGO)'
7338 c The functions above do not handle the requested server name
7339 automatically.  A server would need to check the name requested by the
7340 client using *note gnutls_server_name_get::, and serve the appropriate
7341 certificate.  Note that some of these functions require the
7342 'gnutls_pcert_st' structure to be filled in.  Helper functions to fill
7343 in the structure are listed below.
7344
7345 typedef struct gnutls_pcert_st
7346 {
7347   gnutls_pubkey_t pubkey;
7348   gnutls_datum_t cert;
7349   gnutls_certificate_type_t type;
7350 } gnutls_pcert_st;
7351
7352 'INT *note gnutls_pcert_import_x509:: (gnutls_pcert_st * PCERT, gnutls_x509_crt_t CRT, unsigned int FLAGS)'
7353 'INT *note gnutls_pcert_import_openpgp:: (gnutls_pcert_st * PCERT, gnutls_openpgp_crt_t CRT, unsigned int FLAGS)'
7354 '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)'
7355 '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)'
7356 'VOID *note gnutls_pcert_deinit:: (gnutls_pcert_st * PCERT)'
7357
7358 In a handshake, the negotiated cipher suite depends on the certificate's
7359 parameters, so some key exchange methods might not be available with all
7360 certificates.  GnuTLS will disable ciphersuites that are not compatible
7361 with the key, or the enabled authentication methods.  For example keys
7362 marked as sign-only, will not be able to access the plain RSA
7363 ciphersuites, that require decryption.  It is not recommended to use RSA
7364 keys for both signing and encryption.  If possible use a different key
7365 for the 'DHE-RSA' which uses signing and 'RSA' that requires decryption.
7366 All the key exchange methods shown in *note Table 4.1: tab:key-exchange.
7367 are available in certificate authentication.
7368
7369 Client certificate authentication
7370 .................................
7371
7372 If a certificate is to be requested from the client during the
7373 handshake, the server will send a certificate request message.  This
7374 behavior is controlled *note gnutls_certificate_server_set_request::.
7375 The request contains a list of the acceptable by the server certificate
7376 signers.  This list is constructed using the trusted certificate
7377 authorities of the server.  In cases where the server supports a large
7378 number of certificate authorities it makes sense not to advertise all of
7379 the names to save bandwidth.  That can be controlled using the function
7380 *note gnutls_certificate_send_x509_rdn_sequence::.  This however will
7381 have the side-effect of not restricting the client to certificates
7382 signed by server's acceptable signers.
7383
7384  -- Function: void gnutls_certificate_server_set_request
7385           (gnutls_session_t SESSION, gnutls_certificate_request_t REQ)
7386      SESSION: is a 'gnutls_session_t' structure.
7387
7388      REQ: is one of GNUTLS_CERT_REQUEST, GNUTLS_CERT_REQUIRE
7389
7390      This function specifies if we (in case of a server) are going to
7391      send a certificate request message to the client.  If 'req' is
7392      GNUTLS_CERT_REQUIRE then the server will return an error if the
7393      peer does not provide a certificate.  If you do not call this
7394      function then the client will not be asked to send a certificate.
7395
7396  -- Function: void gnutls_certificate_send_x509_rdn_sequence
7397           (gnutls_session_t SESSION, int STATUS)
7398      SESSION: is a pointer to a 'gnutls_session_t' structure.
7399
7400      STATUS: is 0 or 1
7401
7402      If status is non zero, this function will order gnutls not to send
7403      the rdnSequence in the certificate request message.  That is the
7404      server will not advertise its trusted CAs to the peer.  If status
7405      is zero then the default behaviour will take effect, which is to
7406      advertise the server's trusted CAs.
7407
7408      This function has no effect in clients, and in authentication
7409      methods other than certificate with X.509 certificates.
7410
7411 Client or server certificate verification
7412 .........................................
7413
7414 Certificate verification is possible by loading the trusted authorities
7415 into the credentials structure by using the following functions,
7416 applicable to X.509 and OpenPGP certificates.
7417
7418 'INT *note gnutls_certificate_set_x509_system_trust:: (gnutls_certificate_credentials_t CRED)'
7419 'INT *note gnutls_certificate_set_x509_trust_file:: (gnutls_certificate_credentials_t CRED, const char * CAFILE, gnutls_x509_crt_fmt_t TYPE)'
7420 'INT *note gnutls_certificate_set_openpgp_keyring_file:: (gnutls_certificate_credentials_t C, const char * FILE, gnutls_openpgp_crt_fmt_t FORMAT)'
7421
7422 The peer's certificate is not automatically verified and one must call
7423 *note gnutls_certificate_verify_peers3:: after a successful handshake to
7424 verify the certificate's signature and the owner of the certificate.
7425 The verification status returned can be printed using *note
7426 gnutls_certificate_verification_status_print::.
7427
7428 Alternatively the verification can occur during the handshake by using
7429 *note gnutls_certificate_set_verify_function::.
7430
7431 The functions above provide a brief verification output.  If a detailed
7432 output is required one should call *note gnutls_certificate_get_peers::
7433 to obtain the raw certificate of the peer and verify it using the
7434 functions discussed in *note X.509 certificates::.
7435
7436  -- Function: int gnutls_certificate_verify_peers3 (gnutls_session_t
7437           SESSION, const char * HOSTNAME, unsigned int * STATUS)
7438      SESSION: is a gnutls session
7439
7440      HOSTNAME: is the expected name of the peer; may be 'NULL'
7441
7442      STATUS: is the output of the verification
7443
7444      This function will verify the peer's certificate and store the
7445      status in the 'status' variable as a bitwise or'd
7446      gnutls_certificate_status_t values or zero if the certificate is
7447      trusted.  Note that value in 'status' is set only when the return
7448      value of this function is success (i.e, failure to trust a
7449      certificate does not imply a negative return value).  The default
7450      verification flags used by this function can be overridden using
7451      'gnutls_certificate_set_verify_flags()' .  See the documentation of
7452      'gnutls_certificate_verify_peers2()' for details in the
7453      verification process.
7454
7455      If the 'hostname' provided is non-NULL then this function will
7456      compare the hostname in the certificate against the given.  The
7457      comparison will be accurate for ascii names; non-ascii names are
7458      compared byte-by-byte.  If names do not match the
7459      'GNUTLS_CERT_UNEXPECTED_OWNER' status flag will be set.
7460
7461      In order to verify the purpose of the end-certificate (by checking
7462      the extended key usage), use 'gnutls_certificate_verify_peers()' .
7463
7464      *Returns:* a negative error code on error and 'GNUTLS_E_SUCCESS'
7465      (0) when the peer's certificate was successfully parsed,
7466      irrespective of whether it was verified.
7467
7468      *Since:* 3.1.4
7469
7470  -- Function: void gnutls_certificate_set_verify_function
7471           (gnutls_certificate_credentials_t CRED,
7472           gnutls_certificate_verify_function * FUNC)
7473      CRED: is a 'gnutls_certificate_credentials_t' structure.
7474
7475      FUNC: is the callback function
7476
7477      This function sets a callback to be called when peer's certificate
7478      has been received in order to verify it on receipt rather than
7479      doing after the handshake is completed.
7480
7481      The callback's function prototype is: int
7482      (*callback)(gnutls_session_t);
7483
7484      If the callback function is provided then gnutls will call it, in
7485      the handshake, just after the certificate message has been
7486      received.  To verify or obtain the certificate the
7487      'gnutls_certificate_verify_peers2()' ,
7488      'gnutls_certificate_type_get()' , 'gnutls_certificate_get_peers()'
7489      functions can be used.
7490
7491      The callback function should return 0 for the handshake to continue
7492      or non-zero to terminate.
7493
7494      *Since:* 2.10.0
7495