forked from nmap/nmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathosscan2.cc
3905 lines (3301 loc) · 122 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 http://nmap.org/osdetect/ *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2008 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-db or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is just meant to *
* clarify our interpretation of derived works with some common examples. *
* These restrictions only apply when you actually redistribute Nmap. For *
* example, nothing stops you from writing and selling a proprietary *
* front-end to Nmap. Just distribute it by itself, and point people to *
* http://nmap.org to download Nmap. *
* *
* We don't consider these to be added restrictions on top of the GPL, but *
* just a clarification of how we interpret "derived works" as it applies *
* to our GPL-licensed Nmap product. This is similar to the way Linus *
* Torvalds has announced his interpretation of how "derived works" *
* applies to Linux kernel modules. Our interpretation refers only to *
* Nmap - we don't speak for any other GPL products. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included COPYING.OpenSSL file, and distribute linked *
* combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to fyodor@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one of the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering Fyodor and Insecure.Com LLC the unlimited, non-exclusive right *
* to reuse, modify, and relicense the code. Nmap will always be *
* available Open Source, but this is important because the inability to *
* relicense code has caused devastating problems for other Free Software *
* projects (such as KDE and NASM). We also occasionally relicense the *
* code to third parties as discussed above. If you wish to specify *
* special license conditions of your contributions, just say so when you *
* send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License v2.0 for more details at *
* http://www.gnu.org/licenses/gpl-2.0.html , or in the COPYING file *
* included with Nmap. *
* *
***************************************************************************/
/* $Id: osscan.cc 3636 2006-07-04 23:04:56Z fyodor $ */
#include "osscan.h"
#include "osscan2.h"
#include "timing.h"
#include "NmapOps.h"
#include "Target.h"
#include "utils.h"
#include <dnet.h>
#include <list>
#define NUM_FPTESTS 13
/* The number of tries we normally do. This may be increased if
the target looks like a good candidate for fingerprint submission, or fewer
if the user gave the --max-os-tries option */
#define STANDARD_OS2_TRIES 2
// The minimum (and target) amount of time to wait between probes
// sent to a single host, in milliseconds.
#define OS_PROBE_DELAY 25
// The target amount of time to wait between sequencing probes sent to
// a single host, in milliseconds. The ideal is 500ms because of the
// common 2Hz timestamp frequencies. Less than 500ms and we might not
// see any change in the TS counter (and it gets less accurate even if
// we do). More than 500MS and we risk having two changes (and it
// gets less accurate even if we have just one). So we delay 100MS
// between probes, leaving 500MS between 1st and 6th.
#define OS_SEQ_PROBE_DELAY 100
using namespace std;
extern NmapOps o;
/* 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*) "\003\003\012\001\002\004\005\264\010\012\377\377\377\377\000\000\000\000\004\002", 20},
{(u8*) "\002\004\005\170\003\003\000\004\002\010\012\377\377\377\377\000\000\000\000\000", 20},
{(u8*) "\010\012\377\377\377\377\000\000\000\000\001\001\003\003\005\001\002\004\002\200", 20},
{(u8*) "\004\002\010\012\377\377\377\377\000\000\000\000\003\003\012\000", 16},
{(u8*) "\002\004\002\030\004\002\010\012\377\377\377\377\000\000\000\000\003\003\012\0", 20},
{(u8*) "\002\004\001\011\004\002\010\012\377\377\377\377\000\000\000\000", 16},
{(u8*) "\003\003\012\001\002\004\005\264\004\002\001\001", 12},
{(u8*) "\003\003\012\001\002\004\001\011\010\012\377\377\377\377\000\000\000\000\004\002", 20},
{(u8*) "\003\003\012\001\002\004\001\011\010\012\377\377\377\377\000\000\000\000\004\002", 20},
{(u8*) "\003\003\012\001\002\004\001\011\010\012\377\377\377\377\000\000\000\000\004\002", 20},
{(u8*) "\003\003\012\001\002\004\001\011\010\012\377\377\377\377\000\000\000\000\004\002", 20},
{(u8*) "\003\003\012\001\002\004\001\011\010\012\377\377\377\377\000\000\000\000\004\002", 20},
{(u8*) "\003\003\017\001\002\004\001\011\010\012\377\377\377\377\000\000\000\000\004\002", 20}
};
/* Numbering is the same as for prbOpts[] */
u16 prbWindowSz[] = { 1, 63, 4, 4, 16, 512, 3, 128, 256, 1024, 31337, 32768, 65535 };
/* A global now. Updated after potentially meaningful delays. This can
* be used to save a call to gettimeofday()
*/
static struct timeval now;
class OFProbe;
class HostOsScanStats;
class HostOsScan;
class HostOsScanInfo;
class OsScanInfo;
/* Performance tuning variable. */
struct os_scan_performance_vars {
int low_cwnd; /* The lowest cwnd (congestion window) allowed */
int host_initial_cwnd; /* Initial congestion window for ind. hosts */
int group_initial_cwnd; /* Initial congestion window for all hosts as a group */
int max_cwnd; /* I should never have more than this many probes
outstanding */
int quick_incr; /* How many probes are incremented for each response
in quick start mode */
int cc_incr; /* How many probes are incremented per (roughly) rtt in
congestion control mode */
int initial_ccthresh;
/* When a successful ping response comes back, it counts as this many
"normal" responses, because the fact that pings are neccessary means
we aren't getting much input. */
int ping_magnifier;
/* Try to send a scanping if no response has been received from a target host
in this many usecs */
int pingtime;
double group_drop_cwnd_divisor; /* all-host group cwnd divided by this
value if any packet drop occurs */
double group_drop_ccthresh_divisor; /* used to drop the group ccthresh when
any drop occurs */
double host_drop_ccthresh_divisor; /* used to drop the host ccthresh when
any drop occurs */
int tryno_cap; /* The maximum trynumber (starts at zero) allowed */
} perf;
/* Some of the algorithms used here are TCP congestion control
techniques from RFC2581. */
struct osscan_timing_vals {
double cwnd; /* Congestion window - in probes */
/* The threshold after which mode is changed from QUICK_START to
CONGESTION_CONTROL */
int ccthresh;
/* Number of updates to this utv (generally packet receipts ) */
int num_updates;
/* Last time values were adjusted for a drop (you usually only want
to adjust again based on probes sent after that adjustment so a
sudden batch of drops doesn't destroy timing. Init to now */
struct timeval last_drop;
};
typedef enum OFProbeType {
OFP_UNSET,
OFP_TSEQ,
OFP_TOPS,
OFP_TECN,
OFP_T1_7,
OFP_TICMP,
OFP_TUDP
} OFProbeType;
class OFProbe
{
public:
OFProbe();
/* The literal string for the current probe type. */
const char *typestr();
/* Type of the probe: for what os fingerprinting test? */
OFProbeType type;
/* Subid of this probe to separate different tcp/udp/icmp. */
int subid;
int tryno; /* Try (retransmission) number of this probe */
/* A packet may be timedout for a while before being retransmitted
due to packet sending rate limitations */
bool retransmitted;
struct timeval sent;
/* Time the previous probe was sent, if this is a retransmit (tryno > 0) */
struct timeval prevSent;
};
/*
* HostOsScanStats stores the status for a host being scanned
* in a scan round.
*/
class HostOsScanStats
{
friend class HostOsScan;
public:
HostOsScanStats(Target *t);
~HostOsScanStats();
void initScanStats();
void addNewProbe(OFProbeType type, int subid);
void removeActiveProbe(list<OFProbe *>::iterator probeI);
/* Get an active probe from active probe list identified by probe type
and subid. returns probesActive.end() if there isn't one. */
list<OFProbe *>::iterator getActiveProbe(OFProbeType type, int subid);
void moveProbeToActiveList(list<OFProbe *>::iterator probeI);
void moveProbeToUnSendList(list<OFProbe *>::iterator probeI);
unsigned int numProbesToSend() {return probesToSend.size();}
unsigned int numProbesActive() {return probesActive.size();}
FingerPrint *getFP() {fpPassed = true; return FP;}
Target *target; /* the Target */
struct seq_info si;
struct ipid_info ipid;
/*
* distance, distance_guess: hop count between us and the target.
*
* Possible values of distance:
* 0: when scan self;
* 1: when scan a target on the same network segment;
* >=1: not self, not same network and nmap has got the icmp reply to the U1 probe.
* -1: none of the above situations.
*
* Possible values of distance_guess:
* -1: nmap fails to get a valid ttl by all kinds of probes.
* >=1: a guessing value based on ttl.
*/
int distance;
int distance_guess;
/* Returns the amount of time taken between sending 1st tseq probe
and the last one. Zero is
returned if we didn't send the tseq probes because there was no
open tcp port */
double timingRatio();
private:
/* Ports of the targets used in os fingerprinting. */
int openTCPPort, closedTCPPort, closedUDPPort;
/* Probe list used in tests. At first, probes are linked in
* probesToSend; when a probe is sent, it will be removed from
* probesToSend and appended to probesActive. If any probes in
* probesActive are timedout, they will be moved to probesToSend and
* sent again till expired.
*/
list<OFProbe *> probesToSend;
list<OFProbe *> probesActive;
/* A record of total number of probes that have been sent to this
* host, including restranmited ones. */
unsigned int num_probes_sent;
/* Delay between two probes. */
unsigned int sendDelayMs;
/* When the last probe is sent. */
struct timeval lastProbeSent;
struct osscan_timing_vals timing;
/*
* Fingerprint of this target. When a scan is completed, it'll
* finally be passed to hs->target->FPR->FPs[x].
*/
FingerPrint *FP;
FingerPrint *FPtests[NUM_FPTESTS];
#define FP_TSeq FPtests[0]
#define FP_TOps FPtests[1]
#define FP_TWin FPtests[2]
#define FP_TEcn FPtests[3]
#define FP_T1_7_OFF 4
#define FP_T1 FPtests[4]
#define FP_T2 FPtests[5]
#define FP_T3 FPtests[6]
#define FP_T4 FPtests[7]
#define FP_T5 FPtests[8]
#define FP_T6 FPtests[9]
#define FP_T7 FPtests[10]
#define FP_TUdp FPtests[11]
#define FP_TIcmp FPtests[12]
struct AVal *TOps_AVs[6]; /* 6 AVs of TOps */
struct AVal *TWin_AVs[6]; /* 6 AVs of TWin */
/* Whether the above FPs is passed. If not and the hss stats is to be
deleted, delete the FPs. This happens when the host is timedout
during the scan. */
bool fpPassed;
/* The following are variables to store temporary results
* during the os fingerprinting process of this host.
*/
u16 lastipid;
struct timeval seq_send_times[NUM_SEQ_SAMPLES];
int TWinReplyNum; /* how many TWin replies are received. */
int TOpsReplyNum; /* how many TOps replies are received. Actually it is the same with TOpsReplyNum. */
struct ip *icmpEchoReply; /* To store one of the two icmp replies */
int storedIcmpReply; /* Which one of the two icmp replies is stored? */
struct udpprobeinfo upi; /* info of the udp probe we sent */
};
/* These are statistics for the whole group of Targets */
class ScanStats {
public:
ScanStats();
/* Returns true if the system says that sending is OK. */
bool sendOK();
struct osscan_timing_vals timing;
struct timeout_info to; /* rtt/timeout info */
/* Total number of active probes */
int num_probes_active;
/* Number of probes sent in total. */
int num_probes_sent;
int num_probes_sent_at_last_wait;
};
/*
* HostOsScan does the scan job, setting and using the status of a host in
* the host's HostOsScanStats.
*/
class HostOsScan
{
public:
HostOsScan(Target *t); /* OsScan need a target to set eth stuffs */
~HostOsScan();
pcap_t *pd;
ScanStats *stats;
/* (Re)Initial the parameters that will be used during the scan.*/
void reInitScanSystem();
void buildSeqProbeList(HostOsScanStats *hss);
void updateActiveSeqProbes(HostOsScanStats *hss);
void buildTUIProbeList(HostOsScanStats *hss);
void updateActiveTUIProbes(HostOsScanStats *hss);
/* send the next probe in the probe list of the hss */
void sendNextProbe(HostOsScanStats *hss);
/* Process one response.
* If the response is useful, return true. */
bool processResp(HostOsScanStats *hss, struct ip *ip, unsigned int len, struct timeval *rcvdtime);
/* Make up the fingerprint. */
void makeFP(HostOsScanStats *hss);
/* Check whether the host is sendok. If not, fill _when_ with the
* time when it will be sendOK and return false; else, fill it with
* now and return true.
*/
bool hostSendOK(HostOsScanStats *hss, struct timeval *when);
/* Check whether it is ok to send the next seq probe to the host. If
* not, fill _when_ with the time when it will be sendOK and return
* false; else, fill it with now and return true.
*/
bool hostSeqSendOK(HostOsScanStats *hss, struct timeval *when);
/* 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 timeProbeTimeout(HostOsScanStats *hss);
/* 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 nextTimeout(HostOsScanStats *hss, struct timeval *when);
/* Adjust various timing variables based on pcket receipt. */
void adjust_times(HostOsScanStats *hss, OFProbe *probe, struct timeval *rcvdtime);
private:
/* Probe send functions. */
void sendTSeqProbe(HostOsScanStats *hss, int probeNo);
void sendTOpsProbe(HostOsScanStats *hss, int probeNo);
void sendTEcnProbe(HostOsScanStats *hss);
void sendT1_7Probe(HostOsScanStats *hss, int probeNo);
void sendTUdpProbe(HostOsScanStats *hss, int probeNo);
void sendTIcmpProbe(HostOsScanStats *hss, int probeNo);
/* Response process functions. */
bool processTSeqResp(HostOsScanStats *hss, struct ip *ip, int replyNo);
bool processTOpsResp(HostOsScanStats *hss, struct tcp_hdr *tcp, int replyNo);
bool processTWinResp(HostOsScanStats *hss, struct tcp_hdr *tcp, int replyNo);
bool processTEcnResp(HostOsScanStats *hss, struct ip *ip);
bool processT1_7Resp(HostOsScanStats *hss, struct ip *ip, int replyNo);
bool processTUdpResp(HostOsScanStats *hss, struct ip *ip);
bool processTIcmpResp(HostOsScanStats *hss, struct ip *ip, int replyNo);
void makeTSeqFP(HostOsScanStats *hss);
void makeTOpsFP(HostOsScanStats *hss);
void makeTWinFP(HostOsScanStats *hss);
bool get_tcpopt_string(struct tcp_hdr *tcp, int mss, char *result, int maxlen);
int rawsd; /* raw socket descriptor */
struct eth_nfo eth;
struct eth_nfo *ethptr; /* for passing to send_ functions */
unsigned int tcpSeqBase, tcpAck; /* Seq&Ack value used in TCP probes */
int tcpMss; /* tcp Mss value used in TCP probes */
int udpttl; /* ttl value used in udp probe. */
unsigned short icmpEchoId, icmpEchoSeq; /* Icmp Echo Id&Seq value used in ICMP probes*/
/* Source port number in TCP probes. Different probe will use
* arbitrary offset value of it. */
int tcpPortBase;
int udpPortBase;
};
/*
* The overall os scan information of a host:
* - Fingerprints gotten from every scan round;
* - Maching results of these fingerprints.
* - Is it timeout/completed?
* - ...
*/
class HostOsScanInfo
{
public:
HostOsScanInfo(Target *t, OsScanInfo *OSI);
~HostOsScanInfo();
Target *target; /* the Target */
OsScanInfo *OSI; /* The OSI which contains this HostOsScanInfo */
FingerPrint **FPs; /* Fingerprints of the host */
FingerPrintResults *FP_matches; /* Fingerprint-matching results */
struct seq_info *si;
bool timedOut;
bool isCompleted;
HostOsScanStats *hss; /* Scan status of the host in one scan round */
};
/*
* Maintain a link of incomplete HostOsScanInfo.
*/
class OsScanInfo
{
public:
OsScanInfo(vector<Target *> &Targets);
~OsScanInfo();
/* If you remove from this, you had better adjust nextI too (or call
resetHostIterator() afterward). Don't let this list get empty,
then add to it again, or you may mess up nextI (I'm not sure) */
list<HostOsScanInfo *> incompleteHosts;
unsigned int starttimems;
unsigned int numIncompleteHosts() {return incompleteHosts.size();}
HostOsScanInfo *findIncompleteHost(struct sockaddr_storage *ss);
/* 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. */
HostOsScanInfo *nextIncompleteHost();
/* Resets the host iterator used with nextIncompleteHost() to the
beginning. If you remove a host from incompleteHosts, call this
right afterward */
void resetHostIterator() { nextI = incompleteHosts.begin(); }
int removeCompletedHosts();
private:
unsigned int numInitialTargets;
list<HostOsScanInfo *>::iterator nextI;
};
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() {
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";
}
}
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;
num_probes_sent = 0;
sendDelayMs = MAX(o.scan_delay, OS_PROBE_DELAY);
lastProbeSent = now;
/* timing */
timing.cwnd = perf.host_initial_cwnd;
timing.ccthresh = perf.initial_ccthresh; /* Will be reduced if any packets are dropped anyway */
timing.num_updates = 0;
gettimeofday(&timing.last_drop, NULL);
for (i=0; i<NUM_FPTESTS; i++)
FPtests[i] = NULL;
for (i=0; i<6; i++) {
TOps_AVs[i] = NULL;
TWin_AVs[i] = NULL;
}
fpPassed = true;
icmpEchoReply = NULL;
distance = -1;
distance_guess = -1;
}
HostOsScanStats::~HostOsScanStats() {
int i;
if(!fpPassed) {
for(i=0; i<NUM_FPTESTS; i++) {
if(FPtests[i]) {
if(FPtests[i]->results) {
free(FPtests[i]->results);
}
free(FPtests[i]);
}
}
for(i=0; i<6; i++) {
if(TOps_AVs[i]) free(TOps_AVs[i]);
if(TWin_AVs[i]) free(TWin_AVs[i]);
}
}
while(!probesToSend.empty()) {
delete probesToSend.front();
probesToSend.pop_front();
}
while(!probesActive.empty()) {
delete probesActive.front();
probesActive.pop_front();
}
if (icmpEchoReply) free(icmpEchoReply);
}
void HostOsScanStats::initScanStats() {
Port *tport = NULL;
int i;
/* Lets find an open port to use if we don't already have one */
openTCPPort = -1;
/* target->FPR->osscan_opentcpport = -1;
target->FPR->osscan_closedtcpport = -1;
target->FPR->osscan_closedudpport = -1; */
if (target->FPR->osscan_opentcpport > 0)
openTCPPort = target->FPR->osscan_opentcpport;
else if ((tport = target->ports.nextPort(NULL, IPPROTO_TCP, PORT_OPEN))) {
openTCPPort = tport->portno;
/* If it is zero, let's try another one if there is one ) */
if (tport->portno == 0)
if ((tport = target->ports.nextPort(tport, IPPROTO_TCP, PORT_OPEN)))
openTCPPort = tport->portno;
target->FPR->osscan_opentcpport = openTCPPort;
}
/* Now we should find a closed port */
if (target->FPR->osscan_closedtcpport > 0)
closedTCPPort = target->FPR->osscan_closedtcpport;
else if ((tport = target->ports.nextPort(NULL, IPPROTO_TCP, PORT_CLOSED))) {
closedTCPPort = tport->portno;
/* If it is zero, let's try another one if there is one ) */
if (tport->portno == 0)
if ((tport = target->ports.nextPort(tport, IPPROTO_TCP, PORT_CLOSED)))
closedTCPPort = tport->portno;
target->FPR->osscan_closedtcpport = closedTCPPort;
} else if ((tport = target->ports.nextPort(NULL, IPPROTO_TCP, PORT_UNFILTERED))) {
/* Well, we will settle for unfiltered */
closedTCPPort = tport->portno;
/* But again we'd prefer not to have zero */
if (tport->portno == 0)
if ((tport = target->ports.nextPort(tport, IPPROTO_TCP, PORT_UNFILTERED)))
closedTCPPort = tport->portno;
} else {
/* We'll just have to pick one at random :( */
closedTCPPort = (get_random_uint() % 14781) + 30000;
}
/* Now we should find a closed udp port */
if (target->FPR->osscan_closedudpport > 0)
closedUDPPort = target->FPR->osscan_closedudpport;
else if ((tport = target->ports.nextPort(NULL, IPPROTO_UDP, PORT_CLOSED))) {
closedUDPPort = tport->portno;
/* Not zero, if possible */
if (tport->portno == 0)
if ((tport = target->ports.nextPort(tport, IPPROTO_UDP, PORT_CLOSED)))
closedUDPPort = tport->portno;
target->FPR->osscan_closedudpport = closedUDPPort;
} else if ((tport = target->ports.nextPort(NULL, IPPROTO_UDP, PORT_UNFILTERED))) {
/* Well, we will settle for unfiltered */
closedUDPPort = tport->portno;
/* But not zero, please */
if (tport->portno == 0)
if ((tport = target->ports.nextPort(NULL, IPPROTO_UDP, PORT_UNFILTERED)))
closedUDPPort = tport->portno;
} else {
/* Pick one at random. Shrug. */
closedUDPPort = (get_random_uint() % 14781) + 30000;
}
FP = NULL;
for (i=0; i<NUM_FPTESTS; i++)
FPtests[i] = NULL;
for (i=0; i<6; i++) {
TOps_AVs[i] = NULL;
TWin_AVs[i] = NULL;
}
fpPassed = false;
TOpsReplyNum = 0;
TWinReplyNum = 0;
lastipid = 0;
memset(&si, 0, sizeof(si));
for (i=0; i<NUM_SEQ_SAMPLES; i++) {
ipid.tcp_ipids[i] = -1;
ipid.icmp_ipids[i] = -1;
}
memset(&seq_send_times, 0, sizeof(seq_send_times));
if (icmpEchoReply) {
free(icmpEchoReply);
icmpEchoReply = NULL;
}
storedIcmpReply = -1;
memset(&upi, 0, sizeof(upi));
}
/* Add a probe to the probe list. */
void HostOsScanStats::addNewProbe(OFProbeType type, int subid) {
OFProbe *probe = new OFProbe();
probe->type = type;
probe->subid = subid;
probesToSend.push_back(probe);
}
/* Remove a probe from the probesActive. */
void HostOsScanStats::removeActiveProbe(list<OFProbe *>::iterator probeI) {
OFProbe *probe = *probeI;
probesActive.erase(probeI);
delete probe;
}
/* Get an active probe from active probe list identified by probe type
and subid. Returns probesActive.end() if there isn't one */
list<OFProbe *>::iterator HostOsScanStats::getActiveProbe(OFProbeType type, int subid) {
list<OFProbe *>::iterator probeI;
OFProbe *probe = NULL;
for(probeI = probesActive.begin(); probeI != probesActive.end(); probeI++) {
probe = *probeI;
if(probe->type == type && probe->subid == subid)
break;
}
if(probeI == probesActive.end()) {
/* not found!? */
if(o.debugging > 1)
log_write(LOG_PLAIN, "Probe doesn't exist! Probe type: %d. Probe subid: %d\n", type, subid);
return probesActive.end();
}
return probeI;
}
/* Move a probe from probesToSend to probesActive. */
void HostOsScanStats::moveProbeToActiveList(list<OFProbe *>::iterator probeI) {
probesActive.push_back(*probeI);
probesToSend.erase(probeI);
}
/* Move a probe from probesActive to probesToSend. */
void HostOsScanStats::moveProbeToUnSendList(list<OFProbe *>::iterator probeI) {
probesToSend.push_back(*probeI);
probesActive.erase(probeI);
}
/* Compute the ratio of amount of time taken between sending 1st TSEQ
probe and 1st ICMP probe compared to the amount of time it should
have taken. Ratios far from 1 can cause bogus results */
double HostOsScanStats::timingRatio() {
if (openTCPPort < 0)
return 0;
int msec_ideal = OS_SEQ_PROBE_DELAY * (NUM_SEQ_SAMPLES - 1);
int msec_taken = TIMEVAL_MSEC_SUBTRACT(seq_send_times[NUM_SEQ_SAMPLES -1 ],
seq_send_times[0]);
if (o.debugging) {
log_write(LOG_PLAIN, "OS detection timingRatio() == (%.3f - %.3f) * 1000 / %d == %.3f\n",
seq_send_times[NUM_SEQ_SAMPLES - 1].tv_sec + seq_send_times[NUM_SEQ_SAMPLES - 1].tv_usec / 1000000.0, seq_send_times[0].tv_sec + (float) seq_send_times[0].tv_usec / 1000000.0, msec_ideal, (float) msec_taken / msec_ideal);
}
return (double) msec_taken / msec_ideal;
}
/* 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 HostOsScan::nextTimeout(HostOsScanStats *hss, struct timeval *when) {
assert(hss);
struct timeval probe_to, earliest_to;
list<OFProbe *>::iterator probeI;
bool firstgood = true;
assert(when);
memset(&probe_to, 0, sizeof(probe_to));
memset(&earliest_to, 0, sizeof(earliest_to));
for(probeI = hss->probesActive.begin(); probeI != hss->probesActive.end(); probeI++) {
TIMEVAL_ADD(probe_to, (*probeI)->sent, timeProbeTimeout(hss));
if (firstgood || TIMEVAL_SUBTRACT(probe_to, earliest_to) < 0) {
earliest_to = probe_to;
firstgood = false;
}
}
*when = (firstgood)? now : earliest_to;
return (firstgood)? false : true;
}
void HostOsScan::adjust_times(HostOsScanStats *hss, OFProbe *probe, struct timeval *rcvdtime) {
assert(hss);
assert(probe);
/* Adjust timing */
if(rcvdtime) {
adjust_timeouts2(&(probe->sent), rcvdtime, &(hss->target->to));
adjust_timeouts2(&(probe->sent), rcvdtime, &(stats->to));
}
hss->timing.num_updates++;
stats->timing.num_updates++;
/* Adjust window */
if (probe->tryno > 0 || !rcvdtime) {
if (TIMEVAL_SUBTRACT(probe->sent, hss->timing.last_drop) > 0) {
hss->timing.cwnd = perf.low_cwnd;
hss->timing.ccthresh = (int) MAX(hss->numProbesActive() / perf.host_drop_ccthresh_divisor, 2);
hss->timing.last_drop = now;
}
if (TIMEVAL_SUBTRACT(probe->sent, stats->timing.last_drop) > 0) {
stats->timing.cwnd = MAX(perf.low_cwnd, stats->timing.cwnd / perf.group_drop_cwnd_divisor);
stats->timing.ccthresh = (int) MAX(stats->num_probes_active / perf.group_drop_ccthresh_divisor, 2);
stats->timing.last_drop = now;
}
} else {
/* Good news -- got a response to first try. Increase window as
appropriate. */
if (hss->timing.cwnd <= hss->timing.ccthresh) {
/* In quick start mode */
hss->timing.cwnd += perf.quick_incr;
} else {
/* Congestion control mode */
hss->timing.cwnd += perf.cc_incr / hss->timing.cwnd;
}
if (hss->timing.cwnd > perf.max_cwnd)
hss->timing.cwnd = perf.max_cwnd;
if (stats->timing.cwnd <= stats->timing.ccthresh) {
/* In quick start mode */
stats->timing.cwnd += perf.quick_incr;
} else {
/* Congestion control mode */
stats->timing.cwnd += perf.cc_incr / stats->timing.cwnd;
}
if (stats->timing.cwnd > perf.max_cwnd)
stats->timing.cwnd = perf.max_cwnd;
}
}
ScanStats::ScanStats() {
/* init timing val */
timing.cwnd = perf.group_initial_cwnd;
timing.ccthresh = perf.initial_ccthresh; /* Will be reduced if any packets are dropped anyway */
timing.num_updates = 0;
gettimeofday(&timing.last_drop, NULL);
initialize_timeout_info(&to);
num_probes_active = 0;
num_probes_sent = num_probes_sent_at_last_wait = 0;
}
/* Returns true if the os scan system says that sending is OK.*/
bool ScanStats::sendOK() {
if (num_probes_sent - num_probes_sent_at_last_wait >= 50)
return false;
if (timing.cwnd < num_probes_active + 0.5)
return false;
return true;
}
HostOsScan::HostOsScan(Target *t) {
pd = NULL;
rawsd = -1;
if ((o.sendpref & PACKET_SEND_ETH) && t->ifType() == devt_ethernet) {
memcpy(eth.srcmac, t->SrcMACAddress(), 6);
memcpy(eth.dstmac, t->NextHopMACAddress(), 6);
if ((eth.ethsd = eth_open_cached(t->deviceName())) == NULL)
fatal("%s: Failed to open ethernet device (%s)", __func__, t->deviceName());
rawsd = -1;
ethptr = ð
} else {
/* Init our raw socket */
if ((rawsd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0 )
pfatal("socket troubles in %s", __func__);
unblock_socket(rawsd);
broadcast_socket(rawsd);
#ifndef WIN32
sethdrinclude(rawsd);
#endif
ethptr = NULL;
eth.ethsd = NULL;
}
tcpPortBase = o.magic_port_set? o.magic_port : o.magic_port + get_random_u8();
udpPortBase = o.magic_port_set? o.magic_port : o.magic_port + get_random_u8();
reInitScanSystem();
stats = new ScanStats();
}
HostOsScan::~HostOsScan() {
if (rawsd >= 0) { close(rawsd); rawsd = -1; }
if (pd) { pcap_close(pd); pd = NULL; }
/*
* No need to close ethptr->ethsd due to caching
* if (eth.ethsd) { eth_close(eth.ethsd); eth.ethsd = NULL; }
*/
delete stats;
}
void HostOsScan::reInitScanSystem() {
tcpSeqBase = get_random_u32();
tcpAck = get_random_u32();
tcpMss = 265;
icmpEchoId = get_random_u16();
icmpEchoSeq = 295;
udpttl = (time(NULL) % 14) + 51;
}
/* Initiate seq probe list */
void HostOsScan::buildSeqProbeList(HostOsScanStats *hss) {
assert(hss);
int i;
if(hss->openTCPPort == -1) return;
if(hss->FP_TSeq) return;
for(i=0; i<NUM_SEQ_SAMPLES; i++)
hss->addNewProbe(OFP_TSEQ, i);
}
/* Update the seq probes in the active probe list:
* o Remove the timedout seq probes.
*/
void HostOsScan::updateActiveSeqProbes(HostOsScanStats *hss) {
assert(hss);
list<OFProbe *>::iterator probeI, nxt;
OFProbe *probe = NULL;
for(probeI = hss->probesActive.begin(); probeI != hss->probesActive.end();
probeI = nxt) {
nxt = probeI;
nxt++;
probe = *probeI;
/* Is the probe timedout? */
if (TIMEVAL_SUBTRACT(now, probe->sent) > (long) timeProbeTimeout(hss)) {
hss->removeActiveProbe(probeI);
stats->num_probes_active--;
}