-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput.cc
2712 lines (2417 loc) · 92 KB
/
output.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
/***************************************************************************
* output.cc -- Handles the Nmap output system. This currently involves *
* console-style human readable output, XML output, Script |<iddi3 *
* output, and the legacy grepable output (used to be called "machine *
* readable"). I expect that future output forms (such as HTML) may be *
* created by a different program, library, or script using the XML *
* output. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2022 Nmap Software LLC ("The Nmap *
* Project"). Nmap is also a registered trademark of the Nmap Project. *
* *
* This program is distributed under the terms of the Nmap Public Source *
* License (NPSL). The exact license text applying to a particular Nmap *
* release or source code control revision is contained in the LICENSE *
* file distributed with that version of Nmap or source code control *
* revision. More Nmap copyright/legal information is available from *
* https://nmap.org/book/man-legal.html, and further information on the *
* NPSL license itself can be found at https://nmap.org/npsl/ . This *
* header summarizes some key points from the Nmap license, but is no *
* substitute for the actual license text. *
* *
* Nmap is generally free for end users to download and use themselves, *
* including commercial use. It is available from https://nmap.org. *
* *
* The Nmap license generally prohibits companies from using and *
* redistributing Nmap in commercial products, but we sell a special Nmap *
* OEM Edition with a more permissive license and special features for *
* this purpose. See https://nmap.org/oem/ *
* *
* If you have received a written Nmap license agreement or contract *
* stating terms other than these (such as an Nmap OEM license), you may *
* choose to use and redistribute Nmap under those terms instead. *
* *
* The official Nmap Windows builds include the Npcap software *
* (https://npcap.com) for packet capture and transmission. It is under *
* separate license terms which forbid redistribution without special *
* permission. So the official Nmap Windows builds may not be *
* redistributed without special permission (such as an Nmap OEM *
* license). *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes. *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to submit your *
* changes as a Github PR or by email to the [email protected] mailing list *
* for possible incorporation into the main distribution. Unless you *
* specify otherwise, it is understood that you are offering us very *
* broad rights to use your submissions as described in the Nmap Public *
* Source License Contributor Agreement. This is important because we *
* fund the project by selling licenses with various terms, and also *
* because the inability to relicense code has caused devastating *
* problems for other Free Software projects (such as KDE and NASM). *
* *
* The free version of Nmap is distributed in the hope that it will be *
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Warranties, *
* indemnification and commercial support are all available through the *
* Npcap OEM program--see https://nmap.org/oem/ *
* *
***************************************************************************/
/* $Id$ */
#include "nmap.h"
#include "output.h"
#include "osscan.h"
#include "osscan2.h"
#include "NmapOps.h"
#include "NmapOutputTable.h"
#include "MACLookup.h"
#include "portreasons.h"
#include "protocols.h"
#include "FingerPrintResults.h"
#include "tcpip.h"
#include "Target.h"
#include "nmap_error.h"
#include "utils.h"
#include "xml.h"
#include "nbase.h"
#include "libnetutil/netutil.h"
#include <nsock.h>
#include <math.h>
#include <set>
#include <vector>
#include <list>
#include <sstream>
extern NmapOps o;
static const char *logtypes[LOG_NUM_FILES] = LOG_NAMES;
/* Used in creating skript kiddie style output. |<-R4d! */
static void skid_output(char *s) {
int i;
for (i = 0; s[i]; i++)
/* We need a 50/50 chance here, use a random number */
if ((get_random_u8() & 0x01) == 0)
/* Substitutions commented out are not known to me, but maybe look nice */
switch (s[i]) {
case 'A':
s[i] = '4';
break;
/* case 'B': s[i]='8'; break;
case 'b': s[i]='6'; break;
case 'c': s[i]='k'; break;
case 'C': s[i]='K'; break; */
case 'e':
case 'E':
s[i] = '3';
break;
case 'i':
case 'I':
s[i] = "!|1"[get_random_u8() % 3];
break;
/* case 'k': s[i]='c'; break;
case 'K': s[i]='C'; break; */
case 'o':
case 'O':
s[i] = '0';
break;
case 's':
case 'S':
if (s[i + 1] && !isalnum((int) (unsigned char) s[i + 1]))
s[i] = 'z';
else
s[i] = '$';
break;
case 'z':
s[i] = 's';
break;
case 'Z':
s[i] = 'S';
break;
} else {
if (s[i] >= 'A' && s[i] <= 'Z' && (get_random_u8() % 3 == 0)) {
s[i] += 'a' - 'A'; /* 1/3 chance of lower-case */
} else if (s[i] >= 'a' && s[i] <= 'z' && (get_random_u8() % 3 == 0)) {
s[i] -= 'a' - 'A'; /* 1/3 chance of upper-case */
}
}
}
/* Remove all "\nSF:" from fingerprints */
static char *servicefp_sf_remove(const char *str) {
char *temp = (char *) safe_malloc(strlen(str) + 1);
char *dst = temp, *src = (char *) str;
char *ampptr = 0;
while (*src) {
if (strncmp(src, "\nSF:", 4) == 0) {
src += 4;
continue;
}
/* Needed so "&something;" is not truncated midway */
if (*src == '&') {
ampptr = dst;
} else if (*src == ';') {
ampptr = 0;
}
*dst++ = *src++;
}
if (ampptr != 0) {
*ampptr = '\0';
} else {
*dst = '\0';
}
return temp;
}
// Prints an XML <service> element for the information given in
// serviceDeduction. This function should only be called if ether
// the service name or the service fingerprint is non-null.
static void print_xml_service(const struct serviceDeductions *sd) {
xml_open_start_tag("service");
xml_attribute("name", "%s", sd->name ? sd->name : "unknown");
if (sd->product)
xml_attribute("product", "%s", sd->product);
if (sd->version)
xml_attribute("version", "%s", sd->version);
if (sd->extrainfo)
xml_attribute("extrainfo", "%s", sd->extrainfo);
if (sd->hostname)
xml_attribute("hostname", "%s", sd->hostname);
if (sd->ostype)
xml_attribute("ostype", "%s", sd->ostype);
if (sd->devicetype)
xml_attribute("devicetype", "%s", sd->devicetype);
if (sd->service_fp) {
char *servicefp = servicefp_sf_remove(sd->service_fp);
xml_attribute("servicefp", "%s", servicefp);
free(servicefp);
}
if (sd->service_tunnel == SERVICE_TUNNEL_SSL)
xml_attribute("tunnel", "ssl");
xml_attribute("method", "%s", (sd->dtype == SERVICE_DETECTION_TABLE) ? "table" : "probed");
xml_attribute("conf", "%i", sd->name_confidence);
if (sd->cpe.empty()) {
xml_close_empty_tag();
} else {
unsigned int i;
xml_close_start_tag();
for (i = 0; i < sd->cpe.size(); i++) {
xml_start_tag("cpe");
xml_write_escaped("%s", sd->cpe[i]);
xml_end_tag();
}
xml_end_tag();
}
}
#ifdef WIN32
/* Show a fatal error explaining that an interface is not Ethernet and won't
work on Windows. Do nothing if --send-ip (PACKET_SEND_IP_STRONG) was used. */
void win32_fatal_raw_sockets(const char *devname) {
if ((o.sendpref & PACKET_SEND_IP_STRONG) != 0)
return;
if (devname != NULL) {
fatal("Only ethernet devices can be used for raw scans on Windows, and\n"
"\"%s\" is not an ethernet device. Use the --unprivileged option\n"
"for this scan.", devname);
} else {
fatal("Only ethernet devices can be used for raw scans on Windows. Use\n"
"the --unprivileged option for this scan.");
}
}
/* Display the mapping from libdnet interface names (like "eth0") to Npcap
interface names (like "\Device\NPF_{...}"). This is the same mapping used by
eth_open and so can help diagnose connection problems. Additionally display
Npcap interface names that are not mapped to by any libdnet name, in other
words the names of interfaces Nmap has no way of using.*/
static void print_iflist_pcap_mapping(const struct interface_info *iflist,
int numifs) {
pcap_if_t *pcap_ifs = NULL;
char errbuf[PCAP_ERRBUF_SIZE];
std::list<const pcap_if_t *> leftover_pcap_ifs;
std::list<const pcap_if_t *>::iterator leftover_p;
int i;
/* Build a list of "leftover" libpcap interfaces. Initially it contains all
the interfaces. */
if (o.have_pcap) {
if (pcap_findalldevs(&pcap_ifs, errbuf) == -1) {
fatal("pcap_findalldevs(): Cannot retrieve pcap interfaces: %s", errbuf);
}
for (const pcap_if_t *p = pcap_ifs; p != NULL; p = p->next)
leftover_pcap_ifs.push_front(p);
}
if (numifs > 0 || !leftover_pcap_ifs.empty()) {
NmapOutputTable Tbl(1 + numifs + leftover_pcap_ifs.size(), 2);
Tbl.addItem(0, 0, false, "DEV");
Tbl.addItem(0, 1, false, "WINDEVICE");
/* Show the libdnet names and what they map to. */
for (i = 0; i < numifs; i++) {
char pcap_name[1024];
if (DnetName2PcapName(iflist[i].devname, pcap_name, sizeof(pcap_name))) {
/* We got a name. Remove it from the list of leftovers. */
std::list<const pcap_if_t *>::iterator next;
for (leftover_p = leftover_pcap_ifs.begin();
leftover_p != leftover_pcap_ifs.end(); leftover_p = next) {
next = leftover_p;
next++;
if (strcmp((*leftover_p)->name, pcap_name) == 0)
leftover_pcap_ifs.erase(leftover_p);
}
} else {
Strncpy(pcap_name, "<none>", sizeof(pcap_name));
}
Tbl.addItem(i + 1, 0, false, iflist[i].devname);
Tbl.addItem(i + 1, 1, true, pcap_name);
}
/* Show the "leftover" libpcap interface names (those without a libdnet
name that maps to them). */
for (leftover_p = leftover_pcap_ifs.begin();
leftover_p != leftover_pcap_ifs.end();
leftover_p++) {
Tbl.addItem(i + 1, 0, false, "<none>");
Tbl.addItem(i + 1, 1, false, (*leftover_p)->name);
i++;
}
log_write(LOG_PLAIN, "%s\n", Tbl.printableTable(NULL));
log_flush_all();
}
if (pcap_ifs) {
pcap_freealldevs(pcap_ifs);
}
}
#endif
/* Print a detailed list of Nmap interfaces and routes to
normal/skiddy/stdout output */
int print_iflist(void) {
int numifs = 0, numroutes = 0;
struct interface_info *iflist;
struct sys_route *routes;
NmapOutputTable *Tbl = NULL;
char errstr[256];
const char *address = NULL;
errstr[0]='\0';
iflist = getinterfaces(&numifs, errstr, sizeof(errstr));
int i;
/* First let's handle interfaces ... */
if (iflist==NULL || numifs<=0) {
log_write(LOG_PLAIN, "INTERFACES: NONE FOUND(!)\n");
if (o.debugging)
log_write(LOG_STDOUT, "Reason: %s\n", errstr);
} else {
int devcol = 0, shortdevcol = 1, ipcol = 2, typecol = 3, upcol = 4, mtucol = 5, maccol = 6;
Tbl = new NmapOutputTable(numifs + 1, 7);
Tbl->addItem(0, devcol, false, "DEV", 3);
Tbl->addItem(0, shortdevcol, false, "(SHORT)", 7);
Tbl->addItem(0, ipcol, false, "IP/MASK", 7);
Tbl->addItem(0, typecol, false, "TYPE", 4);
Tbl->addItem(0, upcol, false, "UP", 2);
Tbl->addItem(0, mtucol, false, "MTU", 3);
Tbl->addItem(0, maccol, false, "MAC", 3);
for (i = 0; i < numifs; i++) {
Tbl->addItem(i + 1, devcol, false, iflist[i].devfullname);
Tbl->addItemFormatted(i + 1, shortdevcol, false, "(%s)",
iflist[i].devname);
address = inet_ntop_ez(&(iflist[i].addr), sizeof(iflist[i].addr));
Tbl->addItemFormatted(i + 1, ipcol, false, "%s/%d",
address == NULL ? "(none)" : address,
iflist[i].netmask_bits);
if (iflist[i].device_type == devt_ethernet) {
Tbl->addItem(i + 1, typecol, false, "ethernet");
Tbl->addItemFormatted(i + 1, maccol, false,
"%02X:%02X:%02X:%02X:%02X:%02X",
iflist[i].mac[0], iflist[i].mac[1],
iflist[i].mac[2], iflist[i].mac[3],
iflist[i].mac[4], iflist[i].mac[5]);
} else if (iflist[i].device_type == devt_loopback)
Tbl->addItem(i + 1, typecol, false, "loopback");
else if (iflist[i].device_type == devt_p2p)
Tbl->addItem(i + 1, typecol, false, "point2point");
else
Tbl->addItem(i + 1, typecol, false, "other");
Tbl->addItem(i + 1, upcol, false,
(iflist[i].device_up ? "up" : "down"));
Tbl->addItemFormatted(i + 1, mtucol, false, "%d", iflist[i].mtu);
}
log_write(LOG_PLAIN, "************************INTERFACES************************\n");
log_write(LOG_PLAIN, "%s\n", Tbl->printableTable(NULL));
log_flush_all();
delete Tbl;
}
#ifdef WIN32
/* Print the libdnet->libpcap interface name mapping. */
print_iflist_pcap_mapping(iflist, numifs);
#endif
/* OK -- time to handle routes */
errstr[0]='\0';
routes = getsysroutes(&numroutes, errstr, sizeof(errstr));
u16 nbits;
if (routes==NULL || numroutes<= 0) {
log_write(LOG_PLAIN, "ROUTES: NONE FOUND(!)\n");
if (o.debugging)
log_write(LOG_STDOUT, "Reason: %s\n", errstr);
} else {
int dstcol = 0, devcol = 1, metcol = 2, gwcol = 3;
Tbl = new NmapOutputTable(numroutes + 1, 4);
Tbl->addItem(0, dstcol, false, "DST/MASK", 8);
Tbl->addItem(0, devcol, false, "DEV", 3);
Tbl->addItem(0, metcol, false, "METRIC", 6);
Tbl->addItem(0, gwcol, false, "GATEWAY", 7);
for (i = 0; i < numroutes; i++) {
nbits = routes[i].netmask_bits;
Tbl->addItemFormatted(i + 1, dstcol, false, "%s/%d",
inet_ntop_ez(&routes[i].dest, sizeof(routes[i].dest)), nbits);
Tbl->addItem(i + 1, devcol, false, routes[i].device->devfullname);
Tbl->addItemFormatted(i + 1, metcol, false, "%d", routes[i].metric);
if (!sockaddr_equal_zero(&routes[i].gw))
Tbl->addItem(i + 1, gwcol, true, inet_ntop_ez(&routes[i].gw, sizeof(routes[i].gw)));
}
log_write(LOG_PLAIN, "**************************ROUTES**************************\n");
log_write(LOG_PLAIN, "%s\n", Tbl->printableTable(NULL));
log_flush_all();
delete Tbl;
}
return 0;
}
#ifndef NOLUA
/* Escape control characters to make a string safe to display on a terminal. */
static std::string escape_for_screen(const std::string s) {
std::string r;
for (unsigned int i = 0; i < s.size(); i++) {
char buf[5];
unsigned char c = s[i];
// Printable and some whitespace ok. "\r" not ok because it overwrites the line.
if (c == '\t' || c == '\n' || (0x20 <= c && c <= 0x7e)) {
r += c;
} else {
Snprintf(buf, sizeof(buf), "\\x%02X", c);
r += buf;
}
}
return r;
}
/* Do something to protect characters that can't appear in XML. This is not a
reversible transform, more a last-ditch effort to write readable XML with
characters that shouldn't be part of regular output anyway. The escaping that
xml_write_escaped is not enough; some characters are not allowed to appear in
XML, not even escaped. */
std::string protect_xml(const std::string s) {
std::string r;
for (unsigned int i = 0; i < s.size(); i++) {
char buf[5];
unsigned char c = s[i];
// Printable and some whitespace ok.
if (c == '\t' || c == '\r' || c == '\n' || (0x20 <= c && c <= 0x7e)) {
r += c;
} else {
Snprintf(buf, sizeof(buf), "\\x%02X", c);
r += buf;
}
}
return r;
}
static char *formatScriptOutput(const ScriptResult *sr) {
std::vector<std::string> lines;
std::string c_output;
const char *p, *q;
std::string result;
unsigned int i;
c_output = escape_for_screen(sr->get_output_str());
if (c_output.empty())
return NULL;
p = c_output.c_str();
while (*p != '\0') {
q = strchr(p, '\n');
if (q == NULL) {
lines.push_back(std::string(p));
break;
} else {
lines.push_back(std::string(p, q - p));
p = q + 1;
}
}
if (lines.empty())
lines.push_back("");
for (i = 0; i < lines.size(); i++) {
if (i < lines.size() - 1)
result += "| ";
else
result += "|_";
if (i == 0)
result += std::string(sr->get_id()) + ": ";
result += lines[i];
if (i < lines.size() - 1)
result += "\n";
}
return strdup(result.c_str());
}
#endif /* NOLUA */
/* Output a list of ports, compressing ranges like 80-85 */
static void output_rangelist_given_ports(int logt, const unsigned short *ports, int numports);
/* Prints the familiar Nmap tabular output showing the "interesting"
ports found on the machine. It also handles the Machine/Grepable
output and the XML output. It is pretty ugly -- in particular I
should write helper functions to handle the table creation */
void printportoutput(const Target *currenths, const PortList *plist) {
char protocol[MAX_IPPROTOSTRLEN + 1];
char portinfo[64];
char grepvers[256];
char *p;
const char *state;
char serviceinfo[64];
int i;
int first = 1;
const struct nprotoent *proto;
Port *current;
Port port;
char hostname[1200];
struct serviceDeductions sd;
NmapOutputTable *Tbl = NULL;
int portcol = -1; // port or IP protocol #
int statecol = -1; // port/protocol state
int servicecol = -1; // service or protocol name
int versioncol = -1;
int reasoncol = -1;
int colno = 0;
unsigned int rowno;
int numrows;
int numignoredports = plist->numIgnoredPorts();
int numports = plist->numPorts();
state_reason_summary_t *reasons, *currentr;
std::vector<const char *> saved_servicefps;
if (o.noportscan || numports == 0)
return;
xml_start_tag("ports");
log_write(LOG_MACHINE, "Host: %s (%s)", currenths->targetipstr(),
currenths->HostName());
if ((o.verbose > 1 || o.debugging) && currenths->StartTime()) {
time_t tm_secs, tm_sece;
struct tm tm;
int err;
char tbufs[128];
tm_secs = currenths->StartTime();
tm_sece = currenths->EndTime();
err = n_localtime(&tm_secs, &tm);
if (err) {
error("Error in localtime: %s", strerror(err));
log_write(LOG_PLAIN, "Scanned for %lds\n",
(long) (tm_sece - tm_secs));
}
else {
if (strftime(tbufs, sizeof(tbufs), "%Y-%m-%d %H:%M:%S %Z", &tm) <= 0) {
error("Unable to properly format host start time");
log_write(LOG_PLAIN, "Scanned for %lds\n",
(long) (tm_sece - tm_secs));
}
else {
log_write(LOG_PLAIN, "Scanned at %s for %lds\n",
tbufs, (long) (tm_sece - tm_secs));
}
}
}
int prevstate = PORT_UNKNOWN;
int istate;
while ((istate = plist->nextIgnoredState(prevstate)) != PORT_UNKNOWN) {
i = plist->getStateCounts(istate);
xml_open_start_tag("extraports");
xml_attribute("state", "%s", statenum2str(istate));
xml_attribute("count", "%d", i);
xml_close_start_tag();
xml_newline();
/* Show line like:
Not shown: 98 open|filtered udp ports (no-response), 59 closed tcp ports (reset)
if appropriate (note that states are reverse-sorted by # of ports) */
if (prevstate == PORT_UNKNOWN) {
// First time through, check special case
if (numignoredports == numports) {
log_write(LOG_PLAIN, "All %d scanned ports on %s are in ignored states.\n",
numignoredports, currenths->NameIP(hostname, sizeof(hostname)));
log_write(LOG_MACHINE, "\t%s: ", (o.ipprotscan) ? "Protocols" : "Ports");
/* Grepable output supports only one ignored state. */
if (plist->numIgnoredStates() == 1) {
log_write(LOG_MACHINE, "\tIgnored State: %s (%d)", statenum2str(istate), i);
}
}
log_write(LOG_PLAIN, "Not shown: ");
} else {
log_write(LOG_PLAIN, ", ");
}
if((currentr = reasons = get_state_reason_summary(plist, istate)) == NULL) {
log_write(LOG_PLAIN, "%d %s %s%s", i, statenum2str(istate),
o.ipprotscan ? "protocol" : "port",
plist->getStateCounts(istate) == 1 ? "" : "s");
prevstate = istate;
continue;
}
while(currentr != NULL) {
if(currentr->count > 0) {
xml_open_start_tag("extrareasons");
xml_attribute("reason", "%s", reason_str(currentr->reason_id, SINGULAR));
xml_attribute("count", "%d", currentr->count);
xml_attribute("proto", "%s", IPPROTO2STR(currentr->proto));
xml_write_raw(" ports=\"");
output_rangelist_given_ports(LOG_XML, currentr->ports, currentr->count);
xml_write_raw("\"");
xml_close_empty_tag();
xml_newline();
if (currentr != reasons)
log_write(LOG_PLAIN, ", ");
log_write(LOG_PLAIN, "%d %s %s %s%s (%s)",
currentr->count, statenum2str(istate), IPPROTO2STR(currentr->proto),
o.ipprotscan ? "protocol" : "port",
plist->getStateCounts(istate) == 1 ? "" : "s",
reason_str(currentr->reason_id, SINGULAR));
}
currentr = currentr->next;
}
state_reason_summary_dinit(reasons);
xml_end_tag();
xml_newline();
prevstate = istate;
}
log_write(LOG_PLAIN, "\n");
if (numignoredports == numports) {
// Nothing left to show.
xml_end_tag(); /* ports */
xml_newline();
log_flush_all();
return;
}
/* OK, now it is time to deal with the service table ... */
colno = 0;
portcol = colno++;
statecol = colno++;
servicecol = colno++;
if (o.reason)
reasoncol = colno++;
if (o.servicescan)
versioncol = colno++;
numrows = numports - numignoredports;
#ifndef NOLUA
int scriptrows = 0;
if (plist->numscriptresults > 0)
scriptrows = plist->numscriptresults;
numrows += scriptrows;
#endif
assert(numrows > 0);
numrows++; // The header counts as a row
Tbl = new NmapOutputTable(numrows, colno);
// Lets start with the headers
if (o.ipprotscan)
Tbl->addItem(0, portcol, false, "PROTOCOL", 8);
else
Tbl->addItem(0, portcol, false, "PORT", 4);
Tbl->addItem(0, statecol, false, "STATE", 5);
Tbl->addItem(0, servicecol, false, "SERVICE", 7);
if (versioncol > 0)
Tbl->addItem(0, versioncol, false, "VERSION", 7);
if (reasoncol > 0)
Tbl->addItem(0, reasoncol, false, "REASON", 6);
log_write(LOG_MACHINE, "\t%s: ", (o.ipprotscan) ? "Protocols" : "Ports");
rowno = 1;
if (o.ipprotscan) {
current = NULL;
while ((current = plist->nextPort(current, &port, IPPROTO_IP, 0)) != NULL) {
if (!plist->isIgnoredState(current->state, NULL)) {
if (!first)
log_write(LOG_MACHINE, ", ");
else
first = 0;
if (o.reason) {
if (current->reason.ttl)
Tbl->addItemFormatted(rowno, reasoncol, false, "%s ttl %d",
port_reason_str(current->reason), current->reason.ttl);
else
Tbl->addItem(rowno, reasoncol, true, port_reason_str(current->reason));
}
state = statenum2str(current->state);
proto = nmap_getprotbynum(current->portno);
Snprintf(portinfo, sizeof(portinfo), "%s", proto ? proto->p_name : "unknown");
Tbl->addItemFormatted(rowno, portcol, false, "%d", current->portno);
Tbl->addItem(rowno, statecol, true, state);
Tbl->addItem(rowno, servicecol, true, portinfo);
log_write(LOG_MACHINE, "%d/%s/%s/", current->portno, state,
(proto) ? proto->p_name : "");
xml_open_start_tag("port");
xml_attribute("protocol", "ip");
xml_attribute("portid", "%d", current->portno);
xml_close_start_tag();
xml_open_start_tag("state");
xml_attribute("state", "%s", state);
xml_attribute("reason", "%s", reason_str(current->reason.reason_id, SINGULAR));
xml_attribute("reason_ttl", "%d", current->reason.ttl);
if (current->reason.ip_addr.sockaddr.sa_family != AF_UNSPEC) {
struct sockaddr_storage ss;
memcpy(&ss, ¤t->reason.ip_addr, sizeof(current->reason.ip_addr));
xml_attribute("reason_ip", "%s", inet_ntop_ez(&ss, sizeof(ss)));
}
xml_close_empty_tag();
if (proto && proto->p_name && *proto->p_name) {
xml_newline();
xml_open_start_tag("service");
xml_attribute("name", "%s", proto->p_name);
xml_attribute("conf", "8");
xml_attribute("method", "table");
xml_close_empty_tag();
}
xml_end_tag(); /* port */
xml_newline();
rowno++;
}
}
} else {
char fullversion[160];
current = NULL;
while ((current = plist->nextPort(current, &port, TCPANDUDPANDSCTP, 0)) != NULL) {
if (!plist->isIgnoredState(current->state, NULL)) {
if (!first)
log_write(LOG_MACHINE, ", ");
else
first = 0;
strcpy(protocol, IPPROTO2STR(current->proto));
Snprintf(portinfo, sizeof(portinfo), "%d/%s", current->portno, protocol);
state = statenum2str(current->state);
plist->getServiceDeductions(current->portno, current->proto, &sd);
if (sd.service_fp && saved_servicefps.size() <= 8)
saved_servicefps.push_back(sd.service_fp);
current->getNmapServiceName(serviceinfo, sizeof(serviceinfo));
Tbl->addItem(rowno, portcol, true, portinfo);
Tbl->addItem(rowno, statecol, false, state);
Tbl->addItem(rowno, servicecol, true, serviceinfo);
if (o.reason) {
if (current->reason.ttl)
Tbl->addItemFormatted(rowno, reasoncol, false, "%s ttl %d",
port_reason_str(current->reason), current->reason.ttl);
else
Tbl->addItem(rowno, reasoncol, true, port_reason_str(current->reason));
}
sd.populateFullVersionString(fullversion, sizeof(fullversion));
if (*fullversion && versioncol > 0)
Tbl->addItem(rowno, versioncol, true, fullversion);
// How should we escape illegal chars in grepable output?
// Well, a reasonably clean way would be backslash escapes
// such as \/ and \\ . // But that makes it harder to pick
// out fields with awk, cut, and such. So I'm gonna use the
// ugly hack (fitting to grepable output) of replacing the '/'
// character with '|' in the version field.
Strncpy(grepvers, fullversion, sizeof(grepvers) / sizeof(*grepvers));
p = grepvers;
while ((p = strchr(p, '/'))) {
*p = '|';
p++;
}
if (sd.name || sd.service_fp || sd.service_tunnel != SERVICE_TUNNEL_NONE) {
p = serviceinfo;
while ((p = strchr(p, '/'))) {
*p = '|';
p++;
}
}
else {
serviceinfo[0] = '\0';
}
log_write(LOG_MACHINE, "%d/%s/%s//%s//%s/", current->portno,
state, protocol, serviceinfo, grepvers);
xml_open_start_tag("port");
xml_attribute("protocol", "%s", protocol);
xml_attribute("portid", "%d", current->portno);
xml_close_start_tag();
xml_open_start_tag("state");
xml_attribute("state", "%s", state);
xml_attribute("reason", "%s", reason_str(current->reason.reason_id, SINGULAR));
xml_attribute("reason_ttl", "%d", current->reason.ttl);
if (current->reason.ip_addr.sockaddr.sa_family != AF_UNSPEC) {
struct sockaddr_storage ss;
memcpy(&ss, ¤t->reason.ip_addr, sizeof(current->reason.ip_addr));
xml_attribute("reason_ip", "%s", inet_ntop_ez(&ss, sizeof(ss)));
}
xml_close_empty_tag();
if (sd.name || sd.service_fp || sd.service_tunnel != SERVICE_TUNNEL_NONE)
print_xml_service(&sd);
rowno++;
#ifndef NOLUA
if (o.script) {
ScriptResults::const_iterator ssr_iter;
for (ssr_iter = current->scriptResults.begin();
ssr_iter != current->scriptResults.end(); ssr_iter++) {
(*ssr_iter)->write_xml();
char *script_output = formatScriptOutput((*ssr_iter));
if (script_output != NULL) {
Tbl->addItem(rowno, 0, true, true, script_output);
free(script_output);
}
rowno++;
}
}
#endif
xml_end_tag(); /* port */
xml_newline();
}
}
}
/* log_write(LOG_PLAIN,"\n"); */
/* Grepable output supports only one ignored state. */
if (plist->numIgnoredStates() == 1) {
istate = plist->nextIgnoredState(PORT_UNKNOWN);
if (plist->getStateCounts(istate) > 0)
log_write(LOG_MACHINE, "\tIgnored State: %s (%d)",
statenum2str(istate), plist->getStateCounts(istate));
}
xml_end_tag(); /* ports */
xml_newline();
if (o.defeat_rst_ratelimit && o.TCPScan() && plist->getStateCounts(PORT_FILTERED) > 0) {
log_write(LOG_PLAIN, "Some closed ports may be reported as filtered due to --defeat-rst-ratelimit\n");
}
// Now we write the table for the user
log_write(LOG_PLAIN, "%s", Tbl->printableTable(NULL));
delete Tbl;
// There may be service fingerprints I would like the user to submit
if (saved_servicefps.size() > 0) {
int numfps = saved_servicefps.size();
log_write(LOG_PLAIN, "%d service%s unrecognized despite returning data."
" If you know the service/version, please submit the following"
" fingerprint%s at"
" https://nmap.org/cgi-bin/submit.cgi?new-service :\n",
numfps, (numfps > 1) ? "s" : "", (numfps > 1) ? "s" : "");
for (i = 0; i < numfps; i++) {
if (numfps > 1)
log_write(LOG_PLAIN, "==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============\n");
log_write(LOG_PLAIN, "%s\n", saved_servicefps[i]);
}
}
log_flush_all();
}
/* MAX_STRFTIME_EXPANSION is the maximum length that a single %_ escape can
* expand to, not including null terminator. If you add another supported
* escape, check that it doesn't exceed this value, otherwise increase it.
*/
#define MAX_STRFTIME_EXPANSION 10
char *logfilename(const char *str, struct tm *tm) {
char *ret, *end, *p;
// Max expansion: "%F" => "YYYY-mm-dd"
int retlen = strlen(str) * (MAX_STRFTIME_EXPANSION - 2) + 1;
size_t written = 0;
ret = (char *) safe_malloc(retlen);
end = ret + retlen;
for (p = ret; *str; str++) {
if (*str == '%') {
str++;
written = 0;
if (!*str)
break;
#define FTIME_CASE(_fmt, _fmt_str) case _fmt: \
written = strftime(p, end - p, _fmt_str, tm); \
break;
switch (*str) {
FTIME_CASE('H', "%H");
FTIME_CASE('M', "%M");
FTIME_CASE('S', "%S");
FTIME_CASE('T', "%H%M%S");
FTIME_CASE('R', "%H%M");
FTIME_CASE('m', "%m");
FTIME_CASE('d', "%d");
FTIME_CASE('y', "%y");
FTIME_CASE('Y', "%Y");
FTIME_CASE('D', "%m%d%y");
FTIME_CASE('F', "%Y-%m-%d");
default:
*p++ = *str;
continue;
}
assert(end - p > 1);
p += written;
} else {
*p++ = *str;
}
}
*p = 0;
return (char *) safe_realloc(ret, strlen(ret) + 1);
}
/* This is the workhorse of the logging functions. Usually it is
called through log_write(), but it can be called directly if you are dealing
with a vfprintf-style va_list. YOU MUST SANDWICH EACH EXECUTION OF THIS CALL
BETWEEN va_start() AND va_end() calls. */
void log_vwrite(int logt, const char *fmt, va_list ap) {
char *writebuf;
bool skid_noxlate = false;
int rc = 0;
int len;
int fileidx = 0;
int l;
int logtype;
va_list apcopy;
for (logtype = 1; logtype <= LOG_MAX; logtype <<= 1) {
if (!(logt & logtype))
continue;
switch (logtype) {
case LOG_STDOUT:
vfprintf(o.nmap_stdout, fmt, ap);
break;
case LOG_STDERR:
fflush(stdout); // Otherwise some systems will print stderr out of order
vfprintf(stderr, fmt, ap);
break;
case LOG_SKID_NOXLT:
skid_noxlate = true;
/* no break */
case LOG_NORMAL:
case LOG_MACHINE:
case LOG_SKID:
case LOG_XML:
if (logtype == LOG_SKID_NOXLT)
l = LOG_SKID;
else
l = logtype;
fileidx = 0;
while ((l & 1) == 0) {
fileidx++;
l >>= 1;
}
assert(fileidx < LOG_NUM_FILES);
if (o.logfd[fileidx]) {
len = alloc_vsprintf(&writebuf, fmt, ap);
if (writebuf == NULL)
fatal("%s: alloc_vsprintf failed.", __func__);
if (len) {
if ((logtype & (LOG_SKID|LOG_SKID_NOXLT)) && !skid_noxlate)
skid_output(writebuf);
rc = fwrite(writebuf, len, 1, o.logfd[fileidx]);
if (rc != 1) {
fatal("Failed to write %d bytes of data to (logt==%d) stream. fwrite returned %d. Quitting.", len, logtype, rc);
}
va_end(apcopy);
}
free(writebuf);
}
break;
default:
/* Unknown log type.
* ---
* Note that we're not calling fatal() here to avoid infinite call loop
* between fatal() and this log_vwrite() function. */
assert(0); /* We want people to report it. */
}
}
return;
}
/* Write some information (printf style args) to the given log stream(s).
Remember to watch out for format string bugs. */
void log_write(int logt, const char *fmt, ...) {
va_list ap;
assert(logt > 0);