-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscan_engine.cc
2846 lines (2584 loc) · 102 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-2024 Nmap Software LLC ("The Nmap
* Project"). Nmap is also a registered trademark of the Nmap Project.
*
* This program is distributed under the terms of the Nmap Public Source
* License (NPSL). The exact license text applying to a particular Nmap
* release or source code control revision is contained in the LICENSE
* file distributed with that version of Nmap or source code control
* revision. More Nmap copyright/legal information is available from
* https://nmap.org/book/man-legal.html, and further information on the
* NPSL license itself can be found at https://nmap.org/npsl/ . This
* header summarizes some key points from the Nmap license, but is no
* substitute for the actual license text.
*
* Nmap is generally free for end users to download and use themselves,
* including commercial use. It is available from https://nmap.org.
*
* The Nmap license generally prohibits companies from using and
* redistributing Nmap in commercial products, but we sell a special Nmap
* OEM Edition with a more permissive license and special features for
* this purpose. See https://nmap.org/oem/
*
* If you have received a written Nmap license agreement or contract
* stating terms other than these (such as an Nmap OEM license), you may
* choose to use and redistribute Nmap under those terms instead.
*
* The official Nmap Windows builds include the Npcap software
* (https://npcap.com) for packet capture and transmission. It is under
* separate license terms which forbid redistribution without special
* permission. So the official Nmap Windows builds may not be redistributed
* without special permission (such as an Nmap OEM license).
*
* 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 submit your changes as a
* Github PR or by email to the [email protected] mailing list for possible
* incorporation into the main distribution. Unless you specify otherwise, it
* is understood that you are offering us very broad rights to use your
* submissions as described in the Nmap Public Source License Contributor
* Agreement. This is important because we fund the project by selling licenses
* with various terms, and also because the inability to relicense code has
* caused devastating problems for other Free Software projects (such as KDE
* and NASM).
*
* The free version of Nmap 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. Warranties,
* indemnification and commercial support are all available through the
* Npcap OEM program--see https://nmap.org/oem/
*
***************************************************************************/
/* $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
/* How long extra to wait before retransmitting for rate-limit detection */
#define RLD_TIME_MS 1000
/* Keep a completed host around for a standard TCP MSL (2 min) */
#define COMPL_HOST_LIFETIME_MS 120000
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);
}
const struct sockaddr_storage *HssPredicate::ss = NULL;
void UltraScanInfo::log_overall_rates(int logt) const {
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,
const struct ultra_scan_performance_vars *perf,
const 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.opaque = 0;
timedout = false;
retransmitted = false;
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 timeout should be much lower for arp */
if (USI->ping_scan_arp)
to.timeout = box(o.minRttTimeout(), 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. */
static time_t max_rate_add = o.max_packet_send_rate != 0.0 ?
(1000000.0 / o.max_packet_send_rate) : 0;
static time_t min_rate_add = o.min_packet_send_rate != 0.0 ?
(1000000.0 / o.min_packet_send_rate) : 0;
if (o.max_packet_send_rate != 0.0)
TIMEVAL_ADD(send_no_earlier_than, send_no_earlier_than, max_rate_add);
/* 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_AFTER(send_no_later_than, USI->now)) {
/* 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, min_rate_add);
}
}
/* Returns true if the GLOBAL system says that sending is OK.*/
bool GroupScanStats::sendOK(struct timeval *when) const {
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 (CSI && !CSI->sendOK())
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 = MAX(to.srtt * 3 / 4000, 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_AFTER(send_no_earlier_than, USI->now)) {
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_AFTER(send_no_later_than, USI->now)) {
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->numIncompleteHosts() < 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;
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;
sdn.maxdelay = USI->tcp_scan ? o.maxTCPScanDelay() :
USI->udp_scan ? o.maxUDPScanDelay() :
o.maxSCTPScanDelay();
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() const {
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. */
unsigned long HostScanStats::probeExpireTime(const UltraProbe *probe,
unsigned long to_us) const {
if (probe->type == UltraProbe::UP_CONNECT)
/* timedout probes close socket -- late resp. impossible */
return to_us;
else
/* Wait a bit longer after probeTimeout. */
return 10 * MIN(1000000, to_us);
}
/* 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) const {
struct ultra_timing_vals tmng;
std::list<UltraProbe *>::const_iterator probeI;
struct timeval probe_to, earliest_to, sendTime;
long tdiff;
if ((!USI->ping_scan && 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_AFTER(USI->gstats->send_no_later_than, USI->now)) {
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?
unsigned long msec_to = probeTimeout() / 1000;
for (probeI = probes_outstanding.begin(); probeI != probes_outstanding.end();
probeI++) {
if (!(*probeI)->timedout) {
TIMEVAL_MSEC_ADD(probe_to, (*probeI)->sent, msec_to);
if (TIMEVAL_BEFORE(probe_to, earliest_to)) {
earliest_to = probe_to;
}
// probes_outstanding is in order by time sent, so
// the first one we find is the earliest.
break;
}
}
// 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, compares the earliest one with `when`;
if it is earlier than `when`, replaces `when` with the time of
the earliest one and returns true. Otherwise returns false. */
bool HostScanStats::soonerTimeout(struct timeval *when) const {
std::list<UltraProbe *>::const_iterator probeI, endI;
/* For any given invocation, the probe timeout is the same for all probes, so
* we can get the earliest-sent probe and then add the timeout to that.
*/
for (probeI = probes_outstanding.begin(), endI = probes_outstanding.end();
probeI != endI; probeI++) {
UltraProbe *probe = *probeI;
if (!probe->timedout) {
unsigned long usec_to = probeTimeout();
struct timeval our_when;
TIMEVAL_ADD(our_when, probe->sent, usec_to);
// probes_outstanding is in order by time sent, so
// the first one we find is the earliest.
if (TIMEVAL_BEFORE(our_when, *when)) {
// If ours is earlier, replace when.
*when = our_when;
return true;
}
// regardless, there are no earlier probes, so stop looking.
break;
}
}
return false;
}
/* 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) const {
std::list<UltraProbe *>::const_iterator probeI;
UltraProbe *probe = NULL;
bool allfinished = true;
bool tryno_mayincrease = 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;
// Only do this work if the caller needs to know
if (mayincrease) {
/* Decide if the tryno can possibly increase. */
if (tryno_mayincrease && num_probes_active == 0 && !freshPortsLeft()) {
/* 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->get_tryno() < maxval) {
/* Needs at least one more retransmit. */
allfinished = false;
break;
}
}
if (allfinished)
tryno_mayincrease = false;
}
*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() const {
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() const {
std::multiset<HostScanStats *, HssPredicate>::const_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++) {
const 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, const 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));
perf.init();
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;
/* For ARP and ND scan, we send pings more frequently. Otherwise we can't
* notice drops until we start sending retransmits after RLD_TIME_MS. */
perf.pingtime = RLD_TIME_MS * 1000 / 4;
break;
case PING_SCAN_ND:
ping_scan = true;
ping_scan_nd = true;
perf.pingtime = RLD_TIME_MS * 1000 / 4;
break;
default:
break;
}
set_default_port_state(Targets, scantype);
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;
/* See if we need an ethernet handle or raw socket. Basically, it's if we
aren't doing a TCP connect scan, or if we're doing a ping scan that
requires it. */
if (isRawScan()) {
if (ping_scan_arp || (ping_scan_nd && o.sendpref != PACKET_SEND_IP_STRONG) || ((o.sendpref & PACKET_SEND_ETH) &&
(Targets[0]->ifType() == devt_ethernet
#ifdef WIN32
|| (g_has_npcap_loopback && Targets[0]->ifType() == devt_loopback)
#endif
))) {
/* We'll send ethernet packets with dnet */
ethsd = eth_open_cached(Targets[0]->deviceName());
if (ethsd == NULL)
fatal("dnet: Failed to open device %s", Targets[0]->deviceName());
rawsd = -1;
} else {
#ifdef WIN32
win32_fatal_raw_sockets(Targets[0]->deviceName());
#endif
rawsd = nmap_raw_socket();
if (rawsd < 0)
pfatal("Couldn't open a raw socket. "
#if defined(sun) && defined(__SVR4)
"In Solaris shared-IP non-global zones, this requires the PRIV_NET_RAWACCESS privilege. "
#endif
"Error"
);
/* We do not want to unblock the socket since we want to wait
if kernel send buffers fill up rather than get ENOBUF, and
we won't be receiving on the socket anyway
unblock_socket(rawsd);*/
ethsd = NULL;
}
/* Raw scan types also need to know the source IP. */
Targets[0]->SourceSockAddr(&sourceSockAddr, NULL);
}
base_port = UltraScanInfo::increment_base_port();
}
/* Return the total number of probes that may be sent to each host. This never
changes after initialization. */
unsigned int UltraScanInfo::numProbesPerHost() const {
unsigned int numprobes = 0;
if (tcp_scan) {
numprobes = ports->tcp_count;
} else if (udp_scan) {
numprobes = ports->udp_count;
} else if (sctp_scan) {