Nmap-Parser-1.05/0040700000175300010010000000000010277405243013074 5ustar ironstarNoneNmap-Parser-1.05/Changes0100700000175300010010000002734110277315147014401 0ustar ironstarNoneRevision history for Perl extension Nmap::Parser. Latest version: http://sourceforge.net/projects/npx http://search.cpan.org/~apersaud/Nmap-Parser/ Website: http://www.nmapparser.com Changes for 1.05 - Major speed improvements (less compile time) - Major reduction in unwanted memory usage - Redundant functions (or less used functions) are now created dynamically. (AUTOLOAD) - Documentation fixes Changes for 1.00 - To see the changes, please read over the new documentation - Internal code is much (MUCH) cleaner and readable - removed 'ducttape' fixes and made stable & roubust changes - improved performance, removed unwanted code (legacy) - complete overhaul of internal code - new Framework - support for IPv6 addresses - data overwrite (overflow) protection - better support for multiple instances - fixed some minor bugs - process owner information obtained - all OS accuracy information obtained - some functions now take new parameters (more concise) - some functions renamed for clarity - new shortcut functions (for doing repetitive tasks easier) - Removed parsing filters (finally) - All indexes now start at 0 (not at 1). - Removed internal OS generic matching function since this is given by nmap now in the osclass tags - Removed the use of constants for indexes - Nmap::Parser::Host::Service object provides OO interface to service information for a given port - Nmap::Parser::Host::OS object provides OO interface to OS signature information for a given host - Nmap::Parser::Session replaces old Nmap::Parser::ScanInfo package - Nmap2SQLite security script included - removed old security tools - rewrote scan.pl (from scanhost.pl) - rewrote old tools to fit new framework - Fully updated documentation Changes for 0.80 - Support for multiple instances of Nmap::Parser objects without overwriting data - All data (except filters) is are localized per object - The use of Storable (dclone) to correctly make duplicate of data structured - When filters are used to skip portinfo, all ports return state of 'closed'. - Nmap::Parser::XML no longer supported in distribution (you should change all calls to Nmap::Parser::XML to Nmap::Parser) Changes for 0.79 - fixed ports that were declared as 'open|filtered' these now are counted as both 'open' and 'filtered' when using tcp_ports() and udp_ports(). - sent a patch for XML::Twig in order to fix. It is now released in XML:Twig 3.16 - added start_str() and time_str() : they return the human readable format of the scan start time and scan finish time (respectively). - updated for Nmap 3.81 - documentation changes Changes for 0.78 - updated documentation - now included tcp/udp service product - added new methods for new nmap command switch (-A) mac_addr, mac_vendor, ipv4_addr - verified xml format is still valid for nmap 3.55 Changes for 0.77 - updated documentation - added patches from Jeremy S. - tcp_service and udp_service tunnel, accuracy, confidence - os_accuracy method implemented - added ident/owner information Changes for 0.76 - new module name: Nmap::Parser - leagcy file still ok to use for now: Nmap::Parser::XML - fixed problem using 'our' with older versions of perl - updated requirement for oldest usable version of XML::Twig => 3.11 - you can extract owner information from running -I scanning tcp_service_owner and udp_service_owner Changes for 0.74 - fixed ip address input bug - updated example scripts - fixed nmap not found bug - updated authorship informatin - raised verbose level to 2 in example scripts (help pages) - test script 4_scanner does not test. If nmap not installed it skips all tests. - updated tests - some example scripts read IP addresses from file - placed sourceforge image link on documentation - status_check is now called sweep - sweep.pl outputs active IP's to a file with a new command line switch - scan_host.pl is renamed to scanhost.pl - get_host_list,filter_by_osfamily, filter_by_status returns IP addresses in sorted IP order. ( uses sort_ips() ) - sort_ips is a new function which will take a series of IPs and sort them correctly by comparing each quad in the address to each other. - example scripts use --randomize_hosts to be more stealthy - updated information on some example scripts because they require nmap 3.50+ for the version scanning. - updated parser tests, to check for sorted ip order Changes for 0.73 - removed safe_* functions and placed them in the actual parsing functions. (I don't think they were never used. - updated BUG REPORT information Changes for 0.72 - removed IGNORE_ADDPORTS constant - added contribution from Sebastian: nmap2csv. - edited the links to the sourceforge project site. - added parsescan() function to peroform quick nmap scans and parsing. - added more documentation - fixed some example scripts - added more tests for the new functionality Changes for 0.71 - fixed a small bug in the installation under MSWin32 (PM_FILTER) which caused all tests to fail. (It was removing things that weren't comments. Changes for 0.70 - updated changes from 0.69 - updated documentation - fixed documentation bug of all the example scripts - updated examples script: they are more robust. Can either take the example file as input, or actually run scans. Changes for 0.69 - new utility script : scan_host.pl - added EXAMPLES seciton in documentation - parses new 'version', 'extrainfo', and 'product' att from service tag (3.40+) - added *_service_version to *::Host - added xml_version to *::ScanInfo - more error prevention mechanisms - added os_osfamily, os_gen, os_vendor, os_type added - added OSINFO filter - ::ScanInfo::scan_types does not return number of scan types in scalar format. It will always return an array containing the scan types. - osfamily does not return the actual string (comma delimited), it always returns an array of os matches. - DEPRECATED: tcpsequence, ipidsequence, tcptssequence now use: tcpsequence_class, tcpsequence_values, tcpsequence_index ipidsequence_class, ipidsequence_values tcptssequence_class, tcptssequence_values Changes for 0.68 - Licensing changes, now under GPL - added signatures for wireless access points (wap) - added os_match shortcut function - Problem with Makefile.PL, didn't pass correct dependencies. - tcp_port_state() and udp_port_state() return the state of the port when passed a port number. - Sorted port order when using tcp_ports and udp_ports - extraports tag parsing. It is also set up as a filter 'extraports' filtering. Added extraports_state and extraports_count to Nmap::Parser::Host class. - Added and fix some documentation - tcp_ports and udp_ports can take a parameter to filter what port list you wish to receive. It selects states based on port content state tag: filtered, closed, or open - previous versions (0.64 or earlier) of the parser, no arguments to tcp_ports and udp_ports would return the whole hashref of all the ports, this is now deprecated. Use the newly created functions tcp_service_name, tcp_service_proto, tcp_service_rpcnum, udp_service_name, udp_service_proto, and udp_service_rpcnum. - changed default filter for solaris to include 'sun' and not 'sunos' - more example scripts - no more wantarray usage for tcp_ports and udp_ports - more test cases Changes for 0.66 - added short-cut function hostname() to return first hostname - added preliminary callback functionality (for registering events). This includes register_host_callback, and reset_host_callback - tcp_ports and udp_ports do not return hashref of all ports, only if passed a port number as an argument.The argument must be a port number. They default to returning an array of port numbers. - added short-cuts tcp_ports_count and udp_ports_count functions - added tcp_service_proto and udp_service_proto - added tcp_service_rpcnum and udp_service_rpcnum - POD fixes. - speed improvements Changes for 0.64 - nmaprun filter bug fixed - important documentation changes Changes for 0.63 - added vendor to os_class - fixed division by zero on one of the efficiency test. - it now checks to make sure Time::HiRes is installed before performing tests. - minor warning problems removed on Win32 systems. Changes for 0.62 - stable release with all new changes. Changes for 0.6_4 - changes to parse filter tags. All previously called PARSE_* have the PARSE_ removed from them. Ex: PARSE_OSFAMILY is now OSFAMILY. - osclass tag added. - a bug found with the sequences is fixed - making use of ignore_elts to save when creating objects - parse_filters completly excludes tags that you decide not to parse. Much faster parsing and memory usage efficiency. efficiency.t tests this benchmark to make sure that the twig parser does not do any work it doesn't have to. - permanently excluding some static tags using ignore_elts. - added SCANINFO filter. Changes for 0.60_3 - os_port_used, now can return the open or closed port used in OS detection depending on the given parameter. Changes for 0.60_2 - Bug #2968: fixed bogus 'use 5.008' in Makefile.PL (runs on 5.6 also) instead using 5.004 fixed minor warnings when compiling with -w added 'use warnings' to _methods test Changes for 0.60_1 - fixed a bug with the test script (finding test file) - made a separate test to test the actual method existance - portability when running the tests using File::Spec. Changed for 0.60 - better memory management using twig_roots - some bugs with output types and filters - generic_os and all references are now refereed to as 'osfamily' I thought it better resembles what it stands for. - fixed some documentation problems - parse_filter_* have been replaced with parse_filters(), which can enable multiple different filters through a hashref. Filters available: ONLY_ACTIVE, PARSE_OSFAMILY, PARSE_UPTIME, PARSE_PORTINFO, PARSE_SEQUENCES - added parse information of tcpsequence, ipidsequence, tcptssequence - additions to Nmap::Parser::Host methods tcpsequence, ipidsequence, tcptssequence Changes for 0.50 - faster loading module - added more documentation - minor speed improvements - added methods to Nmap::Parser parse_filter_generic_os($bool) (see doc) - renamed only_active() to parse_filter_status($bool) (see doc) - Nmap::Parser::Host changed hostnames() to take a value a number (see doc) changed os_matches() to take a value a number (see doc) Changes for 0.40 - added new package called ScanInfo (Nmap::Parser::ScanInfo this contains methods that make it easier to access the scan information - added new package called Host (Nmap::Parser::Host), which makes it easier to access values for each of the hosts found. See documentation. Host trees are now full of these *::Host objects. - fixed minor bugs with parsing the xml files. - some memory usage improvments. COPYRIGHT AND LICENCE Copyright (C) 2003-2005 Anthony G Persaud http://www.opensource.org/licenses/gpl-license.php This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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.Nmap-Parser-1.05/LICENSE0100700000175300010010000004506507770241351014115 0ustar ironstarNone GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. http://www.opensource.org/licenses/gpl-license.php Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement. These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse -clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. Nmap-Parser-1.05/Makefile.PL0100700000175300010010000000112110257307741015043 0ustar ironstarNoneuse 5.004; use ExtUtils::MakeMaker; # See lib/ExtUtils/MakeMaker.pm for details of how to influence # the contents of the Makefile that is written. my %depends = (XML::Twig => 3.16, Storable => 2); WriteMakefile( ABSTRACT => 'parse nmap scan data with perl', AUTHOR => 'Anthony G Persaud (apersaud@gmail.com)', clean => {FILES => "*.tar *.old pod2htm* *.htm*"}, #EXE_FILES => [ map {"tools/$_"} @programs], #soon NAME => 'Nmap::Parser', PREREQ_PM => \%depends, VERSION_FROM => 'Parser.pm' # finds $VERSION ); Nmap-Parser-1.05/MANIFEST0100700000175300010010000000064310277314747014240 0ustar ironstarNoneChanges Read for changes LICENSE GPL Makefile.PL MANIFEST This list of files Parser.pm Core parser README You should read it t/callback.t t/instance.t t/instance.xml t/nmap_results.xml t/parser.t t/scanner.t tools/nmap2sqlite.pl Nmap scans to a DBI (SQLite) database tools/scan.pl Scan a set of hosts with Nmap-Parser META.yml Module meta-data (added by MakeMaker) Nmap-Parser-1.05/META.yml0100700000175300010010000000060210277405243014343 0ustar ironstarNone# http://module-build.sourceforge.net/META-spec.html #XXXXXXX This is a prototype!!! It will change in the future!!! XXXXX# name: Nmap-Parser version: 1.05 version_from: Parser.pm installdirs: site requires: Storable: 2 XML::Twig: 3.16 distribution_type: module generated_by: ExtUtils::MakeMaker version 6.17 Nmap-Parser-1.05/Parser.pm0100700000175300010010000012011110277405137014664 0ustar ironstarNonepackage Nmap::Parser; use strict; use XML::Twig; use Storable qw(dclone); use vars qw($VERSION %D); $VERSION = 1.05; #---------------------------------------- # NEW - #---------------------------------------- sub new { my ($class,$self) = shift; $class = ref($class) || $class; %{$self->{HOSTS}} = (); %{$self->{SESSION}} = (); $self->{twig} = new XML::Twig( start_tag_handlers => {nmaprun => \&_nmaprun_start_tag_hdlr }, twig_roots => { scaninfo => \&_scaninfo_tag_hdlr, finished => \&_finished_tag_hdlr, host => \&_host_tag_hdlr }, ignore_elts => { addport => 1, debugging => 1, verbose => 1, hosts => 1 } ); bless ($self,$class); return $self; } 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}; } ################################################################################ ## PARSE 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 _init { my $self = shift; $D{callback} = $self->{callback}; } sub _clean { my $self = shift; $self->{SESSION} = dclone($D{$$}{SESSION}) if($D{$$}{SESSION}); $self->{HOSTS} = dclone($D{$$}{HOSTS} ) if($D{$$}{HOSTS} ); delete $D{$$}; delete $D{callback}; } sub parse { my $self = shift; $self->_init(); $self->{twig}->safe_parse(@_); if($@){die $@;} $self->_clean(); $self->purge; return $self; } sub parsefile { my $self = shift; $self->_init(); $self->{twig}->safe_parsefile(@_); if($@){die $@;} $self->_clean(); $self->purge; return $self; } 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 = "$nmap $args -v -v -v -oX - ".(join ' ',@ips); open $FH, "$cmd |" || die "[Nmap-Parser] Could not perform nmap scan - $!"; $self->_init(); $self->parse($FH); close $FH; $self->_clean(); $self->purge; return $self; } sub purge { my $self = shift; $self->{twig}->purge; return $self; } sub ipv4_sort { my $self = shift; return (sort { my @ipa = split('\.',$a); my @ipb = split('\.',$b); $ipa[0] <=> $ipb[0] || $ipa[1] <=> $ipb[1] || $ipa[2] <=> $ipb[2] || $ipa[3] <=> $ipb[3] } @_); } #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->ipv4_sort(keys %{$self->{HOSTS}}) if($status eq ''); my @hosts = grep {$self->{HOSTS}{$_}{status} eq $status} (keys %{$self->{HOSTS}}); return $self->ipv4_sort(@hosts); } ################################################################################ ## Parsing Tag Handlers ## ################################################################################ sub _nmaprun_start_tag_hdlr { my ($twig, $tag) = @_; $D{$$}{SESSION}{start_time} = $tag->{att}->{start}; $D{$$}{SESSION}{nmap_version}= $tag->{att}->{version}; $D{$$}{SESSION}{start_str} = $tag->{att}->{startstr}; $D{$$}{SESSION}{xml_version} = $tag->{att}->{xmloutputversion}; $D{$$}{SESSION}{scan_args} = $tag->{att}->{args}; $D{$$}{SESSION} = Nmap::Parser::Session->new($D{$$}{SESSION}); $twig->purge; } sub _scaninfo_tag_hdlr { my ($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 $D{$$}{SESSION}{type}{$type} = $proto; $D{$$}{SESSION}{numservices}{$type} = $numservices; } $twig->purge; } sub _finished_tag_hdlr { my ($twig, $tag) = @_; $D{$$}{SESSION}{finish_time} = $tag->{att}->{time}; $D{$$}{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 ($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 $D{$$}{HOSTS}{$id}{addrs} = $addr_hashref; return undef unless(defined($id) || $id ne ''); #GET HOSTNAMES $D{$$}{HOSTS}{$id}{hostnames} = __host_hostnames_tag_hdlr($tag); #GET STATUS $D{$$}{HOSTS}{$id}{status} = $tag->first_child('status')->{att}->{state}; #CONTINUE PROCESSING IF STATUS IS UP - OTHERWISE NO MORE XML if(lc($D{$$}{HOSTS}{$id}{status}) eq 'up'){ $D{$$}{HOSTS}{$id}{ports} = __host_port_tag_hdlr($tag); $D{$$}{HOSTS}{$id}{os} = __host_os_tag_hdlr($tag); $D{$$}{HOSTS}{$id}{uptime} = __host_uptime_tag_hdlr($tag); $D{$$}{HOSTS}{$id}{tcpsequence} = __host_tcpsequence_tag_hdlr($tag); $D{$$}{HOSTS}{$id}{ipidsequence} = __host_ipidsequence_tag_hdlr($tag); $D{$$}{HOSTS}{$id}{tcptssequence} = __host_tcptssequence_tag_hdlr($tag); } #CREATE HOST OBJECT FOR USER $D{$$}{HOSTS}{$id} = Nmap::Parser::Host->new($D{$$}{HOSTS}{$id}); if($D{callback}{is_registered}){ &{$D{callback}{coderef}}($D{$$}{HOSTS}{$id}); delete $D{$$}{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 ''); #GET SERVICE INFORMATION $port_hashref->{$proto}{$portid}{service} = __host_service_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->{extrainfo} = $service->{att}->{extrainfo}; $service_hashref->{proto} = $service->{att}->{proto} || '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}; } return $service_hashref; } sub __host_os_tag_hdlr { my $tag = shift; my $os_tag = $tag->first_child('os'); my $os_hashref; my $portused_tag; 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); #This will go in Nmap::Parser::Host::OS my $osmatch_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++; } $os_hashref->{'osmatch_count'} = $osmatch_index; #parse osclass tags my $osclass_index = 0; 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->{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; } ################################################################################ ## 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;} 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 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 _get_ports { my $self = shift; my $proto = pop; #param might be empty, so this goes first my $state = lc(shift); #open, filtered, closed or any combination my @matched_ports = (); #if $state eq '', then tcp_ports or udp_ports was called for all ports #therefore, only return the keys of all ports found if($state eq ''){return sort {$a <=> $b} (keys %{ $self->{ports}{$proto} }) } #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}; } #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 {return _get_port_state(@_,'tcp');} sub udp_port_state {return _get_port_state(@_,'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); no strict 'refs'; if( ($type eq 'tcp' || $type eq 'udp') && ($val eq 'open' || $val eq 'filtered' || $val eq 'closed') ){ *$AUTOLOAD = sub {return _get_ports($_[0], $val, $type);}; goto &$AUTOLOAD; } elsif(defined $type && defined $val) { *$AUTOLOAD = sub {return $_[0]->{$type}{$val}}; goto &$AUTOLOAD; } else {die '[Nmap-Parser] method ->'.$param."() not defined!\n";} } 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; } #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; } 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 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]; } 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 =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. =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 =item B 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 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 returns. =item B This method runs an nmap scan where $nmap is the path to the nmap executable, $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. I I 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 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 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 Obtains the Nmap::Parser::Session object which contains the session scan information. =item B Obtains the Nmap::Parser::Host object for the given $ip_addr. =item B Deletes the stored Nmap::Parser::Host object whose IP is $ip_addr. =item B =item B 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 =item B Returns the list of IP addresses that were scanned in this nmap session. They are sorted using ipv4_sort. If there are IPv6 addresses, or mixed, it might not be in correct sorted order. 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 This function takes a list of IPv4 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 Returns the numeric time that the nmap scan finished. =item B Returns the version of nmap used for the scan. =item B =item B 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 Returns a string which contains the nmap executed command line used to run the scan. =item B Returns the protocol type of the given scan type (provided by $type). See scan_types() for more info. =item B 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 Returns the human readable format of the start time. =item B Returns the numeric form of the time the nmap scan started. =item B Returns the human readable format of the finish time. =item B Returns the version of nmap xml file. =back =head2 Nmap::Parser::Host This object represents the information collected from a scanned host. =over 4 =item B Returns the state of the host. It is usually one of these C<(up|down|unknown|skipped)>. =item B 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 Returns the address type of the address given by addr() . =item B Returns a list of all hostnames found for the given host. =item B Returns the number of extraports found. =item B Returns the state of all the extraports found. =item B =item B 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 Explicitly return the IPv4 address. =item B Explicitly return the IPv6 address. =item B Explicitly return the MAC address. =item B Return the vendor information of the MAC. =item B 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 =item B =item B Returns the class, index and values information respectively of the tcp sequence. =item B =item B Returns the class and values information respectively of the ipid sequence. =item B =item B Returns the class and values information respectively of the tcpts sequence. =item B Returns the human readable format of the timestamp of when the host had last rebooted. =item B Returns the number of seconds that have passed since the host's last boot from when the scan was performed. =item B =item B 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 =item B =item B Returns the total of TCP|UDP ports scanned respectively. =item B =item B Returns the state of the given port, provided by the port number in $portid. =item B =item B 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 =item B 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 =item B 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 =item B 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 Returns the confidence level in service detection. =item B Returns any additional information nmap knows about the service. =item B Returns the detection method. =item B Returns the service name. =item B Returns the process owner of the given service. (If available) =item B Returns the port number where the service is running on. =item B Returns the product information of the service. =item B Returns the protocol type of the service. =item B Returns the RPC number. =item B Returns the tunnel value. (If available) =item B Returns the version of the given product of the running service. =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 method. One important thing to note is that the order of OS names and classes are sorted by B. 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 Returns the list of all the guessed OS names for the given host. =item B =item B 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 Returns the total number of OS class records obtained from the nmap scan. =item B =item B =item B =item B 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 =item B 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 Returns the total number of OS names (records) for the given host. =item B =item B 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 =item B 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 Returns the closed port number used to help identify the OS signatures. This might not be available for all hosts. =item B Returns the open port number used to help identify the OS signatures. This might not be available for all hosts. =item B =item B 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 =item B 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 =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 =head2 Real-Time Scanning - (no better C like C<'now'>) 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... } =head2 Callbacks - (C) 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 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) Using multiple instances of Nmap::Parser is extremely useful in helping audit/monitor the network B

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. 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 Bompliance 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 =head2 Bug Reports Please submit any bugs to: L B 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. =head1 SEE ALSO nmap, XML::Twig The Nmap::Parser page can be found at: L. It contains the latest developments on the module. The nmap security scanner homepage can be found at: L. =head1 AUTHOR Anthony G Persaud L =head1 COPYRIGHT This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. L =cutNmap-Parser-1.05/README0100700000175300010010000000474210277315177013771 0ustar ironstarNoneNmap/Parser version 1.05 ============================ parse nmap scan data with perl 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. INSTALLATION Latest version: http://sourceforge.net/projects/npx http://search.cpan.org/~apersaud/Nmap-Parser/ Website: http://www.nmapparser.com MANUAL INSTALL Download the file and unpack. This is usually done by: tar zxvf Nmap-Parser-x.xx.tar.gz Where x.xx is the version number. Next change into the newly created directory. To install this module type the following: perl Makefile.PL make make test make install If you would like to install Nmap-Parser in a different directory (or if you do not have root access use 'perl Makefile.PL PREFIX=/install/path', where /install/path is the directory in which you want to install the module. Note that you should then use the "use lib '/install/path'" in your scripts. ACTIVESTATE PERL (Perl Package Manager) - MSWin32 Run this in the command prompt: ppm install Nmap-Parser This should contact the ActiveState respository, download the file and install it automagically. DEPENDENCIES This module requires these other modules and libraries: XML::Twig 3.16+ Storable In addition, you will need nmap 3.00+. You don't exactly need it, but this version of nmap supports the xml output that this module can parse. So, you do not really need the executable, but the xml output that you will be parsing (or able to parse), must be from this version onward. FOR CHANGE INFORMATION SEE THE "CHANGES" FILE COPYRIGHT AND LICENCE Copyright (C) 2003-2005 Anthony G Persaud http://www.opensource.org/licenses/gpl-license.php This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. Nmap-Parser-1.05/t/0040700000175300010010000000000010277405243013337 5ustar ironstarNoneNmap-Parser-1.05/t/callback.t0100700000175300010010000000270710255417422015264 0ustar ironstarNone#!/usr/bin/perl use strict; use blib; use File::Spec; use Cwd; use Test::More tests => 15; use Nmap::Parser; use constant TEST_FILE =>'nmap_results.xml'; use constant HOST1 => '127.0.0.1'; use constant HOST2 => '127.0.0.2'; use constant HOST3 => '127.0.0.3'; use constant HOST4 => '127.0.0.4'; use constant TOTAL_ADDRS => 4; use vars qw($FH $TOTAL @UP_HOSTS @DOWN_HOSTS); $FH = File::Spec->catfile(cwd(),'t',TEST_FILE); $FH = File::Spec->catfile(cwd(), TEST_FILE) unless(-e $FH); my $np = new Nmap::Parser; isa_ok($np, 'Nmap::Parser'); ok($np->callback(\&my_callback),'Registering callback function'); is($np->callback(),0,'Unregistering callback function'); ok($np->callback(\&my_callback),'re-registering callback function'); $TOTAL = 0; $np->parsefile($FH); is($TOTAL, TOTAL_ADDRS, 'Making sure all hosts were parsed in callback'); ok(eq_set([@UP_HOSTS], [HOST1,HOST3,HOST4]), 'Testing for correct UP hosts'); ok(eq_set([@DOWN_HOSTS], [HOST2]), 'Testing for correct DOWN hosts'); for my $host (HOST1, HOST2, HOST3, HOST4){ is($np->get_host($host) , undef, 'Making sure '.$host.' does not exists'); } sub my_callback { my $host = shift; my $addr = $host->addr; if($addr =~ /^127\.0\.0/){ $TOTAL++; } isa_ok($host,'Nmap::Parser::Host',$host->addr); if( $host->status eq 'up'){push @UP_HOSTS, $addr;} elsif($host->status eq 'down'){push @DOWN_HOSTS, $addr;} }Nmap-Parser-1.05/t/instance.t0100700000175300010010000000356410255417422015336 0ustar ironstarNone#!/usr/bin/perl use strict; use blib; use File::Spec; use Cwd; use Test::More tests => 12; use Nmap::Parser; use constant HOST1 => '127.0.0.1'; use constant HOST2 => '127.0.0.2'; use constant HOST3 => '127.0.0.3'; use constant HOST4 => '127.0.0.4'; use constant BASE_FILE =>'instance.xml'; use constant CURR_FILE =>'nmap_results.xml'; use vars qw($base $curr $BASE $CURR); $BASE = File::Spec->catfile(cwd(),'t',BASE_FILE); $BASE = File::Spec->catfile(cwd(), BASE_FILE) unless(-e $BASE); $CURR = File::Spec->catfile(cwd(),'t',CURR_FILE); $CURR = File::Spec->catfile(cwd(), CURR_FILE) unless(-e $CURR); $curr = new Nmap::Parser; $base = new Nmap::Parser; isa_ok($curr, 'Nmap::Parser'); isa_ok($base, 'Nmap::Parser'); ok($base->parsefile($BASE),'Parsing from nmap data base image file'); ok($curr->parsefile($CURR),'Parsing from nmap data current image file'); my $host_curr = $curr->get_host(HOST3); my $host_base = $base->get_host(HOST3); isa_ok($host_curr,'Nmap::Parser::Host','host_curr'); isa_ok($host_base,'Nmap::Parser::Host','host_base'); cmp_ok($host_curr->tcp_port_count,'!=',$host_base->tcp_port_count, 'Object instance difference: TCP COUNT'); cmp_ok($host_curr->udp_port_count,'!=',$host_base->udp_port_count, 'Object instance difference: UDP COUNT'); my %port = (); my @diff_open = grep { $port{$_} < 2} (map {$port{$_}++; $_} ($host_curr->tcp_open_ports, $host_base->tcp_open_ports)); is(scalar @diff_open, 2, "Open port difference: ".(join '',@diff_open)); my @diff_filtered = grep { $port{$_} < 2} (map {$port{$_}++; $_} ($host_curr->tcp_filtered_ports, $host_base->tcp_filtered_ports)); is(scalar @diff_filtered, 1, "Filtered port difference: ".(join '',@diff_filtered)); is($base->get_host(HOST2),undef, 'Base image should not have '.HOST2); isnt($curr->get_host(HOST2),undef,'Current image should have '.HOST2); Nmap-Parser-1.05/t/instance.xml0100700000175300010010000000513410255417422015666 0ustar ironstarNone

