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. */
10 #include "lf_functions.h"
14 /* Ancient systems (e.g. SunOS4) don't appear to have T_TXT defined in their
21 /* Many systems do not have T_SPF. */
26 /* New TLSA record for DANE */
31 /* Table of recognized DNS record types and their integer values. */
33 static const char *type_names[] = {
53 static int type_values[] = {
56 T_ADDRESSES, /* Private type for AAAA + A */
60 T_CSA, /* Private type for "Client SMTP Authorization". */
62 T_MXH, /* Private type for "MX hostnames" */
70 T_ZNS /* Private type for "zone nameservers" */
74 /*************************************************
76 *************************************************/
78 /* See local README for interface description. */
81 dnsdb_open(const uschar * filename, uschar **errmsg)
83 return (void *)(-1); /* Any non-0 value */
88 /*************************************************
89 * Find entry point for dnsdb *
90 *************************************************/
92 /* See local README for interface description. The query in the "keystring" may
93 consist of a number of parts.
95 (a) If the first significant character is '>' then the next character is the
96 separator character that is used when multiple records are found. The default
99 (b) If the next character is ',' then the next character is the separator
100 character used for multiple items of text in "TXT" records. Alternatively,
101 if the next character is ';' then these multiple items are concatenated with
102 no separator. With neither of these options specified, only the first item
103 is output. Similarly for "SPF" records, but the default for joining multiple
104 items in one SPF record is the empty string, for direct concatenation.
106 (c) Options, all comma-terminated, in any order. Any unrecognised option
107 terminates option processing. Recognised options are:
109 - 'defer_FOO': set the defer behaviour to FOO. The possible behaviours are:
110 'strict', where any defer causes the whole lookup to defer; 'lax', where a defer
111 causes the whole lookup to defer only if none of the DNS queries succeeds; and
112 'never', where all defers are as if the lookup failed. The default is 'lax'.
114 - 'dnssec_FOO', with 'strict', 'lax' (default), and 'never'. The meanings are
115 require, try and don't-try dnssec respectively.
117 - 'retrans_VAL', set the timeout value. VAL is an Exim time specification
118 (eg "5s"). The default is set by the main configuration option 'dns_retrans'.
120 - 'retry_VAL', set the retry count on timeouts. VAL is an integer. The
121 default is set by the main configuration option "dns_retry".
123 (d) If the next sequence of characters is a sequence of letters and digits
124 followed by '=', it is interpreted as the name of the DNS record type. The
127 (e) Then there follows list of domain names. This is a generalized Exim list,
128 which may start with '<' in order to set a specific separator. The default
129 separator, as always, is colon. */
132 dnsdb_find(void * handle, const uschar * filename, const uschar * keystring,
133 int length, uschar ** result, uschar ** errmsg, uint * do_cache,
138 int defer_mode = PASS;
139 int dnssec_mode = PASS;
140 int save_retrans = dns_retrans;
141 int save_retry = dns_retry;
144 const uschar *outsep = CUS"\n";
145 const uschar *outsep2 = NULL;
146 uschar *equals, *domain, *found;
148 dns_answer * dnsa = store_get_dns_answer();
151 /* Because we're working in the search pool, we try to reclaim as much
152 store as possible later, so we preallocate the result here */
154 gstring * yield = string_get(256);
156 /* If the string starts with '>' we change the output separator.
157 If it's followed by ';' or ',' we set the TXT output separator. */
159 while (isspace(*keystring)) keystring++;
160 if (*keystring == '>')
162 outsep = keystring + 1;
164 if (*keystring == ',')
166 outsep2 = keystring + 1;
169 else if (*keystring == ';')
174 while (isspace(*keystring)) keystring++;
177 /* Check for a modifier keyword. */
181 if (strncmpic(keystring, US"defer_", 6) == 0)
184 if (strncmpic(keystring, US"strict", 6) == 0)
185 { defer_mode = DEFER; keystring += 6; }
186 else if (strncmpic(keystring, US"lax", 3) == 0)
187 { defer_mode = PASS; keystring += 3; }
188 else if (strncmpic(keystring, US"never", 5) == 0)
189 { defer_mode = OK; keystring += 5; }
192 *errmsg = US"unsupported dnsdb defer behaviour";
197 else if (strncmpic(keystring, US"dnssec_", 7) == 0)
200 if (strncmpic(keystring, US"strict", 6) == 0)
201 { dnssec_mode = DEFER; keystring += 6; }
202 else if (strncmpic(keystring, US"lax", 3) == 0)
203 { dnssec_mode = PASS; keystring += 3; }
204 else if (strncmpic(keystring, US"never", 5) == 0)
205 { dnssec_mode = OK; keystring += 5; }
208 *errmsg = US"unsupported dnsdb dnssec behaviour";
213 else if (strncmpic(keystring, US"retrans_", 8) == 0)
216 if ((timeout_sec = readconf_readtime(keystring += 8, ',', FALSE)) <= 0)
218 *errmsg = US"unsupported dnsdb timeout value";
222 dns_retrans = timeout_sec;
223 while (*keystring != ',') keystring++;
225 else if (strncmpic(keystring, US"retry_", 6) == 0)
228 if ((retries = (int)strtol(CCS keystring + 6, CSS &keystring, 0)) < 0)
230 *errmsg = US"unsupported dnsdb retry count";
239 while (isspace(*keystring)) keystring++;
240 if (*keystring++ != ',')
242 *errmsg = US"dnsdb modifier syntax error";
246 while (isspace(*keystring)) keystring++;
249 /* Figure out the "type" value if it is not T_TXT.
250 If the keystring contains an = this must be preceded by a valid type name. */
253 if ((equals = Ustrchr(keystring, '=')) != NULL)
256 uschar *tend = equals;
258 while (tend > keystring && isspace(tend[-1])) tend--;
259 len = tend - keystring;
261 for (i = 0; i < nelem(type_names); i++)
262 if (len == Ustrlen(type_names[i]) &&
263 strncmpic(keystring, US type_names[i], len) == 0)
265 type = type_values[i];
269 if (i >= nelem(type_names))
271 *errmsg = US"unsupported DNS record type";
276 keystring = equals + 1;
277 while (isspace(*keystring)) keystring++;
280 /* Initialize the resolver in case this is the first time it has been used. */
282 dns_init(FALSE, FALSE, dnssec_mode != OK);
284 /* The remainder of the string must be a list of domains. As long as the lookup
285 for at least one of them succeeds, we return success. Failure means that none
288 The original implementation did not support a list of domains. Adding the list
289 feature is compatible, except in one case: when PTR records are being looked up
290 for a single IPv6 address. Fortunately, we can hack in a compatibility feature
291 here: If the type is PTR and no list separator is specified, and the entire
292 remaining string is valid as an IP address, set an impossible separator so that
293 it is treated as one item. */
295 if (type == T_PTR && keystring[0] != '<' &&
296 string_is_ip_address(keystring, NULL) != 0)
299 /* SPF strings should be concatenated without a separator, thus make
300 it the default if not defined (see RFC 4408 section 3.1.3).
301 Multiple SPF records are forbidden (section 3.1.2) but are currently
302 not handled specially, thus they are concatenated with \n by default.
303 MX priority and value are space-separated by default.
304 SRV and TLSA record parts are space-separated by default. */
306 if (!outsep2) switch(type)
308 case T_SPF: outsep2 = US""; break;
309 case T_SRV: case T_MX: case T_TLSA: outsep2 = US" "; break;
312 /* Now scan the list and do a lookup for each item */
314 while ((domain = string_nextinlist(&keystring, &sep, NULL, 0)))
316 int searchtype = type == T_CSA ? T_SRV : /* record type we want */
317 type == T_MXH ? T_MX :
318 type == T_ZNS ? T_NS : type;
320 /* If the type is PTR or CSA, we have to construct the relevant magic lookup
321 key if the original is an IP address (some experimental protocols are using
322 PTR records for different purposes where the key string is a host name, and
323 Exim's extended CSA can be keyed by domains or IP addresses). This code for
324 doing the reversal is now in a separate function. */
326 if ((type == T_PTR || type == T_CSA) &&
327 string_is_ip_address(domain, NULL) != 0)
328 domain = dns_build_reverse(domain);
332 DEBUG(D_lookup) debug_printf_indent("dnsdb key: %s\n", domain);
334 /* Do the lookup and sort out the result. There are four special types that
335 are handled specially: T_CSA, T_ZNS, T_ADDRESSES and T_MXH.
336 The first two are handled in a special lookup function so that the facility
337 could be used from other parts of the Exim code. T_ADDRESSES is handled by looping
338 over the types of A lookup. T_MXH affects only what happens later on in
339 this function, but for tidiness it is handled by the "special". If the
340 lookup fails, continue with the next domain. In the case of DEFER, adjust
341 the final "nothing found" result, but carry on to the next domain. */
345 if (type == T_ADDRESSES) /* NB cannot happen unless HAVE_IPV6 */
347 if (searchtype == T_ADDRESSES) searchtype = T_AAAA;
348 else if (searchtype == T_AAAA) searchtype = T_A;
349 rc = dns_special_lookup(dnsa, domain, searchtype, CUSS &found);
353 rc = dns_special_lookup(dnsa, domain, type, CUSS &found);
355 lookup_dnssec_authenticated = dnssec_mode==OK ? NULL
356 : dns_is_secure(dnsa) ? US"yes" : US"no";
358 if (rc == DNS_NOMATCH || rc == DNS_NODATA) continue;
359 if ( rc != DNS_SUCCEED
360 || (dnssec_mode == DEFER && !dns_is_secure(dnsa))
363 if (defer_mode == DEFER)
365 dns_retrans = save_retrans;
366 dns_retry = save_retry;
367 dns_init(FALSE, FALSE, FALSE); /* clr dnssec bit */
368 rc = DEFER; /* always defer */
371 if (defer_mode == PASS) failrc = DEFER; /* defer only if all do */
372 continue; /* treat defer as fail */
376 /* Search the returned records */
378 for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
379 rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)) if (rr->type == searchtype)
381 if (*do_cache > rr->ttl)
384 if (type == T_A || type == T_AAAA || type == T_ADDRESSES)
386 for (dns_address * da = dns_address_from_rr(dnsa, rr); da; da = da->next)
388 if (yield->ptr) yield = string_catn(yield, outsep, 1);
389 yield = string_cat(yield, da->address);
394 /* Other kinds of record just have one piece of data each, but there may be
395 several of them, of course. */
397 if (yield->ptr) yield = string_catn(yield, outsep, 1);
399 if (type == T_TXT || type == T_SPF)
401 if (!outsep2) /* output only the first item of data */
403 uschar n = (rr->data)[0];
404 /* size byte + data bytes must not excced the RRs length */
405 if (n + 1 <= rr->size)
406 yield = string_catn(yield, US (rr->data+1), n);
410 /* output all items */
412 while (data_offset < rr->size)
414 uschar chunk_len = (rr->data)[data_offset];
415 int remain = rr->size - data_offset;
417 /* Apparently there are resolvers that do not check RRs before passing
418 them on, and glibc fails to do so. So every application must...
419 Check for chunk len exceeding RR */
421 if (chunk_len > remain)
424 if (*outsep2 && data_offset != 0)
425 yield = string_catn(yield, outsep2, 1);
426 yield = string_catn(yield, US ((rr->data) + ++data_offset), --chunk_len);
427 data_offset += chunk_len;
431 else if (type == T_TLSA)
436 uint8_t usage, selector, matching_type;
437 uint16_t payload_length;
438 uschar s[MAX_TLSA_EXPANDED_SIZE];
440 uschar * p = US rr->data;
444 matching_type = *p++;
445 /* What's left after removing the first 3 bytes above */
446 payload_length = rr->size - 3;
447 sp += sprintf(CS s, "%d%c%d%c%d%c", usage, *outsep2,
448 selector, *outsep2, matching_type, *outsep2);
449 /* Now append the cert/identifier, one hex char at a time */
450 while (payload_length-- > 0 && sp-s < (MAX_TLSA_EXPANDED_SIZE - 4))
451 sp += sprintf(CS sp, "%02x", *p++);
453 yield = string_cat(yield, s);
455 else /* T_CNAME, T_CSA, T_MX, T_MXH, T_NS, T_PTR, T_SOA, T_SRV */
457 int priority, weight, port;
459 uschar * p = US rr->data;
464 if (rr->size < sizeof(u_int16_t)) continue;
465 /* mxh ignores the priority number and includes only the hostnames */
466 GETSHORT(priority, p);
470 if (rr->size < sizeof(u_int16_t)) continue;
471 GETSHORT(priority, p);
472 sprintf(CS s, "%d%c", priority, *outsep2);
473 yield = string_cat(yield, s);
477 if (rr->size < 3*sizeof(u_int16_t)) continue;
478 GETSHORT(priority, p);
481 sprintf(CS s, "%d%c%d%c%d%c", priority, *outsep2,
482 weight, *outsep2, port, *outsep2);
483 yield = string_cat(yield, s);
487 if (rr->size < 3*sizeof(u_int16_t)) continue;
488 /* See acl_verify_csa() for more comments about CSA. */
489 GETSHORT(priority, p);
493 if (priority != 1) continue; /* CSA version must be 1 */
495 /* If the CSA record we found is not the one we asked for, analyse
496 the subdomain assertions in the port field, else analyse the direct
497 authorization status in the weight field. */
499 if (Ustrcmp(found, domain) != 0)
501 if (port & 1) *s = 'X'; /* explicit authorization required */
502 else *s = '?'; /* no subdomain assertions here */
506 if (weight < 2) *s = 'N'; /* not authorized */
507 else if (weight == 2) *s = 'Y'; /* authorized */
508 else if (weight == 3) *s = '?'; /* unauthorizable */
509 else continue; /* invalid */
513 yield = string_catn(yield, s, 2);
520 /* GETSHORT() has advanced the pointer to the target domain. */
522 rc = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, p,
523 (DN_EXPAND_ARG4_TYPE)s, sizeof(s));
525 /* If an overlong response was received, the data will have been
526 truncated and dn_expand may fail. */
530 log_write(0, LOG_MAIN, "host name alias list truncated: type=%s "
531 "domain=%s", dns_text_type(type), domain);
534 else yield = string_cat(yield, s);
536 if (type == T_SOA && outsep2 != NULL)
538 unsigned long serial = 0, refresh = 0, retry = 0, expire = 0, minimum = 0;
541 yield = string_catn(yield, outsep2, 1);
543 rc = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, p,
544 (DN_EXPAND_ARG4_TYPE)s, sizeof(s));
547 log_write(0, LOG_MAIN, "responsible-mailbox truncated: type=%s "
548 "domain=%s", dns_text_type(type), domain);
551 else yield = string_cat(yield, s);
554 if (rr->size >= p - rr->data - 5*sizeof(u_int32_t))
556 GETLONG(serial, p); GETLONG(refresh, p);
557 GETLONG(retry, p); GETLONG(expire, p); GETLONG(minimum, p);
559 sprintf(CS s, "%c%lu%c%lu%c%lu%c%lu%c%lu",
560 *outsep2, serial, *outsep2, refresh,
561 *outsep2, retry, *outsep2, expire, *outsep2, minimum);
562 yield = string_cat(yield, s);
565 } /* Loop for list of returned records */
567 /* Loop for set of A-lookup types */
568 } while (type == T_ADDRESSES && searchtype != T_A);
570 } /* Loop for list of domains */
572 /* Reclaim unused memory */
574 gstring_release_unused(yield);
576 /* If yield NULL we have not found anything. Otherwise, insert the terminating
577 zero and return the result. */
579 dns_retrans = save_retrans;
580 dns_retry = save_retry;
581 dns_init(FALSE, FALSE, FALSE); /* clear the dnssec bit for getaddrbyname */
583 if (!yield || !yield->ptr)
587 *result = string_from_gstring(yield);
593 store_free_dns_answer(dnsa);
599 /*************************************************
600 * Version reporting entry point *
601 *************************************************/
603 /* See local README for interface description. */
605 #include "../version.h"
608 dnsdb_version_report(gstring * g)
611 g = string_fmt_append(g, "Library version: DNSDB: Exim version %s\n", EXIM_VERSION_STR);
617 static lookup_info _lookup_info = {
618 .name = US"dnsdb", /* lookup name */
619 .type = lookup_querystyle, /* query style */
620 .open = dnsdb_open, /* open function */
621 .check = NULL, /* check function */
622 .find = dnsdb_find, /* find function */
623 .close = NULL, /* no close function */
624 .tidy = NULL, /* no tidy function */
625 .quote = NULL, /* no quoting function */
626 .version_report = dnsdb_version_report /* version reporting */
630 #define dnsdb_lookup_module_info _lookup_module_info
633 static lookup_info *_lookup_list[] = { &_lookup_info };
634 lookup_module_info dnsdb_lookup_module_info = { LOOKUP_MODULE_INFO_MAGIC, _lookup_list, 1 };
638 /* End of lookups/dnsdb.c */