dnsd.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini DNS server implementation for busybox
  4. *
  5. * Copyright (C) 2005 Roberto A. Foglietta (me@roberto.foglietta.name)
  6. * Copyright (C) 2005 Odd Arild Olsen (oao at fibula dot no)
  7. * Copyright (C) 2003 Paul Sheer
  8. *
  9. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  10. *
  11. * Odd Arild Olsen started out with the sheerdns [1] of Paul Sheer and rewrote
  12. * it into a shape which I believe is both easier to understand and maintain.
  13. * I also reused the input buffer for output and removed services he did not
  14. * need. [1] http://threading.2038bug.com/sheerdns/
  15. *
  16. * Some bugfix and minor changes was applied by Roberto A. Foglietta who made
  17. * the first porting of oao' scdns to busybox also.
  18. */
  19. //config:config DNSD
  20. //config: bool "dnsd"
  21. //config: default y
  22. //config: help
  23. //config: Small and static DNS server daemon.
  24. //applet:IF_DNSD(APPLET(dnsd, BB_DIR_USR_SBIN, BB_SUID_DROP))
  25. //kbuild:lib-$(CONFIG_DNSD) += dnsd.o
  26. //usage:#define dnsd_trivial_usage
  27. //usage: "[-dvs] [-c CONFFILE] [-t TTL_SEC] [-p PORT] [-i ADDR]"
  28. //usage:#define dnsd_full_usage "\n\n"
  29. //usage: "Small static DNS server daemon\n"
  30. //usage: "\n -c FILE Config file"
  31. //usage: "\n -t SEC TTL"
  32. //usage: "\n -p PORT Listen on PORT"
  33. //usage: "\n -i ADDR Listen on ADDR"
  34. //usage: "\n -d Daemonize"
  35. //usage: "\n -v Verbose"
  36. //usage: "\n -s Send successful replies only. Use this if you want"
  37. //usage: "\n to use /etc/resolv.conf with two nameserver lines:"
  38. //usage: "\n nameserver DNSD_SERVER"
  39. //usage: "\n nameserver NORMAL_DNS_SERVER"
  40. #include "libbb.h"
  41. #include <syslog.h>
  42. //#define DEBUG 1
  43. #define DEBUG 0
  44. enum {
  45. /* can tweak this */
  46. DEFAULT_TTL = 120,
  47. /* cannot get bigger packets than 512 per RFC1035. */
  48. MAX_PACK_LEN = 512,
  49. IP_STRING_LEN = sizeof(".xxx.xxx.xxx.xxx"),
  50. MAX_NAME_LEN = IP_STRING_LEN - 1 + sizeof(".in-addr.arpa"),
  51. REQ_A = 1,
  52. REQ_PTR = 12,
  53. };
  54. /* the message from client and first part of response msg */
  55. struct dns_head {
  56. uint16_t id;
  57. uint16_t flags;
  58. uint16_t nquer;
  59. uint16_t nansw;
  60. uint16_t nauth;
  61. uint16_t nadd;
  62. };
  63. /* Structure used to access type and class fields.
  64. * They are totally unaligned, but gcc 4.3.4 thinks that pointer of type uint16_t*
  65. * is 16-bit aligned and replaces 16-bit memcpy (in move_from_unaligned16 macro)
  66. * with aligned halfword access on arm920t!
  67. * Oh well. Slapping PACKED everywhere seems to help: */
  68. struct type_and_class {
  69. uint16_t type PACKED;
  70. uint16_t class PACKED;
  71. } PACKED;
  72. /* element of known name, ip address and reversed ip address */
  73. struct dns_entry {
  74. struct dns_entry *next;
  75. uint32_t ip;
  76. char rip[IP_STRING_LEN]; /* length decimal reversed IP */
  77. char name[1];
  78. };
  79. #define OPT_verbose (option_mask32 & 1)
  80. #define OPT_silent (option_mask32 & 2)
  81. /*
  82. * Insert length of substrings instead of dots
  83. */
  84. static void undot(char *rip)
  85. {
  86. int i = 0;
  87. int s = 0;
  88. while (rip[i])
  89. i++;
  90. for (--i; i >= 0; i--) {
  91. if (rip[i] == '.') {
  92. rip[i] = s;
  93. s = 0;
  94. } else {
  95. s++;
  96. }
  97. }
  98. }
  99. /*
  100. * Read hostname/IP records from file
  101. */
  102. static struct dns_entry *parse_conf_file(const char *fileconf)
  103. {
  104. char *token[2];
  105. parser_t *parser;
  106. struct dns_entry *m, *conf_data;
  107. struct dns_entry **nextp;
  108. conf_data = NULL;
  109. nextp = &conf_data;
  110. parser = config_open(fileconf);
  111. while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
  112. struct in_addr ip;
  113. uint32_t v32;
  114. if (inet_aton(token[1], &ip) == 0) {
  115. bb_error_msg("error at line %u, skipping", parser->lineno);
  116. continue;
  117. }
  118. if (OPT_verbose)
  119. bb_error_msg("name:%s, ip:%s", token[0], token[1]);
  120. /* sizeof(*m) includes 1 byte for m->name[0] */
  121. m = xzalloc(sizeof(*m) + strlen(token[0]) + 1);
  122. /*m->next = NULL;*/
  123. *nextp = m;
  124. nextp = &m->next;
  125. m->name[0] = '.';
  126. strcpy(m->name + 1, token[0]);
  127. undot(m->name);
  128. m->ip = ip.s_addr; /* in network order */
  129. v32 = ntohl(m->ip);
  130. /* inverted order */
  131. sprintf(m->rip, ".%u.%u.%u.%u",
  132. (uint8_t)(v32),
  133. (uint8_t)(v32 >> 8),
  134. (uint8_t)(v32 >> 16),
  135. (v32 >> 24)
  136. );
  137. undot(m->rip);
  138. }
  139. config_close(parser);
  140. return conf_data;
  141. }
  142. /*
  143. * Look query up in dns records and return answer if found.
  144. */
  145. static char *table_lookup(struct dns_entry *d,
  146. uint16_t type,
  147. char* query_string)
  148. {
  149. while (d) {
  150. unsigned len = d->name[0];
  151. /* d->name[len] is the last (non NUL) char */
  152. #if DEBUG
  153. char *p, *q;
  154. q = query_string + 1;
  155. p = d->name + 1;
  156. fprintf(stderr, "%d/%d p:%s q:%s %d\n",
  157. (int)strlen(p), len,
  158. p, q, (int)strlen(q)
  159. );
  160. #endif
  161. if (type == htons(REQ_A)) {
  162. /* search by host name */
  163. if (len != 1 || d->name[1] != '*') {
  164. /* we are lax, hope no name component is ever >64 so that length
  165. * (which will be represented as 'A','B'...) matches a lowercase letter.
  166. * Actually, I think false matches are hard to construct.
  167. * Example.
  168. * [31] len is represented as '1', [65] as 'A', [65+32] as 'a'.
  169. * [65] <65 same chars>[31]<31 same chars>NUL
  170. * [65+32]<65 same chars>1 <31 same chars>NUL
  171. * This example seems to be the minimal case when false match occurs.
  172. */
  173. if (strcasecmp(d->name, query_string) != 0)
  174. goto next;
  175. }
  176. return (char *)&d->ip;
  177. #if DEBUG
  178. fprintf(stderr, "Found IP:%x\n", (int)d->ip);
  179. #endif
  180. return 0;
  181. }
  182. /* search by IP-address */
  183. if ((len != 1 || d->name[1] != '*')
  184. /* we assume (do not check) that query_string
  185. * ends in ".in-addr.arpa" */
  186. && is_prefixed_with(query_string, d->rip)
  187. ) {
  188. #if DEBUG
  189. fprintf(stderr, "Found name:%s\n", d->name);
  190. #endif
  191. return d->name;
  192. }
  193. next:
  194. d = d->next;
  195. }
  196. return NULL;
  197. }
  198. /*
  199. * Decode message and generate answer
  200. */
  201. /* RFC 1035
  202. ...
  203. Whenever an octet represents a numeric quantity, the left most bit
  204. in the diagram is the high order or most significant bit.
  205. That is, the bit labeled 0 is the most significant bit.
  206. ...
  207. 4.1.1. Header section format
  208. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  209. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  210. | ID |
  211. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  212. |QR| OPCODE |AA|TC|RD|RA| 0 0 0| RCODE |
  213. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  214. | QDCOUNT |
  215. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  216. | ANCOUNT |
  217. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  218. | NSCOUNT |
  219. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  220. | ARCOUNT |
  221. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  222. ID 16 bit random identifier assigned by querying peer.
  223. Used to match query/response.
  224. QR message is a query (0), or a response (1).
  225. OPCODE 0 standard query (QUERY)
  226. 1 inverse query (IQUERY)
  227. 2 server status request (STATUS)
  228. AA Authoritative Answer - this bit is valid in responses.
  229. Responding name server is an authority for the domain name
  230. in question section. Answer section may have multiple owner names
  231. because of aliases. The AA bit corresponds to the name which matches
  232. the query name, or the first owner name in the answer section.
  233. TC TrunCation - this message was truncated.
  234. RD Recursion Desired - this bit may be set in a query and
  235. is copied into the response. If RD is set, it directs
  236. the name server to pursue the query recursively.
  237. Recursive query support is optional.
  238. RA Recursion Available - this be is set or cleared in a
  239. response, and denotes whether recursive query support is
  240. available in the name server.
  241. RCODE Response code.
  242. 0 No error condition
  243. 1 Format error
  244. 2 Server failure - server was unable to process the query
  245. due to a problem with the name server.
  246. 3 Name Error - meaningful only for responses from
  247. an authoritative name server. The referenced domain name
  248. does not exist.
  249. 4 Not Implemented.
  250. 5 Refused.
  251. QDCOUNT number of entries in the question section.
  252. ANCOUNT number of records in the answer section.
  253. NSCOUNT number of records in the authority records section.
  254. ARCOUNT number of records in the additional records section.
  255. 4.1.2. Question section format
  256. The section contains QDCOUNT (usually 1) entries, each of this format:
  257. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  258. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  259. / QNAME /
  260. / /
  261. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  262. | QTYPE |
  263. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  264. | QCLASS |
  265. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  266. QNAME a domain name represented as a sequence of labels, where
  267. each label consists of a length octet followed by that
  268. number of octets. The domain name terminates with the
  269. zero length octet for the null label of the root. Note
  270. that this field may be an odd number of octets; no
  271. padding is used.
  272. QTYPE a two octet type of the query.
  273. 1 a host address [REQ_A const]
  274. 2 an authoritative name server
  275. 3 a mail destination (Obsolete - use MX)
  276. 4 a mail forwarder (Obsolete - use MX)
  277. 5 the canonical name for an alias
  278. 6 marks the start of a zone of authority
  279. 7 a mailbox domain name (EXPERIMENTAL)
  280. 8 a mail group member (EXPERIMENTAL)
  281. 9 a mail rename domain name (EXPERIMENTAL)
  282. 10 a null RR (EXPERIMENTAL)
  283. 11 a well known service description
  284. 12 a domain name pointer [REQ_PTR const]
  285. 13 host information
  286. 14 mailbox or mail list information
  287. 15 mail exchange
  288. 16 text strings
  289. 0x1c IPv6?
  290. 252 a request for a transfer of an entire zone
  291. 253 a request for mailbox-related records (MB, MG or MR)
  292. 254 a request for mail agent RRs (Obsolete - see MX)
  293. 255 a request for all records
  294. QCLASS a two octet code that specifies the class of the query.
  295. 1 the Internet
  296. (others are historic only)
  297. 255 any class
  298. 4.1.3. Resource Record format
  299. The answer, authority, and additional sections all share the same format:
  300. a variable number of resource records, where the number of records
  301. is specified in the corresponding count field in the header.
  302. Each resource record has this format:
  303. 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  304. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  305. / /
  306. / NAME /
  307. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  308. | TYPE |
  309. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  310. | CLASS |
  311. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  312. | TTL |
  313. | |
  314. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  315. | RDLENGTH |
  316. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
  317. / RDATA /
  318. / /
  319. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  320. NAME a domain name to which this resource record pertains.
  321. TYPE two octets containing one of the RR type codes. This
  322. field specifies the meaning of the data in the RDATA field.
  323. CLASS two octets which specify the class of the data in the RDATA field.
  324. TTL a 32 bit unsigned integer that specifies the time interval
  325. (in seconds) that the record may be cached.
  326. RDLENGTH a 16 bit integer, length in octets of the RDATA field.
  327. RDATA a variable length string of octets that describes the resource.
  328. The format of this information varies according to the TYPE
  329. and CLASS of the resource record.
  330. If the TYPE is A and the CLASS is IN, it's a 4 octet IP address.
  331. 4.1.4. Message compression
  332. In order to reduce the size of messages, domain names coan be compressed.
  333. An entire domain name or a list of labels at the end of a domain name
  334. is replaced with a pointer to a prior occurrence of the same name.
  335. The pointer takes the form of a two octet sequence:
  336. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  337. | 1 1| OFFSET |
  338. +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
  339. The first two bits are ones. This allows a pointer to be distinguished
  340. from a label, since the label must begin with two zero bits because
  341. labels are restricted to 63 octets or less. The OFFSET field specifies
  342. an offset from the start of the message (i.e., the first octet
  343. of the ID field in the domain header).
  344. A zero offset specifies the first byte of the ID field, etc.
  345. Domain name in a message can be represented as either:
  346. - a sequence of labels ending in a zero octet
  347. - a pointer
  348. - a sequence of labels ending with a pointer
  349. */
  350. static int process_packet(struct dns_entry *conf_data,
  351. uint32_t conf_ttl,
  352. uint8_t *buf)
  353. {
  354. struct dns_head *head;
  355. struct type_and_class *unaligned_type_class;
  356. const char *err_msg;
  357. char *query_string;
  358. char *answstr;
  359. uint8_t *answb;
  360. uint16_t outr_rlen;
  361. uint16_t outr_flags;
  362. uint16_t type;
  363. uint16_t class;
  364. int query_len;
  365. head = (struct dns_head *)buf;
  366. if (head->nquer == 0) {
  367. bb_error_msg("packet has 0 queries, ignored");
  368. return 0; /* don't reply */
  369. }
  370. if (head->flags & htons(0x8000)) { /* QR bit */
  371. bb_error_msg("response packet, ignored");
  372. return 0; /* don't reply */
  373. }
  374. /* QR = 1 "response", RCODE = 4 "Not Implemented" */
  375. outr_flags = htons(0x8000 | 4);
  376. err_msg = NULL;
  377. /* start of query string */
  378. query_string = (void *)(head + 1);
  379. /* caller guarantees strlen is <= MAX_PACK_LEN */
  380. query_len = strlen(query_string) + 1;
  381. /* may be unaligned! */
  382. unaligned_type_class = (void *)(query_string + query_len);
  383. query_len += sizeof(*unaligned_type_class);
  384. /* where to append answer block */
  385. answb = (void *)(unaligned_type_class + 1);
  386. /* OPCODE != 0 "standard query"? */
  387. if ((head->flags & htons(0x7800)) != 0) {
  388. err_msg = "opcode != 0";
  389. goto empty_packet;
  390. }
  391. move_from_unaligned16(class, &unaligned_type_class->class);
  392. if (class != htons(1)) { /* not class INET? */
  393. err_msg = "class != 1";
  394. goto empty_packet;
  395. }
  396. move_from_unaligned16(type, &unaligned_type_class->type);
  397. if (type != htons(REQ_A) && type != htons(REQ_PTR)) {
  398. /* we can't handle this query type */
  399. //TODO: happens all the time with REQ_AAAA (0x1c) requests - implement those?
  400. err_msg = "type is !REQ_A and !REQ_PTR";
  401. goto empty_packet;
  402. }
  403. /* look up the name */
  404. answstr = table_lookup(conf_data, type, query_string);
  405. #if DEBUG
  406. /* Shows lengths instead of dots, unusable for !DEBUG */
  407. bb_error_msg("'%s'->'%s'", query_string, answstr);
  408. #endif
  409. outr_rlen = 4;
  410. if (answstr && type == htons(REQ_PTR)) {
  411. /* returning a host name */
  412. outr_rlen = strlen(answstr) + 1;
  413. }
  414. if (!answstr
  415. || (unsigned)(answb - buf) + query_len + 4 + 2 + outr_rlen > MAX_PACK_LEN
  416. ) {
  417. /* QR = 1 "response"
  418. * AA = 1 "Authoritative Answer"
  419. * RCODE = 3 "Name Error" */
  420. err_msg = "name is not found";
  421. outr_flags = htons(0x8000 | 0x0400 | 3);
  422. goto empty_packet;
  423. }
  424. /* Append answer Resource Record */
  425. memcpy(answb, query_string, query_len); /* name, type, class */
  426. answb += query_len;
  427. move_to_unaligned32((uint32_t *)answb, htonl(conf_ttl));
  428. answb += 4;
  429. move_to_unaligned16((uint16_t *)answb, htons(outr_rlen));
  430. answb += 2;
  431. memcpy(answb, answstr, outr_rlen);
  432. answb += outr_rlen;
  433. /* QR = 1 "response",
  434. * AA = 1 "Authoritative Answer",
  435. * TODO: need to set RA bit 0x80? One user says nslookup complains
  436. * "Got recursion not available from SERVER, trying next server"
  437. * "** server can't find HOSTNAME"
  438. * RCODE = 0 "success"
  439. */
  440. if (OPT_verbose)
  441. bb_error_msg("returning positive reply");
  442. outr_flags = htons(0x8000 | 0x0400 | 0);
  443. /* we have one answer */
  444. head->nansw = htons(1);
  445. empty_packet:
  446. if ((outr_flags & htons(0xf)) != 0) { /* not a positive response */
  447. if (OPT_verbose) {
  448. bb_error_msg("%s, %s",
  449. err_msg,
  450. OPT_silent ? "dropping query" : "sending error reply"
  451. );
  452. }
  453. if (OPT_silent)
  454. return 0;
  455. }
  456. head->flags |= outr_flags;
  457. head->nauth = head->nadd = 0;
  458. head->nquer = htons(1); // why???
  459. return answb - buf;
  460. }
  461. int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  462. int dnsd_main(int argc UNUSED_PARAM, char **argv)
  463. {
  464. const char *listen_interface = "0.0.0.0";
  465. const char *fileconf = "/etc/dnsd.conf";
  466. struct dns_entry *conf_data;
  467. uint32_t conf_ttl = DEFAULT_TTL;
  468. char *sttl, *sport;
  469. len_and_sockaddr *lsa, *from, *to;
  470. unsigned lsa_size;
  471. int udps, opts;
  472. uint16_t port = 53;
  473. /* Ensure buf is 32bit aligned (we need 16bit, but 32bit can't hurt) */
  474. uint8_t buf[MAX_PACK_LEN + 1] ALIGN4;
  475. opts = getopt32(argv, "vsi:c:t:p:d", &listen_interface, &fileconf, &sttl, &sport);
  476. //if (opts & (1 << 0)) // -v
  477. //if (opts & (1 << 1)) // -s
  478. //if (opts & (1 << 2)) // -i
  479. //if (opts & (1 << 3)) // -c
  480. if (opts & (1 << 4)) // -t
  481. conf_ttl = xatou_range(sttl, 1, 0xffffffff);
  482. if (opts & (1 << 5)) // -p
  483. port = xatou_range(sport, 1, 0xffff);
  484. if (opts & (1 << 6)) { // -d
  485. bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
  486. openlog(applet_name, LOG_PID, LOG_DAEMON);
  487. logmode = LOGMODE_SYSLOG;
  488. }
  489. conf_data = parse_conf_file(fileconf);
  490. lsa = xdotted2sockaddr(listen_interface, port);
  491. udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
  492. xbind(udps, &lsa->u.sa, lsa->len);
  493. socket_want_pktinfo(udps); /* needed for recv_from_to to work */
  494. lsa_size = LSA_LEN_SIZE + lsa->len;
  495. from = xzalloc(lsa_size);
  496. to = xzalloc(lsa_size);
  497. {
  498. char *p = xmalloc_sockaddr2dotted(&lsa->u.sa);
  499. bb_error_msg("accepting UDP packets on %s", p);
  500. free(p);
  501. }
  502. while (1) {
  503. int r;
  504. /* Try to get *DEST* address (to which of our addresses
  505. * this query was directed), and reply from the same address.
  506. * Or else we can exhibit usual UDP ugliness:
  507. * [ip1.multihomed.ip2] <= query to ip1 <= peer
  508. * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
  509. memcpy(to, lsa, lsa_size);
  510. r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
  511. if (r < 12 || r > MAX_PACK_LEN) {
  512. bb_error_msg("packet size %d, ignored", r);
  513. continue;
  514. }
  515. if (OPT_verbose)
  516. bb_error_msg("got UDP packet");
  517. buf[r] = '\0'; /* paranoia */
  518. r = process_packet(conf_data, conf_ttl, buf);
  519. if (r <= 0)
  520. continue;
  521. send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len);
  522. }
  523. return 0;
  524. }