Fix fakens TLSA generation and DANE TLSA lookup
[exim.git] / test / src / fakens.c
1 /*************************************************
2 *       fakens - A Fake Nameserver Program       *
3 *************************************************/
4
5 /* This program exists to support the testing of DNS handling code in Exim. It
6 avoids the need to install special zones in a real nameserver. When Exim is
7 running in its (new) test harness, DNS lookups are first passed to this program
8 instead of to the real resolver. (With a few exceptions - see the discussion in
9 the test suite's README file.) The program is also passed the name of the Exim
10 spool directory; it expects to find its "zone files" in ../dnszones relative to
11 that directory. Note that there is little checking in this program. The fake
12 zone files are assumed to be syntactically valid.
13
14 The zones that are handled are found by scanning the dnszones directory. A file
15 whose name is of the form db.ip4.x is a zone file for .x.in-addr.arpa; a file
16 whose name is of the form db.ip6.x is a zone file for .x.ip6.arpa; a file of
17 the form db.anything.else is a zone file for .anything.else. A file of the form
18 qualify.x.y specifies the domain that is used to qualify single-component
19 names, except for the name "dontqualify".
20
21 The arguments to the program are:
22
23   the name of the Exim spool directory
24   the domain name that is being sought
25   the DNS record type that is being sought
26
27 The output from the program is written to stdout. It is supposed to be in
28 exactly the same format as a traditional namserver response (see RFC 1035) so
29 that Exim can process it as normal. At present, no compression is used.
30 Error messages are written to stderr.
31
32 The return codes from the program are zero for success, and otherwise the
33 values that are set in h_errno after a failing call to the normal resolver:
34
35   1 HOST_NOT_FOUND     host not found (authoritative)
36   2 TRY_AGAIN          server failure
37   3 NO_RECOVERY        non-recoverable error
38   4 NO_DATA            valid name, no data of requested type
39
40 In a real nameserver, TRY_AGAIN is also used for a non-authoritative not found,
41 but it is not used for that here. There is also one extra return code:
42
43   5 PASS_ON            requests Exim to call res_search()
44
45 This is used for zones that fakens does not recognize. It is also used if a
46 line in the zone file contains exactly this:
47
48   PASS ON NOT FOUND
49
50 and the domain is not found. It converts the the result to PASS_ON instead of
51 HOST_NOT_FOUND.
52
53 Any DNS record line in a zone file can be prefixed with "DNSSEC" and
54 at least one space; if all the records found by a lookup are marked
55 as such then the response will have the "AD" bit set. */
56
57 #include <ctype.h>
58 #include <stdarg.h>
59 #include <stdio.h>
60 #include <string.h>
61 #include <netdb.h>
62 #include <errno.h>
63 #include <arpa/nameser.h>
64 #include <sys/types.h>
65 #include <dirent.h>
66
67 #define FALSE         0
68 #define TRUE          1
69 #define PASS_ON       5
70
71 typedef int BOOL;
72 typedef unsigned char uschar;
73
74 #define CS   (char *)
75 #define CCS  (const char *)
76 #define US   (unsigned char *)
77
78 #define Ustrcat(s,t)       strcat(CS(s),CCS(t))
79 #define Ustrchr(s,n)       US strchr(CCS(s),n)
80 #define Ustrcmp(s,t)       strcmp(CCS(s),CCS(t))
81 #define Ustrcpy(s,t)       strcpy(CS(s),CCS(t))
82 #define Ustrlen(s)         (int)strlen(CCS(s))
83 #define Ustrncmp(s,t,n)    strncmp(CCS(s),CCS(t),n)
84 #define Ustrncpy(s,t,n)    strncpy(CS(s),CCS(t),n)
85
86 typedef struct zoneitem {
87   uschar *zone;
88   uschar *zonefile;
89 } zoneitem;
90
91 typedef struct tlist {
92   uschar *name;
93   int value;
94 } tlist;
95
96 /* On some (older?) operating systems, the standard ns_t_xxx definitions are
97 not available, and only the older T_xxx ones exist in nameser.h. If ns_t_a is
98 not defined, assume we are in this state. A really old system might not even
99 know about AAAA and SRV at all. */
100
101 #ifndef ns_t_a
102 # define ns_t_a      T_A
103 # define ns_t_ns     T_NS
104 # define ns_t_cname  T_CNAME
105 # define ns_t_soa    T_SOA
106 # define ns_t_ptr    T_PTR
107 # define ns_t_mx     T_MX
108 # define ns_t_txt    T_TXT
109 # define ns_t_aaaa   T_AAAA
110 # define ns_t_srv    T_SRV
111 # define ns_t_tlsa   T_TLSA
112 # ifndef T_AAAA
113 #  define T_AAAA      28
114 # endif
115 # ifndef T_SRV
116 #  define T_SRV       33
117 # endif
118 # ifndef T_TLSA
119 #  define T_TLSA      52
120 # endif
121 #endif
122
123 static tlist type_list[] = {
124   { US"A",       ns_t_a },
125   { US"NS",      ns_t_ns },
126   { US"CNAME",   ns_t_cname },
127 /*  { US"SOA",     ns_t_soa },  Not currently in use */
128   { US"PTR",     ns_t_ptr },
129   { US"MX",      ns_t_mx },
130   { US"TXT",     ns_t_txt },
131   { US"AAAA",    ns_t_aaaa },
132   { US"SRV",     ns_t_srv },
133   { US"TLSA",    ns_t_tlsa },
134   { NULL,        0 }
135 };
136
137
138
139 /*************************************************
140 *           Get memory and sprintf into it       *
141 *************************************************/
142
143 /* This is used when building a table of zones and their files.
144
145 Arguments:
146   format       a format string
147   ...          arguments
148
149 Returns:       pointer to formatted string
150 */
151
152 static uschar *
153 fcopystring(uschar *format, ...)
154 {
155 uschar *yield;
156 char buffer[256];
157 va_list ap;
158 va_start(ap, format);
159 vsprintf(buffer, format, ap);
160 va_end(ap);
161 yield = (uschar *)malloc(Ustrlen(buffer) + 1);
162 Ustrcpy(yield, buffer);
163 return yield;
164 }
165
166
167 /*************************************************
168 *             Pack name into memory              *
169 *************************************************/
170
171 /* This function packs a domain name into memory according to DNS rules. At
172 present, it doesn't do any compression.
173
174 Arguments:
175   name         the name
176   pk           where to put it
177
178 Returns:       the updated value of pk
179 */
180
181 static uschar *
182 packname(uschar *name, uschar *pk)
183 {
184 while (*name != 0)
185   {
186   uschar *p = name;
187   while (*p != 0 && *p != '.') p++;
188   *pk++ = (p - name);
189   memmove(pk, name, p - name);
190   pk += p - name;
191   name = (*p == 0)? p : p + 1;
192   }
193 *pk++ = 0;
194 return pk;
195 }
196
197 uschar *
198 bytefield(uschar ** pp, uschar * pk)
199 {
200 unsigned value = 0;
201 uschar * p = *pp;
202
203 while (isdigit(*p)) value = value*10 + *p++ - '0';
204 while (isspace(*p)) p++;
205 *pp = p;
206 *pk++ = value & 255;
207 return pk;
208 }
209
210 uschar *
211 shortfield(uschar ** pp, uschar * pk)
212 {
213 unsigned value = 0;
214 uschar * p = *pp;
215
216 while (isdigit(*p)) value = value*10 + *p++ - '0';
217 while (isspace(*p)) p++;
218 *pp = p;
219 *pk++ = (value >> 8) & 255;
220 *pk++ = value & 255;
221 return pk;
222 }
223
224
225
226 /*************************************************
227 *              Scan file for RRs                 *
228 *************************************************/
229
230 /* This function scans an open "zone file" for appropriate records, and adds
231 any that are found to the output buffer.
232
233 Arguments:
234   f           the input FILE
235   zone        the current zone name
236   domain      the domain we are looking for
237   qtype       the type of RR we want
238   qtypelen    the length of qtype
239   pkptr       points to the output buffer pointer; this is updated
240   countptr    points to the record count; this is updated
241
242 Returns:      0 on success, else HOST_NOT_FOUND or NO_DATA or NO_RECOVERY or
243               PASS_ON - the latter if a "PASS ON NOT FOUND" line is seen
244 */
245
246 static int
247 find_records(FILE *f, uschar *zone, uschar *domain, uschar *qtype,
248   int qtypelen, uschar **pkptr, int *countptr, BOOL * dnssec)
249 {
250 int yield = HOST_NOT_FOUND;
251 int domainlen = Ustrlen(domain);
252 BOOL pass_on_not_found = FALSE;
253 tlist *typeptr;
254 uschar *pk = *pkptr;
255 uschar buffer[256];
256 uschar rrdomain[256];
257 uschar RRdomain[256];
258
259 /* Decode the required type */
260
261 for (typeptr = type_list; typeptr->name != NULL; typeptr++)
262   { if (Ustrcmp(typeptr->name, qtype) == 0) break; }
263 if (typeptr->name == NULL)
264   {
265   fprintf(stderr, "fakens: unknown record type %s\n", qtype);
266   return NO_RECOVERY;
267   }
268
269 rrdomain[0] = 0;                 /* No previous domain */
270 (void)fseek(f, 0, SEEK_SET);     /* Start again at the beginning */
271
272 *dnssec = TRUE;                 /* cancelled by first nonsecure rec found */ 
273
274 /* Scan for RRs */
275
276 while (fgets(CS buffer, sizeof(buffer), f) != NULL)
277   {
278   uschar *rdlptr;
279   uschar *p, *ep, *pp;
280   BOOL found_cname = FALSE;
281   int i, plen, value;
282   int tvalue = typeptr->value;
283   int qtlen = qtypelen;
284   BOOL rr_sec = FALSE;
285
286   p = buffer;
287   while (isspace(*p)) p++;
288   if (*p == 0 || *p == ';') continue;
289
290   if (Ustrncmp(p, US"PASS ON NOT FOUND", 17) == 0)
291     {
292     pass_on_not_found = TRUE;
293     continue;
294     }
295
296   ep = buffer + Ustrlen(buffer);
297   while (isspace(ep[-1])) ep--;
298   *ep = 0;
299
300   p = buffer;
301   if (Ustrncmp(p, US"DNSSEC ", 7) == 0) /* tagged as secure */
302     {
303     rr_sec = TRUE;
304     p += 7;
305     }
306
307   if (!isspace(*p))
308     {
309     uschar *pp = rrdomain;
310     uschar *PP = RRdomain;
311     while (!isspace(*p))
312       {
313       *pp++ = tolower(*p);
314       *PP++ = *p++;
315       }
316     if (pp[-1] != '.')
317       {
318       Ustrcpy(pp, zone);
319       Ustrcpy(PP, zone);
320       }
321     else
322       {
323       pp[-1] = 0;
324       PP[-1] = 0;
325       }
326     }
327
328   /* Compare domain names; first check for a wildcard */
329
330   if (rrdomain[0] == '*')
331     {
332     int restlen = Ustrlen(rrdomain) - 1;
333     if (domainlen > restlen &&
334         Ustrcmp(domain + domainlen - restlen, rrdomain + 1) != 0) continue;
335     }
336
337   /* Not a wildcard RR */
338
339   else if (Ustrcmp(domain, rrdomain) != 0) continue;
340
341   /* The domain matches */
342
343   if (yield == HOST_NOT_FOUND) yield = NO_DATA;
344
345   /* Compare RR types; a CNAME record is always returned */
346
347   while (isspace(*p)) p++;
348
349   if (Ustrncmp(p, "CNAME", 5) == 0)
350     {
351     tvalue = ns_t_cname;
352     qtlen = 5;
353     found_cname = TRUE;
354     }
355   else if (Ustrncmp(p, qtype, qtypelen) != 0 || !isspace(p[qtypelen])) continue;
356
357   /* Found a relevant record */
358
359   if (!rr_sec)
360     *dnssec = FALSE;                    /* cancel AD return */
361
362   yield = 0;
363   *countptr = *countptr + 1;
364
365   p += qtlen;
366   while (isspace(*p)) p++;
367
368   /* For a wildcard record, use the search name; otherwise use the record's
369   name in its original case because it might contain upper case letters. */
370
371   pk = packname((rrdomain[0] == '*')? domain : RRdomain, pk);
372   *pk++ = (tvalue >> 8) & 255;
373   *pk++ = (tvalue) & 255;
374   *pk++ = 0;
375   *pk++ = 1;     /* class = IN */
376
377   pk += 4;       /* TTL field; don't care */
378
379   rdlptr = pk;   /* remember rdlength field */
380   pk += 2;
381
382   /* The rest of the data depends on the type */
383
384   switch (tvalue)
385     {
386     case ns_t_soa:  /* Not currently used */
387     break;
388
389     case ns_t_a:
390     for (i = 0; i < 4; i++)
391       {
392       value = 0;
393       while (isdigit(*p)) value = value*10 + *p++ - '0';
394       *pk++ = value;
395       p++;
396       }
397     break;
398
399     /* The only occurrence of a double colon is for ::1 */
400     case ns_t_aaaa:
401     if (Ustrcmp(p, "::1") == 0)
402       {
403       memset(pk, 0, 15);
404       pk += 15;
405       *pk++ = 1;
406       }
407     else for (i = 0; i < 8; i++)
408       {
409       value = 0;
410       while (isxdigit(*p))
411         {
412         value = value * 16 + toupper(*p) - (isdigit(*p)? '0' : '7');
413         p++;
414         }
415       *pk++ = (value >> 8) & 255;
416       *pk++ = value & 255;
417       p++;
418       }
419     break;
420
421     case ns_t_mx:
422     pk = shortfield(&p, pk);
423     if (ep[-1] != '.') sprintf(ep, "%s.", zone);
424     pk = packname(p, pk);
425     plen = Ustrlen(p);
426     break;
427
428     case ns_t_txt:
429     pp = pk++;
430     if (*p == '"') p++;   /* Should always be the case */
431     while (*p != 0 && *p != '"') *pk++ = *p++;
432     *pp = pk - pp - 1;
433     break;
434
435     case ns_t_tlsa:
436     pk = bytefield(&p, pk);     /* usage */
437     pk = bytefield(&p, pk);     /* selector */
438     pk = bytefield(&p, pk);     /* match type */
439     while (isxdigit(*p))
440       {
441       value = toupper(*p) - (isdigit(*p) ? '0' : '7') << 4;
442       if (isxdigit(*++p))
443         {
444         value |= toupper(*p) - (isdigit(*p) ? '0' : '7');
445         p++;
446         }
447       *pk++ = value & 255;
448       }
449
450     break;
451
452     case ns_t_srv:
453     for (i = 0; i < 3; i++)
454       {
455       value = 0;
456       while (isdigit(*p)) value = value*10 + *p++ - '0';
457       while (isspace(*p)) p++;
458       *pk++ = (value >> 8) & 255;
459       *pk++ = value & 255;
460       }
461
462     /* Fall through */
463
464     case ns_t_cname:
465     case ns_t_ns:
466     case ns_t_ptr:
467     if (ep[-1] != '.') sprintf(ep, "%s.", zone);
468     pk = packname(p, pk);
469     plen = Ustrlen(p);
470     break;
471     }
472
473   /* Fill in the length, and we are done with this RR */
474
475   rdlptr[0] = ((pk - rdlptr - 2) >> 8) & 255;
476   rdlptr[1] = (pk -rdlptr - 2) & 255;
477   }
478
479 *pkptr = pk;
480 return (yield == HOST_NOT_FOUND && pass_on_not_found)? PASS_ON : yield;
481 }
482
483
484
485 /*************************************************
486 *           Entry point and main program         *
487 *************************************************/
488
489 int
490 main(int argc, char **argv)
491 {
492 FILE *f;
493 DIR *d;
494 int domlen, qtypelen;
495 int yield, count;
496 int i;
497 int zonecount = 0;
498 struct dirent *de;
499 zoneitem zones[32];
500 uschar *qualify = NULL;
501 uschar *p, *zone;
502 uschar *zonefile = NULL;
503 uschar domain[256];
504 uschar buffer[256];
505 uschar qtype[12];
506 uschar packet[512];
507 uschar *pk = packet;
508 BOOL dnssec;
509
510 if (argc != 4)
511   {
512   fprintf(stderr, "fakens: expected 3 arguments, received %d\n", argc-1);
513   return NO_RECOVERY;
514   }
515
516 /* Find the zones */
517
518 (void)sprintf(buffer, "%s/../dnszones", argv[1]);
519
520 d = opendir(CCS buffer);
521 if (d == NULL)
522   {
523   fprintf(stderr, "fakens: failed to opendir %s: %s\n", buffer,
524     strerror(errno));
525   return NO_RECOVERY;
526   }
527
528 while ((de = readdir(d)) != NULL)
529   {
530   uschar *name = de->d_name;
531   if (Ustrncmp(name, "qualify.", 8) == 0)
532     {
533     qualify = fcopystring("%s", name + 7);
534     continue;
535     }
536   if (Ustrncmp(name, "db.", 3) != 0) continue;
537   if (Ustrncmp(name + 3, "ip4.", 4) == 0)
538     zones[zonecount].zone = fcopystring("%s.in-addr.arpa", name + 6);
539   else if (Ustrncmp(name + 3, "ip6.", 4) == 0)
540     zones[zonecount].zone = fcopystring("%s.ip6.arpa", name + 6);
541   else
542     zones[zonecount].zone = fcopystring("%s", name + 2);
543   zones[zonecount++].zonefile = fcopystring("%s", name);
544   }
545 (void)closedir(d);
546
547 /* Get the RR type and upper case it, and check that we recognize it. */
548
549 Ustrncpy(qtype, argv[3], sizeof(qtype));
550 qtypelen = Ustrlen(qtype);
551 for (p = qtype; *p != 0; p++) *p = toupper(*p);
552
553 /* Find the domain, lower case it, check that it is in a zone that we handle,
554 and set up the zone file name. The zone names in the table all start with a
555 dot. */
556
557 domlen = Ustrlen(argv[2]);
558 if (argv[2][domlen-1] == '.') domlen--;
559 Ustrncpy(domain, argv[2], domlen);
560 domain[domlen] = 0;
561 for (i = 0; i < domlen; i++) domain[i] = tolower(domain[i]);
562
563 if (Ustrchr(domain, '.') == NULL && qualify != NULL &&
564     Ustrcmp(domain, "dontqualify") != 0)
565   {
566   Ustrcat(domain, qualify);
567   domlen += Ustrlen(qualify);
568   }
569
570 for (i = 0; i < zonecount; i++)
571   {
572   int zlen;
573   zone = zones[i].zone;
574   zlen = Ustrlen(zone);
575   if (Ustrcmp(domain, zone+1) == 0 || (domlen >= zlen &&
576       Ustrcmp(domain + domlen - zlen, zone) == 0))
577     {
578     zonefile = zones[i].zonefile;
579     break;
580     }
581   }
582
583 if (zonefile == NULL)
584   {
585   fprintf(stderr, "fakens: query not in faked zone: domain is: %s\n", domain);
586   return PASS_ON;
587   }
588
589 (void)sprintf(buffer, "%s/../dnszones/%s", argv[1], zonefile);
590
591 /* Initialize the start of the response packet. We don't have to fake up
592 everything, because we know that Exim will look only at the answer and
593 additional section parts. */
594
595 memset(packet, 0, 12);
596 pk += 12;
597
598 /* Open the zone file. */
599
600 f = fopen(buffer, "r");
601 if (f == NULL)
602   {
603   fprintf(stderr, "fakens: failed to open %s: %s\n", buffer, strerror(errno));
604   return NO_RECOVERY;
605   }
606
607 /* Find the records we want, and add them to the result. */
608
609 count = 0;
610 yield = find_records(f, zone, domain, qtype, qtypelen, &pk, &count, &dnssec);
611 if (yield == NO_RECOVERY) goto END_OFF;
612
613 packet[6] = (count >> 8) & 255;
614 packet[7] = count & 255;
615
616 /* There is no need to return any additional records because Exim no longer
617 (from release 4.61) makes any use of them. */
618
619 packet[10] = 0;
620 packet[11] = 0;
621
622 if (dnssec)
623   ((HEADER *)packet)->ad = 1;
624
625 /* Close the zone file, write the result, and return. */
626
627 END_OFF:
628 (void)fclose(f);
629 (void)fwrite(packet, 1, pk - packet, stdout);
630 return yield;
631 }
632
633 /* vi: aw ai sw=2
634 */
635 /* End of fakens.c */