A userspace application that filters DHCP floods to protect a DHCP server. It uses the Netfilter userspace packet queuing API.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

dhcp_protect.c 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. dp_usage(argv[0]);
  38. return EXIT_FAILURE;
  39. }
  40. if ( dp_load_config(&conf, configfile) == NULL )
  41. return EXIT_FAILURE;
  42. openlog("dhcp_protect", LOG_PID, LOG_DAEMON);
  43. dp_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 dp_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 dp_usage(char *prog) {
  94. fprintf(stderr,"Usage: %s <configuration file>\n",prog);
  95. }
  96. // load configuration file
  97. dp_conf *dp_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 dp_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 rv = NF_ACCEPT;
  173. pktlen = nfq_get_payload(nfa, &pkt);
  174. if ( conf->debug ) printf("got a packet, len = %i\n", pktlen);
  175. // can we read the IP proto and IP header length ?
  176. if ( pktlen > 0 ) {
  177. uint8_t ipver;
  178. uint8_t ihl;
  179. ipver = pkt[offset];
  180. ipver >>= 4;
  181. ihl = pkt[offset];
  182. ihl &= 0x0f;
  183. if ( ipver == 4 ) {
  184. // jump to DHCPv4
  185. offset += ( ihl * 4 ) + 8;
  186. dp_dhcpv4_check(conf, pkt, pktlen, offset, &remoteid, &remoteidlen);
  187. }
  188. else if ( ipver == 6 ) {
  189. // jump to DHCPv6
  190. offset += 40 + 8;
  191. dp_dhcpv6_check(conf, pkt, pktlen, offset, &remoteid, &remoteidlen);
  192. }
  193. else {
  194. if ( conf->debug ) printf("not an IPv4 packet\n");
  195. goto end;
  196. }
  197. }
  198. if ( remoteidlen>0 ) {
  199. if ( conf->debug ) {
  200. int i;
  201. printf("remoteid: ");
  202. for(i=0; i<remoteidlen; i++)
  203. printf("%02x", remoteid[i]);
  204. printf("\n");
  205. }
  206. // count the packet, even when blacklisted.
  207. dp_accounting_add(conf, remoteid, remoteidlen);
  208. // check if already in the blacklist
  209. if ( dp_blacklist_check(conf, remoteid, remoteidlen) == NF_DROP )
  210. rv = NF_DROP;
  211. // check if it must be added to the blacklist
  212. else if ( dp_accounting_check(conf, remoteid, remoteidlen) == NF_DROP ) {
  213. dp_blacklist_add(conf, remoteid, remoteidlen);
  214. rv = NF_DROP;
  215. }
  216. }
  217. end:
  218. dp_hash_cleanup(conf);
  219. return rv;
  220. }
  221. void dp_dhcpv6_check(dp_conf *conf, unsigned char *pkt, int pktlen, int offset, unsigned char **remoteid, int *remoteidlen) {
  222. while(offset<pktlen) {
  223. uint8_t msgtype = (uint8_t)pkt[offset];
  224. switch(msgtype) {
  225. case 11: // RELAY-FORW
  226. case 12: // RELAY-REPL
  227. offset += 2 + 16 + 16; // msg-type, hop-count, link-addr, peer-addr
  228. break;
  229. default: // all other msgtypes
  230. offset += 2; // msg-type, hop-count
  231. }
  232. while(offset+1<pktlen) {
  233. uint8_t code = (uint8_t)pkt[offset];
  234. uint8_t len = (uint8_t)pkt[offset+1];
  235. offset+=2;
  236. if ( code == 1 ) { // Client identifier / DUID
  237. // make sure there's enough space
  238. if ( offset + len <= pktlen ) {
  239. *remoteid = pkt+offset;
  240. *remoteidlen = len;
  241. break;
  242. }
  243. }
  244. offset+=len;
  245. }
  246. if ( *remoteidlen>0 )
  247. break;
  248. }
  249. }
  250. void dp_dhcpv4_check(dp_conf *conf, unsigned char *pkt, int pktlen, int offset, unsigned char **remoteid, int *remoteidlen) {
  251. int hwaddrpos = offset + 28; // remember where the hw addr is if we need to fallback to it
  252. int hwlenpos = offset + 2; // remember where the hw addr len is if we need to fallback to it
  253. // jump DHCP header
  254. offset += 28 + 16 + 64 + 128;
  255. // minimum packet size, fixed header + magic cookie (4 octets)
  256. if ( pktlen < offset + 4 ) {
  257. if ( conf->debug ) printf("packet too small\n");
  258. return;
  259. }
  260. // check magic cookie
  261. if ( pkt[offset] != 99 || pkt[offset+1] != 130 || pkt[offset+2] != 83 || pkt[offset+3] != 99 ) {
  262. if ( conf->debug )
  263. printf(
  264. "invalid magic cookie %02x%02x%02x%02x\n",
  265. pkt[offset], pkt[offset+1],
  266. pkt[offset+2], pkt[offset+3]);
  267. return;
  268. }
  269. offset+=4;
  270. // parse TLV options
  271. while(offset<pktlen && remoteidlen==0) {
  272. uint8_t type = pkt[offset];
  273. uint8_t len;
  274. offset++;
  275. // padding of 1 octet
  276. if ( type == 0 ) {
  277. continue;
  278. }
  279. // end of options
  280. if ( type == 255 )
  281. break;
  282. // make sure we can read len
  283. if ( offset>=pktlen )
  284. break;
  285. len = pkt[offset];
  286. offset++;
  287. // can the value be read
  288. if ( offset+len>pktlen )
  289. break;
  290. // option 82 parser
  291. if ( type == 82 ) {
  292. unsigned char *o82 = pkt+offset;
  293. int o82off = 0;
  294. // loop until the end, +2 to ensure we can read type and length
  295. while(o82off+2<len && remoteidlen==0) {
  296. uint8_t otype = o82[o82off];
  297. uint8_t olen = o82[o82off+1];
  298. o82off+=2;
  299. // printf("o82 type=%i len=%i\n", otype, olen);
  300. // remoteid
  301. if ( otype == 2 ) {
  302. // make sure we don't overflow and can read all data
  303. if ( o82off + olen > len ) {
  304. if ( conf->debug) printf("option 82.2 data too long\n");
  305. break;
  306. }
  307. else {
  308. *remoteid = o82 + o82off;
  309. *remoteidlen = olen;
  310. }
  311. }
  312. o82off+=olen;
  313. }
  314. }
  315. offset+=len;
  316. }
  317. // if we didn't find opt82.2, we fallback to the hw addr
  318. if ( *remoteidlen == 0 ) {
  319. // nope, we won't overflow
  320. if ( (uint8_t)pkt[hwlenpos] <= 16 ) {
  321. *remoteid = pkt+hwaddrpos;
  322. *remoteidlen = (uint8_t)pkt[hwlenpos];
  323. }
  324. }
  325. }
  326. // netfilter queue callback
  327. static int dp_callback(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg, struct nfq_data *nfa, void *data) {
  328. struct nfqnl_msg_packet_hdr *ph = nfq_get_msg_packet_hdr(nfa);
  329. dp_conf *conf = (dp_conf*)data;
  330. int id = -1;
  331. int verdict;
  332. if ( ph ) {
  333. id = ntohl (ph->packet_id);
  334. if ( conf->debug ) printf ("received packet with id %d\n", id);
  335. }
  336. verdict = dp_dhcp_check(nfa, conf); /* Treat packet */
  337. // override decision for dryrun
  338. if ( conf->dryrun )
  339. verdict = NF_ACCEPT;
  340. return nfq_set_verdict(qh, id, verdict, 0, NULL); /* Verdict packet */
  341. }
  342. void dp_accounting_add(dp_conf *conf, unsigned char *remoteid, int len) {
  343. //int i;
  344. dp_accounting *ac;
  345. // does the element already exist
  346. HASH_FIND(hh, accountings, remoteid, len, ac);
  347. if ( conf->debug ) printf("AC: add item\n");
  348. // found it, increment the counter
  349. if ( ac ) {
  350. if ( conf->debug ) printf("AC: item found, incrementing\n");
  351. ac->count++;
  352. }
  353. // not found, create a new one
  354. else {
  355. if ( conf->debug ) printf("AC: item not found, creating\n");
  356. ac = malloc(sizeof(dp_accounting));
  357. memcpy(ac->remoteid, remoteid, len);
  358. ac->len = len;
  359. ac->count = 1;
  360. HASH_ADD(hh, accountings, remoteid, len, ac);
  361. }
  362. }
  363. void dp_blacklist_add(dp_conf *conf, unsigned char *remoteid, int len) {
  364. dp_blacklist *bl;
  365. // alrady exists?
  366. HASH_FIND(hh, blacklists, remoteid, len, bl);
  367. if ( conf->debug ) printf("BL: add item\n");
  368. // found an entry, push the expiration further
  369. if ( bl ) {
  370. if ( conf->debug ) printf("BL: item found -> pushing further\n");
  371. bl->expire = time(NULL) + conf->bltime;
  372. }
  373. // not found, create a new one
  374. else {
  375. if ( conf->debug ) printf("BL: item not found, new entry in BL\n");
  376. dp_log(remoteid, len, "blacklisting started");
  377. bl = malloc(sizeof(dp_blacklist));
  378. memcpy(bl->remoteid, remoteid, len);
  379. bl->len = len;
  380. bl->expire = time(NULL) + conf->bltime;
  381. HASH_ADD(hh, blacklists, remoteid, len, bl);
  382. }
  383. }
  384. void dp_hash_cleanup(dp_conf *conf) {
  385. dp_accounting *ac, *actmp;
  386. dp_blacklist *bl, *bltmp;
  387. // is it time to cleanup the list?
  388. // cleanup every conf->interval seconds
  389. if ( dp_accountingtime + conf->interval < time(NULL) ) {
  390. if ( conf->debug ) printf("cleanup interval\n");
  391. dp_accountingtime = time(NULL);
  392. HASH_ITER(hh, accountings, ac, actmp) {
  393. HASH_DEL(accountings, ac);
  394. free(ac);
  395. }
  396. }
  397. // blacklist cleanup check every 1 sec
  398. if ( dp_cleanuptime < time(NULL) ) {
  399. if ( conf->debug ) printf("cleanup BL\n");
  400. dp_cleanuptime = time(NULL);
  401. HASH_ITER(hh, blacklists, bl, bltmp) {
  402. if ( bl->expire < time(NULL) ) {
  403. dp_log(
  404. bl->remoteid, bl->len,
  405. "blacklisting ended");
  406. HASH_DEL(blacklists, bl);
  407. free(bl);
  408. }
  409. }
  410. }
  411. }
  412. int dp_accounting_check(dp_conf *conf, unsigned char *remoteid, int len) {
  413. dp_accounting *ac;
  414. HASH_FIND(hh, accountings, remoteid, len, ac);
  415. if ( conf->debug ) printf("AC Check\n");
  416. if ( ac ) {
  417. if(conf->debug) printf("AC Check: found item %i > %i ?\n", ac->count, conf->pktint);
  418. if ( ac->count > conf->pktint ) {
  419. if(conf->debug) printf("flood detected!\n");
  420. return NF_DROP;
  421. }
  422. }
  423. return NF_ACCEPT;
  424. }
  425. int dp_blacklist_check(dp_conf *conf, unsigned char *remoteid, int len) {
  426. dp_blacklist *bl;
  427. HASH_FIND(hh, blacklists, remoteid, len, bl);
  428. if ( conf->debug ) printf("BL Check\n");
  429. if ( bl ) {
  430. if ( bl->expire > time(NULL) ) {
  431. if ( conf->debug ) printf("blacklisted!\n");
  432. return NF_DROP;
  433. }
  434. }
  435. return NF_ACCEPT;
  436. }