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