forked from nmap/nmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathosscan2.cc
3749 lines (3146 loc) · 112 KB
/
osscan2.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
/***************************************************************************
* osscan2.cc -- Routines used for 2nd Generation OS detection via *
* TCP/IP fingerprinting. * For more information on how this works in *
* Nmap, see https://nmap.org/osdetect/ *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2020 Insecure.Com 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.org) 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$ */
#include "osscan.h"
#include "osscan2.h"
#include "timing.h"
#include "NmapOps.h"
#include "tcpip.h"
#include "Target.h"
#include "utils.h"
#include "nmap_error.h"
#include "FPEngine.h"
#include "FingerPrintResults.h"
#include <dnet.h>
#include "struct_ip.h"
#include "string_pool.h"
#include <list>
#include <math.h>
extern NmapOps o;
#ifdef WIN32
/* from libdnet's intf-win32.c */
extern "C" int g_has_npcap_loopback;
#endif
/* 8 options:
* 0~5: six options for SEQ/OPS/WIN/T1 probes.
* 6: ECN probe.
* 7-12: T2~T7 probes.
*
* option 0: WScale (10), Nop, MSS (1460), Timestamp, SackP
* option 1: MSS (1400), WScale (0), SackP, T(0xFFFFFFFF,0x0), EOL
* option 2: T(0xFFFFFFFF, 0x0), Nop, Nop, WScale (5), Nop, MSS (640)
* option 3: SackP, T(0xFFFFFFFF,0x0), WScale (10), EOL
* option 4: MSS (536), SackP, T(0xFFFFFFFF,0x0), WScale (10), EOL
* option 5: MSS (265), SackP, T(0xFFFFFFFF,0x0)
* option 6: WScale (10), Nop, MSS (1460), SackP, Nop, Nop
* option 7-11: WScale (10), Nop, MSS (265), T(0xFFFFFFFF,0x0), SackP
* option 12: WScale (15), Nop, MSS (265), T(0xFFFFFFFF,0x0), SackP
*/
static struct {
u8* val;
int len;
} prbOpts[] = {
{(u8*) "\x03\x03\x0A\x01\x02\x04\x05\xb4\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
{(u8*) "\x02\x04\x05\x78\x03\x03\x00\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x00", 20},
{(u8*) "\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x01\x01\x03\x03\x05\x01\x02\x04\x02\x80", 20},
{(u8*) "\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x03\x03\x0A\x00", 16},
{(u8*) "\x02\x04\x02\x18\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x03\x03\x0A\x00", 20},
{(u8*) "\x02\x04\x01\x09\x04\x02\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00", 16},
{(u8*) "\x03\x03\x0A\x01\x02\x04\x05\xb4\x04\x02\x01\x01", 12},
{(u8*) "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
{(u8*) "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
{(u8*) "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
{(u8*) "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
{(u8*) "\x03\x03\x0A\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20},
{(u8*) "\x03\x03\x0f\x01\x02\x04\x01\x09\x08\x0A\xff\xff\xff\xff\x00\x00\x00\x00\x04\x02", 20}
};
/* TCP Window sizes. Numbering is the same as for prbOpts[] */
u16 prbWindowSz[] = { 1, 63, 4, 4, 16, 512, 3, 128, 256, 1024, 31337, 32768, 65535 };
/* Current time. It is globally accessible so it can save calls to gettimeofday() */
static struct timeval now;
/* Global to store performance info */
static struct scan_performance_vars perf;
/******************************************************************************
* Miscellaneous functions *
******************************************************************************/
/* Fill in a struct AVal with a value based on the IP ID sequence generation
class (one of the IPID_SEQ_* constants). If ipid_seqclass is such that the
test result should be omitted, the function returns NULL and doesn't modify
*av. Otherwise, it returns av after filling in the information. */
static struct AVal *make_aval_ipid_seq(struct AVal *av, const char *attribute,
int ipid_seqclass, u32 ipids[NUM_SEQ_SAMPLES]) {
switch (ipid_seqclass) {
case IPID_SEQ_CONSTANT:
av->value = string_pool_sprintf("%X", ipids[0]);
break;
case IPID_SEQ_INCR_BY_2:
case IPID_SEQ_INCR:
av->value = "I";
break;
case IPID_SEQ_BROKEN_INCR:
av->value = "BI";
break;
case IPID_SEQ_RPI:
av->value = "RI";
break;
case IPID_SEQ_RD:
av->value = "RD";
break;
case IPID_SEQ_ZERO:
av->value = "Z";
break;
default:
/* Signal to omit test result. */
return NULL;
break;
}
av->attribute = string_pool_insert(attribute);
return av;
}
/* Returns a guess about the original TTL based on an observed TTL value.
* This function assumes that the target from which we received the packet was
* less than 32 hops away. Also, note that although some systems use an
* initial TTL of 60, this function rounds that to 64, as both values
* cannot be reliably distinguished based on a simple observed hop count. */
int get_initial_ttl_guess(u8 ttl) {
if (ttl <= 32)
return 32;
else if (ttl <= 64)
return 64;
else if (ttl <= 128)
return 128;
else
return 255;
}
/* This function takes an array of "numSamples" IP IDs and analyzes
them to determine their sequence classification. It returns
one of the IPID_SEQ_* classifications defined in nmap.h . If the
function cannot determine the sequence, IPID_SEQ_UNKNOWN is returned.
This islocalhost argument is a boolean specifying whether these
numbers were generated by scanning localhost. */
int identify_sequence(int numSamples, u32 *ipid_diffs, int islocalhost) {
int i, j, k, l;
if (islocalhost) {
int allgto = 1; /* ALL diffs greater than one */
for (i = 0; i < numSamples - 1; i++) {
if (ipid_diffs[i] < 2) {
allgto = 0; break;
}
}
if (allgto) {
for (i = 0; i < numSamples - 1; i++) {
if (ipid_diffs[i] % 256 == 0) /* Stupid MS */
ipid_diffs[i] -= 256;
else
ipid_diffs[i]--; /* Because on localhost the RST sent back use an IPID */
}
}
}
/* Constant */
j = 1; /* j is a flag meaning "all differences seen are zero" */
for (i = 0; i < numSamples - 1; i++) {
if (ipid_diffs[i] != 0) {
j = 0;
break;
}
}
if (j) {
return IPID_SEQ_CONSTANT;
}
/* Random Positive Increments */
for (i = 0; i < numSamples - 1; i++) {
if (ipid_diffs[i] > 1000 &&
(ipid_diffs[i] % 256 != 0 ||
(ipid_diffs[i] % 256 == 0 && ipid_diffs[i] >= 25600))) {
return IPID_SEQ_RPI;
}
}
j = 1; /* j is a flag meaning "all differences seen are < 10" */
k = 1; /* k is a flag meaning "all difference seen are multiples of 256 and
* no greater than 5120" */
l = 1; /* l is a flag meaning "all differences are multiples of 2" */
for (i = 0; i < numSamples - 1; i++) {
if (k && (ipid_diffs[i] > 5120 || ipid_diffs[i] % 256 != 0)) {
k = 0;
}
if (l && ipid_diffs[i] % 2 != 0) {
l = 0;
}
if (j && ipid_diffs[i] > 9) {
j = 0;
}
}
/* Broken Increment */
if (k == 1) {
return IPID_SEQ_BROKEN_INCR;
}
/* Incrementing by 2 */
if (l == 1)
return IPID_SEQ_INCR_BY_2;
/* Incremental by 1 */
if (j == 1)
return IPID_SEQ_INCR;
return IPID_SEQ_UNKNOWN;
}
/* Calculate the distances between the ipids and write them
into the ipid_diffs array. If the sequence class can be determined
immediately, return it; otherwise return -1 */
int get_diffs(u32 *ipid_diffs, int numSamples, const u32 *ipids, int islocalhost) {
int i;
bool allipideqz = true;
if (numSamples < 2)
return IPID_SEQ_UNKNOWN;
for (i = 1; i < numSamples; i++) {
if (ipids[i - 1] != 0 || ipids[i] != 0)
allipideqz = false; /* All IP.ID values do *NOT* equal zero */
ipid_diffs[i - 1] = ipids[i] - ipids[i - 1];
/* Random */
if (numSamples > 2 && ipid_diffs[i - 1] > 20000)
return IPID_SEQ_RD;
}
if (allipideqz) {
return IPID_SEQ_ZERO;
}
else {
return -1;
}
}
/* Indentify the ipid sequence for 32-bit IPID values (IPv6) */
int get_ipid_sequence_32(int numSamples, const u32 *ipids, int islocalhost) {
int ipid_seq = IPID_SEQ_UNKNOWN;
u32 ipid_diffs[32];
assert(numSamples < (int) (sizeof(ipid_diffs) / 2));
ipid_seq = get_diffs(ipid_diffs, numSamples, ipids, islocalhost);
if (ipid_seq < 0) {
return identify_sequence(numSamples, ipid_diffs, islocalhost);
}
else {
return ipid_seq;
}
}
/* Indentify the ipid sequence for 16-bit IPID values (IPv4) */
int get_ipid_sequence_16(int numSamples, const u32 *ipids, int islocalhost) {
int i;
int ipid_seq = IPID_SEQ_UNKNOWN;
u32 ipid_diffs[32];
assert(numSamples < (int) (sizeof(ipid_diffs) / 2));
ipid_seq = get_diffs(ipid_diffs, numSamples, ipids, islocalhost);
/* AND with 0xffff so that in case the 16 bit counter was
* flipped over we still have a continuous sequence */
for (i = 0; i < numSamples; i++) {
ipid_diffs[i] = ipid_diffs[i] & 0xffff;
}
if (ipid_seq < 0) {
return identify_sequence(numSamples, ipid_diffs, islocalhost);
}
else {
return ipid_seq;
}
}
/* Convert a TCP sequence prediction difficulty index like 1264386
into a difficulty string like "Worthy Challenge */
const char *seqidx2difficultystr(unsigned long idx) {
return (idx < 3) ? "Trivial joke" : (idx < 6) ? "Easy" : (idx < 11) ? "Medium" : (idx < 12) ? "Formidable" : (idx < 16) ? "Worthy challenge" : "Good luck!";
}
const char *ipidclass2ascii(int seqclass) {
switch (seqclass) {
case IPID_SEQ_CONSTANT:
return "Duplicated ipid (!)";
case IPID_SEQ_INCR:
return "Incremental";
case IPID_SEQ_INCR_BY_2:
return "Incrementing by 2";
case IPID_SEQ_BROKEN_INCR:
return "Broken little-endian incremental";
case IPID_SEQ_RD:
return "Randomized";
case IPID_SEQ_RPI:
return "Random positive increments";
case IPID_SEQ_ZERO:
return "All zeros";
case IPID_SEQ_UNKNOWN:
return "Busy server or unknown class";
default:
return "ERROR, WTF?";
}
}
const char *tsseqclass2ascii(int seqclass) {
switch (seqclass) {
case TS_SEQ_ZERO:
return "zero timestamp";
case TS_SEQ_2HZ:
return "2HZ";
case TS_SEQ_100HZ:
return "100HZ";
case TS_SEQ_1000HZ:
return "1000HZ";
case TS_SEQ_OTHER_NUM:
return "other";
case TS_SEQ_UNSUPPORTED:
return "none returned (unsupported)";
case TS_SEQ_UNKNOWN:
return "unknown class";
default:
return "ERROR, WTF?";
}
}
/** Sets up the pcap descriptor in HOS (obtains a descriptor and sets the
* appropriate BPF filter, based on the supplied list of targets). */
static void begin_sniffer(HostOsScan *HOS, std::vector<Target *> &Targets) {
char pcap_filter[2048];
/* 20 IPv6 addresses is max (45 byte addy + 14 (" or src host ")) * 20 == 1180 */
char dst_hosts[1200];
int filterlen = 0;
int len;
unsigned int targetno;
bool doIndividual = Targets.size() <= 20; // Don't bother IP limits if scanning huge # of hosts
pcap_filter[0] = '\0';
/* If we have 20 or less targets, build a list of addresses so we can set
* an explicit BPF filter */
if (doIndividual) {
for (targetno = 0; targetno < Targets.size(); targetno++) {
len = Snprintf(dst_hosts + filterlen,
sizeof(dst_hosts) - filterlen,
"%ssrc host %s", (targetno == 0)? "" : " or ",
Targets[targetno]->targetipstr());
if (len < 0 || len + filterlen >= (int) sizeof(dst_hosts))
fatal("ran out of space in dst_hosts");
filterlen += len;
}
len = Snprintf(dst_hosts + filterlen, sizeof(dst_hosts) - filterlen, ")))");
if (len < 0 || len + filterlen >= (int) sizeof(dst_hosts))
fatal("ran out of space in dst_hosts");
}
/* Open a network interface for packet capture */
HOS->pd = my_pcap_open_live(Targets[0]->deviceName(), 8192,
o.spoofsource ? 1 : 0, pcap_selectable_fd_valid() ? 200 : 2);
if (HOS->pd == NULL)
fatal("%s", PCAP_OPEN_ERRMSG);
struct sockaddr_storage ss = Targets[0]->source();
/* Build the final BPF filter */
if (ss.ss_family == AF_INET) {
if (doIndividual)
len = Snprintf(pcap_filter, sizeof(pcap_filter), "dst host %s and (icmp or (tcp and (%s",
inet_ntoa(((struct sockaddr_in *)&ss)->sin_addr), dst_hosts);
else
len = Snprintf(pcap_filter, sizeof(pcap_filter), "dst host %s and (icmp or tcp)",
inet_ntoa(((struct sockaddr_in *)&ss)->sin_addr));
if (len < 0 || len >= (int) sizeof(pcap_filter))
fatal("ran out of space in pcap filter");
/* Compile and apply the filter to the pcap descriptor */
if (o.debugging)
log_write(LOG_PLAIN, "Packet capture filter (device %s): %s\n", Targets[0]->deviceFullName(), pcap_filter);
set_pcap_filter(Targets[0]->deviceFullName(), HOS->pd, pcap_filter);
}
return;
}
/* Sets everything up so the current round can be performed. This includes
* reinitializing some variables of the supplied objects and deleting
* some old information. */
static void startRound(OsScanInfo *OSI, HostOsScan *HOS, int roundNum) {
std::list<HostOsScanInfo *>::iterator hostI;
HostOsScanInfo *hsi = NULL;
/* Reinitial some parameters of the scan system. */
HOS->reInitScanSystem();
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
hsi = *hostI;
if (hsi->FPs[roundNum]) {
delete hsi->FPs[roundNum];
hsi->FPs[roundNum] = NULL;
}
hsi->hss->initScanStats();
}
}
/* Run the sequence generation tests (6 TCP probes sent 100ms apart) */
static void doSeqTests(OsScanInfo *OSI, HostOsScan *HOS) {
std::list<HostOsScanInfo *>::iterator hostI;
HostOsScanInfo *hsi = NULL;
HostOsScanStats *hss = NULL;
unsigned int unableToSend = 0; /* # of times in a row that hosts were unable to send probe */
unsigned int expectReplies = 0;
long to_usec = 0;
int timeToSleep = 0;
struct ip *ip = NULL;
struct link_header linkhdr;
struct sockaddr_storage ss;
unsigned int bytes = 0;
struct timeval rcvdtime;
struct timeval stime;
struct timeval tmptv;
bool timedout = false;
bool thisHostGood = false;
bool foundgood = false;
bool goodResponse = false;
int numProbesLeft = 0;
memset(&stime, 0, sizeof(stime));
memset(&tmptv, 0, sizeof(tmptv));
/* For each host, build a list of sequence probes to send */
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
hsi = *hostI;
hss = hsi->hss;
HOS->buildSeqProbeList(hss);
}
/* Iterate until we have sent all the probes */
do {
if (timeToSleep > 0) {
if (o.debugging > 1)
log_write(LOG_PLAIN, "Sleep %dus for next sequence probe\n", timeToSleep);
usleep(timeToSleep);
}
gettimeofday(&now, NULL);
expectReplies = 0;
unableToSend = 0;
if (o.debugging > 2) {
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
hss = (*hostI)->hss;
log_write(LOG_PLAIN, "Host %s. ProbesToSend %d: \tProbesActive %d\n",
hss->target->targetipstr(), hss->numProbesToSend(),
hss->numProbesActive());
}
}
/* Send a seq probe to each host. */
while (unableToSend < OSI->numIncompleteHosts() && HOS->stats->sendOK()) {
hsi = OSI->nextIncompleteHost();
hss = hsi->hss;
gettimeofday(&now, NULL);
if (hss->numProbesToSend()>0 && HOS->hostSeqSendOK(hss, NULL)) {
HOS->sendNextProbe(hss);
expectReplies++;
unableToSend = 0;
} else {
unableToSend++;
}
}
HOS->stats->num_probes_sent_at_last_wait = HOS->stats->num_probes_sent;
gettimeofday(&now, NULL);
/* Count the pcap wait time. */
if (!HOS->stats->sendOK()) {
TIMEVAL_MSEC_ADD(stime, now, 1000);
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
if (HOS->nextTimeout((*hostI)->hss, &tmptv)) {
if (TIMEVAL_SUBTRACT(tmptv, stime) < 0)
stime = tmptv;
}
}
} else {
foundgood = false;
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
thisHostGood = HOS->hostSeqSendOK((*hostI)->hss, &tmptv);
if (thisHostGood) {
stime = tmptv;
foundgood = true;
break;
}
if (!foundgood || TIMEVAL_SUBTRACT(tmptv, stime) < 0) {
stime = tmptv;
foundgood = true;
}
}
}
do {
to_usec = TIMEVAL_SUBTRACT(stime, now);
if (to_usec < 2000)
to_usec = 2000;
if (o.debugging > 2)
log_write(LOG_PLAIN, "pcap wait time is %ld.\n", to_usec);
ip = (struct ip*) readipv4_pcap(HOS->pd, &bytes, to_usec, &rcvdtime, &linkhdr, true);
gettimeofday(&now, NULL);
if (!ip && TIMEVAL_SUBTRACT(stime, now) < 0) {
timedout = true;
break;
} else if (!ip) {
continue;
}
if (TIMEVAL_SUBTRACT(now, stime) > 200000) {
/* While packets are still being received, I'll be generous and give
an extra 1/5 sec. But we have to draw the line somewhere */
timedout = true;
}
if (bytes < (4 * ip->ip_hl) + 4U)
continue;
memset(&ss, 0, sizeof(ss));
((struct sockaddr_in *) &ss)->sin_addr.s_addr = ip->ip_src.s_addr;
ss.ss_family = AF_INET;
hsi = OSI->findIncompleteHost(&ss);
if (!hsi)
continue; /* Not from one of our targets. */
setTargetMACIfAvailable(hsi->target, &linkhdr, &ss, 0);
goodResponse = HOS->processResp(hsi->hss, ip, bytes, &rcvdtime);
if (goodResponse)
expectReplies--;
} while (!timedout && expectReplies > 0);
/* Remove any timeout hosts during the scan. */
OSI->removeCompletedHosts();
numProbesLeft = 0;
for (hostI = OSI->incompleteHosts.begin();
hostI != OSI->incompleteHosts.end(); hostI++) {
hss = (*hostI)->hss;
HOS->updateActiveSeqProbes(hss);
numProbesLeft += hss->numProbesToSend();
numProbesLeft += hss->numProbesActive();
}
gettimeofday(&now, NULL);
if (expectReplies == 0) {
timeToSleep = TIMEVAL_SUBTRACT(stime, now);
} else {
timeToSleep = 0;
}
} while (numProbesLeft > 0);
}
/* TCP, UDP, ICMP Tests */
static void doTUITests(OsScanInfo *OSI, HostOsScan *HOS) {
std::list<HostOsScanInfo *>::iterator hostI;
HostOsScanInfo *hsi = NULL;
HostOsScanStats *hss = NULL;
unsigned int unableToSend; /* # of times in a row that hosts were unable to send probe */
unsigned int expectReplies;
long to_usec;
int timeToSleep = 0;
struct ip *ip = NULL;
struct link_header linkhdr;
struct sockaddr_storage ss;
unsigned int bytes;
struct timeval rcvdtime;
struct timeval stime, tmptv;
bool timedout = false;
bool thisHostGood;
bool foundgood;
bool goodResponse;
int numProbesLeft = 0;
memset(&stime, 0, sizeof(stime));
memset(&tmptv, 0, sizeof(tmptv));
for (hostI = OSI->incompleteHosts.begin();
hostI != OSI->incompleteHosts.end(); hostI++) {
hsi = *hostI;
hss = hsi->hss;
HOS->buildTUIProbeList(hss);
}
do {
if (timeToSleep > 0) {
if (o.debugging > 1) {
log_write(LOG_PLAIN, "Time to sleep %d. Sleeping. \n", timeToSleep);
}
usleep(timeToSleep);
}
gettimeofday(&now, NULL);
expectReplies = 0;
unableToSend = 0;
if (o.debugging > 2) {
for (hostI = OSI->incompleteHosts.begin();
hostI != OSI->incompleteHosts.end(); hostI++) {
hss = (*hostI)->hss;
log_write(LOG_PLAIN, "Host %s. ProbesToSend %d: \tProbesActive %d\n",
hss->target->targetipstr(), hss->numProbesToSend(),
hss->numProbesActive());
}
}
while (unableToSend < OSI->numIncompleteHosts() && HOS->stats->sendOK()) {
hsi = OSI->nextIncompleteHost();
hss = hsi->hss;
gettimeofday(&now, NULL);
if (hss->numProbesToSend()>0 && HOS->hostSendOK(hss, NULL)) {
HOS->sendNextProbe(hss);
expectReplies++;
unableToSend = 0;
} else {
unableToSend++;
}
}
HOS->stats->num_probes_sent_at_last_wait = HOS->stats->num_probes_sent;
gettimeofday(&now, NULL);
/* Count the pcap wait time. */
if (!HOS->stats->sendOK()) {
TIMEVAL_MSEC_ADD(stime, now, 1000);
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end();
hostI++) {
if (HOS->nextTimeout((*hostI)->hss, &tmptv)) {
if (TIMEVAL_SUBTRACT(tmptv, stime) < 0)
stime = tmptv;
}
}
}
else {
foundgood = false;
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
thisHostGood = HOS->hostSendOK((*hostI)->hss, &tmptv);
if (thisHostGood) {
stime = tmptv;
foundgood = true;
break;
}
if (!foundgood || TIMEVAL_SUBTRACT(tmptv, stime) < 0) {
stime = tmptv;
foundgood = true;
}
}
}
do {
to_usec = TIMEVAL_SUBTRACT(stime, now);
if (to_usec < 2000) to_usec = 2000;
if (o.debugging > 2)
log_write(LOG_PLAIN, "pcap wait time is %ld.\n", to_usec);
ip = (struct ip*) readipv4_pcap(HOS->pd, &bytes, to_usec, &rcvdtime, &linkhdr, true);
gettimeofday(&now, NULL);
if (!ip && TIMEVAL_SUBTRACT(stime, now) < 0) {
timedout = true;
break;
} else if (!ip) {
continue;
}
if (TIMEVAL_SUBTRACT(now, stime) > 200000) {
/* While packets are still being received, I'll be generous and give
an extra 1/5 sec. But we have to draw the line somewhere */
timedout = true;
}
if (bytes < (4 * ip->ip_hl) + 4U)
continue;
memset(&ss, 0, sizeof(ss));
((struct sockaddr_in *) &ss)->sin_addr.s_addr = ip->ip_src.s_addr;
ss.ss_family = AF_INET;
hsi = OSI->findIncompleteHost(&ss);
if (!hsi)
continue; /* Not from one of our targets. */
setTargetMACIfAvailable(hsi->target, &linkhdr, &ss, 0);
goodResponse = HOS->processResp(hsi->hss, ip, bytes, &rcvdtime);
if (goodResponse)
expectReplies--;
} while (!timedout && expectReplies > 0);
/* Remove any timeout hosts during the scan. */
OSI->removeCompletedHosts();
numProbesLeft = 0;
for (hostI = OSI->incompleteHosts.begin();
hostI != OSI->incompleteHosts.end(); hostI++) {
hss = (*hostI)->hss;
HOS->updateActiveTUIProbes(hss);
numProbesLeft += hss->numProbesToSend();
numProbesLeft += hss->numProbesActive();
}
gettimeofday(&now, NULL);
if (expectReplies == 0) {
timeToSleep = TIMEVAL_SUBTRACT(stime, now);
} else {
timeToSleep = 0;
}
} while (numProbesLeft > 0);
}
static void endRound(OsScanInfo *OSI, HostOsScan *HOS, int roundNum) {
std::list<HostOsScanInfo *>::iterator hostI;
HostOsScanInfo *hsi = NULL;
int distance = -1;
enum dist_calc_method distance_calculation_method = DIST_METHOD_NONE;
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
distance = -1;
hsi = *hostI;
HOS->makeFP(hsi->hss);
hsi->FPs[roundNum] = hsi->hss->getFP();
hsi->FPR->FPs[roundNum] = hsi->FPs[roundNum];
hsi->FPR->numFPs = roundNum + 1;
double tr = hsi->hss->timingRatio();
hsi->target->FPR->maxTimingRatio = MAX(hsi->target->FPR->maxTimingRatio, tr);
match_fingerprint(hsi->FPs[roundNum], &hsi->FP_matches[roundNum],
o.reference_FPs, OSSCAN_GUESS_THRESHOLD);
if (hsi->FP_matches[roundNum].overall_results == OSSCAN_SUCCESS &&
hsi->FP_matches[roundNum].num_perfect_matches > 0) {
memcpy(&(hsi->target->seq), &hsi->hss->si, sizeof(struct seq_info));
if (roundNum > 0) {
if (o.verbose)
log_write(LOG_STDOUT, "WARNING: OS didn't match until try #%d\n", roundNum + 1);
}
match_fingerprint(hsi->FPR->FPs[roundNum], hsi->FPR,
o.reference_FPs, OSSCAN_GUESS_THRESHOLD);
hsi->isCompleted = true;
}
if (islocalhost(hsi->target->TargetSockAddr())) {
/* scanning localhost */
distance = 0;
distance_calculation_method = DIST_METHOD_LOCALHOST;
} else if (hsi->target->MACAddress()) {
/* on the same network segment */
distance = 1;
distance_calculation_method = DIST_METHOD_DIRECT;
} else if (hsi->hss->distance!=-1) {
distance = hsi->hss->distance;
distance_calculation_method = DIST_METHOD_ICMP;
}
hsi->target->distance = hsi->target->FPR->distance = distance;
hsi->target->distance_calculation_method = distance_calculation_method;
hsi->target->FPR->distance_guess = hsi->hss->distance_guess;
}
OSI->removeCompletedHosts();
}
static void findBestFPs(OsScanInfo *OSI) {
std::list<HostOsScanInfo *>::iterator hostI;
HostOsScanInfo *hsi = NULL;
int i;
double bestacc;
int bestaccidx;
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
hsi = *hostI;
memcpy(&(hsi->target->seq), &hsi->hss->si, sizeof(struct seq_info));
/* Now lets find the best match */
bestacc = 0;
bestaccidx = 0;
for (i = 0; i < hsi->FPR->numFPs; i++) {
if (hsi->FP_matches[i].overall_results == OSSCAN_SUCCESS &&
hsi->FP_matches[i].num_matches > 0 &&
hsi->FP_matches[i].accuracy[0] > bestacc) {
bestacc = hsi->FP_matches[i].accuracy[0];
bestaccidx = i;
if (hsi->FP_matches[i].num_perfect_matches)
break;
}
}
// Now we redo the match, since target->FPR has various data (such as
// target->FPR->numFPs) which is not in FP_matches[bestaccidx]. This is
// kinda ugly.
match_fingerprint(hsi->FPR->FPs[bestaccidx], (FingerPrintResultsIPv4 *) hsi->target->FPR,
o.reference_FPs, OSSCAN_GUESS_THRESHOLD);
}
}
static void printFP(OsScanInfo *OSI) {
std::list<HostOsScanInfo *>::const_iterator hostI;
const HostOsScanInfo *hsi = NULL;
const FingerPrintResultsIPv4 *FPR;
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI++) {
hsi = *hostI;
FPR = hsi->FPR;
log_write(LOG_NORMAL|LOG_SKID_NOXLT|LOG_STDOUT,
"No OS matches for %s by new os scan system.\n\nTCP/IP fingerprint:\n%s",
hsi->target->targetipstr(),
mergeFPs(FPR->FPs, FPR->numFPs, true,
hsi->target->TargetSockAddr(), hsi->target->distance,
hsi->target->distance_calculation_method,
hsi->target->MACAddress(),
FPR->osscan_opentcpport, FPR->osscan_closedtcpport,
FPR->osscan_closedudpport, false));
}
}
/* Goes through every unmatched host in OSI. If a host has completed
the maximum number of OS detection tries allowed for it without
matching, it is transferred to the passed in unMatchedHosts list.
Returns the number of hosts moved to unMatchedHosts. */
static int expireUnmatchedHosts(OsScanInfo *OSI, std::list<HostOsScanInfo *> *unMatchedHosts) {
std::list<HostOsScanInfo *>::iterator hostI, nextHost;
int hostsRemoved = 0;
HostOsScanInfo *HOS;
gettimeofday(&now, NULL);
for (hostI = OSI->incompleteHosts.begin(); hostI != OSI->incompleteHosts.end(); hostI = nextHost) {
HOS = *hostI;
nextHost = hostI;
nextHost++;
int max_tries = o.maxOSTries(); /* The amt. if print is suitable for submission */
if (HOS->target->FPR->OmitSubmissionFP())
max_tries = MIN(max_tries, STANDARD_OS2_TRIES);
if (HOS->FPR->numFPs >= max_tries) {
/* We've done all the OS2 tries we're going to do ... move this
to unMatchedHosts */
HOS->target->stopTimeOutClock(&now);
OSI->incompleteHosts.erase(hostI);
/* We need to adjust nextI if necessary */
OSI->resetHostIterator();
hostsRemoved++;
unMatchedHosts->push_back(HOS);
}
}
return hostsRemoved;
}
/******************************************************************************
* Implementation of class OFProbe *
******************************************************************************/
OFProbe::OFProbe() {
type = OFP_UNSET;
subid = 0;
tryno = -1;
retransmitted = false;
memset(&sent, 0, sizeof(sent));
memset(&prevSent, 0, sizeof(prevSent));
}
const char *OFProbe::typestr() const {
switch (type) {
case OFP_UNSET:
return "OFP_UNSET";
case OFP_TSEQ:
return "OFP_TSEQ";
case OFP_TOPS:
return "OFP_TOPS";
case OFP_TECN:
return "OFP_TECN";
case OFP_T1_7:
return "OFP_T1_7";
case OFP_TUDP:
return "OFP_TUDP";
case OFP_TICMP:
return "OFP_TICMP";
default:
assert(false);
return "ERROR";
}
}
/******************************************************************************
* Implementation of class HostOsScanStats *
******************************************************************************/
HostOsScanStats::HostOsScanStats(Target * t) {
int i;
target = t;
FP = NULL;
memset(&si, 0, sizeof(si));
memset(&ipid, 0, sizeof(ipid));
openTCPPort = -1;
closedTCPPort = -1;
closedUDPPort = -1;