Media Log

[악성코드]에 해당되는 글 1

  1. php sql인젝션 공격막기 2009.06.05

Example#1 mysql_real_escape_string() 예제

<?php
// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(
mysql_error());

// Query
$query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'",
           
mysql_real_escape_string($user),
           
mysql_real_escape_string($password));
?>

Example#2 SQL 인젝션 공격(Injection Attack)의 예

<?php
// Query database to check if there are any matching users
$query = "SELECT * FROM users WHERE user='{$_POST['username']}' AND password='{$_POST['password']}'";
mysql_query($query);

// We didn't check $_POST['password'], it could be anything the user wanted! For example:
$_POST['username'] = 'aidan';
$_POST['password'] = "' OR ''='";

// This means the query sent to MySQL would be:
echo $query;
?>

MySQL로 전송되는 질의:

SELECT * FROM users WHERE name='aidan' AND password='' OR ''=''

유효한 비밀번호 없이 누구나 접속하여 접근이 가능하다.

Example#3 "Best Practice" 질의

mysql_real_escape_string()은 각 변수에 대해 SQL 인젝션을 방지한다. 이 예제는 Magic Quotes 설정과는 별개로 데이터베이스를 질의하는 "best practice" 방법을 시연한다.

<?php
// Quote variable to make safe
function quote_smart($value)
{
   
// Stripslashes
   
if (get_magic_quotes_gpc()) {
       
$value = stripslashes($value);
    }
   
// Quote if not integer
   
if (!is_numeric($value)) {
       
$value = "'" . mysql_real_escape_string($value) . "'";
    }
    return
$value;
}

// Connect
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
    OR die(
mysql_error());

// Make a safe query
$query = sprintf("SELECT * FROM users WHERE user=%s AND password=%s",
           
quote_smart($_POST['username']),
           
quote_smart($_POST['password']));

mysql_query($query);
?>

SQL 인젝션 공격이 동작하지 않으며 질의가 정확하게 실행될 것이다.