-
Notifications
You must be signed in to change notification settings - Fork 154
/
arp-scan.c
2740 lines (2646 loc) · 96.9 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
/*
* arp-scan is Copyright (C) 2005-2024 Roy Hills
*
* 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 -- Send ARP requests to network hosts and display responses
*
* 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; /* 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 = NULL; /* OUI filename */
static char *macfilename = NULL; /* MAC filename */
static char *pcap_savefile = NULL; /* 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 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 = NULL; /* 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 */
static int resolve_flag = 0; /* Resolve IP addresses to hostnames */
unsigned int random_seed = 0;
static unsigned retry_send = DEFAULT_RETRY_SEND; /* Number of send packet retries */
static unsigned retry_send_interval = DEFAULT_RETRY_SEND_INTERVAL; /* Interval in seconds between send packet retries */
static unsigned int host_limit = 0; /* Exit after n responders if nonzero */
static format_element *format = NULL; /* Output format linked list */
int
main(int argc, char *argv[]) {
struct timeval now;
struct timeval diff; /* Difference between two timevals */
int select_timeout; /* Select timeout */
uint64_t loop_timediff; /* Time since last packet sent in us */
uint64_t 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 ret_status = 0;
int pcap_fd; /* Pcap file descriptor */
unsigned char interface_mac[ETH_ALEN];
pcap_t *pcap_handle; /* pcap handle */
struct in_addr interface_ip_addr;
/*
* Limit process capabilities to the minimum necessary to run this program.
*
* If we have POSIX.1e capability support, this removes all capabilities
* from the effective set and reduces the capabilities in the permitted
* set to the minimum needed.
*
* If we do not have capability support, then drop any SUID root privs
* by setting the effective user id to the real uid.
*/
limit_capabilities();
/*
* Process options.
*/
process_options(argc, argv);
/*
* If we're not reading from a file, and --localnet was not specified, then
* die if no hosts were given as command line arguments.
*/
if (!filename_flag && !localnet_flag)
if ((argc - optind) < 1)
err_msg("ERROR: No target hosts on command line and neither --file or "
"--localnet options given");
/*
* Get program start time for statistics displayed on completion.
*/
Gettimeofday(&start_time);
/*
* 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) { /* Reading packets from pcap file */
if (!(pcap_handle = pcap_open_offline(pkt_filename, errbuf)))
err_msg("pcap_open_offline: %s", errbuf);
} else if (!pkt_write_file_flag) { /* Reading packets from network */
/*
* enable CAP_NET_RAW in the effective set if we have POSIX.1e capability
* support. If we don't have capability support then restore SUID root
* privs by setting the effective user id to the saved euid.
*/
set_capability(ENABLE);
/*
* Determine network interface to use. If the interface was specified
* with the --interface option then use that, otherwise use
* my_lookupdev() to pick a suitable interface.
*
*/
if (!if_name) {
if (!(if_name = my_lookupdev(errbuf))) {
err_msg("my_lookupdev: %s", errbuf);
}
}
if (!(pcap_handle = pcap_create(if_name, errbuf)))
err_msg("pcap_create: %s", errbuf);
if ((pcap_set_snaplen(pcap_handle, snaplen)) < 0)
err_msg("pcap_set_snaplen: %s", pcap_geterr(pcap_handle));
if ((pcap_set_promisc(pcap_handle, PROMISC)) < 0)
err_msg("pcap_set_promisc: %s", pcap_geterr(pcap_handle));
if ((pcap_set_immediate_mode(pcap_handle, 1)) < 0)
err_msg("pcap_set_immediate_mode: %s", pcap_geterr(pcap_handle));
if ((pcap_set_timeout(pcap_handle, TO_MS)) < 0) /* Is this still needed? */
err_msg("pcap_set_timeout: %s", pcap_geterr(pcap_handle));
ret_status = pcap_activate(pcap_handle);
if (ret_status < 0) { /* Error from pcap_activate() */
char *cp;
cp = pcap_geterr(pcap_handle);
if (ret_status == PCAP_ERROR)
err_msg("pcap_activate: %s", cp);
else if ((ret_status == PCAP_ERROR_NO_SUCH_DEVICE ||
ret_status == PCAP_ERROR_PERM_DENIED) && *cp != '\0')
err_msg("pcap_activate: %s: %s\n(%s)", if_name,
pcap_statustostr(ret_status), cp);
else
err_msg("pcap_activate: %s: %s", if_name,
pcap_statustostr(ret_status));
} else if (ret_status > 0) { /* Warning from pcap_activate() */
char *cp;
cp = pcap_geterr(pcap_handle);
if (ret_status == PCAP_WARNING)
warn_msg("pcap_activate: %s", cp);
else if (ret_status == PCAP_WARNING_PROMISC_NOTSUP && *cp != '\0')
warn_msg("pcap_activate: %s: %s\n(%s)", if_name,
pcap_statustostr(ret_status), cp);
else
warn_msg("pcap_activate: %s: %s", if_name,
pcap_statustostr(ret_status));
}
/*
* Obtain the MAC address for the selected interface, and use this
* as the default value for the source hardware addresses in the frame
* header and ARP packet if the user has not specified their values.
*/
get_hardware_address(if_name, interface_mac);
/*
* Disable CAP_NET_RAW in the effective set if we have POSIX.1e capability
* support. If we don't have capability support then drop SUID root
* privs by setting the effective user id to the real uid.
*/
set_capability(DISABLE);
/*
* Permanently remove all capabilities or SUID root privilege as we
* don't need any special privileges after this point.
*
* We disable all capabilities in both the effective and permitted sets
* if we have POSIX.1e capability support, otherwise we permanently drop
* SUID root privs by setting the user ID to the real user ID.
*/
drop_capabilities();
/*
* 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.
*/
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);
/*
* Obtain the interface IP address, and use that as the default value
* if the user has not manually specified the ARP source address.
*
* Give a warning and use 0.0.0.0 if the interface has no IP address.
*/
ret_status = get_source_ip(if_name, &interface_ip_addr);
if (arp_spa_flag == 0) {
if (ret_status == -1) {
warn_msg(
"WARNING: Could not obtain IP address for interface %s. "
"Using 0.0.0.0 for\nthe source address, which may not be "
"what you want. Either configure\n"
"%s with an IP address, or specify the address "
"with the --arpspa option.",if_name, if_name);
}
memcpy(&arp_spa, &(interface_ip_addr.s_addr), sizeof(arp_spa));
}
} else { /* Not reading packets because we are writing to pcap file */
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) {
if (!pkt_read_file_flag) {
printf("Interface: %s, type: %s, "
"MAC: %.2x:%.2x:%.2x:%.2x:%.2x:%.2x, IPv4: %s\n",
if_name, pcap_datalink_val_to_name(datalink),
interface_mac[0], interface_mac[1], interface_mac[2],
interface_mac[3], interface_mac[4], interface_mac[5],
(interface_ip_addr.s_addr==0) ? "(none)" : my_ntoa(interface_ip_addr));
} else {
printf("Interface: pcap file\n");
}
}
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);
if (pcap_lookupnet(if_name, &localnet, &netmask, errbuf) < 0) {
memset(&localnet, '\0', sizeof(localnet));
memset(&netmask, '\0', sizeof(netmask));
if (localnet_flag) {
err_msg("ERROR: Could not obtain interface IP address and "
"netmask: pcap_lookupnet: %s", errbuf);
}
}
/*
* The pcap 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));
pcap_freecode(&filter);
} else { /* Reading packets from file */
pcap_fd = -1;
}
/*
* Open pcap savefile is the --pcapsavefile (-W) option was specified
*/
if (pcap_savefile) {
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");
}
/*
* Create MAC/Vendor hash table if quiet is not in effect.
*/
if (!quiet_flag) {
char *fn;
int count;
if ((hcreate(HASH_TABLE_SIZE)) == 0)
err_sys("hcreate");
fn = get_mac_vendor_filename(ouifilename, PKGDATADIR, OUIFILENAME);
count = add_mac_vendor(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(macfilename, PKGSYSCONFDIR, MACFILENAME);
count = add_mac_vendor(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("Cannot open %s", filename);
}
}
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);
if (!plain_flag) {
printf("Target list from interface: network %s netmask %s\n",
c_network, c_netmask);
}
free(c_network);
free(c_netmask);
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);
}
/*
* If we have the OpenBSD pledge(2) system call, use it to restrict
* system operations from this point.
*/
#ifdef HAVE_PLEDGE
if (pledge("stdio dns bpf", NULL) == -1)
err_sys("pledge");
#endif
/*
* 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 = ((uint64_t)packet_out_len * 8 * 1000000) / bandwidth;
if (verbose > 1) {
warn_msg("DEBUG: pkt len=%zu bytes, bandwidth=%u bps, interval=%u us",
packet_out_len, bandwidth, interval);
}
}
/*
* Display initial message.
*/
if (!plain_flag) {
printf("Starting %s with %u hosts (https://github.com/royhills/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;
* or if the number of responders reaches host_limit when host_limit is
* non zero.
*/
reset_cum_err = 1;
req_interval = interval;
while (live_count && !(host_limit != 0 && responders >= host_limit)) {
/*
* 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 microseconds ago, we
* can potentially send a packet to the current host.
*/
timeval_diff(&now, &last_packet_time, &diff);
loop_timediff = (uint64_t)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 = (uint64_t)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;
req_interval = (req_interval>=cum_err) ? req_interval-cum_err : 0;
}
select_timeout = req_interval;
/*
* If we've exceeded our retry limit, 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 = (uint64_t)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 = (uint64_t)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 */
/*
* There is no point calling advance_cursor() here because if
* host n is not ready to send 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);
}
/*
* exit with status 1 if host_limit has been set with the --limit option and
* the number of responding hosts is less than this limit. Otherwise exit
* with status 0.
*/
return (host_limit == 0 || responders >= host_limit) ? 0 : 1;
}
/*
* 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) {
typedef struct {
const char *name;
char *value;
} field;
static field fields[NUMFIELDS] = {
{"IP",NULL}, {"Name",NULL}, {"MAC",NULL}, {"HdrMAC",NULL},
{"Vendor",NULL}, {"Padding",NULL}, {"Framing",NULL}, {"VLAN",NULL},
{"Proto",NULL}, {"DUP",NULL}, {"RTT",NULL}, {"IPnum",NULL},
};
static const id_name_map fields_map[] = {
{0, "IP"}, {1, "Name"}, {2, "MAC"},
{3, "HdrMAC"}, {4, "Vendor"}, {5, "Padding"},
{6, "Framing"}, {7, "VLAN"}, {8, "Proto"},
{9, "DUP"}, {10, "RTT"}, {11, "IPnum"},
{-1, NULL} /* -1 marks end of list */
};
char *msg;
char *cp;
char *ga_err_msg;
int nonzero = 0;
unsigned i;
/*
* Assign output fields based on response packet and options.
*/
/*
* IP field, always present.
*/
fields[0].value = make_message("%s", my_ntoa(he->addr));
/*
* Name field, present if --resolve option given.
*/
if (resolve_flag) {
cp = get_host_name(he->addr, &ga_err_msg);
if (cp) {
fields[1].value = make_message("%s", cp);
} else {
warn_msg("WARNING: getnameinfo() failed for \"%s\": %s",
my_ntoa(he->addr), ga_err_msg);
}
}
/*
* MAC field, always present.
*/
fields[2].value = make_message("%.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]);
/*
* HdrMAC field, present if source MAC in the ARP packet is different
* to source MAC in the Ethernet frame header.
*/
if ((memcmp(arpei->ar_sha, frame_hdr->src_addr, ETH_ALEN)) != 0) {
fields[3].value = make_message("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
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]);
}
/*
* Vendor field, present if --quiet option not given
*/
if (!quiet_flag) {
/*
* Find vendor in hash table.
*
* 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.
*/
char oui_string[13]; /* Space for full hw addr plus NULL */
const char *vendor = NULL;
int oui_end = 12;
ENTRY hash_query;
ENTRY *hash_result;
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 */
hash_query.key = oui_string;
hash_result = hsearch(hash_query, FIND);
if (hash_result) {
vendor = hash_result->data;
} else {
vendor = NULL;
}
oui_end--;
}
if (vendor)
fields[4].value = make_message("%s", vendor);
else
/* Check the second-least-significant bit of first octet */
if (arpei->ar_sha[0] & (1<<1))
fields[4].value = make_message("%s", "(Unknown: locally administered)");
else
fields[4].value = make_message("%s", "(Unknown)");
/*
* Padding field, present if --quiet option not given and frame padding
* is non zero
*/
/*
* Check that any data after the ARP packet is zero.
* If it is non-zero, and verbose is selected, then set the Padding
* field to the hex representation of the padding.
*/
if (extra_data_len > 0) {
const unsigned char *ucp = extra_data;
for (i=0; i<extra_data_len; i++) {
if (ucp[i] != '\0') {
nonzero = 1;
break;
}
}
}
if (nonzero) {
fields[5].value = hexstring(extra_data, extra_data_len);
}
/*
* Framing field, present if the framing type is 802.2 LLC/SNAP
*/
if (framing == FRAMING_LLC_SNAP) {
fields[6].value = make_message("802.2 LLC/SNAP");
}
/*
* VLAN field, present if the packet uses 802.1Q VLAN tagging.
*/
if (vlan_id != -1) {
fields[7].value = make_message("%d", vlan_id);
}
/*
* Proto field, present if the ARP protocol type is not IP (0x0800)
* This can occur with trailer encapsulation ARP replies on 4.2BSD VAX
*/
if (ntohs(arpei->ar_pro) != 0x0800) {
fields[8].value = make_message("0x%04x", ntohs(arpei->ar_pro));
}
/*
* DUP field, present if this is not the first response from this host.
*/
if (he->num_recv > 1) {
fields[9].value = make_message("%u", he->num_recv);
}
/*
* RTT field, present if the --rtt option is given
*/
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 may not 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;
fields[10].value=make_message("%lu.%03lu", rtt_us/1000, rtt_us%1000);
}
} /* End if (!quiet_flag) */
/*
* IPnum field, always present
*/
fields[11].value=make_message("%lu", ntohl(he->addr.s_addr));
/*
* Output fields.
*/
if (!format) { /* If --format option not given */
/*
* Output IP field or Name field depending on whether --resolve option
* was given.
*/
if (resolve_flag) {
msg = make_message("%s", fields[1].value);
} else {
msg = make_message("%s", fields[0].value);
}
/*
* Output MAC field
*/
cp = msg;
msg = make_message("%s\t%s", cp, fields[2].value);
free(cp);
/*
* Output HdrMAC field if present
*/
if (fields[3].value) {
cp = msg;
msg = make_message("%s (%s)", cp, fields[3].value);
free(cp);
}
/*
* Output Vendor field if present.
*/
if (fields[4].value) {
cp = msg;
msg = make_message("%s\t%s", cp, fields[4].value);
free(cp);
}
/*
* Output Padding field if present and --verbose is given
*/
if (fields[5].value && verbose) {
cp = msg;
msg = make_message("%s\tPadding=%s", cp, fields[5].value);
free(cp);
}
/*
* Output Framing field if present.
*/
if (fields[6].value) {
cp = msg;
if (framing == FRAMING_LLC_SNAP) {
msg = make_message("%s (%s)", cp, fields[6].value);
}
free(cp);
}
/*
* Output VLAN ID if the VLAN field is present.
*/
if (fields[7].value) {
cp = msg;
msg = make_message("%s (802.1Q VLAN=%s)", cp, fields[7].value);
free(cp);
}
/*
* Output Proto field if present.
*/
if (fields[8].value) {
cp = msg;
msg = make_message("%s (ARP Proto=%s)", cp, fields[8].value);
free(cp);
}
/*
* Output DUP field if present.
*/
if (fields[9].value) {
cp = msg;
msg = make_message("%s (DUP: %s)", cp, fields[9].value);
free(cp);
}
/*
* Output RTT field if present.
*/
if (fields[10].value) {
cp = msg;
msg = make_message("%s\tRTT=%s ms", cp, fields[10].value);
free(cp);
}
} else { /* --format option given */
format_element *fmt;
int idx;
msg = dupstr(""); /* Set msg to empty string */
for (fmt=format; fmt; fmt=fmt->next) {
if (fmt->type == FORMAT_FIELD) {
if ((idx=name_to_id(fmt->data, fields_map)) != -1 &&
fields[idx].value) {
cp = msg;
msg = make_message("%s%*s", cp, fmt->width, fields[idx].value);
free(cp);
} else { /* Field name not found in map */
warn_msg("WARNING: Field ${%s} unknown or not available",
fmt->data);
}
} else if (fmt->type == FORMAT_STRING) {
cp = msg;
msg = make_message("%s%s", cp, fmt->data);
free(cp);
}
}
}
/*
* Display the message on stdout and flush output buffer.
*/
printf("%s\n", msg);
fflush(stdout);
/*
* Free the message and any field values.
*/
free(msg);
for (i=0; i<NUMFIELDS; i++)
if (fields[i].value) {
free(fields[i].value);
fields[i].value = NULL;
}
}
/*
* 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) {