php sql injection ๋ณด์
php sql ์ธ์ ์ ์๋ฐฉ
- magic_quote_gpc
Sets the magic_quotes state for GPC (Get/Post/Cookie) operations. When magic_quotes are on, all ' (single-quote), " (double quote), \ (backslash) and NUL's are escaped with a backslash automatically.
์ด๊ฒ์ ์๋์ผ๋ก addslashes() ๋ฅผ ํ๋ ์ต์ ์ ๋๋ค.
ํ์ง๋ง sql ๋ฌธ๋ฒ์ ์์ ํ ๋ง์ง ์์ต๋๋ค.
๋ฌผ๋ก \ ๋ก escape ํ๋ ๋ฌธ๋ฒ์ ์ง์ํด ์ฃผ๊ธด ํฉ๋๋ค๋ง, ์๋์ ๋ฌธ๋ฒ์ ์๋๋๋ค.
๊ฒ๋ค๊ฐ ; ๋ escape ์ํค์ง ์์ผ๋ ์ฌ์ํ ์ค์๋ก ํฐ ๋ณด์๊ตฌ๋ฉ์ด ๋ฐ์ํ ์ ์์ต๋๋ค.
- *_escape_string()
๊ฐ sql ๋ณ๋ก escape_string() ์ด๋ผ๋ ํจ์๊ฐ ์ ๊ณต๋ฉ๋๋ค.
mysql_escape_string('๋ฌธ์์ด') ๋ก mysql ์ ๋ง๋ escape ๋ ๋ฌธ์์ด๋ก ๋ณํํด ์ค๋๋ค.
์ผ๋ฐ์ ์ผ๋ก sql ์ ๋ฌธ๋ฒ์ ๋ฌธ์์ด์ ์์๋ฐ์ดํ(') ๋ก ๋ฌถ๊ณ , ์์๋ฐ์ดํ๋ฅผ ํํํ๋๊ฒ์ ์์๋ฐ์ดํ 2๋ฒ ์ ๋๋ค.('')
์ด๊ฒ '์ฐธ' ์ข๊ตฐ ์ด๋ผ๋ ๋ฌธ์์ด์ escape ์ํจ๋ค๋ฉด
์ด๊ฒ ''์ฐธ'' ์ข๊ตฐ ์ด ๋๊ณ
query('INSERT INTO table VALUES (\'์ด๊ฒ \'\'์ฐธ\'\' ์ข๊ตฐ\');') ์ด ๋ ๊ฒ์ ๋๋ค.
๋ณดํต์ post ๋ฐ์ ๋ฌธ์์ด์ db ์ ๋ฃ์ ๊ฒ์ด๋ฏ๋ก
$_POST = array_map('mysql_escape_string', $_POST); ๋ก ํ๋ฒ์ escape ์ํค๊ณ ์ฌ์ฉํ๋ฉด ๋ฉ๋๋ค.
์ฃผ์ํ ๊ฒ์ select ํ ๊ฒฐ๊ณผ๋ฅผ ๊ทธ๋๋ก ์ฌ์ฌ์ฉํ ๋ ๋ค์ escape ์์ผ์ผ ํ๋ค๋ ๊ฒ์ ๋๋ค.
result ๋ escape ๋์ง ์์ ๋ฌธ์์ด ์ ๋๋ค.
- prepared query
์ข๋ ์์ ํ๊ณ ํธ๋ฆฌํ ๋ฐฉ๋ฒ์ผ๋ก prepared query ๋ฅผ ์ด์ฉํ๋ ๋ฐฉ๋ฒ์ด ์์ต๋๋ค.
INSERT INTO table (a, b) VALUES (:a, :b) ๋ผ๋ ์ฟผ๋ฆฌ๋ฅผ ๋ฏธ๋ฆฌ prepare (์ปดํ์ผ?) ์ํต๋๋ค.
์ด ๋จ๊ณ์์๋ ์ธ์ ์ ์ด ์ผ์ด๋ ๋ฌธ์์ด์ด ์์ ํฌํจ๋์ง ์์์ฑ prepare ๋ฉ๋๋ค.
๊ทธ ๋ค์ prepare ๋ ์ฟผ๋ฆฌ์ ๋ฌธ์์ด์ bind ํ์ฌ ์ฟผ๋ฆฌ๋ฅผ ์คํํฉ๋๋ค.
bind ๋จ๊ณ์์๋ ํ์ฑํ์ง ์์ผ๋ฏ๋ก escape ์ํค์ง ์์๋ ์์ ํฉ๋๋ค.
mysqli, pg ๋ฑ์ด ์ ๊ณตํ๊ณ , PDO ๋ฅผ ์ด์ฉํ๋ฉด ์์ฝ๊ฒ ์ ์ฉํ ์ ์์ต๋๋ค.
$db = new PDO(์ ์);
$stmt = $db->prepare('INSERT INTO table (a, b) VALUES (:a, :b)');
$fields[':a'] = '\'; DELETE FROM table;\';
$fields[':b'] = '\'; DELETE FROM table;\';
$stmt->execute($fields);
bind ๊ฐ์ธ :a, :b ๋ ๋ฌธ์์ด์ด๋ ์์ด๋ ๋ฐ์ดํ๋ฅผ ์ฐ์ง ์์ต๋๋ค.
์์ ์์ ์ธ์ bindParam() ํจ์๋ฅผ ์ด์ฉํ์ฌ & ์ฐธ์กฐ๋ณ์๋ก ๋ง๋ค์ด ๋ณ์์ ๊ฐ๋ง ์ฑ์ฐ๊ณ execute() ํ๋ฉด ๋๋ ๋ฐฉ์๋ ์์ต๋๋ค.
์ด๋ป๊ฒ ๋ซ์ ์ ์์ง? ์๋ฌด๋ฆฌ ์๊ฐํด๋ ์ด ์ฝ๋์์๋ ๋ซ์ ์ ์์ด. ๊ทธ๋ฌ๋ ๊ท์ฐฎ๊ฒ escape ์์์ผ๋ ๋ผ.
์ค๋ง์ ๋๋ค. ๊ฐ์ธ์ ์๊ฐ์๋ ํ๊ณ๊ฐ ์๊ณ , ๋ซ๋ฆฐ ํ์๋ ๋ฆ์ต๋๋ค.
escape ๋ ํ๋ก๊ทธ๋๋จธ์ ๊ธฐ๋ณธ ์์ ์ ๋๋ค.
์ถ์ฒ : http://phpschool.com