Events: dns:fail Bug 3011
[exim.git] / src / src / lookups / dnsdb.c
1 /*************************************************
2 *     Exim - an Internet mail transport agent    *
3 *************************************************/
4
5 /* Copyright (c) The Exim Maintainers 2020 - 2023 */
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 */
9
10 #include "../exim.h"
11 #include "lf_functions.h"
12
13
14
15 /* Ancient systems (e.g. SunOS4) don't appear to have T_TXT defined in their
16 header files. */
17
18 #ifndef T_TXT
19 # define T_TXT 16
20 #endif
21
22 /* Many systems do not have T_SPF. */
23 #ifndef T_SPF
24 # define T_SPF 99
25 #endif
26
27 /* New TLSA record for DANE */
28 #ifndef T_TLSA
29 # define T_TLSA 52
30 #endif
31
32 /* Table of recognized DNS record types and their integer values. */
33
34 static const char *type_names[] = {
35   "a",
36 #if HAVE_IPV6
37   "a+",
38   "aaaa",
39 #endif
40   "cname",
41   "csa",
42   "mx",
43   "mxh",
44   "ns",
45   "ptr",
46   "soa",
47   "spf",
48   "srv",
49   "tlsa",
50   "txt",
51   "zns"
52 };
53
54 static int type_values[] = {
55   T_A,
56 #if HAVE_IPV6
57   T_ADDRESSES,     /* Private type for AAAA + A */
58   T_AAAA,
59 #endif
60   T_CNAME,
61   T_CSA,     /* Private type for "Client SMTP Authorization". */
62   T_MX,
63   T_MXH,     /* Private type for "MX hostnames" */
64   T_NS,
65   T_PTR,
66   T_SOA,
67   T_SPF,
68   T_SRV,
69   T_TLSA,
70   T_TXT,
71   T_ZNS      /* Private type for "zone nameservers" */
72 };
73
74
75 /*************************************************
76 *              Open entry point                  *
77 *************************************************/
78
79 /* See local README for interface description. */
80
81 static void *
82 dnsdb_open(const uschar * filename, uschar **errmsg)
83 {
84 return (void *)(-1);   /* Any non-0 value */
85 }
86
87
88
89 /*************************************************
90 *           Find entry point for dnsdb           *
91 *************************************************/
92
93 /* See local README for interface description. The query in the "keystring" may
94 consist of a number of parts.
95
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
98 separator is newline.
99
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.
106
107 (c) Options, all comma-terminated, in any order.  Any unrecognised option
108 terminates option processing.  Recognised options are:
109
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'.
114
115 - 'dnssec_FOO', with 'strict', 'lax' (default), and 'never'.  The meanings are
116 require, try and don't-try dnssec respectively.
117
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'.
120
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".
123
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
126 default is "TXT".
127
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. */
131
132 static int
133 dnsdb_find(void * handle, const uschar * filename, const uschar * keystring,
134  int length, uschar ** result, uschar ** errmsg, uint * do_cache,
135  const uschar * opts)
136 {
137 int rc;
138 int sep = 0;
139 int defer_mode = PASS, dnssec_mode = PASS;
140 int save_retrans = dns_retrans, save_retry =   dns_retry;
141 int type;
142 int failrc = FAIL;
143 const uschar * outsep = CUS"\n", * outsep2 = NULL;
144 uschar * equals, * domain, * found;
145
146 dns_answer * dnsa = store_get_dns_answer();
147 dns_scan dnss;
148
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 */
151
152 gstring * yield = string_get(256);
153
154 /* If the string starts with '>' we change the output separator.
155 If it's followed by ';' or ',' we set the TXT output separator. */
156
157 if (Uskip_whitespace(&keystring) == '>')
158   {
159   outsep = keystring + 1;
160   keystring += 2;
161   if (*keystring == ',')
162     {
163     outsep2 = keystring + 1;
164     keystring += 2;
165     }
166   else if (*keystring == ';')
167     {
168     outsep2 = US"";
169     keystring++;
170     }
171   Uskip_whitespace(&keystring);
172   }
173
174 /* Check for a modifier keyword. */
175
176 for (;;)
177   {
178   if (strncmpic(keystring, US"defer_", 6) == 0)
179     {
180     keystring += 6;
181     if (strncmpic(keystring, US"strict", 6) == 0)
182       { defer_mode = DEFER; keystring += 6; }
183     else if (strncmpic(keystring, US"lax", 3) == 0)
184       { defer_mode = PASS; keystring += 3; }
185     else if (strncmpic(keystring, US"never", 5) == 0)
186       { defer_mode = OK; keystring += 5; }
187     else
188       {
189       *errmsg = US"unsupported dnsdb defer behaviour";
190       rc = DEFER;
191       goto out;
192       }
193     }
194   else if (strncmpic(keystring, US"dnssec_", 7) == 0)
195     {
196     keystring += 7;
197     if (strncmpic(keystring, US"strict", 6) == 0)
198       { dnssec_mode = DEFER; keystring += 6; }
199     else if (strncmpic(keystring, US"lax", 3) == 0)
200       { dnssec_mode = PASS; keystring += 3; }
201     else if (strncmpic(keystring, US"never", 5) == 0)
202       { dnssec_mode = OK; keystring += 5; }
203     else
204       {
205       *errmsg = US"unsupported dnsdb dnssec behaviour";
206       rc = DEFER;
207       goto out;
208       }
209     }
210   else if (strncmpic(keystring, US"retrans_", 8) == 0)
211     {
212     int timeout_sec;
213     if ((timeout_sec = readconf_readtime(keystring += 8, ',', FALSE)) <= 0)
214       {
215       *errmsg = US"unsupported dnsdb timeout value";
216       rc = DEFER;
217       goto out;
218       }
219     dns_retrans = timeout_sec;
220     while (*keystring != ',') keystring++;
221     }
222   else if (strncmpic(keystring, US"retry_", 6) == 0)
223     {
224     int retries;
225     if ((retries = (int)strtol(CCS keystring + 6, CSS &keystring, 0)) < 0)
226       {
227       *errmsg = US"unsupported dnsdb retry count";
228       rc = DEFER;
229       goto out;
230       }
231     dns_retry = retries;
232     }
233   else
234     break;
235
236   Uskip_whitespace(&keystring);
237   if (*keystring++ != ',')
238     {
239     *errmsg = US"dnsdb modifier syntax error";
240     rc = DEFER;
241     goto out;
242     }
243   Uskip_whitespace(&keystring);
244   }
245
246 /* Figure out the "type" value if it is not T_TXT.
247 If the keystring contains an = this must be preceded by a valid type name. */
248
249 type = T_TXT;
250 if ((equals = Ustrchr(keystring, '=')) != NULL)
251   {
252   int i, len;
253   uschar *tend = equals;
254
255   while (tend > keystring && isspace(tend[-1])) tend--;
256   len = tend - keystring;
257
258   for (i = 0; i < nelem(type_names); i++)
259     if (len == Ustrlen(type_names[i]) &&
260         strncmpic(keystring, US type_names[i], len) == 0)
261       {
262       type = type_values[i];
263       break;
264       }
265
266   if (i >= nelem(type_names))
267     {
268     *errmsg = US"unsupported DNS record type";
269     rc = DEFER;
270     goto out;
271     }
272
273   keystring = equals + 1;
274   Uskip_whitespace(&keystring);
275   }
276
277 /* Initialize the resolver in case this is the first time it has been used. */
278
279 dns_init(FALSE, FALSE, dnssec_mode != OK);
280
281 /* The remainder of the string must be a list of domains. As long as the lookup
282 for at least one of them succeeds, we return success. Failure means that none
283 of them were found.
284
285 The original implementation did not support a list of domains. Adding the list
286 feature is compatible, except in one case: when PTR records are being looked up
287 for a single IPv6 address. Fortunately, we can hack in a compatibility feature
288 here: If the type is PTR and no list separator is specified, and the entire
289 remaining string is valid as an IP address, set an impossible separator so that
290 it is treated as one item. */
291
292 if (type == T_PTR && keystring[0] != '<' &&
293     string_is_ip_address(keystring, NULL) != 0)
294   sep = -1;
295
296 /* SPF strings should be concatenated without a separator, thus make
297 it the default if not defined (see RFC 4408 section 3.1.3).
298 Multiple SPF records are forbidden (section 3.1.2) but are currently
299 not handled specially, thus they are concatenated with \n by default.
300 MX priority and value are space-separated by default.
301 SRV and TLSA record parts are space-separated by default. */
302
303 if (!outsep2) switch(type)
304   {
305   case T_SPF:                         outsep2 = US"";  break;
306   case T_SRV: case T_MX: case T_TLSA: outsep2 = US" "; break;
307   }
308
309 /* Now scan the list and do a lookup for each item */
310
311 while ((domain = string_nextinlist(&keystring, &sep, NULL, 0)))
312   {
313   int searchtype = type == T_CSA ? T_SRV :         /* record type we want */
314                    type == T_MXH ? T_MX :
315                    type == T_ZNS ? T_NS : type;
316
317   /* If the type is PTR or CSA, we have to construct the relevant magic lookup
318   key if the original is an IP address (some experimental protocols are using
319   PTR records for different purposes where the key string is a host name, and
320   Exim's extended CSA can be keyed by domains or IP addresses). This code for
321   doing the reversal is now in a separate function. */
322
323   if ((type == T_PTR || type == T_CSA) &&
324       string_is_ip_address(domain, NULL) != 0)
325     domain = dns_build_reverse(domain);
326
327   do
328     {
329     DEBUG(D_lookup) debug_printf_indent("dnsdb key: %s\n", domain);
330
331     /* Do the lookup and sort out the result. There are four special types that
332     are handled specially: T_CSA, T_ZNS, T_ADDRESSES and T_MXH.
333     The first two are handled in a special lookup function so that the facility
334     could be used from other parts of the Exim code. T_ADDRESSES is handled by looping
335     over the types of A lookup.  T_MXH affects only what happens later on in
336     this function, but for tidiness it is handled by the "special". If the
337     lookup fails, continue with the next domain. In the case of DEFER, adjust
338     the final "nothing found" result, but carry on to the next domain. */
339
340     found = domain;
341 #if HAVE_IPV6
342     if (type == T_ADDRESSES)            /* NB cannot happen unless HAVE_IPV6 */
343       {
344       if (searchtype == T_ADDRESSES) searchtype = T_AAAA;
345       else if (searchtype == T_AAAA) searchtype = T_A;
346       rc = dns_special_lookup(dnsa, domain, searchtype, CUSS &found);
347       }
348     else
349 #endif
350       rc = dns_special_lookup(dnsa, domain, type, CUSS &found);
351
352     lookup_dnssec_authenticated = dnssec_mode==OK ? NULL
353       : dns_is_secure(dnsa) ? US"yes" : US"no";
354
355     if (rc == DNS_NOMATCH || rc == DNS_NODATA) continue;
356     if (  rc != DNS_SUCCEED
357        || (dnssec_mode == DEFER && !dns_is_secure(dnsa))
358        )
359       {
360       if (defer_mode == DEFER)
361         {
362         dns_retrans = save_retrans;
363         dns_retry = save_retry;
364         dns_init(FALSE, FALSE, FALSE);                  /* clr dnssec bit */
365         rc = DEFER;                                     /* always defer */
366         goto out;
367         }
368       if (defer_mode == PASS) failrc = DEFER;         /* defer only if all do */
369       continue;                                       /* treat defer as fail */
370       }
371
372
373     /* Search the returned records */
374
375     for (dns_record * rr = dns_next_rr(dnsa, &dnss, RESET_ANSWERS); rr;
376          rr = dns_next_rr(dnsa, &dnss, RESET_NEXT)) if (rr->type == searchtype)
377       {
378       if (*do_cache > rr->ttl)
379         *do_cache = rr->ttl;
380
381       if (type == T_A || type == T_AAAA || type == T_ADDRESSES)
382         {
383         for (dns_address * da = dns_address_from_rr(dnsa, rr); da; da = da->next)
384           yield = string_append_listele(yield, *outsep, da->address);
385         continue;
386         }
387
388       /* Other kinds of record just have one piece of data each, but there may be
389       several of them, of course.  TXT & SPF can have data in multiple chunks. */
390
391       if (yield->ptr) yield = string_catn(yield, outsep, 1);
392
393       if (type == T_TXT || type == T_SPF)
394         for (unsigned data_offset = 0; data_offset + 1 < rr->size; )
395           {
396           uschar chunk_len = (rr->data)[data_offset];
397           int remain;
398
399           if (outsep2 && *outsep2 && data_offset != 0)
400             yield = string_catn(yield, outsep2, 1);
401
402           /* Apparently there are resolvers that do not check RRs before passing
403           them on, and glibc fails to do so.  So every application must...
404           Check for chunk len exceeding RR */
405
406           remain = rr->size - ++data_offset;
407           if (chunk_len > remain)
408             chunk_len = remain;
409           yield = string_catn(yield, US ((rr->data) + data_offset), chunk_len);
410           data_offset += chunk_len;
411
412           if (!outsep2) break;          /* output only the first chunk of the RR */
413           }
414       else if (type == T_TLSA)
415         if (rr->size < 3)
416           continue;
417         else
418           {
419           uint8_t usage, selector, matching_type;
420           uint16_t payload_length;
421           uschar s[MAX_TLSA_EXPANDED_SIZE];
422           uschar * sp = s;
423           uschar * p = US rr->data;
424
425           usage = *p++;
426           selector = *p++;
427           matching_type = *p++;
428           /* What's left after removing the first 3 bytes above */
429           payload_length = rr->size - 3;
430           sp += sprintf(CS s, "%d%c%d%c%d%c", usage, *outsep2,
431                   selector, *outsep2, matching_type, *outsep2);
432           /* Now append the cert/identifier, one hex char at a time */
433           while (payload_length-- > 0 && sp-s < (MAX_TLSA_EXPANDED_SIZE - 4))
434             sp += sprintf(CS sp, "%02x", *p++);
435
436           yield = string_cat(yield, s);
437           }
438       else   /* T_CNAME, T_CSA, T_MX, T_MXH, T_NS, T_PTR, T_SOA, T_SRV */
439         {
440         int priority, weight, port;
441         uschar s[264];
442         uschar * p = US rr->data;
443
444         switch (type)
445           {
446           case T_MXH:
447             if (rr_bad_size(rr, sizeof(uint16_t))) continue;
448             /* mxh ignores the priority number and includes only the hostnames */
449             GETSHORT(priority, p);
450             break;
451
452           case T_MX:
453             if (rr_bad_size(rr, sizeof(uint16_t))) continue;
454             GETSHORT(priority, p);
455             sprintf(CS s, "%d%c", priority, *outsep2);
456             yield = string_cat(yield, s);
457             break;
458
459           case T_SRV:
460             if (rr_bad_size(rr, 3*sizeof(uint16_t))) continue;
461             GETSHORT(priority, p);
462             GETSHORT(weight, p);
463             GETSHORT(port, p);
464             sprintf(CS s, "%d%c%d%c%d%c", priority, *outsep2,
465                               weight, *outsep2, port, *outsep2);
466             yield = string_cat(yield, s);
467             break;
468
469           case T_CSA:
470             if (rr_bad_size(rr, 3*sizeof(uint16_t))) continue;
471             /* See acl_verify_csa() for more comments about CSA. */
472             GETSHORT(priority, p);
473             GETSHORT(weight, p);
474             GETSHORT(port, p);
475
476             if (priority != 1) continue;      /* CSA version must be 1 */
477
478             /* If the CSA record we found is not the one we asked for, analyse
479             the subdomain assertions in the port field, else analyse the direct
480             authorization status in the weight field. */
481
482             if (Ustrcmp(found, domain) != 0)
483               {
484               if (port & 1) *s = 'X';         /* explicit authorization required */
485               else *s = '?';                  /* no subdomain assertions here */
486               }
487             else
488               {
489               if (weight < 2) *s = 'N';       /* not authorized */
490               else if (weight == 2) *s = 'Y'; /* authorized */
491               else if (weight == 3) *s = '?'; /* unauthorizable */
492               else continue;                  /* invalid */
493               }
494
495             s[1] = ' ';
496             yield = string_catn(yield, s, 2);
497             break;
498
499           default:
500             break;
501           }
502
503         /* GETSHORT() has advanced the pointer to the target domain. */
504
505         rc = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, p,
506           (DN_EXPAND_ARG4_TYPE)s, sizeof(s));
507
508         /* If an overlong response was received, the data will have been
509         truncated and dn_expand may fail. */
510
511         if (rc < 0)
512           {
513           log_write(0, LOG_MAIN, "host name alias list truncated: type=%s "
514             "domain=%s", dns_text_type(type), domain);
515           break;
516           }
517         else yield = string_cat(yield, s);
518
519         if (type == T_SOA && outsep2 != NULL)
520           {
521           unsigned long serial = 0, refresh = 0, retry = 0, expire = 0, minimum = 0;
522
523           p += rc;
524           yield = string_catn(yield, outsep2, 1);
525
526           rc = dn_expand(dnsa->answer, dnsa->answer + dnsa->answerlen, p,
527             (DN_EXPAND_ARG4_TYPE)s, sizeof(s));
528           if (rc < 0)
529             {
530             log_write(0, LOG_MAIN, "responsible-mailbox truncated: type=%s "
531               "domain=%s", dns_text_type(type), domain);
532             break;
533             }
534           else yield = string_cat(yield, s);
535
536           p += rc;
537           if (!rr_bad_increment(rr, p, 5 * sizeof(u_int32_t)))
538             {
539             GETLONG(serial, p); GETLONG(refresh, p);
540             GETLONG(retry,  p); GETLONG(expire,  p); GETLONG(minimum, p);
541             }
542           sprintf(CS s, "%c%lu%c%lu%c%lu%c%lu%c%lu",
543             *outsep2, serial, *outsep2, refresh,
544             *outsep2, retry,  *outsep2, expire,  *outsep2, minimum);
545           yield = string_cat(yield, s);
546           }
547         }
548       }    /* Loop for list of returned records */
549
550            /* Loop for set of A-lookup types */
551     } while (type == T_ADDRESSES && searchtype != T_A);
552
553   }        /* Loop for list of domains */
554
555 /* Reclaim unused memory */
556
557 gstring_release_unused(yield);
558
559 /* If yield NULL we have not found anything. Otherwise, insert the terminating
560 zero and return the result. */
561
562 dns_retrans = save_retrans;
563 dns_retry = save_retry;
564 dns_init(FALSE, FALSE, FALSE);  /* clear the dnssec bit for getaddrbyname */
565
566 if (!yield || !yield->ptr)
567   rc = failrc;
568 else
569   {
570   *result = string_from_gstring(yield);
571   rc = OK;
572   }
573
574 out:
575
576 store_free_dns_answer(dnsa);
577 return rc;
578 }
579
580
581
582 /*************************************************
583 *         Version reporting entry point          *
584 *************************************************/
585
586 /* See local README for interface description. */
587
588 #include "../version.h"
589
590 gstring *
591 dnsdb_version_report(gstring * g)
592 {
593 #ifdef DYNLOOKUP
594 g = string_fmt_append(g, "Library version: DNSDB: Exim version %s\n", EXIM_VERSION_STR);
595 #endif
596 return g;
597 }
598
599
600 static lookup_info _lookup_info = {
601   .name = US"dnsdb",                    /* lookup name */
602   .type = lookup_querystyle,            /* query style */
603   .open = dnsdb_open,                   /* open function */
604   .check = NULL,                        /* check function */
605   .find = dnsdb_find,                   /* find function */
606   .close = NULL,                        /* no close function */
607   .tidy = NULL,                         /* no tidy function */
608   .quote = NULL,                        /* no quoting function */
609   .version_report = dnsdb_version_report           /* version reporting */
610 };
611
612 #ifdef DYNLOOKUP
613 #define dnsdb_lookup_module_info _lookup_module_info
614 #endif
615
616 static lookup_info *_lookup_list[] = { &_lookup_info };
617 lookup_module_info dnsdb_lookup_module_info = { LOOKUP_MODULE_INFO_MAGIC, _lookup_list, 1 };
618
619 /* vi: aw ai sw=2
620 */
621 /* End of lookups/dnsdb.c */