3
0

dnsd.c 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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 tarball for details.
  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. #include "libbb.h"
  20. #include <syslog.h>
  21. //#define DEBUG 1
  22. #define DEBUG 0
  23. enum {
  24. MAX_HOST_LEN = 16, // longest host name allowed is 15
  25. IP_STRING_LEN = 18, // .xxx.xxx.xxx.xxx\0
  26. //must be strlen('.in-addr.arpa') larger than IP_STRING_LEN
  27. MAX_NAME_LEN = (IP_STRING_LEN + 13),
  28. /* Cannot get bigger packets than 512 per RFC1035
  29. In practice this can be set considerably smaller:
  30. Length of response packet is header (12B) + 2*type(4B) + 2*class(4B) +
  31. ttl(4B) + rlen(2B) + r (MAX_NAME_LEN =21B) +
  32. 2*querystring (2 MAX_NAME_LEN= 42B), all together 90 Byte
  33. */
  34. MAX_PACK_LEN = 512,
  35. DEFAULT_TTL = 30, // increase this when not testing?
  36. REQ_A = 1,
  37. REQ_PTR = 12
  38. };
  39. struct dns_head { // the message from client and first part of response mag
  40. uint16_t id;
  41. uint16_t flags;
  42. uint16_t nquer; // accepts 0
  43. uint16_t nansw; // 1 in response
  44. uint16_t nauth; // 0
  45. uint16_t nadd; // 0
  46. };
  47. struct dns_prop {
  48. uint16_t type;
  49. uint16_t class;
  50. };
  51. struct dns_entry { // element of known name, ip address and reversed ip address
  52. struct dns_entry *next;
  53. char ip[IP_STRING_LEN]; // dotted decimal IP
  54. char rip[IP_STRING_LEN]; // length decimal reversed IP
  55. char name[MAX_HOST_LEN];
  56. };
  57. static struct dns_entry *dnsentry;
  58. static uint32_t ttl = DEFAULT_TTL;
  59. static const char *fileconf = "/etc/dnsd.conf";
  60. // Must match getopt32 call
  61. #define OPT_daemon (option_mask32 & 0x10)
  62. #define OPT_verbose (option_mask32 & 0x20)
  63. /*
  64. * Convert host name from C-string to dns length/string.
  65. */
  66. static void convname(char *a, uint8_t *q)
  67. {
  68. int i = (q[0] == '.') ? 0 : 1;
  69. for (; i < MAX_HOST_LEN-1 && *q; i++, q++)
  70. a[i] = tolower(*q);
  71. a[0] = i - 1;
  72. a[i] = 0;
  73. }
  74. /*
  75. * Insert length of substrings instead of dots
  76. */
  77. static void undot(uint8_t * rip)
  78. {
  79. int i = 0, s = 0;
  80. while (rip[i])
  81. i++;
  82. for (--i; i >= 0; i--) {
  83. if (rip[i] == '.') {
  84. rip[i] = s;
  85. s = 0;
  86. } else s++;
  87. }
  88. }
  89. /*
  90. * Read hostname/IP records from file
  91. */
  92. static void dnsentryinit(void)
  93. {
  94. char *token[2];
  95. parser_t *parser;
  96. struct dns_entry *m, *prev;
  97. prev = dnsentry = NULL;
  98. parser = config_open(fileconf);
  99. while (config_read(parser, token, 2, 2, "# \t", PARSE_NORMAL)) {
  100. unsigned a, b, c, d;
  101. /*
  102. * Assumes all host names are lower case only
  103. * Hostnames with more than one label are not handled correctly.
  104. * Presently the dot is copied into name without
  105. * converting to a length/string substring for that label.
  106. */
  107. // if (!token[1] || sscanf(token[1], ".%u.%u.%u.%u"+1, &a, &b, &c, &d) != 4)
  108. if (sscanf(token[1], ".%u.%u.%u.%u"+1, &a, &b, &c, &d) != 4)
  109. continue;
  110. m = xzalloc(sizeof(*m));
  111. /*m->next = NULL;*/
  112. sprintf(m->ip, ".%u.%u.%u.%u"+1, a, b, c, d);
  113. sprintf(m->rip, ".%u.%u.%u.%u", d, c, b, a);
  114. undot((uint8_t*)m->rip);
  115. convname(m->name, (uint8_t*)token[0]);
  116. if (OPT_verbose)
  117. fprintf(stderr, "\tname:%s, ip:%s\n", &(m->name[1]), m->ip);
  118. if (prev == NULL)
  119. dnsentry = m;
  120. else
  121. prev->next = m;
  122. prev = m;
  123. }
  124. config_close(parser);
  125. }
  126. /*
  127. * Look query up in dns records and return answer if found
  128. * qs is the query string, first byte the string length
  129. */
  130. static int table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
  131. {
  132. int i;
  133. struct dns_entry *d = dnsentry;
  134. do {
  135. #if DEBUG
  136. char *p,*q;
  137. q = (char *)&(qs[1]);
  138. p = &(d->name[1]);
  139. fprintf(stderr, "\n%s: %d/%d p:%s q:%s %d",
  140. __FUNCTION__, (int)strlen(p), (int)(d->name[0]),
  141. p, q, (int)strlen(q));
  142. #endif
  143. if (type == REQ_A) { /* search by host name */
  144. for (i = 1; i <= (int)(d->name[0]); i++)
  145. if (tolower(qs[i]) != d->name[i])
  146. break;
  147. if (i > (int)(d->name[0]) ||
  148. (d->name[0] == 1 && d->name[1] == '*')) {
  149. strcpy((char *)as, d->ip);
  150. #if DEBUG
  151. fprintf(stderr, " OK as:%s\n", as);
  152. #endif
  153. return 0;
  154. }
  155. } else if (type == REQ_PTR) { /* search by IP-address */
  156. if ((d->name[0] != 1 || d->name[1] != '*') &&
  157. !strncmp((char*)&d->rip[1], (char*)&qs[1], strlen(d->rip)-1)) {
  158. strcpy((char *)as, d->name);
  159. return 0;
  160. }
  161. }
  162. d = d->next;
  163. } while (d);
  164. return -1;
  165. }
  166. /*
  167. * Decode message and generate answer
  168. */
  169. static int process_packet(uint8_t *buf)
  170. {
  171. uint8_t answstr[MAX_NAME_LEN + 1];
  172. struct dns_head *head;
  173. struct dns_prop *qprop;
  174. uint8_t *from, *answb;
  175. uint16_t outr_rlen;
  176. uint16_t outr_flags;
  177. uint16_t flags;
  178. int lookup_result, type, packet_len;
  179. int querystr_len;
  180. answstr[0] = '\0';
  181. head = (struct dns_head *)buf;
  182. if (head->nquer == 0) {
  183. bb_error_msg("no queries");
  184. return -1;
  185. }
  186. if (head->flags & 0x8000) {
  187. bb_error_msg("ignoring response packet");
  188. return -1;
  189. }
  190. from = (void *)&head[1]; // start of query string
  191. //FIXME: strlen of untrusted data??!
  192. querystr_len = strlen((char *)from) + 1 + sizeof(struct dns_prop);
  193. answb = from + querystr_len; // where to append answer block
  194. outr_rlen = 0;
  195. outr_flags = 0;
  196. qprop = (struct dns_prop *)(answb - 4);
  197. type = ntohs(qprop->type);
  198. // only let REQ_A and REQ_PTR pass
  199. if (!(type == REQ_A || type == REQ_PTR)) {
  200. goto empty_packet; /* we can't handle the query type */
  201. }
  202. if (ntohs(qprop->class) != 1 /* class INET */ ) {
  203. outr_flags = 4; /* not supported */
  204. goto empty_packet;
  205. }
  206. /* we only support standard queries */
  207. if ((ntohs(head->flags) & 0x7800) != 0)
  208. goto empty_packet;
  209. // We have a standard query
  210. bb_info_msg("%s", (char *)from);
  211. lookup_result = table_lookup(type, answstr, from);
  212. if (lookup_result != 0) {
  213. outr_flags = 3 | 0x0400; // name do not exist and auth
  214. goto empty_packet;
  215. }
  216. if (type == REQ_A) { // return an address
  217. struct in_addr a; // NB! its "struct { unsigned __long__ s_addr; }"
  218. uint32_t v32;
  219. if (!inet_aton((char*)answstr, &a)) { //dotted dec to long conv
  220. outr_flags = 1; /* Frmt err */
  221. goto empty_packet;
  222. }
  223. v32 = a.s_addr; /* in case long != int */
  224. memcpy(answstr, &v32, 4);
  225. outr_rlen = 4; // uint32_t IP
  226. } else
  227. outr_rlen = strlen((char *)answstr) + 1; // a host name
  228. outr_flags |= 0x0400; /* authority-bit */
  229. // we have an answer
  230. head->nansw = htons(1);
  231. // copy query block to answer block
  232. memcpy(answb, from, querystr_len);
  233. answb += querystr_len;
  234. // and append answer rr
  235. // FIXME: unaligned accesses??
  236. *(uint32_t *) answb = htonl(ttl);
  237. answb += 4;
  238. *(uint16_t *) answb = htons(outr_rlen);
  239. answb += 2;
  240. memcpy(answb, answstr, outr_rlen);
  241. answb += outr_rlen;
  242. empty_packet:
  243. flags = ntohs(head->flags);
  244. // clear rcode and RA, set responsebit and our new flags
  245. flags |= (outr_flags & 0xff80) | 0x8000;
  246. head->flags = htons(flags);
  247. head->nauth = head->nadd = 0;
  248. head->nquer = htons(1);
  249. packet_len = answb - buf;
  250. return packet_len;
  251. }
  252. /*
  253. * Exit on signal
  254. */
  255. static void interrupt(int sig)
  256. {
  257. /* unlink("/var/run/dnsd.lock"); */
  258. bb_error_msg("interrupt, exiting\n");
  259. kill_myself_with_sig(sig);
  260. }
  261. int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  262. int dnsd_main(int argc UNUSED_PARAM, char **argv)
  263. {
  264. const char *listen_interface = "0.0.0.0";
  265. char *sttl, *sport;
  266. len_and_sockaddr *lsa, *from, *to;
  267. unsigned lsa_size;
  268. int udps;
  269. uint16_t port = 53;
  270. /* Paranoid sizing: querystring x2 + ttl + outr_rlen + answstr */
  271. /* I'd rather see process_packet() fixed instead... */
  272. uint8_t buf[MAX_PACK_LEN * 2 + 4 + 2 + (MAX_NAME_LEN+1)];
  273. getopt32(argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
  274. //if (option_mask32 & 0x1) // -i
  275. //if (option_mask32 & 0x2) // -c
  276. if (option_mask32 & 0x4) // -t
  277. ttl = xatou_range(sttl, 1, 0xffffffff);
  278. if (option_mask32 & 0x8) // -p
  279. port = xatou_range(sport, 1, 0xffff);
  280. if (OPT_verbose) {
  281. bb_info_msg("listen_interface: %s", listen_interface);
  282. bb_info_msg("ttl: %d, port: %d", ttl, port);
  283. bb_info_msg("fileconf: %s", fileconf);
  284. }
  285. if (OPT_daemon) {
  286. bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
  287. openlog(applet_name, LOG_PID, LOG_DAEMON);
  288. logmode = LOGMODE_SYSLOG;
  289. }
  290. dnsentryinit();
  291. signal(SIGINT, interrupt);
  292. bb_signals(0
  293. /* why? + (1 << SIGPIPE) */
  294. + (1 << SIGHUP)
  295. #ifdef SIGTSTP
  296. + (1 << SIGTSTP)
  297. #endif
  298. #ifdef SIGURG
  299. + (1 << SIGURG)
  300. #endif
  301. , SIG_IGN);
  302. lsa = xdotted2sockaddr(listen_interface, port);
  303. udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
  304. xbind(udps, &lsa->u.sa, lsa->len);
  305. socket_want_pktinfo(udps); /* needed for recv_from_to to work */
  306. lsa_size = LSA_LEN_SIZE + lsa->len;
  307. from = xzalloc(lsa_size);
  308. to = xzalloc(lsa_size);
  309. bb_info_msg("Accepting UDP packets on %s",
  310. xmalloc_sockaddr2dotted(&lsa->u.sa));
  311. while (1) {
  312. int r;
  313. /* Try to get *DEST* address (to which of our addresses
  314. * this query was directed), and reply from the same address.
  315. * Or else we can exhibit usual UDP ugliness:
  316. * [ip1.multihomed.ip2] <= query to ip1 <= peer
  317. * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
  318. memcpy(to, lsa, lsa_size);
  319. r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
  320. if (r < 12 || r > MAX_PACK_LEN) {
  321. bb_error_msg("invalid packet size");
  322. continue;
  323. }
  324. if (OPT_verbose)
  325. bb_info_msg("Got UDP packet");
  326. buf[r] = '\0'; /* paranoia */
  327. r = process_packet(buf);
  328. if (r <= 0)
  329. continue;
  330. send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len);
  331. }
  332. return 0;
  333. }