1 /*************************************************
2 * Exim - an Internet mail transport agent *
3 *************************************************/
5 /* Copyright (c) The Exim Maintainers 2020 - 2022 */
6 /* Copyright (c) University of Cambridge 1995 - 2018 */
7 /* See the file NOTICE for conditions of use and distribution. */
8 /* SPDX-License-Identifier: GPL-2.0-or-later */
11 #include "lf_functions.h"
15 /* Ancient systems (e.g. SunOS4) don't appear to have T_TXT defined in their
22 /* Many systems do not have T_SPF. */
27 /* New TLSA record for DANE */
32 /* Table of recognized DNS record types and their integer values. */
34 static const char *type_names[] = {
54 static int type_values[] = {
57 T_ADDRESSES, /* Private type for AAAA + A */
61 T_CSA, /* Private type for "Client SMTP Authorization". */
63 T_MXH, /* Private type for "MX hostnames" */
71 T_ZNS /* Private type for "zone nameservers" */
75 /*************************************************
77 *************************************************/
79 /* See local README for interface description. */
82 dnsdb_open(const uschar * filename, uschar **errmsg)
84 return (void *)(-1); /* Any non-0 value */
89 /*************************************************
90 * Find entry point for dnsdb *
91 *************************************************/
93 /* See local README for interface description. The query in the "keystring" may
94 consist of a number of parts.
96 (a) If the first significant character is '>' then the next character is the
97 separator character that is used when multiple records are found. The default
100 (b) If the next character is ',' then the next character is the separator
101 character used for multiple items of text in "TXT" records. Alternatively,
102 if the next character is ';' then these multiple items are concatenated with
103 no separator. With neither of these options specified, only the first item
104 is output. Similarly for "SPF" records, but the default for joining multiple
105 items in one SPF record is the empty string, for direct concatenation.
107 (c) Options, all comma-terminated, in any order. Any unrecognised option
108 terminates option processing. Recognised options are:
110 - 'defer_FOO': set the defer behaviour to FOO. The possible behaviours are:
111 'strict', where any defer causes the whole lookup to defer; 'lax', where a defer
112 causes the whole lookup to defer only if none of the DNS queries succeeds; and
113 'never', where all defers are as if the lookup failed. The default is 'lax'.
115 - 'dnssec_FOO', with 'strict', 'lax' (default), and 'never'. The meanings are
116 require, try and don't-try dnssec respectively.
118 - 'retrans_VAL', set the timeout value. VAL is an Exim time specification
119 (eg "5s"). The default is set by the main configuration option 'dns_retrans'.
121 - 'retry_VAL', set the retry count on timeouts. VAL is an integer. The
122 default is set by the main configuration option "dns_retry".
124 (d) If the next sequence of characters is a sequence of letters and digits
125 followed by '=', it is interpreted as the name of the DNS record type. The
128 (e) Then there follows list of domain names. This is a generalized Exim list,
129 which may start with '<' in order to set a specific separator. The default
130 separator, as always, is colon. */
133 dnsdb_find(void * handle, const uschar * filename, const uschar * keystring,
134 int length, uschar ** result, uschar ** errmsg, uint * do_cache,
139 int defer_mode = PASS, dnssec_mode = PASS;
140 int save_retrans = dns_retrans, save_retry = dns_retry;
143 const uschar * outsep = CUS"\n", * outsep2 = NULL;
144 uschar * equals, * domain, * found;
146 dns_answer * dnsa = store_get_dns_answer();
149 /* Because we're working in the search pool, we try to reclaim as much
150 store as possible later, so we preallocate the result here */
152 gstring * yield = string_get(256);
154 /* If the string starts with '>' we change the output separator.
155 If it's followed by ';' or ',' we set the TXT output separator. */
157 while (isspace(*keystring)) keystring++;
158 if (*keystring == '>')
160 outsep = keystring + 1;
162 if (*keystring == ',')
164 outsep2 = keystring + 1;
167 else if (*keystring == ';')
172 while (isspace(*keystring)) keystring++;
175 /* Check for a modifier keyword. */
179 if (strncmpic(keystring, US"defer_", 6) == 0)
182 if (strncmpic(keystring, US"strict", 6) == 0)
183 { defer_mode = DEFER; keystring += 6; }
184 else if (strncmpic(keystring, US"lax", 3) == 0)
185 { defer_mode = PASS; keystring += 3; }
186 else if (strncmpic(keystring, US"never", 5) == 0)
187 { defer_mode = OK; keystring += 5; }
190 *errmsg = US"unsupported dnsdb defer behaviour";
195 else if (strncmpic(keystring, US"dnssec_", 7) == 0)
198 if (strncmpic(keystring, US"strict", 6) == 0)
199 { dnssec_mode = DEFER; keystring += 6; }
200 else if (strncmpic(keystring, US"lax", 3) == 0)
201 { dnssec_mode = PASS; keystring += 3; }
202 else if (strncmpic(keystring, US"never", 5) == 0)
203 { dnssec_mode = OK; keystring += 5; }
206 *errmsg = US"unsupported dnsdb dnssec behaviour";
211 else if (strncmpic(keystring, US"retrans_", 8) == 0)
214 if ((timeout_sec = readconf_readtime(keystring += 8, ',', FALSE)) <= 0)
216 *errmsg = US"unsupported dnsdb timeout value";
220 dns_retrans = timeout_sec;
221 while (*keystring != ',') keystring++;
223 else if (strncmpic(keystring, US"retry_", 6) == 0)
226 if ((retries = (int)strtol(CCS keystring + 6, CSS &keystring, 0)) < 0)
228 *errmsg = US"unsupported dnsdb retry count";
237 while (isspace(*keystring)) keystring++;
238 if (*keystring++ != ',')
240 *errmsg = US"dnsdb modifier syntax error";
244 while (isspace(*keystring)) keystring++;
247 /* Figure out the "type" value if it is not T_TXT.
248 If the keystring contains an = this must be preceded by a valid type name. */
251 if ((equals = Ustrchr(keystring, '=')) != NULL)
254 uschar *tend = equals;
256 while (tend > keystring && isspace(tend[-1])) tend--;
257 len = tend - keystring;
259 for (i = 0; i < nelem(type_names); i++)
260 if (len == Ustrlen(type_names[i]) &&
261 strncmpic(keystring, US type_names[i], len) == 0)
263 type = type_values[i];
267 if (i >= nelem(type_names))
269 *errmsg = US"unsupported DNS record type";
274 keystring = equals + 1;
275 while (isspace(*keystring)) keystring++;
278 /* Initialize the resolver in case this is the first time it has been used. */
280 dns_init(FALSE, FALSE, dnssec_mode != OK);
282 /* The remainder of the string must be a list of domains. As long as the lookup
283 for at least one of them succeeds, we return success. Failure means that none
286 The original implementation did not support a list of domains. Adding the list
287 feature is compatible, except in one case: when PTR records are being looked up
288 for a single IPv6 address. Fortunately, we can hack in a compatibility feature
289 here: If the type is PTR and no list separator is specified, and the entire
290 remaining string is valid as an IP address, set an impossible separator so that
291 it is treated as one item. */
293 if (type == T_PTR && keystring[0] != '<' &&
294 string_is_ip_address(keystring, NULL) != 0)
297 /* SPF strings should be concatenated without a separator, thus make
298 it the default if not defined (see RFC 4408 section 3.1.3).
299 Multiple SPF records are forbidden (section 3.1.2) but are currently
300 not handled specially, thus they are concatenated with \n by default.
301 MX priority and value are space-separated by default.
302 SRV and TLSA record parts are space-separated by default. */
304 if (!outsep2) switch(type)
306 case T_SPF: outsep2 = US""; break;
307 case T_SRV: case T_MX: case T_TLSA: outsep2 = US" "; break;
310 /* Now scan the list and do a lookup for each item */
312 while ((domain = string_nextinlist(&keystring, &sep, NULL, 0)))
314 int searchtype = type == T_CSA ? T_SRV : /* record type we want */
315 type == T_MXH ? T_MX :
316 type == T_ZNS ? T_NS : type;
318 /* If the type is PTR or CSA, we have to construct the relevant magic lookup
319 key if the original is an IP address (some experimental protocols are using
320 PTR records for different purposes where the key string is a host name, and
321 Exim's extended CSA can be keyed by domains or IP addresses). This code for
322 doing the reversal is now in a separate function. */
324 if ((type == T_PTR || type == T_CSA) &&
325 string_is_ip_address(domain, NULL) != 0)
326 domain = dns_build_reverse(domain);
330 DEBUG(D_lookup) debug_printf_indent("dnsdb key: %s\n", domain);
332 /* Do the lookup and sort out the result. There are four special types that
333 are handled specially: T_CSA, T_ZNS, T_ADDRESSES and T_MXH.
334 The first two are handled in a special lookup function so that the facility
335 could be used from other parts of the Exim code. T_ADDRESSES is handled by looping
336 over the types of A lookup. T_MXH affects only what happens later on in
337 this function, but for tidiness it is handled by the "special". If the
338 lookup fails, continue with the next domain. In the case of DEFER, adjust
339 the final "nothing found" result, but carry on to the next domain. */
343 if (type == T_ADDRESSES) /* NB cannot happen unless HAVE_IPV6 */
345 if (searchtype == T_ADDRESSES) searchtype = T_AAAA;
346 else if (searchtype == T_AAAA) searchtype = T_A;
347 rc = dns_special_lookup(dnsa, domain, searchtype, CUSS &found);
351 rc = dns_special_lookup(dnsa, domain, type, CUSS &found);
353 lookup_dnssec_authenticated = dnssec_mode==OK ? NULL
354 : dns_is_secure(dnsa) ? US"yes" : US"no";
356 if (rc == DNS_NOMATCH || rc == DNS_NODATA) continue;
357 if ( rc != DNS_SUCCEED
358 || (dnssec_mode == DEFER && !dns_is_secure(dnsa))
361 if (defer_mode == DEFER)
363 dns_retrans = save_retrans;
364 dns_retry = save_retry;
365 dns_init(FALSE, FALSE, FALSE); /* clr dnssec bit */
366 rc = DEFER; /* always defer */
369 if (defer_mode == PASS) failrc = DEFER; /* defer only if all do */
370 continue; /* treat defer as fail */
374 /* Search the returned records */
376 for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
377 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)) if (rr->type == searchtype)
379 if (*do_cache > rr->ttl)
382 if (type == T_A || type == T_AAAA || type == T_ADDRESSES)
384 for (dns_address * da = dns_address_from_rr(dnsa, rr); da; da = da->next)
385 yield = string_append_listele(yield, *outsep, da->address);
389 /* Other kinds of record just have one piece of data each, but there may be
390 several of them, of course. */
392 if (yield->ptr) yield = string_catn(yield, outsep, 1);
394 if (type == T_TXT || type == T_SPF)
396 if (!outsep2) /* output only the first item of data */
398 uschar n = (rr->data)[0];
399 /* size byte + data bytes must not excced the RRs length */
400 if (n + 1 <= rr->size)
401 yield = string_catn(yield, US (rr->data+1), n);
404 for (unsigned data_offset = 0; data_offset < rr->size; )
406 uschar chunk_len = (rr->data)[data_offset];
407 int remain = rr->size - data_offset;
409 /* Apparently there are resolvers that do not check RRs before passing
410 them on, and glibc fails to do so. So every application must...
411 Check for chunk len exceeding RR */
413 if (chunk_len > remain)
416 if (*outsep2 && data_offset != 0)
417 yield = string_catn(yield, outsep2, 1);
418 yield = string_catn(yield, US ((rr->data) + ++data_offset), --chunk_len);
419 data_offset += chunk_len;
422 else if (type == T_TLSA)
427 uint8_t usage, selector, matching_type;
428 uint16_t payload_length;
429 uschar s[MAX_TLSA_EXPANDED_SIZE];
431 uschar * p = US rr->data;
435 matching_type = *p++;
436 /* What's left after removing the first 3 bytes above */
437 payload_length = rr->size - 3;
438 sp += sprintf(CS s, "%d%c%d%c%d%c", usage, *outsep2,
439 selector, *outsep2, matching_type, *outsep2);
440 /* Now append the cert/identifier, one hex char at a time */
441 while (payload_length-- > 0 && sp-s < (MAX_TLSA_EXPANDED_SIZE - 4))
442 sp += sprintf(CS sp, "%02x", *p++);
444 yield = string_cat(yield, s);
446 else /* T_CNAME, T_CSA, T_MX, T_MXH, T_NS, T_PTR, T_SOA, T_SRV */
448 int priority, weight, port;
450 uschar * p = US rr->data;
455 if (rr->size < sizeof(u_int16_t)) continue;
456 /* mxh ignores the priority number and includes only the hostnames */
457 GETSHORT(priority, p);
461 if (rr->size < sizeof(u_int16_t)) continue;
462 GETSHORT(priority, p);
463 sprintf(CS s, "%d%c", priority, *outsep2);
464 yield = string_cat(yield, s);
468 if (rr->size < 3*sizeof(u_int16_t)) continue;
469 GETSHORT(priority, p);
472 sprintf(CS s, "%d%c%d%c%d%c", priority, *outsep2,
473 weight, *outsep2, port, *outsep2);
474 yield = string_cat(yield, s);
478 if (rr->size < 3*sizeof(u_int16_t)) continue;
479 /* See acl_verify_csa() for more comments about CSA. */
480 GETSHORT(priority, p);
484 if (priority != 1) continue; /* CSA version must be 1 */
486 /* If the CSA record we found is not the one we asked for, analyse
487 the subdomain assertions in the port field, else analyse the direct
488 authorization status in the weight field. */
490 if (Ustrcmp(found, domain) != 0)
492 if (port & 1) *s = 'X'; /* explicit authorization required */
493 else *s = '?'; /* no subdomain assertions here */
497 if (weight < 2) *s = 'N'; /* not authorized */
498 else if (weight == 2) *s = 'Y'; /* authorized */
499 else if (weight == 3) *s = '?'; /* unauthorizable */
500 else continue; /* invalid */
504 yield = string_catn(yield, s, 2);
511 /* GETSHORT() has advanced the pointer to the target domain. */
513 rc = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, p,
514 (DN_EXPAND_ARG4_TYPE)s, sizeof(s));
516 /* If an overlong response was received, the data will have been
517 truncated and dn_expand may fail. */
521 log_write(0, LOG_MAIN, "host name alias list truncated: type=%s "
522 "domain=%s", dns_text_type(type), domain);
525 else yield = string_cat(yield, s);
527 if (type == T_SOA && outsep2 != NULL)
529 unsigned long serial = 0, refresh = 0, retry = 0, expire = 0, minimum = 0;
532 yield = string_catn(yield, outsep2, 1);
534 rc = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, p,
535 (DN_EXPAND_ARG4_TYPE)s, sizeof(s));
538 log_write(0, LOG_MAIN, "responsible-mailbox truncated: type=%s "
539 "domain=%s", dns_text_type(type), domain);
542 else yield = string_cat(yield, s);
545 if (rr->size >= p - rr->data - 5*sizeof(u_int32_t))
547 GETLONG(serial, p); GETLONG(refresh, p);
548 GETLONG(retry, p); GETLONG(expire, p); GETLONG(minimum, p);
550 sprintf(CS s, "%c%lu%c%lu%c%lu%c%lu%c%lu",
551 *outsep2, serial, *outsep2, refresh,
552 *outsep2, retry, *outsep2, expire, *outsep2, minimum);
553 yield = string_cat(yield, s);
556 } /* Loop for list of returned records */
558 /* Loop for set of A-lookup types */
559 } while (type == T_ADDRESSES && searchtype != T_A);
561 } /* Loop for list of domains */
563 /* Reclaim unused memory */
565 gstring_release_unused(yield);
567 /* If yield NULL we have not found anything. Otherwise, insert the terminating
568 zero and return the result. */
570 dns_retrans = save_retrans;
571 dns_retry = save_retry;
572 dns_init(FALSE, FALSE, FALSE); /* clear the dnssec bit for getaddrbyname */
574 if (!yield || !yield->ptr)
578 *result = string_from_gstring(yield);
584 store_free_dns_answer(dnsa);
590 /*************************************************
591 * Version reporting entry point *
592 *************************************************/
594 /* See local README for interface description. */
596 #include "../version.h"
599 dnsdb_version_report(gstring * g)
602 g = string_fmt_append(g, "Library version: DNSDB: Exim version %s\n", EXIM_VERSION_STR);
608 static lookup_info _lookup_info = {
609 .name = US"dnsdb", /* lookup name */
610 .type = lookup_querystyle, /* query style */
611 .open = dnsdb_open, /* open function */
612 .check = NULL, /* check function */
613 .find = dnsdb_find, /* find function */
614 .close = NULL, /* no close function */
615 .tidy = NULL, /* no tidy function */
616 .quote = NULL, /* no quoting function */
617 .version_report = dnsdb_version_report /* version reporting */
621 #define dnsdb_lookup_module_info _lookup_module_info
624 static lookup_info *_lookup_list[] = { &_lookup_info };
625 lookup_module_info dnsdb_lookup_module_info = { LOOKUP_MODULE_INFO_MAGIC, _lookup_list, 1 };
629 /* End of lookups/dnsdb.c */