A userspace application that filters DHCP floods to protect a DHCP server. It uses the Netfilter userspace packet queuing API.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

dhcp_protect.c 13KB

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