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