Fix CVE-2017-6891 in minitasn1 code
[platform/upstream/gnutls.git] / lib / gnutls_cert.c
1 /*
2  * Copyright (C) 2001-2012 Free Software Foundation, Inc.
3  *
4  * Author: Nikos Mavrogiannopoulos
5  *
6  * This file is part of GnuTLS.
7  *
8  * The GnuTLS is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * as published by the Free Software Foundation; either version 2.1 of
11  * the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>
20  *
21  */
22
23 /* Some of the stuff needed for Certificate authentication is contained
24  * in this file.
25  */
26
27 #include <gnutls_int.h>
28 #include <gnutls_errors.h>
29 #include <auth/cert.h>
30 #include <gnutls_datum.h>
31 #include <gnutls_mpi.h>
32 #include <gnutls_global.h>
33 #include <algorithms.h>
34 #include <gnutls_dh.h>
35 #include <gnutls_str.h>
36 #include <gnutls_state.h>
37 #include <gnutls_auth.h>
38 #include <gnutls_x509.h>
39 #include <gnutls_str_array.h>
40 #include <x509/verify-high.h>
41 #include "x509/x509_int.h"
42 #ifdef ENABLE_OPENPGP
43 #include "openpgp/gnutls_openpgp.h"
44 #endif
45 #include "gettext.h"
46 #define _(String) dgettext (PACKAGE, String)
47
48 /**
49  * gnutls_certificate_free_keys:
50  * @sc: is a #gnutls_certificate_credentials_t structure.
51  *
52  * This function will delete all the keys and the certificates associated
53  * with the given credentials. This function must not be called when a
54  * TLS negotiation that uses the credentials is in progress.
55  *
56  **/
57 void gnutls_certificate_free_keys(gnutls_certificate_credentials_t sc)
58 {
59         unsigned i, j;
60
61         for (i = 0; i < sc->ncerts; i++) {
62                 for (j = 0; j < sc->certs[i].cert_list_length; j++) {
63                         gnutls_pcert_deinit(&sc->certs[i].cert_list[j]);
64                 }
65                 gnutls_free(sc->certs[i].cert_list);
66                 _gnutls_str_array_clear(&sc->certs[i].names);
67         }
68
69         gnutls_free(sc->certs);
70         sc->certs = NULL;
71
72         for (i = 0; i < sc->ncerts; i++) {
73                 gnutls_privkey_deinit(sc->pkey[i]);
74         }
75
76         gnutls_free(sc->pkey);
77         sc->pkey = NULL;
78
79         sc->ncerts = 0;
80 }
81
82 /**
83  * gnutls_certificate_free_cas:
84  * @sc: is a #gnutls_certificate_credentials_t structure.
85  *
86  * This function will delete all the CAs associated with the given
87  * credentials. Servers that do not use
88  * gnutls_certificate_verify_peers2() may call this to save some
89  * memory.
90  **/
91 void gnutls_certificate_free_cas(gnutls_certificate_credentials_t sc)
92 {
93         /* FIXME: do nothing for now */
94         return;
95 }
96
97 /**
98  * gnutls_certificate_get_issuer:
99  * @sc: is a #gnutls_certificate_credentials_t structure.
100  * @cert: is the certificate to find issuer for
101  * @issuer: Will hold the issuer if any. Should be treated as constant.
102  * @flags: Use zero or %GNUTLS_TL_GET_COPY
103  *
104  * This function will return the issuer of a given certificate.
105  * As with gnutls_x509_trust_list_get_issuer() this function requires
106  * the %GNUTLS_TL_GET_COPY flag in order to operate with PKCS #11 trust
107  * lists. In that case the issuer must be freed using gnutls_x509_crt_deinit().
108  *
109  * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
110  *   negative error value.
111  *
112  * Since: 3.0
113  **/
114 int
115 gnutls_certificate_get_issuer(gnutls_certificate_credentials_t sc,
116                               gnutls_x509_crt_t cert,
117                               gnutls_x509_crt_t * issuer,
118                               unsigned int flags)
119 {
120         return gnutls_x509_trust_list_get_issuer(sc->tlist, cert, issuer,
121                                                  flags);
122 }
123
124 /**
125  * gnutls_certificate_get_crt_raw:
126  * @sc: is a #gnutls_certificate_credentials_t structure.
127  * @idx1: the index of the certificate if multiple are present
128  * @idx2: the index in the certificate list. Zero gives the server's certificate.
129  * @cert: Will hold the DER encoded certificate.
130  *
131  * This function will return the DER encoded certificate of the
132  * server or any other certificate on its certificate chain (based on @idx2).
133  * The returned data should be treated as constant and only accessible during the lifetime
134  * of @sc.
135  *
136  * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
137  *   negative error value. In case the indexes are out of bounds %GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE
138  *   is returned.
139  *
140  * Since: 3.2.5
141  **/
142 int
143 gnutls_certificate_get_crt_raw(gnutls_certificate_credentials_t sc,
144                                unsigned idx1,
145                                unsigned idx2, gnutls_datum_t * cert)
146 {
147         if (idx1 >= sc->ncerts)
148                 return
149                     gnutls_assert_val
150                     (GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
151
152         if (idx2 >= sc->certs[idx1].cert_list_length)
153                 return
154                     gnutls_assert_val
155                     (GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE);
156
157         cert->data = sc->certs[idx1].cert_list[idx2].cert.data;
158         cert->size = sc->certs[idx1].cert_list[idx2].cert.size;
159
160         return 0;
161 }
162
163 /**
164  * gnutls_certificate_free_ca_names:
165  * @sc: is a #gnutls_certificate_credentials_t structure.
166  *
167  * This function will delete all the CA name in the given
168  * credentials. Clients may call this to save some memory since in
169  * client side the CA names are not used. Servers might want to use
170  * this function if a large list of trusted CAs is present and
171  * sending the names of it would just consume bandwidth without providing 
172  * information to client.
173  *
174  * CA names are used by servers to advertise the CAs they support to
175  * clients.
176  **/
177 void gnutls_certificate_free_ca_names(gnutls_certificate_credentials_t sc)
178 {
179         _gnutls_free_datum(&sc->tlist->x509_rdn_sequence);
180 }
181
182
183 /**
184  * gnutls_certificate_free_credentials:
185  * @sc: is a #gnutls_certificate_credentials_t structure.
186  *
187  * This structure is complex enough to manipulate directly thus this
188  * helper function is provided in order to free (deallocate) it.
189  *
190  * This function does not free any temporary parameters associated
191  * with this structure (ie RSA and DH parameters are not freed by this
192  * function).
193  **/
194 void
195 gnutls_certificate_free_credentials(gnutls_certificate_credentials_t sc)
196 {
197         gnutls_x509_trust_list_deinit(sc->tlist, 1);
198         gnutls_certificate_free_keys(sc);
199         gnutls_free(sc->ocsp_response_file);
200         memset(sc->pin_tmp, 0, sizeof(sc->pin_tmp));
201 #ifdef ENABLE_OPENPGP
202         gnutls_openpgp_keyring_deinit(sc->keyring);
203 #endif
204
205         gnutls_free(sc);
206 }
207
208
209 /**
210  * gnutls_certificate_allocate_credentials:
211  * @res: is a pointer to a #gnutls_certificate_credentials_t structure.
212  *
213  * This structure is complex enough to manipulate directly thus this
214  * helper function is provided in order to allocate it.
215  *
216  * Returns: %GNUTLS_E_SUCCESS on success, or an error code.
217  **/
218 int
219 gnutls_certificate_allocate_credentials(gnutls_certificate_credentials_t *
220                                         res)
221 {
222         int ret;
223
224         *res = gnutls_calloc(1, sizeof(certificate_credentials_st));
225
226         if (*res == NULL)
227                 return GNUTLS_E_MEMORY_ERROR;
228
229         ret = gnutls_x509_trust_list_init(&(*res)->tlist, 0);
230         if (ret < 0) {
231                 gnutls_assert();
232                 gnutls_free(*res);
233                 return GNUTLS_E_MEMORY_ERROR;
234         }
235         (*res)->verify_bits = DEFAULT_MAX_VERIFY_BITS;
236         (*res)->verify_depth = DEFAULT_MAX_VERIFY_DEPTH;
237
238         return 0;
239 }
240
241
242 /* returns the KX algorithms that are supported by a
243  * certificate. (Eg a certificate with RSA params, supports
244  * GNUTLS_KX_RSA algorithm).
245  * This function also uses the KeyUsage field of the certificate
246  * extensions in order to disable unneded algorithms.
247  */
248 int
249 _gnutls_selected_cert_supported_kx(gnutls_session_t session,
250                                    gnutls_kx_algorithm_t * alg,
251                                    int *alg_size)
252 {
253         unsigned kx;
254         gnutls_pk_algorithm_t pk, cert_pk;
255         gnutls_pcert_st *cert;
256         int i;
257
258         if (session->internals.selected_cert_list_length == 0) {
259                 *alg_size = 0;
260                 return 0;
261         }
262
263         cert = &session->internals.selected_cert_list[0];
264         cert_pk = gnutls_pubkey_get_pk_algorithm(cert->pubkey, NULL);
265         i = 0;
266
267         for (kx = 0; kx < MAX_ALGOS; kx++) {
268                 pk = _gnutls_map_pk_get_pk(kx);
269                 if (pk == cert_pk) {
270                         /* then check key usage */
271                         if (_gnutls_check_key_usage(cert, kx) == 0) {
272                                 alg[i] = kx;
273                                 i++;
274
275                                 if (i > *alg_size)
276                                         return
277                                             gnutls_assert_val
278                                             (GNUTLS_E_INTERNAL_ERROR);
279                         }
280                 }
281         }
282
283         if (i == 0) {
284                 gnutls_assert();
285                 return GNUTLS_E_INVALID_REQUEST;
286         }
287
288         *alg_size = i;
289
290         return 0;
291 }
292
293
294 /**
295  * gnutls_certificate_server_set_request:
296  * @session: is a #gnutls_session_t structure.
297  * @req: is one of GNUTLS_CERT_REQUEST, GNUTLS_CERT_REQUIRE
298  *
299  * This function specifies if we (in case of a server) are going to
300  * send a certificate request message to the client. If @req is
301  * GNUTLS_CERT_REQUIRE then the server will return an error if the
302  * peer does not provide a certificate. If you do not call this
303  * function then the client will not be asked to send a certificate.
304  **/
305 void
306 gnutls_certificate_server_set_request(gnutls_session_t session,
307                                       gnutls_certificate_request_t req)
308 {
309         session->internals.send_cert_req = req;
310 }
311
312 /**
313  * gnutls_certificate_client_set_retrieve_function:
314  * @cred: is a #gnutls_certificate_credentials_t structure.
315  * @func: is the callback function
316  *
317  * This function sets a callback to be called in order to retrieve the
318  * certificate to be used in the handshake.
319  * You are advised to use gnutls_certificate_set_retrieve_function2() because it
320  * is much more efficient in the processing it requires from gnutls.
321  *
322  * The callback's function prototype is:
323  * int (*callback)(gnutls_session_t, const gnutls_datum_t* req_ca_dn, int nreqs,
324  * const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_retr_st* st);
325  *
326  * @req_ca_cert is only used in X.509 certificates.
327  * Contains a list with the CA names that the server considers trusted.
328  * Normally we should send a certificate that is signed
329  * by one of these CAs. These names are DER encoded. To get a more
330  * meaningful value use the function gnutls_x509_rdn_get().
331  *
332  * @pk_algos contains a list with server's acceptable signature algorithms.
333  * The certificate returned should support the server's given algorithms.
334  *
335  * @st should contain the certificates and private keys.
336  *
337  * If the callback function is provided then gnutls will call it, in the
338  * handshake, if a certificate is requested by the server (and after the 
339  * certificate request message has been received).
340  *
341  * The callback function should set the certificate list to be sent,
342  * and return 0 on success. If no certificate was selected then the
343  * number of certificates should be set to zero. The value (-1)
344  * indicates error and the handshake will be terminated.
345  **/
346 void gnutls_certificate_client_set_retrieve_function
347     (gnutls_certificate_credentials_t cred,
348      gnutls_certificate_client_retrieve_function * func) {
349         cred->client_get_cert_callback = func;
350 }
351
352 /**
353  * gnutls_certificate_server_set_retrieve_function:
354  * @cred: is a #gnutls_certificate_credentials_t structure.
355  * @func: is the callback function
356  *
357  * This function sets a callback to be called in order to retrieve the
358  * certificate to be used in the handshake.
359  * You are advised to use gnutls_certificate_set_retrieve_function2() because it
360  * is much more efficient in the processing it requires from gnutls.
361  *
362  * The callback's function prototype is:
363  * int (*callback)(gnutls_session_t, gnutls_retr_st* st);
364  *
365  * @st should contain the certificates and private keys.
366  *
367  * If the callback function is provided then gnutls will call it, in the
368  * handshake, after the certificate request message has been received.
369  *
370  * The callback function should set the certificate list to be sent, and
371  * return 0 on success.  The value (-1) indicates error and the handshake
372  * will be terminated.
373  **/
374 void gnutls_certificate_server_set_retrieve_function
375     (gnutls_certificate_credentials_t cred,
376      gnutls_certificate_server_retrieve_function * func) {
377         cred->server_get_cert_callback = func;
378 }
379
380 /**
381  * gnutls_certificate_set_retrieve_function:
382  * @cred: is a #gnutls_certificate_credentials_t structure.
383  * @func: is the callback function
384  *
385  * This function sets a callback to be called in order to retrieve the
386  * certificate to be used in the handshake. You are advised
387  * to use gnutls_certificate_set_retrieve_function2() because it
388  * is much more efficient in the processing it requires from gnutls.
389  *
390  * The callback's function prototype is:
391  * int (*callback)(gnutls_session_t, const gnutls_datum_t* req_ca_dn, int nreqs,
392  * const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_retr2_st* st);
393  *
394  * @req_ca_dn is only used in X.509 certificates.
395  * Contains a list with the CA names that the server considers trusted.
396  * Normally we should send a certificate that is signed
397  * by one of these CAs. These names are DER encoded. To get a more
398  * meaningful value use the function gnutls_x509_rdn_get().
399  *
400  * @pk_algos contains a list with server's acceptable signature algorithms.
401  * The certificate returned should support the server's given algorithms.
402  *
403  * @st should contain the certificates and private keys.
404  *
405  * If the callback function is provided then gnutls will call it, in the
406  * handshake, after the certificate request message has been received.
407  *
408  * In server side pk_algos and req_ca_dn are NULL.
409  *
410  * The callback function should set the certificate list to be sent,
411  * and return 0 on success. If no certificate was selected then the
412  * number of certificates should be set to zero. The value (-1)
413  * indicates error and the handshake will be terminated.
414  *
415  * Since: 3.0
416  **/
417 void gnutls_certificate_set_retrieve_function
418     (gnutls_certificate_credentials_t cred,
419      gnutls_certificate_retrieve_function * func) {
420         cred->get_cert_callback = func;
421 }
422
423 /**
424  * gnutls_certificate_set_retrieve_function2:
425  * @cred: is a #gnutls_certificate_credentials_t structure.
426  * @func: is the callback function
427  *
428  * This function sets a callback to be called in order to retrieve the
429  * certificate to be used in the handshake.
430  *
431  * The callback's function prototype is:
432  * int (*callback)(gnutls_session_t, const gnutls_datum_t* req_ca_dn, int nreqs,
433  * const gnutls_pk_algorithm_t* pk_algos, int pk_algos_length, gnutls_pcert_st** pcert,
434  * unsigned int *pcert_length, gnutls_privkey_t * pkey);
435  *
436  * @req_ca_dn is only used in X.509 certificates.
437  * Contains a list with the CA names that the server considers trusted.
438  * Normally we should send a certificate that is signed
439  * by one of these CAs. These names are DER encoded. To get a more
440  * meaningful value use the function gnutls_x509_rdn_get().
441  *
442  * @pk_algos contains a list with server's acceptable signature algorithms.
443  * The certificate returned should support the server's given algorithms.
444  *
445  * @pcert should contain a single certificate and public key or a list of them.
446  *
447  * @pcert_length is the size of the previous list.
448  *
449  * @pkey is the private key.
450  *
451  * If the callback function is provided then gnutls will call it, in the
452  * handshake, after the certificate request message has been received.
453  * All the provided by the callback values will not be released or
454  * modified by gnutls.
455  *
456  * In server side pk_algos and req_ca_dn are NULL.
457  *
458  * The callback function should set the certificate list to be sent,
459  * and return 0 on success. If no certificate was selected then the
460  * number of certificates should be set to zero. The value (-1)
461  * indicates error and the handshake will be terminated.
462  *
463  * Since: 3.0
464  **/
465 void gnutls_certificate_set_retrieve_function2
466     (gnutls_certificate_credentials_t cred,
467      gnutls_certificate_retrieve_function2 * func) {
468         cred->get_cert_callback2 = func;
469 }
470
471 /**
472  * gnutls_certificate_set_verify_function:
473  * @cred: is a #gnutls_certificate_credentials_t structure.
474  * @func: is the callback function
475  *
476  * This function sets a callback to be called when peer's certificate
477  * has been received in order to verify it on receipt rather than
478  * doing after the handshake is completed.
479  *
480  * The callback's function prototype is:
481  * int (*callback)(gnutls_session_t);
482  *
483  * If the callback function is provided then gnutls will call it, in the
484  * handshake, just after the certificate message has been received.
485  * To verify or obtain the certificate the gnutls_certificate_verify_peers2(),
486  * gnutls_certificate_type_get(), gnutls_certificate_get_peers() functions
487  * can be used.
488  *
489  * The callback function should return 0 for the handshake to continue
490  * or non-zero to terminate.
491  *
492  * Since: 2.10.0
493  **/
494 void
495  gnutls_certificate_set_verify_function
496     (gnutls_certificate_credentials_t cred,
497      gnutls_certificate_verify_function * func) {
498         cred->verify_callback = func;
499 }
500
501 /*-
502  * _gnutls_x509_extract_certificate_activation_time - return the peer's certificate activation time
503  * @cert: should contain an X.509 DER encoded certificate
504  *
505  * This function will return the certificate's activation time in UNIX time
506  * (ie seconds since 00:00:00 UTC January 1, 1970).
507  *
508  * Returns a (time_t) -1 in case of an error.
509  *
510  -*/
511 static time_t
512 _gnutls_x509_get_raw_crt_activation_time(const gnutls_datum_t * cert)
513 {
514         gnutls_x509_crt_t xcert;
515         time_t result;
516
517         result = gnutls_x509_crt_init(&xcert);
518         if (result < 0)
519                 return (time_t) - 1;
520
521         result = gnutls_x509_crt_import(xcert, cert, GNUTLS_X509_FMT_DER);
522         if (result < 0) {
523                 gnutls_x509_crt_deinit(xcert);
524                 return (time_t) - 1;
525         }
526
527         result = gnutls_x509_crt_get_activation_time(xcert);
528
529         gnutls_x509_crt_deinit(xcert);
530
531         return result;
532 }
533
534 /*-
535  * gnutls_x509_extract_certificate_expiration_time:
536  * @cert: should contain an X.509 DER encoded certificate
537  *
538  * This function will return the certificate's expiration time in UNIX
539  * time (ie seconds since 00:00:00 UTC January 1, 1970).  Returns a
540  *
541  * (time_t) -1 in case of an error.
542  *
543  -*/
544 static time_t
545 _gnutls_x509_get_raw_crt_expiration_time(const gnutls_datum_t * cert)
546 {
547         gnutls_x509_crt_t xcert;
548         time_t result;
549
550         result = gnutls_x509_crt_init(&xcert);
551         if (result < 0)
552                 return (time_t) - 1;
553
554         result = gnutls_x509_crt_import(xcert, cert, GNUTLS_X509_FMT_DER);
555         if (result < 0) {
556                 gnutls_x509_crt_deinit(xcert);
557                 return (time_t) - 1;
558         }
559
560         result = gnutls_x509_crt_get_expiration_time(xcert);
561
562         gnutls_x509_crt_deinit(xcert);
563
564         return result;
565 }
566
567 #ifdef ENABLE_OPENPGP
568 /*-
569  * _gnutls_openpgp_crt_verify_peers - return the peer's certificate status
570  * @session: is a gnutls session
571  *
572  * This function will try to verify the peer's certificate and return its status (TRUSTED, INVALID etc.).
573  * Returns a negative error code in case of an error, or GNUTLS_E_NO_CERTIFICATE_FOUND if no certificate was sent.
574  -*/
575 static int
576 _gnutls_openpgp_crt_verify_peers(gnutls_session_t session,
577                                  const char *hostname,
578                                  unsigned int *status)
579 {
580         cert_auth_info_t info;
581         gnutls_certificate_credentials_t cred;
582         int peer_certificate_list_size, ret;
583         unsigned int verify_flags;
584
585         CHECK_AUTH(GNUTLS_CRD_CERTIFICATE, GNUTLS_E_INVALID_REQUEST);
586
587         info = _gnutls_get_auth_info(session, GNUTLS_CRD_CERTIFICATE);
588         if (info == NULL)
589                 return GNUTLS_E_INVALID_REQUEST;
590
591         cred = (gnutls_certificate_credentials_t)
592             _gnutls_get_cred(session, GNUTLS_CRD_CERTIFICATE);
593         if (cred == NULL) {
594                 gnutls_assert();
595                 return GNUTLS_E_INSUFFICIENT_CREDENTIALS;
596         }
597
598         if (info->raw_certificate_list == NULL || info->ncerts == 0) {
599                 gnutls_assert();
600                 return GNUTLS_E_NO_CERTIFICATE_FOUND;
601         }
602
603         verify_flags = cred->verify_flags | session->internals.priorities.additional_verify_flags;
604
605         /* generate a list of gnutls_certs based on the auth info
606          * raw certs.
607          */
608         peer_certificate_list_size = info->ncerts;
609
610         if (peer_certificate_list_size != 1) {
611                 gnutls_assert();
612                 return GNUTLS_E_INTERNAL_ERROR;
613         }
614
615         /* Verify certificate 
616          */
617         ret =
618             _gnutls_openpgp_verify_key(cred, hostname,
619                                        &info->raw_certificate_list[0],
620                                        peer_certificate_list_size,
621                                        verify_flags,
622                                        status);
623
624         if (ret < 0) {
625                 gnutls_assert();
626                 return ret;
627         }
628
629         return 0;
630 }
631 #endif
632
633 /**
634  * gnutls_certificate_verify_peers2:
635  * @session: is a gnutls session
636  * @status: is the output of the verification
637  *
638  * This function will verify the peer's certificate and store
639  * the status in the @status variable as a bitwise or'd gnutls_certificate_status_t
640  * values or zero if the certificate is trusted. Note that value in @status
641  * is set only when the return value of this function is success (i.e, failure 
642  * to trust a certificate does not imply a negative return value).
643  * The default verification flags used by this function can be overridden
644  * using gnutls_certificate_set_verify_flags().
645  *
646  * This function will take into account the OCSP Certificate Status TLS extension,
647  * as well as the following X.509 certificate extensions: Name Constraints,
648  * Key Usage, and Basic Constraints (pathlen).
649  * 
650  * To avoid denial of service attacks some
651  * default upper limits regarding the certificate key size and chain
652  * size are set. To override them use gnutls_certificate_set_verify_limits().
653  *
654  * Note that you must also check the peer's name in order to check if
655  * the verified certificate belongs to the actual peer, see gnutls_x509_crt_check_hostname(),
656  * or use gnutls_certificate_verify_peers3().
657  *
658  * Returns: a negative error code on error and %GNUTLS_E_SUCCESS (0)
659  * when the peer's certificate was successfully parsed, irrespective of whether
660  * it was verified.
661  **/
662 int
663 gnutls_certificate_verify_peers2(gnutls_session_t session,
664                                  unsigned int *status)
665 {
666         return gnutls_certificate_verify_peers(session, NULL, 0, status);
667 }
668
669 /**
670  * gnutls_certificate_verify_peers3:
671  * @session: is a gnutls session
672  * @hostname: is the expected name of the peer; may be %NULL
673  * @status: is the output of the verification
674  *
675  * This function will verify the peer's certificate and store the
676  * status in the @status variable as a bitwise or'd gnutls_certificate_status_t
677  * values or zero if the certificate is trusted. Note that value in @status
678  * is set only when the return value of this function is success (i.e, failure 
679  * to trust a certificate does not imply a negative return value).
680  * The default verification flags used by this function can be overridden
681  * using gnutls_certificate_set_verify_flags(). See the documentation
682  * of gnutls_certificate_verify_peers2() for details in the verification process.
683  *
684  * If the @hostname provided is non-NULL then this function will compare
685  * the hostname in the certificate against the given. The comparison will
686  * be accurate for ascii names; non-ascii names are compared byte-by-byte. 
687  * If names do not match the %GNUTLS_CERT_UNEXPECTED_OWNER status flag will be set.
688  *
689  * In order to verify the purpose of the end-certificate (by checking the extended
690  * key usage), use gnutls_certificate_verify_peers().
691  *
692  * Returns: a negative error code on error and %GNUTLS_E_SUCCESS (0)
693  * when the peer's certificate was successfully parsed, irrespective of whether
694  * it was verified.
695  *
696  * Since: 3.1.4
697  **/
698 int
699 gnutls_certificate_verify_peers3(gnutls_session_t session,
700                                  const char *hostname,
701                                  unsigned int *status)
702 {
703 gnutls_typed_vdata_st data;
704
705         data.type = GNUTLS_DT_DNS_HOSTNAME;
706         data.size = 0;
707         data.data = (void*)hostname;
708
709         return gnutls_certificate_verify_peers(session, &data, 1, status);
710 }
711
712 /**
713  * gnutls_certificate_verify_peers:
714  * @session: is a gnutls session
715  * @data: an array of typed data
716  * @elements: the number of data elements
717  * @status: is the output of the verification
718  *
719  * This function will verify the peer's certificate and store the
720  * status in the @status variable as a bitwise or'd gnutls_certificate_status_t
721  * values or zero if the certificate is trusted. Note that value in @status
722  * is set only when the return value of this function is success (i.e, failure 
723  * to trust a certificate does not imply a negative return value).
724  * The default verification flags used by this function can be overridden
725  * using gnutls_certificate_set_verify_flags(). See the documentation
726  * of gnutls_certificate_verify_peers2() for details in the verification process.
727  *
728  * The acceptable @data types are %GNUTLS_DT_DNS_HOSTNAME and %GNUTLS_DT_KEY_PURPOSE_OID.
729  * The former accepts as data a null-terminated hostname, and the latter a null-terminated
730  * object identifier (e.g., %GNUTLS_KP_TLS_WWW_SERVER).
731  * If a DNS hostname is provided then this function will compare
732  * the hostname in the certificate against the given. If names do not match the 
733  * %GNUTLS_CERT_UNEXPECTED_OWNER status flag will be set.
734  * If a key purpose OID is provided and the end-certificate contains the extended key
735  * usage PKIX extension, it will be required to be have the provided key purpose 
736  * or be marked for any purpose, otherwise verification will fail with %GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE status.
737  *
738  * Returns: a negative error code on error and %GNUTLS_E_SUCCESS (0)
739  * when the peer's certificate was successfully parsed, irrespective of whether
740  * it was verified.
741  *
742  * Since: 3.3.0
743  **/
744 int
745 gnutls_certificate_verify_peers(gnutls_session_t session,
746                                 gnutls_typed_vdata_st * data,
747                                 unsigned int elements,
748                                 unsigned int *status)
749 {
750         cert_auth_info_t info;
751         const char *hostname = NULL;
752         unsigned i;
753
754         CHECK_AUTH(GNUTLS_CRD_CERTIFICATE, GNUTLS_E_INVALID_REQUEST);
755
756         info = _gnutls_get_auth_info(session, GNUTLS_CRD_CERTIFICATE);
757         if (info == NULL) {
758                 return GNUTLS_E_NO_CERTIFICATE_FOUND;
759         }
760
761         if (info->raw_certificate_list == NULL || info->ncerts == 0)
762                 return GNUTLS_E_NO_CERTIFICATE_FOUND;
763
764
765         switch (gnutls_certificate_type_get(session)) {
766         case GNUTLS_CRT_X509:
767                 return _gnutls_x509_cert_verify_peers(session, data, elements,
768                                                       status);
769 #ifdef ENABLE_OPENPGP
770         case GNUTLS_CRT_OPENPGP:
771                 for (i=0;i<elements;i++) {
772                         if (data[i].type == GNUTLS_DT_DNS_HOSTNAME) {
773                                 hostname = (void*)data[i].data;
774                                 break;
775                         }
776                 }
777                 return _gnutls_openpgp_crt_verify_peers(session, hostname,
778                                                         status);
779 #endif
780         default:
781                 return GNUTLS_E_INVALID_REQUEST;
782         }
783 }
784
785 /**
786  * gnutls_certificate_expiration_time_peers:
787  * @session: is a gnutls session
788  *
789  * This function will return the peer's certificate expiration time.
790  *
791  * Returns: (time_t)-1 on error.
792  *
793  * Deprecated: gnutls_certificate_verify_peers2() now verifies expiration times.
794  **/
795 time_t gnutls_certificate_expiration_time_peers(gnutls_session_t session)
796 {
797         cert_auth_info_t info;
798
799         CHECK_AUTH(GNUTLS_CRD_CERTIFICATE, GNUTLS_E_INVALID_REQUEST);
800
801         info = _gnutls_get_auth_info(session, GNUTLS_CRD_CERTIFICATE);
802         if (info == NULL) {
803                 return (time_t) - 1;
804         }
805
806         if (info->raw_certificate_list == NULL || info->ncerts == 0) {
807                 gnutls_assert();
808                 return (time_t) - 1;
809         }
810
811         switch (gnutls_certificate_type_get(session)) {
812         case GNUTLS_CRT_X509:
813                 return
814                     _gnutls_x509_get_raw_crt_expiration_time(&info->
815                                                              raw_certificate_list
816                                                              [0]);
817 #ifdef ENABLE_OPENPGP
818         case GNUTLS_CRT_OPENPGP:
819                 return
820                     _gnutls_openpgp_get_raw_key_expiration_time
821                     (&info->raw_certificate_list[0]);
822 #endif
823         default:
824                 return (time_t) - 1;
825         }
826 }
827
828 /**
829  * gnutls_certificate_activation_time_peers:
830  * @session: is a gnutls session
831  *
832  * This function will return the peer's certificate activation time.
833  * This is the creation time for openpgp keys.
834  *
835  * Returns: (time_t)-1 on error.
836  *
837  * Deprecated: gnutls_certificate_verify_peers2() now verifies activation times.
838  **/
839 time_t gnutls_certificate_activation_time_peers(gnutls_session_t session)
840 {
841         cert_auth_info_t info;
842
843         CHECK_AUTH(GNUTLS_CRD_CERTIFICATE, GNUTLS_E_INVALID_REQUEST);
844
845         info = _gnutls_get_auth_info(session, GNUTLS_CRD_CERTIFICATE);
846         if (info == NULL) {
847                 return (time_t) - 1;
848         }
849
850         if (info->raw_certificate_list == NULL || info->ncerts == 0) {
851                 gnutls_assert();
852                 return (time_t) - 1;
853         }
854
855         switch (gnutls_certificate_type_get(session)) {
856         case GNUTLS_CRT_X509:
857                 return
858                     _gnutls_x509_get_raw_crt_activation_time(&info->
859                                                              raw_certificate_list
860                                                              [0]);
861 #ifdef ENABLE_OPENPGP
862         case GNUTLS_CRT_OPENPGP:
863                 return
864                     _gnutls_openpgp_get_raw_key_creation_time(&info->
865                                                               raw_certificate_list
866                                                               [0]);
867 #endif
868         default:
869                 return (time_t) - 1;
870         }
871 }
872
873 /**
874  * gnutls_sign_callback_set:
875  * @session: is a gnutls session
876  * @sign_func: function pointer to application's sign callback.
877  * @userdata: void pointer that will be passed to sign callback.
878  *
879  * Set the callback function.  The function must have this prototype:
880  *
881  * typedef int (*gnutls_sign_func) (gnutls_session_t session,
882  *                                  void *userdata,
883  *                                  gnutls_certificate_type_t cert_type,
884  *                                  const gnutls_datum_t * cert,
885  *                                  const gnutls_datum_t * hash,
886  *                                  gnutls_datum_t * signature);
887  *
888  * The @userdata parameter is passed to the @sign_func verbatim, and
889  * can be used to store application-specific data needed in the
890  * callback function.  See also gnutls_sign_callback_get().
891  *
892  * Deprecated: Use the PKCS 11 or #gnutls_privkey_t interfacess like gnutls_privkey_import_ext() instead.
893  **/
894 void
895 gnutls_sign_callback_set(gnutls_session_t session,
896                          gnutls_sign_func sign_func, void *userdata)
897 {
898         session->internals.sign_func = sign_func;
899         session->internals.sign_func_userdata = userdata;
900 }
901
902 /**
903  * gnutls_sign_callback_get:
904  * @session: is a gnutls session
905  * @userdata: if non-%NULL, will be set to abstract callback pointer.
906  *
907  * Retrieve the callback function, and its userdata pointer.
908  *
909  * Returns: The function pointer set by gnutls_sign_callback_set(), or
910  *   if not set, %NULL.
911  *
912  * Deprecated: Use the PKCS 11 interfaces instead.
913  **/
914 gnutls_sign_func
915 gnutls_sign_callback_get(gnutls_session_t session, void **userdata)
916 {
917         if (userdata)
918                 *userdata = session->internals.sign_func_userdata;
919         return session->internals.sign_func;
920 }
921
922 #define TEST_TEXT "test text"
923 /* returns error if the certificate has different algorithm than
924  * the given key parameters.
925  */
926 int _gnutls_check_key_cert_match(gnutls_certificate_credentials_t res)
927 {
928         gnutls_datum_t test = {(void*)TEST_TEXT, sizeof(TEST_TEXT)-1};
929         gnutls_datum_t sig = {NULL, 0};
930         int pk, pk2, ret;
931
932         pk =
933             gnutls_pubkey_get_pk_algorithm(res->certs[res->ncerts - 1].
934                                            cert_list[0].pubkey, NULL);
935         pk2 =
936             gnutls_privkey_get_pk_algorithm(res->pkey[res->ncerts - 1],
937                                             NULL);
938
939         if (pk2 != pk) {
940                 gnutls_assert();
941                 return GNUTLS_E_CERTIFICATE_KEY_MISMATCH;
942         }
943
944         /* now check if keys really match. We use the sign/verify approach
945          * because we cannot always obtain the parameters from the abstract
946          * keys (e.g. PKCS #11). */
947         ret = gnutls_privkey_sign_data(res->pkey[res->ncerts - 1],
948                 GNUTLS_DIG_SHA256, 0, &test, &sig);
949         if (ret < 0) {
950                 /* for some reason we couldn't sign that. That shouldn't have
951                  * happened, but since it did, report the issue and do not
952                  * try the key matching test */
953                 _gnutls_debug_log("%s: failed signing\n", __func__);
954                 goto finish;
955         }
956
957         ret = gnutls_pubkey_verify_data2(res->certs[res->ncerts - 1].cert_list[0].pubkey,
958                 gnutls_pk_to_sign(pk, GNUTLS_DIG_SHA256),
959                 0, &test, &sig);
960
961         gnutls_free(sig.data);
962
963         if (ret < 0)
964                 return gnutls_assert_val(GNUTLS_E_CERTIFICATE_KEY_MISMATCH);
965
966  finish:
967         return 0;
968 }
969
970 /**
971  * gnutls_certificate_verification_status_print:
972  * @status: The status flags to be printed
973  * @type: The certificate type
974  * @out: Newly allocated datum with (0) terminated string.
975  * @flags: should be zero
976  *
977  * This function will pretty print the status of a verification
978  * process -- eg. the one obtained by gnutls_certificate_verify_peers3().
979  *
980  * The output @out needs to be deallocated using gnutls_free().
981  *
982  * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
983  *   negative error value.
984  *
985  * Since: 3.1.4
986  **/
987 int
988 gnutls_certificate_verification_status_print(unsigned int status,
989                                              gnutls_certificate_type_t
990                                              type, gnutls_datum_t * out,
991                                              unsigned int flags)
992 {
993         gnutls_buffer_st str;
994         int ret;
995
996         _gnutls_buffer_init(&str);
997
998         if (status == 0)
999                 _gnutls_buffer_append_str(&str,
1000                                           _
1001                                           ("The certificate is trusted. "));
1002         else
1003                 _gnutls_buffer_append_str(&str,
1004                                           _
1005                                           ("The certificate is NOT trusted. "));
1006
1007         if (type == GNUTLS_CRT_X509) {
1008                 if (status & GNUTLS_CERT_REVOKED)
1009                         _gnutls_buffer_append_str(&str,
1010                                                   _
1011                                                   ("The certificate chain is revoked. "));
1012
1013                 if (status & GNUTLS_CERT_MISMATCH)
1014                         _gnutls_buffer_append_str(&str,
1015                                                   _
1016                                                   ("The certificate doesn't match the local copy (TOFU). "));
1017
1018                 if (status & GNUTLS_CERT_REVOCATION_DATA_SUPERSEDED)
1019                         _gnutls_buffer_append_str(&str,
1020                                                   _
1021                                                   ("The revocation data are old and have been superseded. "));
1022
1023                 if (status & GNUTLS_CERT_REVOCATION_DATA_ISSUED_IN_FUTURE)
1024                         _gnutls_buffer_append_str(&str,
1025                                                   _
1026                                                   ("The revocation data are issued with a future date. "));
1027
1028                 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1029                         _gnutls_buffer_append_str(&str,
1030                                                   _
1031                                                   ("The certificate issuer is unknown. "));
1032
1033                 if (status & GNUTLS_CERT_SIGNER_NOT_CA)
1034                         _gnutls_buffer_append_str(&str,
1035                                                   _
1036                                                   ("The certificate issuer is not a CA. "));
1037         } else if (type == GNUTLS_CRT_OPENPGP) {
1038                 if (status & GNUTLS_CERT_SIGNER_NOT_FOUND)
1039                         _gnutls_buffer_append_str(&str,
1040                                                   _
1041                                                   ("Could not find a signer of the certificate. "));
1042
1043                 if (status & GNUTLS_CERT_REVOKED)
1044                         _gnutls_buffer_append_str(&str,
1045                                                   _
1046                                                   ("The certificate is revoked. "));
1047         }
1048
1049         if (status & GNUTLS_CERT_INSECURE_ALGORITHM)
1050                 _gnutls_buffer_append_str(&str,
1051                                           _
1052                                           ("The certificate chain uses insecure algorithm. "));
1053
1054         if (status & GNUTLS_CERT_SIGNER_CONSTRAINTS_FAILURE)
1055                 _gnutls_buffer_append_str(&str,
1056                                           _
1057                                           ("The certificate chain violates the signer's constraints. "));
1058
1059         if (status & GNUTLS_CERT_NOT_ACTIVATED)
1060                 _gnutls_buffer_append_str(&str,
1061                                           _
1062                                           ("The certificate chain uses not yet valid certificate. "));
1063
1064         if (status & GNUTLS_CERT_EXPIRED)
1065                 _gnutls_buffer_append_str(&str,
1066                                           _
1067                                           ("The certificate chain uses expired certificate. "));
1068
1069         if (status & GNUTLS_CERT_SIGNATURE_FAILURE)
1070                 _gnutls_buffer_append_str(&str,
1071                                           _
1072                                           ("The signature in the certificate is invalid. "));
1073
1074         if (status & GNUTLS_CERT_UNEXPECTED_OWNER)
1075                 _gnutls_buffer_append_str(&str,
1076                                           _
1077                                           ("The name in the certificate does not match the expected. "));
1078
1079         ret = _gnutls_buffer_to_datum(&str, out);
1080         if (out->size > 0)
1081                 out->size--;
1082
1083         return ret;
1084 }