Nmap-Parser-1.05/t/nmap_results.xml0100700000175300010010000001565610255417422016610 0ustar ironstarNone
Nmap-Parser-1.05/t/parser.t0100700000175300010010000002612110255417332015020 0ustar ironstarNone#!/usr/bin/perl use strict; use blib; use Nmap::Parser; use File::Spec; use Cwd; use Test::More tests => 141; use constant HOST1 => '127.0.0.1'; use constant HOST2 => '127.0.0.2'; use constant HOST3 => '127.0.0.3'; use constant HOST4 => '127.0.0.4'; my @UP_HOSTS = (HOST1, HOST3, HOST4); my @DOWN_HOSTS = (HOST2); use constant TOTAL_HOSTS => 4; use constant TEST_FILE =>'nmap_results.xml'; use vars qw($host $np $session $svc $os $FH); $FH = File::Spec->catfile(cwd(),'t',TEST_FILE); $FH = File::Spec->catfile(cwd(), TEST_FILE) unless(-e $FH); my $np = new Nmap::Parser; parser_test(); session_test(); host_1(); host_2(); host_3(); host_4(); sub parser_test { ok($np->parsefile($FH),"Parsing nmap data: $FH"); #TESTING GET_IPS() is_deeply([$np->get_ips()],[HOST1, HOST2, HOST3, HOST4], 'Testing get_ips for correct number of hosts'); is_deeply([$np->get_ips('up')],[HOST1,HOST3, HOST4], 'Testing get_ips for correct hosts with status = up'); is_deeply([$np->get_ips('down')],[HOST2], 'Testing get_ips for correct hosts for with status = down'); #TESTING IPV4_SORT my @hosts = (HOST3, HOST1, HOST4, HOST2); is_deeply([$np->ipv4_sort(@hosts)],[HOST1, HOST2, HOST3, HOST4], 'Testing ipv4_sort'); #TESTING ALL_HOSTS() my $total_hosts = 0; for my $h ($np->all_hosts()){ isa_ok($h, 'Nmap::Parser::Host'); isnt($h->status,undef,'Testing host object '.$h->addr.' in all_hosts()'); $total_hosts++; } is($total_hosts, TOTAL_HOSTS, "Testing correct number of hosts with all_hosts()"); #TESTING ALL_HOSTS(UP) my $total_uphosts = 0; for my $h ($np->all_hosts('up')){ isnt($h->addr,HOST2,'Testing host '.$h->addr.' in all_hosts(up)'); $total_uphosts++; } is($total_uphosts, scalar(@UP_HOSTS), "Testing correct number of UP hosts with all_hosts(up)"); #TESTING ALL_HOSTS(DOWN) my $total_downhosts = 0; for my $h ($np->all_hosts('down')){ is($h->addr,HOST2,'Testing host '.$h->addr.' in all_hosts(up)'); $total_downhosts++; } is($total_downhosts, scalar(@DOWN_HOSTS), "Testing correct number of DOWN hosts with all_hosts(down)"); } sub session_test { isa_ok($session = $np->get_session(), 'Nmap::Parser::Session'); is($session->numservices(),1023+1023,'Session: total number of services'); is($session->numservices('connect'),1023,'Session: numservices type = connect'); is($session->numservices('udp'),1023,'Session: numservices type = udp'); is($session->start_time(),1057088883,'Session: start_time'); is($session->start_str(),'Tue Jul 1 14:48:03 2003','Session: start_str'); is($session->finish_time(),1057088900,'Session: finish_time'); is($session->time_str(),'Tue Jul 1 14:48:20 2003','Session: time_str'); is($session->nmap_version(),'3.80','Session: nmap_version'); is($session->xml_version(),'1.01','Session: xml_version'); is($session->scan_args(),'nmap -v -v -v -oX test.xml -O -sTUR -p 1-1023 127.0.0.[1-4]','Session: scan_args'); is($session->scan_type_proto(),undef,'Session: scan_type_proto()'); is($session->scan_type_proto('connect'),'tcp','Session: scan_type_proto(connect)'); is($session->scan_type_proto('udp'),'udp','Session: scan_type_proto(udp)'); } sub host_1 { isa_ok($host = $np->get_host(HOST1), 'Nmap::Parser::Host','GET '.HOST1); is($host->status,'up','Host1: status'); is($host->addr,HOST1,'Host1: addr'); is($host->addrtype,'ipv4','Host1: addrtype'); is($host->ipv4_addr,HOST1,'Host1: ipv4_addr'); is($host->mac_addr,'00:09:5B:3F:7D:5E','Host1: mac_addr'); is($host->mac_vendor, 'Netgear','Host1: mac_vendor'); is($host->hostname,'host1','Host1: hostname()'); is($host->hostname(0),$host->hostname, 'Host1: hostname(0)'); is($host->hostname(1),'host1_2', 'Host1: hostname(1)'); is_deeply([$host->all_hostnames()],['host1','host1_2'],'Host1: all_hostnames'); is($host->extraports_state(),'closed','Host1: extraports_state'); is($host->extraports_count(),2038,'Host1: extraports_count'); is($host->tcp_port_count(),8,'Host1: tcp_port_count'); is($host->udp_port_count(),2,'Host1: udp_port_count'); is_deeply([$host->tcp_ports()],[qw(22 25 80 111 443 555 631 4903)],'Host1: tcp_ports()'); is_deeply([$host->tcp_ports('open')],[qw(80 111 443 555 631)],'Host1: tcp_ports(open)'); is_deeply([$host->tcp_ports('closed')], [qw(4903)],'Host1: tcp_ports(closed)'); is_deeply([$host->tcp_ports('filtered')], [qw(22 25 555)],'Host1: tcp_ports(filtered)'); is_deeply([$host->tcp_ports('open|filtered')],[qw(555)],'Host1: tcp_ports(open|filtered)'); is_deeply([$host->udp_ports()], [qw(111 937)],'Host1: udp_ports()'); is_deeply([$host->udp_ports('open')], [qw(111)],'Host1: udp_ports(open)'); is_deeply([$host->udp_ports('filtered')], [qw(937)],'Host1: udp_ports(filtered)'); is_deeply([$host->udp_ports('closed')], [qw()],'Host1: udp_ports(closed)'); is($host->tcp_ports('open'), $host->tcp_open_ports(), 'Host1: tcp_open_ports'); is($host->tcp_ports('filtered'),$host->tcp_filtered_ports(),'Host1: tcp_filtered_ports'); is($host->tcp_ports('closed'), $host->tcp_closed_ports(), 'Host1: tcp_closed_ports'); is($host->udp_ports('open'), $host->udp_open_ports(), 'Host1: udp_open_ports'); is($host->udp_ports('filtered'),$host->udp_filtered_ports(),'Host1: udp_filtered_ports'); is($host->udp_ports('closed'), $host->udp_closed_ports(), 'Host1: udp_closed_ports'); is($host->uptime_seconds(), '1973', 'Host1: uptime_seconds'); is($host->uptime_lastboot(),'Tue Jul 1 14:15:27 2003','Host1: uptime_lastboot'); is($host->tcpsequence_index(), 4336320, 'Host1: tcpsequence_index'); is($host->tcpsequence_class(),'random positive increments','Host1: tcpsequence_class'); is($host->tcpsequence_values(), 'B742FEAF,B673A3F0,B6B42D41,B6C710A1,B6F23FC4,B72FA3A8', 'Host1: tcpsequence_values'); is($host->ipidsequence_class(),'All zeros','Host1: ipidsequence_class'); is($host->ipidsequence_values(), '0,0,0,0,0,0', 'Host1: ipidsequence_values'); is($host->tcptssequence_class(),'100HZ','Host1: tcptssequence_class'); is($host->tcptssequence_values(), '30299,302A5,302B1,302BD,302C9,302D5', 'Host1: tcptssequence_values'); isa_ok($np->del_host(HOST1), 'Nmap::Parser::Host','DEL '.HOST1); is($np->get_host(HOST1),undef, 'Testing deletion of '.HOST1); #TESTING SERVICE OBJECT FOR HOST 1 my $svc; isa_ok($svc = $host->tcp_service(22),'Nmap::Parser::Host::Service','TCP port 22'); is($svc->name, 'ssh','Service: name'); is($svc->method, 'table','Service: method'); is($svc->confidence, 3, 'Service: confidence'); isa_ok($svc = $host->udp_service(111),'Nmap::Parser::Host::Service','UDP port 111'); is($svc->name, 'rpcbind','Service: name'); is($svc->proto, 'rpc','Service: proto'); is($svc->rpcnum, '100000','Service: rpcnum'); #TESTING OS OBJECT FOR HOST 1 my $os; isa_ok($os = $host->os_sig(),'Nmap::Parser::Host::OS','os_sig()'); } sub host_2 { isa_ok($host = $np->get_host(HOST2), 'Nmap::Parser::Host','GET '.HOST2); is($host->addr,HOST2, 'Host2: addr'); is($host->status,'down', 'Host2: status = down'); isa_ok($np->del_host(HOST2), 'Nmap::Parser::Host','DEL '.HOST2); is($np->get_host(HOST2),undef, 'Testing deletion of '.HOST2); } sub host_3 { isa_ok($host = $np->get_host(HOST3), 'Nmap::Parser::Host','GET '.HOST3); #TESTING SERVICE OBJECTS my $svc; isa_ok($svc = $host->tcp_service(22),'Nmap::Parser::Host::Service','tcp_service(22) for '.HOST3); is($svc->owner,'root', 'TCP Service: owner'); is($svc->name, 'ssh', 'TCP Service: name'); is($svc->product,'OpenSSH','TCP Service: product'); is($svc->version,'3.4p1','TCP Service: version'); is($svc->extrainfo,'protocol 1.99', 'TCP Service: extrainfo'); isa_ok($svc = $host->udp_service(80),'Nmap::Parser::Host::Service','udp_service(780) for '.HOST3); is($svc->owner,'www-data', 'UDP Service: owner'); is($svc->name, 'http', 'UDP Service: name'); is($svc->product,'Apache httpd','UDP Service: product'); is($svc->version,'1.3.26','UDP Service: version'); is($svc->extrainfo,'(Unix) Debian GNU/Linux', 'UDP Service: extrainfo'); isa_ok($svc = $host->tcp_service(500),'Nmap::Parser::Host::Service','TCP port 500'); isa_ok($np->del_host(HOST3), 'Nmap::Parser::Host','DEL '.HOST3); is($np->get_host(HOST3),undef, 'Testing deletion of '.HOST3); } sub host_4 { isa_ok($host = $np->get_host(HOST4), 'Nmap::Parser::Host','GET '.HOST4); my $os; #TESTING OS OBJECTS isa_ok($os = $host->os_sig, 'Nmap::Parser::Host::OS','os_sig for '.HOST4); is($os->portused_open,22,'OS: portused open'); is($os->portused_closed,1,'OS: portused closed'); is($os->name_count,2,'OS: name count'); is($os->name,'Linux Kernel 2.4.0 - 2.5.20','OS: name()'); is($os->name(0),$os->name,'OS: name(0)'); is($os->name(1),'Solaris 9','OS: name(1)'); is_deeply([$os->all_names],['Linux Kernel 2.4.0 - 2.5.20','Solaris 9'],'OS: all_names'); is($os->name_accuracy(),100,'OS: name_accuracy()'); is($os->name_accuracy(0),$os->name_accuracy(),'OS: name_accuracy(0)'); is($os->name_accuracy(1),99,'OS: name_accuracy(1)'); my $count = 11; is($os->class_count(),$count,'OS: class_count MAX = '.$count); is($os->osfamily(),'AOS','OS: osfamily()'); is($os->osfamily(0),$os->osfamily(),'OS: osfamily(0)'); is($os->osfamily($count),'Linux','OS: osfamily(MAX)'); is($os->osfamily(15),$os->osfamily($count),'OS: osfamily(15) = osfamily(MAX)'); is($os->vendor(),'Redback','OS: vendor()'); is($os->vendor(0),$os->vendor(),'OS: vendor(0)'); is($os->vendor($count),'Linux','OS: vendor(MAX)'); is($os->vendor(15),$os->vendor($count),'OS: vendor(15) = vendor(MAX)'); is($os->osgen(),undef,'OS: osgen()'); is($os->osgen(0),$os->osgen(),'OS: osgen(0)'); is($os->osgen($count),'2.4.x','OS: osgen(MAX)'); is($os->osgen(15),$os->osgen($count),'OS: osgen(15) = osgen(MAX)'); is($os->type(),'router','OS: type()'); is($os->type(0),$os->type(),'OS: type(0)'); is($os->type($count),'general purpose','OS: type(MAX)'); is($os->type(15),$os->type($count),'OS: type(15) = type(MAX)'); is($os->class_accuracy(),97,'OS: class_accuracy()'); is($os->class_accuracy(0),$os->class_accuracy(),'OS: class_accuracy(0)'); is($os->class_accuracy($count),50,'OS: class_accuracy(MAX)'); is($os->class_accuracy(15),$os->class_accuracy($count),'OS: class_accuracy(15) = type(MAX)'); is($host->tcptssequence_values,undef,'HOST4: tcptssequence_values = undef'); isa_ok($np->del_host(HOST4), 'Nmap::Parser::Host','DEL '.HOST4); is($np->get_host(HOST4),undef, 'Testing deletion of '.HOST4); } Nmap-Parser-1.05/t/scanner.t0100700000175300010010000000226710255417422015162 0ustar ironstarNone#!/usr/bin/perl use strict; use blib; use File::Spec; use Cwd; use Test::More tests => 3; use constant IP => '127.0.0.1'; use Nmap::Parser; my $np = new Nmap::Parser; can_ok($np,'parsescan'); my $nmap_path = find_nmap(); SKIP: { skip '[Nmap-Parser] Could not find nmap executable in path',2 if($nmap_path eq ''); ok($nmap_path,"Exe Path: $nmap_path"); skip "[Nmap-Parser] No self scanning with MSWin32",1 if($^O eq 'MSWin32' || $^O =~ /cygwin/); ok($np->parsescan($nmap_path,'',IP),'Running parsescan against '.IP); } sub find_nmap { my $exe_to_find = 'nmap'; $exe_to_find =~ s/\.exe//; local($_); local(*DIR); for my $dir (File::Spec->path()) { opendir(DIR,$dir) || next; my @files = (readdir(DIR)); closedir(DIR); my $path; for my $file (@files) { $file =~ s/\.exe$//; next unless($file eq $exe_to_find); $path = File::Spec->catfile($dir,$file); # Should symbolic link be considered? Helps me on cygwin but ... next unless -r $path && (-x _ || -l _); return $path; last DIR; } } }Nmap-Parser-1.05/tools/0040700000175300010010000000000010277405243014234 5ustar ironstarNoneNmap-Parser-1.05/tools/nmap2sqlite.pl0100700000175300010010000002266210257664446017052 0ustar ironstarNone#!/usr/bin/perl #Anthony G. Persaud #nmap2sqlite.pl #Description: # It takes in a nmap xml file and stores it into a SQLite database using DBI for # searching, storing and better reporting. This is just an example of how an # IP network database can be created using Nmap-Parser and automation. # # #This program is free software; you can redistribute it and/or modify it under #the terms of the GNU General Public License as published by the Free Software #Foundation; either version 2 of the License, or (at your option) any later #version. # #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. # # use strict; use DBI; use Nmap::Parser 1.00; use vars qw(%S %G); use File::Spec::Functions; use Pod::Usage; #Will use in the future use Getopt::Long; Getopt::Long::Configure('bundling'); GetOptions( 'help|h|?' => \$G{helpme}, 'nmap=s' => \$G{nmap}, 'xml' => \$G{file}, 'scan' => \$G{scan}, 'db=s' => \$G{DBNAME}, 'table=s' => \$G{TABLE} ) or (pod2usage(-exitstatus => 0, -verbose => 2)); unless($G{file} || $G{scan}){pod2usage(-exitstatus => 0, -verbose => 2);} print "\nnmap2sqlite.pl - ( http://www.nmapparser.com )\n", ('-'x50),"\n\n"; if($G{scan} && $G{nmap} eq ''){ $G{nmap} = find_exe(); } $G{DBNAME} ||= 'ip.db'; $G{TABLE} ||= 'hosts'; print "Using DATABASE: $G{DBNAME}\n"; print "Using TABLE : $G{TABLE}\n"; print "Using NMAP_EXE: $G{nmap}\n" if($G{scan}); #Schema for table, simple for now $S{CREATE_TABLE} = qq{ CREATE TABLE }.$G{TABLE}.qq{ ( ip VARCHAR(15) PRIMARY KEY NOT NULL, mac VARCHAR(17), status VARCHAR(7) DEFAULT 'down', hostname TEXT, open_ports TEXT DEFAULT 'none', filtered_ports TEXT DEFAULT 'none', osname TEXT, osfamily TEXT, osgen TEXT, last_scanned TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE (ip)) }; $S{INSERT_HOST} = qq{INSERT OR REPLACE INTO }.$G{TABLE}. qq{ (ip, mac, status, hostname, open_ports, filtered_ports, osname, osfamily, osgen) VALUES (?,?,?,?,?,?,?,?,?)}; my $np = new Nmap::Parser; $np->callback(\&insert_host); #not implemented in this script, will finish for Nmap::Parser 1.00 #$np->parsescan($PATH_TO_NMAP, $NMAP_ARGS, @IPS); #SQLite is used for simplicity. my $dsn = 'DBI:SQLite:'.$G{DBNAME}; my $dbh = DBI->connect($dsn) or die "Could not connect to $G{DBNAME}: ".DBI->errstr; #Check if tables exists... my @tables_exists = $dbh->tables(undef, undef, $G{TABLE} , undef); #if it doesn't - create it if(scalar @tables_exists == 0) { print "\nGenerating table: $G{TABLE} ...\n"; $dbh->do($S{CREATE_TABLE}); } #do stuff my $sth_ins = $dbh->prepare_cached($S{INSERT_HOST}); #for every host scanned, insert or updated it in the table if($G{file}){ for my $file (@ARGV){ print "\nProcessing file $file...\n"; $np->parsefile($file); } } elsif($G{scan} && $G{nmap}){ print "\nProcessing scan: ".$G{nmap}.' -sT -O -F '.join(' ',@ARGV); $np->parsescan($G{nmap},'-sT -O -F',@ARGV); } #Booyah! $sth_ins->finish; $dbh->disconnect(); #This function will insert the host, or update it if it already exists #Of course, we can always check the last_scanned entry in the database to #make sure the latest information is there, but this is just beta version. sub insert_host { my $host = shift; my $os = $host->os_sig(); #ip, mac, status, hostname, open_ports, filtered_ports, os_family, os_gen my @input_values = ( $host->addr, $host->mac_addr || undef, $host->status || undef, $host->hostname || undef, join(',',$host->tcp_open_ports) || undef, join(',',$host->tcp_filtered_ports) || undef, $os->name || undef, $os->osfamily || undef, $os->osgen || undef ); my $rv = $sth_ins->execute(@input_values) ? "ok" : "OOPS! - ".DBI->errstr; printf("\t..> %-15s : (%4s) : %-s\n",$host->addr,$host->status ,$rv); } sub find_exe { my $exe_to_find = 'nmap'; $exe_to_find =~ s/\.exe//; local($_); local(*DIR); for my $dir (File::Spec->path()) { opendir(DIR,$dir) || next; my @files = (readdir(DIR)); closedir(DIR); my $path; for my $file (@files) { $file =~ s/\.exe$//; next unless($file eq $exe_to_find); $path = File::Spec->catfile($dir,$file); next unless -r $path && (-x _ || -l _); return $path; last DIR; } } warn "[Nmap2SQLite] No nmap in your PATH: use '--nmap nmap_path' option\n"; exit; } __END__ =pod =head1 NAME nmap2sqlite - turn nmap scan data into entries in SQLite DB =head1 SYNOPSIS nmap2sqlite.pl [--db ip.db][--table hosts] --xml [ ...] nmap2sqlite.pl [--db ip.db][--table hosts] --scan [ ...] =head1 DESCRIPTION This script uses the nmap security scanner with the Nmap::Parser module in order to take an xml output scan file from nmap (-oX option), and place the information into a SQLite database (ip.db), into table (hosts). Here is the schema for the table stored in the SQLite database ip TEXT PRIMARY KEY NOT NULL, mac TEXT, status TEXT DEFAULT 'down', hostname TEXT, open_ports TEXT DEFAULT 'none', filtered_ports TEXT DEFAULT 'none', osname TEXT, osfamily TEXT, osgen TEXT, last_scanned TIMESTAMP DEFAULT CURRENT_TIMESTAMP, UNIQUE (ip)) =head1 OPTIONS These options are passed as command line parameters. Please use EITHER --scan or --xml. NOT both. =over 4 =item B<--db DBNAME> Sets the database name to DBNAME. =item B<-h,--help,-?> Shows this help information. =item B<--nmap> The path to the nmap executable. This should be used if nmap is not on your path. =item B<--scan> This will use parsescan() for the scan and take the arguments as IP addreses. =item B<--table TABLE_NAME> Sets the table name to use in the database as TABLE_NAME. =item B<--xml> This will use parsefile() for the input and take the arguments as nmap scan xml files. =back 4 =head1 TARGET SPECIFICATION This documentation was taken from the nmap man page. The IP address inputs to this scripts should be in the nmap target specification format. The simplest case is listing single hostnames or IP addresses onthe command line. If you want to scan a subnet of IP addresses, you can append '/mask' to the hostname or IP address. mask must be between 0 (scan the whole internet) and 32 (scan the single host specified). Use /24 to scan a class 'C' address and /16 for a class 'B'. You can use a more powerful notation which lets you specify an IP address using lists/ranges for each element. Thus you can scan the whole class 'B' network 128.210.*.* by specifying '128.210.*.*' or '128.210.0-255.0-255' or even use the mask notation: '128.210.0.0/16'. These are all equivalent. If you use asterisks ('*'), remember that most shells require you to escape them with back slashes or protect them with quotes. Another interesting thing to do is slice the Internet the other way. Examples: nmap2sqlite.pl --scan 127.0.0.1 nmap2sqlite.pl --scan target.example.com nmap2sqlite.pl --scan target.example.com/24 nmap2sqlite.pl --scan 10.210.*.1-127 nmap2sqlite.pl --scan *.*.2.3-5 nmap2sqlite.pl --scan 10.[10-15].10.[2-254] =head1 OUTPUT EXAMPLE See the SQLite database that is created. Default ip.db =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 =head2 Bug Reports Please submit any bugs to: L B 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. =head2 Feature Requests Please submit any requests to: L =head1 SEE ALSO L The Nmap::Parser page can be found at: L or L. It contains the latest developments on the module. The nmap security scanner homepage can be found at: L. =head1 AUTHOR Anthony G Persaud L =head1 COPYRIGHT This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. L =cut Nmap-Parser-1.05/tools/scan.pl0100700000175300010010000001577710257664446015550 0ustar ironstarNone#!/usr/bin/perl #Anthony G. Persaud use strict; use Nmap::Parser 1.00; use Getopt::Long; use File::Spec; use Pod::Usage; use vars qw(%G); $G{nmap_exe} = find_exe(); my $np = new Nmap::Parser; print "\nscan.pl - ( http://www.nmapparser.com )\n", ('-'x80),"\n\n"; GetOptions( 'help|h|?' => \$G{helpme}, 'nmap=s' => \$G{nmap} ) or (pod2usage(-exitstatus => 0, -verbose => 2)); if($G{nmap} eq '' || scalar @ARGV == 0) {pod2usage(-exitstatus => 0, -verbose => 2)} print "Using nmap exe: ".$G{nmap}."\n\n"; $np->callback(\&host_handler); $np->parsescan($G{nmap},'-sVU -O -F --randomize_hosts',@ARGV); sub host_handler { my $host = shift; print ' > '.$host->ipv4_addr."\n"; print "\t[+] Status: (".uc($host->status).")\n"; if($host->status eq 'up'){ my $os = $host->os_sig(); tab_print("Hostname(s)",$host->all_hostnames()); tab_print("Uptime",($host->uptime_seconds())." seconds") if($host->uptime_seconds()); tab_print("Last Rebooted",$host->uptime_lastboot()) if($host->uptime_lastboot); tab_print("OS Signatures",$os->all_names()); port_service_print($host); } print "\n\n"; } sub port_service_print { my $host = shift; print "\t[+] TCP Ports :\n" if($host->tcp_port_count); for my $port ($host->tcp_open_ports){ my $svc = $host->tcp_service($port); printf("\t\t%-6s %-20s %s\n", $port, '('.$svc->name.') ', $svc->product.' '. $svc->version).' '. $svc->extrainfo; } print "\t[+] UDP Ports :\n" if($host->udp_port_count); for my $port ($host->udp_open_ports){ my $svc = $host->udp_service($port); printf("\t\t%-6s %-20s %s\n", $port, '('.$svc->name.') ', $svc->product.' '. $svc->version).' '. $svc->extrainfo; } } sub tab_print { my $title = shift; print "\t[+] $title :\n"; for my $a (@_) {print "\t\t$a\n";} } sub find_exe { my $exe_to_find = 'nmap'; $exe_to_find =~ s/\.exe//; local($_); local(*DIR); for my $dir (File::Spec->path()) { opendir(DIR,$dir) || next; my @files = (readdir(DIR)); closedir(DIR); my $path; for my $file (@files) { $file =~ s/\.exe$//; next unless($file eq $exe_to_find); $path = File::Spec->catfile($dir,$file); next unless -r $path && (-x _ || -l _); return $path; last DIR; } } } __END__ =pod =head1 NAME scan - a scanning script to gather port and OS information from hosts =head1 SYNOPSIS scan.pl [--nmap ] [ ...] =head1 DESCRIPTION This script uses the nmap security scanner with the Nmap::Parser module in order to run quick scans against specific hosts, and gather all the information that is required to know about that specific host which nmap can figure out. This script can be used for quick audits against machines on the network and an educational use for learning how to write scripts using the Nmap::Parser module. B =head1 OPTIONS These options are passed as command line parameters. =over 4 =item B<--nmap> The path to the nmap executable. This should be used if nmap is not on your path. =item B<-h,--help,-?> Shows this help information. =back 4 =head1 TARGET SPECIFICATION This documentation was taken from the nmap man page. The IP address inputs to this scripts should be in the nmap target specification format. The simplest case is listing single hostnames or IP addresses onthe command line. If you want to scan a subnet of IP addresses, you can append '/mask' to the hostname or IP address. mask must be between 0 (scan the whole internet) and 32 (scan the single host specified). Use /24 to scan a class 'C' address and /16 for a class 'B'. You can use a more powerful notation which lets you specify an IP address using lists/ranges for each element. Thus you can scan the whole class 'B' network 128.210.*.* by specifying '128.210.*.*' or '128.210.0-255.0-255' or even use the mask notation: '128.210.0.0/16'. These are all equivalent. If you use asterisks ('*'), remember that most shells require you to escape them with back slashes or protect them with quotes. Another interesting thing to do is slice the Internet the other way. Examples: scan.pl 127.0.0.1 scan.pl target.example.com scan.pl target.example.com/24 scan.pl 10.210.*.1-127 scan.pl *.*.2.3-5 scan.pl 10.[10-15].10.[2-254] =head1 OUTPUT EXAMPLE These are ONLY examples of how the output would look like. Not the specs to my machine Scan Host -------------------------------------------------- [>] 127.0.0.1 [+] Status: (UP) [+] Hostname(s) : localhost.localdomain [+] Operation System(s) : Linux Kernel 2.4.0 - 2.5.20 [+] TCP Ports : (service) [version] 22 ssh OpenSSH 3.5p1 25 smtp 111 rpcbind 443 https 631 ipp [+] UDP Ports : 111 rpcbind 937 unknown =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 =head2 Bug Reports Please submit any bugs to: L B 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. =head2 Feature Requests Please submit any requests to: L =head1 SEE ALSO L The Nmap::Parser page can be found at: L or L. It contains the latest developments on the module. The nmap security scanner homepage can be found at: L. =head1 AUTHOR Anthony G Persaud L =head1 COPYRIGHT This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. 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. L =cut