-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnmap.cc
2143 lines (1954 loc) · 75.7 KB
/
nmap.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
/***************************************************************************
* nmap.cc -- Currently handles some of Nmap's port scanning features as *
* well as the command line user interface. Note that the actual main() *
* function is in main.cc *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2004 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. 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 may be *
* willing to sell alternative licenses (contact sales@insecure.com). *
* Many security scanner vendors already license Nmap technology such as *
* our remote OS fingerprinting database and code, service/version *
* detection system, and port scanning code. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-fingerprints or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is just meant to *
* clarify our interpretation of derived works with some common examples. *
* These restrictions only apply when you actually redistribute Nmap. For *
* example, nothing stops you from writing and selling a proprietary *
* front-end to Nmap. Just distribute it by itself, and point people to *
* http://www.insecure.org/nmap/ to download Nmap. *
* *
* We don't consider these to be added restrictions on top of the GPL, but *
* just a clarification of how we interpret "derived works" as it applies *
* to our GPL-licensed Nmap product. This is similar to the way Linus *
* Torvalds has announced his interpretation of how "derived works" *
* applies to Linux kernel modules. Our interpretation refers only to *
* Nmap - we don't speak for any other GPL products. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to many *
* security vendors, and generally include a perpetual license as well as *
* providing for priority support and updates as well as helping to fund *
* the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included Copying.OpenSSL file, and distribute linked *
* combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to fyodor@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering Fyodor and Insecure.Com LLC the unlimited, non-exclusive right *
* to reuse, modify, and relicense the code. Nmap will always be *
* available Open Source, but this is important because the inability to *
* relicense code has caused devastating problems for other Free Software *
* projects (such as KDE and NASM). We also occasionally relicense the *
* code to third parties as discussed above. If you wish to specify *
* special license conditions of your contributions, just say so when you *
* send them. *
* *
* This program is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* General Public License for more details at *
* http://www.gnu.org/copyleft/gpl.html , or in the COPYING file included *
* with Nmap. *
* *
***************************************************************************/
/* $Id$ */
#include "nmap.h"
#include "osscan.h"
#include "scan_engine.h"
#include "idle_scan.h"
#include "timing.h"
#include "NmapOps.h"
#include "MACLookup.h"
#ifdef WIN32
#include "winfix.h"
#endif
using namespace std;
/* global options */
extern char *optarg;
extern int optind;
extern NmapOps o; /* option structure */
#ifdef __amigaos__
extern void CloseLibs(void);
#endif
/* parse the --scanflags argument. It can be a number >=0 or a string consisting of TCP flag names like "URGPSHFIN". Returns -1 if the argument is invalid. */
static int parse_scanflags(char *arg) {
int flagval = 0;
char *end = NULL;
if (isdigit(arg[0])) {
flagval = strtol(arg, &end, 0);
if (*end || flagval < 0 || flagval > 255) return -1;
} else {
if (strcasestr(arg, "FIN")) {
flagval |= TH_FIN;
}
if (strcasestr(arg, "SYN")) {
flagval |= TH_SYN;
}
if (strcasestr(arg, "RST") || strcasestr(arg, "RESET")) {
flagval |= TH_RST;
}
if (strcasestr(arg, "PSH") || strcasestr(arg, "PUSH")) {
flagval |= TH_PUSH;
}
if (strcasestr(arg, "ACK")) {
flagval |= TH_ACK;
}
if (strcasestr(arg, "URG")) {
flagval |= TH_URG;
}
if (strcasestr(arg, "SYN")) {
flagval |= TH_SYN;
}
}
return flagval;
}
/* parse a URL stype ftp string of the form user:pass@server:portno */
static int parse_bounce_argument(struct ftpinfo *ftp, char *url) {
char *p = url,*q, *s;
if ((q = strrchr(url, '@'))) /*we have username and/or pass */ {
*(q++) = '\0';
if ((s = strchr(q, ':')))
{ /* has portno */
*(s++) = '\0';
strncpy(ftp->server_name, q, MAXHOSTNAMELEN);
ftp->port = atoi(s);
}
else strncpy(ftp->server_name, q, MAXHOSTNAMELEN);
if ((s = strchr(p, ':'))) { /* User AND pass given */
*(s++) = '\0';
strncpy(ftp->user, p, 63);
strncpy(ftp->pass, s, 255);
}
else { /* Username ONLY given */
log_write(LOG_STDOUT, "Assuming %s is a username, and using the default password: %s\n",
p, ftp->pass);
strncpy(ftp->user, p, 63);
}
}
else /* no username or password given */
if ((s = strchr(url, ':'))) { /* portno is given */
*(s++) = '\0';
strncpy(ftp->server_name, url, MAXHOSTNAMELEN);
ftp->port = atoi(s);
}
else /* default case, no username, password, or portnumber */
strncpy(ftp->server_name, url, MAXHOSTNAMELEN);
ftp->user[63] = ftp->pass[255] = ftp->server_name[MAXHOSTNAMELEN] = 0;
return 1;
}
int nmap_main(int argc, char *argv[]) {
char *p, *q;
int i, arg;
unsigned int targetno;
size_t j, argvlen;
FILE *inputfd = NULL, *excludefd = NULL;
char *host_spec = NULL, *exclude_spec = NULL;
short fastscan=0, randomize=1, resolve_all=0;
short quashargv = 0;
int numhosts_scanned = 0;
char **host_exp_group;
char *idleProxy = NULL; /* The idle host used to "Proxy" an Idlescan */
int num_host_exp_groups = 0;
char *machinefilename = NULL, *kiddiefilename = NULL,
*normalfilename = NULL, *xmlfilename = NULL;
HostGroupState *hstate = NULL;
int numhosts_up = 0;
int starttime;
char *endptr = NULL;
struct scan_lists *ports = NULL;
TargetGroup *exclude_group = NULL;
char myname[MAXHOSTNAMELEN + 1];
#if (defined(IN_ADDR_DEEPSTRUCT) || defined( SOLARIS))
/* Note that struct in_addr in solaris is 3 levels deep just to store an
* unsigned int! */
struct ftpinfo ftp = { FTPUSER, FTPPASS, "", { { { 0 } } } , 21, 0};
#else
struct ftpinfo ftp = { FTPUSER, FTPPASS, "", { 0 }, 21, 0};
#endif
struct hostent *target = NULL;
char **fakeargv;
Target *currenths;
vector<Target *> Targets;
char *proberr;
char emptystring[1];
int sourceaddrwarning = 0; /* Have we warned them yet about unguessable
source addresses? */
unsigned int ideal_scan_group_sz = 0;
char hostname[MAXHOSTNAMELEN + 1] = "";
const char *spoofmac = NULL;
time_t timep;
char mytime[128];
struct sockaddr_storage ss;
size_t sslen;
int option_index;
bool iflist = false;
struct option long_options[] =
{
{"version", no_argument, 0, 'V'},
{"verbose", no_argument, 0, 'v'},
{"datadir", required_argument, 0, 0},
{"debug", optional_argument, 0, 'd'},
{"help", no_argument, 0, 'h'},
{"iflist", no_argument, 0, 0},
{"max_parallelism", required_argument, 0, 'M'},
{"min_parallelism", required_argument, 0, 0},
{"timing", required_argument, 0, 'T'},
{"timing", no_argument, 0, 0},
{"max_rtt_timeout", required_argument, 0, 0},
{"min_rtt_timeout", required_argument, 0, 0},
{"initial_rtt_timeout", required_argument, 0, 0},
{"excludefile", required_argument, 0, 0},
{"exclude", required_argument, 0, 0},
{"max_hostgroup", required_argument, 0, 0},
{"min_hostgroup", required_argument, 0, 0},
{"scanflags", required_argument, 0, 0},
{"host_timeout", required_argument, 0, 0},
{"scan_delay", required_argument, 0, 0},
{"max_scan_delay", required_argument, 0, 0},
{"oA", required_argument, 0, 0},
{"oN", required_argument, 0, 0},
{"oM", required_argument, 0, 0},
{"oG", required_argument, 0, 0},
{"oS", required_argument, 0, 0},
{"oH", required_argument, 0, 0},
{"oX", required_argument, 0, 0},
{"iL", required_argument, 0, 0},
{"iR", required_argument, 0, 0},
{"sI", required_argument, 0, 0},
{"source_port", required_argument, 0, 'g'},
{"randomize_hosts", no_argument, 0, 0},
{"osscan_limit", no_argument, 0, 0}, /* skip OSScan if no open ports */
{"osscan_guess", no_argument, 0, 0}, /* More guessing flexability */
{"packet_trace", no_argument, 0, 0}, /* Display all packets sent/rcv */
{"version_trace", no_argument, 0, 0}, /* Display -sV related activity */
{"fuzzy", no_argument, 0, 0}, /* Alias for osscan_guess */
{"data_length", required_argument, 0, 0},
{"send_eth", no_argument, 0, 0},
{"send_ip", no_argument, 0, 0},
{"stylesheet", required_argument, 0, 0},
{"no_stylesheet", no_argument, 0, 0},
{"rH", no_argument, 0, 0},
{"vv", no_argument, 0, 0},
{"ff", no_argument, 0, 0},
{"privileged", no_argument, 0, 0},
{"mtu", required_argument, 0, 0},
{"append_output", no_argument, 0, 0},
{"noninteractive", no_argument, 0, 0},
{"spoof_mac", required_argument, 0, 0},
{"ttl", required_argument, 0, 0}, /* Time to live */
{"allports", no_argument, 0, 0},
{"version_intensity", required_argument, 0, 0},
{"version_light", no_argument, 0, 0},
{"version_all", no_argument, 0, 0},
{0, 0, 0, 0}
};
/* argv faking silliness */
fakeargv = (char **) safe_malloc(sizeof(char *) * (argc + 1));
for(i=0; i < argc; i++) {
fakeargv[i] = strdup(argv[i]);
}
fakeargv[argc] = NULL;
emptystring[0] = '\0'; /* It wouldn't be an emptystring w/o this ;) */
if (argc < 2 ) printusage(argv[0], -1);
Targets.reserve(100);
/* OK, lets parse these args! */
optind = 1; /* so it can be called multiple times */
while((arg = getopt_long_only(argc,fakeargv,"6Ab:D:d::e:Ffg:hIi:M:m:NnOo:P:p:qRrS:s:T:Vv", long_options, &option_index)) != EOF) {
switch(arg) {
case 0:
if (strcmp(long_options[option_index].name, "max_rtt_timeout") == 0) {
o.setMaxRttTimeout(atoi(optarg));
if (o.maxRttTimeout() < 5) {
fatal("max_rtt_timeout is given in milliseconds and must be at least 5");
}
if (o.maxRttTimeout() < 20) {
error("WARNING: You specified a round-trip time timeout (%d ms) that is EXTRAORDINARILY SMALL. Accuracy may suffer.", o.maxRttTimeout());
}
} else if (strcmp(long_options[option_index].name, "min_rtt_timeout") == 0) {
o.setMinRttTimeout(atoi(optarg));
if (o.minRttTimeout() > 50000) {
error("Warning: min_rtt_timeout is given in milliseconds, your value seems pretty large.");
}
} else if (strcmp(long_options[option_index].name, "initial_rtt_timeout") == 0) {
o.setInitialRttTimeout(atoi(optarg));
if (o.initialRttTimeout() <= 0) {
fatal("initial_rtt_timeout must be greater than 0");
}
} else if (strcmp(long_options[option_index].name, "excludefile") == 0) {
excludefd = fopen(optarg, "r");
if (!excludefd) {
fatal("Failed to open exclude file %s for reading", optarg);
}
} else if (strcmp(long_options[option_index].name, "exclude") == 0) {
if (excludefd)
fatal("--excludefile and --exclude options are mutually exclusive.");
exclude_spec = strdup(optarg);
} else if (strcmp(long_options[option_index].name, "max_hostgroup") == 0) {
o.setMaxHostGroupSz(atoi(optarg));
} else if (strcmp(long_options[option_index].name, "min_hostgroup") == 0) {
o.setMinHostGroupSz(atoi(optarg));
if (atoi(optarg) > 100)
error("Warning: You specified a highly aggressive --min_hostgroup.");
} else if (strcmp(long_options[option_index].name, "scanflags") == 0) {
o.scanflags = parse_scanflags(optarg);
if (o.scanflags < 0) {
fatal("--scanflags option must be a number between 0 and 255 (inclusive) or a string like \"URGPSHFIN\".");
}
} else if (strcmp(long_options[option_index].name, "iflist") == 0 ) {
iflist = true;
} else if (strcmp(long_options[option_index].name, "min_parallelism") == 0 ) {
o.min_parallelism = atoi(optarg);
if (o.min_parallelism < 1) fatal("Argument to --min_parallelism must be at least 1!");
if (o.min_parallelism > 100) {
error("Warning: Your --min_parallelism option is absurdly high! Don't complain to Fyodor if all hell breaks loose!");
}
} else if (strcmp(long_options[option_index].name, "host_timeout") == 0) {
o.host_timeout = strtoul(optarg, NULL, 10);
if (o.host_timeout <= 200) {
fatal("host_timeout is given in milliseconds and must be greater than 200");
}
} else if (strcmp(long_options[option_index].name, "ttl") == 0) {
o.ttl = atoi(optarg);
if (o.ttl < 0 || o.ttl > 255) {
fatal("ttl option must be a number between 0 and 255 (inclusive)");
}
} else if (strcmp(long_options[option_index].name, "datadir") == 0) {
o.datadir = strdup(optarg);
} else if (strcmp(long_options[option_index].name, "append_output") == 0) {
o.append_output = 1;
} else if (strcmp(long_options[option_index].name, "noninteractive") == 0) {
/* Do nothing */
} else if (strcmp(long_options[option_index].name, "spoof_mac") == 0) {
/* I need to deal with this later, once I'm sure that I have output
files set up, --datadir, etc. */
spoofmac = optarg;
} else if (strcmp(long_options[option_index].name, "allports") == 0) {
o.override_excludeports = 1;
} else if (strcmp(long_options[option_index].name, "version_intensity") == 0) {
o.version_intensity = atoi(optarg);
if (o.version_intensity < 0 || o.version_intensity > 9)
fatal("version_intensity must be between 0 and 9");
} else if (strcmp(long_options[option_index].name, "version_light") == 0) {
o.version_intensity = 2;
} else if (strcmp(long_options[option_index].name, "version_all") == 0) {
o.version_intensity = 9;
} else if (strcmp(long_options[option_index].name, "scan_delay") == 0) {
o.scan_delay = atoi(optarg);
if (o.scan_delay <= 0) {
fatal("scan_delay must be greater than 0");
}
if (o.scan_delay > o.maxTCPScanDelay()) o.setMaxTCPScanDelay(o.scan_delay);
if (o.scan_delay > o.maxUDPScanDelay()) o.setMaxUDPScanDelay(o.scan_delay);
o.max_parallelism = 1;
} else if (strcmp(long_options[option_index].name, "max_scan_delay") == 0) {
unsigned int scand = atoi(optarg);
if (scand < 0) {
fatal("max_scan_delay must be greater than 0");
}
o.setMaxTCPScanDelay(scand);
o.setMaxUDPScanDelay(scand);
} else if (strcmp(long_options[option_index].name, "randomize_hosts") == 0
|| strcmp(long_options[option_index].name, "rH") == 0) {
o.randomize_hosts = 1;
o.ping_group_sz = PING_GROUP_SZ * 4;
} else if (strcmp(long_options[option_index].name, "osscan_limit") == 0) {
o.osscan_limit = 1;
} else if (strcmp(long_options[option_index].name, "osscan_guess") == 0
|| strcmp(long_options[option_index].name, "fuzzy") == 0) {
o.osscan_guess = 1;
} else if (strcmp(long_options[option_index].name, "packet_trace") == 0) {
o.setPacketTrace(true);
} else if (strcmp(long_options[option_index].name, "version_trace") == 0) {
o.setVersionTrace(true);
o.debugging++;
} else if (strcmp(long_options[option_index].name, "data_length") == 0) {
o.extra_payload_length = atoi(optarg);
if (o.extra_payload_length < 0) {
fatal("data_length must be greater than 0");
} else if (o.extra_payload_length > 0) {
o.extra_payload = (char *) safe_malloc(o.extra_payload_length);
get_random_bytes(o.extra_payload, o.extra_payload_length);
}
} else if (strcmp(long_options[option_index].name, "send_eth") == 0) {
o.sendpref = PACKET_SEND_ETH_STRONG;
} else if (strcmp(long_options[option_index].name, "send_ip") == 0) {
o.sendpref = PACKET_SEND_IP_STRONG;
} else if (strcmp(long_options[option_index].name, "stylesheet") == 0) {
o.setXSLStyleSheet(optarg);
} else if (strcmp(long_options[option_index].name, "no_stylesheet") == 0) {
o.setXSLStyleSheet(NULL);
} else if (strcmp(long_options[option_index].name, "oN") == 0) {
normalfilename = optarg;
} else if (strcmp(long_options[option_index].name, "oG") == 0 ||
strcmp(long_options[option_index].name, "oM") == 0) {
machinefilename = optarg;
} else if (strcmp(long_options[option_index].name, "oS") == 0) {
kiddiefilename = optarg;
} else if (strcmp(long_options[option_index].name, "oH") == 0) {
fatal("HTML output is not yet supported");
} else if (strcmp(long_options[option_index].name, "oX") == 0) {
xmlfilename = optarg;
} else if (strcmp(long_options[option_index].name, "oA") == 0) {
char buf[MAXPATHLEN];
snprintf(buf, sizeof(buf), "%s.nmap", optarg);
normalfilename = strdup(buf);
snprintf(buf, sizeof(buf), "%s.gnmap", optarg);
machinefilename = strdup(buf);
snprintf(buf, sizeof(buf), "%s.xml", optarg);
xmlfilename = strdup(buf);
}
else if (strcmp(long_options[option_index].name, "iL") == 0) {
if (inputfd) {
fatal("Only one input filename allowed");
}
if (!strcmp(optarg, "-")) {
inputfd = stdin;
} else {
inputfd = fopen(optarg, "r");
if (!inputfd) {
fatal("Failed to open input file %s for reading", optarg);
}
}
} else if (strcmp(long_options[option_index].name, "iR") == 0) {
o.generate_random_ips = 1;
o.max_ips_to_scan = strtoul(optarg, &endptr, 10);
if (*endptr != '\0') {
fatal("ERROR: -iR argument must be the maximum number of random IPs you wish to scan (use 0 for unlimited)");
}
} else if (strcmp(long_options[option_index].name, "sI") == 0) {
o.idlescan = 1;
idleProxy = optarg;
} else if (strcmp(long_options[option_index].name, "vv") == 0) {
/* Compatability hack ... ugly */
o.verbose += 2;
} else if (strcmp(long_options[option_index].name, "ff") == 0) {
o.fragscan += 16;
} else if (strcmp(long_options[option_index].name, "privileged") == 0) {
o.isr00t = 1;
} else if (strcmp(long_options[option_index].name, "mtu") == 0) {
o.fragscan = atoi(optarg);
if (o.fragscan <= 0 || o.fragscan % 8 != 0)
fatal("Data payload MTU must be >0 and multiple of 8");
} else {
fatal("Unknown long option (%s) given@#!$#$", long_options[option_index].name);
}
break;
case '6':
#if !HAVE_IPV6
fatal("I am afraid IPv6 is not available because your host doesn't support it or you chose to compile Nmap w/o IPv6 support.");
#else
o.setaf(AF_INET6);
#endif /* !HAVE_IPV6 */
break;
case 'A':
o.servicescan = true;
if (o.isr00t)
o.osscan++;
break;
case 'b':
o.bouncescan++;
if (parse_bounce_argument(&ftp, optarg) < 0 ) {
fprintf(stderr, "Your argument to -b is b0rked. Use the normal url style: user:pass@server:port or just use server and use default anon login\n Use -h for help\n");
}
break;
case 'D':
p = optarg;
do {
q = strchr(p, ',');
if (q) *q = '\0';
if (!strcasecmp(p, "me")) {
if (o.decoyturn != -1)
fatal("Can only use 'ME' as a decoy once.\n");
o.decoyturn = o.numdecoys++;
} else {
if (o.numdecoys >= MAX_DECOYS -1)
fatal("You are only allowed %d decoys (if you need more redefine MAX_DECOYS in nmap.h)", MAX_DECOYS);
if (resolve(p, &o.decoys[o.numdecoys])) {
o.numdecoys++;
} else {
fatal("Failed to resolve decoy host: %s (must be hostname or IP address", optarg);
}
}
if (q) {
*q = ',';
p = q+1;
}
} while(q);
break;
case 'd':
if (optarg)
o.debugging = o.verbose = atoi(optarg);
else {
o.debugging++; o.verbose++;
}
break;
case 'e':
strncpy(o.device, optarg,63); o.device[63] = '\0'; break;
case 'F': fastscan++; break;
case 'f': o.fragscan += 8; break;
case 'g':
o.magic_port = atoi(optarg);
o.magic_port_set = 1;
if (!o.magic_port) fatal("-g needs nonzero argument");
break;
case 'h': printusage(argv[0], 0); break;
case '?': printusage(argv[0], -1); break;
case 'I':
printf("WARNING: identscan (-I) no longer supported. Ignoring -I\n");
break;
// o.identscan++; break;
case 'i':
if (inputfd) {
fatal("Only one input filename allowed");
}
if (!strcmp(optarg, "-")) {
inputfd = stdin;
} else {
inputfd = fopen(optarg, "r");
if (!inputfd) {
fatal("Failed to open input file %s for reading", optarg);
}
}
break;
case 'M':
o.max_parallelism = atoi(optarg);
if (o.max_parallelism < 1) fatal("Argument to -M must be at least 1!");
if (o.max_parallelism > 900) {
error("Warning: Your max_parallelism (-M) option is absurdly high! Don't complain to Fyodor if all hell breaks loose!");
}
break;
case 'm':
machinefilename = optarg;
break;
case 'n': o.noresolve++; break;
case 'O':
o.osscan++;
break;
case 'o':
normalfilename = optarg;
break;
case 'P':
if (*optarg == '\0' || *optarg == 'I' || *optarg == 'E')
o.pingtype |= PINGTYPE_ICMP_PING;
else if (*optarg == 'M')
o.pingtype |= PINGTYPE_ICMP_MASK;
else if (*optarg == 'P')
o.pingtype |= PINGTYPE_ICMP_TS;
else if (*optarg == '0' || *optarg == 'N' || *optarg == 'D')
o.pingtype = PINGTYPE_NONE;
else if (*optarg == 'R')
o.pingtype |= PINGTYPE_ARP;
else if (*optarg == 'S') {
o.pingtype |= (PINGTYPE_TCP|PINGTYPE_TCP_USE_SYN);
if (isdigit((int) *(optarg+1)))
{
o.num_ping_synprobes = numberlist2array(optarg+1, o.ping_synprobes, sizeof(o.ping_synprobes), &proberr);
if (o.num_ping_synprobes < 0) {
fatal("Bogus argument to -PS: %s", proberr);
}
}
if (o.num_ping_synprobes == 0) {
o.num_ping_synprobes = 1;
o.ping_synprobes[0] = DEFAULT_TCP_PROBE_PORT;
}
}
else if (*optarg == 'T' || *optarg == 'A') {
o.pingtype |= (PINGTYPE_TCP|PINGTYPE_TCP_USE_ACK);
if (isdigit((int) *(optarg+1))) {
o.num_ping_ackprobes = numberlist2array(optarg+1, o.ping_ackprobes, sizeof(o.ping_ackprobes), &proberr);
if (o.num_ping_ackprobes < 0) {
fatal("Bogus argument to -PB: %s", proberr);
}
}
if (o.num_ping_ackprobes == 0) {
o.num_ping_ackprobes = 1;
o.ping_ackprobes[0] = DEFAULT_TCP_PROBE_PORT;
}
}
else if (*optarg == 'U') {
o.pingtype |= (PINGTYPE_UDP);
if (isdigit((int) *(optarg+1))) {
o.num_ping_udpprobes = numberlist2array(optarg+1, o.ping_udpprobes, sizeof(o.ping_udpprobes), &proberr);
if (o.num_ping_udpprobes < 0) {
fatal("Bogus argument to -PU: %s", proberr);
}
}
if (o.num_ping_udpprobes == 0) {
o.num_ping_udpprobes = 1;
o.ping_udpprobes[0] = DEFAULT_UDP_PROBE_PORT;
}
}
else if (*optarg == 'B') {
o.pingtype = (PINGTYPE_TCP|PINGTYPE_TCP_USE_ACK|PINGTYPE_ICMP_PING);
if (isdigit((int) *(optarg+1))) {
o.num_ping_ackprobes = numberlist2array(optarg+1, o.ping_ackprobes, sizeof(o.ping_ackprobes), &proberr);
if (o.num_ping_ackprobes < 0) {
fatal("Bogus argument to -PB: %s", proberr);
}
}
if (o.num_ping_ackprobes == 0) {
o.num_ping_ackprobes = 1;
o.ping_ackprobes[0] = DEFAULT_TCP_PROBE_PORT;
}
} else if (*optarg == 'O') {
fatal("-PO (the letter O)? No such option. Perhaps you meant to disable pings with -P0 (Zero).");
} else {
fatal("Illegal Argument to -P, use -P0, -PI, -PB, -PE, -PM, -PP, -PA, -PU, -PT, or -PT80 (or whatever number you want for the TCP probe destination port)");
}
break;
case 'p':
if (ports)
fatal("Only 1 -p option allowed, separate multiple ranges with commas.");
ports = getpts(optarg);
if (!ports)
fatal("Your port specification string is not parseable");
break;
case 'q': quashargv++; break;
case 'R': resolve_all++; break;
case 'r':
randomize = 0;
break;
case 'S':
if (o.spoofsource)
fatal("You can only use the source option once! Use -D <decoy1> -D <decoy2> etc. for decoys\n");
if (resolve(optarg, &ss, &sslen, o.af()) == 0) {
fatal("Failed to resolve/decode supposed %s source address %s. Note that if you are using IPv6, the -6 argument must come before -S", (o.af() == AF_INET)? "IPv4" : "IPv6", optarg);
}
o.setSourceSockAddr(&ss, sslen);
o.spoofsource = 1;
break;
case 's':
if (!*optarg) {
fprintf(stderr, "An option is required for -s, most common are -sT (tcp scan), -sS (SYN scan), -sF (FIN scan), -sU (UDP scan) and -sP (Ping scan)");
printusage(argv[0], -1);
}
p = optarg;
while(*p) {
switch(*p) {
case 'A': o.ackscan = 1; break;
case 'B': fatal("No scan type 'B', did you mean bounce scan (-b)?");
break;
case 'F': o.finscan = 1; break;
case 'L': o.listscan = 1; o.pingtype = PINGTYPE_NONE; break;
case 'M': o.maimonscan = 1; break;
case 'N': o.nullscan = 1; break;
case 'O': o.ipprotscan = 1; break;
case 'P': o.pingscan = 1; break;
case 'R': o.rpcscan = 1; break;
case 'S': o.synscan = 1; break;
case 'W': o.windowscan = 1; break;
case 'T': o.connectscan = 1; break;
case 'V': o.servicescan = 1; break;
case 'U':
o.udpscan++;
break;
case 'X': o.xmasscan++;break;
default: error("Scantype %c not supported\n",*p); printusage(argv[0], -1); break;
}
p++;
}
break;
case 'T':
if (*optarg == '0' || (strcasecmp(optarg, "Paranoid") == 0)) {
o.timing_level = 0;
o.max_parallelism = 1;
o.scan_delay = 300000;
o.setInitialRttTimeout(300000);
} else if (*optarg == '1' || (strcasecmp(optarg, "Sneaky") == 0)) {
o.timing_level = 1;
o.max_parallelism = 1;
o.scan_delay = 15000;
o.setInitialRttTimeout(15000);
} else if (*optarg == '2' || (strcasecmp(optarg, "Polite") == 0)) {
o.timing_level = 2;
o.max_parallelism = 1;
o.scan_delay = 400;
} else if (*optarg == '3' || (strcasecmp(optarg, "Normal") == 0)) {
} else if (*optarg == '4' || (strcasecmp(optarg, "Aggressive") == 0)) {
o.timing_level = 4;
o.setMinRttTimeout(100);
o.setMaxRttTimeout(1250);
o.setInitialRttTimeout(500);
o.setMaxTCPScanDelay(10);
} else if (*optarg == '5' || (strcasecmp(optarg, "Insane") == 0)) {
o.timing_level = 5;
o.setMinRttTimeout(50);
o.setMaxRttTimeout(300);
o.setInitialRttTimeout(250);
o.host_timeout = 900000;
o.setMaxTCPScanDelay(5);
} else {
fatal("Unknown timing mode (-T argment). Use either \"Paranoid\", \"Sneaky\", \"Polite\", \"Normal\", \"Aggressive\", \"Insane\" or a number from 0 (Paranoid) to 5 (Insane)");
}
break;
case 'V':
printf("\n%s version %s ( %s )\n", NMAP_NAME, NMAP_VERSION, NMAP_URL);
exit(0);
break;
case 'v': o.verbose++; break;
}
}
#ifdef WIN32
win_init();
#endif
#if HAVE_SIGNAL
if (!o.debugging)
signal(SIGSEGV, sigdie);
#endif
if (o.osscan)
o.reference_FPs = parse_fingerprint_reference_file();
o.ValidateOptions();
/* Open the log files, now that we know whether the user wants them appended
or overwritten */
if (normalfilename)
log_open(LOG_NORMAL, o.append_output, normalfilename);
if (machinefilename)
log_open(LOG_MACHINE, o.append_output, machinefilename);
if (kiddiefilename)
log_open(LOG_SKID, o.append_output, kiddiefilename);
if (xmlfilename)
log_open(LOG_XML, o.append_output, xmlfilename);
if (!o.interactivemode) {
char tbuf[128];
struct tm *tm;
time_t now = time(NULL);
if (!(tm = localtime(&now)))
fatal("Unable to get current localtime()#!#");
// ISO 8601 date/time -- http://www.cl.cam.ac.uk/~mgk25/iso-time.html
if (strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M %Z", tm) <= 0)
fatal("Unable to properly format time");
log_write(LOG_STDOUT|LOG_SKID, "\nStarting %s %s ( %s ) at %s\n", NMAP_NAME, NMAP_VERSION, NMAP_URL, tbuf);
if (o.verbose && tm->tm_mon == 8 && tm->tm_mday == 1) {
log_write(LOG_STDOUT|LOG_SKID, "Happy %dth Birthday to Nmap, may it live to be %d!\n", tm->tm_year - 97, tm->tm_year + 3 );
}
if (iflist) {
print_iflist();
exit(0);
}
}
if ((o.pingscan || o.listscan) && fastscan) {
fatal("The fast scan (-F) is incompatible with ping scan");
}
if (fastscan && ports) {
fatal("You can specify fast scan (-F) or explicitly select individual ports (-p), but not both");
} else if (fastscan && o.ipprotscan) {
ports = getfastprots();
} else if (fastscan) {
ports = getfastports(o.TCPScan(), o.UDPScan());
}
if ((o.pingscan || o.listscan) && ports) {
fatal("You cannot use -F (fast scan) or -p (explicit port selection) with PING scan or LIST scan");
}
#ifdef WIN32
if (o.sendpref & PACKET_SEND_IP) {
error("WARNING: raw IP (rather than raw ethernet) packet sending attempted on Windows. This probably won't work. Consider --send_eth next time.\n");
}
#endif
if (spoofmac) {
u8 mac_data[6];
int pos = 0; /* Next index of mac_data to fill in */
char tmphex[3];
/* A zero means set it all randomly. Anything that is all digits
or colons is treated as a prefix, with remaining characters for
the 6-byte MAC (if any) chosen randomly. Otherwise, it is
treated as a vendor string for lookup in nmap-mac-prefixes */
if (strcmp(spoofmac, "0") == 0) {
pos = 0;
} else {
const char *p = spoofmac;
while(*p) {
if (*p == ':') p++;
if (isxdigit(*p) && isxdigit(*(p+1))) {
if (pos >= 6) fatal("Bogus --spoof_mac value encountered (%s) -- only up to 6 bytes permitted", spoofmac);
tmphex[0] = *p; tmphex[1] = *(p+1); tmphex[2] = '\0';
mac_data[pos] = (u8) strtol(tmphex, NULL, 16);
pos++;
p += 2;
} else break;
}
if (*p) {
/* Failed to parse it as a MAC prefix -- treating as a vendor substring instead */
if (!MACCorp2Prefix(spoofmac, mac_data))
fatal("Could not parse as a prefix nor find as a vendor substring the given --spoof_mac argument: %s. If you are giving hex digits, there must be an even number of them.", spoofmac);
pos = 3;
}
}
if (pos < 6) {
get_random_bytes(mac_data + pos, 6 - pos);
}
/* Got the new MAC! */
const char *vend = MACPrefix2Corp(mac_data);
log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT,
"Spoofing MAC address %02X:%02X:%02X:%02X:%02X:%02X (%s)\n",
mac_data[0], mac_data[1], mac_data[2], mac_data[3], mac_data[4],
mac_data[5], vend? vend : "No registered vendor");
o.setSpoofMACAddress(mac_data);
/* If they want to spoof the MAC address, we should at least make
some effort to actually send raw ethernet frames rather than IP
packets (which would use the real IP */
if (o.sendpref != PACKET_SEND_IP_STRONG)
o.sendpref = PACKET_SEND_ETH_STRONG;
}
if (!ports) {
if (o.ipprotscan) {
ports = getdefaultprots();
} else {
ports = getdefaultports(o.TCPScan(), o.UDPScan());
}
}
/* By now, we've got our port lists. Give the user a warning if no
* ports are specified for the type of scan being requested. Other things
* (such as OS ident scan) might break cause no ports were specified, but
* we've given our warning...
*/
if ((o.TCPScan()) && ports->tcp_count == 0)
error("WARNING: a TCP scan type was requested, but no tcp ports were specified. Skipping this scan type.");
if (o.UDPScan() && ports->udp_count == 0)
error("WARNING: UDP scan was requested, but no udp ports were specified. Skipping this scan type.");
if (o.ipprotscan && ports->prot_count == 0)
error("WARNING: protocol scan was requested, but no protocols were specified to be scanned. Skipping this scan type.");
/* Set up our array of decoys! */
if (o.decoyturn == -1) {
o.decoyturn = (o.numdecoys == 0)? 0 : get_random_uint() % o.numdecoys;
o.numdecoys++;
for(i=o.numdecoys-1; i > o.decoyturn; i--)
o.decoys[i] = o.decoys[i-1];
}
/* We need to find what interface to route through if:
* --None have been specified AND
* --We are root and doing tcp ping OR
* --We are doing a raw sock scan and NOT pinging anyone */
if (o.af() == AF_INET && o.v4sourceip() && !*o.device) {
if (ipaddr2devname(o.device, o.v4sourceip()) != 0) {
fatal("Could not figure out what device to send the packet out on with the source address you gave me! If you are trying to sp00f your scan, this is normal, just give the -e eth0 or -e ppp0 or whatever. Otherwise you can still use -e, but I find it kindof fishy.");
}
}
if (o.af() == AF_INET && *o.device && !o.v4sourceip()) {
struct sockaddr_in tmpsock;
memset(&tmpsock, 0, sizeof(tmpsock));
if (devname2ipaddr(o.device, &(tmpsock.sin_addr)) == -1) {
fatal("I cannot figure out what source address to use for device %s, does it even exist?", o.device);
}
tmpsock.sin_family = AF_INET;
#if HAVE_SOCKADDR_SA_LEN
tmpsock.sin_len = sizeof(tmpsock);
#endif
o.setSourceSockAddr((struct sockaddr_storage *) &tmpsock, sizeof(tmpsock));
}
/* If he wants to bounce off of an ftp site, that site better damn well be reachable! */
if (o.bouncescan) {
if (!inet_aton(ftp.server_name, &ftp.server)) {
if ((target = gethostbyname(ftp.server_name)))
memcpy(&ftp.server, target->h_addr_list[0], 4);
else {
fprintf(stderr, "Failed to resolve ftp bounce proxy hostname/IP: %s\n",
ftp.server_name);
exit(1);
}
} else if (o.verbose)
log_write(LOG_STDOUT, "Resolved ftp bounce attack proxy to %s (%s).\n",
ftp.server_name, inet_ntoa(ftp.server));
}
fflush(stdout);
fflush(stderr);
timep = time(NULL);
/* Brief info incase they forget what was scanned */
Strncpy(mytime, ctime(&timep), sizeof(mytime));
chomp(mytime);
char *xslfname = o.XSLStyleSheet();
char xslline[1024];
if (xslfname) {
char *p = xml_convert(xslfname);
snprintf(xslline, sizeof(xslline), "<?xml-stylesheet href=\"%s\" type=\"text/xsl\"?>\n", p);
free(p);
} else xslline[0] = '\0';
log_write(LOG_XML, "<?xml version=\"1.0\" ?>\n%s<!-- ", xslline);
log_write(LOG_NORMAL|LOG_MACHINE, "# ");
log_write(LOG_NORMAL|LOG_MACHINE|LOG_XML, "%s %s scan initiated %s as: ", NMAP_NAME, NMAP_VERSION, mytime);
for(i=0; i < argc; i++) {
char *p = xml_convert(fakeargv[i]);
log_write(LOG_XML,"%s ", p);
free(p);
log_write(LOG_NORMAL|LOG_MACHINE,"%s ", fakeargv[i]);
}
log_write(LOG_XML, "-->");
log_write(LOG_NORMAL|LOG_MACHINE|LOG_XML,"\n");
log_write(LOG_XML, "<nmaprun scanner=\"nmap\" args=\"");
for(i=0; i < argc; i++)
log_write(LOG_XML, (i == argc-1)? "%s\" " : "%s ", fakeargv[i]);
log_write(LOG_XML, "start=\"%lu\" startstr=\"%s\" version=\"%s\" xmloutputversion=\"1.01\">\n",
(unsigned long) timep, mytime, NMAP_VERSION);
output_xml_scaninfo_records(ports);
log_write(LOG_XML, "<verbose level=\"%d\" />\n<debugging level=\"%d\" />\n",
o.verbose, o.debugging);
/* Before we randomize the ports scanned, lets output them to machine
parseable output */
if (o.verbose)
output_ports_to_machine_parseable_output(ports, o.TCPScan(), o.udpscan, o.ipprotscan);
/* more fakeargv junk, BTW malloc'ing extra space in argv[0] doesn't work */
if (quashargv) {
argvlen = strlen(argv[0]);
if (argvlen < strlen(FAKE_ARGV))
fatal("If you want me to fake your argv, you need to call the program with a longer name. Try the full pathname, or rename it fyodorssuperdedouperportscanner");
strncpy(argv[0], FAKE_ARGV, strlen(FAKE_ARGV));
for(j = strlen(FAKE_ARGV); j < argvlen; j++) argv[0][j] = '\0';
for(i=1; i < argc; i++) {
argvlen = strlen(argv[i]);
for(j=0; j <= argvlen; j++)
argv[i][j] = '\0';
}
}
#if defined(HAVE_SIGNAL) && defined(SIGPIPE)
signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE so our program doesn't crash because
of it, but we really shouldn't get an unsuspected
SIGPIPE */
#endif
if (o.max_parallelism && (i = max_sd()) && i < o.max_parallelism) {
fprintf(stderr, "WARNING: Your specified max_parallel_sockets of %d, but your system says it might only give us %d. Trying anyway\n", o.max_parallelism, i);