-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathoutput.cc
2057 lines (1826 loc) · 74.3 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 greppable 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-2009 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 [email protected]). 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 meant to clarify our *
* interpretation of derived works with some common examples. Our *
* interpretation applies only to Nmap--we don't speak for other people's *
* GPL works. *
* *
* 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 *
* [email protected] 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 [email protected] 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 the Nmap Project (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$ */
#include "output.h"
#include "osscan.h"
#include "NmapOps.h"
#include "NmapOutputTable.h"
#include "MACLookup.h"
#include "portreasons.h"
#include "protocols.h"
#include "nmap_rpc.h"
#include "Target.h"
#include "utils.h"
#include <math.h>
#include <set>
#include <string>
#include <vector>
#include <list>
/* Workaround for lack of namespace std on HP-UX 11.00 */
namespace std {};
using namespace std;
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* xml_sf_convert (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;
}
// Creates 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.
// Returns a pointer to a buffer containing the element,
// you will have to call free on it.
static char * getServiceXMLBuf(struct serviceDeductions *sd) {
string versionxmlstring = "";
char rpcbuf[128];
char confBuf[20];
char *xml_product = NULL, *xml_version = NULL, *xml_extrainfo = NULL;
char *xml_hostname = NULL, *xml_ostype = NULL, *xml_devicetype = NULL;
char *xml_servicefp = NULL, *xml_servicefp_temp = NULL;
versionxmlstring = "<service name=\"";
versionxmlstring += sd->name? sd->name : "unknown";
versionxmlstring += "\"";
if (sd->product) {
xml_product = xml_convert(sd->product);
versionxmlstring += " product=\"";
versionxmlstring += xml_product;
free(xml_product); xml_product = NULL;
versionxmlstring += '\"';
}
if (sd->version) {
xml_version = xml_convert(sd->version);
versionxmlstring += " version=\"";
versionxmlstring += xml_version;
free(xml_version); xml_version = NULL;
versionxmlstring += '\"';
}
if (sd->extrainfo) {
xml_extrainfo = xml_convert(sd->extrainfo);
versionxmlstring += " extrainfo=\"";
versionxmlstring += xml_extrainfo;
free(xml_extrainfo); xml_extrainfo = NULL;
versionxmlstring += '\"';
}
if (sd->hostname) {
xml_hostname = xml_convert(sd->hostname);
versionxmlstring += " hostname=\"";
versionxmlstring += xml_hostname;
free(xml_hostname); xml_hostname = NULL;
versionxmlstring += '\"';
}
if (sd->ostype) {
xml_ostype = xml_convert(sd->ostype);
versionxmlstring += " ostype=\"";
versionxmlstring += xml_ostype;
free(xml_ostype); xml_ostype = NULL;
versionxmlstring += '\"';
}
if (sd->devicetype) {
xml_devicetype = xml_convert(sd->devicetype);
versionxmlstring += " devicetype=\"";
versionxmlstring += xml_devicetype;
free(xml_devicetype); xml_devicetype = NULL;
versionxmlstring += '\"';
}
if (sd->service_fp) {
xml_servicefp_temp = xml_convert(sd->service_fp);
xml_servicefp = xml_sf_convert(xml_servicefp_temp);
versionxmlstring += " servicefp=\"";
versionxmlstring += xml_servicefp;
free(xml_servicefp_temp); xml_servicefp_temp = NULL;
free(xml_servicefp); xml_servicefp = NULL;
versionxmlstring += '\"';
}
if (o.rpcscan && sd->rpc_status == RPC_STATUS_GOOD_PROG) {
Snprintf(rpcbuf, sizeof(rpcbuf),
" rpcnum=\"%li\" lowver=\"%i\" highver=\"%i\" proto=\"rpc\"",
sd->rpc_program, sd->rpc_lowver, sd->rpc_highver);
} else rpcbuf[0] = '\0';
versionxmlstring += " ";
versionxmlstring += (sd->service_tunnel == SERVICE_TUNNEL_SSL)? "tunnel=\"ssl\" " : "";
versionxmlstring += "method=\"";
versionxmlstring += (sd->dtype == SERVICE_DETECTION_TABLE)? "table" : "probed";
versionxmlstring += "\" conf=\"";
Snprintf(confBuf,20,"%i",sd->name_confidence);
versionxmlstring += confBuf;
versionxmlstring += "\"";
versionxmlstring += rpcbuf;
versionxmlstring += " />";
return strdup(versionxmlstring.c_str());
}
#ifdef WIN32
/* Display a warning that a device is not Ethernet and so raw sockets
will be used. The warning is shown only once per unique device name. */
void win32_warn_raw_sockets(const char *devname) {
static set<string> shown_names;
if (devname != NULL && shown_names.find(devname) == shown_names.end()) {
error("WARNING: Using raw sockets because %s is not an ethernet device. This probably won't work on Windows.\n", devname);
shown_names.insert(devname);
}
}
/* From tcpip.cc. */
bool DnetName2PcapName(const char *dnetdev, char *pcapdev, int pcapdevlen);
/* Display the mapping from libdnet interface names (like "eth0") to WinPcap
interface names (like "\Device\NPF_{...}"). This is the same mapping used by
eth_open and so can help diagnose connection problems. Additionally display
WinPcap 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;
list<const pcap_if_t *> leftover_pcap_ifs;
list<const pcap_if_t *>::iterator leftover_p;
int i;
/* Build a list of "leftover" libpcap interfaces. Initially it contains all
the interfaces. */
pcap_ifs = getpcapinterfaces();
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. */
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();
}
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;
iflist = getinterfaces(&numifs);
int i;
/* First let's handle interfaces ... */
if (numifs == 0) {
log_write(LOG_PLAIN, "INTERFACES: NONE FOUND(!)\n");
} else {
int devcol=0, shortdevcol=1, ipcol=2, typecol = 3, upcol = 4, maccol = 5;
Tbl = new NmapOutputTable( numifs+1, 6 );
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, 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);
Tbl->addItemFormatted(i+1, ipcol, false, "%s/%d", inet_ntop_ez(&(iflist[i].addr), sizeof(iflist[i].addr)), 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"));
}
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 */
routes = getsysroutes(&numroutes);
u32 mask_nbo;
u16 nbits;
struct in_addr ia;
if (numroutes == 0) {
log_write(LOG_PLAIN, "ROUTES: NONE FOUND(!)\n");
} else {
int dstcol=0, devcol=1, gwcol=2;
Tbl = new NmapOutputTable( numroutes+1, 3 );
Tbl->addItem(0, dstcol, false, "DST/MASK", 8);
Tbl->addItem(0, devcol, false, "DEV", 3);
Tbl->addItem(0, gwcol, false, "GATEWAY", 7);
for(i=0; i < numroutes; i++) {
mask_nbo = htonl(routes[i].netmask);
addr_mtob(&mask_nbo, sizeof(mask_nbo), &nbits);
assert(nbits <= 32);
ia.s_addr = routes[i].dest;
Tbl->addItemFormatted(i+1, dstcol, false, "%s/%d", inet_ntoa(ia), nbits);
Tbl->addItem(i+1, devcol, false, routes[i].device->devfullname);
if (routes[i].gw.s_addr != 0)
Tbl->addItem(i+1, gwcol, true, inet_ntoa(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;
}
/* Fills in namebuf (as long as there is space in buflen) with the
Name nmap normal output will use to describe the port. This takes
into account to confidence level, any SSL tunneling, etc. Truncates
namebuf to 0 length if there is no room.*/
static void getNmapServiceName(struct serviceDeductions *sd, int state,
char *namebuf, int buflen) {
const char *tunnel_prefix;
int len;
if (sd->service_tunnel == SERVICE_TUNNEL_SSL)
tunnel_prefix = "ssl/";
else
tunnel_prefix = "";
if (sd->name != NULL && strcmp(sd->name, "unknown") != 0) {
/* The port has a name and the name is not "unknown". How confident are we? */
if (o.servicescan && state == PORT_OPEN && sd->name_confidence <= 5)
len = Snprintf(namebuf, buflen, "%s%s?", tunnel_prefix, sd->name);
else
len = Snprintf(namebuf, buflen, "%s%s", tunnel_prefix, sd->name);
} else {
len = Snprintf(namebuf, buflen, "%sunknown", tunnel_prefix);
}
if (len >= buflen || len < 0)
namebuf[0] = '\0';
}
#ifndef NOLUA
static char* formatScriptOutput(ScriptResult sr) {
std::string result = std::string(), output = sr.get_output();
string::size_type pos;
char *c_result, *c_output = new char[output.length()+1];
strncpy(c_output, output.c_str(), output.length()+1);
int line = 0;
std::string line_prfx = "| ";
char* token = strtok(c_output, "\n");
result += line_prfx + sr.get_id() + ": ";
while(token != NULL) {
if(line > 0)
result += line_prfx;
result += std::string(token) + "\n";
token = strtok(NULL, "\n");
line++;
}
// fix the last line
pos = result.rfind(line_prfx);
result.replace(pos, 3, "|_ ");
// delete the unwanted trailing newline
pos = result.rfind("\n");
if(pos!=std::string::npos){
result.erase(pos, strlen("\n"));
}
c_result = strdup(result.c_str());
delete[] c_output;
return c_result;
}
#endif /* NOLUA */
/* Prints the familiar Nmap tabular output showing the "interesting"
ports found on the machine. It also handles the Machine/Greppable
output and the XML output. It is pretty ugly -- in particular I
should write helper functions to handle the table creation */
void printportoutput(Target *currenths, PortList *plist) {
char protocol[MAX_IPPROTOSTRLEN+1];
char rpcinfo[64];
char rpcmachineinfo[64];
char portinfo[64];
char grepvers[256];
char grepown[64];
char *p;
char * xmlBuf=NULL;
const char *state;
char serviceinfo[64];
char *name=NULL;
int i;
int first = 1;
struct protoent *proto;
Port *current;
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 ownercol = -1; // Used for ident scan
int colno = 0;
unsigned int rowno;
int numrows;
int numignoredports = plist->numIgnoredPorts();
vector<const char *> saved_servicefps;
if (o.noportscan)
return;
log_write(LOG_XML, "<ports>");
int prevstate = PORT_UNKNOWN;
int istate;
while ((istate = plist->nextIgnoredState(prevstate)) != PORT_UNKNOWN) {
log_write(LOG_XML, "<extraports state=\"%s\" count=\"%d\">\n",
statenum2str(istate), plist->getStateCounts(istate));
print_xml_state_summary(plist, istate);
log_write(LOG_XML, "</extraports>\n");
prevstate = istate;
}
if (numignoredports == plist->numports) {
if (numignoredports == 0) {
log_write(LOG_PLAIN, "0 ports scanned on %s\n", currenths->NameIP(hostname, sizeof(hostname)));
} else {
log_write(LOG_PLAIN,
"%s %d scanned %s on %s %s ",
(numignoredports == 1)? "The" : "All", numignoredports,
(numignoredports == 1)? "port" : "ports",
currenths->NameIP(hostname, sizeof(hostname)),
(numignoredports == 1)? "is" : "are");
if (plist->numIgnoredStates() == 1) {
log_write(LOG_PLAIN, "%s", statenum2str(plist->nextIgnoredState(PORT_UNKNOWN)));
} else {
prevstate = PORT_UNKNOWN;
while ((istate = plist->nextIgnoredState(prevstate)) != PORT_UNKNOWN) {
if (prevstate != PORT_UNKNOWN) log_write(LOG_PLAIN, " or ");
log_write(LOG_PLAIN, "%s (%d)", statenum2str(istate), plist->getStateCounts(istate));
prevstate = istate;
}
}
if(o.reason)
print_state_summary(plist, STATE_REASON_EMPTY);
log_write(LOG_PLAIN, "\n");
}
log_write(LOG_MACHINE,"Host: %s (%s)\tStatus: Up",
currenths->targetipstr(), currenths->HostName());
log_write(LOG_XML, "</ports>\n");
return;
}
if (o.verbose > 1 || o.debugging) {
time_t tm_secs, tm_sece;
struct tm *tm;
char tbufs[128];
tm_secs = currenths->StartTime();
tm_sece = currenths->EndTime();
tm = localtime(&tm_secs);
if (strftime(tbufs, sizeof(tbufs), "%Y-%m-%d %H:%M:%S %Z", tm) <= 0)
fatal("Unable to properly format host start time");
log_write(LOG_PLAIN,"Scanned at %s for %lds\n",
tbufs, tm_sece - tm_secs);
}
log_write(LOG_PLAIN,"Interesting %s on %s:\n",
(o.ipprotscan)? "protocols" : "ports",
currenths->NameIP(hostname, sizeof(hostname)));
log_write(LOG_MACHINE,"Host: %s (%s)", currenths->targetipstr(),
currenths->HostName());
/* Show line like:
Not shown: 3995 closed ports, 514 filtered ports
if appropriate (note that states are reverse-sorted by # of ports) */
prevstate = PORT_UNKNOWN;
while ((istate = plist->nextIgnoredState(prevstate)) != PORT_UNKNOWN) {
if (prevstate == PORT_UNKNOWN)
log_write(LOG_PLAIN, "Not shown: ");
else log_write(LOG_PLAIN, ", ");
char desc[32];
if (o.ipprotscan)
Snprintf(desc, sizeof(desc), (plist->getStateCounts(istate) == 1)? "protocol" : "protocols");
else
Snprintf(desc, sizeof(desc), (plist->getStateCounts(istate) == 1)? "port" : "ports");
log_write(LOG_PLAIN, "%d %s %s", plist->getStateCounts(istate), statenum2str(istate), desc);
prevstate = istate;
}
if (prevstate != PORT_UNKNOWN) log_write(LOG_PLAIN, "\n");
if(o.reason)
print_state_summary(plist, STATE_REASON_FULL);
/* 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.identscan)
ownercol = colno++; */
if (o.servicescan || o.rpcscan)
versioncol = colno++;
numrows = plist->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);
/* if (ownercol > 0)
Tbl->addItem(0, ownercol, false, "OWNER", 5); */
log_write(LOG_MACHINE,"\t%s: ", (o.ipprotscan)? "Protocols" : "Ports" );
rowno = 1;
if (o.ipprotscan) {
current = NULL;
while( (current=plist->nextPort(current, IPPROTO_IP, 0))!=NULL ) {
if (!plist->isIgnoredState(current->state)) {
if (!first) log_write(LOG_MACHINE,", ");
else first = 0;
if(o.reason)
Tbl->addItem(rowno, reasoncol, true, port_reason_str(current->reason));
state = statenum2str(current->state);
proto = nmap_getprotbynum(htons(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 : "");
log_write(LOG_XML, "<port protocol=\"ip\" portid=\"%d\"><state state=\"%s\" reason=\"%s\" reason_ttl=\"%d\"",
current->portno, state, reason_str(current->reason.reason_id, SINGULAR), current->reason.ttl);
if(current->reason.ip_addr.s_addr)
log_write(LOG_XML, " reason_ip=\"%s\"", inet_ntoa(current->reason.ip_addr));
log_write(LOG_XML, "/>");
if (proto && proto->p_name && *proto->p_name)
log_write(LOG_XML, "\n<service name=\"%s\" conf=\"8\" method=\"table\" />", proto->p_name);
log_write(LOG_XML, "</port>\n");
rowno++;
}
}
} else {
current = NULL;
while( (current=plist->nextPort(current, TCPANDUDPANDSCTP, 0))!=NULL ) {
if (!plist->isIgnoredState(current->state)) {
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);
current->getServiceDeductions(&sd);
if (sd.service_fp && saved_servicefps.size() <= 8)
saved_servicefps.push_back(sd.service_fp);
if (o.rpcscan) {
switch(sd.rpc_status) {
case RPC_STATUS_UNTESTED:
rpcinfo[0] = '\0';
strcpy(rpcmachineinfo, "");
break;
case RPC_STATUS_UNKNOWN:
strcpy(rpcinfo, "(RPC (Unknown Prog #))");
strcpy(rpcmachineinfo, "R");
break;
case RPC_STATUS_NOT_RPC:
rpcinfo[0] = '\0';
strcpy(rpcmachineinfo, "N");
break;
case RPC_STATUS_GOOD_PROG:
name = nmap_getrpcnamebynum(sd.rpc_program);
Snprintf(rpcmachineinfo, sizeof(rpcmachineinfo), "(%s:%li*%i-%i)", (name)? name : "", sd.rpc_program, sd.rpc_lowver, sd.rpc_highver);
if (!name) {
Snprintf(rpcinfo, sizeof(rpcinfo), "(#%li (unknown) V%i-%i)", sd.rpc_program, sd.rpc_lowver, sd.rpc_highver);
} else {
if (sd.rpc_lowver == sd.rpc_highver) {
Snprintf(rpcinfo, sizeof(rpcinfo), "(%s V%i)", name, sd.rpc_lowver);
} else
Snprintf(rpcinfo, sizeof(rpcinfo), "(%s V%i-%i)", name, sd.rpc_lowver, sd.rpc_highver);
}
break;
default:
fatal("Unknown rpc_status %d", sd.rpc_status);
break;
}
Snprintf(serviceinfo, sizeof(serviceinfo), "%s%s%s", (sd.name)? sd.name : ((*rpcinfo)? "" : "unknown"), (sd.name)? " " : "", rpcinfo);
} else {
getNmapServiceName(&sd, current->state, serviceinfo, sizeof(serviceinfo));
rpcmachineinfo[0] = '\0';
}
Tbl->addItem(rowno, portcol, true, portinfo);
Tbl->addItem(rowno, statecol, false, state);
Tbl->addItem(rowno, servicecol, true, serviceinfo);
if(o.reason)
Tbl->addItem(rowno, reasoncol, true, port_reason_str(current->reason));
/* if (current->owner)
Tbl->addItem(rowno, ownercol, true, current->owner); */
if (*sd.fullversion)
Tbl->addItem(rowno, versioncol, true, sd.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 hat (fitting to grepable output) or replacing the '/'
// character with '|' in the version and owner fields.
Strncpy(grepvers, sd.fullversion,
sizeof(grepvers) / sizeof(*grepvers));
p = grepvers;
while((p = strchr(p, '/'))) {
*p = '|';
p++;
}
if (!current->owner) *grepown = '\0';
else {
Strncpy(grepown, current->owner,
sizeof(grepown) / sizeof(*grepown));
p = grepown;
while((p = strchr(p, '/'))) {
*p = '|';
p++;
}
}
if (!sd.name) serviceinfo[0] = '\0';
else {
p = serviceinfo;
while((p = strchr(p, '/'))) {
*p = '|';
p++;
}
}
log_write(LOG_MACHINE,"%d/%s/%s/%s/%s/%s/%s/", current->portno, state,
protocol, grepown, serviceinfo, rpcmachineinfo, grepvers);
log_write(LOG_XML, "<port protocol=\"%s\" portid=\"%d\">", protocol, current->portno);
log_write(LOG_XML, "<state state=\"%s\" reason=\"%s\" reason_ttl=\"%d\"", state,
reason_str(current->reason.reason_id, SINGULAR), current->reason.ttl);
if(current->reason.ip_addr.s_addr)
log_write(LOG_XML, " reason_ip=\"%s\"", inet_ntoa(current->reason.ip_addr));
log_write(LOG_XML, "/>");
if (current->owner && *current->owner) {
log_write(LOG_XML, "<owner name=\"%s\" />", current->owner);
}
if (sd.name || sd.service_fp){
xmlBuf = getServiceXMLBuf(&sd);
if(xmlBuf){
log_write(LOG_XML, "%s", xmlBuf);
free(xmlBuf);
xmlBuf=NULL;
}
}
rowno++;
#ifndef NOLUA
if(o.script) {
ScriptResults::iterator ssr_iter;
for( ssr_iter = current->scriptResults.begin();
ssr_iter != current->scriptResults.end();
ssr_iter++) {
char* xml_id= xml_convert(ssr_iter->get_id().c_str());
char* xml_scriptoutput= xml_convert(ssr_iter->get_output().c_str());
log_write(LOG_XML, "<script id=\"%s\" output=\"%s\" />",
xml_id, xml_scriptoutput);
free(xml_id);
free(xml_scriptoutput);
char* script_output = formatScriptOutput((*ssr_iter));
Tbl->addItem(rowno, 0, true, true, script_output);
free(script_output);
rowno++;
}
}
#endif
log_write(LOG_XML, "</port>\n");
}
}
}
/* 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));
}
log_write(LOG_XML, "</ports>\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 http://www.insecure.org/cgi-bin/servicefp-submit.cgi :\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();
}
/* Escape a string for inclusion in XML. This gets <>&, "' for attribute values,
-- for inside comments, and characters with value > 0x7F. It also gets
control characters with value < 0x20 to avoid parser normalization of \r\n\t
in attribute values. If this is not desired in some cases, we'll have to add
a parameter to control this. */
char *xml_convert(const char *str) {
/* result is the result buffer; n + 1 is the allocated size. Double the
allocation when space runs out. */
char *result = NULL;
size_t n = 0, len;
const char *p;
int i;
i = 0;
for (p = str; *p != '\0'; p++) {
const char *repl;
char buf[32];
if (*p == '<')
repl = "<";
else if (*p == '>')
repl = ">";
else if (*p == '&')
repl = "&";
else if (*p == '"')
repl = """;
else if (*p == '\'')
repl = "'";
else if (*p == '-' && p > str && *(p - 1) == '-') {
/* Escape -- for comments. */
repl = "-";
} else if (*p < 0x20 || (unsigned char) *p > 0x7F) {
/* Escape control characters and anything outside of ASCII. We have to
emit UTF-8 and an easy way to do that is to emit ASCII. */
Snprintf(buf, sizeof(buf), "&#x%x;", (unsigned char) *p);
repl = buf;
} else {
/* Unescaped character. */
buf[0] = *p;
buf[1] = '\0';
repl = buf;
}
len = strlen(repl);
/* Double the size of the result buffer if necessary. */
if (i + len > n) {
n = (i + len) * 2;
result = (char *) safe_realloc(result, n + 1);
}
memcpy(result + i, repl, len);
i += len;
}
/* Trim to length. (Also does initial allocation when str is empty.) */
result = (char *) safe_realloc(result, i + 1);
result[i] = '\0';
return result;
}
char *logfilename(const char *str, struct tm *tm)
{
char *ret, *end, *p;
char tbuf[10];
int retlen = strlen(str) * 6 + 1;
ret = (char *) safe_malloc(retlen);
end = ret + retlen;
for (p = ret; *str; str++) {
if (*str == '%') {
str++;
if (!*str)
break;
switch (*str) {
case 'H':
strftime(tbuf, sizeof tbuf, "%H", tm);
break;
case 'M':
strftime(tbuf, sizeof tbuf, "%M", tm);
break;
case 'S':
strftime(tbuf, sizeof tbuf, "%S", tm);
break;
case 'T':
strftime(tbuf, sizeof tbuf, "%H%M%S", tm);
break;
case 'R':
strftime(tbuf, sizeof tbuf, "%H%M", tm);
break;
case 'm':
strftime(tbuf, sizeof tbuf, "%m", tm);
break;
case 'd':
strftime(tbuf, sizeof tbuf, "%d", tm);
break;
case 'y':
strftime(tbuf, sizeof tbuf, "%y", tm);
break;
case 'Y':
strftime(tbuf, sizeof tbuf, "%Y", tm);
break;
case 'D':
strftime(tbuf, sizeof tbuf, "%m%d%y", tm);
break;
default:
*p++ = *str;
continue;
}
assert(end - p > 1);
Strncpy(p, tbuf, end - p - 1);
p += strlen(tbuf);
} 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. Unlike log_write, YOU
CAN ONLY CALL THIS WITH ONE LOG TYPE (not a bitmask full of them).
In addition, YOU MUST SANDWHICH EACH EXECUTION IF THIS CALL BETWEEN
va_start() AND va_end() calls. */
void log_vwrite(int logt, const char *fmt, va_list ap) {