blib/lib/Masscan/Client.pm untested

filter: Statementstmt 0.0% 0 / 274 Branchbran 0.0% 0 / 74 Conditioncond 0.0% 0 / 27 Subroutinesub 0.0% 0 / 43 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 437 CC 38 SCAR 31.6
CC
38
Cov
0%
_resolve_dns
72.0
scan
56.0
_build_binary
56.0
CRAP 23.5
1 package Masscan::Client;
2 use strict;
3 use warnings;
4 use 5.020;
5 use Moose;
6 use MooseX::AttributeShortcuts;
7 use MooseX::StrictConstructor;
8 use MooseX::Types::Moose qw(:all);
9 use MooseX::Types::Structured qw(:all);
10 use Carp;
11 use English qw(-no_match_vars);
12 use File::Spec;
13 use File::Temp;
14 use IPC::Open3;
15 use POSIX qw(WEXITSTATUS);
16 use Symbol 'gensym';
17 use JSON;
18 use Net::DNS;
19 use Data::Validate::IP qw(is_ipv4 is_ipv6);
20 use Data::Validate::Domain qw(is_domain);
21 use Log::Log4perl qw(:easy);
22 use Log::Log4perl::Appender::ScreenColoredLevels::UsingMyColors;
23 use Try::Catch;
24 use Data::Dumper;
25 use namespace::autoclean;
26  
27 our $VERSION = '0.2';
28  
29 has hosts => (
30 is => 'rw',
31 isa => ArrayRef,
32 required => 0,
33 default => sub { [] },
34 );
35  
36 has ports => (
37 is => 'rw',
38 isa => ArrayRef,
39 required => 0,
40 default => sub { [] },
41 );
42  
43 has arguments => (
44 is => 'rw',
45 isa => ArrayRef,
46 required => 0,
47 default => sub { [] },
48 );
49  
50 has binary => (
51 is => 'rw',
52 isa => Str,
53 required => 0,
54 builder => '_build_binary',
55 lazy => 1,
56 );
57  
58 has command_line => (
59 is => 'rw',
60 isa => Str,
61 required => 0,
62 );
63  
64 has scan_results_file => (
65 is => 'rw',
66 isa => Str,
67 required => 0,
68 builder => 'build_scan_results_file',
69 lazy => 1,
70 );
71  
72 has sudo => (
73 is => 'rw',
74 isa => Int,
75 required => 0,
76 default => 0,
77 );
78  
79 has verbose => (
80 is => 'rw',
81 isa => Int,
82 required => 0,
83 default => 0,
84 );
85  
86 has logger => (
87 is => 'ro',
88 isa => Object,
89 required => 0,
90 builder => 'build_logger',
91 lazy => 1,
92 );
93  
94 has name_servers => (
95 is => 'rw',
96 isa => ArrayRef,
97 required => 0,
98 builder => 'build_name_servers',
99 );
100  
101 sub add_host {
102 my ($self, $host) = @_;
103  
104 if (!$self -> _is_valid_host($host)) {
105 return 0;
106 }
107  
108 return push $self -> hosts -> @*, $host;
109 }
110  
111 sub add_port {
112 my ($self, $port) = @_;
113  
114 if (!$self -> _is_valid_port($port)) {
115 return 0;
116 }
117  
118 return push $self -> ports -> @*, $port;
119 }
120  
121 sub add_argument {
122 my ($self, $arg) = @_;
123  
124 return push $self -> arguments -> @*, $arg;
125 }
126  
127 sub scan {
128 my ($self) = @_;
129 my $binary = $self -> binary;
130 my $hosts = $self -> _aref_to_str(
131 $self -> _hosts_to_ips($self -> hosts),
132 'hosts'
133 );
134 my $ports = $self -> _aref_to_str($self -> ports, 'ports');
135 my $fstore = $self -> scan_results_file;
136 my $args = $self -> _aref_to_str($self -> arguments, 'args');
137 my $sudo = q{};
138  
139 if (!$args) {
140 $args = q{};
141 }
142  
143 if ($self -> sudo) {
144 $sudo = $self -> _build_binary('sudo');
145 }
146  
147 my $cmd = "$sudo $binary $args -p $ports $hosts";
148  
149 $self -> logger -> info('Starting masscan');
150 $self -> logger -> debug("Command: $cmd");
151  
152 $self -> command_line($cmd);
153  
154 if (!$binary || $binary !~ m{masscan$}xmsi) {
155 $self -> logger -> fatal('masscan not found');
156 croak;
157 }
158  
159 $self -> logger -> info('Attempting to run command');
160 my $scan = $self -> _run_cmd($cmd . " -oJ $fstore");
161  
162 if ($scan -> {success}) {
163 $self -> logger -> info('Command executed successfully');
164 }
165  
166 if (!$scan -> {success}) {
167 $self -> logger -> error(
168 "Command has failed: $scan -> {stderr} "
169 . 'Ensure root or sudo permissions'
170 );
171 }
172  
173 if ($scan -> {success}) {
174 return 1;
175 }
176  
177 return 0;
178 }
179  
180 sub scan_results {
181 my ($self) = @_;
182 my $cmd = $self -> command_line;
183 my $sres = $self -> _from_json(
184 $self -> _slurp_file($self -> scan_results_file)
185 );
186 my %up_hosts;
187  
188 if (!$sres) {
189 $self -> logger -> warn('No results');
190 $sres = [];
191 }
192  
193 for my $result ($sres -> @*) {
194 $up_hosts{$result -> {ip}} = 1;
195 }
196  
197 $self -> logger -> info('Collating scan results');
198  
199 return {
200 masscan => {
201 command_line => $cmd,
202 scan_stats => {
203 total_hosts => scalar($self -> hosts -> @*),
204 up_hosts => scalar(keys %up_hosts),
205 },
206 },
207 scan_results => $sres,
208 };
209 }
210  
211 sub _run_cmd {
212 my ($self, $cmd) = @_;
213  
214 my ($stdin, $stdout, $stderr);
215 $stderr = gensym;
216 my $pid = open3($stdin, $stdout, $stderr, $cmd);
217 my $waited_pid = waitpid $pid, 0;
218  
219 my $success = 0;
220 if ($waited_pid == $pid && WEXITSTATUS($CHILD_ERROR) == 0) {
221 $success = 1;
222 }
223  
224 return {
225 stdout => $self -> _slurp($stdout),
226 stderr => $self -> _slurp($stderr),
227 success => $success,
228 };
229 }
230  
231 sub _slurp_file {
232 my ($self, $path) = @_;
233 my $file_data;
234 my $file_read_succeeded = 0;
235  
236 $self -> logger -> debug("Slurping up file: $path");
237  
238 try {
239 open(my $fh, '<', $path)
240 || croak("Unable to open $path: $ERRNO");
241 $file_data = $self -> _slurp($fh);
242 if (!close $fh) {
243 croak("Unable to close $path: $ERRNO");
244 }
245 $file_read_succeeded = 1;
246 }
247 catch {
248 $self -> logger -> warn(
249 "$ERRNO. " . 'Most likely scan was not successful.'
250 );
251 };
252  
253 if ($file_read_succeeded) {
254 return $file_data;
255 }
256  
257 return;
258 }
259  
260 sub _slurp {
261 my ($self, $glob) = @_;
262  
263 local $INPUT_RECORD_SEPARATOR = undef;
264 return scalar <$glob>;
265 }
266  
267 sub _hosts_to_ips {
268 my ($self, $hosts) = @_;
269 my @sane_hosts;
270  
271 for my $host ($hosts -> @*) {
272 $self -> logger -> info("Checking $host sanity");
273  
274 if ($self -> _is_valid_host($host)) {
275 if (is_domain($host)) {
276 my $ips = $self -> _resolve_dns($host);
277 for my $ip ($ips -> @*) {
278 push @sane_hosts, $ip;
279 }
280 }
281  
282 if (!is_domain($host)) {
283 push @sane_hosts, $host;
284 $self -> logger -> info("Added $host to scan list");
285 }
286 }
287 }
288  
289 return \@sane_hosts;
290 }
291  
292 sub _is_valid_host {
293 my ($self, $host) = @_;
294 my $target = $host || 0;
295  
296 $target =~ s{\/.*$}{}xmsg;
297  
298 if (is_ipv4($target) || is_ipv6($target) || is_domain($target)) {
299 $self -> logger -> debug(
300 "$host is a valid IP address or domain name"
301 );
302 return 1;
303 }
304  
305 $self -> logger -> warn(
306 "$host is not a valid IP address or domain name"
307 );
308 return 0;
309 }
310  
311 sub _is_valid_port {
312 my ($self, $port) = @_;
313 my $target = $port || 0;
314  
315 if ($target =~ m{^\d+$}xms || $target =~ m{^\d+-\d+$}xms) {
316 $self -> logger -> debug(
317 "$port is valid port number or port range"
318 );
319 return 1;
320 }
321  
322 $self -> logger -> warn(
323 "$port is not valid port number or port range"
324 );
325 return 0;
326 }
327  
328 sub _aref_to_str {
329 my ($self, $aref, $type) = @_;
330 my $str = q{};
331  
332 $self -> logger -> info("Converting $type ArrayRef to masscan cli format");
333  
334 if ($type eq 'hosts') {
335 my @hosts;
336 for my $host ($aref -> @*) {
337 if ($self -> _is_valid_host($host)) {
338 push @hosts, $host;
339 }
340 }
341 return join q{,}, @hosts;
342 }
343  
344 if ($type eq 'ports') {
345 my @ports;
346 for my $port ($aref -> @*) {
347 if ($self -> _is_valid_port($port)) {
348 push @ports, $port;
349 }
350 }
351 return join q{,}, @ports;
352 }
353  
354 if ($type eq 'args') {
355 for my $arg ($aref -> @*) {
356 $str .= $arg . q{ };
357 }
358 $str =~ s/\s+$//xms;
359 return $str;
360 }
361  
362 return $str;
363 }
364  
365 sub _from_json {
366 my ($self, $json) = @_;
367 my $decoded_data = [];
368  
369 if (!$json) {
370 return [];
371 }
372  
373 try {
374 $decoded_data = decode_json($json);
375 }
376 catch {
377 $self -> logger -> warn('Unable to parse scan results JSON');
378 $decoded_data = [];
379 };
380  
381 return $decoded_data;
382 }
383  
384 sub _resolve_dns {
385 my ($self, $domain) = @_;
386 my $resolver = Net::DNS::Resolver -> new;
387 my @ips;
388  
389 if ($self -> name_servers) {
390 $resolver -> nameservers($self -> name_servers -> @*);
391 }
392  
393 if ($domain) {
394 my $query = $resolver -> search($domain);
395 if ($query) {
396 for my $answer ($query -> answer) {
397 if ($answer -> type eq 'A') {
398 push @ips, $answer -> address;
399 }
400  
401 if ($answer -> type eq 'AAAA') {
402 push @ips, $answer -> address;
403 }
404 }
405 }
406  
407 if (!$query) {
408 return [];
409 }
410 }
411  
412 if (!@ips) {
413 return [];
414 }
415  
416 return \@ips;
417 }
418  
419 sub build_name_servers {
420 my ($self) = @_;
421  
422 return [
423 '1.1.1.1',
424 '2606:4700:4700::1111',
425 '1.0.0.1',
426 '2606:4700:4700::1001',
427 '8.8.8.8',
428 '2001:4860:4860::8888',
429 '8.8.4.4',
430 '2001:4860:4860::8844'
431 ];
432 }
433  
434 sub build_scan_results_file {
435 my ($self) = @_;
436 my $handle = File::Temp -> new();
437  
438 return $handle -> filename;
439 }
440  
441 sub _build_binary {
442 my ($self, $binary) = @_;
443  
444 if (!$binary) {
445 $binary = 'masscan';
446 }
447  
448 my $sep = q{:};
449 if ($OSNAME =~ m{Win}xms) {
450 $sep = q{;};
451 }
452  
453 for my $dir (split $sep, $ENV{PATH}) {
454 my $dh;
455 if (!opendir $dh, $dir) {
456 next;
457 }
458 my @files = readdir $dh;
459 if (!closedir $dh) {
460 next;
461 }
462  
463 for my $file (@files) {
464 if ($file !~ m{^$binary(?:[.]exe)?$}xms) {
465 next;
466 }
467 my $path = File::Spec -> catfile($dir, $file);
468 if (!(-r $path && (-x _ || -l _))) {
469 next;
470 }
471 return $path;
472 }
473 }
474  
475 return;
476 }
477  
478 sub build_logger {
479 my ($self) = @_;
480 my $conf = _build_log_conf('OFF');
481  
482 if ($self -> verbose) {
483 $conf = _build_log_conf('DEBUG');
484 }
485  
486 Log::Log4perl -> init(\$conf);
487  
488 return Log::Log4perl -> get_logger(__PACKAGE__);
489 }
490  
491 sub _build_log_conf {
492 my ($level) = @_;
493  
494 return <<"__LOG_CONF__";
495 log4perl.logger = TRACE, Screen
496 log4perl.appender.Screen = Log::Log4perl::Appender::ScreenColoredLevels::UsingMyColors
497 log4perl.appender.Screen.Threshold = $level
498 log4perl.appender.Screen.stderr = 0
499 log4perl.appender.Screen.utf8 = 1
500 log4perl.appender.Screen.layout = Log::Log4perl::Layout::PatternLayout::Multiline
501 log4perl.appender.Screen.color.trace = cyan
502 log4perl.appender.Screen.color.debug = magenta
503 log4perl.appender.Screen.color.info = green
504 log4perl.appender.Screen.color.warn = yellow
505 log4perl.appender.Screen.color.error = red
506 log4perl.appender.Screen.color.fatal = bright_red
507 log4perl.appender.Screen.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm} %M (%L) [%p] %m{indent=4} %n
508 __LOG_CONF__
509 }
510  
511 __PACKAGE__ -> meta -> make_immutable;
512 1;
513  
514 __END__
515  
516 =pod
517  
518 =encoding UTF-8
519  
520 =head1 NAME
521  
522 Masscan::Client - A Perl module which helps in using the masscan port scanner.
523  
524 =head1 VERSION
525  
526 version 0.2
527  
528 =head1 SYNOPSIS
529  
530 use Masscan::Client;
531  
532 my @hosts = qw(::1 127.0.0.1);
533 my @ports = qw(22 80 443 1-100);
534 my @arguments = qw(--banners);
535  
536 my $mas = Masscan::Client -> new(
537 hosts => \@hosts,
538 ports => \@ports,
539 arguments => \@arguments
540 );
541  
542 $mas -> add_host('10.0.0.1');
543 $mas -> add_host('10.0.0.0/24');
544 $mas -> add_port(25);
545 $mas -> add_port(110);
546  
547 $mas -> add_port('1024-2048');
548 $mas -> add_port('3000-65535');
549  
550 $mas -> add_host('averna.id.au');
551 $mas -> add_host('duckduckgo.com');
552  
553 $mas -> sudo(1);
554  
555 $mas -> verbose(1);
556  
557 $mas -> add_argument('--rate 100000');
558  
559 $mas -> binary('/usr/bin/masscan');
560  
561 $mas -> name_servers(['192.168.0.100', '192.168.0.101']);
562  
563 my $scan = $mas -> scan;
564 my $res;
565 if ($scan) {
566 $res = $mas -> scan_results;
567 }
568  
569 =head1 DESCRIPTION
570  
571 Masscan::Client provides an object-oriented interface for building,
572 running, and parsing masscan scans from Perl code.
573  
574 =head1 SUBROUTINES/METHODS
575  
576 =head2 add_host
577  
578 This method allows the addition of a host to the host list to be scaned.
579  
580 my $mas = Masscan::Client -> new();
581 $mas -> add_host('127.0.0.1');
582  
583 =head2 add_port
584  
585 This method allows the addition of a port or port range to the port list to be scaned.
586  
587 my $mas = Masscan::Client -> new();
588 $mas -> add_port(443);
589 $mas -> add_port('1-65535');
590  
591 =head2 add_argument
592  
593 This method allows the addition of masscan command line arguments.
594  
595 my $mas = Masscan::Client -> new(
596 hosts => ['127.0.0.1', '10.0.0.1'],
597 ports => [80, 443]
598 );
599 $mas -> add_argument('--banners');
600 $mas -> add_argument('--rate 100000');
601  
602 =head2 scan
603  
604 Will initiate the scan of what hosts & ports have been provided.
605 Returns true fi the scan was successful otherwise returns false.
606  
607 my $mas = Masscan::Client -> new();
608 $mas -> hosts(['127.0.0.1', '::1']);
609 $mas -> ports(['22', '80', '443']);
610 $mas -> add_port('1024');
611  
612 $mas -> scan;
613  
614 =head2 scan_results
615  
616 Returns the result of the masscan as a Perl data structure.
617  
618 my $mas = Masscan::Client -> new();
619 $mas -> hosts(['127.0.0.1', '::1']);
620 $mas -> ports(['22', '80', '443']);
621 $mas -> add_port('1024');
622  
623 my $scan = $mas -> scan;
624  
625 if ($scan) {
626 my $res = $mas -> scan_results;
627 }
628  
629 =head1 SCAN RESULTS
630  
631 The scan_results method returns a data structure like so:
632  
633 {
634 'scan_results' => [
635 {
636 'timestamp' => '1584816181',
637 'ip' => '10.0.0.1',
638 'ports' => [
639 {
640 'status' => 'open',
641 'reason' => 'syn-ack',
642 'port' => 443,
643 'proto' => 'tcp',
644 'ttl' => 60
645 }
646 ]
647 },
648 {
649 'timestamp' => '1584816181',
650 'ip' => '10.0.0.2',
651 'ports' => [
652 {
653 'reason' => 'syn-ack',
654 'status' => 'open',
655 'port' => 443,
656 'ttl' => 60,
657 'proto' => 'tcp'
658 }
659 ]
660 },
661 {
662 'ports' => [
663 {
664 'port' => 80,
665 'ttl' => 60,
666 'proto' => 'tcp',
667 'reason' => 'syn-ack',
668 'status' => 'open'
669 }
670 ],
671 'ip' => '10.0.0.1',
672 'timestamp' => '1584816181'
673 },
674 {
675 'ip' => '10.0.0.2',
676 'timestamp' => '1584816181',
677 'ports' => [
678 {
679 'port' => 80,
680 'ttl' => 60,
681 'proto' => 'tcp',
682 'status' => 'open',
683 'reason' => 'syn-ack'
684 }
685 ]
686 },
687 {
688 'timestamp' => '1584816181',
689 'ip' => '10.0.0.3',
690 'ports' => [
691 {
692 'reason' => 'syn-ack',
693 'status' => 'open',
694 'proto' => 'tcp',
695 'ttl' => 111,
696 'port' => 80
697 }
698 ]
699 },
700 {
701 'ports' => [
702 {
703 'ttl' => 111,
704 'proto' => 'tcp',
705 'port' => 443,
706 'reason' => 'syn-ack',
707 'status' => 'open'
708 }
709 ],
710 'timestamp' => '1584816181',
711 'ip' => '10.0.0.3'
712 }
713 ],
714 'masscan' => {
715 'scan_stats' => {
716 'total_hosts' => 4,
717 'up_hosts' => 3
718 },
719 'command_line' => '/usr/bin/masscan --rate 100000 --banners -p 22,80,443,61222,25 10.0.0.2,10.0.0.1,10.0.0.3,10.0.0.4'
720 }
721 };
722  
723 =head1 DIAGNOSTICS
724  
725 The module logs warnings and errors through Log::Log4perl. Typical
726 diagnostics include invalid host or port input, missing masscan binary,
727 and JSON parsing failures in scan output.
728  
729 =head1 CONFIGURATION AND ENVIRONMENT
730  
731 The module discovers the masscan binary from the `PATH` environment
732 variable when not explicitly set. DNS lookups use configurable name
733 servers through the `name_servers` attribute.
734  
735 =head1 DEPENDENCIES
736  
737 Core dependencies include Moose, JSON, Net::DNS, Data::Validate::IP,
738 Data::Validate::Domain, Try::Catch, and Log::Log4perl.
739  
740 =head1 INCOMPATIBILITIES
741  
742 No known incompatibilities are documented.
743  
744 =head1 BUGS AND LIMITATIONS
745  
746 Scan execution depends on the external masscan binary and required
747 execution privileges in the runtime environment.
748  
749 =head1 AUTHOR
750  
751 Heitor Gouvea <hgouvea@cpan.org>
752  
753 =head1 LICENSE AND COPYRIGHT
754  
755 This software is copyright (c) 2026 by Heitor Gouvea.
756  
757 This is free software; you can redistribute it and/or modify it under
758 the same terms as the Perl 5 programming language system itself.
759  
760 =cut