1 /* dns-stuff.c - DNS related code including CERT RR (rfc-4398)
2 * Copyright (C) 2003, 2005, 2006, 2009 Free Software Foundation, Inc.
3 * Copyright (C) 2005, 2006, 2009, 2015 Werner Koch
5 * This file is part of GnuPG.
7 * This file is free software; you can redistribute it and/or modify
8 * it under the terms of either
10 * - the GNU Lesser General Public License as published by the Free
11 * Software Foundation; either version 3 of the License, or (at
12 * your option) any later version.
16 * - the GNU General Public License as published by the Free
17 * Software Foundation; either version 2 of the License, or (at
18 * your option) any later version.
20 * or both in parallel, as here.
22 * This file is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
27 * You should have received a copy of the GNU General Public License
28 * along with this program; if not, see <http://www.gnu.org/licenses/>.
32 #include <sys/types.h>
33 #ifdef HAVE_W32_SYSTEM
34 # ifdef HAVE_WINSOCK2_H
35 # include <winsock2.h>
39 # include <netinet/in.h>
40 # include <arpa/nameser.h>
49 #if !defined(HAVE_GETADDRINFO) && !defined(USE_ADNS)
50 # error Either getaddrinfo or the ADNS libary is required.
55 #include "dns-stuff.h"
59 # error AF_UNSPEC does not have the value 0
62 /* Not every installation has gotten around to supporting SRVs or
71 /* ADNS has no support for CERT yet. */
72 #define my_adns_r_cert 37
74 /* If set Tor mode shall be used. */
77 /* Sets the module in Tor mode. Returns 0 is this is possible or an
80 enable_dns_tormode (void)
82 #if defined(USE_DNS_CERT) && defined(USE_ADNS)
83 # if HAVE_ADNS_IF_TORMODE
88 return gpg_error (GPG_ERR_NOT_IMPLEMENTED);
91 /* Free an addressinfo linked list as returned by resolve_dns_name. */
93 free_dns_addrinfo (dns_addrinfo_t ai)
97 dns_addrinfo_t next = ai->next;
105 map_eai_to_gpg_error (int ec)
111 case EAI_AGAIN: err = gpg_error (GPG_ERR_EAGAIN); break;
112 case EAI_BADFLAGS: err = gpg_error (GPG_ERR_INV_FLAG); break;
113 case EAI_FAIL: err = gpg_error (GPG_ERR_SERVER_FAILED); break;
114 case EAI_MEMORY: err = gpg_error (GPG_ERR_ENOMEM); break;
115 case EAI_NODATA: err = gpg_error (GPG_ERR_NO_DATA); break;
116 case EAI_NONAME: err = gpg_error (GPG_ERR_NO_NAME); break;
117 case EAI_SERVICE: err = gpg_error (GPG_ERR_NOT_SUPPORTED); break;
118 case EAI_ADDRFAMILY:err = gpg_error (GPG_ERR_EADDRNOTAVAIL); break;
119 case EAI_FAMILY: err = gpg_error (GPG_ERR_EAFNOSUPPORT); break;
120 case EAI_SOCKTYPE: err = gpg_error (GPG_ERR_ESOCKTNOSUPPORT); break;
121 case EAI_SYSTEM: err = gpg_error_from_syserror (); break;
122 default: err = gpg_error (GPG_ERR_UNKNOWN_ERRNO); break;
128 /* Resolve a name using the standard system function. */
130 resolve_name_standard (const char *name, unsigned short port,
131 int want_family, int want_socktype,
132 dns_addrinfo_t *r_dai, char **r_canonname)
135 dns_addrinfo_t daihead = NULL;
137 struct addrinfo *aibuf = NULL;
138 struct addrinfo hints, *ai;
146 memset (&hints, 0, sizeof hints);
147 hints.ai_family = want_family;
148 hints.ai_socktype = want_socktype;
149 hints.ai_flags = AI_ADDRCONFIG;
151 hints.ai_flags |= AI_CANONNAME;
154 snprintf (portstr, sizeof portstr, "%hu", port);
158 /* We can't use the the AI_IDN flag because that does the conversion
159 using the current locale. However, GnuPG always used UTF-8. To
160 support IDN we would need to make use of the libidn API. */
161 ret = getaddrinfo (name, *portstr? portstr : NULL, &hints, &aibuf);
165 err = map_eai_to_gpg_error (ret);
169 if (r_canonname && aibuf && aibuf->ai_canonname)
171 *r_canonname = xtrystrdup (aibuf->ai_canonname);
174 err = gpg_error_from_syserror ();
179 for (ai = aibuf; ai; ai = ai->ai_next)
181 if (ai->ai_family != AF_INET6 && ai->ai_family != AF_INET)
184 dai = xtrymalloc (sizeof *dai + ai->ai_addrlen - 1);
185 dai->family = ai->ai_family;
186 dai->socktype = ai->ai_socktype;
187 dai->protocol = ai->ai_protocol;
188 dai->addrlen = ai->ai_addrlen;
189 memcpy (dai->addr, ai->ai_addr, ai->ai_addrlen);
196 freeaddrinfo (aibuf);
201 xfree (*r_canonname);
204 free_dns_addrinfo (daihead);
212 /* Resolve an address using the standard system function. */
214 resolve_addr_standard (const struct sockaddr *addr, int addrlen,
215 unsigned int flags, char **r_name)
225 buffer = xtrymalloc (buflen + 2 + 1);
227 return gpg_error_from_syserror ();
229 if ((flags & DNS_NUMERICHOST) || tor_mode)
232 ec = getnameinfo (addr, addrlen, buffer, buflen, NULL, 0, NI_NAMEREQD);
234 if (!ec && *buffer == '[')
235 ec = EAI_FAIL; /* A name may never start with a bracket. */
236 else if (ec == EAI_NONAME)
239 if (addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
244 ec = getnameinfo (addr, addrlen, p, buflen, NULL, 0, NI_NUMERICHOST);
245 if (!ec && addr->sa_family == AF_INET6 && (flags & DNS_WITHBRACKET))
246 strcat (buffer, "]");
250 err = map_eai_to_gpg_error (ec);
253 p = xtryrealloc (buffer, strlen (buffer)+1);
255 err = gpg_error_from_syserror ();
272 /* This a wrapper around getaddrinfo with slighly different semantics.
273 NAME is the name to resolve.
274 PORT is the requested port or 0.
275 WANT_FAMILY is either 0 (AF_UNSPEC), AF_INET6, or AF_INET4.
276 WANT_SOCKETTYPE is either SOCK_STREAM or SOCK_DGRAM.
278 On success the result is stored in a linked list with the head
279 stored at the address R_AI; the caller must call gpg_addrinfo_free
280 on this. If R_CANONNAME is not NULL the official name of the host
281 is stored there as a malloced string; if that name is not available
284 resolve_dns_name (const char *name, unsigned short port,
285 int want_family, int want_socktype,
286 dns_addrinfo_t *r_ai, char **r_canonname)
288 #ifdef USE_ADNS_disabled_for_now
289 return resolve_name_adns (name, port, want_family, want_socktype,
292 return resolve_name_standard (name, port, want_family, want_socktype,
299 resolve_dns_addr (const struct sockaddr *addr, int addrlen,
300 unsigned int flags, char **r_name)
302 #ifdef USE_ADNS_disabled_for_now
303 return resolve_addr_adns (addr, addrlen, flags, r_name);
305 return resolve_addr_standard (addr, addrlen, flags, r_name);
310 /* Check whether NAME is an IP address. Returns true if it is either
311 an IPv6 or IPv4 numerical address. */
313 is_ip_address (const char *name)
316 int ndots, dblcol, n;
319 return 1; /* yes: A legal DNS name may not contain this character;
320 this mut be bracketed v6 address. */
322 return 0; /* No. A leading dot is not a valid IP address. */
324 /* Check whether this is a v6 address. */
325 ndots = n = dblcol = 0;
326 for (s=name; *s; s++)
335 return 0; /* No: Only one "::" allowed. */
344 else if (!strchr ("0123456789abcdefABCDEF", *s))
345 return 0; /* No: Not a hex digit. */
347 return 0; /* To many digits in a group. */
350 return 0; /* No: Too many colons. */
352 return 1; /* Yes: At least 2 colons indicate an v6 address. */
355 /* Check whether it is legacy IP address. */
357 for (s=name; *s; s++)
362 return 0; /* No: Douple dot. */
363 if (atoi (s+1) > 255)
364 return 0; /* No: Ipv4 byte value too large. */
368 else if (!strchr ("0123456789", *s))
369 return 0; /* No: Not a digit. */
371 return 0; /* No: More than 3 digits. */
373 return !!(ndots == 3);
378 /* Init ADNS and store the new state at R_STATE. Returns 0 on
379 success; prints an error message and returns an error code on
382 my_adns_init (adns_state *r_state)
386 if (tor_mode? adns_init_strcfg (r_state,
387 adns_if_noerrprint|adns_if_tormode,
388 NULL, "nameserver 8.8.8.8")
389 /* */: adns_init (r_state, adns_if_noerrprint, NULL))
391 err = gpg_err_make (default_errsource, gpg_err_code_from_syserror ());
392 log_error ("error initializing adns: %s\n", gpg_strerror (err));
400 /* Returns 0 on success or an error code. If a PGP CERT record was
401 found, the malloced data is returned at (R_KEY, R_KEYLEN) and
402 the other return parameters are set to NULL/0. If an IPGP CERT
403 record was found the fingerprint is stored as an allocated block at
404 R_FPR and its length at R_FPRLEN; an URL is is allocated as a
405 string and returned at R_URL. If WANT_CERTTYPE is 0 this function
406 returns the first CERT found with a supported type; it is expected
407 that only one CERT record is used. If WANT_CERTTYPE is one of the
408 supported certtypes only records with this certtype are considered
409 and the first found is returned. (R_KEY,R_KEYLEN) are optional. */
411 get_dns_cert (const char *name, int want_certtype,
412 void **r_key, size_t *r_keylen,
413 unsigned char **r_fpr, size_t *r_fprlen, char **r_url)
419 adns_answer *answer = NULL;
431 err = my_adns_init (&state);
435 if (adns_synchronous (state, name,
437 | (want_certtype < DNS_CERTTYPE_RRBASE
439 : (want_certtype - DNS_CERTTYPE_RRBASE))),
440 adns_qf_quoteok_query, &answer))
442 err = gpg_err_make (default_errsource, gpg_err_code_from_syserror ());
443 /* log_error ("DNS query failed: %s\n", strerror (errno)); */
447 if (answer->status != adns_s_ok)
449 /* log_error ("DNS query returned an error: %s (%s)\n", */
450 /* adns_strerror (answer->status), */
451 /* adns_errabbrev (answer->status)); */
452 err = gpg_err_make (default_errsource, GPG_ERR_NOT_FOUND);
456 err = gpg_err_make (default_errsource, GPG_ERR_NOT_FOUND);
457 for (count = 0; count < answer->nrrs; count++)
459 int datalen = answer->rrs.byteblock[count].len;
460 const unsigned char *data = answer->rrs.byteblock[count].data;
462 /* First check for our generic RR hack. */
464 && want_certtype >= DNS_CERTTYPE_RRBASE
465 && ((want_certtype - DNS_CERTTYPE_RRBASE)
466 == (answer->type & ~adns_r_unknown)))
468 /* Found the requested record - return it. */
469 *r_key = xtrymalloc (datalen);
471 err = gpg_err_make (default_errsource,
472 gpg_err_code_from_syserror ());
475 memcpy (*r_key, data, datalen);
483 continue; /* Truncated CERT record - skip. */
485 ctype = buf16_to_uint (data);
486 /* (key tag and algorithm fields are not required.) */
490 if (want_certtype && want_certtype != ctype)
491 ; /* Not of the requested certtype. */
492 else if (ctype == DNS_CERTTYPE_PGP && datalen >= 11 && r_key && r_keylen)
494 /* CERT type is PGP. Gpg checks for a minimum length of 11,
495 thus we do the same. */
496 *r_key = xtrymalloc (datalen);
498 err = gpg_err_make (default_errsource,
499 gpg_err_code_from_syserror ());
502 memcpy (*r_key, data, datalen);
508 else if (ctype == DNS_CERTTYPE_IPGP && datalen && datalen < 1023
509 && datalen >= data[0] + 1 && r_fpr && r_fprlen && r_url)
511 /* CERT type is IPGP. We made sure that the data is
512 plausible and that the caller requested this
517 *r_fpr = xtrymalloc (*r_fprlen);
520 err = gpg_err_make (default_errsource,
521 gpg_err_code_from_syserror ());
524 memcpy (*r_fpr, data + 1, *r_fprlen);
529 if (datalen > *r_fprlen + 1)
531 *r_url = xtrymalloc (datalen - (*r_fprlen + 1) + 1);
534 err = gpg_err_make (default_errsource,
535 gpg_err_code_from_syserror ());
541 data + (*r_fprlen + 1), datalen - (*r_fprlen + 1));
542 (*r_url)[datalen - (*r_fprlen + 1)] = '\0';
560 unsigned char *answer;
572 /* Allocate a 64k buffer which is the limit for an DNS response. */
573 answer = xtrymalloc (65536);
575 return gpg_err_make (default_errsource, gpg_err_code_from_syserror ());
577 err = gpg_err_make (default_errsource, GPG_ERR_NOT_FOUND);
579 r = res_query (name, C_IN,
580 (want_certtype < DNS_CERTTYPE_RRBASE
582 : (want_certtype - DNS_CERTTYPE_RRBASE)),
584 /* Not too big, not too small, no errors and at least 1 answer. */
585 if (r >= sizeof (HEADER) && r <= 65536
586 && (((HEADER *) answer)->rcode) == NOERROR
587 && (count = ntohs (((HEADER *) answer)->ancount)))
590 unsigned char *pt, *emsg;
594 pt = &answer[sizeof (HEADER)];
596 /* Skip over the query */
598 rc = dn_skipname (pt, emsg);
601 err = gpg_err_make (default_errsource, GPG_ERR_INV_OBJ);
606 /* There are several possible response types for a CERT request.
607 We're interested in the PGP (a key) and IPGP (a URI) types.
608 Skip all others. TODO: A key is better than a URI since
609 we've gone through all this bother to fetch it, so favor that
610 if we have both PGP and IPGP? */
612 while (count-- > 0 && pt < emsg)
614 u16 type, class, dlen, ctype;
616 rc = dn_skipname (pt, emsg); /* the name we just queried for */
619 err = gpg_err_make (default_errsource, GPG_ERR_INV_OBJ);
625 /* Truncated message? 15 bytes takes us to the point where
626 we start looking at the ctype. */
627 if ((emsg - pt) < 15)
630 type = buf16_to_u16 (pt);
633 class = buf16_to_u16 (pt);
643 dlen = buf16_to_u16 (pt);
646 /* Check the type and parse. */
647 if (want_certtype >= DNS_CERTTYPE_RRBASE
648 && type == (want_certtype - DNS_CERTTYPE_RRBASE)
651 *r_key = xtrymalloc (dlen);
653 err = gpg_err_make (default_errsource,
654 gpg_err_code_from_syserror ());
657 memcpy (*r_key, pt, dlen);
663 else if (want_certtype >= DNS_CERTTYPE_RRBASE)
665 /* We did not found the requested RR. */
668 else if (type == T_CERT)
670 /* We got a CERT type. */
671 ctype = buf16_to_u16 (pt);
674 /* Skip the CERT key tag and algo which we don't need. */
679 /* 15 bytes takes us to here */
680 if (want_certtype && want_certtype != ctype)
681 ; /* Not of the requested certtype. */
682 else if (ctype == DNS_CERTTYPE_PGP && dlen && r_key && r_keylen)
685 *r_key = xtrymalloc (dlen);
687 err = gpg_err_make (default_errsource,
688 gpg_err_code_from_syserror ());
691 memcpy (*r_key, pt, dlen);
697 else if (ctype == DNS_CERTTYPE_IPGP
698 && dlen && dlen < 1023 && dlen >= pt[0] + 1)
704 *r_fpr = xtrymalloc (*r_fprlen);
707 err = gpg_err_make (default_errsource,
708 gpg_err_code_from_syserror ());
711 memcpy (*r_fpr, &pt[1], *r_fprlen);
716 if (dlen > *r_fprlen + 1)
718 *r_url = xtrymalloc (dlen - (*r_fprlen + 1) + 1);
721 err = gpg_err_make (default_errsource,
722 gpg_err_code_from_syserror ());
727 memcpy (*r_url, &pt[*r_fprlen + 1],
728 dlen - (*r_fprlen + 1));
729 (*r_url)[dlen - (*r_fprlen + 1)] = '\0';
738 /* No subtype matches, so continue with the next answer. */
743 /* Not a requested type - might be a CNAME. Try next item. */
753 #endif /*!USE_ADNS */
754 #else /* !USE_DNS_CERT */
764 return gpg_err_make (default_errsource, GPG_ERR_NOT_SUPPORTED);
770 priosort(const void *a,const void *b)
772 const struct srventry *sa=a,*sb=b;
773 if(sa->priority>sb->priority)
775 else if(sa->priority<sb->priority)
783 getsrv (const char *name,struct srventry **list)
794 adns_answer *answer = NULL;
796 if (my_adns_init (&state))
799 rc = adns_synchronous (state, name, adns_r_srv, adns_qf_quoteok_query,
803 log_error ("DNS query failed: %s\n", strerror (errno));
807 if (answer->status != adns_s_ok
808 || answer->type != adns_r_srv || !answer->nrrs)
810 log_error ("DNS query returned an error or no records: %s (%s)\n",
811 adns_strerror (answer->status),
812 adns_errabbrev (answer->status));
818 for (count = 0; count < answer->nrrs; count++)
820 struct srventry *srv = NULL;
821 struct srventry *newlist;
823 if (strlen (answer->rrs.srvha[count].ha.host) >= sizeof srv->target)
825 log_info ("hostname in SRV record too long - skipped\n");
829 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
833 memset (&(*list)[srvcount], 0, sizeof(struct srventry));
834 srv = &(*list)[srvcount];
837 srv->priority = answer->rrs.srvha[count].priority;
838 srv->weight = answer->rrs.srvha[count].weight;
839 srv->port = answer->rrs.srvha[count].port;
840 strcpy (srv->target, answer->rrs.srvha[count].ha.host);
848 unsigned char answer[2048];
849 HEADER *header = (HEADER *)answer;
850 unsigned char *pt, *emsg;
854 /* Do not allow a query using the standard resolver in Tor mode. */
858 r = res_query (name, C_IN, T_SRV, answer, sizeof answer);
859 if (r < sizeof (HEADER) || r > sizeof answer)
861 if (header->rcode != NOERROR || !(count=ntohs (header->ancount)))
862 return 0; /* Error or no record found. */
865 pt = &answer[sizeof(HEADER)];
867 /* Skip over the query */
868 rc = dn_skipname (pt, emsg);
874 while (count-- > 0 && pt < emsg)
876 struct srventry *srv=NULL;
878 struct srventry *newlist;
880 newlist = xtryrealloc (*list, (srvcount+1)*sizeof(struct srventry));
884 memset(&(*list)[srvcount],0,sizeof(struct srventry));
885 srv=&(*list)[srvcount];
888 rc = dn_skipname(pt,emsg); /* the name we just queried for */
893 /* Truncated message? */
897 type = buf16_to_u16 (pt);
899 /* We asked for SRV and got something else !? */
903 class = buf16_to_u16 (pt);
905 /* We asked for IN and got something else !? */
910 dlen = buf16_to_u16 (pt);
913 srv->priority = buf16_to_ushort (pt);
915 srv->weight = buf16_to_ushort (pt);
917 srv->port = buf16_to_ushort (pt);
920 /* Get the name. 2782 doesn't allow name compression, but
921 dn_expand still works to pull the name out of the
923 rc = dn_expand(answer,emsg,pt,srv->target, sizeof srv->target);
924 if (rc == 1 && srv->target[0] == 0) /* "." */
933 /* Corrupt packet? */
940 /* Now we have an array of all the srv records. */
942 /* Order by priority */
943 qsort(*list,srvcount,sizeof(struct srventry),priosort);
945 /* For each priority, move the zero-weighted items first. */
946 for (i=0; i < srvcount; i++)
950 for (j=i;j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
952 if((*list)[j].weight==0)
957 struct srventry temp;
959 memcpy (&temp,&(*list)[j],sizeof(struct srventry));
960 memcpy (&(*list)[j],&(*list)[i],sizeof(struct srventry));
961 memcpy (&(*list)[i],&temp,sizeof(struct srventry));
969 /* Run the RFC-2782 weighting algorithm. We don't need very high
970 quality randomness for this, so regular libc srand/rand is
971 sufficient. Fixme: It is a bit questionaly to reinitalize srand
972 - better use a gnupg fucntion for this. */
973 srand(time(NULL)*getpid());
975 for (i=0; i < srvcount; i++)
978 float prio_count=0,chose;
980 for (j=i; j < srvcount && (*list)[i].priority == (*list)[j].priority; j++)
982 prio_count+=(*list)[j].weight;
983 (*list)[j].run_count=prio_count;
986 chose=prio_count*rand()/RAND_MAX;
988 for (j=i;j<srvcount && (*list)[i].priority==(*list)[j].priority;j++)
990 if (chose<=(*list)[j].run_count)
995 struct srventry temp;
997 memcpy(&temp,&(*list)[j],sizeof(struct srventry));
998 memcpy(&(*list)[j],&(*list)[i],sizeof(struct srventry));
999 memcpy(&(*list)[i],&temp,sizeof(struct srventry));
1013 #endif /*USE_DNS_SRV*/