forked from nmap/nmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscan_engine.cc
2826 lines (2560 loc) · 105 KB
/
scan_engine.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
/***************************************************************************
* scan_engine.cc -- Includes much of the "engine" functions for scanning, *
* such as ultra_scan. It also includes dependent functions such as those *
* for collecting SYN/connect scan responses. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2019 Insecure.Com LLC ("The Nmap *
* Project"). Nmap is also a registered trademark of the Nmap Project. *
* 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 ("GPL"), BUT ONLY WITH ALL OF THE *
* CLARIFICATIONS AND EXCEPTIONS DESCRIBED HEREIN. 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 [email protected]). *
* Dozens of software vendors already license Nmap technology such as *
* host discovery, port scanning, OS detection, version detection, and *
* the Nmap Scripting Engine. *
* *
* Note that the GPL places important restrictions on "derivative works", *
* yet it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we interpret that term as broadly as copyright law *
* allows. For example, we consider an application to constitute a *
* derivative work for the purpose of this license if it does any of the *
* following with any software or content covered by this license *
* ("Covered Software"): *
* *
* o Integrates source code from Covered Software. *
* *
* o Reads or includes copyrighted data files, such as Nmap's nmap-os-db *
* or nmap-service-probes. *
* *
* o Is designed specifically to execute Covered Software and parse the *
* results (as opposed to typical shell or execution-menu apps, which will *
* execute anything you tell them to). *
* *
* o Includes Covered Software in a proprietary executable installer. The *
* installers produced by InstallShield are an example of this. Including *
* Nmap with other software in compressed or archival form does not *
* trigger this provision, provided appropriate open source decompression *
* or de-archiving software is widely available for no charge. For the *
* purposes of this license, an installer is considered to include Covered *
* Software even if it actually retrieves a copy of Covered Software from *
* another source during runtime (such as by downloading it from the *
* Internet). *
* *
* o Links (statically or dynamically) to a library which does any of the *
* above. *
* *
* o Executes a helper program, module, or script to do any of the above. *
* *
* This list is not exclusive, but is meant to clarify our interpretation *
* of derived works with some common examples. Other people may interpret *
* the plain GPL differently, so we consider this a special exception to *
* the GPL that we apply to Covered Software. Works which meet any of *
* these conditions must conform to all of the terms of this license, *
* particularly including the GPL Section 3 requirements of providing *
* source code and allowing free redistribution of the work as a whole. *
* *
* As another special exception to the GPL terms, the Nmap Project 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 docs/licenses/OpenSSL.txt file, and distribute *
* linked combinations including the two. *
* *
* The Nmap Project has permission to redistribute Npcap, a packet *
* capturing driver and library for the Microsoft Windows platform. *
* Npcap is a separate work with it's own license rather than this Nmap *
* license. Since the Npcap license does not permit redistribution *
* without special permission, our Nmap Windows binary packages which *
* contain Npcap may not be redistributed without special permission. *
* *
* Any redistribution of Covered Software, including any derived works, *
* must obey and carry forward all of the terms of this license, including *
* obeying all GPL rules and restrictions. For example, source code of *
* the whole work must be provided and free redistribution must be *
* allowed. All GPL references to "this License", are to be treated as *
* including the terms and conditions of this license text as well. *
* *
* Because this license imposes special exceptions to the GPL, Covered *
* Work may not be combined (even as part of a larger work) with plain GPL *
* software. The terms, conditions, and exceptions of this license must *
* be included as well. This license is incompatible with some other open *
* source licenses as well. In some cases we can relicense portions of *
* Nmap or grant special permissions to use it in other open source *
* software. Please contact [email protected] with any such requests. *
* Similarly, we don't incorporate incompatible open source software into *
* Covered Software without special permission from the copyright holders. *
* *
* If you have any questions about the licensing restrictions on using *
* Nmap in other works, we are happy to help. As mentioned above, we also *
* offer an 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 support and updates. They also fund the continued *
* development of Nmap. Please email [email protected] for further *
* information. *
* *
* If you have received a written license agreement or contract for *
* Covered Software stating terms other than these, you may choose to use *
* and redistribute Covered Software under those terms instead of these. *
* *
* 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. *
* *
* 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 the [email protected] mailing list for possible incorporation into the *
* main distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, or checking them into the Nmap *
* source code repository, it is understood (unless you specify *
* otherwise) that you are offering the Nmap Project 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 Nmap *
* license file for more details (it's in a COPYING file included with *
* Nmap, and also available from https://svn.nmap.org/nmap/COPYING) *
* *
***************************************************************************/
/* $Id$ */
#ifdef WIN32
#include "nmap_winconfig.h"
#endif
#include "portreasons.h"
#include <dnet.h>
#include "scan_engine.h"
#include "scan_engine_connect.h"
#include "scan_engine_raw.h"
#include "timing.h"
#include "tcpip.h"
#include "NmapOps.h"
#include "nmap_tty.h"
#include "payload.h"
#include "Target.h"
#include "targets.h"
#include "utils.h"
#include "nmap_error.h"
#include "output.h"
#include "struct_ip.h"
#ifndef IPPROTO_SCTP
#include "libnetutil/netutil.h"
#endif
#include <math.h>
#include <list>
#include <map>
extern NmapOps o;
#ifdef WIN32
/* from libdnet's intf-win32.c */
extern "C" int g_has_npcap_loopback;
#endif
int HssPredicate::operator() (const HostScanStats *lhs, const HostScanStats *rhs) const {
const struct sockaddr_storage *lss, *rss;
lss = (lhs) ? lhs->target->TargetSockAddr() : ss;
rss = (rhs) ? rhs->target->TargetSockAddr() : ss;
return 0 > sockaddr_storage_cmp(lss, rss);
}
struct sockaddr_storage *HssPredicate::ss = NULL;
void UltraScanInfo::log_overall_rates(int logt) {
log_write(logt, "Overall sending rates: %.2f packets / s", send_rate_meter.getOverallPacketRate(&now));
if (send_rate_meter.getNumBytes() > 0)
log_write(logt, ", %.2f bytes / s", send_rate_meter.getOverallByteRate(&now));
log_write(logt, ".\n");
}
void UltraScanInfo::log_current_rates(int logt, bool update) {
log_write(logt, "Current sending rates: %.2f packets / s", send_rate_meter.getCurrentPacketRate(&now, update));
if (send_rate_meter.getNumBytes() > 0)
log_write(logt, ", %.2f bytes / s", send_rate_meter.getCurrentByteRate(&now));
log_write(logt, ".\n");
}
void ultra_scan_performance_vars::init() {
scan_performance_vars::init();
ping_magnifier = 3;
pingtime = 1250000;
tryno_cap = o.getMaxRetransmissions();
}
const char *pspectype2ascii(int type) {
switch (type) {
case PS_NONE:
return "NONE";
case PS_TCP:
return "TCP";
case PS_UDP:
return "UDP";
case PS_SCTP:
return "SCTP";
case PS_PROTO:
return "IP Proto";
case PS_ICMP:
return "ICMP";
case PS_ARP:
return "ARP";
case PS_ICMPV6:
return "ICMPv6";
case PS_ND:
return "ND";
case PS_CONNECTTCP:
return "connect";
default:
fatal("%s: Unknown type: %d", __func__, type);
}
return ""; // Unreached
}
/* Initialize the ultra_timing_vals structure timing. The utt must be
TIMING_HOST or TIMING_GROUP. If you happen to have the current
time handy, pass it as now, otherwise pass NULL */
static void init_ultra_timing_vals(ultra_timing_vals *timing,
enum ultra_timing_type utt,
int num_hosts_in_group,
struct ultra_scan_performance_vars *perf,
struct timeval *now);
/* Take a buffer, buf, of size bufsz (64 bytes is sufficient) and
writes a short description of the probe (arg1) into buf. It also returns
buf. */
static char *probespec2ascii(const probespec *pspec, char *buf, unsigned int bufsz) {
char flagbuf[32];
char *f;
switch (pspec->type) {
case PS_TCP:
if (!pspec->pd.tcp.flags) {
Strncpy(flagbuf, "(none)", sizeof(flagbuf));
} else {
f = flagbuf;
if (pspec->pd.tcp.flags & TH_SYN)
*f++ = 'S';
if (pspec->pd.tcp.flags & TH_FIN)
*f++ = 'F';
if (pspec->pd.tcp.flags & TH_RST)
*f++ = 'R';
if (pspec->pd.tcp.flags & TH_PUSH)
*f++ = 'P';
if (pspec->pd.tcp.flags & TH_ACK)
*f++ = 'A';
if (pspec->pd.tcp.flags & TH_URG)
*f++ = 'U';
if (pspec->pd.tcp.flags & TH_ECE)
*f++ = 'E'; /* rfc 2481/3168 */
if (pspec->pd.tcp.flags & TH_CWR)
*f++ = 'C'; /* rfc 2481/3168 */
*f++ = '\0';
}
Snprintf(buf, bufsz, "tcp to port %hu; flags: %s", pspec->pd.tcp.dport, flagbuf);
break;
case PS_UDP:
Snprintf(buf, bufsz, "udp to port %hu", pspec->pd.udp.dport);
break;
case PS_SCTP:
switch (pspec->pd.sctp.chunktype) {
case SCTP_INIT:
Strncpy(flagbuf, "INIT", sizeof(flagbuf));
break;
case SCTP_COOKIE_ECHO:
Strncpy(flagbuf, "COOKIE-ECHO", sizeof(flagbuf));
break;
default:
Strncpy(flagbuf, "(unknown)", sizeof(flagbuf));
}
Snprintf(buf, bufsz, "sctp to port %hu; chunk: %s", pspec->pd.sctp.dport,
flagbuf);
break;
case PS_PROTO:
Snprintf(buf, bufsz, "protocol %u", (unsigned int) pspec->proto);
break;
case PS_ICMP:
Snprintf(buf, bufsz, "icmp type %d code %d",
pspec->pd.icmp.type, pspec->pd.icmp.code);
break;
case PS_ARP:
Snprintf(buf, bufsz, "ARP");
break;
case PS_ICMPV6:
Snprintf(buf, bufsz, "icmpv6 type %d code %d",
pspec->pd.icmpv6.type, pspec->pd.icmpv6.code);
break;
case PS_ND:
Snprintf(buf, bufsz, "ND");
break;
case PS_CONNECTTCP:
Snprintf(buf, bufsz, "connect to port %hu", pspec->pd.tcp.dport);
break;
default:
fatal("Unexpected %s type encountered", __func__);
break;
}
return buf;
}
UltraProbe::UltraProbe() {
type = UP_UNSET;
tryno = 0;
timedout = false;
retransmitted = false;
pingseq = 0;
mypspec.type = PS_NONE;
memset(&sent, 0, sizeof(prevSent));
memset(&prevSent, 0, sizeof(prevSent));
}
UltraProbe::~UltraProbe() {
if (type == UP_CONNECT)
delete probes.CP;
}
GroupScanStats::GroupScanStats(UltraScanInfo *UltraSI) {
memset(&latestip, 0, sizeof(latestip));
memset(&timeout, 0, sizeof(timeout));
USI = UltraSI;
init_ultra_timing_vals(&timing, TIMING_GROUP, USI->numIncompleteHosts(), &(USI->perf), &USI->now);
initialize_timeout_info(&to);
/* Default timout should be much lower for arp */
if (USI->ping_scan_arp)
to.timeout = MAX(o.minRttTimeout(), MIN(o.initialRttTimeout(), INITIAL_ARP_RTT_TIMEOUT)) * 1000;
num_probes_active = 0;
numtargets = USI->numIncompleteHosts(); // They are all incomplete at the beginning
numprobes = USI->numProbesPerHost();
if (USI->scantype == CONNECT_SCAN || USI->ptech.connecttcpscan)
CSI = new ConnectScanInfo;
else CSI = NULL;
probes_sent = probes_sent_at_last_wait = 0;
lastping_sent = lastrcvd = USI->now;
send_no_earlier_than = USI->now;
send_no_later_than = USI->now;
lastping_sent_numprobes = 0;
pinghost = NULL;
gettimeofday(&last_wait, NULL);
num_hosts_timedout = 0;
}
GroupScanStats::~GroupScanStats() {
delete CSI;
}
/* Called whenever a probe is sent to any host. Should only be called by
HostScanStats::probeSent. */
void GroupScanStats::probeSent(unsigned int nbytes) {
USI->send_rate_meter.update(nbytes, &USI->now);
/* Find a new scheduling interval for minimum- and maximum-rate sending.
Recall that these have effect only when --min-rate or --max-rate is
given. */
if (o.max_packet_send_rate != 0.0)
TIMEVAL_ADD(send_no_earlier_than, send_no_earlier_than,
(time_t) (1000000.0 / o.max_packet_send_rate));
/* Allow send_no_earlier_than to slip into the past. This allows the sending
scheduler to catch up and make up for delays in other parts of the scan
engine. If we were to update send_no_earlier_than to the present the
sending rate could be much less than the maximum requested, even if the
connection is capable of the maximum. */
if (o.min_packet_send_rate != 0.0) {
if (TIMEVAL_SUBTRACT(send_no_later_than, USI->now) > 0) {
/* The next scheduled send is in the future. That means there's slack time
during which the sending rate could drop. Pull the time back to the
present to prevent that. */
send_no_later_than = USI->now;
}
TIMEVAL_ADD(send_no_later_than, send_no_later_than,
(time_t) (1000000.0 / o.min_packet_send_rate));
}
}
/* Returns true if the GLOBAL system says that sending is OK.*/
bool GroupScanStats::sendOK(struct timeval *when) {
int recentsends;
/* In case it's not okay to send, arbitrarily say to check back in one
second. */
if (when)
TIMEVAL_MSEC_ADD(*when, USI->now, 1000);
if ((USI->scantype == CONNECT_SCAN || USI->ptech.connecttcpscan)
&& CSI->numSDs >= CSI->maxSocketsAllowed)
return false;
/* We need to stop sending if it has been a long time since
the last listen call, at least for systems such as Windows that
don't give us a proper pcap time. Also for connect scans, since
we don't get an exact response time with them either. */
recentsends = USI->gstats->probes_sent - USI->gstats->probes_sent_at_last_wait;
if (recentsends > 0 &&
(USI->scantype == CONNECT_SCAN || USI->ptech.connecttcpscan || !pcap_recv_timeval_valid())) {
int to_ms = (int) MAX(to.srtt * .75 / 1000, 50);
if (TIMEVAL_MSEC_SUBTRACT(USI->now, last_wait) > to_ms)
return false;
}
/* Enforce a maximum scanning rate, if necessary. If it's too early to send,
return false. If not, mark now as a good time to send and allow the
congestion control to override it. */
if (o.max_packet_send_rate != 0.0) {
if (TIMEVAL_SUBTRACT(send_no_earlier_than, USI->now) > 0) {
if (when)
*when = send_no_earlier_than;
return false;
} else {
if (when)
*when = USI->now;
}
}
/* Enforce a minimum scanning rate, if necessary. If we're ahead of schedule,
record the time of the next scheduled send and submit to congestion
control. If we're behind schedule, return true to indicate that we need to
send right now. */
if (o.min_packet_send_rate != 0.0) {
if (TIMEVAL_SUBTRACT(send_no_later_than, USI->now) > 0) {
if (when)
*when = send_no_later_than;
} else {
if (when)
*when = USI->now;
return true;
}
}
/* There are good arguments for limiting the number of probes sent
between waits even when we do get appropriate receive times. For
example, overflowing the pcap receive buffer with responses is no
fun. On one of my Linux boxes, it seems to hold about 113
responses when I scan localhost. And half of those are the @#$#
sends being received. I think I'll put a limit of 50 sends per
wait */
if (recentsends >= 50)
return false;
/* In case the user specifically asked for no group congestion control */
if (o.nogcc) {
if (when)
*when = USI->now;
return true;
}
/* When there is only one target left, let the host congestion
stuff deal with it. */
if (USI->numIncompleteHostsLessThan(2)) {
if (when)
*when = USI->now;
return true;
}
if (timing.cwnd >= num_probes_active + 0.5) {
if (when)
*when = USI->now;
return true;
}
return false;
}
/* Return true if pingprobe is an appropriate ping probe for the currently
running scan. Because ping probes persist between host discovery and port
scanning stages, it's possible to have a ping probe that is not relevant for
the scan type, or won't be caught by the pcap filters. Examples of
inappropriate ping probes are an ARP ping for a TCP scan, or a raw SYN ping
for a connect scan. */
static bool pingprobe_is_appropriate(const UltraScanInfo *USI,
const probespec *pingprobe) {
switch (pingprobe->type) {
case(PS_NONE):
return true;
case(PS_CONNECTTCP):
return USI->scantype == CONNECT_SCAN || (USI->ping_scan && USI->ptech.connecttcpscan);
case(PS_TCP):
case(PS_UDP):
case(PS_SCTP):
return (USI->tcp_scan && USI->scantype != CONNECT_SCAN) ||
USI->udp_scan ||
USI->sctp_scan ||
(USI->ping_scan && (USI->ptech.rawtcpscan || USI->ptech.rawudpscan || USI->ptech.rawsctpscan));
case(PS_PROTO):
return USI->prot_scan || (USI->ping_scan && USI->ptech.rawprotoscan);
case(PS_ICMP):
return ((USI->ping_scan && !USI->ping_scan_arp ) || pingprobe->pd.icmp.type == 3);
case(PS_ARP):
return USI->ping_scan_arp;
case(PS_ND):
return USI->ping_scan_nd;
}
return false;
}
HostScanStats::HostScanStats(Target *t, UltraScanInfo *UltraSI) {
target = t;
USI = UltraSI;
next_portidx = 0;
sent_arp = false;
next_ackportpingidx = 0;
next_synportpingidx = 0;
next_udpportpingidx = 0;
next_sctpportpingidx = 0;
next_protoportpingidx = 0;
sent_icmp_ping = false;
sent_icmp_mask = false;
sent_icmp_ts = false;
retry_capped_warned = false;
num_probes_active = 0;
num_probes_waiting_retransmit = 0;
lastping_sent = lastprobe_sent = lastrcvd = USI->now;
lastping_sent_numprobes = 0;
nxtpseq = 1;
max_successful_tryno = 0;
tryno_mayincrease = true;
ports_finished = 0;
numprobes_sent = 0;
memset(&completiontime, 0, sizeof(completiontime));
init_ultra_timing_vals(&timing, TIMING_HOST, 1, &(USI->perf), &USI->now);
bench_tryno = 0;
memset(&sdn, 0, sizeof(sdn));
sdn.last_boost = USI->now;
sdn.delayms = o.scan_delay;
rld.max_tryno_sent = 0;
rld.rld_waiting = false;
rld.rld_waittime = USI->now;
if (!pingprobe_is_appropriate(USI, &target->pingprobe)) {
if (o.debugging > 1)
log_write(LOG_STDOUT, "%s pingprobe type %s is inappropriate for this scan type; resetting.\n", target->targetipstr(), pspectype2ascii(target->pingprobe.type));
memset(&target->pingprobe, 0, sizeof(target->pingprobe));
target->pingprobe_state = PORT_UNKNOWN;
}
}
HostScanStats::~HostScanStats() {
std::list<UltraProbe *>::iterator probeI, next;
/* Move any hosts from the bench to probes_outstanding for easier deletion */
for (probeI = probes_outstanding.begin(); probeI != probes_outstanding.end();
probeI = next) {
next = probeI;
next++;
destroyOutstandingProbe(probeI);
}
}
/* Called whenever a probe is sent to this host. Takes care of updating scan
delay and rate limiting variables. */
void HostScanStats::probeSent(unsigned int nbytes) {
lastprobe_sent = USI->now;
/* Update group variables. */
USI->gstats->probeSent(nbytes);
}
/* How long I am currently willing to wait for a probe response before
considering it timed out. Uses the host values from target if they
are available, otherwise from gstats. Results returned in
MICROseconds. */
unsigned long HostScanStats::probeTimeout() {
if (target->to.srtt > 0) {
/* We have at least one timing value to use. Good enough, I suppose */
return target->to.timeout;
} else if (USI->gstats->to.srtt > 0) {
/* OK, we'll use this one instead */
return USI->gstats->to.timeout;
} else {
return target->to.timeout; /* It comes with a default */
}
}
/* How long I'll wait until completely giving up on a probe.
Timedout probes are often marked as such (and sometimes
considered a drop), but kept in the list just in case they come
really late. But after probeExpireTime(), I don't waste time
keeping them around. Give in MICROseconds. The expiry time can
depend on the type of probe. Pass NULL to get the default time. */
unsigned long HostScanStats::probeExpireTime(const UltraProbe *probe) {
if (probe == NULL || probe->type == UltraProbe::UP_CONNECT)
/* timedout probes close socket -- late resp. impossible */
return probeTimeout();
else
/* Wait a bit longer after probeTimeout. */
return MIN(10000000, probeTimeout() * 10);
}
/* Returns OK if sending a new probe to this host is OK (to avoid
flooding). If when is non-NULL, fills it with the time that sending
will be OK assuming no pending probes are resolved by responses
(call it again if they do). when will become now if it returns
true. */
bool HostScanStats::sendOK(struct timeval *when) {
struct ultra_timing_vals tmng;
std::list<UltraProbe *>::iterator probeI;
struct timeval probe_to, earliest_to, sendTime;
long tdiff;
if (target->timedOut(&USI->now) || completed()) {
if (when)
*when = USI->now;
return false;
}
/* If the group stats say we need to send a probe to enforce a minimum
scanning rate, then we need to step up and send a probe. */
if (o.min_packet_send_rate != 0.0) {
if (TIMEVAL_SUBTRACT(USI->gstats->send_no_later_than, USI->now) <= 0) {
if (when)
*when = USI->now;
return true;
}
}
if (rld.rld_waiting) {
if (TIMEVAL_AFTER(rld.rld_waittime, USI->now)) {
if (when)
*when = rld.rld_waittime;
return false;
} else {
if (when)
*when = USI->now;
return true;
}
}
if (sdn.delayms) {
if (TIMEVAL_MSEC_SUBTRACT(USI->now, lastprobe_sent) < (int) sdn.delayms) {
if (when) {
TIMEVAL_MSEC_ADD(*when, lastprobe_sent, sdn.delayms);
}
return false;
}
}
getTiming(&tmng);
if (tmng.cwnd >= num_probes_active + .5 &&
(freshPortsLeft() || num_probes_waiting_retransmit || !retry_stack.empty())) {
if (when)
*when = USI->now;
return true;
}
if (!when)
return false;
TIMEVAL_MSEC_ADD(earliest_to, USI->now, 10000);
// Any timeouts coming up?
for (probeI = probes_outstanding.begin(); probeI != probes_outstanding.end();
probeI++) {
if (!(*probeI)->timedout) {
TIMEVAL_MSEC_ADD(probe_to, (*probeI)->sent, probeTimeout() / 1000);
if (TIMEVAL_SUBTRACT(probe_to, earliest_to) < 0) {
earliest_to = probe_to;
}
}
}
// Will any scan delay affect this?
if (sdn.delayms) {
TIMEVAL_MSEC_ADD(sendTime, lastprobe_sent, sdn.delayms);
if (TIMEVAL_BEFORE(sendTime, USI->now))
sendTime = USI->now;
tdiff = TIMEVAL_MSEC_SUBTRACT(earliest_to, sendTime);
/* Timeouts previous to the sendTime requirement are pointless,
and those later than sendTime are not needed if we can send a
new packet at sendTime */
if (tdiff < 0) {
earliest_to = sendTime;
} else {
getTiming(&tmng);
if (tdiff > 0 && tmng.cwnd > num_probes_active + .5) {
earliest_to = sendTime;
}
}
}
*when = earliest_to;
return false;
}
/* If there are pending probe timeouts, fills in when with the time of
the earliest one and returns true. Otherwise returns false and
puts now in when. */
bool HostScanStats::nextTimeout(struct timeval *when) {
struct timeval probe_to, earliest_to;
std::list<UltraProbe *>::iterator probeI;
bool firstgood = true;
assert(when);
memset(&probe_to, 0, sizeof(probe_to));
memset(&earliest_to, 0, sizeof(earliest_to));
for (probeI = probes_outstanding.begin(); probeI != probes_outstanding.end();
probeI++) {
if (!(*probeI)->timedout) {
TIMEVAL_ADD(probe_to, (*probeI)->sent, probeTimeout());
if (firstgood || TIMEVAL_SUBTRACT(probe_to, earliest_to) < 0) {
earliest_to = probe_to;
firstgood = false;
}
}
}
*when = (firstgood) ? USI->now : earliest_to;
return !firstgood;
}
/* gives the maximum try number (try numbers start at zero and
increments for each retransmission) that may be used, based on
the scan type, observed network reliability, timing mode, etc.
This may change during the scan based on network traffic. If
capped is not null, it will be filled with true if the tryno is
at its upper limit. That often calls for a warning to be issued,
and marking of remaining timedout ports firewalled or whatever is
appropriate. If mayincrease is non-NULL, it is set to whether
the allowedTryno may increase again. If it is false, any probes
which have reached the given limit may be dealt with. */
unsigned int HostScanStats::allowedTryno(bool *capped, bool *mayincrease) {
std::list<UltraProbe *>::iterator probeI;
UltraProbe *probe = NULL;
bool allfinished = true;
unsigned int maxval = 0;
/* TODO: This should perhaps differ by scan type. */
maxval = MAX(1, max_successful_tryno + 1);
if (maxval > USI->perf.tryno_cap) {
if (capped)
*capped = true;
maxval = USI->perf.tryno_cap;
tryno_mayincrease = false; /* It never exceeds the cap */
} else if (capped) *capped = false;
/* Decide if the tryno can possibly increase. */
if (tryno_mayincrease && num_probes_active == 0 && freshPortsLeft() == 0) {
/* If every outstanding probe is timedout and at maxval, then no further
retransmits are necessary. */
for (probeI = probes_outstanding.begin();
probeI != probes_outstanding.end(); probeI++) {
probe = *probeI;
assert(probe->timedout);
if (!probe->retransmitted && !probe->isPing() && probe->tryno < maxval) {
/* Needs at least one more retransmit. */
allfinished = false;
break;
}
}
if (allfinished)
tryno_mayincrease = false;
}
if (mayincrease)
*mayincrease = tryno_mayincrease;
return maxval;
}
UltraScanInfo::UltraScanInfo() {
}
UltraScanInfo::~UltraScanInfo() {
std::multiset<HostScanStats *, HssPredicate>::iterator hostI;
for (hostI = incompleteHosts.begin(); hostI != incompleteHosts.end(); hostI++) {
delete *hostI;
}
for (hostI = completedHosts.begin(); hostI != completedHosts.end(); hostI++) {
delete *hostI;
}
incompleteHosts.clear();
completedHosts.clear();
delete gstats;
delete SPM;
if (rawsd >= 0) {
close(rawsd);
rawsd = -1;
}
if (pd) {
pcap_close(pd);
pd = NULL;
}
if (ethsd) {
ethsd = NULL; /* NO need to eth_close it due to caching */
}
}
/* Returns true if this scan is a "raw" scan. A raw scan is ont that requires a
raw socket or ethernet handle to send, or a pcap sniffer to receive.
Basically, any scan type except pure TCP connect scans are raw. */
bool UltraScanInfo::isRawScan() {
return scantype != CONNECT_SCAN
&& (tcp_scan || udp_scan || sctp_scan || prot_scan || ping_scan_arp || ping_scan_nd
|| (ping_scan && (ptech.rawicmpscan || ptech.rawtcpscan || ptech.rawudpscan
|| ptech.rawsctpscan || ptech.rawprotoscan)));
}
/* A circular buffer of the incompleteHosts. nextIncompleteHost() gives
the next one. The first time it is called, it will give the
first host in the list. If incompleteHosts is empty, returns
NULL. */
HostScanStats *UltraScanInfo::nextIncompleteHost() {
HostScanStats *nxt;
if (incompleteHosts.empty())
return NULL;
nxt = *nextI;
nextI++;
if (nextI == incompleteHosts.end())
nextI = incompleteHosts.begin();
return nxt;
}
/* Return a number between 0.0 and 1.0 inclusive indicating how much of the scan
is done. */
double UltraScanInfo::getCompletionFraction() {
std::multiset<HostScanStats *, HssPredicate>::iterator hostI;
double total;
/* Add 1 for each completed host. */
total = gstats->numtargets - numIncompleteHosts();
/* Get the completion fraction for each incomplete host. */
for (hostI = incompleteHosts.begin(); hostI != incompleteHosts.end(); hostI++) {
HostScanStats *host = *hostI;
int maxtries = host->allowedTryno(NULL, NULL) + 1;
double thishostpercdone;
// This is inexact (maxtries - 1) because numprobes_sent includes
// at least one try of ports_finished.
thishostpercdone = host->ports_finished * (maxtries - 1) + host->numprobes_sent;
thishostpercdone /= maxtries * gstats->numprobes;
if (thishostpercdone >= 0.9999)
thishostpercdone = 0.9999;
total += thishostpercdone;
}
return total / gstats->numtargets;
}
/* Initialize the state for ports that don't receive a response in all the
targets. */
static void set_default_port_state(std::vector<Target *> &targets, stype scantype) {
std::vector<Target *>::iterator target;
for (target = targets.begin(); target != targets.end(); target++) {
switch (scantype) {
case SYN_SCAN:
case ACK_SCAN:
case WINDOW_SCAN:
case CONNECT_SCAN:
(*target)->ports.setDefaultPortState(IPPROTO_TCP, PORT_FILTERED);
break;
case SCTP_INIT_SCAN:
(*target)->ports.setDefaultPortState(IPPROTO_SCTP, PORT_FILTERED);
break;
case NULL_SCAN:
case FIN_SCAN:
case MAIMON_SCAN:
case XMAS_SCAN:
(*target)->ports.setDefaultPortState(IPPROTO_TCP, PORT_OPENFILTERED);
break;
case UDP_SCAN:
(*target)->ports.setDefaultPortState(IPPROTO_UDP,
o.defeat_icmp_ratelimit ? PORT_CLOSEDFILTERED : PORT_OPENFILTERED);
break;
case IPPROT_SCAN:
(*target)->ports.setDefaultPortState(IPPROTO_IP, PORT_OPENFILTERED);
break;
case SCTP_COOKIE_ECHO_SCAN:
(*target)->ports.setDefaultPortState(IPPROTO_SCTP, PORT_OPENFILTERED);
break;
case PING_SCAN:
case PING_SCAN_ARP:
case PING_SCAN_ND:
break;
default:
fatal("Unexpected scan type found in %s()", __func__);
}
}
}
/* Order of initializations in this function CAN BE IMPORTANT, so be careful
mucking with it. */
void UltraScanInfo::Init(std::vector<Target *> &Targets, struct scan_lists *pts, stype scantp) {
unsigned int targetno = 0;
HostScanStats *hss;
int num_timedout = 0;
gettimeofday(&now, NULL);
ports = pts;
seqmask = get_random_u32();
scantype = scantp;
SPM = new ScanProgressMeter(scantype2str(scantype));
send_rate_meter.start(&now);
tcp_scan = udp_scan = sctp_scan = prot_scan = false;
ping_scan = noresp_open_scan = ping_scan_arp = ping_scan_nd = false;
memset((char *) &ptech, 0, sizeof(ptech));
switch (scantype) {
case FIN_SCAN:
case XMAS_SCAN:
case MAIMON_SCAN:
case NULL_SCAN:
noresp_open_scan = true;
case ACK_SCAN:
case CONNECT_SCAN:
case SYN_SCAN:
case WINDOW_SCAN:
tcp_scan = true;
break;
case UDP_SCAN:
noresp_open_scan = true;
udp_scan = true;
break;
case SCTP_INIT_SCAN:
case SCTP_COOKIE_ECHO_SCAN:
sctp_scan = true;
break;
case IPPROT_SCAN:
noresp_open_scan = true;
prot_scan = true;
break;
case PING_SCAN:
ping_scan = true;
/* What kind of pings are we doing? */
if (o.pingtype & (PINGTYPE_ICMP_PING | PINGTYPE_ICMP_MASK | PINGTYPE_ICMP_TS))
ptech.rawicmpscan = 1;
if (o.pingtype & PINGTYPE_UDP)
ptech.rawudpscan = 1;
if (o.pingtype & PINGTYPE_SCTP_INIT)
ptech.rawsctpscan = 1;
if (o.pingtype & PINGTYPE_TCP) {
if (o.isr00t)
ptech.rawtcpscan = 1;
else
ptech.connecttcpscan = 1;
}
if (o.pingtype & PINGTYPE_PROTO)
ptech.rawprotoscan = 1;
if (o.pingtype & PINGTYPE_CONNECTTCP)
ptech.connecttcpscan = 1;
break;
case PING_SCAN_ARP:
ping_scan = true;
ping_scan_arp = true;
break;
case PING_SCAN_ND:
ping_scan = true;
ping_scan_nd = true;
break;
default:
break;
}
set_default_port_state(Targets, scantype);
perf.init();
/* Keep a completed host around for a standard TCP MSL (2 min) */
completedHostLifetime = 120000;
memset(&lastCompletedHostRemoval, 0, sizeof(lastCompletedHostRemoval));
for (targetno = 0; targetno < Targets.size(); targetno++) {
if (Targets[targetno]->timedOut(&now)) {
num_timedout++;
continue;
}
hss = new HostScanStats(Targets[targetno], this);
incompleteHosts.insert(hss);
}
numInitialTargets = Targets.size();
nextI = incompleteHosts.begin();
gstats = new GroupScanStats(this); /* Peeks at several elements in USI - careful of order */
gstats->num_hosts_timedout += num_timedout;
pd = NULL;
rawsd = -1;
ethsd = NULL;