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