Imported Upstream version 3.3.27
[platform/upstream/gnutls.git] / libdane / dane.c
1 /*
2  * Copyright (C) 2012 KU Leuven
3  * Copyright (C) 2013 Christian Grothoff
4  * Copyright (C) 2013 Nikos Mavrogiannopoulos
5  *
6  * Author: Nikos Mavrogiannopoulos
7  *
8  * This file is part of libdane.
9  *
10  * The libdane library is free software; you can redistribute it
11  * and/or modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>
22  *
23  */
24
25 #include <config.h>
26
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <errno.h>
31 #include <arpa/inet.h>
32 #include <unbound.h>
33 #include <gnutls/dane.h>
34 #include <gnutls/x509.h>
35 #include <gnutls/abstract.h>
36 #include <gnutls/crypto.h>
37 #include "../lib/gnutls_int.h"
38
39 #define MAX_DATA_ENTRIES 100
40 #ifdef DEBUG
41 #define gnutls_assert() fprintf(stderr, "ASSERT: %s: %d\n", __FILE__, __LINE__);
42 #define gnutls_assert_val(x) gnutls_assert_val_int(x, __FILE__, __LINE__)
43 static int gnutls_assert_val_int(int val, const char *file, int line)
44 {
45         fprintf(stderr, "ASSERT: %s: %d\n", file, line);
46         return val;
47 }
48 #else
49 #define gnutls_assert()
50 #define gnutls_assert_val(x) (x)
51 #endif
52
53 struct dane_state_st {
54         struct ub_ctx *ctx;
55         unsigned int flags;
56 };
57
58 struct dane_query_st {
59         struct ub_result *result;
60         unsigned int data_entries;
61         dane_cert_usage_t usage[MAX_DATA_ENTRIES];
62         dane_cert_type_t type[MAX_DATA_ENTRIES];
63         dane_match_type_t match[MAX_DATA_ENTRIES];
64         gnutls_datum_t data[MAX_DATA_ENTRIES];
65         unsigned int flags;
66         dane_query_status_t status;
67 };
68
69 /**
70  * dane_query_status:
71  * @q: The query result structure
72  *
73  * This function will return the status of the query response.
74  * See %dane_query_status_t for the possible types.
75  *
76  * Returns: The status type.
77  **/
78 dane_query_status_t dane_query_status(dane_query_t q)
79 {
80         return q->status;
81 }
82
83 /**
84  * dane_query_entries:
85  * @q: The query result structure
86  *
87  * This function will return the number of entries in a query.
88  *
89  * Returns: The number of entries.
90  **/
91 unsigned int dane_query_entries(dane_query_t q)
92 {
93         return q->data_entries;
94 }
95
96 /**
97  * dane_query_data:
98  * @q: The query result structure
99  * @idx: The index of the query response.
100  * @usage: The certificate usage (see %dane_cert_usage_t)
101  * @type: The certificate type (see %dane_cert_type_t)
102  * @match: The DANE matching type (see %dane_match_type_t)
103  * @data: The DANE data.
104  *
105  * This function will provide the DANE data from the query
106  * response.
107  *
108  * Returns: On success, %DANE_E_SUCCESS (0) is returned, otherwise a
109  *   negative error value.
110  **/
111 int
112 dane_query_data(dane_query_t q, unsigned int idx,
113                 unsigned int *usage, unsigned int *type,
114                 unsigned int *match, gnutls_datum_t * data)
115 {
116         if (idx >= q->data_entries)
117                 return
118                     gnutls_assert_val(DANE_E_REQUESTED_DATA_NOT_AVAILABLE);
119
120         if (usage)
121                 *usage = q->usage[idx];
122         if (type)
123                 *type = q->type[idx];
124         if (match)
125                 *match = q->match[idx];
126         if (data) {
127                 data->data = q->data[idx].data;
128                 data->size = q->data[idx].size;
129         }
130
131         return DANE_E_SUCCESS;
132 }
133
134 /**
135  * dane_query_to_raw_tlsa:
136  * @q: The query result structure
137  * @data_entries: Pointer set to the number of entries in the query
138  * @dane_data: Pointer to contain an array of DNS rdata items, terminated with a NULL pointer;
139  *             caller must guarantee that the referenced data remains
140  *             valid until dane_query_deinit() is called.
141  * @dane_data_len: Pointer to contain the length n bytes of the dane_data items
142  * @secure: Pointer set true if the result is validated securely, false if
143  *               validation failed or the domain queried has no security info
144  * @bogus: Pointer set true if the result was not secure due to a security failure
145  *
146  * This function will provide the DANE data from the query
147  * response.
148  *
149  * The pointers dane_data and dane_data_len are allocated with gnutls_malloc()
150  * to contain the data from the query result structure (individual
151  * @dane_data items simply point to the original data and are not allocated separately).
152  * The returned @dane_data are only valid during the lifetime of @q.
153  *
154  * Returns: On success, %DANE_E_SUCCESS (0) is returned, otherwise a
155  *   negative error value.
156  */
157 int
158 dane_query_to_raw_tlsa(dane_query_t q, unsigned int *data_entries,
159                 char ***dane_data, int **dane_data_len, int *secure, int *bogus)
160 {
161         size_t data_sz;
162         char *data_buf;
163         unsigned int idx;
164
165         *data_entries = 0;
166         *dane_data = NULL;
167         *dane_data_len = NULL;
168
169         if (secure) {
170                 if (q->status & DANE_QUERY_DNSSEC_VERIFIED)
171                         *secure = 1;
172                 else
173                         *secure = 0;
174         }
175
176         if (bogus) {
177                 if (q->status & DANE_QUERY_BOGUS)
178                         *bogus = 1;
179                 else
180                         *bogus = 0;
181         }
182
183         /* pack dane_data pointer list followed by dane_data contents */
184         data_sz = sizeof (**dane_data) * (q->data_entries + 1);
185         for (idx = 0; idx < q->data_entries; idx++)
186                 data_sz += 3 + q->data[idx].size;
187
188         *dane_data = gnutls_calloc (1, data_sz);
189         if (*dane_data == NULL)
190                 return DANE_E_MEMORY_ERROR;
191         data_buf = (char *)*dane_data;
192         data_buf += sizeof (**dane_data) * (q->data_entries + 1);
193
194         *dane_data_len = gnutls_calloc (q->data_entries + 1, sizeof (**dane_data_len));
195         if (*dane_data_len == NULL) {
196                 free(*dane_data);
197                 *dane_data = NULL;
198                 return DANE_E_MEMORY_ERROR;
199         }
200
201         for (idx = 0; idx < q->data_entries; idx++) {
202                 (*dane_data)[idx] = data_buf;
203                 (*dane_data)[idx][0] = q->usage[idx];
204                 (*dane_data)[idx][1] = q->type[idx];
205                 (*dane_data)[idx][2] = q->match[idx];
206                 memcpy(&(*dane_data)[idx][3], q->data[idx].data, q->data[idx].size);
207                 (*dane_data_len)[idx] = 3 + q->data[idx].size;
208                 data_buf += 3 + q->data[idx].size;
209         }
210         (*dane_data)[idx] = NULL;
211         (*dane_data_len)[idx] = 0;
212         *data_entries = q->data_entries;
213
214         return DANE_E_SUCCESS;
215 }
216
217 /**
218  * dane_state_init:
219  * @s: The structure to be initialized
220  * @flags: flags from the %dane_state_flags enumeration
221  *
222  * This function will initialize a DANE query structure.
223  *
224  * Returns: On success, %DANE_E_SUCCESS (0) is returned, otherwise a
225  *   negative error value.
226  **/
227 int dane_state_init(dane_state_t * s, unsigned int flags)
228 {
229         struct ub_ctx *ctx;
230         int ret;
231
232         *s = calloc(1, sizeof(struct dane_state_st));
233         if (*s == NULL)
234                 return gnutls_assert_val(DANE_E_MEMORY_ERROR);
235
236         ctx = ub_ctx_create();
237         if (!ctx) {
238                 gnutls_assert();
239                 ret = DANE_E_INITIALIZATION_ERROR;
240                 goto cleanup;
241         }
242         ub_ctx_debugout(ctx, stderr);
243
244         if (!(flags & DANE_F_IGNORE_LOCAL_RESOLVER)) {
245                 if ((ret = ub_ctx_resolvconf(ctx, NULL)) != 0) {
246                         gnutls_assert();
247                         ret = DANE_E_INITIALIZATION_ERROR;
248                         goto cleanup;
249                 }
250
251                 if ((ret = ub_ctx_hosts(ctx, NULL)) != 0) {
252                         gnutls_assert();
253                         ret = DANE_E_INITIALIZATION_ERROR;
254                         goto cleanup;
255                 }
256         }
257
258         /* read public keys for DNSSEC verification */
259         if (!(flags & DANE_F_IGNORE_DNSSEC)) {
260                 if ((ret =
261                      ub_ctx_add_ta_file(ctx,
262                                         (char *) UNBOUND_ROOT_KEY_FILE)) !=
263                     0) {
264                         gnutls_assert();
265                         ret = DANE_E_INITIALIZATION_ERROR;
266                         goto cleanup;
267                 }
268         }
269
270         (*s)->ctx = ctx;
271         (*s)->flags = flags;
272
273         return DANE_E_SUCCESS;
274       cleanup:
275
276         if (ctx)
277                 ub_ctx_delete(ctx);
278         free(*s);
279
280         return ret;
281 }
282
283 /**
284  * dane_state_deinit:
285  * @s: The structure to be deinitialized
286  *
287  * This function will deinitialize a DANE query structure.
288  *
289  **/
290 void dane_state_deinit(dane_state_t s)
291 {
292         ub_ctx_delete(s->ctx);
293         free(s);
294 }
295
296 /**
297  * dane_state_set_dlv_file:
298  * @s: The structure to be deinitialized
299  * @file: The file holding the DLV keys.
300  *
301  * This function will set a file with trusted keys
302  * for DLV  (DNSSEC  Lookaside  Validation).
303  *
304  **/
305 int dane_state_set_dlv_file(dane_state_t s, const char *file)
306 {
307         int ret;
308
309         ret =
310             ub_ctx_set_option(s->ctx, (char *) "dlv-anchor-file:",
311                               (void *) file);
312         if (ret != 0)
313                 return gnutls_assert_val(DANE_E_FILE_ERROR);
314
315         return 0;
316 }
317
318 /**
319  * dane_query_deinit:
320  * @q: The structure to be deinitialized
321  *
322  * This function will deinitialize a DANE query result structure.
323  *
324  **/
325 void dane_query_deinit(dane_query_t q)
326 {
327         if (q->result)
328                 ub_resolve_free(q->result);
329         free(q);
330 }
331
332
333 /**
334  * dane_raw_tlsa:
335  * @s: The DANE state structure
336  * @r: A structure to place the result
337  * @dane_data: array of DNS rdata items, terminated with a NULL pointer;
338  *             caller must guarantee that the referenced data remains
339  *             valid until dane_query_deinit() is called.
340  * @dane_data_len: the length n bytes of the dane_data items
341  * @secure: true if the result is validated securely, false if
342  *               validation failed or the domain queried has no security info
343  * @bogus: if the result was not secure (secure = 0) due to a security failure,
344  *              and the result is due to a security failure, bogus is true.
345  *
346  * This function will fill in the TLSA (DANE) structure from
347  * the given raw DNS record data. The @dane_data must be valid
348  * during the lifetime of the query.
349  *
350  * Returns: On success, %DANE_E_SUCCESS (0) is returned, otherwise a
351  *   negative error value.
352  **/
353 int
354 dane_raw_tlsa(dane_state_t s, dane_query_t * r, char *const *dane_data,
355               const int *dane_data_len, int secure, int bogus)
356 {
357         int ret = DANE_E_SUCCESS;
358         unsigned int i;
359
360         *r = calloc(1, sizeof(struct dane_query_st));
361         if (*r == NULL)
362                 return gnutls_assert_val(DANE_E_MEMORY_ERROR);
363
364         (*r)->data_entries = 0;
365
366         for (i = 0; i < MAX_DATA_ENTRIES; i++) {
367                 if (dane_data[i] == NULL)
368                         break;
369
370                 if (dane_data_len[i] <= 3)
371                         return
372                             gnutls_assert_val
373                             (DANE_E_RECEIVED_CORRUPT_DATA);
374
375                 (*r)->usage[i] = dane_data[i][0];
376                 (*r)->type[i] = dane_data[i][1];
377                 (*r)->match[i] = dane_data[i][2];
378                 (*r)->data[i].data = (void *) &dane_data[i][3];
379                 (*r)->data[i].size = dane_data_len[i] - 3;
380                 (*r)->data_entries++;
381         }
382
383         if (!(s->flags & DANE_F_INSECURE) && !secure) {
384                 if (bogus)
385                         ret = gnutls_assert_val(DANE_E_INVALID_DNSSEC_SIG);
386                 else
387                         ret = gnutls_assert_val(DANE_E_NO_DNSSEC_SIG);
388         }
389
390         /* show security status */
391         if (secure) {
392                 (*r)->status = DANE_QUERY_DNSSEC_VERIFIED;
393         } else if (bogus) {
394                 gnutls_assert();
395                 (*r)->status = DANE_QUERY_BOGUS;
396         } else {
397                 gnutls_assert();
398                 (*r)->status = DANE_QUERY_NO_DNSSEC;
399         }
400
401         return ret;
402 }
403
404
405 /**
406  * dane_query_tlsa:
407  * @s: The DANE state structure
408  * @r: A structure to place the result
409  * @host: The host name to resolve.
410  * @proto: The protocol type (tcp, udp, etc.)
411  * @port: The service port number (eg. 443).
412  *
413  * This function will query the DNS server for the TLSA (DANE)
414  * data for the given host.
415  *
416  * Returns: On success, %DANE_E_SUCCESS (0) is returned, otherwise a
417  *   negative error value.
418  **/
419 int
420 dane_query_tlsa(dane_state_t s, dane_query_t * r, const char *host,
421                 const char *proto, unsigned int port)
422 {
423         char ns[1024];
424         int ret;
425         struct ub_result *result;
426
427         snprintf(ns, sizeof(ns), "_%u._%s.%s", port, proto, host);
428
429         /* query for webserver */
430         ret = ub_resolve(s->ctx, ns, 52, 1, &result);
431         if (ret != 0) {
432                 return gnutls_assert_val(DANE_E_RESOLVING_ERROR);
433         }
434
435 /* show first result */
436         if (!result->havedata) {
437                 ub_resolve_free(result);
438                 return gnutls_assert_val(DANE_E_NO_DANE_DATA);
439         }
440
441         ret =
442             dane_raw_tlsa(s, r, result->data, result->len, result->secure,
443                           result->bogus);
444         if (*r == NULL) {
445                 ub_resolve_free(result);
446                 return ret;
447         }
448         (*r)->result = result;
449         return ret;
450 }
451
452
453 static unsigned int
454 matches(const gnutls_datum_t * raw1, const gnutls_datum_t * raw2,
455         dane_match_type_t match)
456 {
457         uint8_t digest[64];
458         int ret;
459
460         if (match == DANE_MATCH_EXACT) {
461                 if (raw1->size != raw2->size)
462                         return gnutls_assert_val(0);
463
464                 if (memcmp(raw1->data, raw2->data, raw1->size) != 0)
465                         return gnutls_assert_val(0);
466
467                 return 1;
468         } else if (match == DANE_MATCH_SHA2_256) {
469
470                 if (raw2->size != 32)
471                         return gnutls_assert_val(0);
472
473                 ret =
474                     gnutls_hash_fast(GNUTLS_DIG_SHA256, raw1->data,
475                                      raw1->size, digest);
476                 if (ret < 0)
477                         return gnutls_assert_val(0);
478
479                 if (memcmp(digest, raw2->data, 32) != 0)
480                         return gnutls_assert_val(0);
481
482                 return 1;
483         } else if (match == DANE_MATCH_SHA2_512) {
484                 if (raw2->size != 64)
485                         return gnutls_assert_val(0);
486
487                 ret =
488                     gnutls_hash_fast(GNUTLS_DIG_SHA512, raw1->data,
489                                      raw1->size, digest);
490                 if (ret < 0)
491                         return gnutls_assert_val(0);
492
493                 if (memcmp(digest, raw2->data, 64) != 0)
494                         return gnutls_assert_val(0);
495
496                 return 1;
497         }
498
499         return gnutls_assert_val(0);
500 }
501
502 static int
503 crt_to_pubkey(const gnutls_datum_t * raw_crt, gnutls_datum_t * out)
504 {
505         gnutls_pubkey_t pub = NULL;
506         gnutls_x509_crt_t crt = NULL;
507         int ret;
508
509         out->data = NULL;
510
511         ret = gnutls_x509_crt_init(&crt);
512         if (ret < 0)
513                 return gnutls_assert_val(DANE_E_PUBKEY_ERROR);
514
515         ret = gnutls_pubkey_init(&pub);
516         if (ret < 0) {
517                 gnutls_assert();
518                 ret = DANE_E_PUBKEY_ERROR;
519                 goto cleanup;
520         }
521
522         ret = gnutls_x509_crt_import(crt, raw_crt, GNUTLS_X509_FMT_DER);
523         if (ret < 0) {
524                 gnutls_assert();
525                 ret = DANE_E_PUBKEY_ERROR;
526                 goto cleanup;
527         }
528
529         ret = gnutls_pubkey_import_x509(pub, crt, 0);
530         if (ret < 0) {
531                 gnutls_assert();
532                 ret = DANE_E_PUBKEY_ERROR;
533                 goto cleanup;
534         }
535
536         ret = gnutls_pubkey_export2(pub, GNUTLS_X509_FMT_DER, out);
537         if (ret < 0) {
538                 gnutls_assert();
539                 ret = DANE_E_PUBKEY_ERROR;
540                 goto cleanup;
541         }
542
543         ret = 0;
544         goto clean_certs;
545
546       cleanup:
547         free(out->data);
548         out->data = NULL;
549       clean_certs:
550         if (pub)
551                 gnutls_pubkey_deinit(pub);
552         if (crt)
553                 gnutls_x509_crt_deinit(crt);
554
555         return ret;
556 }
557
558 static int
559 verify_ca(const gnutls_datum_t * raw_crt, unsigned raw_crt_size,
560           gnutls_certificate_type_t crt_type,
561           dane_cert_type_t ctype,
562           dane_match_type_t match, gnutls_datum_t * data,
563           unsigned int *verify)
564 {
565         gnutls_datum_t pubkey = { NULL, 0 };
566         int ret, i;
567         unsigned int vstatus = 0;
568         gnutls_x509_crt_t crt = NULL, ca = NULL;
569         unsigned is_ok = 0;
570
571         if (raw_crt_size < 2) /* we cannot verify the CA */
572                 return gnutls_assert_val(DANE_E_UNKNOWN_DANE_DATA);
573
574         if (ctype == DANE_CERT_X509 && crt_type == GNUTLS_CRT_X509) {
575                 is_ok = 0;
576                 for (i=raw_crt_size-1;i>=1;i--) {
577                         if (matches(&raw_crt[i], data, match)) {
578                                 is_ok = 1;
579                                 break;
580                         }
581                 }
582
583                 if (is_ok == 0) {
584                         gnutls_assert();
585                         *verify |= DANE_VERIFY_CA_CONSTRAINTS_VIOLATED;
586                 }
587
588         } else if (ctype == DANE_CERT_PK && crt_type == GNUTLS_CRT_X509) {
589                 is_ok = 0;
590
591                 for (i=raw_crt_size-1;i>=1;i--) {
592                         ret = crt_to_pubkey(&raw_crt[i], &pubkey);
593                         if (ret < 0) {
594                                 gnutls_assert();
595                                 goto cleanup;
596                         }
597
598                         if (matches(&pubkey, data, match)) {
599                                 is_ok = 1;
600                                 break;
601                         }
602
603                         free(pubkey.data);
604                         pubkey.data = NULL;
605                 }
606
607                 if (is_ok == 0) {
608                         gnutls_assert();
609                         *verify |= DANE_VERIFY_CA_CONSTRAINTS_VIOLATED;
610                 }
611         } else {
612                 ret = gnutls_assert_val(DANE_E_UNKNOWN_DANE_DATA);
613                 goto cleanup;
614         }
615
616         /* check if the certificate chain is actually a chain */
617         ret = gnutls_x509_crt_init(&crt);
618         if (ret < 0) {
619                 ret = gnutls_assert_val(DANE_E_CERT_ERROR);
620                 goto cleanup;
621         }
622
623         ret =
624             gnutls_x509_crt_import(crt, &raw_crt[0], GNUTLS_X509_FMT_DER);
625         if (ret < 0) {
626                 ret = gnutls_assert_val(DANE_E_CERT_ERROR);
627                 goto cleanup;
628         }
629
630         for (i=raw_crt_size-1;i>=1;i--) {
631                 ret = gnutls_x509_crt_init(&ca);
632                 if (ret < 0) {
633                         ret = gnutls_assert_val(DANE_E_CERT_ERROR);
634                         goto cleanup;
635                 }
636
637                 ret = gnutls_x509_crt_import(ca, &raw_crt[i], GNUTLS_X509_FMT_DER);
638                 if (ret < 0) {
639                         ret = gnutls_assert_val(DANE_E_CERT_ERROR);
640                         goto cleanup;
641                 }
642
643                 ret = gnutls_x509_crt_check_issuer(crt, ca);
644                 if (ret != 0)
645                         break;
646
647                 gnutls_x509_crt_deinit(ca);
648                 ca = NULL;
649         }
650
651         if (ca == NULL) {
652                 gnutls_assert();
653                 *verify |= DANE_VERIFY_CA_CONSTRAINTS_VIOLATED;
654         } else {
655                 ret = gnutls_x509_crt_verify(crt, &ca, 1, 0, &vstatus);
656                 if (ret < 0) {
657                         ret = gnutls_assert_val(DANE_E_CERT_ERROR);
658                         goto cleanup;
659                 }
660
661                 if (vstatus != 0)
662                         *verify |= DANE_VERIFY_CA_CONSTRAINTS_VIOLATED;
663         }
664
665         ret = 0;
666       cleanup:
667         free(pubkey.data);
668         if (crt != NULL)
669                 gnutls_x509_crt_deinit(crt);
670         if (ca != NULL)
671                 gnutls_x509_crt_deinit(ca);
672         return ret;
673 }
674
675 static int
676 verify_ee(const gnutls_datum_t * raw_crt,
677           gnutls_certificate_type_t crt_type, dane_cert_type_t ctype,
678           dane_match_type_t match, gnutls_datum_t * data,
679           unsigned int *verify)
680 {
681         gnutls_datum_t pubkey = { NULL, 0 };
682         int ret;
683
684         if (ctype == DANE_CERT_X509 && crt_type == GNUTLS_CRT_X509) {
685
686                 if (!matches(raw_crt, data, match)) {
687                         gnutls_assert();
688                         *verify |= DANE_VERIFY_CERT_DIFFERS;
689                 }
690
691         } else if (ctype == DANE_CERT_PK && crt_type == GNUTLS_CRT_X509) {
692
693                 ret = crt_to_pubkey(raw_crt, &pubkey);
694                 if (ret < 0) {
695                         gnutls_assert();
696                         goto cleanup;
697                 }
698
699                 if (!matches(&pubkey, data, match)) {
700                         gnutls_assert();
701                         *verify |= DANE_VERIFY_CERT_DIFFERS;
702                 }
703         } else {
704                 ret = gnutls_assert_val(DANE_E_UNKNOWN_DANE_DATA);
705                 goto cleanup;
706         }
707
708         ret = 0;
709       cleanup:
710         free(pubkey.data);
711         return ret;
712 }
713
714 #define CHECK_VRET(ret, checked, record_status, status) \
715                         if (ret == DANE_E_UNKNOWN_DANE_DATA) { \
716                                 /* skip that entry */ \
717                                 continue; \
718                         } else if (ret < 0) { \
719                                 gnutls_assert(); \
720                                 goto cleanup; \
721                         } \
722                         checked = 1; \
723                         if (record_status == 0) { \
724                                 status = 0; \
725                                 break; \
726                         } else { \
727                                 status |= record_status; \
728                         }
729
730 /**
731  * dane_verify_crt_raw:
732  * @s: A DANE state structure (may be NULL)
733  * @chain: A certificate chain
734  * @chain_size: The size of the chain
735  * @chain_type: The type of the certificate chain
736  * @r: DANE data to check against
737  * @sflags: Flags for the the initialization of @s (if NULL)
738  * @vflags: Verification flags; an OR'ed list of %dane_verify_flags_t.
739  * @verify: An OR'ed list of %dane_verify_status_t.
740  *
741  * This function will verify the given certificate chain against the
742  * CA constrains and/or the certificate available via DANE.
743  * If no information via DANE can be obtained the flag %DANE_VERIFY_NO_DANE_INFO
744  * is set. If a DNSSEC signature is not available for the DANE
745  * record then the verify flag %DANE_VERIFY_NO_DNSSEC_DATA is set.
746  *
747  * Due to the many possible options of DANE, there is no single threat
748  * model countered. When notifying the user about DANE verification results
749  * it may be better to mention: DANE verification did not reject the certificate,
750  * rather than mentioning a successful DANE verication.
751  *
752  * Note that this function is designed to be run in addition to
753  * PKIX - certificate chain - verification. To be run independently
754  * the %DANE_VFLAG_ONLY_CHECK_EE_USAGE flag should be specified; 
755  * then the function will check whether the key of the peer matches the
756  * key advertized in the DANE entry.
757  *
758  * If the @q parameter is provided it will be used for caching entries.
759  *
760  * Returns: a negative error code on error and %DANE_E_SUCCESS (0)
761  * when the DANE entries were successfully parsed, irrespective of
762  * whether they were verified (see @verify for that information). If
763  * no usable entries were encountered %DANE_E_REQUESTED_DATA_NOT_AVAILABLE
764  * will be returned.
765  *
766  **/
767 int
768 dane_verify_crt_raw(dane_state_t s,
769                     const gnutls_datum_t * chain, unsigned chain_size,
770                     gnutls_certificate_type_t chain_type,
771                     dane_query_t r,
772                     unsigned int sflags, unsigned int vflags,
773                     unsigned int *verify)
774 {
775         int ret;
776         unsigned checked = 0;
777         unsigned int usage, type, match, idx;
778         gnutls_datum_t data;
779
780         if (chain_type != GNUTLS_CRT_X509)
781                 return gnutls_assert_val(DANE_E_INVALID_REQUEST);
782
783         if (chain_size == 0)
784                 return gnutls_assert_val(DANE_E_NO_CERT);
785
786         *verify = 0;
787         idx = 0;
788         do {
789                 unsigned int record_verify = 0;
790
791                 ret =
792                     dane_query_data(r, idx++, &usage, &type, &match,
793                                     &data);
794                 if (ret == DANE_E_REQUESTED_DATA_NOT_AVAILABLE)
795                         break;
796
797                 if (ret < 0) {
798                         gnutls_assert();
799                         goto cleanup;
800                 }
801
802                 if (!(vflags & DANE_VFLAG_ONLY_CHECK_EE_USAGE)
803                     && (usage == DANE_CERT_USAGE_LOCAL_CA
804                         || usage == DANE_CERT_USAGE_CA)) {
805                         ret =
806                             verify_ca(chain, chain_size, chain_type, type,
807                                       match, &data, &record_verify);
808                         CHECK_VRET(ret, checked, record_verify, *verify);
809
810                 } else if (!(vflags & DANE_VFLAG_ONLY_CHECK_CA_USAGE)
811                            && (usage == DANE_CERT_USAGE_LOCAL_EE
812                                || usage == DANE_CERT_USAGE_EE)) {
813                         ret =
814                             verify_ee(&chain[0], chain_type, type, match,
815                                       &data, &record_verify);
816                         CHECK_VRET(ret, checked, record_verify, *verify);
817                 }
818         }
819         while (1);
820
821         if ((vflags & DANE_VFLAG_FAIL_IF_NOT_CHECKED) && checked == 0) {
822                 ret =
823                     gnutls_assert_val(DANE_E_REQUESTED_DATA_NOT_AVAILABLE);
824         } else if (checked == 0) {
825                 *verify |= DANE_VERIFY_UNKNOWN_DANE_INFO;
826         } else {
827                 ret = 0;
828         }
829
830       cleanup:
831         return ret;
832 }
833
834
835 /**
836  * dane_verify_crt:
837  * @s: A DANE state structure (may be NULL)
838  * @chain: A certificate chain
839  * @chain_size: The size of the chain
840  * @chain_type: The type of the certificate chain
841  * @hostname: The hostname associated with the chain
842  * @proto: The protocol of the service connecting (e.g. tcp)
843  * @port: The port of the service connecting (e.g. 443)
844  * @sflags: Flags for the the initialization of @s (if NULL)
845  * @vflags: Verification flags; an OR'ed list of %dane_verify_flags_t.
846  * @verify: An OR'ed list of %dane_verify_status_t.
847  *
848  * This function will verify the given certificate chain against the
849  * CA constrains and/or the certificate available via DANE.
850  * If no information via DANE can be obtained the flag %DANE_VERIFY_NO_DANE_INFO
851  * is set. If a DNSSEC signature is not available for the DANE
852  * record then the verify flag %DANE_VERIFY_NO_DNSSEC_DATA is set.
853  *
854  * Due to the many possible options of DANE, there is no single threat
855  * model countered. When notifying the user about DANE verification results
856  * it may be better to mention: DANE verification did not reject the certificate,
857  * rather than mentioning a successful DANE verication.
858  *
859  * Note that this function is designed to be run in addition to
860  * PKIX - certificate chain - verification. To be run independently
861  * the %DANE_VFLAG_ONLY_CHECK_EE_USAGE flag should be specified; 
862  * then the function will check whether the key of the peer matches the
863  * key advertized in the DANE entry.
864  *
865  * Returns: a negative error code on error and %DANE_E_SUCCESS (0)
866  * when the DANE entries were successfully parsed, irrespective of
867  * whether they were verified (see @verify for that information). If
868  * no usable entries were encountered %DANE_E_REQUESTED_DATA_NOT_AVAILABLE
869  * will be returned.
870  *
871  **/
872 int
873 dane_verify_crt(dane_state_t s,
874                 const gnutls_datum_t * chain, unsigned chain_size,
875                 gnutls_certificate_type_t chain_type,
876                 const char *hostname, const char *proto, unsigned int port,
877                 unsigned int sflags, unsigned int vflags,
878                 unsigned int *verify)
879 {
880         dane_state_t state = NULL;
881         dane_query_t r = NULL;
882         int ret;
883
884         *verify = 0;
885         if (s == NULL) {
886                 ret = dane_state_init(&state, sflags);
887                 if (ret < 0) {
888                         gnutls_assert();
889                         return ret;
890                 }
891         } else
892                 state = s;
893
894         ret = dane_query_tlsa(state, &r, hostname, proto, port);
895         if (ret < 0) {
896                 gnutls_assert();
897                 goto cleanup;
898         }
899         ret = dane_verify_crt_raw(state, chain, chain_size, chain_type,
900                                   r, sflags, vflags, verify);
901       cleanup:
902         if (state != s)
903                 dane_state_deinit(state);
904         if (r != NULL)
905                 dane_query_deinit(r);
906         return ret;
907 }
908
909 /**
910  * dane_verify_session_crt:
911  * @s: A DANE state structure (may be NULL)
912  * @session: A gnutls session
913  * @hostname: The hostname associated with the chain
914  * @proto: The protocol of the service connecting (e.g. tcp)
915  * @port: The port of the service connecting (e.g. 443)
916  * @sflags: Flags for the the initialization of @s (if NULL)
917  * @vflags: Verification flags; an OR'ed list of %dane_verify_flags_t.
918  * @verify: An OR'ed list of %dane_verify_status_t.
919  *
920  * This function will verify session's certificate chain against the
921  * CA constrains and/or the certificate available via DANE.
922  * See dane_verify_crt() for more information.
923  *
924  * This will not verify the chain for validity; unless the DANE
925  * verification is restricted to end certificates, this must be
926  * be performed separately using gnutls_certificate_verify_peers3().
927  *
928  * Returns: a negative error code on error and %DANE_E_SUCCESS (0)
929  * when the DANE entries were successfully parsed, irrespective of
930  * whether they were verified (see @verify for that information). If
931  * no usable entries were encountered %DANE_E_REQUESTED_DATA_NOT_AVAILABLE
932  * will be returned.
933  *
934  **/
935 int
936 dane_verify_session_crt(dane_state_t s,
937                         gnutls_session_t session,
938                         const char *hostname, const char *proto,
939                         unsigned int port, unsigned int sflags,
940                         unsigned int vflags, unsigned int *verify)
941 {
942         const gnutls_datum_t *cert_list;
943         unsigned int cert_list_size = 0;
944         unsigned int type;
945         int ret;
946
947         cert_list = gnutls_certificate_get_peers(session, &cert_list_size);
948         if (cert_list_size == 0) {
949                 return gnutls_assert_val(DANE_E_NO_CERT);
950         }
951
952         type = gnutls_certificate_type_get(session);
953
954         /* this list may be incomplete, try to get the self-signed CA if any */
955         if (cert_list_size > 0) {
956                 gnutls_datum_t new_cert_list[cert_list_size+1];
957                 gnutls_x509_crt_t crt, ca;
958                 gnutls_certificate_credentials_t sc;
959
960                 ret = gnutls_x509_crt_init(&crt);
961                 if (ret < 0) {
962                         gnutls_assert();
963                         goto failsafe;
964                 }
965
966                 ret = gnutls_x509_crt_import(crt, &cert_list[cert_list_size-1], GNUTLS_X509_FMT_DER);
967                 if (ret < 0) {
968                         gnutls_assert();
969                         gnutls_x509_crt_deinit(crt);
970                         goto failsafe;
971                 }
972
973                 /* if it is already self signed continue normally */
974                 ret = gnutls_x509_crt_check_issuer(crt, crt);
975                 if (ret != 0) {
976                         gnutls_assert();
977                         gnutls_x509_crt_deinit(crt);
978                         goto failsafe;
979                 }
980
981                 /* chain does not finish in a self signed cert, try to obtain the issuer */
982                 ret = gnutls_credentials_get(session, GNUTLS_CRD_CERTIFICATE, (void**)&sc);
983                 if (ret < 0) {
984                         gnutls_assert();
985                         gnutls_x509_crt_deinit(crt);
986                         goto failsafe;
987                 }
988
989                 ret = gnutls_certificate_get_issuer(sc, crt, &ca, 0);
990                 if (ret < 0) {
991                         gnutls_assert();
992                         gnutls_x509_crt_deinit(crt);
993                         goto failsafe;
994                 }
995
996                 /* make the new list */
997                 memcpy(new_cert_list, cert_list, cert_list_size*sizeof(gnutls_datum_t));
998
999                 ret = gnutls_x509_crt_export2(ca, GNUTLS_X509_FMT_DER, &new_cert_list[cert_list_size]);
1000                 if (ret < 0) {
1001                         gnutls_assert();
1002                         gnutls_x509_crt_deinit(crt);
1003                         goto failsafe;
1004                 }
1005
1006                 ret = dane_verify_crt(s, new_cert_list, cert_list_size+1, type,
1007                                hostname, proto, port, sflags, vflags,
1008                                verify);
1009                 if (ret < 0) {
1010                         gnutls_assert();
1011                 }
1012                 gnutls_free(new_cert_list[cert_list_size].data);
1013                 return ret;
1014         }
1015
1016  failsafe:
1017         return dane_verify_crt(s, cert_list, cert_list_size, type,
1018                                hostname, proto, port, sflags, vflags,
1019                                verify);
1020 }
1021
1022 /**
1023  * dane_verification_status_print:
1024  * @status: The status flags to be printed
1025  * @type: The certificate type
1026  * @out: Newly allocated datum with (0) terminated string.
1027  * @flags: should be zero
1028  *
1029  * This function will pretty print the status of a verification
1030  * process -- eg. the one obtained by dane_verify_crt().
1031  *
1032  * The output @out needs to be deallocated using gnutls_free().
1033  *
1034  * Returns: On success, %GNUTLS_E_SUCCESS (0) is returned, otherwise a
1035  *   negative error value.
1036  **/
1037 int
1038 dane_verification_status_print(unsigned int status,
1039                                gnutls_datum_t * out, unsigned int flags)
1040 {
1041         gnutls_buffer_st str;
1042         int ret;
1043
1044         _gnutls_buffer_init(&str);
1045
1046         if (status == 0)
1047                 _gnutls_buffer_append_str(&str,
1048                                           _("Certificate matches. "));
1049         else
1050                 _gnutls_buffer_append_str(&str,
1051                                           _("Verification failed. "));
1052
1053         if (status & DANE_VERIFY_CA_CONSTRAINTS_VIOLATED)
1054                 _gnutls_buffer_append_str(&str,
1055                                           _
1056                                           ("CA constrains were violated. "));
1057
1058         if (status & DANE_VERIFY_CERT_DIFFERS)
1059                 _gnutls_buffer_append_str(&str,
1060                                           _("The certificate differs. "));
1061
1062         if (status & DANE_VERIFY_NO_DANE_INFO)
1063                 _gnutls_buffer_append_str(&str,
1064                                           _
1065                                           ("There were no DANE information. "));
1066
1067         ret = _gnutls_buffer_to_datum(&str, out);
1068         if (out->size > 0)
1069                 out->size--;
1070
1071         return ret;
1072 }