3
0

dnsd.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 one line of hostname/IP from file
  91. * Returns 0 for each valid entry read, -1 at EOF
  92. * Assumes all host names are lower case only
  93. * Hostnames with more than one label are not handled correctly.
  94. * Presently the dot is copied into name without
  95. * converting to a length/string substring for that label.
  96. */
  97. static int getfileentry(FILE * fp, struct dns_entry *s)
  98. {
  99. unsigned int a,b,c,d;
  100. char *line, *r, *name;
  101. restart:
  102. line = r = xmalloc_fgets(fp);
  103. if (!r)
  104. return -1;
  105. while (*r == ' ' || *r == '\t') {
  106. r++;
  107. if (!*r || *r == '#' || *r == '\n') {
  108. free(line);
  109. goto restart; /* skipping empty/blank and commented lines */
  110. }
  111. }
  112. name = r;
  113. while (*r != ' ' && *r != '\t')
  114. r++;
  115. *r++ = '\0';
  116. if (sscanf(r, ".%u.%u.%u.%u"+1, &a, &b, &c, &d) != 4) {
  117. free(line);
  118. goto restart; /* skipping wrong lines */
  119. }
  120. sprintf(s->ip, ".%u.%u.%u.%u"+1, a, b, c, d);
  121. sprintf(s->rip, ".%u.%u.%u.%u", d, c, b, a);
  122. undot((uint8_t*)s->rip);
  123. convname(s->name, (uint8_t*)name);
  124. if (OPT_verbose)
  125. fprintf(stderr, "\tname:%s, ip:%s\n", &(s->name[1]),s->ip);
  126. free(line);
  127. return 0;
  128. }
  129. /*
  130. * Read hostname/IP records from file
  131. */
  132. static void dnsentryinit(void)
  133. {
  134. FILE *fp;
  135. struct dns_entry *m, *prev;
  136. prev = dnsentry = NULL;
  137. fp = xfopen(fileconf, "r");
  138. while (1) {
  139. m = xzalloc(sizeof(*m));
  140. /*m->next = NULL;*/
  141. if (getfileentry(fp, m))
  142. break;
  143. if (prev == NULL)
  144. dnsentry = m;
  145. else
  146. prev->next = m;
  147. prev = m;
  148. }
  149. fclose(fp);
  150. }
  151. /*
  152. * Look query up in dns records and return answer if found
  153. * qs is the query string, first byte the string length
  154. */
  155. static int table_lookup(uint16_t type, uint8_t * as, uint8_t * qs)
  156. {
  157. int i;
  158. struct dns_entry *d = dnsentry;
  159. do {
  160. #if DEBUG
  161. char *p,*q;
  162. q = (char *)&(qs[1]);
  163. p = &(d->name[1]);
  164. fprintf(stderr, "\n%s: %d/%d p:%s q:%s %d",
  165. __FUNCTION__, (int)strlen(p), (int)(d->name[0]),
  166. p, q, (int)strlen(q));
  167. #endif
  168. if (type == REQ_A) { /* search by host name */
  169. for (i = 1; i <= (int)(d->name[0]); i++)
  170. if (tolower(qs[i]) != d->name[i])
  171. break;
  172. if (i > (int)(d->name[0]) ||
  173. (d->name[0] == 1 && d->name[1] == '*')) {
  174. strcpy((char *)as, d->ip);
  175. #if DEBUG
  176. fprintf(stderr, " OK as:%s\n", as);
  177. #endif
  178. return 0;
  179. }
  180. } else if (type == REQ_PTR) { /* search by IP-address */
  181. if ((d->name[0] != 1 || d->name[1] != '*') &&
  182. !strncmp((char*)&d->rip[1], (char*)&qs[1], strlen(d->rip)-1)) {
  183. strcpy((char *)as, d->name);
  184. return 0;
  185. }
  186. }
  187. d = d->next;
  188. } while (d);
  189. return -1;
  190. }
  191. /*
  192. * Decode message and generate answer
  193. */
  194. static int process_packet(uint8_t *buf)
  195. {
  196. uint8_t answstr[MAX_NAME_LEN + 1];
  197. struct dns_head *head;
  198. struct dns_prop *qprop;
  199. uint8_t *from, *answb;
  200. uint16_t outr_rlen;
  201. uint16_t outr_flags;
  202. uint16_t flags;
  203. int lookup_result, type, packet_len;
  204. int querystr_len;
  205. answstr[0] = '\0';
  206. head = (struct dns_head *)buf;
  207. if (head->nquer == 0) {
  208. bb_error_msg("no queries");
  209. return -1;
  210. }
  211. if (head->flags & 0x8000) {
  212. bb_error_msg("ignoring response packet");
  213. return -1;
  214. }
  215. from = (void *)&head[1]; // start of query string
  216. //FIXME: strlen of untrusted data??!
  217. querystr_len = strlen((char *)from) + 1 + sizeof(struct dns_prop);
  218. answb = from + querystr_len; // where to append answer block
  219. outr_rlen = 0;
  220. outr_flags = 0;
  221. qprop = (struct dns_prop *)(answb - 4);
  222. type = ntohs(qprop->type);
  223. // only let REQ_A and REQ_PTR pass
  224. if (!(type == REQ_A || type == REQ_PTR)) {
  225. goto empty_packet; /* we can't handle the query type */
  226. }
  227. if (ntohs(qprop->class) != 1 /* class INET */ ) {
  228. outr_flags = 4; /* not supported */
  229. goto empty_packet;
  230. }
  231. /* we only support standard queries */
  232. if ((ntohs(head->flags) & 0x7800) != 0)
  233. goto empty_packet;
  234. // We have a standard query
  235. bb_info_msg("%s", (char *)from);
  236. lookup_result = table_lookup(type, answstr, from);
  237. if (lookup_result != 0) {
  238. outr_flags = 3 | 0x0400; // name do not exist and auth
  239. goto empty_packet;
  240. }
  241. if (type == REQ_A) { // return an address
  242. struct in_addr a; // NB! its "struct { unsigned __long__ s_addr; }"
  243. uint32_t v32;
  244. if (!inet_aton((char*)answstr, &a)) { //dotted dec to long conv
  245. outr_flags = 1; /* Frmt err */
  246. goto empty_packet;
  247. }
  248. v32 = a.s_addr; /* in case long != int */
  249. memcpy(answstr, &v32, 4);
  250. outr_rlen = 4; // uint32_t IP
  251. } else
  252. outr_rlen = strlen((char *)answstr) + 1; // a host name
  253. outr_flags |= 0x0400; /* authority-bit */
  254. // we have an answer
  255. head->nansw = htons(1);
  256. // copy query block to answer block
  257. memcpy(answb, from, querystr_len);
  258. answb += querystr_len;
  259. // and append answer rr
  260. // FIXME: unaligned accesses??
  261. *(uint32_t *) answb = htonl(ttl);
  262. answb += 4;
  263. *(uint16_t *) answb = htons(outr_rlen);
  264. answb += 2;
  265. memcpy(answb, answstr, outr_rlen);
  266. answb += outr_rlen;
  267. empty_packet:
  268. flags = ntohs(head->flags);
  269. // clear rcode and RA, set responsebit and our new flags
  270. flags |= (outr_flags & 0xff80) | 0x8000;
  271. head->flags = htons(flags);
  272. head->nauth = head->nadd = 0;
  273. head->nquer = htons(1);
  274. packet_len = answb - buf;
  275. return packet_len;
  276. }
  277. /*
  278. * Exit on signal
  279. */
  280. static void interrupt(int sig)
  281. {
  282. /* unlink("/var/run/dnsd.lock"); */
  283. bb_error_msg("interrupt, exiting\n");
  284. kill_myself_with_sig(sig);
  285. }
  286. int dnsd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  287. int dnsd_main(int argc ATTRIBUTE_UNUSED, char **argv)
  288. {
  289. const char *listen_interface = "0.0.0.0";
  290. char *sttl, *sport;
  291. len_and_sockaddr *lsa, *from, *to;
  292. unsigned lsa_size;
  293. int udps;
  294. uint16_t port = 53;
  295. /* Paranoid sizing: querystring x2 + ttl + outr_rlen + answstr */
  296. /* I'd rather see process_packet() fixed instead... */
  297. uint8_t buf[MAX_PACK_LEN * 2 + 4 + 2 + (MAX_NAME_LEN+1)];
  298. getopt32(argv, "i:c:t:p:dv", &listen_interface, &fileconf, &sttl, &sport);
  299. //if (option_mask32 & 0x1) // -i
  300. //if (option_mask32 & 0x2) // -c
  301. if (option_mask32 & 0x4) // -t
  302. ttl = xatou_range(sttl, 1, 0xffffffff);
  303. if (option_mask32 & 0x8) // -p
  304. port = xatou_range(sport, 1, 0xffff);
  305. if (OPT_verbose) {
  306. bb_info_msg("listen_interface: %s", listen_interface);
  307. bb_info_msg("ttl: %d, port: %d", ttl, port);
  308. bb_info_msg("fileconf: %s", fileconf);
  309. }
  310. if (OPT_daemon) {
  311. bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
  312. openlog(applet_name, LOG_PID, LOG_DAEMON);
  313. logmode = LOGMODE_SYSLOG;
  314. }
  315. dnsentryinit();
  316. signal(SIGINT, interrupt);
  317. bb_signals(0
  318. /* why? + (1 << SIGPIPE) */
  319. + (1 << SIGHUP)
  320. #ifdef SIGTSTP
  321. + (1 << SIGTSTP)
  322. #endif
  323. #ifdef SIGURG
  324. + (1 << SIGURG)
  325. #endif
  326. , SIG_IGN);
  327. lsa = xdotted2sockaddr(listen_interface, port);
  328. udps = xsocket(lsa->u.sa.sa_family, SOCK_DGRAM, 0);
  329. xbind(udps, &lsa->u.sa, lsa->len);
  330. socket_want_pktinfo(udps); /* needed for recv_from_to to work */
  331. lsa_size = LSA_LEN_SIZE + lsa->len;
  332. from = xzalloc(lsa_size);
  333. to = xzalloc(lsa_size);
  334. bb_info_msg("Accepting UDP packets on %s",
  335. xmalloc_sockaddr2dotted(&lsa->u.sa));
  336. while (1) {
  337. int r;
  338. /* Try to get *DEST* address (to which of our addresses
  339. * this query was directed), and reply from the same address.
  340. * Or else we can exhibit usual UDP ugliness:
  341. * [ip1.multihomed.ip2] <= query to ip1 <= peer
  342. * [ip1.multihomed.ip2] => reply from ip2 => peer (confused) */
  343. memcpy(to, lsa, lsa_size);
  344. r = recv_from_to(udps, buf, MAX_PACK_LEN + 1, 0, &from->u.sa, &to->u.sa, lsa->len);
  345. if (r < 12 || r > MAX_PACK_LEN) {
  346. bb_error_msg("invalid packet size");
  347. continue;
  348. }
  349. if (OPT_verbose)
  350. bb_info_msg("Got UDP packet");
  351. buf[r] = '\0'; /* paranoia */
  352. r = process_packet(buf);
  353. if (r <= 0)
  354. continue;
  355. send_to_from(udps, buf, r, 0, &from->u.sa, &to->u.sa, lsa->len);
  356. }
  357. return 0;
  358. }