LoginSignup
11
19

脆弱性のあるソースコードサンプル集

Last updated at Posted at 2021-12-16

概要

Webアプリケーションの脆弱性が存在するソースコードをまとめてみました。

あくまでサンプルだということは頭に入れておいてください。
今からお見せするソースコードのような書き方をしていないからといって、脆弱性が存在しないわけでは全くありません。
逆に同じようなソースコードが散見されたからといって、100%脆弱性があるとは限らないこともご了承ください。

詳しくはソースコードと一緒に貼ってある各リンクを参照してください。

随時アップデートしていきます。9/11

脆弱性一覧

LFI/ローカルファイルインクルード(PHP)

<?php
   $file = $_GET['file'];
   if(isset($file))
   {
       include("pages/$file");
   }
   else
   {
       include("index.php");
   }
?>

RFI/リモートファイルインクルード(PHP)

<?php
    $file = $_GET['file'];
    include($file);
?>

Directory Traversal/ディレクトリトラバーサル(PHP)

<?php
    $file = $_GET['file'];
    file_get_contents('directory/' . $file);
?>

SQLi/SQLインジェクション(PHP)

<?php
      $con = mysql_connect("localhost","sqli","sqli");
      if (!$con) {
        die('Could not connect: ' . mysql_error());
      }
      mysql_select_db("sqliexample", $con);
      $id = $_GET['id'];
      $result = mysql_query("SELECT name FROM user WHERE id=$id", $con);
    
      mysql_close($con);
      $num = mysql_num_rows($result);
      $i=0;
      while ($i < $num) {
        $name = mysql_result($result, $i, "name");
        echo "Hello " . $name;
        echo "<br/>";
        $i++;
      }
?>

XSS/クロスサイトスクリプティング(JavaScript)

protected void doGet(HttpServletRequest request, HttpServletResponse resp) {
    String firstName = request.getParameter("firstName");
    resp.getWriter().append("<div>");
    resp.getWriter().append("Search for " + firstName);
    resp.getWriter().append("</div>");
}

File Upload Vulnerability(PHP)

$file = $_FILES['wpshop_file'];
$tmp_name = $file['tmp_name'];
$name = $file["name"];
@move_uploaded_file($tmp_name, WPSHOP_UPLOAD_DIR.$name);

XXE/XML外部エンティティ攻撃(PHP)

<?php
libxml_disable_entity_loader (false);
$xmlfile = file_get_contents('php://input');
$dom = new DOMDocument();
$dom->loadXML($xmlfile, LIBXML_NOENT | LIBXML_DTDLOAD); 
$creds = simplexml_import_dom($dom);
$user = $creds->user;
$pass = $creds->pass;

echo "You have logged in as user $user";
?>

SSRF/サーバーサイドリクエストフォージェリ(PHP)

<?php

if (isset($_GET['image_url'])){
$url = $_GET['image_url'];

$file = fopen($url, 'rb');
header("Content-Type: image/png");
fpassthru($file);

}
echo 'Please enter image url'
?>

SSRF/サーバーサイドリクエストフォージェリ(Java)

private static String fetchRemoteObject(String location) throws Exception {
    URL url = new URL(location);
    URLConnection connection = url.openConnection();
    BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String body = reader.lines().collect(Collectors.joining());
    return body;
}

OS Command Injection(PHP)

<?php
  $dir = $_GET['dir'];

  $cmd = 'ls images/' . $dir;
  system($cmd, $return_value);
  echo $return_value;
?>

OS Command Injection(Java)

public static void listFiles(String dir) throws Exception {
  Runtime rt = Runtime.getRuntime();
  Process proc = rt.exec(new String[] {"sh", "-c", "ls " + dir});
  int result = proc.waitFor();
  if (result != 0) {
    System.out.println("process error: " + result);
  }
  InputStream in = (result == 0) ? proc.getInputStream() :
                                   proc.getErrorStream();
  int c;
  while ((c = in.read()) != -1) {
    System.out.print((char) c);
  }
}

SSTI/サーバーサイドテンプレートインジェクション(Python)

@app.route("/")
def index():
            username = request.values.get('username')
            return Jinja2.from_string('Hello ' + username).render()

Insecure Deserialization(Python)

半分Exploit Codeになってます

import os
import _pickle

class Exploit(object):
def __reduce__(self):
return (os.system, ('whoami',))

def serialize_exploit():
shellcode = _pickle.dumps(Exploit())
return shellcode

def insecure_deserialization(exploit_code):
_pickle.loads(exploit_code)

if __name__ == '__main__':
shellcode = serialize_exploit()
insecure_deserialization(shellcode)

Zip Slip Vulnerability(Java)

Enumeration<ZipEntry>entries = zip.getEntries(); 
while (entries.hasMoreElements()) { 
    ZipEntry e = entries.nextElement(); 
    File f = new File(destinationDir, e.getName()); 
    InputStream input = zip.getInputStream(e); 
    IOUtils.copy(input, write(f)); 
}

最後に

脆弱性のあるソースコードを探していると、どの様なコードが危険なのか何となく肌感覚で分かってきた気がします。
ユーザーのインプットから、何かしらの関数を実行するまでにチェックやバリデーションをしている形跡がないと、怪しい匂いがプンプンします。

この記事が皆さんのお役に立てれば嬉しいです。最後まで読んでくださってありがとうございました。

質問がある方は是非コメントしてください😃

11
19
1

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
  3. You can use dark theme
What you can do with signing up
11
19