forked from royhills/arp-scan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
arp-scan.c
2452 lines (2366 loc) · 90 KB
/
arp-scan.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The ARP Scanner (arp-scan) is Copyright (C) 2005-2013 Roy Hills,
* NTA Monitor Ltd.
*
* This file is part of arp-scan.
*
* arp-scan is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* arp-scan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with arp-scan. If not, see <http://www.gnu.org/licenses/>.
*
* arp-scan -- The ARP Scanner
*
* Author: Roy Hills
* Date: 13 October 2005
*
* Usage:
* arp-scan [options] [host...]
*
* Description:
*
* arp-scan sends the specified ARP packet to the specified hosts
* and displays any responses received.
*
* The ARP protocol is defined in RFC 826 Ethernet Address Resolution Protocol
*
*/
#include "arp-scan.h"
/* Global variables */
static host_entry *helist = NULL; /* Array of host entries */
static host_entry **helistptr; /* Array of pointers to host entries */
static host_entry **cursor; /* Pointer to current host entry ptr */
static unsigned num_hosts = 0; /* Number of entries in the list */
static unsigned responders = 0; /* Number of hosts which responded */
static unsigned live_count; /* Number of entries awaiting reply */
static int verbose=0; /* Verbose level */
static char filename[MAXLINE]; /* Target list file name */
static int filename_flag=0; /* Set if using target list file */
static int random_flag=0; /* Randomise the list */
static int numeric_flag=0; /* IP addresses only */
static unsigned interval=0; /* Desired interval between packets */
static unsigned bandwidth=DEFAULT_BANDWIDTH; /* Bandwidth in bits per sec */
static unsigned retry = DEFAULT_RETRY; /* Number of retries */
static unsigned timeout = DEFAULT_TIMEOUT; /* Per-host timeout */
static float backoff_factor = DEFAULT_BACKOFF_FACTOR; /* Backoff factor */
static int snaplen = SNAPLEN; /* Pcap snap length */
static char *if_name=NULL; /* Interface name, e.g. "eth0" */
static int quiet_flag=0; /* Don't decode the packet */
static int ignore_dups=0; /* Don't display duplicate packets */
static uint32_t arp_spa; /* Source IP address */
static int arp_spa_flag=0; /* Source IP address specified */
static int arp_spa_is_tpa=0; /* Source IP is dest IP */
static unsigned char arp_sha[ETH_ALEN]; /* Source Ethernet MAC Address */
static int arp_sha_flag=0; /* Source MAC address specified */
static char ouifilename[MAXLINE]; /* OUI filename */
static char iabfilename[MAXLINE]; /* IAB filename */
static char macfilename[MAXLINE]; /* MAC filename */
static char pcap_savefile[MAXLINE]; /* pcap savefile filename */
static int arp_op=DEFAULT_ARP_OP; /* ARP Operation code */
static int arp_hrd=DEFAULT_ARP_HRD; /* ARP hardware type */
static int arp_pro=DEFAULT_ARP_PRO; /* ARP protocol */
static int arp_hln=DEFAULT_ARP_HLN; /* Hardware address length */
static int arp_pln=DEFAULT_ARP_PLN; /* Protocol address length */
static int eth_pro=DEFAULT_ETH_PRO; /* Ethernet protocol type */
static unsigned char arp_tha[6] = {0, 0, 0, 0, 0, 0};
static unsigned char target_mac[6] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
static unsigned char source_mac[6];
static int source_mac_flag = 0;
static unsigned char *padding=NULL;
static size_t padding_len=0;
static struct hash_control *hash_table;
static int localnet_flag=0; /* Scan local network */
static int llc_flag=0; /* Use 802.2 LLC with SNAP */
static int ieee_8021q_vlan=-1; /* Use 802.1Q VLAN tagging if >= 0 */
static int pkt_write_file_flag=0; /* Write packet to file flag */
static int pkt_read_file_flag=0; /* Read packet from file flag */
static char pkt_filename[MAXLINE]; /* Read/Write packet to file filename */
static int write_pkt_to_file=0; /* Write packet to file for debugging */
static int rtt_flag=0; /* Display round-trip time */
static pcap_dumper_t *pcap_dump_handle = NULL; /* pcap savefile handle */
static int plain_flag=0; /* Only show host information */
unsigned int random_seed=0;
int
main(int argc, char *argv[]) {
struct timeval now;
struct timeval diff; /* Difference between two timevals */
int select_timeout; /* Select timeout */
ARP_UINT64 loop_timediff; /* Time since last packet sent in us */
ARP_UINT64 host_timediff; /* Time since last pkt sent to this host (us) */
struct timeval last_packet_time; /* Time last packet was sent */
int req_interval; /* Requested per-packet interval */
int cum_err=0; /* Cumulative timing error */
struct timeval start_time; /* Program start time */
struct timeval end_time; /* Program end time */
struct timeval elapsed_time; /* Elapsed time as timeval */
double elapsed_seconds; /* Elapsed time in seconds */
int reset_cum_err;
int pass_no = 0;
int first_timeout=1;
unsigned i;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program filter;
char *filter_string;
bpf_u_int32 netmask;
bpf_u_int32 localnet;
int datalink;
int get_addr_status = 0;
int pcap_fd; /* Pcap file descriptor */
unsigned char interface_mac[ETH_ALEN];
pcap_t *pcap_handle; /* pcap handle */
/*
* Initialise file names to the empty string.
*/
ouifilename[0] = '\0';
iabfilename[0] = '\0';
macfilename[0] = '\0';
pcap_savefile[0] = '\0';
/*
* Process options.
*/
process_options(argc, argv);
/*
* Get program start time for statistics displayed on completion.
*/
Gettimeofday(&start_time);
/*
* Obtain network interface details unless we're reading
* from a pcap file or writing to a binary file.
*/
if (!pkt_read_file_flag && !pkt_write_file_flag) {
/*
* Determine network interface to use. If the interface was specified
* with the --interface option then use that, otherwise use
* pcap_lookupdev() to pick a suitable interface.
*/
if (!if_name) {
if (!(if_name=pcap_lookupdev(errbuf))) {
err_msg("pcap_lookupdev: %s", errbuf);
}
}
/*
* Obtain the MAC address for the selected interface, and use this
* as default for the source hardware addresses in the frame header
* and ARP packet if the user has not specified their values.
*
* Die with an error if we can't get the MAC address, as this
* indicates that the interface doesn't have a MAC address, so is
* probably not a compatible interface type.
*/
get_hardware_address(if_name, interface_mac);
if (interface_mac[0]==0 && interface_mac[1]==0 &&
interface_mac[2]==0 && interface_mac[3]==0 &&
interface_mac[4]==0 && interface_mac[5]==0) {
err_msg("ERROR: Could not obtain MAC address for interface %s",
if_name);
}
if (source_mac_flag == 0)
memcpy(source_mac, interface_mac, ETH_ALEN);
if (arp_sha_flag == 0)
memcpy(arp_sha, interface_mac, ETH_ALEN);
/*
* If the user has not specified the ARP source address, obtain the
* interface IP address and use that as the default value.
*/
if (arp_spa_flag == 0) {
get_addr_status = get_source_ip(if_name, &arp_spa);
if (get_addr_status == -1) {
warn_msg("WARNING: Could not obtain IP address for interface %s. "
"Using 0.0.0.0 for", if_name);
warn_msg("the source address, which is probably not what you want.");
warn_msg("Either configure %s with an IP address, or manually specify"
" the address", if_name);
warn_msg("with the --arpspa option.");
memset(&arp_spa, '\0', sizeof(arp_spa));
}
}
}
/*
* Open the network device for reading with pcap, or the pcap file if we
* have specified --readpktfromfile. If we are writing packets to a binary
* file, then set pcap_handle to NULL as we don't need to read packets in
* this case.
*/
if (pkt_read_file_flag) {
if (!(pcap_handle = pcap_open_offline(pkt_filename, errbuf)))
err_msg("pcap_open_offline: %s", errbuf);
} else if (!pkt_write_file_flag) {
if (!(pcap_handle = pcap_open_live(if_name, snaplen, PROMISC, TO_MS,
errbuf)))
err_msg("pcap_open_live: %s", errbuf);
} else {
pcap_handle = NULL;
}
/*
* If we are reading data with pcap, get and display the datalink details
*/
if (pcap_handle) {
if ((datalink=pcap_datalink(pcap_handle)) < 0)
err_msg("pcap_datalink: %s", pcap_geterr(pcap_handle));
if (!plain_flag) {
printf("Interface: %s, datalink type: %s (%s)\n",
pkt_read_file_flag ? "savefile" : if_name,
pcap_datalink_val_to_name(datalink),
pcap_datalink_val_to_description(datalink));
}
if (datalink != DLT_EN10MB) {
warn_msg("WARNING: Unsupported datalink type");
}
}
/*
* If we are reading from a network device, then get the associated file
* descriptor and configure it, determine the interface IP network and
* netmask, and install a pcap filter to receive only ARP responses.
* If we are reading from a pcap file, or writing to a binary file, just
* set the file descriptor to -1 to indicate that it is not associated
* with a network device.
*/
if (!pkt_read_file_flag && !pkt_write_file_flag) {
if ((pcap_fd=pcap_get_selectable_fd(pcap_handle)) < 0)
err_msg("pcap_fileno: %s", pcap_geterr(pcap_handle));
if ((pcap_setnonblock(pcap_handle, 1, errbuf)) < 0)
err_msg("pcap_setnonblock: %s", errbuf);
/*
* For the BPF pcap implementation, set the BPF device into immediate mode,
* otherwise it will buffer the responses.
*/
#ifdef ARP_PCAP_BPF
#ifdef BIOCIMMEDIATE
{
unsigned int one = 1;
if (ioctl(pcap_fd, BIOCIMMEDIATE, &one) < 0)
err_sys("ioctl BIOCIMMEDIATE");
}
#endif /* BIOCIMMEDIATE */
#endif /* ARP_PCAP_BPF */
/*
* For the DLPI pcap implementation on Solaris, set the bufmod timeout to
* zero. This has the side-effect of setting the chunk size to zero as
* well, so bufmod will pass all incoming messages on immediately.
*/
#ifdef ARP_PCAP_DLPI
{
struct timeval time_zero = {0, 0};
if (ioctl(pcap_fd, SBIOCSTIME, &time_zero) < 0)
err_sys("ioctl SBIOCSTIME");
}
#endif
if (pcap_lookupnet(if_name, &localnet, &netmask, errbuf) < 0) {
memset(&localnet, '\0', sizeof(localnet));
memset(&netmask, '\0', sizeof(netmask));
if (localnet_flag) {
warn_msg("ERROR: Could not obtain interface IP address and netmask");
err_msg("ERROR: pcap_lookupnet: %s", errbuf);
}
}
/*
* The filter string selects packets addressed to the ARP source address
* that are Ethernet-II ARP packets, 802.3 LLC/SNAP ARP packets,
* 802.1Q tagged ARP packets or 802.1Q tagged 802.3 LLC/SNAP ARP packets.
*/
filter_string=make_message("ether dst %.2x:%.2x:%.2x:%.2x:%.2x:%.2x and "
"(arp or (ether[14:4]=0xaaaa0300 and "
"ether[20:2]=0x0806) or (ether[12:2]=0x8100 "
"and ether[16:2]=0x0806) or "
"(ether[12:2]=0x8100 and "
"ether[18:4]=0xaaaa0300 and "
"ether[24:2]=0x0806))",
arp_sha[0], arp_sha[1],
arp_sha[2], arp_sha[3],
arp_sha[4], arp_sha[5]);
if (verbose > 1)
warn_msg("DEBUG: pcap filter string: \"%s\"", filter_string);
if ((pcap_compile(pcap_handle, &filter, filter_string, OPTIMISE,
netmask)) < 0)
err_msg("pcap_compile: %s", pcap_geterr(pcap_handle));
free(filter_string);
if ((pcap_setfilter(pcap_handle, &filter)) < 0)
err_msg("pcap_setfilter: %s", pcap_geterr(pcap_handle));
} else { /* Reading packets from file */
pcap_fd = -1;
}
/*
* Drop SUID privileges.
*/
if ((setuid(getuid())) < 0) {
err_sys("setuid");
}
/*
* Open pcap savefile is the --pcapsavefile (-W) option was specified
*/
if (*pcap_savefile != '\0') {
if (!(pcap_dump_handle=pcap_dump_open(pcap_handle, pcap_savefile))) {
err_msg("pcap_dump_open: %s", pcap_geterr(pcap_handle));
}
}
/*
* Check that the combination of specified options and arguments is
* valid.
*/
if (interval && bandwidth != DEFAULT_BANDWIDTH)
err_msg("ERROR: You cannot specify both --bandwidth and --interval.");
if (localnet_flag) {
if ((argc - optind) > 0)
err_msg("ERROR: You can not specify targets with the --localnet option");
if (filename_flag)
err_msg("ERROR: You can not specify both --file and --localnet options");
}
/*
* If we're not reading from a file, and --localnet was not specified, then
* we must have some hosts given as command line arguments.
*/
if (!filename_flag && !localnet_flag)
if ((argc - optind) < 1)
usage(EXIT_FAILURE, 0);
/*
* Create MAC/Vendor hash table if quiet if not in effect.
*/
if (!quiet_flag) {
char *fn;
int count;
if ((hash_table = hash_new()) == NULL)
err_sys("hash_new");
fn = get_mac_vendor_filename(ouifilename, DATADIR, OUIFILENAME);
count = add_mac_vendor(hash_table, fn);
if (verbose > 1 && count > 0)
warn_msg("DEBUG: Loaded %d IEEE OUI/Vendor entries from %s.",
count, fn);
free(fn);
fn = get_mac_vendor_filename(iabfilename, DATADIR, IABFILENAME);
count = add_mac_vendor(hash_table, fn);
if (verbose > 1 && count > 0)
warn_msg("DEBUG: Loaded %d IEEE IAB/Vendor entries from %s.",
count, fn);
free(fn);
fn = get_mac_vendor_filename(macfilename, DATADIR, MACFILENAME);
count = add_mac_vendor(hash_table, fn);
if (verbose > 1 && count > 0)
warn_msg("DEBUG: Loaded %d MAC/Vendor entries from %s.",
count, fn);
free(fn);
}
/*
* Populate the list from the specified file if --file was specified, or
* from the interface address and mask if --localnet was specified, or
* otherwise from the remaining command line arguments.
*/
if (filename_flag) { /* Populate list from file */
FILE *fp;
char line[MAXLINE];
char *cp;
if ((strcmp(filename, "-")) == 0) { /* Filename "-" means stdin */
fp = stdin;
} else {
if ((fp = fopen(filename, "r")) == NULL) {
err_sys("fopen");
}
}
while (fgets(line, MAXLINE, fp)) {
for (cp = line; !isspace((unsigned char)*cp) && *cp != '\0'; cp++)
;
*cp = '\0';
add_host_pattern(line, timeout);
}
if (fp != stdin) {
fclose(fp);
}
} else if (localnet_flag) { /* Populate list from i/f addr & mask */
struct in_addr if_network;
struct in_addr if_netmask;
char *c_network;
char *c_netmask;
const char *cp;
char localnet_descr[32];
if_network.s_addr = localnet;
if_netmask.s_addr = netmask;
cp = my_ntoa(if_network);
c_network = make_message("%s", cp);
cp = my_ntoa(if_netmask);
c_netmask = make_message("%s", cp);
snprintf(localnet_descr, 32, "%s:%s", c_network, c_netmask);
free(c_network);
free(c_netmask);
if (verbose) {
warn_msg("Using %s for localnet", localnet_descr);
}
add_host_pattern(localnet_descr, timeout);
} else { /* Populate list from command line arguments */
argv=&argv[optind];
while (*argv) {
add_host_pattern(*argv, timeout);
argv++;
}
}
/*
* Check that we have at least one entry in the list.
*/
if (!num_hosts)
err_msg("ERROR: No hosts to process.");
/*
* If --writepkttofile was specified, open the specified output file.
*/
if (pkt_write_file_flag) {
write_pkt_to_file = open(pkt_filename, O_WRONLY|O_CREAT|O_TRUNC, 0666);
if (write_pkt_to_file == -1)
err_sys("open %s", pkt_filename);
}
/*
* Create and initialise array of pointers to host entries.
*/
helistptr = Malloc(num_hosts * sizeof(host_entry *));
for (i=0; i<num_hosts; i++)
helistptr[i] = &helist[i];
/*
* Randomise the list if required.
* Uses Knuth's shuffle algorithm.
*/
if (random_flag) {
int r;
host_entry *temp;
/*
* Seed random number generator.
* If the random seed has been specified (is non-zero), then use that.
* Otherwise, seed the RNG with an unpredictable value.
*/
if (!random_seed) {
struct timeval tv;
Gettimeofday(&tv);
random_seed = tv.tv_usec ^ getpid(); /* Unpredictable value */
}
init_genrand(random_seed);
for (i=num_hosts-1; i>0; i--) {
r = (int)(genrand_real2() * i); /* 0<=r<i */
temp = helistptr[i];
helistptr[i] = helistptr[r];
helistptr[r] = temp;
}
}
/*
* Set current host pointer (cursor) to start of list, zero
* last packet sent time, and set last receive time to now.
*/
live_count = num_hosts;
cursor = helistptr;
last_packet_time.tv_sec=0;
last_packet_time.tv_usec=0;
/*
* Calculate the required interval to achieve the required outgoing
* bandwidth unless the interval was manually specified with --interval.
*/
if (!interval) {
size_t packet_out_len;
packet_out_len=send_packet(NULL, NULL, NULL); /* Get packet data size */
if (packet_out_len < MINIMUM_FRAME_SIZE)
packet_out_len = MINIMUM_FRAME_SIZE; /* Adjust to minimum size */
packet_out_len += PACKET_OVERHEAD; /* Add layer 2 overhead */
interval = ((ARP_UINT64)packet_out_len * 8 * 1000000) / bandwidth;
if (verbose > 1) {
warn_msg("DEBUG: pkt len=%u bytes, bandwidth=%u bps, interval=%u us",
packet_out_len, bandwidth, interval);
}
}
/*
* Display initial message.
*/
if (!plain_flag) {
printf("Starting %s with %u hosts (http://www.nta-monitor.com/tools/arp-scan/)\n",
PACKAGE_STRING, num_hosts);
}
/*
* Display the lists if verbose setting is 3 or more.
*/
if (verbose > 2)
dump_list();
/*
* Main loop: send packets to all hosts in order until a response
* has been received or the host has exhausted its retry limit.
*
* The loop exits when all hosts have either responded or timed out.
*/
reset_cum_err = 1;
req_interval = interval;
while (live_count) {
/*
* Obtain current time and calculate deltas since last packet and
* last packet to this host.
*/
Gettimeofday(&now);
/*
* If the last packet was sent more than interval us ago, then we can
* potentially send a packet to the current host.
*/
timeval_diff(&now, &last_packet_time, &diff);
loop_timediff = (ARP_UINT64)1000000*diff.tv_sec + diff.tv_usec;
if (loop_timediff >= (unsigned)req_interval) {
/*
* If the last packet to this host was sent more than the current
* timeout for this host us ago, then we can potentially send a packet
* to it.
*/
timeval_diff(&now, &((*cursor)->last_send_time), &diff);
host_timediff = (ARP_UINT64)1000000*diff.tv_sec + diff.tv_usec;
if (host_timediff >= (*cursor)->timeout) {
if (reset_cum_err) {
cum_err = 0;
req_interval = interval;
reset_cum_err = 0;
} else {
cum_err += loop_timediff - interval;
if (req_interval >= cum_err) {
req_interval = req_interval - cum_err;
} else {
req_interval = 0;
}
}
select_timeout = req_interval;
/*
* If we've exceeded our retry limit, then this host has timed out so
* remove it from the list. Otherwise, increase the timeout by the
* backoff factor if this is not the first packet sent to this host
* and send a packet.
*/
if (verbose && (*cursor)->num_sent > pass_no) {
warn_msg("---\tPass %d complete", pass_no+1);
pass_no = (*cursor)->num_sent;
}
if ((*cursor)->num_sent >= retry) {
if (verbose > 1)
warn_msg("---\tRemoving host %s - Timeout",
my_ntoa((*cursor)->addr));
remove_host(cursor); /* Automatically calls advance_cursor() */
if (first_timeout) {
timeval_diff(&now, &((*cursor)->last_send_time), &diff);
host_timediff = (ARP_UINT64)1000000*diff.tv_sec +
diff.tv_usec;
while (host_timediff >= (*cursor)->timeout && live_count) {
if ((*cursor)->live) {
if (verbose > 1)
warn_msg("---\tRemoving host %s - Catch-Up Timeout",
my_ntoa((*cursor)->addr));
remove_host(cursor);
} else {
advance_cursor();
}
timeval_diff(&now, &((*cursor)->last_send_time), &diff);
host_timediff = (ARP_UINT64)1000000*diff.tv_sec +
diff.tv_usec;
}
first_timeout=0;
}
Gettimeofday(&last_packet_time);
} else { /* Retry limit not reached for this host */
if ((*cursor)->num_sent)
(*cursor)->timeout *= backoff_factor;
send_packet(pcap_handle, *cursor, &last_packet_time);
advance_cursor();
}
} else { /* We can't send a packet to this host yet */
/*
* Note that there is no point calling advance_cursor() here because if
* host n is not ready to send, then host n+1 will not be ready either.
*/
select_timeout = (*cursor)->timeout - host_timediff;
reset_cum_err = 1; /* Zero cumulative error */
} /* End If */
} else { /* We can't send a packet yet */
select_timeout = req_interval - loop_timediff;
} /* End If */
recvfrom_wto(pcap_fd, select_timeout, pcap_handle);
} /* End While */
if (!plain_flag) {
printf("\n"); /* Ensure we have a blank line */
}
clean_up(pcap_handle);
if (write_pkt_to_file)
close(write_pkt_to_file);
Gettimeofday(&end_time);
timeval_diff(&end_time, &start_time, &elapsed_time);
elapsed_seconds = (elapsed_time.tv_sec*1000 +
elapsed_time.tv_usec/1000) / 1000.0;
if (!plain_flag) {
printf("Ending %s: %u hosts scanned in %.3f seconds (%.2f hosts/sec). %u responded\n",
PACKAGE_STRING, num_hosts, elapsed_seconds,
num_hosts/elapsed_seconds, responders);
}
return 0;
}
/*
* display_packet -- Check and display received packet
*
* Inputs:
*
* he The host entry corresponding to the received packet
* arpei ARP packet structure
* extra_data Extra data after ARP packet (padding)
* extra_data_len Length of extra data
* framing Framing type (e.g. Ethernet II, LLC)
* vlan_id 802.1Q VLAN identifier, or -1 if not 802.1Q
* frame_hdr The Ethernet frame header
* pcap_header The PCAP header struct
*
* Returns:
*
* None.
*
* This checks the received packet and displays details of what
* was received in the format: <IP-Address><TAB><Details>.
*/
void
display_packet(host_entry *he, arp_ether_ipv4 *arpei,
const unsigned char *extra_data, size_t extra_data_len,
int framing, int vlan_id, ether_hdr *frame_hdr,
const struct pcap_pkthdr *pcap_header) {
char *msg;
char *cp;
char *cp2;
int nonzero=0;
/*
* Set msg to the IP address of the host entry and a tab.
*/
msg = make_message("%s\t", my_ntoa(he->addr));
/*
* Decode ARP packet
*/
cp = msg;
msg = make_message("%s%.2x:%.2x:%.2x:%.2x:%.2x:%.2x", cp,
arpei->ar_sha[0], arpei->ar_sha[1],
arpei->ar_sha[2], arpei->ar_sha[3],
arpei->ar_sha[4], arpei->ar_sha[5]);
free(cp);
/*
* Check that the source address in the Ethernet frame header is the same
* as ar$sha in the ARP packet, and display the Ethernet source address
* if it is different.
*/
if ((memcmp(arpei->ar_sha, frame_hdr->src_addr, ETH_ALEN)) != 0) {
cp = msg;
msg = make_message("%s (%.2x:%.2x:%.2x:%.2x:%.2x:%.2x)", cp,
frame_hdr->src_addr[0], frame_hdr->src_addr[1],
frame_hdr->src_addr[2], frame_hdr->src_addr[3],
frame_hdr->src_addr[4], frame_hdr->src_addr[5]);
free(cp);
}
/*
* Find vendor from hash table and add to message if quiet if not in
* effect.
*
* We start with more specific matches (against larger parts of the
* hardware address), and work towards less specific matches until
* we find a match or exhaust all possible matches.
*/
if (!quiet_flag) {
char oui_string[13]; /* Space for full hw addr plus NULL */
const char *vendor=NULL;
int oui_end=12;
snprintf(oui_string, 13, "%.2X%.2X%.2X%.2X%.2X%.2X",
arpei->ar_sha[0], arpei->ar_sha[1], arpei->ar_sha[2],
arpei->ar_sha[3], arpei->ar_sha[4], arpei->ar_sha[5]);
while (vendor == NULL && oui_end > 1) {
oui_string[oui_end] = '\0'; /* Truncate oui string */
vendor = hash_find(hash_table, oui_string);
oui_end--;
}
cp = msg;
if (vendor)
msg = make_message("%s\t%s", cp, vendor);
else
msg = make_message("%s\t%s", cp, "(Unknown)");
free(cp);
/*
* Check that any data after the ARP packet is zero.
* If it is non-zero, and verbose is selected, then print the padding.
*/
if (extra_data_len > 0) {
unsigned i;
const unsigned char *ucp = extra_data;
for (i=0; i<extra_data_len; i++) {
if (ucp[i] != '\0') {
nonzero=1;
break;
}
}
}
if (nonzero && verbose) {
cp = msg;
cp2 = hexstring(extra_data, extra_data_len);
msg = make_message("%s\tPadding=%s", cp, cp2);
free(cp2);
free(cp);
}
/*
* If the framing type is not Ethernet II, then report the framing type.
*/
if (framing != FRAMING_ETHERNET_II) {
cp = msg;
if (framing == FRAMING_LLC_SNAP) {
msg = make_message("%s (802.2 LLC/SNAP)", cp);
}
free(cp);
}
/*
* If the packet uses 802.1Q VLAN tagging, report the VLAN ID.
*/
if (vlan_id != -1) {
cp = msg;
msg = make_message("%s (802.1Q VLAN=%d)", cp, vlan_id);
free(cp);
}
/*
* If the ARP protocol type is not IP (0x0800), report it.
* This can occur with trailer encapsulation ARP replies.
*/
if (ntohs(arpei->ar_pro) != 0x0800) {
cp = msg;
msg = make_message("%s (ARP Proto=0x%04x)", cp, ntohs(arpei->ar_pro));
free(cp);
}
/*
* If the host entry is not live, then flag this as a duplicate.
*/
if (!he->live) {
cp = msg;
msg = make_message("%s (DUP: %u)", cp, he->num_recv);
free(cp);
}
/*
* If the rtt_flag is set, calculate and report the packet round-trip
* time.
*/
if (rtt_flag) {
struct timeval rtt;
struct timeval pcap_timestamp;
unsigned long rtt_us; /* round-trip time in microseconds */
/*
* We can't pass a pointer to pcap_header->ts directly to timeval_diff
* because it's not guaranteed to have the same size as a struct timeval.
* E.g. OpenBSD 5.1 on amd64.
*/
pcap_timestamp.tv_sec = pcap_header->ts.tv_sec;
pcap_timestamp.tv_usec = pcap_header->ts.tv_usec;
timeval_diff(&pcap_timestamp, &(he->last_send_time), &rtt);
rtt_us = rtt.tv_sec * 1000000 + rtt.tv_usec;
cp=msg;
msg=make_message("%s\tRTT=%lu.%03lu ms", cp, rtt_us/1000, rtt_us%1000);
free(cp);
}
} /* End if (!quiet_flag) */
/*
* Print the message.
*/
printf("%s\n", msg);
free(msg);
}
/*
* send_packet -- Construct and send a packet to the specified host
*
* Inputs:
*
* pcap_handle Pcap handle
* he Host entry to send to. If NULL, then no packet is sent
* last_packet_time Time when last packet was sent
*
* Returns:
*
* The size of the packet that was sent.
*
* This constructs an appropriate packet and sends it to the host
* identified by "he" using the socket "s". It also updates the
* "last_send_time" field for the host entry.
*
* If we are using the undocumented --writepkttofile option, then we
* write the packet to the write_pkt_to_file file descriptor instead of
* transmitting it on the network.
*
* If we are using the undocumented --readpktfromfile option, then we
* don't send anything.
*/
int
send_packet(pcap_t *pcap_handle, host_entry *he,
struct timeval *last_packet_time) {
unsigned char buf[MAX_FRAME];
size_t buflen;
ether_hdr frame_hdr;
arp_ether_ipv4 arpei;
int nsent = 0;
/*
* Construct Ethernet frame header
*/
memcpy(frame_hdr.dest_addr, target_mac, ETH_ALEN);
memcpy(frame_hdr.src_addr, source_mac, ETH_ALEN);
frame_hdr.frame_type = htons(eth_pro);
/*
* Construct the ARP Header.
*/
memset(&arpei, '\0', sizeof(arp_ether_ipv4));
arpei.ar_hrd = htons(arp_hrd);
arpei.ar_pro = htons(arp_pro);
arpei.ar_hln = arp_hln;
arpei.ar_pln = arp_pln;
arpei.ar_op = htons(arp_op);
memcpy(arpei.ar_sha, arp_sha, ETH_ALEN);
memcpy(arpei.ar_tha, arp_tha, ETH_ALEN);
if (arp_spa_is_tpa) {
if (he) {
arpei.ar_sip = he->addr.s_addr;
}
} else {
arpei.ar_sip = arp_spa;
}
if (he)
arpei.ar_tip = he->addr.s_addr;
/*
* Copy the required data into the output buffer "buf" and set "buflen"
* to the number of bytes in this buffer.
*/
marshal_arp_pkt(buf, &frame_hdr, &arpei, &buflen, padding, padding_len);
/*
* If he is NULL, just return with the packet length.
*/
if (he == NULL)
return buflen;
/*
* Check that the host is live. Complain if not.
*/
if (!he->live) {
warn_msg("***\tsend_packet called on non-live host: SHOULDN'T HAPPEN");
return 0;
}
/*
* Update the last send times for this host.
*/
Gettimeofday(last_packet_time);
he->last_send_time.tv_sec = last_packet_time->tv_sec;
he->last_send_time.tv_usec = last_packet_time->tv_usec;
he->num_sent++;
/*
* Send the packet.
*/
if (verbose > 1)
warn_msg("---\tSending packet #%u to host %s tmo %d", he->num_sent,
my_ntoa(he->addr), he->timeout);
if (write_pkt_to_file) {
nsent = write(write_pkt_to_file, buf, buflen);
} else if (!pkt_read_file_flag) {
nsent = pcap_sendpacket(pcap_handle, buf, buflen);
}
if (nsent < 0)
err_sys("ERROR: failed to send packet");
return buflen;
}
/*
* clean_up -- Protocol-specific Clean-Up routine.
*
* Inputs:
*
* None.
*
* Returns:
*
* None.
*
* This is called once after all hosts have been processed. It can be
* used to perform any tidying-up or statistics-displaying required.
* It does not have to do anything.
*/
void
clean_up(pcap_t *pcap_handle) {
struct pcap_stat stats;
if (!plain_flag) {
if (pcap_handle && !pkt_read_file_flag) {
if ((pcap_stats(pcap_handle, &stats)) < 0)
err_msg("pcap_stats: %s", pcap_geterr(pcap_handle));
printf("%u packets received by filter, %u packets dropped by kernel\n",
stats.ps_recv, stats.ps_drop);
}
}
if (pcap_dump_handle) {
pcap_dump_close(pcap_dump_handle);
}
if (pcap_handle) {
pcap_close(pcap_handle);
}
}
/*
* usage -- display usage message and exit
*
* Inputs:
*
* status Status code to pass to exit()
* detailed zero for brief output, non-zero for detailed output
*
* Returns:
*
* None (this function never returns).
*/
void
usage(int status, int detailed) {
fprintf(stderr, "Usage: arp-scan [options] [hosts...]\n");
fprintf(stderr, "\n");
fprintf(stderr, "Target hosts must be specified on the command line unless the --file option is\n");
fprintf(stderr, "given, in which case the targets are read from the specified file instead, or\n");
fprintf(stderr, "the --localnet option is used, in which case the targets are generated from\n");
fprintf(stderr, "the network interface IP address and netmask.\n");
fprintf(stderr, "\n");
fprintf(stderr, "You will need to be root, or arp-scan must be SUID root, in order to run\n");
fprintf(stderr, "arp-scan, because the functions that it uses to read and write packets\n");
fprintf(stderr, "require root privilege.\n");
fprintf(stderr, "\n");
fprintf(stderr, "The target hosts can be specified as IP addresses or hostnames. You can also\n");
fprintf(stderr, "specify the target as IPnetwork/bits (e.g. 192.168.1.0/24) to specify all hosts\n");
fprintf(stderr, "in the given network (network and broadcast addresses included), or\n");
fprintf(stderr, "IPstart-IPend (e.g. 192.168.1.3-192.168.1.27) to specify all hosts in the\n");
fprintf(stderr, "inclusive range, or IPnetwork:NetMask (e.g. 192.168.1.0:255.255.255.0) to\n");
fprintf(stderr, "specify all hosts in the given network and mask.\n");
fprintf(stderr, "\n");
fprintf(stderr, "These different options for specifying target hosts may be used both on the\n");
fprintf(stderr, "command line, and also in the file specified with the --file option.\n");
fprintf(stderr, "\n");
if (detailed) {
fprintf(stderr, "Options:\n");
fprintf(stderr, "\n");
fprintf(stderr, "Note: where an option takes a value, that value is specified as a letter in\n");
fprintf(stderr, "angle brackets. The letter indicates the type of data that is expected:\n");
fprintf(stderr, "\n");
fprintf(stderr, "<s> A character string, e.g. --file=hostlist.txt.\n");
fprintf(stderr, "\n");
fprintf(stderr, "<i> An integer, which can be specified as a decimal number or as a hexadecimal\n");
fprintf(stderr, " number if preceeded with 0x, e.g. --arppro=2048 or --arpro=0x0800.\n");
fprintf(stderr, "\n");
fprintf(stderr, "<f> A floating point decimal number, e.g. --backoff=1.5.\n");
fprintf(stderr, "\n");
fprintf(stderr, "<m> An Ethernet MAC address, which can be specified either in the format\n");
fprintf(stderr, " 01:23:45:67:89:ab, or as 01-23-45-67-89-ab. The alphabetic hex characters\n");
fprintf(stderr, " may be either upper or lower case. E.g. --arpsha=01:23:45:67:89:ab.\n");
fprintf(stderr, "\n");
fprintf(stderr, "<a> An IPv4 address, e.g. --arpspa=10.0.0.1\n");
fprintf(stderr, "\n");
fprintf(stderr, "<h> Binary data specified as a hexadecimal string, which should not\n");
fprintf(stderr, " include a leading 0x. The alphabetic hex characters may be either\n");
fprintf(stderr, " upper or lower case. E.g. --padding=aaaaaaaaaaaa\n");
fprintf(stderr, "\n");
fprintf(stderr, "<x> Something else. See the description of the option for details.\n");
fprintf(stderr, "\n--help or -h\t\tDisplay this usage message and exit.\n");
fprintf(stderr, "\n--file=<s> or -f <s>\tRead hostnames or addresses from the specified file\n");
fprintf(stderr, "\t\t\tinstead of from the command line. One name or IP\n");
fprintf(stderr, "\t\t\taddress per line. Use \"-\" for standard input.\n");
fprintf(stderr, "\n--localnet or -l\tGenerate addresses from network interface configuration.\n");
fprintf(stderr, "\t\t\tUse the network interface IP address and network mask\n");
fprintf(stderr, "\t\t\tto generate the list of target host addresses.\n");
fprintf(stderr, "\t\t\tThe list will include the network and broadcast\n");
fprintf(stderr, "\t\t\taddresses, so an interface address of 10.0.0.1 with\n");
fprintf(stderr, "\t\t\tnetmask 255.255.255.0 would generate 256 target\n");
fprintf(stderr, "\t\t\thosts from 10.0.0.0 to 10.0.0.255 inclusive.\n");
fprintf(stderr, "\t\t\tIf you use this option, you cannot specify the --file\n");
fprintf(stderr, "\t\t\toption or specify any target hosts on the command line.\n");
fprintf(stderr, "\t\t\tThe interface specifications are taken from the\n");
fprintf(stderr, "\t\t\tinterface that arp-scan will use, which can be\n");
fprintf(stderr, "\t\t\tchanged with the --interface option.\n");
fprintf(stderr, "\n--retry=<i> or -r <i>\tSet total number of attempts per host to <i>,\n");
fprintf(stderr, "\t\t\tdefault=%d.\n", DEFAULT_RETRY);
fprintf(stderr, "\n--timeout=<i> or -t <i>\tSet initial per host timeout to <i> ms, default=%d.\n", DEFAULT_TIMEOUT);
fprintf(stderr, "\t\t\tThis timeout is for the first packet sent to each host.\n");
fprintf(stderr, "\t\t\tsubsequent timeouts are multiplied by the backoff\n");
fprintf(stderr, "\t\t\tfactor which is set with --backoff.\n");