-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtargets.cc
1839 lines (1645 loc) · 65.1 KB
/
targets.cc
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
/***************************************************************************
* targets.cc -- Functions relating to "ping scanning" as well as *
* determining the exact IPs to hit based on CIDR and other input *
* formats. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2006 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-fingerprints or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is just meant to *
* clarify our interpretation of derived works with some common examples. *
* These restrictions only apply when you actually redistribute Nmap. For *
* example, nothing stops you from writing and selling a proprietary *
* front-end to Nmap. Just distribute it by itself, and point people to *
* http://insecure.org/nmap/ to download Nmap. *
* *
* We don't consider these to be added restrictions on top of the GPL, but *
* just a clarification of how we interpret "derived works" as it applies *
* to our GPL-licensed Nmap product. This is similar to the way Linus *
* Torvalds has announced his interpretation of how "derived works" *
* applies to Linux kernel modules. Our interpretation refers only to *
* Nmap - we don't speak for any other GPL products. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included Copying.OpenSSL file, and distribute linked *
* combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to fyodor@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering Fyodor and Insecure.Com LLC the unlimited, non-exclusive right *
* to reuse, modify, and relicense the code. Nmap will always be *
* available Open Source, but this is important because the inability to *
* relicense code has caused devastating problems for other Free Software *
* projects (such as KDE and NASM). We also occasionally relicense the *
* code to third parties as discussed above. If you wish to specify *
* special license conditions of your contributions, just say so when you *
* send them. *
* *
* This program 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 at *
* http://www.gnu.org/copyleft/gpl.html , or in the COPYING file included *
* with Nmap. *
* *
***************************************************************************/
/* $Id$ */
#include "targets.h"
#include "timing.h"
#include "osscan.h"
#include "NmapOps.h"
#include "TargetGroup.h"
#include "Target.h"
#include "scan_engine.h"
#include "nmap_dns.h"
#include "nmap_tty.h"
using namespace std;
extern NmapOps o;
enum pingstyle { pingstyle_unknown, pingstyle_rawtcp, pingstyle_rawudp, pingstyle_connecttcp,
pingstyle_icmp };
/* Gets the host number (index) of target in the hostbatch array of
pointers. Note that the target MUST EXIST in the array or all
heck will break loose. */
static inline int gethostnum(Target *hostbatch[], Target *target) {
int i = 0;
do {
if (hostbatch[i] == target)
return i;
} while(++i);
fatal("fluxx0red");
return 0; // Unreached
}
char *readhoststate(int state) {
switch(state) {
case HOST_UP:
return "HOST_UP";
case HOST_DOWN:
return "HOST_DOWN";
case HOST_FIREWALLED:
return "HOST_FIREWALLED";
default:
return "UNKNOWN/COMBO";
}
return NULL;
}
/* Internal function to update the state of machine (up/down/etc) based on
ping results */
static int hostupdate(Target *hostbatch[], Target *target,
int newstate, int dotimeout, int trynum,
struct timeout_info *to, struct timeval *sent,
struct timeval *rcvd,
struct pingtune *pt, struct tcpqueryinfo *tqi,
enum pingstyle style)
{
int hostnum = gethostnum(hostbatch, target);
int i;
int p;
int seq;
int tmpsd;
struct timeval tv;
if (o.debugging) {
gettimeofday(&tv, NULL);
log_write(LOG_STDOUT, "Hostupdate called for machine %s state %s -> %s (trynum %d, dotimeadj: %s time: %ld)\n", target->targetipstr(), readhoststate(target->flags), readhoststate(newstate), trynum, (dotimeout)? "yes" : "no", (long) TIMEVAL_SUBTRACT(tv, *sent));
}
assert(hostnum <= pt->group_end);
if (dotimeout) {
if (!rcvd) {
rcvd = &tv;
gettimeofday(&tv, NULL);
}
adjust_timeouts2(sent, rcvd, to);
}
/* If this is a tcp connect() pingscan, close all sockets */
if (style == pingstyle_connecttcp) {
seq = hostnum * pt->max_tries + trynum;
for(p=0; p < o.num_ping_synprobes; p++) {
for(i=0; i <= pt->block_tries; i++) {
seq = hostnum * pt->max_tries + i;
tmpsd = tqi->sockets[p][seq];
if (tmpsd >= 0) {
assert(tqi->sockets_out > 0);
tqi->sockets_out--;
close(tmpsd);
if (tmpsd == tqi->maxsd) tqi->maxsd--;
FD_CLR(tmpsd, &(tqi->fds_r));
FD_CLR(tmpsd, &(tqi->fds_w));
FD_CLR(tmpsd, &(tqi->fds_x));
tqi->sockets[p][seq] = -1;
}
}
}
}
target->to = *to;
if (target->flags & HOST_UP) {
/* The target is already up and that takes precedence over HOST_DOWN
or HOST_FIREWALLED, so we just return. */
return 0;
}
if (trynum > 0 && !(pt->dropthistry)) {
pt->dropthistry = 1;
if (o.debugging)
log_write(LOG_STDOUT, "Decreasing massping group size from %f to ", pt->group_size);
pt->group_size = MAX(pt->group_size * 0.75, pt->min_group_size);
if (o.debugging)
log_write(LOG_STDOUT, "%f\n", pt->group_size);
}
if (newstate == HOST_DOWN && (target->flags & HOST_DOWN)) {
/* I see nothing to do here */
} else if (newstate == HOST_UP && (target->flags & HOST_DOWN)) {
/* We give host_up precedence */
target->flags &= ~HOST_DOWN; /* Kill the host_down flag */
target->flags |= HOST_UP;
if (hostnum >= pt->group_start) {
/* The pt->block_tries was added because it is possible for a
host to be marked down in the first block try, then
down_this_block will be reset to 0 for the next try, in which
a late packet could cause the box to be marked up. In that
case, down_this_block could legitimately be 0. */
assert(pt->block_tries > 0 || pt->down_this_block > 0);
if (pt->down_this_block > 0)
pt->down_this_block--;
pt->up_this_block++;
}
} else if (newstate == HOST_DOWN) {
target->flags |= HOST_DOWN;
assert(pt->block_unaccounted > 0);
if (hostnum >= pt->group_start) {
pt->down_this_block++;
pt->block_unaccounted--;
pt->num_responses++;
}
} else {
assert(newstate == HOST_UP);
target->flags |= HOST_UP;
assert(pt->block_unaccounted > 0);
if (hostnum >= pt->group_start) {
pt->up_this_block++;
pt->block_unaccounted--;
pt->num_responses++;
}
}
return 0;
}
/* Conducts an ARP ping sweep of the given hosts to determine which ones
are up on a local ethernet network */
static void arpping(Target *hostbatch[], int num_hosts,
struct scan_lists *ports) {
/* First I change hostbatch into a vector<Target *>, which is what ultra_scan
takes. I remove hosts that cannot be ARP scanned (such as localhost) */
vector<Target *> targets;
int targetno;
targets.reserve(num_hosts);
for(targetno = 0; targetno < num_hosts; targetno++) {
initialize_timeout_info(&hostbatch[targetno]->to);
/* Default timout should be much lower for arp */
hostbatch[targetno]->to.timeout = MIN(o.initialRttTimeout(), 100) * 1000;
if (!hostbatch[targetno]->SrcMACAddress()) {
bool islocal = islocalhost(hostbatch[targetno]->v4hostip());
if (islocal) {
log_write(LOG_STDOUT|LOG_NORMAL,
"ARP ping: Considering %s UP because it is a local IP, despite no MAC address for device %s\n",
hostbatch[targetno]->NameIP(), hostbatch[targetno]->deviceName());
hostbatch[targetno]->flags &= ~(HOST_DOWN|HOST_FIREWALLED);
hostbatch[targetno]->flags |= HOST_UP;
} else {
log_write(LOG_STDOUT|LOG_NORMAL,
"ARP ping: Considering %s DOWN because no MAC address found for device %s.\n",
hostbatch[targetno]->NameIP(),
hostbatch[targetno]->deviceName());
hostbatch[targetno]->flags &= ~HOST_FIREWALLED;
hostbatch[targetno]->flags |= HOST_DOWN;
}
continue;
}
targets.push_back(hostbatch[targetno]);
}
if (!targets.empty())
ultra_scan(targets, ports, PING_SCAN_ARP);
return;
}
static void hoststructfry(Target *hostbatch[], int nelem) {
genfry((unsigned char *)hostbatch, sizeof(Target *), nelem);
return;
}
/* Returns the last host obtained by nexthost. It will be given again the next
time you call nexthost(). */
void returnhost(HostGroupState *hs) {
assert(hs->next_batch_no > 0);
hs->next_batch_no--;
}
/* Is the host passed as Target to be excluded, much of this logic had (mdmcl)
* to be rewritten from wam's original code to allow for the objects */
static int hostInExclude(struct sockaddr *checksock, size_t checksocklen,
TargetGroup *exclude_group) {
unsigned long tmpTarget; /* ip we examine */
int i=0; /* a simple index */
char targets_type; /* what is the address type of the Target Group */
struct sockaddr_storage ss;
struct sockaddr_in *sin = (struct sockaddr_in *) &ss;
size_t slen; /* needed for funct but not used */
unsigned long mask = 0; /* our trusty netmask, which we convert to nbo */
struct sockaddr_in *checkhost;
if ((TargetGroup *)0 == exclude_group)
return 0;
assert(checksocklen >= sizeof(struct sockaddr_in));
checkhost = (struct sockaddr_in *) checksock;
if (checkhost->sin_family != AF_INET)
checkhost = NULL;
/* First find out what type of addresses are in the target group */
targets_type = exclude_group[i].get_targets_type();
/* Lets go through the targets until we reach our uninitialized placeholder */
while (exclude_group[i].get_targets_type() != TargetGroup::TYPE_NONE)
{
/* while there are still hosts in the target group */
while (exclude_group[i].get_next_host(&ss, &slen) == 0) {
tmpTarget = sin->sin_addr.s_addr;
/* For Netmasks simply compare the network bits and move to the next
* group if it does not compare, we don't care about the individual addrs */
if (targets_type == TargetGroup::IPV4_NETMASK) {
mask = htonl((unsigned long) (0-1) << 32-exclude_group[i].get_mask());
if ((tmpTarget & mask) == (checkhost->sin_addr.s_addr & mask)) {
exclude_group[i].rewind();
return 1;
}
else {
break;
}
}
/* For ranges we need to be a little more slick, if we don't find a match
* we should skip the rest of the addrs in the octet, thank wam for this
* optimization */
else if (targets_type == TargetGroup::IPV4_RANGES) {
if (tmpTarget == checkhost->sin_addr.s_addr) {
exclude_group[i].rewind();
return 1;
}
else { /* note these are in network byte order */
if ((tmpTarget & 0x000000ff) != (checkhost->sin_addr.s_addr & 0x000000ff))
exclude_group[i].skip_range(TargetGroup::FIRST_OCTET);
else if ((tmpTarget & 0x0000ff00) != (checkhost->sin_addr.s_addr & 0x0000ff00))
exclude_group[i].skip_range(TargetGroup::SECOND_OCTET);
else if ((tmpTarget & 0x00ff0000) != (checkhost->sin_addr.s_addr & 0x00ff0000))
exclude_group[i].skip_range(TargetGroup::THIRD_OCTET);
continue;
}
}
#if HAVE_IPV6
else if (targets_type == TargetGroup::IPV6_ADDRESS) {
fatal("exclude file not supported for IPV6 -- If it is important to you, send a mail to fyodor@insecure.org so I can guage support\n");
}
#endif
}
exclude_group[i++].rewind();
}
/* we did not find the host */
return 0;
}
static int get_ping_results(int sd, pcap_t *pd, Target *hostbatch[],
int pingtype, struct timeval *time,
struct pingtune *pt, struct timeout_info *to,
int id, struct pingtech *ptech,
struct scan_lists *ports) {
fd_set fd_r, fd_x;
struct timeval myto, tmpto, start, rcvdtime;
unsigned int bytes;
int res;
struct ppkt {
unsigned char type;
unsigned char code;
unsigned short checksum;
unsigned short id;
unsigned short seq;
} *ping = NULL, *ping2 = NULL;
char response[16536];
struct tcp_hdr *tcp;
struct udp_hdr *udp;
struct ip *ip, *ip2;
u32 hostnum = 0xFFFFFF; /* This ought to crash us if it is used uninitialized */
int tm;
int dotimeout = 1;
int newstate = HOST_DOWN;
int foundsomething;
unsigned short newport = 0;
int newportstate; /* Hack so that in some specific cases we can determine the
state of a port and even skip the real scan */
u32 trynum = 0xFFFFFF;
enum pingstyle pingstyle = pingstyle_unknown;
int timeout = 0;
u16 sequence = 65534;
unsigned long tmpl;
unsigned short sportbase;
struct link_header linkhdr;
FD_ZERO(&fd_r);
FD_ZERO(&fd_x);
/* Decide on the timeout, based on whether we need to also watch for TCP stuff */
if (ptech->icmpscan && !ptech->rawtcpscan && !ptech->rawudpscan) {
/* We only need to worry about pings, so we set timeout for the whole she-bang! */
myto.tv_sec = to->timeout / 1000000;
myto.tv_usec = to->timeout % 1000000;
} else {
myto.tv_sec = 0;
myto.tv_usec = 20000;
}
if (o.magic_port_set) sportbase = o.magic_port;
else sportbase = o.magic_port + 20;
gettimeofday(&start, NULL);
newportstate = PORT_UNKNOWN;
while(pt->block_unaccounted > 0 && !timeout) {
keyWasPressed(); // Check for status message printing
tmpto = myto;
if (pd) {
ip = (struct ip *) readip_pcap(pd, &bytes, to->timeout, &rcvdtime, &linkhdr);
if (!ip)
gettimeofday(&rcvdtime, NULL);
} else {
FD_SET(sd, &fd_r);
FD_SET(sd, &fd_x);
res = select(sd+1, &fd_r, NULL, &fd_x, &tmpto);
if (res == 0) break;
bytes = recv(sd, response,sizeof(response), 0 );
ip = (struct ip *) response;
gettimeofday(&rcvdtime, NULL);
if (bytes > 0) {
PacketTrace::trace(PacketTrace::RCVD, (u8 *) response, bytes, &rcvdtime);
}
}
tm = TIMEVAL_SUBTRACT(rcvdtime,start);
if (tm > (MAX(400000,3 * to->timeout)))
timeout = 1;
if (bytes == 0 && tm > to->timeout) {
timeout = 1;
}
if (bytes == 0)
continue;
if (bytes > 0 && bytes <= 20) {
error("%d byte micro packet received in get_ping_results", bytes);
continue;
}
foundsomething = 0;
dotimeout = 0;
/* First check if it is ICMP, TCP, or UDP */
if (ip->ip_p == IPPROTO_ICMP) {
/* if it is our response */
ping = (struct ppkt *) ((ip->ip_hl * 4) + (char *) ip);
if (bytes < ip->ip_hl * 4 + 8U) {
if (!ip->ip_off)
error("Supposed ping packet is only %d bytes long!", bytes);
continue;
}
/* Echo reply, Timestamp reply, or Address Mask Reply */
if ( (ping->type == 0 || ping->type == 14 || ping->type == 18)
&& !ping->code && ping->id == id) {
sequence = ping->seq - pt->seq_offset;
hostnum = sequence / pt->max_tries;
if (hostnum > (u32) pt->group_end) {
if (o.debugging)
error("Ping sequence %hu leads to hostnum %d which is beyond the end of this group (%d)", sequence, hostnum, pt->group_end);
continue;
}
if (o.debugging)
log_write(LOG_STDOUT, "We got a ping packet back from %s: id = %d seq = %d checksum = %d\n", inet_ntoa(ip->ip_src), ping->id, ping->seq, ping->checksum);
if (hostbatch[hostnum]->v4host().s_addr == ip->ip_src.s_addr) {
foundsomething = 1;
pingstyle = pingstyle_icmp;
newstate = HOST_UP;
trynum = sequence % pt->max_tries;
dotimeout = 1;
if (!hostbatch[hostnum]->v4sourceip()) {
struct sockaddr_in sin;
memset(&sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = ip->ip_dst.s_addr;
#if HAVE_SOCKADDR_SA_LEN
sin.sin_len = sizeof(sin);
#endif
hostbatch[hostnum]->setSourceSockAddr((struct sockaddr_storage *) &sin,
sizeof(sin));
}
}
else hostbatch[hostnum]->wierd_responses++;
}
// Destination unreachable, source quench, or time exceeded
else if (ping->type == 3 || ping->type == 4 || ping->type == 11 || o.debugging) {
if (bytes < ip->ip_hl * 4 + 28U) {
if (o.debugging)
error("ICMP type %d code %d packet is only %d bytes\n", ping->type, ping->code, bytes);
continue;
}
ip2 = (struct ip *) ((char *)ip + ip->ip_hl * 4 + 8);
if (bytes < ip->ip_hl * 4 + 8U + ip2->ip_hl * 4 + 8U) {
if (o.debugging)
error("ICMP (embedded) type %d code %d packet is only %d bytes\n", ping->type, ping->code, bytes);
continue;
}
if (ip2->ip_p == IPPROTO_ICMP) {
/* The response was based on a ping packet we sent */
if (!ptech->icmpscan && !ptech->rawicmpscan) {
if (o.debugging)
error("Got ICMP error referring to ICMP msg which we did not send");
continue;
}
ping2 = (struct ppkt *) ((char *)ip2 + ip2->ip_hl * 4);
if (ping2->id != id) {
if (o.debugging) {
error("Illegal id %d found, should be %d (icmp type/code %d/%d)", ping2->id, id, ping->type, ping->code);
if (o.debugging > 1)
lamont_hdump((char *)ip, bytes);
}
continue;
}
sequence = ping2->seq - pt->seq_offset;
hostnum = sequence / pt->max_tries;
trynum = sequence % pt->max_tries;
if (trynum >= (u32) pt->max_tries || hostnum > (u32) pt->group_end ||
hostbatch[hostnum]->v4host().s_addr != ip2->ip_dst.s_addr) {
if (o.debugging) {
error("Bogus trynum, sequence number or unexpected IP address in ICMP error message\n");
}
continue;
}
} else if (ip2->ip_p == IPPROTO_TCP) {
/* The response was based our TCP probe */
if (!ptech->rawtcpscan) {
if (o.debugging)
error("Got ICMP error referring to TCP msg which we did not send");
continue;
}
tcp = (struct tcp_hdr *) (((char *) ip2) + 4 * ip2->ip_hl);
/* No need to check size here, the "+8" check a ways up takes care
of it */
newport = ntohs(tcp->th_dport);
trynum = ntohs(tcp->th_sport) - sportbase;
if (trynum >= (u32) pt->max_tries) {
if (o.debugging)
error("Bogus trynum %d", trynum);
continue;
}
/* Grab the sequence nr */
tmpl = ntohl(tcp->th_seq);
if ((tmpl & 0x3F) == 0x1E) {
sequence = ((tmpl >> 6) & 0xffff) - pt->seq_offset;
hostnum = sequence / pt->max_tries;
trynum = sequence % pt->max_tries;
} else {
if (o.debugging) {
error("Whacked seq number from %s", inet_ntoa(ip->ip_src));
}
continue;
}
if (trynum >= (u32) pt->max_tries || hostnum > (u32) pt->group_end ||
hostbatch[hostnum]->v4host().s_addr != ip2->ip_dst.s_addr) {
if (o.debugging) {
error("Bogus trynum, sequence number or unexpected IP address in ICMP error message\n");
}
continue;
}
} else if (ip2->ip_p == IPPROTO_UDP) {
/* The response was based our UDP probe */
if (!ptech->rawudpscan) {
if (o.debugging)
error("Got ICMP error referring to UDP msg which we did not send");
continue;
}
sequence = ntohs(ip2->ip_id) - pt->seq_offset;
hostnum = sequence / pt->max_tries;
trynum = sequence % pt->max_tries;
if (trynum >= (u32) pt->max_tries || hostnum > (u32) pt->group_end ||
hostbatch[hostnum]->v4host().s_addr != ip2->ip_dst.s_addr) {
if (o.debugging) {
error("Bogus trynum, sequence number or unexpected IP address in ICMP error message\n");
}
continue;
}
} else {
if (o.debugging)
error("Got ICMP response to a packet which was not TCP, UDP, or ICMP");
continue;
}
assert (hostnum <= (u32) pt->group_end);
if (ping->type == 3) {
dotimeout = 1;
foundsomething = 1;
pingstyle = pingstyle_icmp;
if (ping->code == 3 && ptech->rawudpscan) {
/* ICMP port unreachable -- the port is closed but aparently the machine is up! */
newstate = HOST_UP;
} else {
if (o.debugging)
log_write(LOG_STDOUT, "Got destination unreachable for %s\n", hostbatch[hostnum]->targetipstr());
/* Since this gives an idea of how long it takes to get an answer,
we add it into our times */
newstate = HOST_DOWN;
newportstate = PORT_FILTERED;
}
} else if (ping->type == 11) {
if (o.debugging)
log_write(LOG_STDOUT, "Got Time Exceeded for %s\n", hostbatch[hostnum]->targetipstr());
dotimeout = 0; /* I don't want anything to do with timing this */
foundsomething = 1;
pingstyle = pingstyle_icmp;
newstate = HOST_DOWN;
}
else if (ping->type == 4) {
if (o.debugging) log_write(LOG_STDOUT, "Got ICMP source quench\n");
usleep(50000);
}
else if (o.debugging > 0) {
log_write(LOG_STDOUT, "Got ICMP message type %d code %d\n", ping->type, ping->code);
}
}
} else if (ip->ip_p == IPPROTO_TCP)
{
if (!ptech->rawtcpscan) {
continue;
}
if (bytes < 4 * ip->ip_hl + 16U) {
error("TCP packet is only %d bytes, we can't get enough information from it\n", bytes);
continue;
}
tcp = (struct tcp_hdr *) (((char *) ip) + 4 * ip->ip_hl);
if (!(tcp->th_flags & TH_RST) && ((tcp->th_flags & (TH_SYN|TH_ACK)) != (TH_SYN|TH_ACK)))
continue;
newport = ntohs(tcp->th_sport);
tmpl = ntohl(tcp->th_ack);
if ((tmpl & 0x3F) != 0x1E && (tmpl & 0x3F) != 0x1F)
tmpl = ntohl(tcp->th_seq); // We'll try the seq -- it is often helpful
// in ACK scan responses
if ((tmpl & 0x3F) == 0x1E || (tmpl & 0x3F) == 0x1F) {
sequence = ((tmpl >> 6) & 0xffff) - pt->seq_offset;
hostnum = sequence / pt->max_tries;
trynum = sequence % pt->max_tries;
} else {
// Didn't get it back in either field -- we'll brute force it ...
for(hostnum = pt->group_end; hostnum != (u32) -1; hostnum--) {
if (hostbatch[hostnum]->v4host().s_addr == ip->ip_src.s_addr)
break;
}
if (hostnum == (u32) -1) {
if (o.debugging > 1)
error("Warning, unexpected packet from machine %s", inet_ntoa(ip->ip_src));
continue;
}
trynum = ntohs(tcp->th_dport) - sportbase;
sequence = hostnum * pt->max_tries + trynum;
}
if (trynum >= (u32) pt->max_tries) {
if (o.debugging)
error("Bogus trynum %d", trynum);
continue;
}
if (hostnum > (u32) pt->group_end) {
if (o.debugging) {
error("Response from host beyond group_end");
}
continue;
}
if (hostbatch[hostnum]->v4host().s_addr != ip->ip_src.s_addr) {
if (o.debugging) {
error("TCP ping response from unexpected host %s\n", inet_ntoa(ip->ip_src));
}
continue;
}
if (o.debugging)
log_write(LOG_STDOUT, "We got a TCP ping packet back from %s port %hi (hostnum = %d trynum = %d\n", inet_ntoa(ip->ip_src), ntohs(tcp->th_sport), hostnum, trynum);
pingstyle = pingstyle_rawtcp;
foundsomething = 1;
dotimeout = 1;
newstate = HOST_UP;
if (pingtype & PINGTYPE_TCP_USE_SYN) {
if (tcp->th_flags & TH_RST) {
newportstate = PORT_CLOSED;
} else if ((tcp->th_flags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
newportstate = PORT_OPEN;
}
}
} else if (ip->ip_p == IPPROTO_UDP) {
if (!ptech->rawudpscan) {
continue;
}
udp = (struct udp_hdr *) (((char *) ip) + 4 * ip->ip_hl);
newport = ntohs(udp->uh_sport);
trynum = ntohs(udp->uh_dport) - sportbase;
if (trynum >= (u32) pt->max_tries) {
if (o.debugging)
error("Bogus trynum %d", trynum);
continue;
}
/* Since this UDP response doesn't give us the sequence number, we'll have to brute force
lookup to find the hostnum */
for(hostnum = pt->group_end; hostnum != (u32) -1; hostnum--) {
if (hostbatch[hostnum]->v4host().s_addr == ip->ip_src.s_addr)
break;
}
if (hostnum == (u32) -1) {
if (o.debugging > 1)
error("Warning, unexpected packet from machine %s", inet_ntoa(ip->ip_src));
continue;
}
sequence = hostnum * pt->max_tries + trynum;
if (o.debugging)
log_write(LOG_STDOUT, "In response to UDP-ping, we got UDP packet back from %s port %hi (hostnum = %d trynum = %d\n", inet_ntoa(ip->ip_src), htons(udp->uh_sport), hostnum, trynum);
pingstyle = pingstyle_rawudp;
foundsomething = 1;
dotimeout = 1;
newstate = HOST_UP;
}
else if (o.debugging) {
error("Found whacked packet protocol %d in get_ping_results", ip->ip_p);
}
if (foundsomething) {
hostupdate(hostbatch, hostbatch[hostnum], newstate, dotimeout,
trynum, to, &time[sequence], &rcvdtime, pt, NULL, pingstyle);
if (newstate == HOST_UP && ip && bytes >= 20)
setTargetMACIfAvailable(hostbatch[hostnum], &linkhdr, ip, 0);
}
if (newport && newportstate != PORT_UNKNOWN) {
/* OK, we can add it, but that is only appropriate if this is one
of the ports the user ASKED for */
/* This was for the old turbo mode -- which I no longer support now that ultra_scan() can handle parallel hosts. Maybe I'll bring it back someday */
/*
if (ports && ports->tcp_count == 1 && ports->tcp_ports[0] == newport)
hostbatch[hostnum]->ports.addPort(newport, IPPROTO_TCP, NULL,
newportstate);
*/
}
}
return 0;
}
static int sendconnecttcpquery(Target *hostbatch[], struct tcpqueryinfo *tqi,
Target *target, int probe_port_num, u16 seq,
struct timeval *time, struct pingtune *pt,
struct timeout_info *to, int max_sockets) {
int res,sock_err,i;
int tmpsd;
int hostnum, trynum;
struct sockaddr_storage sock;
struct sockaddr_in *sin = (struct sockaddr_in *) &sock;
struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *) &sock;
size_t socklen;
seq -= pt->seq_offset; // Because connect() pingscan doesn't send it over the wire
trynum = seq % pt->max_tries;
hostnum = seq / pt->max_tries;
assert(tqi->sockets_out <= max_sockets);
if (tqi->sockets_out == max_sockets) {
/* We've got to free one! */
for(i=0; i < trynum; i++) {
tmpsd = hostnum * pt->max_tries + i;
if (tqi->sockets[probe_port_num][tmpsd] >= 0) {
if (o.debugging)
log_write(LOG_STDOUT, "sendconnecttcpquery: Scavenging a free socket due to serious shortage\n");
close(tqi->sockets[probe_port_num][tmpsd]);
tqi->sockets[probe_port_num][tmpsd] = -1;
tqi->sockets_out--;
break;
}
}
if (i == trynum)
fatal("sendconnecttcpquery: Could not scavenge a free socket!");
}
/* Since we know we now have a free s0cket, lets take it */
assert(tqi->sockets[probe_port_num][seq] == -1);
tqi->sockets[probe_port_num][seq] = socket(o.af(), SOCK_STREAM, IPPROTO_TCP);
if (tqi->sockets[probe_port_num][seq] == -1)
fatal("Socket creation in sendconnecttcpquery");
tqi->maxsd = MAX(tqi->maxsd, tqi->sockets[probe_port_num][seq]);
tqi->sockets_out++;
unblock_socket(tqi->sockets[probe_port_num][seq]);
init_socket(tqi->sockets[probe_port_num][seq]);
if (target->TargetSockAddr(&sock, &socklen) != 0)
fatal("Unable to get target sock in sendconnecttcpquery");
if (sin->sin_family == AF_INET)
sin->sin_port = htons(o.ping_synprobes[probe_port_num]);
#if HAVE_IPV6
else sin6->sin6_port = htons(o.ping_synprobes[probe_port_num]);
#endif //HAVE_IPV6
res = connect(tqi->sockets[probe_port_num][seq],(struct sockaddr *)&sock, socklen);
sock_err = socket_errno();
if ((res != -1 || sock_err == ECONNREFUSED)) {
/* This can happen on localhost, successful/failing connection immediately
in non-blocking mode */
hostupdate(hostbatch, target, HOST_UP, 1, trynum, to,
&time[seq], NULL, pt, tqi, pingstyle_connecttcp);
if (tqi->maxsd == tqi->sockets[probe_port_num][seq]) tqi->maxsd--;
}
else if (sock_err == ENETUNREACH) {
if (o.debugging)
error("Got ENETUNREACH from sendconnecttcpquery connect()");
hostupdate(hostbatch, target, HOST_DOWN, 1, trynum, to,
&time[seq], NULL, pt, tqi, pingstyle_connecttcp);
}
else {
/* We'll need to select() and wait it out */
FD_SET(tqi->sockets[probe_port_num][seq], &(tqi->fds_r));
FD_SET(tqi->sockets[probe_port_num][seq], &(tqi->fds_w));
FD_SET(tqi->sockets[probe_port_num][seq], &(tqi->fds_x));
}
return 0;
}
static int sendconnecttcpqueries(Target *hostbatch[], struct tcpqueryinfo *tqi,
Target *target, u16 seq,
struct timeval *time, struct pingtune *pt,
struct timeout_info *to, int max_sockets) {
int i;
for( i=0; i<o.num_ping_synprobes; i++ ) {
if (i > 0 && o.scan_delay) enforce_scan_delay(NULL);
sendconnecttcpquery(hostbatch, tqi, target, i, seq, time, pt, to, max_sockets);
}
return 0;
}
static int sendrawudppingquery(int rawsd, struct eth_nfo *eth, Target *target, u16 probe_port,
u16 seq, struct timeval *time, struct pingtune *pt) {
int trynum = 0;
unsigned short sportbase;
if (o.magic_port_set) sportbase = o.magic_port;
else {
sportbase = o.magic_port + 20;
trynum = seq % pt->max_tries;
}
o.decoys[o.decoyturn].s_addr = target->v4source().s_addr;
send_udp_raw_decoys( rawsd, eth, target->v4hostip(),
o.ttl, seq,
o.ipoptions, o.ipoptionslen,
sportbase + trynum, probe_port,
o.extra_payload, o.extra_payload_length);
return 0;
}
static int sendrawtcppingquery(int rawsd, struct eth_nfo *eth, Target *target, int pingtype, u16 probe_port,
u16 seq, struct timeval *time, struct pingtune *pt) {
int trynum = 0;
int myseq;
unsigned short sportbase;
unsigned long myack;
if (o.magic_port_set) sportbase = o.magic_port;
else {
sportbase = o.magic_port + 20;
trynum = seq % pt->max_tries;
}
myseq = (get_random_uint() << 22) + (seq << 6) + 0x1E; /* (response & 0x3F) better be 0x1E or 0x1F */
myack = (get_random_uint() << 22) + (seq << 6) + 0x1E; /* (response & 0x3F) better be 0x1E or 0x1F */
o.decoys[o.decoyturn].s_addr = target->v4source().s_addr;
if (pingtype & PINGTYPE_TCP_USE_SYN) {
send_tcp_raw_decoys( rawsd, eth, target->v4hostip(),
o.ttl, false,
o.ipoptions, o.ipoptionslen,
sportbase + trynum, probe_port,
myseq, myack, 0, TH_SYN, 0, 0,
(u8 *) "\x02\x04\x05\xb4", 4,
o.extra_payload, o.extra_payload_length);
} else {
send_tcp_raw_decoys( rawsd, eth, target->v4hostip(),
o.ttl, false,
o.ipoptions, o.ipoptionslen,
sportbase + trynum, probe_port,
myseq, myack, 0, TH_ACK, 0, 0,
NULL, 0,
o.extra_payload, o.extra_payload_length);
}
return 0;
}
static int sendrawtcpudppingqueries(int rawsd, eth_t *ethsd, Target *target, int pingtype, u16 seq,
struct timeval *time, struct pingtune *pt) {
int i;
struct eth_nfo eth;
struct eth_nfo *ethptr = NULL;
if (ethsd) {
memcpy(eth.srcmac, target->SrcMACAddress(), 6);
memcpy(eth.dstmac, target->NextHopMACAddress(), 6);
eth.ethsd = ethsd;
eth.devname[0] = '\0';
ethptr = ð
} else ethptr = NULL;
if (pingtype & PINGTYPE_UDP) {
for( i=0; i<o.num_ping_udpprobes; i++ ) {
if (i > 0 && o.scan_delay) enforce_scan_delay(NULL);
sendrawudppingquery(rawsd, ethptr, target, o.ping_udpprobes[i], seq, time, pt);
}
}
if (pingtype & PINGTYPE_TCP_USE_ACK) {
for( i=0; i<o.num_ping_ackprobes; i++ ) {
if (i > 0 && o.scan_delay) enforce_scan_delay(NULL);
sendrawtcppingquery(rawsd, ethptr, target, PINGTYPE_TCP_USE_ACK, o.ping_ackprobes[i], seq, time, pt);
}
}
if (pingtype & PINGTYPE_TCP_USE_SYN) {
for( i=0; i<o.num_ping_synprobes; i++ ) {
if (i > 0 && o.scan_delay) enforce_scan_delay(NULL);
sendrawtcppingquery(rawsd, ethptr, target, PINGTYPE_TCP_USE_SYN, o.ping_synprobes[i], seq, time, pt);
}
}
return 0;
}
static int sendpingquery(int sd, int rawsd, eth_t *ethsd, Target *target,
u16 seq, unsigned short id, struct scanstats *ss,
struct timeval *time, int pingtype, struct pingtech ptech) {
struct ppkt {
u8 type;
u8 code;
u16 checksum;
u16 id;
u16 seq;
u8 data[1500]; /* Note -- first 4-12 bytes can be used for ICMP header */
} pingpkt;