File: Parser.pm

package info (click to toggle)
libnmap-parser-perl 1.37-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 264 kB
  • sloc: perl: 2,004; xml: 299; makefile: 2
file content (1959 lines) | stat: -rw-r--r-- 58,322 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
package Nmap::Parser;

use strict;
use XML::Twig;

our $VERSION = 1.37;


sub new {

    my ( $class, $self ) = shift;
    $class = ref($class) || $class;

    $self->{twig} = new XML::Twig(
        start_tag_handlers => { nmaprun => sub {$self->_nmaprun_start_tag_hdlr(@_)} },

        twig_roots => {
            scaninfo => sub {$self->_scaninfo_tag_hdlr(@_)},
            prescript => sub {$self->_prescript_tag_hdlr(@_)},
            postscript => sub {$self->_postscript_tag_hdlr(@_)},
            finished => sub {$self->_finished_tag_hdlr(@_)},
            host     => sub {$self->_host_tag_hdlr(@_)},
        },
        ignore_elts => {
            addport      => 1,
            debugging    => 1,
            verbose      => 1,
            hosts        => 1,
            taskbegin    => 1,
            taskend      => 1,
            taskprogress => 1
        }
    );

    bless( $self, $class );
    return $self;
}

#/*****************************************************************************/
# NMAP::PARSER OBJECT METHODS
#/*****************************************************************************/

#Safe parse and parsefile will return $@ which will contain the error
#that occured if the parsing failed (it might be empty when no error occurred)

sub callback {
    my $self     = shift;
    my $callback = shift;    #first arg is CODE
    if ( ref($callback) eq 'CODE' ) {
        $self->{callback}{coderef}       = $callback;
        $self->{callback}{is_registered} = 1;
    }
    else {
        $self->{callback}{is_registered} = 0;
    }

    #returns if a callback is registered or not
    return $self->{callback}{is_registered};
}

sub _parse {
    my $type = shift;
    my $self = shift;
    $self->{HOSTS} = undef;
    $self->{SESSION} = undef;
    {
        file => sub { $self->{twig}->safe_parsefile(@_); },
        string => sub { $self->{twig}->safe_parse(@_); },
    }->{$type}->(@_);
    if ($@) { die $@; }
    $self->purge;
    return $self;
}

sub parse {
    return _parse('string', @_);
}

sub parsefile {
    return _parse('file', @_);
}

sub parsescan {
    my $self = shift;
    my $nmap = shift;
    my $args = shift;
    my @ips  = @_;
    my $FH;

    if ( $args =~ /-o(?:X|N|G)/ ) {
        die
"[Nmap-Parser] Cannot pass option '-oX', '-oN' or '-oG' to parsecan()";
    }

    my $cmd;

#if output file is defined, point it to a localfile then call parsefile instead.
    if ( defined( $self->{cache_file} ) ) {
        $cmd =
            "$nmap $args -v -v -v -oX "
          . $self->{cache_file} . " "
          . ( join ' ', @ips );
        `$cmd`;    #remove output from STDOUT
        $self->parsefile( $self->{cache_file} );
    }
    else {
        $cmd = "$nmap $args -v -v -v -oX - " . ( join ' ', @ips );
        open $FH,
          "$cmd |" || die "[Nmap-Parser] Could not perform nmap scan - $!";
        $self->parse($FH);
        close $FH;
    }

    return $self;
}

sub cache_scan {
    my $self = shift;
    $self->{cache_file} = shift || 'nmap-parser-cache.' . time() . '.xml';
}

sub purge {
    my $self = shift;
    $self->{twig}->purge;
    return $self;
}

