PageRenderTime 76ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

/packages/dhcpdiscover/src/dhcpdiscover.c

https://gitlab.com/libre-mesh/lime-packages
C | 1368 lines | 926 code | 298 blank | 144 comment | 141 complexity | c09d3aec13f8c643bc6e89c808a48adf MD5 | raw file
  1. /******************************************************************************
  2. *
  3. * Original name: CHECK_DHCP.C
  4. * Current name: DHCPDISCOVER.C
  5. *
  6. * License: GPL
  7. * Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org)
  8. * Copyright (c) 2006-2013 OpenWRT.org
  9. *
  10. * License Information:
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 2 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program; if not, write to the Free Software
  24. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  25. *
  26. *****************************************************************************/
  27. const char *COPYRIGHT= " \
  28. *\n \
  29. * License: GPL\n \
  30. * Copyright (c) 2001-2004 Ethan Galstad (nagios@nagios.org)\n \
  31. * Copyright (c) 2006-2013 OpenWRT.org \n \
  32. * ====================================================== \n \
  33. * Mike Gore 25 Aug 2005 \n \
  34. * Modified for standalone operation \n \
  35. * ====================================================== \n \
  36. * Pau Escrich Jun 2013 \n \
  37. * Added -b option and ported to OpenWRT \n \
  38. * ====================================================== \n \
  39. *\n \
  40. ** License Information:\n \
  41. *\n \
  42. * This program is free software; you can redistribute it and/or modify\n \
  43. * it under the terms of the GNU General Public License as published by\n \
  44. * the Free Software Foundation; either version 2 of the License, or\n \
  45. * (at your option) any later version.\n \
  46. *\n \
  47. * This program is distributed in the hope that it will be useful,\n \
  48. * but WITHOUT ANY WARRANTY; without even the implied warranty of\n \
  49. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n \
  50. * GNU General Public License for more details.\n \
  51. *\n \
  52. * You should have received a copy of the GNU General Public License\n \
  53. * along with this program; if not, write to the Free Software\n \
  54. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n \
  55. *\n \
  56. * $Id: dhcpdiscover.c,v 2$\n \
  57. *";
  58. const char *progname = "dhcpdiscover";
  59. const char *revision = "$Revision: 2$";
  60. const char *copyright = "2006-2013";
  61. const char *email = "p4u@dabax.net";
  62. #include <stdio.h>
  63. #include <stdlib.h>
  64. #include <locale.h>
  65. #include <string.h>
  66. #include <errno.h>
  67. #include <unistd.h>
  68. #include <sys/time.h>
  69. #include <sys/ioctl.h>
  70. #include <fcntl.h>
  71. #include <getopt.h>
  72. #include <sys/socket.h>
  73. #include <sys/types.h>
  74. #include <netdb.h>
  75. #include <netinet/in.h>
  76. #include <net/if.h>
  77. #include <arpa/inet.h>
  78. #if defined( __linux__ )
  79. #include <linux/if_ether.h>
  80. #include <features.h>
  81. #elif defined (__bsd__)
  82. #include <netinet/if_ether.h>
  83. #include <sys/sysctl.h>
  84. #include <net/if_dl.h>
  85. #elif defined(__sun__) || defined(__solaris__) || defined(__hpux__)
  86. #define INSAP 22
  87. #define OUTSAP 24
  88. #include <signal.h>
  89. #include <ctype.h>
  90. #include <sys/stropts.h>
  91. #include <sys/poll.h>
  92. #include <sys/dlpi.h>
  93. #define bcopy(source, destination, length) memcpy(destination, source, length)
  94. #define AREA_SZ 5000 /* buffer length in bytes */
  95. static u_long ctl_area[AREA_SZ];
  96. static u_long dat_area[AREA_SZ];
  97. static struct strbuf ctl = {AREA_SZ, 0, (char *)ctl_area};
  98. static struct strbuf dat = {AREA_SZ, 0, (char *)dat_area};
  99. #define GOT_CTRL 1
  100. #define GOT_DATA 2
  101. #define GOT_BOTH 3
  102. #define GOT_INTR 4
  103. #define GOT_ERR 128
  104. #define u_int8_t uint8_t
  105. #define u_int16_t uint16_t
  106. #define u_int32_t uint32_t
  107. static int get_msg(int);
  108. static int check_ctrl(int);
  109. static int put_ctrl(int, int, int);
  110. static int put_both(int, int, int, int);
  111. static int dl_open(const char *, int, int *);
  112. static int dl_bind(int, int, u_char *);
  113. long mac_addr_dlpi( const char *, int, u_char *);
  114. #endif
  115. #define HAVE_GETOPT_H
  116. #define usage printf
  117. /**** Common definitions ****/
  118. #define STATE_OK 0
  119. #define STATE_WARNING 1
  120. #define STATE_CRITICAL 2
  121. #define STATE_UNKNOWN -1
  122. #define OK 0
  123. #define ERROR -1
  124. #define FALSE 0
  125. #define TRUE 1
  126. /**** DHCP definitions ****/
  127. #define MAX_DHCP_CHADDR_LENGTH 16
  128. #define MAX_DHCP_SNAME_LENGTH 64
  129. #define MAX_DHCP_FILE_LENGTH 128
  130. #define MAX_DHCP_OPTIONS_LENGTH 312
  131. typedef struct dhcp_packet_struct{
  132. u_int8_t op; /* packet type */
  133. u_int8_t htype; /* type of hardware address for this machine (Ethernet, etc) */
  134. u_int8_t hlen; /* length of hardware address (of this machine) */
  135. u_int8_t hops; /* hops */
  136. u_int32_t xid; /* random transaction id number - chosen by this machine */
  137. u_int16_t secs; /* seconds used in timing */
  138. u_int16_t flags; /* flags */
  139. struct in_addr ciaddr; /* IP address of this machine (if we already have one) */
  140. struct in_addr yiaddr; /* IP address of this machine (offered by the DHCP server) */
  141. struct in_addr siaddr; /* IP address of DHCP server */
  142. struct in_addr giaddr; /* IP address of DHCP relay */
  143. unsigned char chaddr [MAX_DHCP_CHADDR_LENGTH]; /* hardware address of this machine */
  144. char sname [MAX_DHCP_SNAME_LENGTH]; /* name of DHCP server */
  145. char file [MAX_DHCP_FILE_LENGTH]; /* boot file name (used for diskless booting?) */
  146. char options[MAX_DHCP_OPTIONS_LENGTH]; /* options */
  147. }dhcp_packet;
  148. typedef struct dhcp_offer_struct{
  149. struct in_addr server_address; /* address of DHCP server that sent this offer */
  150. struct in_addr offered_address; /* the IP address that was offered to us */
  151. u_int32_t lease_time; /* lease time in seconds */
  152. u_int32_t renewal_time; /* renewal time in seconds */
  153. u_int32_t rebinding_time; /* rebinding time in seconds */
  154. struct dhcp_offer_struct *next;
  155. }dhcp_offer;
  156. typedef struct requested_server_struct{
  157. struct in_addr server_address;
  158. struct requested_server_struct *next;
  159. }requested_server;
  160. #define BOOTREQUEST 1
  161. #define BOOTREPLY 2
  162. #define DHCPDISCOVER 1
  163. #define DHCPOFFER 2
  164. #define DHCPREQUEST 3
  165. #define DHCPDECLINE 4
  166. #define DHCPACK 5
  167. #define DHCPNACK 6
  168. #define DHCPRELEASE 7
  169. #define DHCP_OPTION_MESSAGE_TYPE 53
  170. #define DHCP_OPTION_HOST_NAME 12
  171. #define DHCP_OPTION_BROADCAST_ADDRESS 28
  172. #define DHCP_OPTION_REQUESTED_ADDRESS 50
  173. #define DHCP_OPTION_LEASE_TIME 51
  174. #define DHCP_OPTION_RENEWAL_TIME 58
  175. #define DHCP_OPTION_REBINDING_TIME 59
  176. #define DHCP_INFINITE_TIME 0xFFFFFFFF
  177. #define DHCP_BROADCAST_FLAG 32768
  178. #define DHCP_SERVER_PORT 67
  179. #define DHCP_CLIENT_PORT 68
  180. #define ETHERNET_HARDWARE_ADDRESS 1 /* used in htype field of dhcp packet */
  181. #define ETHERNET_HARDWARE_ADDRESS_LENGTH 6 /* length of Ethernet hardware addresses */
  182. unsigned char client_hardware_address[MAX_DHCP_CHADDR_LENGTH]="";
  183. unsigned int my_client_mac[MAX_DHCP_CHADDR_LENGTH];
  184. int mymac = 0;
  185. struct in_addr banned_ip;
  186. int banned = 0;
  187. char baddr[16];
  188. char network_interface_name[8]="eth0";
  189. u_int32_t packet_xid=0;
  190. u_int32_t dhcp_lease_time=0;
  191. u_int32_t dhcp_renewal_time=0;
  192. u_int32_t dhcp_rebinding_time=0;
  193. int dhcpoffer_timeout=2;
  194. dhcp_offer *dhcp_offer_list=NULL;
  195. requested_server *requested_server_list=NULL;
  196. int valid_responses=0; /* number of valid DHCPOFFERs we received */
  197. int requested_servers=0;
  198. int requested_responses=0;
  199. int request_specific_address=FALSE;
  200. int received_requested_address=FALSE;
  201. int verbose=0;
  202. struct in_addr requested_address;
  203. void print_revision(const char *progname,const char *revision)
  204. {
  205. printf("Program: %s %s\n",progname,revision);
  206. }
  207. int process_arguments(int, char **);
  208. int call_getopt(int, char **);
  209. int validate_arguments(void);
  210. void print_usage(void);
  211. void print_help(void);
  212. int get_hardware_address(int,char *);
  213. int send_dhcp_discover(int);
  214. int get_dhcp_offer(int);
  215. int get_results(void);
  216. int add_dhcp_offer(struct in_addr,dhcp_packet *);
  217. int free_dhcp_offer_list(void);
  218. int free_requested_server_list(void);
  219. int create_dhcp_socket(void);
  220. int close_dhcp_socket(int);
  221. int send_dhcp_packet(void *,int,int,struct sockaddr_in *);
  222. int receive_dhcp_packet(void *,int,int,int,struct sockaddr_in *);
  223. int main(int argc, char **argv){
  224. int dhcp_socket;
  225. int result;
  226. setlocale (LC_ALL, "");
  227. // bindtextdomain (PACKAGE, LOCALEDIR);
  228. // textdomain (PACKAGE);
  229. if(process_arguments(argc,argv)!=OK){
  230. printf("Could not parse arguments");
  231. }
  232. // Set banned addr in string format in global var baddr
  233. if ( banned ) {
  234. inet_ntop(AF_INET, &(banned_ip), baddr, INET_ADDRSTRLEN);
  235. if(verbose) printf("Banned addr:%s\n",baddr);
  236. }
  237. /* create socket for DHCP communications */
  238. dhcp_socket=create_dhcp_socket();
  239. /* get hardware address of client machine */
  240. get_hardware_address(dhcp_socket,network_interface_name);
  241. /* send DHCPDISCOVER packet */
  242. send_dhcp_discover(dhcp_socket);
  243. /* wait for a DHCPOFFER packet */
  244. get_dhcp_offer(dhcp_socket);
  245. /* close socket we created */
  246. close_dhcp_socket(dhcp_socket);
  247. /* determine state/plugin output to return */
  248. result=get_results();
  249. /* free allocated memory */
  250. free_dhcp_offer_list();
  251. free_requested_server_list();
  252. return result;
  253. }
  254. /* determines hardware address on client machine */
  255. int get_hardware_address(int sock,char *interface_name){
  256. int i;
  257. #if defined(__linux__)
  258. struct ifreq ifr;
  259. strncpy((char *)&ifr.ifr_name,interface_name,sizeof(ifr.ifr_name));
  260. // Added code to try to set local MAC address just to be through
  261. // If this fails the test will still work since
  262. // we do encode the MAC as part of the DHCP frame - tests show it works
  263. if(mymac)
  264. {
  265. int i;
  266. for(i=0;i<MAX_DHCP_CHADDR_LENGTH;++i)
  267. client_hardware_address[i] = my_client_mac[i];
  268. memcpy(&ifr.ifr_hwaddr.sa_data,&client_hardware_address[0],6);
  269. if(ioctl(sock,SIOCSIFHWADDR,&ifr)<0){
  270. printf("Error: Could not set hardware address of interface '%s'\n",interface_name);
  271. // perror("Error");
  272. // exit(STATE_UNKNOWN);
  273. }
  274. }
  275. else
  276. {
  277. /* try and grab hardware address of requested interface */
  278. if(ioctl(sock,SIOCGIFHWADDR,&ifr)<0){
  279. printf("Error: Could not get hardware address of interface '%s'\n",interface_name);
  280. exit(STATE_UNKNOWN);
  281. }
  282. memcpy(&client_hardware_address[0],&ifr.ifr_hwaddr.sa_data,6);
  283. }
  284. #elif defined(__bsd__)
  285. /* King 2004 see ACKNOWLEDGEMENTS */
  286. int mib[6], len;
  287. char *buf;
  288. unsigned char *ptr;
  289. struct if_msghdr *ifm;
  290. struct sockaddr_dl *sdl;
  291. mib[0] = CTL_NET;
  292. mib[1] = AF_ROUTE;
  293. mib[2] = 0;
  294. mib[3] = AF_LINK;
  295. mib[4] = NET_RT_IFLIST;
  296. if ((mib[5] = if_nametoindex(interface_name)) == 0) {
  297. printf("Error: if_nametoindex error - %s.\n", strerror(errno);
  298. exit(STATE_UNKNOWN);
  299. }
  300. if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
  301. printf("Error: Couldn't get hardware address from %s. sysctl 1 error - %s.\n", interface_name, strerror(errno);
  302. exit(STATE_UNKNOWN);
  303. }
  304. if ((buf = malloc(len)) == NULL) {
  305. printf("Error: Couldn't get hardware address from interface %s. malloc error - %s.\n", interface_name, strerror(errno);
  306. exit(4);
  307. }
  308. if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
  309. printf("Error: Couldn't get hardware address from %s. sysctl 2 error - %s.\n", interface_name, strerror(errno);
  310. exit(STATE_UNKNOWN);
  311. }
  312. ifm = (struct if_msghdr *)buf;
  313. sdl = (struct sockaddr_dl *)(ifm + 1);
  314. ptr = (unsigned char *)LLADDR(sdl);
  315. memcpy(&client_hardware_address[0], ptr, 6) ;
  316. /* King 2004 */
  317. #elif defined(__sun__) || defined(__solaris__)
  318. /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
  319. long stat;
  320. char dev[20] = "/dev/";
  321. char *p;
  322. int unit;
  323. for (p = interface_name; *p && isalpha(*p); p++)
  324. /* no-op */ ;
  325. if ( p != '\0' ) {
  326. unit = atoi(p) ;
  327. *p = '\0' ;
  328. strncat(dev, interface_name, 6) ;
  329. } else {
  330. printf("Error: can't find unit number in interface_name (%s) - expecting TypeNumber eg lnc0.\n", interface_name);
  331. exit(STATE_UNKNOWN);
  332. }
  333. stat = mac_addr_dlpi(dev, unit, client_hardware_address);
  334. if (stat != 0) {
  335. printf("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n", dev, unit);
  336. exit(STATE_UNKNOWN);
  337. }
  338. #elif defined(__hpux__)
  339. long stat;
  340. char dev[20] = "/dev/dlpi" ;
  341. int unit = 0;
  342. stat = mac_addr_dlpi(dev, unit, client_hardware_address);
  343. if (stat != 0) {
  344. printf("Error: can't read MAC address from DLPI streams interface for device %s unit %d.\n", dev, unit);
  345. exit(STATE_UNKNOWN);
  346. }
  347. /* Kompf 2000-2003 */
  348. #else
  349. printf("Error: can't get MAC address for this architecture.\n");
  350. exit(STATE_UNKNOWN);
  351. #endif
  352. if (verbose) {
  353. printf("Hardware address: ");
  354. for (i=0; i<6; ++i)
  355. printf("%2.2x", client_hardware_address[i]);
  356. printf( "\n");
  357. }
  358. return OK;
  359. }
  360. /* sends a DHCPDISCOVER broadcast message in an attempt to find DHCP servers */
  361. int send_dhcp_discover(int sock){
  362. dhcp_packet discover_packet;
  363. struct sockaddr_in sockaddr_broadcast;
  364. /* clear the packet data structure */
  365. bzero(&discover_packet,sizeof(discover_packet));
  366. /* boot request flag (backward compatible with BOOTP servers) */
  367. discover_packet.op=BOOTREQUEST;
  368. /* hardware address type */
  369. discover_packet.htype=ETHERNET_HARDWARE_ADDRESS;
  370. /* length of our hardware address */
  371. discover_packet.hlen=ETHERNET_HARDWARE_ADDRESS_LENGTH;
  372. discover_packet.hops=0;
  373. /* transaction id is supposed to be random */
  374. srand(time(NULL));
  375. packet_xid=random();
  376. discover_packet.xid=htonl(packet_xid);
  377. /**** WHAT THE HECK IS UP WITH THIS?!? IF I DON'T MAKE THIS CALL, ONLY ONE SERVER RESPONSE IS PROCESSED!!!! ****/
  378. /* downright bizzarre... */
  379. ntohl(discover_packet.xid);
  380. /*discover_packet.secs=htons(65535);*/
  381. discover_packet.secs=0xFF;
  382. /* tell server it should broadcast its response */
  383. discover_packet.flags=htons(DHCP_BROADCAST_FLAG);
  384. /* our hardware address */
  385. memcpy(discover_packet.chaddr,client_hardware_address,ETHERNET_HARDWARE_ADDRESS_LENGTH);
  386. /* first four bytes of options field is magic cookie (as per RFC 2132) */
  387. discover_packet.options[0]='\x63';
  388. discover_packet.options[1]='\x82';
  389. discover_packet.options[2]='\x53';
  390. discover_packet.options[3]='\x63';
  391. /* DHCP message type is embedded in options field */
  392. discover_packet.options[4]=DHCP_OPTION_MESSAGE_TYPE; /* DHCP message type option identifier */
  393. discover_packet.options[5]='\x01'; /* DHCP message option length in bytes */
  394. discover_packet.options[6]=DHCPDISCOVER;
  395. /* the IP address we're requesting */
  396. if(request_specific_address==TRUE){
  397. discover_packet.options[7]=DHCP_OPTION_REQUESTED_ADDRESS;
  398. discover_packet.options[8]='\x04';
  399. memcpy(&discover_packet.options[9],&requested_address,sizeof(requested_address));
  400. }
  401. /* send the DHCPDISCOVER packet to broadcast address */
  402. sockaddr_broadcast.sin_family=AF_INET;
  403. sockaddr_broadcast.sin_port=htons(DHCP_SERVER_PORT);
  404. sockaddr_broadcast.sin_addr.s_addr=INADDR_BROADCAST;
  405. bzero(&sockaddr_broadcast.sin_zero,sizeof(sockaddr_broadcast.sin_zero));
  406. if (verbose) {
  407. printf("DHCPDISCOVER to %s port %d\n",inet_ntoa(sockaddr_broadcast.sin_addr),ntohs(sockaddr_broadcast.sin_port));
  408. printf("DHCPDISCOVER XID: %lu (0x%X)\n",(unsigned long) ntohl(discover_packet.xid),ntohl(discover_packet.xid));
  409. printf("DHCDISCOVER ciaddr: %s\n",inet_ntoa(discover_packet.ciaddr));
  410. printf("DHCDISCOVER yiaddr: %s\n",inet_ntoa(discover_packet.yiaddr));
  411. printf("DHCDISCOVER siaddr: %s\n",inet_ntoa(discover_packet.siaddr));
  412. printf("DHCDISCOVER giaddr: %s\n",inet_ntoa(discover_packet.giaddr));
  413. }
  414. /* send the DHCPDISCOVER packet out */
  415. send_dhcp_packet(&discover_packet,sizeof(discover_packet),sock,&sockaddr_broadcast);
  416. if (verbose)
  417. printf("\n\n");
  418. return OK;
  419. }
  420. /* waits for a DHCPOFFER message from one or more DHCP servers */
  421. int get_dhcp_offer(int sock){
  422. dhcp_packet offer_packet;
  423. struct sockaddr_in source;
  424. int result=OK;
  425. int timeout=1;
  426. int responses=0;
  427. int x;
  428. time_t start_time;
  429. time_t current_time;
  430. time(&start_time);
  431. /* receive as many responses as we can */
  432. for(responses=0,valid_responses=0;;){
  433. time(&current_time);
  434. if((current_time-start_time)>=dhcpoffer_timeout)
  435. break;
  436. if (verbose)
  437. printf("\n\n");
  438. bzero(&source,sizeof(source));
  439. bzero(&offer_packet,sizeof(offer_packet));
  440. result=OK;
  441. result=receive_dhcp_packet(&offer_packet,sizeof(offer_packet),sock,dhcpoffer_timeout,&source);
  442. // checks if the source address is the banned one
  443. char saddr[16];
  444. inet_ntop(AF_INET, &(source.sin_addr), saddr, INET_ADDRSTRLEN);
  445. if (banned && strcmp(saddr,baddr) == 0) {
  446. printf("DHCP offer comming from the banned addr %s, ignoring it\n",baddr);
  447. result = 1;
  448. }
  449. if(result!=OK){
  450. if (verbose)
  451. printf("Result=ERROR\n");
  452. continue;
  453. }
  454. else{
  455. if (verbose)
  456. printf("Result=OK\n");
  457. responses++;
  458. }
  459. if (verbose) {
  460. printf("DHCPOFFER from IP address %s\n",inet_ntoa(source.sin_addr));
  461. printf("DHCPOFFER XID: %lu (0x%X)\n",(unsigned long) ntohl(offer_packet.xid),ntohl(offer_packet.xid));
  462. }
  463. /* check packet xid to see if its the same as the one we used in the discover packet */
  464. if(ntohl(offer_packet.xid)!=packet_xid){
  465. if (verbose)
  466. printf("DHCPOFFER XID (%lu) did not match DHCPDISCOVER XID (%lu) - ignoring packet\n",(unsigned long) ntohl(offer_packet.xid),(unsigned long) packet_xid);
  467. continue;
  468. }
  469. /* check hardware address */
  470. result=OK;
  471. if (verbose)
  472. printf("DHCPOFFER chaddr: ");
  473. for(x=0;x<ETHERNET_HARDWARE_ADDRESS_LENGTH;x++){
  474. if (verbose)
  475. printf("%02X",(unsigned char)offer_packet.chaddr[x]);
  476. if(offer_packet.chaddr[x]!=client_hardware_address[x])
  477. result=ERROR;
  478. }
  479. if (verbose)
  480. printf("\n");
  481. if(result==ERROR){
  482. if (verbose)
  483. printf("DHCPOFFER hardware address did not match our own - ignoring packet\n");
  484. continue;
  485. }
  486. if (verbose) {
  487. printf("DHCPOFFER ciaddr: %s\n",inet_ntoa(offer_packet.ciaddr));
  488. printf("DHCPOFFER yiaddr: %s\n",inet_ntoa(offer_packet.yiaddr));
  489. printf("DHCPOFFER siaddr: %s\n",inet_ntoa(offer_packet.siaddr));
  490. printf("DHCPOFFER giaddr: %s\n",inet_ntoa(offer_packet.giaddr));
  491. }
  492. add_dhcp_offer(source.sin_addr,&offer_packet);
  493. valid_responses++;
  494. }
  495. if (verbose) {
  496. printf("Total responses seen on the wire: %d\n",responses);
  497. printf("Valid responses for this machine: %d\n",valid_responses);
  498. }
  499. return OK;
  500. }
  501. /* sends a DHCP packet */
  502. int send_dhcp_packet(void *buffer, int buffer_size, int sock, struct sockaddr_in *dest){
  503. struct sockaddr_in myname;
  504. int result;
  505. result=sendto(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)dest,sizeof(*dest));
  506. if (verbose)
  507. printf("send_dhcp_packet result: %d\n",result);
  508. if(result<0)
  509. return ERROR;
  510. return OK;
  511. }
  512. /* receives a DHCP packet */
  513. int receive_dhcp_packet(void *buffer, int buffer_size, int sock, int timeout, struct sockaddr_in *address){
  514. struct timeval tv;
  515. fd_set readfds;
  516. int recv_result;
  517. unsigned long srcmac;
  518. socklen_t address_size;
  519. struct sockaddr_in source_address;
  520. /* wait for data to arrive (up time timeout) */
  521. tv.tv_sec=timeout;
  522. tv.tv_usec=0;
  523. FD_ZERO(&readfds);
  524. FD_SET(sock,&readfds);
  525. select(sock+1,&readfds,NULL,NULL,&tv);
  526. /* make sure some data has arrived */
  527. if(!FD_ISSET(sock,&readfds)){
  528. if (verbose)
  529. printf("No (more) data received\n");
  530. return ERROR;
  531. }
  532. else{
  533. /* why do we need to peek first? i don't know, its a hack. without it, the source address of the first packet received was
  534. not being interpreted correctly. sigh... */
  535. bzero(&source_address,sizeof(source_address));
  536. address_size=sizeof(source_address);
  537. recv_result=recvfrom(sock,(char *)buffer,buffer_size,MSG_PEEK,(struct sockaddr *)&source_address,&address_size);
  538. if (verbose)
  539. printf("recv_result_1: %d\n",recv_result);
  540. recv_result=recvfrom(sock,(char *)buffer,buffer_size,0,(struct sockaddr *)&source_address,&address_size);
  541. if (verbose)
  542. printf("recv_result_2: %d\n",recv_result);
  543. if(recv_result==-1){
  544. if (verbose) {
  545. printf("recvfrom() failed, ");
  546. printf("errno: (%d) -> %s\n",errno,strerror(errno));
  547. }
  548. return ERROR;
  549. }
  550. else{
  551. if (verbose) {
  552. printf("receive_dhcp_packet() result: %d\n",recv_result);
  553. printf("receive_dhcp_packet() source: %s\n",inet_ntoa(source_address.sin_addr));
  554. }
  555. memcpy(address,&source_address,sizeof(source_address));
  556. return OK;
  557. }
  558. }
  559. return OK;
  560. }
  561. /* creates a socket for DHCP communication */
  562. int create_dhcp_socket(void){
  563. struct sockaddr_in myname;
  564. struct ifreq interface;
  565. int sock;
  566. int flag=1;
  567. /* Set up the address we're going to bind to. */
  568. bzero(&myname,sizeof(myname));
  569. myname.sin_family=AF_INET;
  570. myname.sin_port=htons(DHCP_CLIENT_PORT);
  571. myname.sin_addr.s_addr=INADDR_ANY; /* listen on any address */
  572. bzero(&myname.sin_zero,sizeof(myname.sin_zero));
  573. /* create a socket for DHCP communications */
  574. sock=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);
  575. if(sock<0){
  576. printf("Error: Could not create socket!\n");
  577. exit(STATE_UNKNOWN);
  578. }
  579. if (verbose)
  580. printf("DHCP socket: %d\n",sock);
  581. /* set the reuse address flag so we don't get errors when restarting */
  582. flag=1;
  583. if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,(char *)&flag,sizeof(flag))<0){
  584. printf("Error: Could not set reuse address option on DHCP socket!\n");
  585. exit(STATE_UNKNOWN);
  586. }
  587. /* set the broadcast option - we need this to listen to DHCP broadcast messages */
  588. if(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,(char *)&flag,sizeof flag)<0){
  589. printf("Error: Could not set broadcast option on DHCP socket!\n");
  590. exit(STATE_UNKNOWN);
  591. }
  592. /* bind socket to interface */
  593. #if defined(__linux__)
  594. strncpy(interface.ifr_ifrn.ifrn_name,network_interface_name,IFNAMSIZ);
  595. if(setsockopt(sock,SOL_SOCKET,SO_BINDTODEVICE,(char *)&interface,sizeof(interface))<0){
  596. printf("Error: Could not bind socket to interface %s. Check your privileges...\n",network_interface_name);
  597. exit(STATE_UNKNOWN);
  598. }
  599. #else
  600. strncpy(interface.ifr_name,network_interface_name,IFNAMSIZ);
  601. #endif
  602. /* bind the socket */
  603. if(bind(sock,(struct sockaddr *)&myname,sizeof(myname))<0){
  604. printf("Error: Could not bind to DHCP socket (port %d)! Check your privileges...\n",DHCP_CLIENT_PORT);
  605. exit(STATE_UNKNOWN);
  606. }
  607. return sock;
  608. }
  609. /* closes DHCP socket */
  610. int close_dhcp_socket(int sock){
  611. close(sock);
  612. return OK;
  613. }
  614. /* adds a requested server address to list in memory */
  615. int add_requested_server(struct in_addr server_address){
  616. requested_server *new_server;
  617. new_server=(requested_server *)malloc(sizeof(requested_server));
  618. if(new_server==NULL)
  619. return ERROR;
  620. new_server->server_address=server_address;
  621. new_server->next=requested_server_list;
  622. requested_server_list=new_server;
  623. requested_servers++;
  624. if (verbose)
  625. printf("Requested server address: %s\n",inet_ntoa(new_server->server_address));
  626. return OK;
  627. }
  628. /* adds a DHCP OFFER to list in memory */
  629. int add_dhcp_offer(struct in_addr source,dhcp_packet *offer_packet){
  630. dhcp_offer *new_offer;
  631. int x;
  632. int y;
  633. unsigned option_type;
  634. unsigned option_length;
  635. if(offer_packet==NULL)
  636. return ERROR;
  637. /* process all DHCP options present in the packet */
  638. for(x=4;x<MAX_DHCP_OPTIONS_LENGTH;){
  639. /* end of options (0 is really just a pad, but bail out anyway) */
  640. if((int)offer_packet->options[x]==-1 || (int)offer_packet->options[x]==0)
  641. break;
  642. /* get option type */
  643. option_type=offer_packet->options[x++];
  644. /* get option length */
  645. option_length=offer_packet->options[x++];
  646. if (verbose)
  647. printf("Option: %d (0x%02X)\n",option_type,option_length);
  648. /* get option data */
  649. if(option_type==DHCP_OPTION_LEASE_TIME) {
  650. memcpy(&dhcp_lease_time, &offer_packet->options[x],
  651. sizeof(dhcp_lease_time));
  652. dhcp_lease_time = ntohl(dhcp_lease_time);
  653. }
  654. if(option_type==DHCP_OPTION_RENEWAL_TIME) {
  655. memcpy(&dhcp_renewal_time, &offer_packet->options[x],
  656. sizeof(dhcp_renewal_time));
  657. dhcp_renewal_time = ntohl(dhcp_renewal_time);
  658. }
  659. if(option_type==DHCP_OPTION_REBINDING_TIME) {
  660. memcpy(&dhcp_rebinding_time, &offer_packet->options[x],
  661. sizeof(dhcp_rebinding_time));
  662. dhcp_rebinding_time = ntohl(dhcp_rebinding_time);
  663. }
  664. /* skip option data we're ignoring */
  665. else
  666. for(y=0;y<option_length;y++,x++);
  667. }
  668. if (verbose) {
  669. if(dhcp_lease_time==DHCP_INFINITE_TIME)
  670. printf("Lease Time: Infinite\n");
  671. else
  672. printf("Lease Time: %lu seconds\n",(unsigned long)dhcp_lease_time);
  673. if(dhcp_renewal_time==DHCP_INFINITE_TIME)
  674. printf("Renewal Time: Infinite\n");
  675. else
  676. printf("Renewal Time: %lu seconds\n",(unsigned long)dhcp_renewal_time);
  677. if(dhcp_rebinding_time==DHCP_INFINITE_TIME)
  678. printf("Rebinding Time: Infinite\n");
  679. printf("Rebinding Time: %lu seconds\n",(unsigned long)dhcp_rebinding_time);
  680. }
  681. new_offer=(dhcp_offer *)malloc(sizeof(dhcp_offer));
  682. if(new_offer==NULL)
  683. return ERROR;
  684. new_offer->server_address=source;
  685. new_offer->offered_address=offer_packet->yiaddr;
  686. new_offer->lease_time=dhcp_lease_time;
  687. new_offer->renewal_time=dhcp_renewal_time;
  688. new_offer->rebinding_time=dhcp_rebinding_time;
  689. if (verbose) {
  690. printf("Added offer from server @ %s",inet_ntoa(new_offer->server_address));
  691. printf(" of IP address %s\n",inet_ntoa(new_offer->offered_address));
  692. }
  693. /* add new offer to head of list */
  694. new_offer->next=dhcp_offer_list;
  695. dhcp_offer_list=new_offer;
  696. return OK;
  697. }
  698. /* frees memory allocated to DHCP OFFER list */
  699. int free_dhcp_offer_list(void){
  700. dhcp_offer *this_offer;
  701. dhcp_offer *next_offer;
  702. for(this_offer=dhcp_offer_list;this_offer!=NULL;this_offer=next_offer){
  703. next_offer=this_offer->next;
  704. free(this_offer);
  705. }
  706. return OK;
  707. }
  708. /* frees memory allocated to requested server list */
  709. int free_requested_server_list(void){
  710. requested_server *this_server;
  711. requested_server *next_server;
  712. for(this_server=requested_server_list;this_server!=NULL;this_server=next_server){
  713. next_server=this_server->next;
  714. free(this_server);
  715. }
  716. return OK;
  717. }
  718. /* gets state and plugin output to return */
  719. int get_results(void){
  720. dhcp_offer *temp_offer;
  721. requested_server *temp_server;
  722. int result;
  723. u_int32_t max_lease_time=0;
  724. received_requested_address=FALSE;
  725. /* checks responses from requested servers */
  726. requested_responses=0;
  727. if(requested_servers>0){
  728. for(temp_server=requested_server_list;temp_server!=NULL;temp_server=temp_server->next){
  729. for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
  730. /* get max lease time we were offered */
  731. if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
  732. max_lease_time=temp_offer->lease_time;
  733. /* see if we got the address we requested */
  734. if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
  735. received_requested_address=TRUE;
  736. /* see if the servers we wanted a response from talked to us or not */
  737. if(!memcmp(&temp_offer->server_address,&temp_server->server_address,sizeof(temp_server->server_address))){
  738. if (verbose) {
  739. printf("DHCP Server Match: Offerer=%s",inet_ntoa(temp_offer->server_address));
  740. printf(" Requested=%s\n",inet_ntoa(temp_server->server_address));
  741. }
  742. requested_responses++;
  743. }
  744. }
  745. }
  746. }
  747. /* else check and see if we got our requested address from any server */
  748. else{
  749. for(temp_offer=dhcp_offer_list;temp_offer!=NULL;temp_offer=temp_offer->next){
  750. /* get max lease time we were offered */
  751. if(temp_offer->lease_time>max_lease_time || temp_offer->lease_time==DHCP_INFINITE_TIME)
  752. max_lease_time=temp_offer->lease_time;
  753. /* see if we got the address we requested */
  754. if(!memcmp(&requested_address,&temp_offer->offered_address,sizeof(requested_address)))
  755. received_requested_address=TRUE;
  756. }
  757. }
  758. result=STATE_OK;
  759. if(valid_responses==0)
  760. result=STATE_CRITICAL;
  761. else if(requested_servers>0 && requested_responses==0)
  762. result=STATE_CRITICAL;
  763. else if(requested_responses<requested_servers)
  764. result=STATE_WARNING;
  765. else if(request_specific_address==TRUE && received_requested_address==FALSE)
  766. result=STATE_WARNING;
  767. printf("DHCP %s: ",(result==STATE_OK)?"ok":"problem");
  768. /* we didn't receive any DHCPOFFERs */
  769. if(dhcp_offer_list==NULL){
  770. printf("No DHCPOFFERs were received.\n");
  771. return result;
  772. }
  773. printf("Received %d DHCPOFFER(s)",valid_responses);
  774. if(requested_servers>0)
  775. printf(", %s%d of %d requested servers responded",((requested_responses<requested_servers) && requested_responses>0)?"only ":"",requested_responses,requested_servers);
  776. if(request_specific_address==TRUE)
  777. printf(", requested address (%s) was %soffered",inet_ntoa(requested_address),(received_requested_address==TRUE)?"":"not ");
  778. printf(", max lease time = ");
  779. if(max_lease_time==DHCP_INFINITE_TIME)
  780. printf("Infinity");
  781. else
  782. printf("%lu sec",(unsigned long)max_lease_time);
  783. printf(".\n");
  784. return result;
  785. }
  786. /* process command-line arguments */
  787. int process_arguments(int argc, char **argv){
  788. int c;
  789. if(argc<1)
  790. return ERROR;
  791. c=0;
  792. while((c+=(call_getopt(argc-c,&argv[c])))<argc){
  793. /*
  794. if(is_option(argv[c]))
  795. continue;
  796. */
  797. }
  798. return validate_arguments();
  799. }
  800. int call_getopt(int argc, char **argv){
  801. int c=0;
  802. int i=0;
  803. struct in_addr ipaddress;
  804. #ifdef HAVE_GETOPT_H
  805. int option_index = 0;
  806. int ret;
  807. static struct option long_options[] =
  808. {
  809. {"serverip", required_argument,0,'s'},
  810. {"requestedip", required_argument,0,'r'},
  811. {"timeout", required_argument,0,'t'},
  812. {"interface", required_argument,0,'i'},
  813. {"mac", required_argument,0,'m'},
  814. {"bannedip", required_argument,0,'b'},
  815. {"verbose", no_argument, 0,'v'},
  816. {"version", no_argument, 0,'V'},
  817. {"help", no_argument, 0,'h'},
  818. {0,0,0,0}
  819. };
  820. #endif
  821. while(1){
  822. #ifdef HAVE_GETOPT_H
  823. c=getopt_long(argc,argv,"+hVvt:s:r:t:i:m:b:",long_options,&option_index);
  824. #else
  825. c=getopt(argc,argv,"+?hVvt:s:r:t:i:m:b:");
  826. #endif
  827. i++;
  828. if(c==-1||c==EOF||c==1)
  829. break;
  830. switch(c){
  831. case 'w':
  832. case 'r':
  833. case 't':
  834. case 'i':
  835. i++;
  836. break;
  837. default:
  838. break;
  839. }
  840. switch(c){
  841. case 'm': /* Our MAC address */
  842. {
  843. ret = sscanf(optarg,"%x:%x:%x:%x:%x:%x",
  844. my_client_mac+0,
  845. my_client_mac+1,
  846. my_client_mac+2,
  847. my_client_mac+3,
  848. my_client_mac+4,
  849. my_client_mac+5);
  850. if(ret != 6) {
  851. usage("Invalid MAC address\n");
  852. break;
  853. }
  854. for(i=0;i<6;++i)
  855. client_hardware_address[i] = my_client_mac[i];
  856. }
  857. mymac = 1;
  858. break;
  859. case 'b': /* Banned IP */
  860. if(inet_aton(optarg,&ipaddress)) {
  861. banned_ip = ipaddress;
  862. banned = 1;
  863. }
  864. else
  865. printf("Banned IP not specified, ignoring -b");
  866. break;
  867. case 's': /* DHCP server address */
  868. if(inet_aton(optarg,&ipaddress))
  869. add_requested_server(ipaddress);
  870. /*
  871. else
  872. usage("Invalid server IP address\n");
  873. */
  874. break;
  875. case 'r': /* address we are requested from DHCP servers */
  876. if(inet_aton(optarg,&ipaddress)){
  877. requested_address=ipaddress;
  878. request_specific_address=TRUE;
  879. }
  880. /*
  881. else
  882. usage("Invalid requested IP address\n");
  883. */
  884. break;
  885. case 't': /* timeout */
  886. /*
  887. if(is_intnonneg(optarg))
  888. */
  889. if(atoi(optarg)>0)
  890. dhcpoffer_timeout=atoi(optarg);
  891. /*
  892. else
  893. usage("Time interval must be a nonnegative integer\n");
  894. */
  895. break;
  896. case 'i': /* interface name */
  897. strncpy(network_interface_name,optarg,sizeof(network_interface_name)-1);
  898. network_interface_name[sizeof(network_interface_name)-1]='\x0';
  899. break;
  900. case 'V': /* version */
  901. print_revision(progname,revision);
  902. exit(STATE_OK);
  903. case 'h': /* help */
  904. print_help();
  905. exit(STATE_OK);
  906. case 'v': /* verbose */
  907. verbose=1;
  908. break;
  909. default: /* help */
  910. printf("Unknown argument", optarg);
  911. break;
  912. }
  913. }
  914. return i;
  915. }
  916. int validate_arguments(void){
  917. return OK;
  918. }
  919. #if defined(__sun__) || defined(__solaris__) || defined(__hpux__)
  920. /* Kompf 2000-2003 see ACKNOWLEDGEMENTS */
  921. /* get a message from a stream; return type of message */
  922. static int get_msg(int fd)
  923. {
  924. int flags = 0;
  925. int res, ret;
  926. ctl_area[0] = 0;
  927. dat_area[0] = 0;
  928. ret = 0;
  929. res = getmsg(fd, &ctl, &dat, &flags);
  930. if(res < 0) {
  931. if(errno == EINTR) {
  932. return(GOT_INTR);
  933. } else {
  934. printf("%s\n", "get_msg FAILED.");
  935. return(GOT_ERR);
  936. }
  937. }
  938. if(ctl.len > 0) {
  939. ret |= GOT_CTRL;
  940. }
  941. if(dat.len > 0) {
  942. ret |= GOT_DATA;
  943. }
  944. return(ret);
  945. }
  946. /* verify that dl_primitive in ctl_area = prim */
  947. static int check_ctrl(int prim)
  948. {
  949. dl_error_ack_t *err_ack = (dl_error_ack_t *)ctl_area;
  950. if(err_ack->dl_primitive != prim) {
  951. printf("Error: DLPI stream API failed to get MAC in check_ctrl: %s.\n", strerror(errno);
  952. exit(STATE_UNKNOWN);
  953. }
  954. return 0;
  955. }
  956. /* put a control message on a stream */
  957. static int put_ctrl(int fd, int len, int pri)
  958. {
  959. ctl.len = len;
  960. if(putmsg(fd, &ctl, 0, pri) < 0) {
  961. printf("Error: DLPI stream API failed to get MAC in put_ctrl/putmsg(): %s.\n", strerror(errno);
  962. exit(STATE_UNKNOWN);
  963. }
  964. return 0;
  965. }
  966. /* put a control + data message on a stream */
  967. static int put_both(int fd, int clen, int dlen, int pri)
  968. {
  969. ctl.len = clen;
  970. dat.len = dlen;
  971. if(putmsg(fd, &ctl, &dat, pri) < 0) {
  972. printf("Error: DLPI stream API failed to get MAC in put_both/putmsg().\n", strerror(errno);
  973. exit(STATE_UNKNOWN);
  974. }
  975. return 0;
  976. }
  977. /* open file descriptor and attach */
  978. static int dl_open(const char *dev, int unit, int *fd)
  979. {
  980. dl_attach_req_t *attach_req = (dl_attach_req_t *)ctl_area;
  981. if((*fd = open(dev, O_RDWR)) == -1) {
  982. printf("Error: DLPI stream API failed to get MAC in dl_attach_req/open(%s..): %s.\n", dev, strerror(errno);
  983. exit(STATE_UNKNOWN);
  984. }
  985. attach_req->dl_primitive = DL_ATTACH_REQ;
  986. attach_req->dl_ppa = unit;
  987. put_ctrl(*fd, sizeof(dl_attach_req_t), 0);
  988. get_msg(*fd);
  989. return check_ctrl(DL_OK_ACK);
  990. }
  991. /* send DL_BIND_REQ */
  992. static int dl_bind(int fd, int sap, u_char *addr)
  993. {
  994. dl_bind_req_t *bind_req = (dl_bind_req_t *)ctl_area;
  995. dl_bind_ack_t *bind_ack = (dl_bind_ack_t *)ctl_area;
  996. bind_req->dl_primitive = DL_BIND_REQ;
  997. bind_req->dl_sap = sap;
  998. bind_req->dl_max_conind = 1;
  999. bind_req->dl_service_mode = DL_CLDLS;
  1000. bind_req->dl_conn_mgmt = 0;
  1001. bind_req->dl_xidtest_flg = 0;
  1002. put_ctrl(fd, sizeof(dl_bind_req_t), 0);
  1003. get_msg(fd);
  1004. if (GOT_ERR == check_ctrl(DL_BIND_ACK)) {
  1005. printf("Error: DLPI stream API failed to get MAC in dl_bind/check_ctrl(): %s.\n", strerror(errno);
  1006. exit(STATE_UNKNOWN);
  1007. }
  1008. bcopy((u_char *)bind_ack + bind_ack->dl_addr_offset, addr,
  1009. bind_ack->dl_addr_length);
  1010. return 0;
  1011. }
  1012. /***********************************************************************
  1013. * interface:
  1014. * function mac_addr_dlpi - get the mac address of the interface with
  1015. * type dev (eg lnc, hme) and unit (0, 1 ..)
  1016. *
  1017. * parameter: addr: an array of six bytes, has to be allocated by the caller
  1018. *
  1019. * return: 0 if OK, -1 if the address could not be determined
  1020. *
  1021. *
  1022. ***********************************************************************/
  1023. long mac_addr_dlpi( const char *dev, int unit, u_char *addr) {
  1024. int fd;
  1025. u_char mac_addr[25];
  1026. if (GOT_ERR != dl_open(dev, unit, &fd)) {
  1027. if (GOT_ERR != dl_bind(fd, INSAP, mac_addr)) {
  1028. bcopy( mac_addr, addr, 6);
  1029. return 0;
  1030. }
  1031. }
  1032. close(fd);
  1033. return -1;
  1034. }
  1035. /* Kompf 2000-2003 */
  1036. #endif
  1037. /* print usage help */
  1038. void print_help(void){
  1039. print_revision(progname,revision);
  1040. printf(COPYRIGHT, copyright, email);
  1041. printf("\n\nThis program checks the existence and more details of a DHCP server\n\n");
  1042. print_usage();
  1043. printf("\
  1044. -s, --serverip=IPADDRESS\n\
  1045. IP address of DHCP server that we must hear from\n\
  1046. -r, --requestedip=IPADDRESS\n\
  1047. IP address that should be offered by at least one DHCP server\n\
  1048. -m, --mac=MACADDRESS\n\
  1049. Client MAC address to use for sending packets\n\
  1050. -b, --bannedip=IPADDRESS\n\
  1051. Server IP address to ignore\n\
  1052. -t, --timeout=INTEGER\n\
  1053. Seconds to wait for DHCPOFFER before timeout occurs\n\
  1054. -i, --interface=STRING\n\
  1055. Interface to to use for listening (i.e. eth0)\n\
  1056. -v, --verbose\n\
  1057. Print extra information (command-line use only)\n\
  1058. -h, --help\n\
  1059. Print detailed help screen\n\
  1060. -V, --version\n\
  1061. Print version information\n\n\
  1062. Example: sudo ./dhcpdiscover -i eth0 -b 192.168.1.1\n\
  1063. ");
  1064. }
  1065. void print_usage(void)
  1066. {
  1067. printf("\
  1068. Usage: %s [-s serverip] [-r requestedip] [-m clientmac ] [-b bannedip] [-t timeout] [-i interface]\n\
  1069. [-v]",progname);
  1070. }