-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput.cc
1729 lines (1546 loc) · 65 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-2006 Insecure.Com LLC. Nmap is *
* also a registered trademark of Insecure.Com LLC. This program is free *
* software; you may redistribute and/or modify it under the terms of the *
* GNU General Public License as published by the Free Software *
* Foundation; Version 2 with the clarifications and exceptions described *
* below. This guarantees your right to use, modify, and redistribute *
* this software under certain conditions. If you wish to embed Nmap *
* technology into proprietary software, we sell alternative licenses *
* (contact sales@insecure.com). Dozens of software vendors already *
* license Nmap technology such as host discovery, port scanning, OS *
* detection, and version detection. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-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://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 dozens *
* of software vendors, and generally include a perpetual license as well *
* as providing for priority support and updates as well as helping to *
* fund the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included Copying.OpenSSL file, and distribute linked *
* combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to fyodor@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one 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 "output.h"
#include "osscan.h"
#include "NmapOps.h"
#include "NmapOutputTable.h"
#include "MACLookup.h"
#include <string>
/* Workaround for lack of namespace std on HP-UX 11.00 */
namespace std {};
using namespace std;
extern NmapOps o;
static 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++)
if (rand()%2==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"[rand()%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) 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' && (rand()%3==0)) s[i]+='a'-'A';
else if (s[i]>='a' && s[i]<='z' && (rand()%3==0)) s[i]-='a'-'A';
}
}
/* 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;
int charcount = 0;
while(*src && charcount < 2035) { /* 2048 - 14 */
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++;
charcount++;
}
if (ampptr != 0) {
*ampptr = '\0';
}
else {
*dst = '\0';
}
return temp;
}
// Creates an XML <service> element for the information given in
// serviceDeduction. It will be 0-length if none is neccessary.
// returns 0 for success.
static int getServiceXMLBuf(struct serviceDeductions *sd, char *xmlbuf,
unsigned int xmlbuflen) {
string versionxmlstring = "";
char rpcbuf[128];
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;
if (xmlbuflen < 1) return -1;
xmlbuf[0] = '\0';
if (!sd->name && !sd->service_fp) return 0;
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';
snprintf(xmlbuf, xmlbuflen,
"<service name=\"%s\"%s %smethod=\"%s\" conf=\"%d\"%s />",
sd->name? sd->name : "unknown",
versionxmlstring.c_str(),
(sd->service_tunnel == SERVICE_TUNNEL_SSL)? "tunnel=\"ssl\" " : "",
(sd->dtype == SERVICE_DETECTION_TABLE)? "table" : "probed",
sd->name_confidence, rpcbuf);
return 0;
}
/* 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_NORMAL|LOG_SKID|LOG_STDOUT, "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_NORMAL|LOG_SKID|LOG_STDOUT, "************************INTERFACES************************\n");
log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT, "%s\n", Tbl->printableTable(NULL));
log_flush_all();
delete Tbl;
}
/* OK -- time to handle routes */
routes = getsysroutes(&numroutes);
u32 mask_nbo;
u16 nbits;
struct in_addr ia;
if (numroutes == 0) {
log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT, "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_NORMAL|LOG_SKID|LOG_STDOUT, "**************************ROUTES**************************\n");
log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT, "%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) {
char *dst = namebuf;
int lenremaining = buflen;
int len;
if (buflen < 1) return;
if (sd->service_tunnel == SERVICE_TUNNEL_SSL) {
if (lenremaining < 5) goto overflow;
strncpy(dst, "ssl/", lenremaining);
dst += 4;
lenremaining -= 4;
}
if (sd->name && (sd->service_tunnel != SERVICE_TUNNEL_SSL ||
sd->dtype == SERVICE_DETECTION_PROBED)) {
if (o.servicescan && state == PORT_OPEN && sd->name_confidence <= 5)
len = snprintf(dst, lenremaining, "%s?", sd->name);
else len = snprintf(dst, lenremaining, "%s", sd->name);
} else {
len = snprintf(dst, lenremaining, "%s", "unknown");
}
if (len > lenremaining || len < 0) goto overflow;
dst += len;
lenremaining -= len;
if (lenremaining < 1) goto overflow;
*dst = '\0';
return;
overflow:
*namebuf = '\0';
}
/* 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[4];
char rpcinfo[64];
char rpcmachineinfo[64];
char portinfo[64];
char xmlbuf[2560];
char grepvers[256];
char grepown[64];
char *p;
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 ownercol = -1; // Used for ident scan
int colno = 0;
unsigned int rowno;
int numrows;
int numignoredports = plist->numIgnoredPorts();
vector<const char *> saved_servicefps;
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));
prevstate = istate;
}
if (numignoredports == plist->numports) {
log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT,
"%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_NORMAL|LOG_SKID|LOG_STDOUT, statenum2str(plist->nextIgnoredState(PORT_UNKNOWN)));
} else {
prevstate = PORT_UNKNOWN;
while ((istate = plist->nextIgnoredState(prevstate)) != PORT_UNKNOWN) {
if (prevstate != PORT_UNKNOWN) log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT, " or ");
log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT, "%s (%d)", statenum2str(istate), plist->getStateCounts(istate));
prevstate = istate;
}
}
log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT, "\n");
log_write(LOG_MACHINE,"Host: %s (%s)\tStatus: Up",
currenths->targetipstr(), currenths->HostName());
log_write(LOG_XML, "</ports>\n");
return;
}
log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT,"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_NORMAL|LOG_SKID|LOG_STDOUT, "Not shown: ");
else log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT, ", ");
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_NORMAL|LOG_SKID|LOG_STDOUT, "%d %s %s", plist->getStateCounts(istate), statenum2str(istate), desc);
prevstate = istate;
}
if (prevstate != PORT_UNKNOWN) log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT, "\n");
/* OK, now it is time to deal with the service table ... */
colno = 0;
portcol = colno++;
statecol = colno++;
servicecol = 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 (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;
state = statenum2str(current->state);
proto = nmap_getprotbynum(htons(current->portno));
snprintf(portinfo, sizeof(portinfo), "%-24s",
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\" />", current->portno, state);
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, TCPANDUDP, 0))!=NULL ) {
if (!plist->isIgnoredState(current->state)) {
if (!first) log_write(LOG_MACHINE,", ");
else first = 0;
strcpy(protocol,(current->proto == IPPROTO_TCP)? "tcp": "udp");
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 (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\" />", state);
if (current->owner && *current->owner) {
log_write(LOG_XML, "<owner name=\"%s\" />", current->owner);
}
if (getServiceXMLBuf(&sd, xmlbuf, sizeof(xmlbuf)) == 0)
if (*xmlbuf)
log_write(LOG_XML, "%s", xmlbuf);
rowno++;
#ifndef NOLUA
if(o.script) {
ScriptResults::iterator ssr_iter;
for( ssr_iter = current->scriptResults.begin();
ssr_iter != current->scriptResults.end();
ssr_iter++) {
char* script_output = formatScriptOutput((*ssr_iter));
Tbl->addItem(rowno, 0, true, true, script_output);
free(script_output);
log_write(LOG_XML, "<script id=\"%s\" output=\"%s\" />",
(*ssr_iter).id, (*ssr_iter).output);
rowno++;
}
}
#endif
log_write(LOG_XML, "</port>\n");
}
}
}
/* log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT,"\n"); */
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_NORMAL|LOG_SKID|LOG_STDOUT, "%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_NORMAL|LOG_SKID|LOG_STDOUT, "%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_NORMAL|LOG_SKID|LOG_STDOUT, "==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============\n");
log_write(LOG_NORMAL|LOG_SKID|LOG_STDOUT, "%s\n", saved_servicefps[i]);
}
}
log_flush_all();
}
char* formatScriptOutput(struct script_scan_result ssr) {
char* c_result;
std::string result = std::string();
string::size_type pos;
int line = 0;
#ifdef WIN32
char* sep = "\r\n";
#else
char* sep = "\n";
#endif
std::string line_prfx = "| ";
char* token = strtok(ssr.output, sep);
result += line_prfx + std::string(ssr.id) + ": ";
while(token != NULL) {
if(line > 0)
result += line_prfx;
result += std::string(token) + sep;
token = strtok(NULL, sep);
line++;
}
// fix the last line
pos = result.rfind(line_prfx);
result.replace(pos, 3, "|_ ");
// delete the unwanted trailing newline
pos = result.rfind(sep);
result.erase(pos, strlen(sep));
c_result = strdup(result.c_str());
return c_result;
}
char* xml_convert (const char* str) {
char *temp, ch=0, prevch = 0, *p;
int strl = strlen(str);
temp = (char *) safe_malloc(strl*6+1);
char *end = temp + strl * 6 + 1;
for (p = temp;(prevch = ch, ch = *str);str++) {
char *a;
switch (ch) {
case '<':
a = "<";
break;
case '>':
a = ">";
break;
case '&':
a = "&";
break;
case '"':
a = """;
break;
case '\'':
a = "'";
break;
case '-':
if (prevch == '-') { /* Must escape -- for comments */
a = "-";
break;
}
default:
*p++ = ch;
continue;
}
assert(end - p > 1);
Strncpy(p,a, end - p - 1); p += strlen(a); // SAFE
}
*p = 0;
temp = (char *) safe_realloc(temp,strlen(temp)+1);
return temp;
}
/* 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) {
static char *writebuf = NULL;
static int writebuflen = 8192;
bool skid_noxlate = false;
int rc = 0;
int len;
int fileidx = 0;
int l;
va_list apcopy;
if (!writebuf)
writebuf = (char *) safe_malloc(writebuflen);
if (logt == LOG_SKID_NOXLT) {
logt = LOG_SKID;
skid_noxlate = true;
}
switch(logt) {
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_NORMAL:
case LOG_MACHINE:
case LOG_SKID:
case LOG_XML:
#ifdef WIN32
apcopy = ap;
#else
va_copy(apcopy, ap); /* Needed in case we need to so a second vnsprintf */
#endif
l = logt;
fileidx = 0;
while ((l&1)==0) { fileidx++; l>>=1; }
assert(fileidx < LOG_NUM_FILES);
if (o.logfd[fileidx]) {
len = vsnprintf(writebuf, writebuflen, fmt, ap);
if (len == 0) {
va_end(apcopy);
return;
} else if (len < 0) {
fprintf(stderr, "vsnprintf returned %d in %s -- bizarre. Quitting.\n", len, __FUNCTION__);
exit(1);
} else if (len >= writebuflen) {
/* Didn't have enough space. Expand writebuf and try again */
free(writebuf);
writebuflen = len + 1024;
writebuf = (char *) safe_malloc(writebuflen);
len = vsnprintf(writebuf, writebuflen, fmt, apcopy);
if (len <= 0 || len >= writebuflen) {
fprintf(stderr, "%s: vnsprintf failed. Even after increasing bufferlen to %d, vsnprintf returned %d (logt == %d). Please email this message to fyodor@insecure.org. Quitting.\n", __FUNCTION__, writebuflen, len, logt);
exit(1);
}
}
if (logt == LOG_SKID && !skid_noxlate)
skid_output(writebuf);
rc = fwrite(writebuf,len,1,o.logfd[fileidx]);
if (rc != 1) {
fprintf(stderr, "Failed to write %d bytes of data to (logt==%d) stream. fwrite returned %d. Quitting.\n", len, logt, rc);
exit(1);
}
va_end(apcopy);
}
break;
default:
fprintf(stderr, "log_vwrite(): Passed unknown log type (%d). Note that this function, unlike log_write, can only handle one log type at a time (no bitmasks)\n", logt);
exit(1);
}
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);
if (!fmt || !*fmt) return;
for (int l = 1; l <= LOG_MAX; l <<= 1) {
if (logt & l) {
va_start(ap, fmt);
log_vwrite(l, fmt, ap);
va_end(ap);
}
}
return;
}
/* Close the given log stream(s) */
void log_close(int logt)
{
int i;
if (logt<0 || logt>LOG_FILE_MASK) return;
for (i=0;logt;logt>>=1,i++) if (o.logfd[i] && (logt&1)) fclose(o.logfd[i]);
}
/* Flush the given log stream(s). In other words, all buffered output
is written to the log immediately */
void log_flush(int logt) {
int i;
if (logt & LOG_STDOUT) {
fflush(o.nmap_stdout);
logt -= LOG_STDOUT;
}
if (logt & LOG_STDERR) {
fflush(stderr);
logt -= LOG_STDERR;
}
if (logt & LOG_SKID_NOXLT)
fatal("You are not allowed to log_flush() with LOG_SKID_NOXLT");
if (logt<0 || logt>LOG_FILE_MASK) return;
for (i=0;logt;logt>>=1,i++)
{
if (!o.logfd[i] || !(logt&1)) continue;
fflush(o.logfd[i]);
}
}
/* Flush every single log stream -- all buffered output is written to the
corresponding logs immediately */
void log_flush_all() {
int fileno;
for(fileno = 0; fileno < LOG_NUM_FILES; fileno++) {
if (o.logfd[fileno]) fflush(o.logfd[fileno]);
}
fflush(stdout);
fflush(stderr);
}
/* Open a log descriptor of the type given to the filename given. If
append is nonzero, the file will be appended instead of clobbered if
it already exists. If the file does not exist, it will be created */
int log_open(int logt, int append, char *filename)
{
int i=0;
if (logt<=0 || logt>LOG_FILE_MASK) return -1;
while ((logt&1)==0) { i++; logt>>=1; }
if (o.logfd[i]) fatal("Only one %s output filename allowed",logtypes[i]);
if (*filename == '-' && *(filename + 1) == '\0')
{
o.logfd[i]=stdout;
o.nmap_stdout = fopen(DEVNULL, "w");
if (!o.nmap_stdout)
fatal("Could not assign %s to stdout for writing", DEVNULL);
}
else
{
if (o.append_output)
o.logfd[i] = fopen(filename, "a");
else
o.logfd[i] = fopen(filename, "w");
if (!o.logfd[i])
fatal("Failed to open %s output file %s for writing", logtypes[i], filename);
}
return 1;
}
/* The items in ports should be
in sequential order for space savings and easier to read output. Outputs
the rangelist to the log stream given (such as LOG_MACHINE or LOG_XML) */
static void output_rangelist_given_ports(int logt, unsigned short *ports,
int numports) {
int i, previous_port = -2, range_start = -2, port;
char outpbuf[128];
for(i=0; i <= numports; i++) {
port = (i < numports)? ports[i] : 0xABCDE;
if (port != previous_port + 1) {
outpbuf[0] = '\0';
if (range_start != previous_port && range_start != -2)
sprintf(outpbuf, "-%hu", previous_port);
if (port != 0xABCDE) {
if (range_start != -2)
strcat(outpbuf, ",");
sprintf(outpbuf + strlen(outpbuf), "%hu", port);
}
if (*outpbuf)
log_write(logt, "%s", outpbuf);
range_start = port;
}
previous_port = port;
}
}
/* Output the list of ports scanned to the top of machine parseable
logs (in a comment, unfortunately). The items in ports should be
in sequential order for space savings and easier to read output */
void output_ports_to_machine_parseable_output(struct scan_lists *ports,
int tcpscan, int udpscan,
int protscan) {
int tcpportsscanned = ports->tcp_count;
int udpportsscanned = ports->udp_count;
int protsscanned = ports->prot_count;
log_write(LOG_MACHINE, "# Ports scanned: TCP(%d;", tcpportsscanned);
if (tcpportsscanned)
output_rangelist_given_ports(LOG_MACHINE, ports->tcp_ports, tcpportsscanned);
log_write(LOG_MACHINE, ") UDP(%d;", udpportsscanned);
if (udpportsscanned)
output_rangelist_given_ports(LOG_MACHINE, ports->udp_ports, udpportsscanned);
log_write(LOG_MACHINE, ") PROTOCOLS(%d;", protsscanned);
if (protsscanned)
output_rangelist_given_ports(LOG_MACHINE, ports->prots, protsscanned);
log_write(LOG_MACHINE, ")\n");
log_flush_all();
}