sub addr_sort {
    my $self = shift if ref $_[0];

    return (
        map { unpack("x16A*", $_) }
            sort { $a cmp $b }
            map {
                my @vals;
                if( /:/ ) { #IPv6
                    @vals = split /:/;
                    @vals = map { $_ eq '' ? (0) x (8-$#vals) : hex } @vals
                } else { #IPv4
                    my @v4 = split /\./;
                    # Sort as IPv4-mapped IPv6, per RFC 4291 Section 2.5.5.2
                    @vals = ( (0) x 5, 0xffff, map { 256*$v4[$_] + $v4[$_+1] } (0,2) );
                }
                pack("n8A*", @vals, $_)
            } @_
        );
}

#MAIN SCAN INFORMATION
sub get_session {
    my $self = shift;
    my $obj  = Nmap::Parser::Session->new( $self->{SESSION} );
    return $obj;
}

#HOST STUFF
sub get_host {
    my ( $self, $ip ) = (@_);
    if ( $ip eq '' ) {
        warn "[Nmap-Parser] No IP address given to get_host()\n";
        return undef;
    }
    $self->{HOSTS}{$ip};
}

sub del_host {
    my ( $self, $ip ) = (@_);
    if ( $ip eq '' ) {
        warn "[Nmap-Parser] No IP address given to del_host()\n";
        return undef;
    }
    delete $self->{HOSTS}{$ip};
}

sub all_hosts {
    my $self = shift;
    my $status = shift || '';

    return ( values %{ $self->{HOSTS} } ) if ( $status eq '' );

    my @hosts = grep { $_->{status} eq $status } ( values %{ $self->{HOSTS} } );
    return @hosts;
}

sub get_ips {
    my $self = shift;
    my $status = shift || '';

    return $self->addr_sort( keys %{ $self->{HOSTS} } ) if ( $status eq '' );

    my @hosts =
      grep { $self->{HOSTS}{$_}{status} eq $status }
      ( keys %{ $self->{HOSTS} } );
    return $self->addr_sort(@hosts);

}

#/*****************************************************************************/
# PARSING TAG HANDLERS FOR XML::TWIG
#/*****************************************************************************/

sub _nmaprun_start_tag_hdlr {

    my ($self, $twig, $tag ) = @_;

    $self->{SESSION}{start_time}   = $tag->{att}->{start};
    $self->{SESSION}{nmap_version} = $tag->{att}->{version};
    $self->{SESSION}{start_str}    = $tag->{att}->{startstr};
    $self->{SESSION}{xml_version}  = $tag->{att}->{xmloutputversion};
    $self->{SESSION}{scan_args}    = $tag->{att}->{args};
    $self->{SESSION} = Nmap::Parser::Session->new( $self->{SESSION} );

    $twig->purge;

}

sub _scaninfo_tag_hdlr {
    my ( $self, $twig, $tag ) = @_;
    my $type        = $tag->{att}->{type};
    my $proto       = $tag->{att}->{protocol};
    my $numservices = $tag->{att}->{numservices};

    if ( defined($type) ) {    #there can be more than one type in one scan
        $self->{SESSION}{type}{$type}        = $proto;
        $self->{SESSION}{numservices}{$type} = $numservices;
    }
    $twig->purge;
}

sub _prescript_tag_hdlr {
    my ($self, $twig, $tag ) = @_;
    my $scripts_hashref;
    for my $script ( $tag->children('script') ) {
        $scripts_hashref->{ $script->{att}->{id} } =
            __script_tag_hdlr( $script );
    }
    $self->{SESSION}{prescript} = $scripts_hashref;
    $twig->purge;
}

sub _postscript_tag_hdlr {
    my ($self, $twig, $tag ) = @_;
    my $scripts_hashref;
    for my $script ( $tag->children('script') ) {
        $scripts_hashref->{ $script->{att}->{id} } =
          __script_tag_hdlr( $script );
    }
    $self->{SESSION}{postscript} = $scripts_hashref;
    $twig->purge;
}

sub _finished_tag_hdlr {
    my ($self, $twig, $tag ) = @_;
    $self->{SESSION}{finish_time} = $tag->{att}->{time};
    $self->{SESSION}{time_str}    = $tag->{att}->{timestr};
    $twig->purge;
}

#parses all the host information in one swoop (calling __host_*_tag_hdlrs)
sub _host_tag_hdlr {
    my ($self, $twig, $tag ) = @_;
    my $id = undef;

    return undef unless ( defined $tag );

    #GET ADDRESS INFO
    my $addr_hashref;
    $addr_hashref = __host_addr_tag_hdlr($tag);

    #use this as the identifier
    $id =
         $addr_hashref->{ipv4}
      || $addr_hashref->{ipv6}
      || $addr_hashref->{mac};    #worstcase use MAC

    $self->{HOSTS}{$id}{addrs} = $addr_hashref;

    return undef unless ( defined($id) || $id ne '' );

    #GET HOSTNAMES
    $self->{HOSTS}{$id}{hostnames} = __host_hostnames_tag_hdlr($tag);

    #GET STARTTIME
    $self->{HOSTS}{$id}{starttime} = $tag->{att}->{starttime};

    #GET STATUS
    $self->{HOSTS}{$id}{status} = $tag->first_child('status')->{att}->{state};

    #CONTINUE PROCESSING IF STATUS IS UP - OTHERWISE NO MORE XML
    if ( lc( $self->{HOSTS}{$id}{status} ) eq 'up' ) {

        $self->{HOSTS}{$id}{ports}         = __host_port_tag_hdlr($tag);
        $self->{HOSTS}{$id}{os}            = __host_os_tag_hdlr($tag);
        $self->{HOSTS}{$id}{uptime}        = __host_uptime_tag_hdlr($tag);
        $self->{HOSTS}{$id}{tcpsequence}   = __host_tcpsequence_tag_hdlr($tag);
        $self->{HOSTS}{$id}{ipidsequence}  = __host_ipidsequence_tag_hdlr($tag);
        $self->{HOSTS}{$id}{tcptssequence} = __host_tcptssequence_tag_hdlr($tag);
        $self->{HOSTS}{$id}{hostscript} = __host_hostscript_tag_hdlr($tag);
        $self->{HOSTS}{$id}{distance} =
          __host_distance_tag_hdlr($tag);    #returns simple value
        $self->{HOSTS}{$id}{trace}         = __host_trace_tag_hdlr($tag);
        $self->{HOSTS}{$id}{trace_error}   = __host_trace_error_tag_hdlr($tag);
    }

    #CREATE HOST OBJECT FOR USER
    $self->{HOSTS}{$id} = Nmap::Parser::Host->new( $self->{HOSTS}{$id} );

    if ( $self->{callback}{is_registered} ) {
        &{ $self->{callback}{coderef} }( $self->{HOSTS}{$id} );
        delete $self->{HOSTS}{$id};
    }

    $twig->purge;

}

sub __host_addr_tag_hdlr {
    my $tag = shift;
    my $addr_hashref;

    #children() will return all children with tag name address
    for my $addr ( $tag->children('address') ) {
        if ( lc( $addr->{att}->{addrtype} ) eq 'mac' ) {

            #we'll assume for now, only 1 MAC address per system
            $addr_hashref->{mac}{addr}   = $addr->{att}->{addr};
            $addr_hashref->{mac}{vendor} = $addr->{att}->{vendor};
        }
        elsif ( lc( $addr->{att}->{addrtype} ) eq 'ipv4' ) {
            $addr_hashref->{ipv4} = $addr->{att}->{addr};
        }    #support for ipv6? we'll see
        elsif ( lc( $addr->{att}->{addrtype} ) eq 'ipv6' ) {
            $addr_hashref->{ipv6} = $addr->{att}->{addr};
        }

    }

    return $addr_hashref;
}

sub __host_hostnames_tag_hdlr {
    my $tag = shift;

    my $hostnames_tag = $tag->first_child('hostnames');
    return undef unless ( defined $hostnames_tag );

    my @hostnames;

    for my $name ( $hostnames_tag->children('hostname') ) {
        push @hostnames, $name->{att}->{name};
    }

    return \@hostnames;

}

sub __host_port_tag_hdlr {
    my $tag = shift;
    my ( $port_hashref, $ports_tag );

    $ports_tag = $tag->first_child('ports');

    return undef unless ( defined $ports_tag );

    #Parsing Extraports
    my $extraports_tag = $ports_tag->first_child('extraports');
    if ( defined $extraports_tag && $extraports_tag ne '' ) {
        $port_hashref->{extraports}{state} = $extraports_tag->{att}->{state};
        $port_hashref->{extraports}{count} = $extraports_tag->{att}->{count};
    }

    #Parsing regular port information

    my ( $tcp_port_count, $udp_port_count ) = ( 0, 0 );

    for my $port_tag ( $ports_tag->children('port') ) {
        my $proto  = $port_tag->{att}->{protocol};
        my $portid = $port_tag->{att}->{portid};
        my $state  = $port_tag->first_child('state');
        my $owner  = $port_tag->first_child('owner') || undef;

        $tcp_port_count++ if ( $proto eq 'tcp' );
        $udp_port_count++ if ( $proto eq 'udp' );

        $port_hashref->{$proto}{$portid}{state} = $state->{att}->{state}
          || 'unknown'
          if ( $state ne '' );

        $port_hashref->{$proto}{$portid}{reason_ttl} = $state->{att}->{reason_ttl}
          || 'unknown'
          if($state ne '');

        #GET SERVICE INFORMATION
        $port_hashref->{$proto}{$portid}{service} =
          __host_service_tag_hdlr( $port_tag, $portid )
          if ( defined($proto) && defined($portid) );

        #GET SCRIPT INFORMATION
        $port_hashref->{$proto}{$portid}{service}{script} =
          __host_script_tag_hdlr( $port_tag, $portid)
          if ( defined($proto) && defined($portid) );

        #GET OWNER INFORMATION
        $port_hashref->{$proto}{$portid}{service}{owner} = $owner->{att}->{name}
          if ( defined($owner) );

   #These are added at the end, otherwise __host_service_tag_hdlr will overwrite
   #GET PORT STATE

    }

    $port_hashref->{tcp_port_count} = $tcp_port_count;
    $port_hashref->{udp_port_count} = $udp_port_count;

    return $port_hashref;

}

sub __host_service_tag_hdlr {
    my $tag    = shift;
    my $portid = shift;   #need a way to remember what port this service runs on
    my $service = $tag->first_child('service[@name]');
    my $service_hashref;
    $service_hashref->{port} = $portid;

    if ( defined $service ) {
        $service_hashref->{name}      = $service->{att}->{name} || 'unknown';
        $service_hashref->{version}   = $service->{att}->{version};
        $service_hashref->{product}   = $service->{att}->{product};
	$service_hashref->{devicetype} = $service->{att}->{devicetype};
        $service_hashref->{extrainfo} = $service->{att}->{extrainfo};
        $service_hashref->{proto} =
             $service->{att}->{proto}
          || $service->{att}->{protocol}
          || 'unknown';
        $service_hashref->{rpcnum}      = $service->{att}->{rpcnum};
        $service_hashref->{tunnel}      = $service->{att}->{tunnel};
        $service_hashref->{method}      = $service->{att}->{method};
        $service_hashref->{confidence}  = $service->{att}->{conf};
        $service_hashref->{fingerprint} = $service->{att}->{servicefp};
    }

    return $service_hashref;
}

sub __host_script_tag_hdlr {
    my $tag = shift;
    my $script_hashref;

    for ( $tag->children('script') ) {
        $script_hashref->{ $_->{att}->{id} } =
         __script_tag_hdlr($_);
    }

    return $script_hashref;
}

sub __host_os_tag_hdlr {
    my $tag    = shift;
    my $os_tag = $tag->first_child('os');
    my $os_hashref;
    my $portused_tag;
    my $os_fingerprint;

    if ( defined $os_tag ) {

        #get the open port used to match os
        $portused_tag = $os_tag->first_child("portused[\@state='open']");
        $os_hashref->{portused}{open} = $portused_tag->{att}->{portid}
          if ( defined $portused_tag );

        #get the closed port used to match os
        $portused_tag = $os_tag->first_child("portused[\@state='closed']");
        $os_hashref->{portused}{closed} = $portused_tag->{att}->{portid}
          if ( defined $portused_tag );

        #os fingerprint
        $os_fingerprint = $os_tag->first_child("osfingerprint");
        $os_hashref->{os_fingerprint} =
          $os_fingerprint->{'att'}->{'fingerprint'}
          if ( defined $os_fingerprint );

        #This will go in Nmap::Parser::Host::OS
        my $osmatch_index = 0;
        my $osclass_index = 0;
        for my $osmatch ( $os_tag->children('osmatch') ) {
            $os_hashref->{osmatch_name}[$osmatch_index] =
              $osmatch->{att}->{name};
            $os_hashref->{osmatch_name_accuracy}[$osmatch_index] =
              $osmatch->{att}->{accuracy};
            $osmatch_index++;
            for my $osclass ( $osmatch->children('osclass') ) {
                $os_hashref->{osclass_osfamily}[$osclass_index] =
                  $osclass->{att}->{osfamily};
                $os_hashref->{osclass_osgen}[$osclass_index] =
                  $osclass->{att}->{osgen};
                $os_hashref->{osclass_vendor}[$osclass_index] =
                  $osclass->{att}->{vendor};
                $os_hashref->{osclass_type}[$osclass_index] =
                  $osclass->{att}->{type};
                $os_hashref->{osclass_class_accuracy}[$osclass_index] =
                  $osclass->{att}->{accuracy};
                $osclass_index++;
            }
        }
        $os_hashref->{'osmatch_count'} = $osmatch_index;

        #parse osclass tags
        for my $osclass ( $os_tag->children('osclass') ) {
            $os_hashref->{osclass_osfamily}[$osclass_index] =
              $osclass->{att}->{osfamily};
            $os_hashref->{osclass_osgen}[$osclass_index] =
              $osclass->{att}->{osgen};
            $os_hashref->{osclass_vendor}[$osclass_index] =
              $osclass->{att}->{vendor};
            $os_hashref->{osclass_type}[$osclass_index] =
              $osclass->{att}->{type};
            $os_hashref->{osclass_class_accuracy}[$osclass_index] =
              $osclass->{att}->{accuracy};
            $osclass_index++;
        }
        $os_hashref->{'osclass_count'} = $osclass_index;
    }

    return $os_hashref;

}

sub __host_uptime_tag_hdlr {
    my $tag    = shift;
    my $uptime = $tag->first_child('uptime');
    my $uptime_hashref;

    if ( defined $uptime ) {
        $uptime_hashref->{seconds}  = $uptime->{att}->{seconds};
        $uptime_hashref->{lastboot} = $uptime->{att}->{lastboot};

    }

    return $uptime_hashref;

}

sub __host_tcpsequence_tag_hdlr {
    my $tag      = shift;
    my $sequence = $tag->first_child('tcpsequence');
    my $sequence_hashref;
    return undef unless ($sequence);
    $sequence_hashref->{class}  = $sequence->{att}->{class};
    $sequence_hashref->{difficulty}  = $sequence->{att}->{difficulty};
    $sequence_hashref->{values} = $sequence->{att}->{values};
    $sequence_hashref->{index}  = $sequence->{att}->{index};

    return $sequence_hashref;

}

sub __host_ipidsequence_tag_hdlr {
    my $tag      = shift;
    my $sequence = $tag->first_child('ipidsequence');
    my $sequence_hashref;
    return undef unless ($sequence);
    $sequence_hashref->{class}  = $sequence->{att}->{class};
    $sequence_hashref->{values} = $sequence->{att}->{values};
    return $sequence_hashref;

}

sub __host_tcptssequence_tag_hdlr {
    my $tag      = shift;
    my $sequence = $tag->first_child('tcptssequence');
    my $sequence_hashref;
    return undef unless ($sequence);
    $sequence_hashref->{class}  = $sequence->{att}->{class};
    $sequence_hashref->{values} = $sequence->{att}->{values};
    return $sequence_hashref;
}

sub __host_hostscript_tag_hdlr {
    my $tag = shift;
    my $scripts = $tag->first_child('hostscript');
    my $scripts_hashref;
    return undef unless ($scripts);
    for my $script ( $scripts->children('script') ) {
        $scripts_hashref->{ $script->{att}->{id} } =
            __script_tag_hdlr( $script );
    }
    return $scripts_hashref;
}

sub __host_distance_tag_hdlr {
    my $tag      = shift;
    my $distance = $tag->first_child('distance');
    return undef unless ($distance);
    return $distance->{att}->{value};
}

sub __host_trace_tag_hdlr {
    my $tag           = shift;
    my $trace_tag     = $tag->first_child('trace');
    my $trace_hashref = { hops => [], };

    if ( defined $trace_tag ) {

        my $proto = $trace_tag->{att}->{proto};
        $trace_hashref->{proto} = $proto if defined $proto;

        my $port = $trace_tag->{att}->{port};
        $trace_hashref->{port} = $port if defined $port;

        for my $hop_tag ( $trace_tag->children('hop') ) {

            # Copy the known hop attributes, they will go in
            # Nmap::Parser::Host::TraceHop
            my %hop_data;
            $hop_data{$_} = $hop_tag->{att}->{$_} for qw( ttl rtt ipaddr host );
            delete $hop_data{rtt} if $hop_data{rtt} !~ /^[\d.]+$/;

            push @{ $trace_hashref->{hops} }, \%hop_data;
        }

    }

    return $trace_hashref;
}

sub __host_trace_error_tag_hdlr {
    my $tag       = shift;
    my $trace_tag = $tag->first_child('trace');

    if ( defined $trace_tag ) {

        my $error_tag = $trace_tag->first_child('error');
        if ( defined $error_tag ) {

            # If an error happens, always provide a true value even if
            # it doesn't contains a useful string
            my $errorstr = $error_tag->{att}->{errorstr} || 1;
            return $errorstr;
        }
    }

    return;
}

sub __script_tag_hdlr {
    my $tag = shift;
    my $script_hashref = {
        output => $tag->{att}->{output}
    };
    chomp %$script_hashref;
    if ( not $tag->is_empty()) {
        $script_hashref->{contents} = __script_table($tag);
    }
    return $script_hashref;
}

sub __script_table {
    my $tag = shift;
    my ($ref, $subref);
    my $fc = $tag->first_child();
    if ($fc) {
        if ($fc->is_text) {
            $ref = $fc->text;
        }
        else {
            if ($fc->{att}->{key}) {
                $ref = {};
                $subref = sub {
                    $ref->{$_->{att}->{key}} = shift;
                };
            }
            else {
                $ref = [];
                $subref = sub {
                    push @$ref, shift;
                };
            }
            for ($tag->children()) {
                if ($_->tag() eq "table") {
                    $subref->(__script_table( $_ ));
                }
                else {
                    $subref->($_->text);
                }
            }
        }
    }
    return $ref
}

#/*****************************************************************************/
# NMAP::PARSER::SESSION
#/*****************************************************************************/

package Nmap::Parser::Session;
use vars qw($AUTOLOAD);

sub new {
    my $class = shift;
    $class = ref($class) || $class;
    my $self = shift || {};
    bless( $self, $class );
    return $self;
}

#Support for:
#start_time, start_str, finish_time, time_str, nmap_version, xml_version, scan_args
sub AUTOLOAD {
    ( my $param = $AUTOLOAD ) =~ s{.*::}{}xms;
    return if ( $param eq 'DESTROY' );
    no strict 'refs';
    *$AUTOLOAD = sub { return $_[0]->{ lc $param } };
    goto &$AUTOLOAD;
}

sub numservices {
    my $self = shift;
    my $type = shift
      || '';   #(syn|ack|bounce|connect|null|xmas|window|maimon|fin|udp|ipproto)

    return unless ( ref( $self->{numservices} ) eq 'HASH' );

    if ( $type ne '' ) { return $self->{numservices}{$type}; }
    else {
        my $total = 0;
        for ( values %{ $self->{numservices} } ) { $total += $_; }
        return $total;
    }          #(else) total number of services together
}

sub scan_types {
    return sort { $a cmp $b } ( keys %{ $_[0]->{type} } )
      if ( ref( $_[0]->{type} ) eq 'HASH' );
}
sub scan_type_proto { return $_[1] ? $_[0]->{type}{ $_[1] } : undef; }

sub prescripts {
    my $self = shift;
    my $id = shift;
    unless ( defined $id ) {
        return sort keys %{ $self->{prescript} };
    }
    else {
        return $self->{prescript}{$id};
    }
}

sub postscripts {
    my $self = shift;
    my $id = shift;
    unless ( defined $id ) {
        return sort keys %{ $self->{postscript} };
    }
    else {
        return $self->{postscript}{$id};
    }
}

#/*****************************************************************************/
# NMAP::PARSER::HOST
#/*****************************************************************************/

package Nmap::Parser::Host;
use vars qw($AUTOLOAD);

sub new {
    my $class = shift;
    $class = ref($class) || $class;
    my $self = shift || {};
    bless( $self, $class );
    return $self;
}

sub starttime { return $_[0]->{starttime}; }

sub status { return $_[0]->{status}; }

sub addr {
    my $default = $_[0]->{addrs}{ipv4} || $_[0]->{addrs}{ipv6};
    return $default;
}

sub addrtype {
    if    ( $_[0]->{addrs}{ipv4} ) { return 'ipv4'; }
    elsif ( $_[0]->{addrs}{ipv6} ) { return 'ipv6'; }
}

sub ipv4_addr { return $_[0]->{addrs}{ipv4}; }
sub ipv6_addr { return $_[0]->{addrs}{ipv6}; }

sub mac_addr   { return $_[0]->{addrs}{mac}{addr}; }
sub mac_vendor { return $_[0]->{addrs}{mac}{vendor}; }

#returns the first hostname
sub hostname {
    my $self = shift;
    my $index = shift || 0;
    if ( ref( $self->{hostnames} ) ne 'ARRAY' ) { return ''; }
    if ( scalar @{ $self->{hostnames} } <= $index ) {
        $index = scalar @{ $self->{hostnames} } - 1;
    }
    return $self->{hostnames}[$index] if ( scalar @{ $self->{hostnames} } );
}

sub all_hostnames    { return @{ $_[0]->{hostnames} || [] }; }
sub extraports_state { return $_[0]->{ports}{extraports}{state}; }
sub extraports_count { return $_[0]->{ports}{extraports}{count}; }
sub distance         { return $_[0]->{distance}; }

sub hostscripts {
    my $self = shift;
    my $id = shift;
    unless ( defined $id ) {
        return sort keys %{ $self->{hostscript} };
    }
    else {
        return $self->{hostscript}{$id};
    }
}

sub all_trace_hops {

    my $self = shift;

    return unless defined $self->{trace}->{hops};
    return map { Nmap::Parser::Host::TraceHop->new( $_ ) }
      @{ $self->{trace}->{hops} };
}

sub trace_port  { return $_[0]->{trace}->{port} }
sub trace_proto { return $_[0]->{trace}->{proto} }
sub trace_error { return $_[0]->{trace_error} }

sub _del_port {
    my $self    = shift;
    my $proto   = pop;     #portid might be empty, so this goes first
    my @portids = @_;
    @portids = grep { $_ + 0 } @portids;

    unless ( scalar @portids ) {
        warn "[Nmap-Parser] No port number given to del_port()\n";
        return undef;
    }

    delete $self->{ports}{$proto}{$_} for (@portids);
}

sub _get_ports {
    my $self          = shift;
    my $proto         = pop;          #param might be empty, so this goes first
    my $state         = shift;    #open, filtered, closed or any combination
    my @matched_ports = ();

    #if $state is undef, then tcp_ports or udp_ports was called for all ports
    #therefore, only return the keys of all ports found
    if ( not defined $state ) {
        return sort { $a <=> $b } ( keys %{ $self->{ports}{$proto} } );
    }
    else {
        $state = lc($state)
    }

#the port parameter can be set to either any of these also 'open|filtered'
#can count as 'open' and 'filetered'. Therefore I need to use a regex from now on
#if $param is empty, then all ports match.

    for my $portid ( keys %{ $self->{ports}{$proto} } ) {

        #escape metacharacters ('|', for example in: open|filtered)
        #using \Q and \E
        push( @matched_ports, $portid )
          if ( $self->{ports}{$proto}{$portid}{state} =~ /\Q$state\E/ );

    }

    return sort { $a <=> $b } @matched_ports;

}

sub _get_port_state {
    my $self   = shift;
    my $proto  = pop;         #portid might be empty, so this goes first
    my $portid = lc(shift);

    return undef unless ( exists $self->{ports}{$proto}{$portid} );
    return $self->{ports}{$proto}{$portid}{state};

}

sub _get_port_state_ttl {
    my $self = shift;
    my $proto = pop;
    my $portid = lc(shift);

    return undef unless ( exists $self->{ports}{$proto}{$portid} );
    return $self->{ports}{$proto}{$portid}{reason_ttl};
}

#changed this to use _get_ports since it was similar code
sub tcp_ports { return _get_ports( @_, 'tcp' ); }
sub udp_ports { return _get_ports( @_, 'udp' ); }

sub tcp_port_count { return $_[0]->{ports}{tcp_port_count}; }
sub udp_port_count { return $_[0]->{ports}{udp_port_count}; }

sub tcp_port_state_ttl { return _get_port_state_ttl( @_, 'tcp' ); }

sub tcp_port_state { return _get_port_state( @_, 'tcp' ); }
sub udp_port_state { return _get_port_state( @_, 'udp' ); }

sub tcp_del_ports { return _del_port( @_, 'tcp' ); }
sub udp_del_ports { return _del_port( @_, 'udp' ); }

sub tcp_service {
    my $self   = shift;
    my $portid = shift;
    if ( $portid eq '' ) {
        warn "[Nmap-Parser] No port number passed to tcp_service()\n";
        return undef;
    }
    return Nmap::Parser::Host::Service->new(
        $self->{ports}{tcp}{$portid}{service} );
}

sub udp_service {
    my $self   = shift;
    my $portid = shift;
    if ( $portid eq '' ) {
        warn "[Nmap-Parser] No port number passed to udp_service()\n";
        return undef;
    }
    return Nmap::Parser::Host::Service->new(
        $self->{ports}{udp}{$portid}{service} );

}

#usually the first one is the highest accuracy

sub os_sig { return Nmap::Parser::Host::OS->new( $_[0]->{os} ); }

#Support for:
#tcpsequence_class, tcpsequence_values, tcpsequence_index,
#ipidsequence_class, ipidsequence_values, tcptssequence_values,
#tcptssequence_class, uptime_seconds, uptime_lastboot
#tcp_open_ports, udp_open_ports, tcp_filtered_ports, udp_filtered_ports,
#tcp_closed_ports, udp_closed_ports
sub AUTOLOAD {
    ( my $param = $AUTOLOAD ) =~ s{.*::}{}xms;
    return if ( $param eq 'DESTROY' );
    my ( $type, $val ) = split /_/, lc($param);

#splits the given method name by '_'. This will determine the function and param
    no strict 'refs';

    if (   ( $type eq 'tcp' || $type eq 'udp' )
        && ( $val eq 'open' || $val eq 'filtered' || $val eq 'closed' ) )
    {

#they must be looking for port info: tcp or udp. The $val is either open|filtered|closed
        *$AUTOLOAD = sub { return _get_ports( $_[0], $val, $type ); };
        goto &$AUTOLOAD;

    }
    elsif ( defined $type && defined $val ) {

        #must be one of the 'sequence' functions asking for class/values/index
        *$AUTOLOAD = sub { return $_[0]->{$type}{$val} };
        goto &$AUTOLOAD;
    }
    else { die '[Nmap-Parser] method ->' . $param . "() not defined!\n"; }
}

#/*****************************************************************************/
# NMAP::PARSER::HOST::SERVICE
#/*****************************************************************************/

package Nmap::Parser::Host::Service;
use vars qw($AUTOLOAD);

sub new {
    my $class = shift;
    $class = ref($class) || $class;
    my $self = shift || {};
    bless( $self, $class );
    return $self;
}

sub scripts {
    my $self = shift;
    my $id = shift;

    unless ( defined $id ) {
        return sort keys %{ $self->{script} };
    }
    else {
        return $self->{script}{$id};
    }
}

#Support for:
#name port proto rpcnum owner version product extrainfo tunnel method confidence
#this will now only load functions that will be used. This saves
#on delay (increase speed) and memory

sub AUTOLOAD {
    ( my $param = $AUTOLOAD ) =~ s{.*::}{}xms;
    return if ( $param eq 'DESTROY' );
    no strict 'refs';

    *$AUTOLOAD = sub { return $_[0]->{ lc $param } };
    goto &$AUTOLOAD;
}

#/*****************************************************************************/
# NMAP::PARSER::HOST::OS
#/*****************************************************************************/

package Nmap::Parser::Host::OS;
use vars qw($AUTOLOAD);

sub new {
    my $class = shift;
    $class = ref($class) || $class;
    my $self = shift || {};
    bless( $self, $class );
    return $self;
}

sub portused_open   { return $_[0]->{portused}{open}; }
sub portused_closed { return $_[0]->{portused}{closed}; }
sub os_fingerprint  { return $_[0]->{os_fingerprint}; }

sub name_count { return $_[0]->{osmatch_count}; }

sub all_names {
    my $self = shift;
    @_ = ();
    if ( $self->{osclass_count} < 1 ) { return @_; }
    if ( ref( $self->{osmatch_name} ) eq 'ARRAY' ) {
        return sort @{ $self->{osmatch_name} };
    }

}    #given by decreasing accuracy

sub class_count { return $_[0]->{osclass_count}; }

#Support for:
#name,names, name_accuracy, osfamily, vendor, type, osgen, class_accuracy
sub AUTOLOAD {
    ( my $param = $AUTOLOAD ) =~ s{.*::}{}xms;
    return if ( $param eq 'DESTROY' );
    no strict 'refs';
    $param = lc($param);

    $param = 'name' if ( $param eq 'names' );
    if ( $param eq 'name' || $param eq 'name_accuracy' ) {

        *$AUTOLOAD = sub { _get_info( $_[0], $_[1], $param, 'osmatch' ); };
        goto &$AUTOLOAD;
    }
    else {

        *$AUTOLOAD = sub { _get_info( $_[0], $_[1], $param, 'osclass' ); };
        goto &$AUTOLOAD;
    }
}

sub _get_info {
    my ( $self, $index, $param, $type ) = @_;
    $index ||= 0;

    #type is either osclass or osmatch
    if ( $index >= $self->{ $type . '_count' } ) {
        $index = $self->{ $type . '_count' } - 1;
    }
    return $self->{ $type . '_' . $param }[$index];
}

#/*****************************************************************************/
# NMAP::PARSER::HOST::TRACEHOP
#/*****************************************************************************/

package Nmap::Parser::Host::TraceHop;
use vars qw($AUTOLOAD);

sub new {
    my $class = shift;
    $class = ref($class) || $class;
    my $self = shift || {};
    bless( $self, $class );
    return $self;
}

sub AUTOLOAD {
    ( my $param = $AUTOLOAD ) =~ s{.*::}{}xms;
    return if ( $param eq 'DESTROY' );
    no strict 'refs';
    $param = lc($param);

    # Supported accessors:
    my %subs;
    @subs{ qw( ttl rtt ipaddr host ) } = 1;

    if ( exists $subs{$param} ) {

        *$AUTOLOAD = sub { $_[0]->{$param} };
        goto &$AUTOLOAD;
    }
    else { die '[Nmap-Parser] method ->' . $param . "() not defined!\n"; }
}

1;

__END__

=pod

=head1 NAME

Nmap::Parser - parse nmap scan data with perl

=head1 SYNOPSIS

  use Nmap::Parser;
  my $np = new Nmap::Parser;

  $np->parsescan($nmap_path, $nmap_args, @ips);
    #or
  $np->parsefile($file_xml);

  my $session    = $np->get_session();
    #a Nmap::Parser::Session object

  my $host       = $np->get_host($ip_addr);
    #a Nmap::Parser::Host object

  my $service = $host->tcp_service(80);
    #a Nmap::Parser::Host::Service object

  my $os         = $host->os_sig();
    #a Nmap::Parser::Host::OS object

 #---------------------------------------

 my $np2 = new Nmap::Parser;

 $np2->callback(\&my_callback);

 $np2->parsefile($file_xml);
    #or
 $np2->parsescan($nmap_path, $nmap_args, @ips);

 sub my_callback {

   my $host = shift;
    #Nmap::Parser::Host object
    #.. see documentation for all methods ...

 }


I<For a full listing of methods see the documentation corresponding to each object.>
You can also visit the website L<https://github.com/modernistik/Nmap-Parser> for additional installation instructions.

=head1 DESCRIPTION

This module implements a interface to the information contained in an nmap scan.
It is implemented by parsing the xml scan data that is generated by nmap. This
will enable anyone who utilizes nmap to quickly create fast and robust security scripts
that utilize the powerful port scanning abilities of nmap.

The latest version of this module can be found on here L<https://github.com/modernistik/Nmap-Parser>

=head1 OVERVIEW

This module has an internal framework to make it easy to retrieve the desired information of a scan.
Every nmap scan is based on two main sections of informations: the scan session, and the scan information of all hosts.
The session information will be stored as a Nmap::Parser::Session object. This object will contain its own methods
to obtain the desired information. The same is true for any hosts that were scanned using the Nmap::Parser::Host object.
There are two sub objects under Nmap::Parser::Host. One is the Nmap::Parser::Host::Service object which will be used to obtain
information of a given service running on a given port. The second is the Nmap::Parser::Host::OS object which contains the
operating system signature information (OS guessed names, classes, osfamily..etc).

  Nmap::Parser                        -- Core parser
     |
     +--Nmap::Parser::Session         -- Nmap scan session information
     |
     +--Nmap::Parser::Host            -- General host information
     |  |
     |  |-Nmap::Parser::Host::Service -- Port service information
     |  |
     |  |-Nmap::Parser::Host::OS      -- Operating system signature information


=head1 METHODS

=head2 Nmap::Parser

The main idea behind the core module is, you will first parse the information
and then extract data. Therefore, all parse*() methods should be executed before
any get_*() methods.

=over 4


=item B<parse($string)>

=item B<parse($filehandle)>

Parses the nmap scan information in $string. Note that is usually only used if
you have the whole xml scan information in $string or if you are piping the
scan information.

=item B<parsefile($xml_file)>

Parses the nmap scan data in $xml_file. This file can be generated from an nmap
scan by using the '-oX filename.xml' option with nmap. If you get an error or your program dies due to parsing, please check that the
xml information is compliant. The file is closed no matter how C<parsefile()> returns.

=item B<parsescan($nmap,$args,@ips)>

This method runs an nmap scan where $nmap is the path to the nmap executable or binary,
$args are the nmap command line parameters, and @ips are the list of IP addresses
to scan. parsescan() will automagically run the nmap scan and parse the information.

If you wish to save the xml output from parsescan(), you must call cache_scan() method B<BEFORE>
you start the parsescan() process. This is done to conserve memory while parsing. cache_scan() will
let Nmap::Parser know to save the output before parsing the xml since Nmap::Parser purges everything that has
been parsed by the script to conserve memory and increase speed.

I<See section EXAMPLES for a short tutorial>

I<Note: You cannot have one of the nmap options to be '-oX', '-oN' or '-oG'. Your
program will die if you try and pass any of these options because it decides the
type of output nmap will generate. The IP addresses can be nmap-formatted
addresses see nmap(1)>

If you get an error or your program dies due to parsing, please check that the
xml information is compliant. If you are using parsescan() or an open filehandle
, make sure that the nmap scan that you are performing is successful in returning
xml information. (Sometimes using loopback addresses causes nmap to fail).

=item B<cache_scan($filename)>

This function allows you to save the output of a parsescan() (or nmap scan) to the disk. $filename
is the name of the file you wish to save the nmap scan information to. It defaults to nmap-parser-cache.xml
It returns the name of the file to be used as the cache.

 #Must be called before parsescan().
 $np->cache_scan($filename); #output set to nmap-parser-cache.xml

 #.. do other stuff to prepare for parsescan(), ex. setup callbacks

 $np->parsescan('/usr/bin/nmap',$args,@IPS);

=item B<purge()>

Cleans the xml scan data from memory. This is useful if you have a program where
you are parsing lots of nmap scan data files with persistent variables.

=item B<callback(\&code_ref)>

Sets the parsing mode to be done using the callback function. It takes the parameter
of a code reference or a reference to a function. If no code reference is given,
it resets the mode to normal (no callback).

 $np->callback(\&my_function); #sets callback, my_function() will be called
 $np->callback(); #resets it, no callback function called. Back to normal.


=item B<get_session()>

Obtains the Nmap::Parser::Session object which contains the session scan information.

=item B<get_host($ip_addr)>

Obtains the Nmap::Parser::Host object for the given $ip_addr.

=item B<del_host($ip_addr)>

Deletes the stored Nmap::Parser::Host object whose IP is $ip_addr.

=item B<all_hosts()>

=item B<all_hosts($status)>

Returns an array of all the Nmap::Parser::Host objects for the scan. If the optional
status is given, it will only return those hosts that match that status. The status
can be any of the following: C<(up|down|unknown|skipped)>

=item B<get_ips()>

=item B<get_ips($status)>

Returns the list of IP addresses that were scanned in this nmap session. They are
sorted using addr_sort. If the optional status is given, it will only return
those IP addresses that match that status. The status can be any of the
following: C<(up|down|unknown|skipped)>

=item B<addr_sort(@ips)>

This function takes a list of IP addresses and returns the correctly sorted
version of the list.

=back

=head2 Nmap::Parser::Session

This object contains the scan session information of the nmap scan.


=over 4


=item B<finish_time()>

Returns the numeric time that the nmap scan finished.

=item B<nmap_version()>

Returns the version of nmap used for the scan.

=item B<numservices()>

=item B<numservices($type)>

If numservices is called without argument, it returns the total number of services
that were scanned for all types. If $type is given, it returns the number of services
for that given scan type. See scan_types() for more info.

=item B<scan_args()>

Returns a string which contains the nmap executed command line used to run the
scan.

=item B<scan_type_proto($type)>

Returns the protocol type of the given scan type (provided by $type). See scan_types() for
more info.

=item B<scan_types()>

Returns the list of scan types that were performed. It can be any of the following:
C<(syn|ack|bounce|connect|null|xmas|window|maimon|fin|udp|ipproto)>.

=item B<start_str()>

Returns the human readable format of the start time.

=item B<start_time()>

Returns the numeric form of the time the nmap scan started.

=item B<time_str()>

Returns the human readable format of the finish time.

=item B<xml_version()>

Returns the version of nmap xml file.

=item B<prescripts()>

=item B<prescripts($name)>

A basic call to prescripts() returns a list of the names of the NSE scripts
run in the pre-scanning phase. If C<$name> is given, it returns the text output of the
a reference to a hash with "output" and "contents" keys for the
script with that name, or undef if that script was not run.
The value of the "output" key is the text output of the script. The value of the
"contents" key is a data structure based on the XML output of the NSE script.

=item B<postscripts()>

=item B<postscripts($name)>

A basic call to postscripts() returns a list of the names of the NSE scripts
run in the post-scaning phase. If C<$name> is given, it returns the text output of the
a reference to a hash with "output" and "contents" keys for the
script with that name, or undef if that script was not run.
The value of the "output" key is the text output of the script. The value of the
"contents" key is a data structure based on the XML output of the NSE script.

=back

=head2 Nmap::Parser::Host

This object represents the information collected from a scanned host.


=over 4

=item B<status()>

Returns the state of the host. It is usually one of these
C<(up|down|unknown|skipped)>.

=item B<addr()>

Returns the main IP address of the host. This is usually the IPv4 address. If
there is no IPv4 address, the IPv6 is returned (hopefully there is one).

=item B<addrtype()>

Returns the address type of the address given by addr() .

=item B<all_hostnames()>

Returns a list of all hostnames found for the given host.

=item B<extraports_count()>

Returns the number of extraports found.

=item B<extraports_state()>

Returns the state of all the extraports found.

=item B<hostname()>

=item B<hostname($index)>

As a basic call, hostname() returns the first hostname obtained for the given
host. If there exists more than one hostname, you can provide a number, which
is used as the location in the array. The index starts at 0;

 #in the case that there are only 2 hostnames
 hostname() eq hostname(0);
 hostname(1); #second hostname found
 hostname(400) eq hostname(1) #nothing at 400; return the name at the last index


=item B<ipv4_addr()>

Explicitly return the IPv4 address.

=item B<ipv6_addr()>

Explicitly return the IPv6 address.

=item B<mac_addr()>

Explicitly return the MAC address.

=item B<mac_vendor()>

Return the vendor information of the MAC.

=item B<distance()>

Return the distance (in hops) of the target machine from the machine that performed the scan.

=item B<trace_error()>

Returns a true value (usually a meaningful error message) if the traceroute was
performed but could not reach the destination. In this case C<all_trace_hops()>
contains only the part of the path that could be determined.

=item B<all_trace_hops()>

Returns an array of Nmap::Parser::Host::TraceHop objects representing the path
to the target host. This array may be empty if Nmap did not perform the
traceroute for some reason (same network, for example).

Some hops may be missing if Nmap could not figure out information about them.
In this case there is a gap between the C<ttl()> values of consecutive returned
hops. See also C<trace_error()>.

=item B<trace_proto()>

Returns the name of the protocol used to perform the traceroute.

=item B<trace_port()>

Returns the port used to perform the traceroute.

=item B<os_sig()>

Returns an Nmap::Parser::Host::OS object that can be used to obtain all the
Operating System signature (fingerprint) information. See Nmap::Parser::Host::OS
for more details.

 $os = $host->os_sig;
 $os->name;
 $os->osfamily;

=item B<tcpsequence_class()>

=item B<tcpsequence_index()>

=item B<tcpsequence_values()>

Returns the class, index and values information respectively of the tcp sequence.

=item B<ipidsequence_class()>

=item B<ipidsequence_values()>

Returns the class and values information respectively of the ipid sequence.

=item B<tcptssequence_class()>

=item B<tcptssequence_values()>

Returns the class and values information respectively of the tcpts sequence.

=item B<uptime_lastboot()>

Returns the human readable format of the timestamp of when the host had last
rebooted.

=item B<uptime_seconds()>

Returns the number of seconds that have passed since the host's last boot from
when the scan was performed.

=item B<hostscripts()>

=item B<hostscripts($name)>

A basic call to hostscripts() returns a list of the names of the host scripts
run. If C<$name> is given, it returns the text output of the
a reference to a hash with "output" and "contents" keys for the
script with that name, or undef if that script was not run.
The value of the "output" key is the text output of the script. The value of the
"contents" key is a data structure based on the XML output of the NSE script.

=item B<tcp_ports()>

=item B<udp_ports()>

Returns the sorted list of TCP|UDP ports respectively that were scanned on this host. Optionally
a string argument can be given to these functions to filter the list.

 $host->tcp_ports('open') #returns all only 'open' ports (even 'open|filtered')
 $host->udp_ports('open|filtered'); #matches exactly ports with 'open|filtered'

I<Note that if a port state is set to 'open|filtered' (or any combination), it will
be counted as an 'open' port as well as a 'filtered' one.>

=item B<tcp_port_count()>

=item B<udp_port_count()>

Returns the total of TCP|UDP ports scanned respectively.

=item B<tcp_port_state_ttl()>

Returns the 'reason_ttl' value present in nmap xml result.

=item B<tcp_del_ports($portid, [$portid, ...])>

=item B<udp_del_ports($portid, [ $portid, ...])>

Deletes the current $portid from the list of ports for given protocol.

=item B<tcp_port_state($portid)>

=item B<udp_port_state($portid)>

Returns the state of the given port, provided by the port number in $portid.

=item B<tcp_open_ports()>

=item B<udp_open_ports()>

Returns the list of open TCP|UDP ports respectively. Note that if a port state is
for example, 'open|filtered', it will appear on this list as well.

=item B<tcp_filtered_ports()>

=item B<udp_filtered_ports()>

Returns the list of filtered TCP|UDP ports respectively. Note that if a port state is
for example, 'open|filtered', it will appear on this list as well.

=item B<tcp_closed_ports()>

=item B<udp_closed_ports()>

Returns the list of closed TCP|UDP ports respectively. Note that if a port state is
for example, 'closed|filtered', it will appear on this list as well.

=item B<tcp_service($portid)>

=item B<udp_service($portid)>

Returns the Nmap::Parser::Host::Service object of a given service running on port,
provided by $portid. See Nmap::Parser::Host::Service for more info.

 $svc = $host->tcp_service(80);
 $svc->name;
 $svc->proto;


=back

=head3 Nmap::Parser::Host::Service

This object represents the service running on a given port in a given host. This
object is obtained by using the tcp_service($portid) or udp_service($portid) method from the
Nmap::Parser::Host object. If a portid is given that does not exist on the given
host, these functions will still return an object (so your script doesn't die).
Its good to use tcp_ports() or udp_ports() to see what ports were collected.

=over 4


=item B<confidence()>

Returns the confidence level in service detection.

=item B<extrainfo()>

Returns any additional information nmap knows about the service.

=item B<method()>

Returns the detection method.

=item B<name()>

Returns the service name.

=item B<owner()>

Returns the process owner of the given service. (If available)

=item B<port()>

Returns the port number where the service is running on.

=item B<product()>

Returns the product information of the service.

=item B<proto()>

Returns the protocol type of the service.

=item B<rpcnum()>

Returns the RPC number.

=item B<tunnel()>

Returns the tunnel value. (If available)

=item B<fingerprint()>

Returns the service fingerprint. (If available)

=item B<version()>

Returns the version of the given product of the running service.

=item B<scripts()>

=item B<scripts($name)>

A basic call to scripts() returns a list of the names of the NSE scripts
run for this port. If C<$name> is given, it returns
a reference to a hash with "output" and "contents" keys for the
script with that name, or undef if that script was not run.
The value of the "output" key is the text output of the script. The value of the
"contents" key is a data structure based on the XML output of the NSE script.

=back

=head3 Nmap::Parser::Host::OS

This object represents the Operating System signature (fingerprint) information
of the given host. This object is obtained from an Nmap::Parser::Host object
using the C<os_sig()> method. One important thing to note is that the order of OS
names and classes are sorted by B<DECREASING ACCURACY>. This is more important than
alphabetical ordering. Therefore, a basic call
to any of these functions will return the record with the highest accuracy.
(Which is probably the one you want anyways).

=over 4

=item B<all_names()>

Returns the list of all the guessed OS names for the given host.

=item B<class_accuracy()>

=item B<class_accuracy($index)>

A basic call to class_accuracy() returns the osclass accuracy of the first record.
If C<$index> is given, it returns the osclass accuracy for the given record. The
index starts at 0.

=item B<class_count()>

Returns the total number of OS class records obtained from the nmap scan.

=item B<name()>

=item B<name($index)>

=item B<names()>

=item B<names($index)>

A basic call to name() returns the OS name of the first record which is the name
with the highest accuracy. If C<$index> is given, it returns the name for the given record. The
index starts at 0.

=item B<name_accuracy()>

=item B<name_accuracy($index)>

A basic call to name_accuracy() returns the OS name accuracy of the first record. If C<$index> is given, it returns the name for the given record. The
index starts at 0.

=item B<name_count()>

Returns the total number of OS names (records) for the given host.

=item B<osfamily()>

=item B<osfamily($index)>

A basic call to osfamily() returns the OS family information of the first record.
If C<$index> is given, it returns the OS family information for the given record. The
index starts at 0.

=item B<osgen()>

=item B<osgen($index)>

A basic call to osgen() returns the OS generation information of the first record.
If C<$index> is given, it returns the OS generation information for the given record. The
index starts at 0.

=item B<portused_closed()>

Returns the closed port number used to help identify the OS signatures. This might not
be available for all hosts.

=item B<portused_open()>

Returns the open port number used to help identify the OS signatures. This might
not be available for all hosts.

=item B<os_fingerprint()>

Returns the OS fingerprint used to help identify the OS signatures. This might not be available for all hosts.

=item B<type()>

=item B<type($index)>

A basic call to type() returns the OS type information of the first record.
If C<$index> is given, it returns the OS type information for the given record. The
index starts at 0.

=item B<vendor()>

=item B<vendor($index)>

A basic call to vendor() returns the OS vendor information of the first record.
If C<$index> is given, it returns the OS vendor information for the given record. The
index starts at 0.

=back

=head3 Nmap::Parser::Host::TraceHop

This object represents a router on the IP path towards the destination or the
destination itself. This is similar to what the C<traceroute> command outputs.

Nmap::Parser::Host::TraceHop objects are obtained through the
C<all_trace_hops()> and C<trace_hop()> Nmap::Parser::Host methods.

=over 4

=item B<ttl()>

The Time To Live is the network distance of this hop.

=item B<rtt()>

The Round Trip Time is roughly equivalent to the "ping" time towards this hop.
It is not always available (in which case it will be undef).

=item B<ipaddr()>

The known IP address of this hop.

=item B<host()>

The host name of this hop, if known.

=back

=head1 EXAMPLES

I think some of us best learn from examples. These are a couple of examples to help
create custom security audit tools using some of the nice features
of the Nmap::Parser module. Hopefully this can double as a tutorial.
More tutorials (articles) can be found at L<https://github.com/modernistik/Nmap-Parser>

=head2 Real-Time Scanning

You can run a nmap scan and have the parser parse the information automagically.
The only constraint is that you cannot use '-oX', '-oN', or '-oG' as one of your
arguments for nmap command line parameters passed to parsescan().

 use Nmap::Parser;

 my $np = new Nmap::Parser;
 my @hosts = @ARGV; #get hosts from cmd line

 #runs the nmap command with hosts and parses it automagically
 $np->parsescan('/usr/bin/nmap','-sS O -p 1-1023',@hosts);

 for my $host ($np->all_hosts()){
 	print $host->hostname."\n";
	#do mor stuff...
 }

If you would like to run the scan using parsescan() but also save the scan xml output,
you can use cache_scan(). You must call cache_scan() BEFORE you initiate the parsescan() method.

 use Nmap::Parser;
 my $np = new Nmap::Parser;

 #telling np to save output
 $np->cache_scan('nmap.localhost.xml');
 $np->parsescan('/usr/bin/nmap','-F','localhost');
 #do other stuff...

=head2 Callbacks

This is probably the easiest way to write a script with using Nmap::Parser,
if you don't need the general scan session information. During the parsing
process, the parser will obtain information of every host. The
callback function (in this case 'booyah()')  is called after the parsing of
every host (sequentially). When the callback returns, the parser will delete all
information of the host it had sent to the callback. This callback function is
called for every host that the parser encounters. I<The callback function must be
setup before parsing>

 use Nmap::Parser;
 my $np = new Nmap::Parser;


 $np->callback( \&booyah );

 $np->parsefile('nmap_results.xml');
    # or use parsescan()

 sub booyah {
    my $host = shift; #Nmap::Parser::Host object, just parsed
    print 'IP: ',$host->addr,"\n";
	 # ... do more stuff with $host ...

    #when it returns, host object will be deleted from memory
    #(good for processing VERY LARGE files or scans)
 }


=head2 Multiple Instances - (C<no less 'of'; my $self>)

Using multiple instances of Nmap::Parser is extremely useful in helping
audit/monitor the network B<P>olicy (ohh noo! its that 'P' word!).
In this example, we have a set of hosts that had been scanned previously for tcp
services where the image was saved in I<base_image.xml>. We now will scan the
same hosts, and compare if any new tcp have been open since then
(good way to look for suspicious new services). Easy security B<C>ompliance detection.
(ooh noo! The 'C' word too!).


 use Nmap::Parser;
 use vars qw($nmap_exe $nmap_args @ips);
 my $base = new Nmap::Parser;
 my $curr = new Nmap::Parser;


 $base->parsefile('base_image.xml'); #load previous state
 $curr->parsescan($nmap_exe, $nmap_args, @ips); #scan current hosts

 for my $ip ($curr->get_ips )
 {
 	#assume that IPs in base == IPs in curr scan
 	my $ip_base = $base->get_host($ip);
 	my $ip_curr = $curr->get_host($ip);
 	my %port = ();

 	#find ports that are open that were not open before
 	#by finding the difference in port lists
	my @diff =  grep { $port{$_} < 2}
		   (map {$port{$_}++; $_}
		   ( $ip_curr->tcp_open_ports , $ip_base->tcp_open_ports ));

	print "$ip has these new ports open: ".join(',',@diff) if(scalar @diff);

	for (@diff){print "$_ seems to be ",$ip_curr->tcp_service($_)->name,"\n";}

 }


=head1 SUPPORT

=head2 Discussion Forum

If you have questions about how to use the module, or any of its features, you
can post messages to the Nmap::Parser module forum on CPAN::Forum.
L<https://github.com/modernistik/Nmap-Parser/issues>

=head2 Bug Reports, Enhancements, Merge Requests

Please submit any bugs or feature requests to:
L<https://github.com/modernistik/Nmap-Parser/issues>

B<Please make sure that you submit the xml-output file of the scan which you are having
trouble with.> This can be done by running your scan with the I<-oX filename.xml> nmap switch.
Please remove any important IP addresses for security reasons. It saves time in reproducing issues.

=head1 SEE ALSO

 nmap, XML::Twig

The Nmap::Parser page can be found at: L<https://github.com/modernistik/Nmap-Parser>.
It contains the latest developments on the module. The nmap security scanner
homepage can be found at: L<http://www.insecure.org/nmap/>.

=head1 AUTHORS

Origiinal author, Anthony Persaud L<https://www.modernistik.com>. However, special thanks to: Daniel Miller L<https://github.com/bonsaiviking> and Robin Bowes L<http://robinbowes.com>.
Please see Changes.md file for a list of other great contributors.

=head1 COPYRIGHT
Copyright (c) <2003-2017> <Anthony Persaud> L<https://www.modernistik.com>

MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

=cut