A userspace application that filters DHCP floods to protect a DHCP server. It uses the Netfilter userspace packet queuing API.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dhcp_protect.c 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. // dhcp_protect.c
  2. // Copyright 2019 Pascal Gloor
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <unistd.h>
  19. #include <stdint.h>
  20. #include <errno.h>
  21. #include <time.h>
  22. #include <stdarg.h>
  23. #include <syslog.h>
  24. #include <arpa/inet.h>
  25. #include <linux/netfilter.h>
  26. #include <libnetfilter_queue/libnetfilter_queue.h>
  27. #include <uthash.h>
  28. #include "dhcp_protect.h"
  29. // main function
  30. int main(int argc, char **argv) {
  31. char *configfile;
  32. dp_conf conf;
  33. if ( argc == 2 ) {
  34. configfile = argv[1];
  35. }
  36. else {
  37. usage(argv[0]);
  38. return EXIT_FAILURE;
  39. }
  40. if ( load_config(&conf, configfile) == NULL )
  41. return EXIT_FAILURE;
  42. openlog("dhcp_protect", LOG_PID, LOG_DAEMON);
  43. nfq_start(&conf);
  44. return 0;
  45. }
  46. // syslog function
  47. void dp_log(unsigned char *remoteid, int remoteidlen, char *fmt, ...) {
  48. va_list argList;
  49. char buf[1000];
  50. int offset = remoteidlen*2;
  51. int i;
  52. for(i=0; i<remoteidlen; i++) {
  53. sprintf(buf+(i*2), "%02x", remoteid[i]);
  54. }
  55. buf[offset]=':'; offset++;
  56. buf[offset]=' '; offset++;
  57. va_start(argList, fmt);
  58. vsnprintf(buf+offset, sizeof(buf)-offset-1, fmt, argList);
  59. va_end(argList);
  60. syslog(LOG_DAEMON|LOG_INFO, "%s", buf);
  61. }
  62. // start netfilter queue
  63. void nfq_start(dp_conf *conf) {
  64. struct nfq_handle *h;
  65. struct nfq_q_handle *qh;
  66. int fd;
  67. if ( ( h = nfq_open() ) == NULL ) {
  68. fprintf(stderr,"error during nfq_open() %s\n", strerror(errno));
  69. return;
  70. }
  71. if ( ( qh = nfq_create_queue(h, conf->queue, &dp_callback, conf) ) == NULL ) {
  72. fprintf(stderr, "error during nfq_create_queue() %s\n", strerror(errno));
  73. return;
  74. }
  75. if ( nfq_set_mode(qh, NFQNL_COPY_PACKET, 1500) < 0 ) {
  76. fprintf(stderr,"error during nfq_set_mode() %s\n", strerror(errno));
  77. return;
  78. }
  79. if ( nfq_set_queue_flags(qh, NFQA_CFG_F_FAIL_OPEN, NFQA_CFG_F_FAIL_OPEN) < 0 ) {
  80. fprintf(stderr,"error during nfq_set_queue_flags() %s\n", strerror(errno));
  81. return;
  82. }
  83. fd = nfq_fd(h);
  84. while(1) {
  85. static char buf[65536];
  86. int rv;
  87. if ((rv = recv(fd, buf, sizeof(buf), 0)) >= 0) {
  88. nfq_handle_packet(h, buf, rv); /* send packet to callback */
  89. }
  90. }
  91. }
  92. // display usage
  93. void usage(char *prog) {
  94. fprintf(stderr,"Usage: %s <configuration file>\n",prog);
  95. }
  96. // load configuration file
  97. dp_conf *load_config(dp_conf *conf, char *file) {
  98. FILE *fh;
  99. char *line = NULL;
  100. size_t len = 0;
  101. int error = 0;
  102. printf("Loading configuration %s\n",file);
  103. if ( ( fh = fopen(file,"r") ) == NULL ) {
  104. fprintf(stderr,"Failed to open configuration file '%s': %s\n", file, strerror(errno));
  105. return NULL;
  106. }
  107. while (getline(&line, &len, fh) != -1) {
  108. char *name, *value;
  109. name = strtok(line, "=\r\n ");
  110. value = strtok(NULL,"=\r\n ");
  111. if ( name == NULL || value == NULL || name[0] == '#' )
  112. continue;
  113. if ( strcmp(name,"max_pkt_per_interval")==0 )
  114. conf->pktint = atoi(value);
  115. else if ( strcmp(name,"interval")==0 )
  116. conf->interval = atoi(value);
  117. else if ( strcmp(name, "debug")==0 )
  118. conf->debug = atoi(value) ? 1 : 0;
  119. else if ( strcmp(name, "blacklist_time")==0 )
  120. conf->bltime = atoi(value);
  121. else if ( strcmp(name, "queue")==0 )
  122. conf->queue = atoi(value);
  123. else if ( strcmp(name, "dryrun")==0 )
  124. conf->dryrun = atoi(value) ? 1 : 0;
  125. else
  126. fprintf(stderr,"unknown directive '%s', ignored\n", name);
  127. free(line);
  128. }
  129. fclose(fh);
  130. if ( conf->pktint < 1 || conf->pktint > 1000 ) {
  131. fprintf(stderr,"max_pkt_per_interval value invalid (min 1, max 1000)\n");
  132. error=1;
  133. }
  134. if ( conf->interval < 5 || conf->interval > 900 ) {
  135. fprintf(stderr,"interval value invalid (min 5, max 900)\n");
  136. error=1;
  137. }
  138. if ( conf->debug < 0 || conf->debug > 1 ) {
  139. fprintf(stderr,"debug value invalid (0 or 1)\n");
  140. error=1;
  141. }
  142. if ( conf->bltime < 10 || conf->bltime > 900 ) {
  143. fprintf(stderr,"blacklist_time value invalid (min 10, max 900)\n");
  144. error=1;
  145. }
  146. if ( conf->queue < 0 ) {
  147. fprintf(stderr,"queue must be a positive integer\n");
  148. error=1;
  149. }
  150. if ( conf->dryrun < 0 || conf->dryrun > 1 ) {
  151. fprintf(stderr, "dryrun value invalid (0 or 1)\n");
  152. error=1;
  153. }
  154. if ( error )
  155. return NULL;
  156. printf("Configuration:\n");
  157. printf("\t%-20s = %4s\n", "dryrun", conf->dryrun ? "Yes" : "No");
  158. printf("\t%-20s = %4s\n", "debug", conf->debug ? "Yes" : "No" );
  159. printf("\t%-20s = %4is\n", "interval", conf->interval);
  160. printf("\t%-20s = %4i\n", "max_pkt_per_interval", conf->pktint);
  161. printf("\t%-20s = %4is\n", "blacklist_time", conf->bltime);
  162. printf("\t%-20s = %4i\n", "queue", conf->queue);
  163. return conf;
  164. }
  165. // decode dhcp packet
  166. int dhcp_check(struct nfq_data *nfa, dp_conf *conf) {
  167. unsigned char *pkt;
  168. int pktlen;
  169. int offset = 0;
  170. unsigned char *remoteid = NULL;
  171. int remoteidlen = 0;
  172. int found = 0;
  173. uint8_t ipver = 0;
  174. uint8_t ihl = 0;
  175. //int i;
  176. int rv = NF_ACCEPT;
  177. pktlen = nfq_get_payload(nfa, &pkt);
  178. if ( conf->debug ) printf("got a packet, len = %i\n", pktlen);
  179. // can we read the IP proto and IP header length ?
  180. if ( pktlen > 0 ) {
  181. ipver = pkt[offset];
  182. ipver >>= 4;
  183. ihl = pkt[offset];
  184. ihl &= 0x0f;
  185. if ( ipver == 4 ) {
  186. // jump to DHCPv4
  187. offset += ( ihl * 4 ) + 8;
  188. dhcpv4_check(conf, pkt, pktlen, offset, &remoteid, &remoteidlen);
  189. }
  190. else if ( ipver == 6 ) {
  191. // jump to DHCPv6
  192. offset += 48 + 8;
  193. dhcpv6_check(conf, pkt, pktlen, offset, &remoteid, &remoteidlen);
  194. }
  195. else {
  196. if ( conf->debug ) printf("not an IPv4 packet\n");
  197. goto end;
  198. }
  199. }
  200. if ( remoteidlen>0 ) {
  201. // count the packet, even when blacklisted.
  202. dp_accounting_add(conf, remoteid, remoteidlen);
  203. // check if already in the blacklist
  204. if ( dp_blacklist_check(conf, remoteid, remoteidlen) == NF_DROP )
  205. rv = NF_DROP;
  206. // check if it must be added to the blacklist
  207. else if ( dp_accounting_check(conf, remoteid, remoteidlen) == NF_DROP ) {
  208. dp_blacklist_add(conf, remoteid, remoteidlen);
  209. rv = NF_DROP;
  210. }
  211. }
  212. end:
  213. dp_hash_cleanup(conf);
  214. return rv;
  215. }
  216. void dhcpv6_check(dp_conf *conf, unsigned char *pkt, int pktlen, int offset, unsigned char *remoteid, int *remoteidlen) {
  217. while(offset<pktlen) {
  218. uint8_t msgtype = (uint8_t)pkt[offset];
  219. switch(msgtype) {
  220. case 11: // RELAY-FORW
  221. case 12: // RELAY-REPL
  222. offset += 2 + 16 + 16; // msg-type, hop-count, link-addr, peer-addr
  223. break;
  224. default: // all other msgtypes
  225. offset += 2; // msg-type, hop-count
  226. }
  227. while(offset+1<pktlen) {
  228. uint8_t code = (uint8_t)pkt[offset];
  229. uint8_t len = (uint8_t)pkt[offset+1];
  230. offset+2;
  231. if ( code == 1 ) { // Client identifier / DUID
  232. remoteid = pkt+offset;
  233. *remoteidlen = len;
  234. break;
  235. }
  236. offset+=len;
  237. }
  238. if ( *remoteidlen>0 )
  239. break;
  240. }
  241. }
  242. void dhcpv4_check(dp_conf *conf, unsigned char *pkt, int pktlen, int offset, unsigned char *remoteid, int *remoteidlen) {
  243. int hwaddrpos = offset + 28; // remember where the hw addr is if we need to fallback to it
  244. int hwlenpos = offset + 2; // remember where the hw addr len is if we need to fallback to it
  245. // jump DHCP header
  246. offset += 28 + 16 + 64 + 128;
  247. // minimum packet size, fixed header + magic cookie (4 octets)
  248. if ( pktlen < offset + 4 ) {
  249. if ( conf->debug ) printf("packet too small\n");
  250. return;
  251. }
  252. // check magic cookie
  253. if ( pkt[offset] != 99 || pkt[offset+1] != 130 || pkt[offset+2] != 83 || pkt[offset+3] != 99 ) {
  254. if ( conf->debug )
  255. printf(
  256. "invalid magic cookie %02x%02x%02x%02x\n",
  257. pkt[offset], pkt[offset+1],
  258. pkt[offset+2], pkt[offset+3]);
  259. return;
  260. }
  261. offset+=4;
  262. // parse TLV options
  263. while(offset<pktlen && !found) {
  264. uint8_t type = pkt[offset];
  265. uint8_t len;
  266. offset++;
  267. // padding of 1 octet
  268. if ( type == 0 ) {
  269. continue;
  270. }
  271. // end of options
  272. if ( type == 255 )
  273. break;
  274. // make sure we can read len
  275. if ( offset>=pktlen )
  276. break;
  277. len = pkt[offset];
  278. offset++;
  279. // can the value be read
  280. if ( offset+len>pktlen )
  281. break;
  282. // option 82 parser
  283. if ( type == 82 ) {
  284. unsigned char *o82 = pkt+offset;
  285. int o82off = 0;
  286. // loop until the end, +2 to ensure we can read type and length
  287. while(o82off+2<len && !found) {
  288. uint8_t otype = o82[o82off];
  289. uint8_t olen = o82[o82off+1];
  290. o82off+=2;
  291. // printf("o82 type=%i len=%i\n", otype, olen);
  292. // remoteid
  293. if ( otype == 2 ) {
  294. // make sure we don't overflow and can read all data
  295. if ( o82off + olen > len ) {
  296. if ( conf->debug) printf("option 82.2 data too long\n");
  297. break;
  298. }
  299. else {
  300. remoteid = o82 + o82off;
  301. *remoteidlen = olen;
  302. }
  303. }
  304. o82off+=olen;
  305. }
  306. }
  307. offset+=len;
  308. }
  309. // if we didn't find opt82.2, we fallback to the hw addr
  310. if ( *remoteidlen == 0 ) {
  311. // nope, we won't overflow
  312. if ( (uint8_t)pkt[hwlenpos] <= 16 ) {
  313. remoteid = pkt+hwaddrpos;
  314. remoteidlen = (uint8_t)pkt[hwlenpos];
  315. }
  316. }
  317. }
  318. // netfilter queue callback
  319. static int dp_callback(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct nfq_data *nfa, void *data) {
  320. struct nfqnl_msg_packet_hdr *ph = nfq_get_msg_packet_hdr(nfa);
  321. dp_conf *conf = (dp_conf*)data;
  322. int id = -1;
  323. int verdict;
  324. if ( ph ) {
  325. id = ntohl (ph->packet_id);
  326. if ( conf->debug ) printf ("received packet with id %d\n", id);
  327. }
  328. verdict = dhcp_check(nfa, conf); /* Treat packet */
  329. // override decision for dryrun
  330. if ( conf->dryrun )
  331. verdict = NF_ACCEPT;
  332. return nfq_set_verdict(qh, id, verdict, 0, NULL); /* Verdict packet */
  333. }
  334. void dp_accounting_add(dp_conf *conf, unsigned char *remoteid, int len) {
  335. //int i;
  336. dp_accounting *ac;
  337. // does the element already exist
  338. HASH_FIND(hh, accountings, remoteid, len, ac);
  339. if ( conf->debug ) printf("AC: add item\n");
  340. // found it, increment the counter
  341. if ( ac ) {
  342. if ( conf->debug ) printf("AC: item found, incrementing\n");
  343. ac->count++;
  344. }
  345. // not found, create a new one
  346. else {
  347. if ( conf->debug ) printf("AC: item not found, creating\n");
  348. ac = malloc(sizeof(dp_accounting));
  349. memcpy(ac->remoteid, remoteid, len);
  350. ac->len = len;
  351. ac->count = 1;
  352. HASH_ADD(hh, accountings, remoteid, len, ac);
  353. }
  354. }
  355. void dp_blacklist_add(dp_conf *conf, unsigned char *remoteid, int len) {
  356. dp_blacklist *bl;
  357. // alrady exists?
  358. HASH_FIND(hh, blacklists, remoteid, len, bl);
  359. if ( conf->debug ) printf("BL: add item\n");
  360. // found an entry, push the expiration further
  361. if ( bl ) {
  362. if ( conf->debug ) printf("BL: item found -> pushing further\n");
  363. bl->expire = time(NULL) + conf->bltime;
  364. }
  365. // not found, create a new one
  366. else {
  367. if ( conf->debug ) printf("BL: item not found, new entry in BL\n");
  368. dp_log(remoteid, len, "blacklisting started");
  369. bl = malloc(sizeof(dp_blacklist));
  370. memcpy(bl->remoteid, remoteid, len);
  371. bl->len = len;
  372. bl->expire = time(NULL) + conf->bltime;
  373. HASH_ADD(hh, blacklists, remoteid, len, bl);
  374. }
  375. }
  376. void dp_hash_cleanup(dp_conf *conf) {
  377. dp_accounting *ac, *actmp;
  378. dp_blacklist *bl, *bltmp;
  379. // is it time to cleanup the list?
  380. // cleanup every conf->interval seconds
  381. if ( dp_accountingtime + conf->interval < time(NULL) ) {
  382. if ( conf->debug ) printf("cleanup interval\n");
  383. dp_accountingtime = time(NULL);
  384. HASH_ITER(hh, accountings, ac, actmp) {
  385. HASH_DEL(accountings, ac);
  386. free(ac);
  387. }
  388. }
  389. // blacklist cleanup check every 1 sec
  390. if ( dp_cleanuptime < time(NULL) ) {
  391. if ( conf->debug ) printf("cleanup BL\n");
  392. dp_cleanuptime = time(NULL);
  393. HASH_ITER(hh, blacklists, bl, bltmp) {
  394. if ( bl->expire < time(NULL) ) {
  395. dp_log(
  396. bl->remoteid, bl->len,
  397. "blacklisting ended");
  398. HASH_DEL(blacklists, bl);
  399. free(bl);
  400. }
  401. }
  402. }
  403. }
  404. int dp_accounting_check(dp_conf *conf, unsigned char *remoteid, int len) {
  405. dp_accounting *ac;
  406. HASH_FIND(hh, accountings, remoteid, len, ac);
  407. if ( conf->debug ) printf("AC Check\n");
  408. if ( ac ) {
  409. if(conf->debug) printf("AC Check: found item %i > %i ?\n", ac->count, conf->pktint);
  410. if ( ac->count > conf->pktint ) {
  411. if(conf->debug) printf("flood detected!\n");
  412. return NF_DROP;
  413. }
  414. }
  415. return NF_ACCEPT;
  416. }
  417. int dp_blacklist_check(dp_conf *conf, unsigned char *remoteid, int len) {
  418. dp_blacklist *bl;
  419. HASH_FIND(hh, blacklists, remoteid, len, bl);
  420. if ( conf->debug ) printf("BL Check\n");
  421. if ( bl ) {
  422. if ( bl->expire > time(NULL) ) {
  423. if ( conf->debug ) printf("blacklisted!\n");
  424. return NF_DROP;
  425. }
  426. }
  427. return NF_ACCEPT;
  428. }