Database

[Database] SQL Injection

quedevel 2023. 3. 25. 18:56
728x90
๋ฐ˜์‘ํ˜•

๐ŸŽฏ SQL Injection


SQL Injection์€ ์•…์˜์ ์ธ ์‚ฌ์šฉ์ž๊ฐ€ ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ์ž…๋ ฅ ํผ ๋“ฑ์„ ํ†ตํ•ด SQL ์ฟผ๋ฆฌ๋ฌธ์„ ์กฐ์ž‘ํ•˜์—ฌ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์— ๋Œ€ํ•œ ๋น„์ธ๊ฐ€๋œ ์ ‘๊ทผ ๋ฐ ์กฐ์ž‘์„ ์‹œ๋„ํ•˜๋Š” ๊ณต๊ฒฉ ๊ธฐ๋ฒ•์ž…๋‹ˆ๋‹ค.


SQL Injection example


์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์—์„œ ์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•œ ๊ฐ’์„ ๊ธฐ๋ฐ˜์œผ๋กœ SQL ์ฟผ๋ฆฌ๋ฌธ์„ ์ƒ์„ฑํ•  ๋•Œ, ์‚ฌ์šฉ์ž์˜ ์ž…๋ ฅ๊ฐ’์ด ๊ทธ๋Œ€๋กœ ์ฟผ๋ฆฌ๋ฌธ์— ํฌํ•จ๋˜๋Š” ๊ฒฝ์šฐ์— ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์•…์˜์ ์ธ ์‚ฌ์šฉ์ž๋Š” ์ž…๋ ฅ๊ฐ’์— SQL ์ฟผ๋ฆฌ๋ฌธ์„ ํฌํ•จ์‹œ์ผœ ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค๋ฅผ ์กฐ์ž‘ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด, ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋กœ๊ทธ์ธ ์ฟผ๋ฆฌ๋ฌธ์ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค.

SELECT * FROM users WHERE username = '์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’1' AND password = '์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’2'

์ด ๋•Œ, ์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’1์— ' OR '1'='1'์„ ์ž…๋ ฅํ•˜๋ฉด ์ฟผ๋ฆฌ๋ฌธ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ณ€๊ฒฝ๋ฉ๋‹ˆ๋‹ค.

SELECT * FROM users WHERE username = '' OR '1'='1' AND password = '์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’2'

์ด ๊ฒฝ์šฐ, '1':'1' ์€ ํ•ญ์ƒ ์ฐธ์ด๋ฏ€๋กœ WHERE ์ ˆ์ด ํ•ญ์ƒ ์ฐธ์ด ๋˜์–ด ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค์˜ ๋ชจ๋“  ์‚ฌ์šฉ์ž ์ •๋ณด๊ฐ€ ๋ฐ˜ํ™˜๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด๋ฅผ ํ†ตํ•ด ์•…์˜์ ์ธ ์‚ฌ์šฉ์ž๋Š” ๋กœ๊ทธ์ธ ์ •๋ณด๋ฅผ ์•Œ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.


SQL Injection ๋ฐฉ์–ด


  1. Prepared Statements ์‚ฌ์šฉ: Prepared Statements๋Š” ์ž…๋ ฅ๊ฐ’์— ๋Œ€ํ•œ SQL ์ฟผ๋ฆฌ๋ฌธ์„ ๋ฏธ๋ฆฌ ์ปดํŒŒ์ผํ•˜์—ฌ ์บ์‹œ์— ์ €์žฅํ•˜๋Š” ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค. ์ด๋ฅผ ํ†ตํ•ด ์ž…๋ ฅ๊ฐ’์„ ๊ทธ๋Œ€๋กœ ์ฟผ๋ฆฌ๋ฌธ์— ํฌํ•จ์‹œํ‚ค๋Š” ๋Œ€์‹ , ์ฟผ๋ฆฌ๋ฌธ๊ณผ ์ž…๋ ฅ๊ฐ’์„ ๋ณ„๋„๋กœ ์ „๋‹ฌํ•˜์—ฌ ์ฟผ๋ฆฌ๋ฌธ ์กฐ์ž‘์„ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users WHERE username = ? AND password = ?");
stmt.setString(1, ์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’1);
stmt.setString(2, ์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’2);
ResultSet rs = stmt.executeQuery();
  1. ์ž…๋ ฅ๊ฐ’ ๊ฒ€์ฆ: ์ž…๋ ฅ๊ฐ’์„ ๊ฒ€์ฆํ•˜์—ฌ ์ฟผ๋ฆฌ๋ฌธ์— ์•…์˜์ ์ธ ์ฝ”๋“œ๊ฐ€ ํฌํ•จ๋˜์ง€ ์•Š๋„๋ก ํ•˜๋Š” ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’์— ๋Œ€ํ•ด ์ •๊ทœ์‹ ๊ฒ€์ฆ์„ ์ˆ˜ํ–‰ํ•˜์—ฌ ํŠน์ˆ˜๋ฌธ์ž ๋“ฑ์„ ํ•„ํ„ฐ๋งํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
if(!Pattern.matches("[a-zA-Z0-9]+", ์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’1)){
    // ์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’1์— ํŠน์ˆ˜๋ฌธ์ž๊ฐ€ ํฌํ•จ๋˜์–ด ์žˆ์„ ๊ฒฝ์šฐ ์ฒ˜๋ฆฌ
}

์ด ์™ธ์—๋„, ์‚ฌ์šฉ์ž ์ž…๋ ฅ๊ฐ’์„ ์ธ์ฝ”๋”ฉํ•˜๊ฑฐ๋‚˜ SQL ์ฟผ๋ฆฌ๋ฌธ์˜ ์‹คํ–‰ ๊ถŒํ•œ์„ ์ตœ์†Œํ•œ์œผ๋กœ ๋ถ€์—ฌํ•˜๋Š” ๋“ฑ์˜ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜์—ฌ SQL Injection์„ ๋ฐฉ์–ดํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•

'Database' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[Database] ์ •๊ทœํ™”(Normalization)  (0) 2023.03.26
[Database] SQL vs NoSQL  (0) 2023.03.26
[Database] JOIN  (0) 2023.03.25
[Database] Key  (0) 2023.03.25
[Database] MySQL to Oracle  (0) 2021.07.31