language
stringclasses
10 values
tag
stringclasses
34 values
vulnerability_type
stringlengths
4
68
βŒ€
description
stringlengths
7
146
βŒ€
vulnerable_code
stringlengths
14
1.96k
secure_code
stringlengths
18
3.21k
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
SQL μ‚½μž…
SQL μ§ˆμ˜λ¬Έμ„ 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ 질의문이 μ‹€ν–‰κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const mysql = require("mysql"); // 컀λ„₯μ…˜ μ΄ˆκΈ°ν™” μ˜΅μ…˜μ€ μƒλž΅ν•¨ const connection = mysql.createConnection(...); router.get("/vuln/email", (req, res) => { const con = connection; const userInput = req.query.id; // μ‚¬μš©μžλ‘œλΆ€ν„° μž…λ ₯받은 값을 검증 없이 κ·ΈλŒ€λ‘œ 쿼리에 μ‚¬μš© const query = `SELECT email FROM user WHERE user_id = ${userInput}`; con.query(query, (err, result) => { if (err) console.log(err); return res.send(result); } ); });
const mysql = require("mysql"); ... router.get("/patched/email", (req, res) => { const con = connection; const userInput = req.query.id; const query = β€˜SELECT email FROM user WHERE user_id = ?β€˜; // 쿼리 ν•¨μˆ˜μ— μ‚¬μš©μž μž…λ ₯값을 λ§€κ°œλ³€μˆ˜ ν˜•νƒœλ‘œ 전달, μ΄λ ‡κ²Œ μž‘μ„±ν•˜λ©΄ μ‚¬μš©μž μž…λ ₯값에 // escape 처리λ₯Ό ν•œ 것과 λ™μΌν•œ κ²°κ³Όκ°€ μ‹€ν–‰ con.query(query, userInput, (err, result) => { if (err) console.log(err); return res.send(result); } ); });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
SQL μ‚½μž…
SQL μ§ˆμ˜λ¬Έμ„ 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ 질의문이 μ‹€ν–‰κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const mysql = require("mysql"); const Sequelize = require("sequelize"); const { QueryTypes } = require(β€œsequelize”); // 컀λ„₯μ…˜ 및 ORM μ΄ˆκΈ°ν™” μ˜΅μ…˜μ€ μƒλž΅ν•¨ const connection = mysql.createConnection(...); const sequelize = new Sequelize(...); router.get("/vuln/orm/email", (req, res) => { const userInput = req.query.id; // μ‚¬μš©μžλ‘œλΆ€ν„° μž…λ ₯받은 값을 검증 없이 κ·ΈλŒ€λ‘œ 쿼리에 μ‚¬μš© const query = `SELECT email FROM user WHERE user_id = ${userInput}`; sequelize.query(query, { type: QueryTypes.SELECT }) .then((result) => { return res.send(result); }).catch((err) => { console.log(err); }); });
router.get("/vuln/orm/email", (req, res) => { const userInput = req.query.id; // 쿼리 λ‚΄μ—μ„œ 바인딩이 ν•„μš”ν•œ 뢀뢄을 $number둜 ν‘œκΈ° const query = `SELECT email FROM user WHERE user_id = $1`; // μΈμžν™”λœ 쿼리 κΈ°λŠ₯을 톡해 쿼리λ₯Ό 생성 및 μ‹€ν–‰ sequelize.query(query, { bind: [userInput], type: QueryTypes.SELECT }) .then((result) => { return res.send(result); }).catch((err) => { console.log(err); }); });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
μ½”λ“œ μ‚½μž…
ν”„λ‘œμ„ΈμŠ€κ°€ μ™ΈλΆ€ μž…λ ₯값을 μ½”λ“œ(λͺ…λ Ήμ–΄)둜 해석·싀행할 수 있고 ν”„λ‘œμ„ΈμŠ€μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•œ 경우 μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); router.post("/vuln/server", (req, res) => { // μ‚¬μš©μžλ‘œλΆ€ν„° 전달 받은 값을 κ·ΈλŒ€λ‘œ eval ν•¨μˆ˜μ˜ 인자둜 전달 const data = eval(req.body.data); return res.send({ data }); });
const express = require('express'); function alphanumeric(input_text) { // μ •κ·œν‘œν˜„μ‹ 기반 λ¬Έμžμ—΄ 검사 const letterNumber = /^[0-9a-zA-Z]+$/; if (input_text.match(letterNumber)) { return true; } else { return false; } } router.post("/patched/server", (req, res) => { let ret = null; const { data } = req.body; // μ‚¬μš©μž μž…λ ₯을 영문, 숫자둜 μ œν•œν•˜λ©°, λ§Œμ•½ μž…λ ₯κ°’ 내에 νŠΉμˆ˜λ¬Έμžκ°€ ν¬ν•¨λ˜μ–΄ // μžˆμ„ 경우 μ—λŸ¬ λ©”μ‹œμ§€λ₯Ό λ°˜ν™˜ if (alphanumeric(data)) { ret = eval(data); } else { ret = β€˜error’; } return res.send({ ret }); });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
경둜 μ‘°μž‘ 및 μžμ› μ‚½μž…
μ‹œμŠ€ν…œ μžμ› μ ‘κ·Όκ²½λ‘œ λ˜λŠ” μžμ›μ œμ–΄ λͺ…령어에 κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‹œμŠ€ν…œ μžμ›μ— 무단 μ ‘κ·Ό 및 μ•…μ˜μ μΈ ν–‰μœ„κ°€ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const path = require('path'); router.get("/vuln/file", (req, res) => { // μ™ΈλΆ€ μž…λ ₯κ°’μœΌλ‘œλΆ€ν„° 파일λͺ…을 μž…λ ₯ λ°›μŒ const requestFile = req.query.file; // μž…λ ₯값을 검증 없이 파일 μ²˜λ¦¬μ— μ‚¬μš© fs.readFile(path.resolve(__dirname, requestFile), 'utf8', function(err, data) { if (err) { return res.send('error'); } return res.send(data); }) });
const express = require('express'); const path = require('path'); router.get("/patched/file", (req, res) => { const requestFile = req.query.file; // μ •κ·œν‘œν˜„μ‹μ„ μ‚¬μš©ν•΄ μ‚¬μš©μž μž…λ ₯값을 필터링 const filtered = requestFile.replace(/[.\\\/]/gi, ''); fs.readFile(filtered, 'utf8', function(err, data) { if (err) { return res.send('error'); } return res.send(data); }) });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
경둜 μ‘°μž‘ 및 μžμ› μ‚½μž…
μ‹œμŠ€ν…œ μžμ› μ ‘κ·Όκ²½λ‘œ λ˜λŠ” μžμ›μ œμ–΄ λͺ…령어에 κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‹œμŠ€ν…œ μžμ›μ— 무단 μ ‘κ·Ό 및 μ•…μ˜μ μΈ ν–‰μœ„κ°€ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const io = require("socket.io"); router.get("/vuln/socket", (req, res) => { try { // μ™ΈλΆ€λ‘œλΆ€ν„° μž…λ ₯받은 κ²€μ¦λ˜μ§€ μ•Šμ€ μ£Όμ†Œλ₯Ό μ΄μš©ν•˜μ—¬ // μ†ŒμΌ“μ„ 바인딩 ν•˜μ—¬ μ‚¬μš©ν•˜κ³  μžˆμ–΄ μ•ˆμ „ν•˜μ§€ μ•ŠμŒ const socket = io(req.query.url); return res.send(socket); } catch (err) { return res.send("[error] fail to connect"); } });
const express = require('express'); const io = require("socket.io"); router.get("/patched/socket", (req, res) => { // ν™”μ΄νŠΈλ¦¬μŠ€νŠΈ 내에 μ†ν•˜λŠ” μ£Όμ†Œλ§Œ ν—ˆμš© const whitelist = ["ws://localhost", "ws://127.0.0.1"]; if (whitelist.indexOf(req.query.url) < 0) { return res.send("wrong url"); } try { const socket = io(req.query.url); return res.send(socket); } catch (err) { return res.send("[error] fail to connect"); } });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ 슀크립트(XSS)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ μŠ€ν¬λ¦½νŠΈκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
<html> <body> <script> const query = "<script>alert('hello world')<"+"/script>"; async function req() { // μ‚¬μš©μžκ°€ 에디터와 같은 μž…λ ₯ 폼에 μž…λ ₯ν•œ 데이터λ₯Ό μ„œλ²„μ— μ €μž₯ const response = await fetch(`/vuln/search?q=${query}`, { method: 'GET' }) const data = await response.text(); // μ™ΈλΆ€λ‘œλΆ€ν„° 받은 데이터(HTML μ½”λ“œ)λ₯Ό μ•„λ¬΄λŸ° 검증 없이 DOM으둜 기둝 document.write(data); } req(); </script> </body> </html>
<html> <body> <script> const query = "<script>alert('hello world')<"+"/script>"; async function req() { const response = await fetch(`/vuln/search?q=${query}`, { method: 'GET' }) const data = await response.text(); // μ™ΈλΆ€λ‘œλΆ€ν„° 받은 데이터λ₯Ό μ΄μŠ€μΌ€μ΄ν”„ 처리 ν›„ μ‚¬μš© document.write(decodeURI(encodeURIComponent(data))); } req(); </script> </body> </html>
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ 슀크립트(XSS)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ μŠ€ν¬λ¦½νŠΈκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
<html> <body> <script> const query = "<script>alert('hello world')<"+"/script>"; async function req() { // μ‚¬μš©μžκ°€ 에디터와 같은 μž…λ ₯ 폼에 μž…λ ₯ν•œ 데이터λ₯Ό μ„œλ²„μ— μ €μž₯ const response = await fetch(`/vuln/search?q=${query}`, { method: 'GET' }) const data = await response.text(); // μ™ΈλΆ€λ‘œλΆ€ν„° 받은 데이터(HTML μ½”λ“œ)λ₯Ό μ•„λ¬΄λŸ° 검증 없이 DOM으둜 기둝 document.write(data); } req(); </script> </body> </html>
<html> <head> <script src="https://cdn.rawgit.com/yahoo/xss-filters/master/dist/xss-filters.js"></script> </head> <body> <script> async function req() { ... // xss-filters 라이브러리λ₯Ό μ‚¬μš©ν•΄ λ¬Έμžμ—΄μ„ μ΄μŠ€μΌ€μ΄ν”„ 처리 document.write(xssFilters.inHTMLData(data)); } req(); </script> </body> </html>
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ 슀크립트(XSS)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ μŠ€ν¬λ¦½νŠΈκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
function possibleXSS() { return { __html: '<img src="https://upload.wikimedia.org/wikipedia/commons/a/a7/React-icon.svgβ€œ onload="alert(1)"> </img>', }; } const App = ( ) => ( // XSS에 μ·¨μ•½ν•œ ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄ HTML μ½”λ“œ 데이터λ₯Ό λ Œλ”λ§ <div dangerouslySetInnerHTML={possibleXSS()} /> ); ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.4.0/purify.min.js"></script> ... function possibleXSS() { return { __html: // dompurify 라이브러리λ₯Ό μ‚¬μš©ν•΄ μž…λ ₯값을 μ΄μŠ€μΌ€μ΄ν”„ 처리 DOMPurify.sanitize('<img src="https://upload.wikimedia.org/wikipedia/commons/ a/a7/React-icon.svg" onload="alert(1)"></img>'), }; } const App = ( ) => ( <div dangerouslySetInnerHTML={possibleXSS()} /> ); ReactDOM.render(<App />, document.getElementById("root"));
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ 슀크립트(XSS)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ μŠ€ν¬λ¦½νŠΈκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); router.get("/vuln/search", (req, res) => { // μ‚¬μš©μžλ‘œλΆ€ν„° 전달 받은 쿼리 λ°μ΄ν„°λ‘œ 데이터 쑰회 const results = selectFromDB(req.query.q); if (results.length === 0) { // 검색 κ²°κ³Όκ°€ λ°œκ²¬λ˜μ§€ μ•Šμ„ 경우, β€˜μš”μ²­ν•œ 값’을 찾지 λͺ»ν–ˆλ‹€λŠ” λ©”μ‹œμ§€λ₯Ό λ°˜ν™˜ν•˜λŠ”λ°, // 이 λ•Œ 정상적인 질의문이 μ•„λ‹Œ μ•…μ„± μŠ€ν¬λ¦½νŠΈκ°€ ν¬ν•¨λœ 데이터λ₯Ό μž…λ ₯ 받은 경우라면 // ν΄λΌμ΄μ–ΈνŠΈμΈ‘μ—μ„œ μ•…μ„± μŠ€ν¬λ¦½νŠΈκ°€ 싀행될 수 있음 return res.send('<p>No results found for "' + req.query.q + '"</p>'); } ... });
const express = require('express'); const xssFilters = require("xss-filters"); ... router.get("/patched/search", (req, res) => { const unsafeFirstname = req.query.q; // xss-filters 라이브러리λ₯Ό μ‚¬μš©ν•΄ μ‚¬μš©μž μž…λ ₯값을 μ΄μŠ€μΌ€μ΄ν”„ 처리 const safeFirstname = xssFilters.inHTMLData(unsafeFirstname); const results = selectFromDB(safeFirstname); if (results.length === 0) { res.send(util.format("<p>Hello %s</p>", safeFirstname)); } ... });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
운영체제 λͺ…λ Ήμ–΄ μ‚½μž…
운영체제 λͺ…λ Ήμ–΄λ₯Ό 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ λͺ…λ Ήμ–΄κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const child_process = require("child_process"); router.get("/vuln", (req, res) => { // μ‚¬μš©μžκ°€ μž…λ ₯ν•œ λͺ…λ Ήμ–΄ μΈμžκ°’μ„ 검증 없이 μ‚¬μš©ν•΄ μ˜λ„μΉ˜ μ•Šμ€ μΆ”κ°€ λͺ…λ Ήμ–΄ μ‹€ν–‰ κ°€λŠ₯ child_process.exec("ls -l " + req.query.path, function (err, data) { return res.send(data); }); });
const express = require('express'); const child_process = require("child_process"); router.get("/patched", (req, res) => { const inputPath = req.query.path; const regPath = /^(\/[\w^]+)+\/?$/; // 첫 번째 방법, μ‚¬μš©μž μž…λ ₯κ°’ 필터링 ? λ¦¬λˆ…μŠ€ 경둜 지정에 ν•„μš”ν•œ 문자만 ν—ˆμš© if (!inputPath.match(regPath)) { return res.send('not valid path'); } // 두 번째 방법, μ‚¬μš©μž μž…λ ₯값이 λͺ…λ Ήμ–΄μ˜ 인자둜만 μ‚¬μš©λ˜λ„λ‘ ν•˜λŠ” ν•¨μˆ˜ μ‚¬μš© child_process.execFile( "/bin/ls", ["-l", inputPath], function (err, data) { if (err) { return res.send('not valid path'); } else { return res.send(data); } } ); });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
μœ„ν—˜ν•œ ν˜•μ‹ 파일 μ—…λ‘œλ“œ
파일의 ν™•μž₯자 λ“± νŒŒμΌν˜•μ‹μ— λŒ€ν•œ 검증없이 파일 μ—…λ‘œλ“œλ₯Ό ν—ˆμš©ν•˜μ—¬ 곡격이 κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); router.post("/vuln", (req, res) => { const file = req.files.products; const fileName = file.name; // μ—…λ‘œλ“œ ν•œ 파일 νƒ€μž… 검증 λΆ€μž¬λ‘œ μ•…μ„± 슀크립트 파일 μ—…λ‘œλ“œ κ°€λŠ₯ file.mv("/usr/app/temp/" + fileName, (err) => { if (err) return res.send(err); res.send("upload success"); }); });
const express = require('express'); router.post("/patched", (req, res) => { const allowedMimeTypes = ["image/png", "image/jpeg"]; const allowedSize = 5242880; const file = req.files.products; const fileName = file.name; // μ—…λ‘œλ“œ ν•œ 파일 νƒ€μž… 검증을 톡해 μ•…μ„± 슀크립트 파일 μ—…λ‘œλ“œ 방지 if (allowedMimeTypes.indexOf(file.mimetype) < 0) { res.send("file type not allowed"); } else { file.mv("/usr/app/temp/" + fileName, (err) => { if (err) return res.send(err); res.send("upload success"); }); } });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
μ‹ λ’°λ˜μ§€ μ•Šμ€ URLμ£Όμ†Œλ‘œ μžλ™μ ‘μ† μ—°κ²°
URL 링크 생성에 κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ μ‚¬μ΄νŠΈλ‘œ μžλ™ 접속 κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); router.get("/vuln", (req, res) => { const url = req.query.url; // μ‚¬μš©μžκ°€ μ „λ‹¬ν•œ URL μ£Όμ†Œλ₯Ό 검증 없이 κ·ΈλŒ€λ‘œ λ¦¬λ‹€μ΄λ ‰νŠΈ 처리 res.redirect(url); });
const express = require('express'); router.get("/patched", (req, res) => { const whitelist = ["http://safe-site.com", "https://www.example.com"]; const url = req.query.url; // ν™”μ΄νŠΈλ¦¬μŠ€νŠΈμ— ν¬ν•¨λœ μ£Όμ†Œκ°€ μ•„λ‹ˆλΌλ©΄ λ¦¬λ‹€μ΄λ ‰νŠΈ 없이 μ—λŸ¬ λ°˜ν™˜ if (whitelist.indexOf(url) < 0) { res.send("wrong url"); } else { res.redirect(url); } });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
λΆ€μ μ ˆν•œ XML μ™ΈλΆ€ 개체 μ°Έμ‘°
μž„μ˜λ‘œ μ‘°μž‘λœ XML μ™ΈλΆ€κ°œμ²΄μ— λŒ€ν•œ μ μ ˆν•œ 검증 없이 μ°Έμ‘°λ₯Ό ν—ˆμš©ν•˜μ—¬ 곡격이 κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const libxmljs = require("libxmljs"); router.post("/vuln", (req, res) => { if (req.files.products && req.files.products.mimetype == "application/xml") { const products = libxmljs.parseXmlString( req.files.products.data.toString("utf8"), // μ™ΈλΆ€ μ—”ν‹°ν‹° νŒŒμ‹± ν—ˆμš© μ„€μ •(λ―Έμ„€μ • μ‹œ 기본값은 false) { noent: true } ); return res.send(products.get("//foo").text()); } return res.send("fail"); });
const express = require('express'); const libxmljs = require("libxmljs"); router.post("/patched", (req, res) => { if (req.files.products && req.files.products.mimetype == "application/xml") { const products = libxmljs.parseXmlString( req.files.products.data.toString("utf8"), // μ™ΈλΆ€ μ—”ν‹°ν‹° νŒŒμ‹±μ„ ν—ˆμš©ν•˜μ§€ μ•Šλ„λ‘ μ„€μ • // λ―Έμ„€μ • μ‹œ 기본값은 falseμ΄μ§€λ§Œ, λͺ…μ‹œμ μœΌλ‘œ 선언을 ν•΄ μ£ΌλŠ” 것이 μ’‹μŒ { noent: false } ); return res.send(products.get("//foo").text()); } return res.send("fail"); });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
XML μ‚½μž…
XQuery, XPath μ§ˆμ˜λ¬Έμ„ 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ 질의문이 μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const xpath = require('xpath'); const dom = require('xmldom').DOMParser; const xml = `<users> <user> <login>john</login> <password>abracadabra</password> <home_dir>/home/john</home_dir> </user> <user> <login>cbc</login> <password>1mgr8</password> <home_dir>/home/cbc</home_dir> </user> </users>`; router.get("/vuln", (req, res) => { const userName = req.query.userName; const userPass = req.query.userPass; const doc = new dom().parseFromString(xml); // μ‘°μž‘λœ μž…λ ₯κ°’(/vuln?userName=john' or ''='&userPass="' or ''='β€œ)을 톡해 // νŒ¨μŠ€μ›Œλ“œ 검사 λ‘œμ§μ„ μš°νšŒν•  수 있음 const badXPathExpr = "//users/user[login/text()='" + userName + "' and password/text() = '" + userPass + "']/home_dir/text()"; const selected = xpath.select(badXPathExpr, doc); try { const userPath = selected[0].toString(); return res.send(`userPath = ${userPath}`); } catch { return res.send('not found'); } });
const express = require('express'); const xpath = require('xpath'); const dom = require('xmldom').DOMParser; const xml = `<users> ... </users>`; router.get("/patched", (req, res) => { const userName = req.query.userName; const userPass = req.query.userPass; const doc = new dom().parseFromString(xml); // μΈμžν™”λœ 쿼리 생성 const goodXPathExpr = xpath.parse("//users/user[login/text()=$userName and password/text() =$userPass]/home_dir/text()"); // 쿼리문에 λ³€μˆ˜κ°’ 전달 및 XML 쑰회 const selected = goodXPathExpr.select({ node: doc, variables: { userName: userName, userPass: userPass } }); try { const userPath = selected[0].toString(); return res.send(`userPath = ${userPath}`); } catch { return res.send('not found'); } });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
LDAP μ‚½μž…
LDAP λͺ…령문을 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ λͺ…λ Ήμ–΄κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const ldap = require('ldapjs'); const config = { url: 'ldap://ldap.forumsys.com', base: 'dc=example,dc=com', dn: 'cn=read-only-admin,dc=example,dc=com', secret: 'd0accf0ac0dfb0d0fd...', }; async function searchLDAP (search) { const opts = { filter: `(&(objectClass=${search}))`, attributes: ['sn', 'cn', 'mail', 'telephonenumber', 'uid'], scope: 'sub', }; const users = []; const client = ldap.createClient({ url: config.url }); return new Promise((resolve, reject) => { client.bind(config.dn, config.password, (err) => { if (err) { console.log('LDAP bind error - ', err); } else { client.search(config.base, opts, (err, res) => { res.on('searchEntry', (entry) => { users.push(entry.object); }); ... res.on('end', (result) => { console.log('status: ' + result.status); resolve(users); }); }); } }); }); } router.get("/vuln", async (req, res) => { // μ‚¬μš©μžμ˜ μž…λ ₯을 κ·ΈλŒ€λ‘œ LDAP 질의문으둜 μ‚¬μš©ν•΄ κΆŒν•œ μƒμŠΉ λ“±μ˜ 곡격에 λ…ΈμΆœ const search = req.query.search; const result = await searchLDAP(search); return res.send(result); });
const express = require('express'); const ldap = require('ldapjs'); const parseFilter = require('ldapjs').parseFilter; const config = { url: 'ldap://ldap.forumsys.com', base: 'dc=example,dc=com', dn: 'cn=read-only-admin,dc=example,dc=com', secret: 'd0accf0ac0dfb0d0fd...', }; async function searchLDAP (search) { const opts = { filter: `(&(objectClass=${search}))`, attributes: ['sn', 'cn', 'mail', 'telephonenumber', 'uid'], scope: 'sub', }; const users = []; const client = ldap.createClient({ url: config.url }); return new Promise((resolve, reject) => { client.bind(config.dn, config.password, (err) => { if (err) { console.log('LDAP bind error - ', err); } else { client.search(config.base, opts, (err, res) => { res.on('searchEntry', (entry) => { users.push(entry.object); }); ... res.on('end', (result) => { console.log('status: ' + result.status); resolve(users); }); }); } }); }); } router.get("/patched", async (req, res) => { let search; // μ‚¬μš©μžμ˜ μž…λ ₯에 필터링을 μ μš©ν•΄ 곡격에 μ‚¬μš©λ  수 μžˆλŠ” 문자 발견 μ‹œ // μ‚¬μš©μžμ—κ²Œ 잘λͺ»λœ μš”μ²­κ°’μž„μ„ μ•Œλ¦¬κ³ , μ§ˆμ˜λ¬Έμ„ μš”μ²­ν•˜μ§€ μ•ŠμŒ try { search = parseFilter(req.query.search); } catch { return res.send('잘λͺ»λœ μš”μ²­κ°’μž…λ‹ˆλ‹€.'); } const result = await searchLDAP(search); return res.send(result); });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ μš”μ²­ μœ„μ‘°(CSRF)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‚¬μš©μž 본인의 μ˜μ§€μ™€λŠ” λ¬΄κ΄€ν•˜κ²Œ κ³΅κ²©μžκ°€ μ˜λ„ν•œ ν–‰μœ„κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
<html> ... <body> <form method='post' action='/api/vuln'> <!-- CSRF 토큰 없이 폼 데이터λ₯Ό μ„œλ²„μ— 전달 --> <fieldset> <legend>Your Profile:</legend> <label for='username'> Name:</label> <input name='username' class='username' type='text'> <br><br> <label for='email' > Email:</label> <input name='email' class='useremail' type='email'> <br><br> <button type='submit'>UPDATE</button> </fieldset> </form> </body> </html>
<form method='post' action='/api/vuln'> <!-- μ„œλ²„λ‘œλΆ€ν„° 제곡 받은 CSRF 토큰을 폼 데이터에 hidden κ°’μœΌλ‘œ 포함해 전달 --> <input type='hidden' name='_csrf' value='<%= csrfToken %>'> <fieldset> <legend>Your Profile:</legend> <label for='username'> Name:</label> <input name='username' class='username' type='text'> <br><br> <label for='email' > Email:</label> <input name='email' class='useremail' type='email'> <br><br> <button type='submit'>UPDATE</button> </fieldset> </form>
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ μš”μ²­ μœ„μ‘°(CSRF)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‚¬μš©μž 본인의 μ˜μ§€μ™€λŠ” λ¬΄κ΄€ν•˜κ²Œ κ³΅κ²©μžκ°€ μ˜λ„ν•œ ν–‰μœ„κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); router.post("/api/vuln", (req, res) => { const userName = req.body.username; const userEmail = req.body.useremail; // μ‚¬μš©μž μ—…λ°μ΄νŠΈ μš”μ²­μ΄ 정상 μ‚¬μš©μžλ‘œλΆ€ν„° 온 것이라고 κ°„μ£Όν•˜κ³ , // μ‚¬μš©μžλ‘œλΆ€ν„° 받은 값을 κ·ΈλŒ€λ‘œ λ‚΄λΆ€ ν•¨μˆ˜μ— 전달 if (update_user(userName, userEmail)) { return res.send('update completed'); } else { return res.send('update error'); } });
const csrf = require('csurf'); const express = require('express'); const session = require("express-session"); const app = express(); // 토큰을 μΏ ν‚€κ°€ μ•„λ‹Œ μ„Έμ…˜μ— μ €μž₯ app.use(session({ secret: process.env.COOKIE_SECRET, cookie: { path: '/', secure: true, httpOnly: true, sameSite: 'strict' }, saveUninitialized: false, resave: false })); // CSRF 토큰 이름 μ•žμ— __Host- 접두어 μΆ”κ°€ const csrfProtection = csrf({ key: '__Host-token', }); // ν΄λΌμ΄μ–ΈνŠΈμΈ‘ ν”„λ ˆμž„μ›Œν¬(ReactJS)λ₯Ό μœ„ν•œ 토큰 κ°’ 제곡 router.get("/getCSRFToken", csrfProtection, (req, res) => { res.json({ csrfToken: req.csrfToken() }); }); // ν…œν”Œλ¦Ώ νŽ˜μ΄μ§€λ₯Όμœ„ν•œ 토큰 κ°’ 제곡 router.get("/page", csrfProtection, (req, res) => { res.render('csrf', { csrfToken: req.csrfToken() }); }); // λΌμš°ν„° 데이터 처리 μ „ ν΄λΌμ΄μ–ΈνŠΈμ˜ csrf 토큰을 검사 router.post("/api/patched", csrfProtection, (req, res) => { const userName = req.body.username; const userEmail = req.body.useremail; if (update_user(userName, userEmail)) { return res.send('update completed'); } else { return res.send('update error'); } });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ μš”μ²­ μœ„μ‘°(CSRF)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‚¬μš©μž 본인의 μ˜μ§€μ™€λŠ” λ¬΄κ΄€ν•˜κ²Œ κ³΅κ²©μžκ°€ μ˜λ„ν•œ ν–‰μœ„κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
ν΄λΌμ΄μ–ΈνŠΈμΈ‘μ—μ„œ λ Œλ”λ§μ„ μ²˜λ¦¬ν•˜λŠ” ReactJS의 경우 μ„œλ²„ κΈ°λŠ₯ 호좜 μ „ μ„œλ²„λ‘œλΆ€ν„° 토큰을 받아와 μš”μ²­ 헀더 내에 μ‚½μž…ν•΄μ•Ό ν•œλ‹€
const App = () => { const getData = async () => { // μ„œλ²„μ— κΈ°λŠ₯ 호좜 μ „ λ¨Όμ € CSRF 토큰을 받아와 헀더에 μ €μž₯ const response = await axios.get('getCSRFToken'); axios.defaults.headers.post['X-CSRF-Token'] = response.data.csrfToken; // CSRF 토큰이 μ„€μ •λœ μƒνƒœμ—μ„œ μ„œλ²„ κΈ°λŠ₯ 호좜 const res = await axios.post('api/patched', { username: β€˜hello_user’, useremail: β€˜[email protected]’, }); document.write(res.data); }; React.useEffect(() => { getData(); }, []); return <div>react-test</div>; }; ReactDOM.render(<App />, document.getElementById("root"));
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
μ„œλ²„μ‚¬μ΄λ“œ μš”μ²­ μœ„μ‘°
μ„œλ²„ κ°„ μ²˜λ¦¬λ˜λŠ” μš”μ²­μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ κ³΅κ²©μžκ°€ μ˜λ„ν•œ μ„œλ²„λ‘œ 전솑 ν•˜κ±°λ‚˜ λ³€μ‘°ν•˜λŠ” λ³΄μ•ˆμ•½μ 
const request = require('request'); const express = require('express'); router.get("/vuln", async (req, res) => { const url = req.query.url; // μ‚¬μš©μžκ°€ μž…λ ₯ν•œ μ£Όμ†Œλ₯Ό κ²€μ¦ν•˜μ§€ μ•Šκ³  HTTP μš”μ²­μ„ 보낸 ν›„ // κ·Έ 응닡을 κ·ΈλŒ€λ‘œ μ‚¬μš©μžμ—κ²Œ 전달 await request(url, (err, response) => { const resData = response.body; return res.send(resData); }); });
const request = require('request'); const express = require('express'); router.get("/patched", async (req, res) => { const url = req.query.url; const whiteList = [ 'www.example.com', 'www.safe.com']; // μ‚¬μš©μžκ°€ μž…λ ₯ν•œ URL을 ν™”μ΄νŠΈλ¦¬μŠ€νŠΈλ‘œ κ²€μ¦ν•œ ν›„ κ·Έ κ²°κ³Όλ₯Ό λ°˜ν™˜ν•˜μ—¬ // κ²€μ¦λ˜μ§€ μ•Šμ€ μ£Όμ†Œλ‘œ μš”μ²­μ„ 보내지 μ•Šλ„λ‘ μ œν•œ if (whiteList.includes(url)) { await request(url, (err, response) => { const resData = response.body; return res.send(resData); }); } else { return res.send('잘λͺ»λœ μš”μ²­μž…λ‹ˆλ‹€'); } });
Javascript
μž…λ ₯데이터 검증 및 ν‘œν˜„
λ³΄μ•ˆκΈ°λŠ₯ 결정에 μ‚¬μš©λ˜λŠ” λΆ€μ μ ˆν•œ μž…λ ₯κ°’
λ³΄μ•ˆκΈ°λŠ₯(인증, κΆŒν•œλΆ€μ—¬ λ“±) 결정에 κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ λ³΄μ•ˆκΈ°λŠ₯을 μš°νšŒν•˜λŠ” λ³΄μ•ˆμ•½μ 
const express = require('express'); router.get("/admin", (req, res) => { // μΏ ν‚€μ—μ„œ κΆŒν•œ 정보λ₯Ό κ°€μ Έμ˜΄ const role = req.cookies.role; if (role === "admin") { // μΏ ν‚€μ—μ„œ κ°€μ Έμ˜¨ κΆŒν•œ μ •λ³΄λ‘œ κ΄€λ¦¬μž νŽ˜μ΄μ§€ 접속 처리 return res.render(β€˜admin’. { title: β€™κ΄€λ¦¬μž νŽ˜μ΄μ§€β€˜ } )); } else { return res.send("μ‚¬μš© κΆŒν•œμ΄ μ—†μŠ΅λ‹ˆλ‹€."); } });
const express = require('express'); const session = require("express-session"); app.use(session({ secret: 'test', resave: true, saveUninitialized: true, store: new MemoryStore({checkPeriod: 60 * 60 * 1000}) })); router.get("/patched", (req, res) => { // μ„Έμ…˜μ—μ„œ κΆŒν•œ 정보λ₯Ό κ°€μ Έμ˜΄ const role = req.session.role; if (role === "admin") { // μ„Έμ…˜μ—μ„œ κ°€μ Έμ˜¨ κΆŒν•œ μ •λ³΄λ‘œ κ΄€λ¦¬μž νŽ˜μ΄μ§€ 접속 처리 return res.render(β€˜admin’. { title: β€™κ΄€λ¦¬μž νŽ˜μ΄μ§€β€˜ } )); } else { return res.send("μ‚¬μš© κΆŒν•œμ΄ μ—†μŠ΅λ‹ˆλ‹€."); } });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μ μ ˆν•œ 인증 μ—†λŠ” μ€‘μš” κΈ°λŠ₯ ν—ˆμš©
μ€‘μš”μ •λ³΄(κΈˆμœ΅μ •λ³΄, κ°œμΈμ •λ³΄, 인증정보 λ“±)λ₯Ό μ μ ˆν•œ 인증없이 μ—΄λžŒ(λ˜λŠ” λ³€κ²½) κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const crypto = require("crypto"); router.post("/vuln", (req, res) => { const newPassword = req.body.newPassword; const user = req.session.userid; const hs = crypto.createHash(β€œsha256”) const newHashPassword = hs.update(newPassword).digest("base64"); // ν˜„μž¬ νŒ¨μŠ€μ›Œλ“œμ™€ 일치 μ—¬λΆ€λ₯Ό ν™•μΈν•˜μ§€ μ•Šκ³  μ—…λ°μ΄νŠΈ updatePasswordFromDB(user, newHashPassword); return res.send({message: "νŒ¨μŠ€μ›Œλ“œκ°€ λ³€κ²½λ˜μ—ˆμŠ΅λ‹ˆλ‹€.", userId, password, hashPassword}); });
const express = require('express'); const crypto = require("crypto"); router.post("/patched", (req, res) => { const newPassword = req.body.newPassword; const user = req.session.userid; const oldPassword = getPasswordFromDB(user); const salt = crypto.randomBytes(16).toString('hex'); const hs = crypto.createHash("sha256β€œ) const currentPassword = req.body.currentPassword; const currentHashPassword = hs.update(currentPassword + salt).digest("base64"); // ν˜„μž¬ νŒ¨μŠ€μ›Œλ“œ 확인 ν›„ μ‚¬μš©μž 정보 μ—…λ°μ΄νŠΈ if (currentHashPassword === oldPassword) { const newHashPassword = hs.update(newPassword + salt).digest("base64"); updatePasswordFromDB(user, newHashPassword); return res.send({ message: "νŒ¨μŠ€μ›Œλ“œκ°€ λ³€κ²½λ˜μ—ˆμŠ΅λ‹ˆλ‹€." }); } else { return res.send({ message: "νŒ¨μŠ€μ›Œλ“œκ°€ μΌμΉ˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€." }); } });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
λΆ€μ μ ˆν•œ 인가
μ€‘μš”μžμ›μ— μ ‘κ·Όν•  λ•Œ μ μ ˆν•œ μ œμ–΄κ°€ μ—†μ–΄ λΉ„μΈκ°€μžμ˜ 접근이 κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); function deleteContentFromDB(contentId) { ... } router.delete("/vuln", (req, res) => { const contentId = req.body.contentId; // μž‘μ—… μš”μ²­μ„ ν•˜λŠ” μ‚¬μš©μžμ˜ κΆŒν•œ 확인 없이 μ‚­μ œ μž‘μ—… μˆ˜ν–‰ deleteContentFromDB(contentId); return res.send("μ‚­μ œκ°€ μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€."); });
const express = require('express'); function deleteContentFromDB(contentId) { ... } router.delete("/patched", (req, res) => { const contentId = req.body.contentId; const role = req.session.role; // μ‚­μ œ κΈ°λŠ₯을 μˆ˜ν–‰ν•  κΆŒν•œμ΄ μžˆλŠ” κ²½μš°μ—λ§Œ μ‚­μ œ μž‘μ—… μˆ˜ν–‰ if (role === "admin") { deleteContentFromDB(contentId); return res.send("μ‚­μ œκ°€ μ™„λ£Œλ˜μ—ˆμŠ΅λ‹ˆλ‹€."); } else { return res.send("κΆŒν•œμ΄ μ—†μŠ΅λ‹ˆλ‹€."); } });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μ€‘μš”ν•œ μžμ›μ— λŒ€ν•œ 잘λͺ»λœ κΆŒν•œ μ„€μ •
μ€‘μš”μžμ›μ— μ μ ˆν•œ μ ‘κ·Ό κΆŒν•œμ„ λΆ€μ—¬ν•˜μ§€ μ•Šμ•„ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœΒ·μˆ˜μ • κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const fs = require("fs"); function writeFile() { // λͺ¨λ“  μ‚¬μš©μžκ°€ 읽기, μ“°κΈ°, μ‹€ν–‰ κΆŒν•œμ„ κ°€μ§€κ²Œ 됨 fs.chmodSync("/root/system_config", 0o777); fs.open("/root/system_config", "w", function(err,fd) { if (err) throw err; }); fs.writeFile("/root/system_config", "your config is broken", function(err) { if (err) throw err; console.log('write end'); }); }
const fs = require("fs"); function writeFile() { // μ†Œμœ μž μ΄μ™Έμ—λŠ” κΆŒν•œμ„ 가지지 μ•ŠμŒ fs.chmodSync("/root/system_config", 0o700); fs.open("/root/system_config", "w", function(err,fd) { if (err) throw err; }); fs.writeFile("/root/system_config", "your config is broken", function(err) { if (err) throw err; console.log('write end'); }) }
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μ·¨μ•½ν•œ μ•”ν˜Έν™” μ•Œκ³ λ¦¬μ¦˜ μ‚¬μš©
μ€‘μš”μ •λ³΄ (κΈˆμœ΅μ •λ³΄, κ°œμΈμ •λ³΄, 인증정보 λ“±)의 기밀성을 보μž₯ν•  수 μ—†λŠ” μ·¨μ•½ν•œ μ•”ν˜Έν™” μ•Œ κ³ λ¦¬μ¦˜μ„ μ‚¬μš©ν•˜μ—¬ 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const crypto = require("crypto"); function getEncText(plainText, key) { // μ·¨μ•½ν•œ μ•Œκ³ λ¦¬μ¦˜μΈ DESλ₯Ό μ‚¬μš©ν•˜μ—¬ μ•ˆμ „ν•˜μ§€ μ•ŠμŒ const cipherDes = crypto.createCipheriv('des-ecb', key, ''); const encryptedData = cipherDes.update(plainText, 'utf8', 'base64'); const finalEnctypedData = cipherDes.final('base64'); return encryptedData + finalEnctypedData; }
const crypto = require("crypto"); function getEncText(plainText, key, iv) { // ꢌμž₯ μ•Œκ³ λ¦¬μ¦˜μΈ AESλ₯Ό μ‚¬μš©ν•˜μ—¬ μ•ˆμ „ν•¨ const cipherAes = crypto.createCipheriv('aes-256-cbc', key, iv); const encryptedData = cipherAes.update(plainText, 'utf8', 'base64'); const finalEnctypedData = cipherAes.final('base64'); return encryptedData + finalEnctypedData; }
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μ·¨μ•½ν•œ μ•”ν˜Έν™” μ•Œκ³ λ¦¬μ¦˜ μ‚¬μš©
μ€‘μš”μ •λ³΄ (κΈˆμœ΅μ •λ³΄, κ°œμΈμ •λ³΄, 인증정보 λ“±)의 기밀성을 보μž₯ν•  수 μ—†λŠ” μ·¨μ•½ν•œ μ•”ν˜Έν™” μ•Œ κ³ λ¦¬μ¦˜μ„ μ‚¬μš©ν•˜μ—¬ 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const crypto = require("crypto"); function makeMd5(plainText) { // μ·¨μ•½ν•œ md5 ν•΄μ‰¬ν•¨μˆ˜ μ‚¬μš© const hashText = crypto.createHash('md5').update(plainText).digest("hex"); return hashText; }
const crypto = require("crypto"); function makeSha256(plainText) { const salt = crypto.randomBytes(16).toString('hex'); // μ•ˆμ „ν•œ sha-256 ν•΄μ‰¬ν•¨μˆ˜ μ‚¬μš© const hashText = crypto.createHash('sha256').update(plainText + salt).digest("hex"); return hashText; }
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μ•”ν˜Έν™”λ˜μ§€ μ•Šμ€ μ€‘μš”μ •λ³΄
μ€‘μš”μ •λ³΄(νŒ¨μŠ€μ›Œλ“œ, κ°œμΈμ •λ³΄ λ“±) 전솑 μ‹œ μ•”ν˜Έν™” λ˜λŠ” μ•ˆμ „ν•œ 톡신채널을 μ΄μš©ν•˜μ§€ μ•Šκ±°λ‚˜, μ €μž₯ μ‹œ μ•”ν˜Έν™” ν•˜μ§€ μ•Šμ•„ 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
function updatePass(dbconn, password, user_id) { // μ•”ν˜Έν™”λ˜μ§€ μ•Šμ€ λΉ„λ°€λ²ˆν˜Έλ₯Ό DB에 μ €μž₯ν•˜λŠ” 경우 μœ„ν—˜ν•¨ const sql = 'UPDATE user SET password=? WHERE user_id=?'; const params = [password, user_id]; dbconn.query(sql, params, function(err, rows, fields){ if (err) console.log(err); }) }
const crypto = require("crypto"); function updatePass(dbconn, password, user_id, salt) { // 단방ν–₯ μ•”ν˜Έν™”λ₯Ό μ΄μš©ν•˜μ—¬ λΉ„λ°€λ²ˆν˜Έλ₯Ό μ•”ν˜Έν™” const sql = 'UPDATE user SET password=? WHERE user_id=?'; const hashPw = crypto.createHash('sha256').update(password + salt, 'utf-8').digest('hex'); const params = [hashPw, user_id]; dbconn.query(sql, params, function(err, rows, fields){ if (err) console.log(err); }) }
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μ•”ν˜Έν™”λ˜μ§€ μ•Šμ€ μ€‘μš”μ •λ³΄
μ€‘μš”μ •λ³΄(νŒ¨μŠ€μ›Œλ“œ, κ°œμΈμ •λ³΄ λ“±) 전솑 μ‹œ μ•”ν˜Έν™” λ˜λŠ” μ•ˆμ „ν•œ 톡신채널을 μ΄μš©ν•˜μ§€ μ•Šκ±°λ‚˜, μ €μž₯ μ‹œ μ•”ν˜Έν™” ν•˜μ§€ μ•Šμ•„ 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const { io } = require("socket.io-client"); const socket = io("http://localhost:3000"); function sendPassword(password) { // νŒ¨μŠ€μ›Œλ“œλ₯Ό μ•”ν˜Έν™” ν•˜μ§€ μ•Šκ³  μ „μ†‘ν•˜μ—¬ μ•ˆμ „ν•˜μ§€ μ•ŠμŒ socket.emit("password", password); } socket.on("password", function(data) { if (data === 'success') { console.log("\nSuccess to send a message to a server \n") } });
const { io } = require("socket.io-client"); const crypto = require("crypto"); const socket = io("http://localhost:3000"); const PASSWORD = getPassword(); function aesEncrypt(plainText) { const key = getCryptKey(); const iv = getCryptIV(); const cipherAes = crypto.createCipheriv('aes-256-cbc', key, iv); const encryptedData = cipherAes.update(plainText, 'utf8', 'base64'); const finalEncryptedData = cipherAes.final('base64'); return encryptedData + finalEncryptedData; } function sendPassword(password) { // νŒ¨μŠ€μ›Œλ“œ λ“± μ€‘μš”μ •λ³΄λŠ” μ•”ν˜Έν™”ν•˜μ—¬ μ „μ†‘ν•˜λŠ” 것이 μ•ˆμ „ν•¨ const encPassword = aesEncrypt(password); socket.emit("password", encPassword); } socket.on("password", function(data) { if (data === 'success') { console.log("\nSuccess to send a message to a server \n") } });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
ν•˜λ“œμ½”λ“œλœ μ€‘μš”μ •λ³΄
μ†ŒμŠ€μ½”λ“œμ— μ€‘μš”μ •λ³΄(νŒ¨μŠ€μ›Œλ“œ, μ•”ν˜Έν™”ν‚€ λ“±)λ₯Ό 직접 μ½”λ”©ν•˜μ—¬ μ†ŒμŠ€μ½”λ“œ 유좜 μ‹œ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœλ˜κ³  주기적 변경이 μ–΄λ €μš΄ λ³΄μ•ˆμ•½μ 
const express = require('express'); const mysql = require("mysql"); const crypto = require("crypto"); const dbQuery = "SELECT email, name FROM user WHERE name = 'test'"; router.get("/vuln", (req, res) => { // λ°μ΄ν„°λ² μ΄μŠ€ 연결에 ν•„μš”ν•œ 인증 정보가 ν‰λ¬ΈμœΌλ‘œ ν•˜λ“œμ½”λ”©λ˜μ–΄ 있음 const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root1234', database: 'javascript', port: 3306, }); connection.query( dbQuery, (err, result) => { if (err) return res.send(err); return res.send(result); }) });
const express = require('express'); const mysql = require("mysql"); const crypto = require("crypto"); const dbQuery = "SELECT email, name FROM user WHERE name = 'test'"; const key = getCryptKey(); // 32bytes const iv = getCryptIV(); // 16bytes router.get("/patched", (req, res) => { // μ„€μ •νŒŒμΌμ— μ•”ν˜Έν™” λ˜μ–΄ μžˆλŠ” user, password 정보λ₯Ό 가져와 λ³΅ν˜Έν™” ν•œ ν›„ μ‚¬μš© const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv); const user = decipher.update(process.env.USER, 'base64', 'utf8') + decipher.final('utf8'); const decipher2 = crypto.createDecipheriv('aes-256-cbc', key, iv); const password = decipher2.update(process.env.PASSWORD, 'base64', 'utf8') + decipher2.final ('utf8'); // DB μ—°κ²° 정보도 μ„€μ •νŒŒμΌμ—μ„œ 가져와 μ‚¬μš© const connection = mysql.createConnection({ host: process.env.DB_HOST, user: user, password: password, database: process.env.DB_NAME, port: process.env.PORT, });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μΆ©λΆ„ν•˜μ§€ μ•Šμ€ ν‚€ 길이 μ‚¬μš©
μ•”ν˜Έν™” 등에 μ‚¬μš©λ˜λŠ” ν‚€μ˜ 길이가 μΆ©λΆ„ν•˜μ§€ μ•Šμ•„ λ°μ΄ν„°μ˜ 기밀성·무결성을 보μž₯ν•  수 μ—†λŠ” λ³΄μ•ˆμ•½μ 
const crypto = require("crypto"); function vulnMakeRsaKeyPair() { // RSAν‚€ 길이λ₯Ό 1024 λΉ„νŠΈλ‘œ μ„€μ •ν•˜λŠ” 경우 μ•ˆμ „ν•˜μ§€ μ•ŠμŒ const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 1024, publicKeyEncoding: { type: "spki", format: 'pem' }, privateKeyEncoding: { type: "pkcs8", format: 'pem' } }); return { PRIVATE: publicKey, PUBLIC: privateKey } } function vulnMakeEcc() { // ECC ν‚€ 길이가 224λΉ„νŠΈ μ΄ν•˜μ΄λ©΄ μ•ˆμ „ν•˜μ§€ μ•ŠμŒ const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'secp192k1', publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' } }); return { PRIVATE: publicKey.toString('hex'), PUBLIC: privateKey.toString('hex') } }
const crypto = require("crypto"); function vulnMakeRsaKeyPair() { // RSAν‚€ 길이λ₯Ό 2048 λΉ„νŠΈλ‘œ μ„€μ •ν•΄ μ•ˆμ „ν•¨ const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: { type: "spki", format: 'pem' }, privateKeyEncoding: { type: "pkcs8", format: 'pem' } }); return { PRIVATE: publicKey, PUBLIC: privateKey } } function vulnMakeEcc() { // ECC ν‚€ 길이λ₯Ό 256 λΉ„νŠΈλ‘œ μ„€μ •ν•΄ μ•ˆμ „ν•¨ const { publicKey, privateKey } = crypto.generateKeyPairSync('ec', { namedCurve: 'secp256k1', publicKeyEncoding: { type: 'spki', format: 'der' }, privateKeyEncoding: { type: 'pkcs8', format: 'der' } }); return { PRIVATE: publicKey.toString('hex'), PUBLIC: privateKey.toString('hex') } }
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μ μ ˆν•˜μ§€ μ•Šμ€ λ‚œμˆ˜ κ°’ μ‚¬μš©
μ‚¬μš©ν•œ λ‚œμˆ˜κ°€ 예츑 κ°€λŠ₯ν•˜μ—¬, κ³΅κ²©μžκ°€ λ‹€μŒ λ‚œμˆ˜λ₯Ό μ˜ˆμƒν•΄μ„œ μ‹œμŠ€ν…œμ„ 곡격 κ°€λŠ₯ν•œ λ³΄μ•ˆ 약점
function getOtpNumber() { let randomStr = ''; // Math.random λΌμ΄λΈŒλŸ¬λ¦¬λŠ” λ³΄μ•ˆκΈ°λŠ₯에 μ‚¬μš©ν•˜λ©΄ μœ„ν—˜ν•¨ for (let i = 0; i < 6; i++) { randomStr += String(Math.floor(Math.random() * 10)) } return randomStr; }
const crypto = require("crypto"); function getOtpNumber() { // λ³΄μ•ˆκΈ°λŠ₯에 μ ν•©ν•œ λ‚œμˆ˜ μƒμ„±μš© crypto 라이브러리 μ‚¬μš© const array = new Uint32Array(1); // λΈŒλΌμš°μ €μ—μ„œλŠ” crypto λŒ€μ‹ μ— window.cryptoλ₯Ό μ‚¬μš© const randomStr = crypto.getRandomValues(array); let result; for (let i = 0; i < randomStr.length; i++) { result = array[i]; } return String(result).substring(0, 6); }
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μ·¨μ•½ν•œ νŒ¨μŠ€μ›Œλ“œ ν—ˆμš©
νŒ¨μŠ€μ›Œλ“œ μ‘°ν•©κ·œμΉ™(영문, 숫자, 특수문자 λ“±) 미흑 및 길이가 μΆ©λΆ„ν•˜μ§€ μ•Šμ•„ νŒ¨μŠ€μ›Œλ“œκ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const mysql = require("mysql"); const connection = mysql.createConnection( ... ); router.post("/vuln", (req, res) => { const con = connection; const { email, password, name } = req.body; // νŒ¨μŠ€μ›Œλ“œ 생성 κ·œμΉ™ 검증 없이 νšŒμ› κ°€μž… 처리 con.query( "INSERT INTO user (email, password, name) VALUES (?, ?, ?)", [email, password, name], (err, result) => { if (err) return res.send(err); return res.send("νšŒμ›κ°€μž… 성곡"); }); });
const express = require('express'); const mysql = require("mysql"); const connection = mysql.createConnection(...); router.post("/patched", (req, res) => { const con = connection; const { email, password, name } = req.body; function checkPassword(password) { // 2μ’… 이상 문자둜 κ΅¬μ„±λœ 8자리 이상 λΉ„λ°€λ²ˆν˜Έ 검사 μ •κ·œμ‹ const pt1 = /^(?=.*[A-Z])(?=.*[a-z])[A-Za-z\d!@#$%^&*]{8,}$/; const pt2 = /^(?=.*[A-Z])(?=.*\d)[A-Za-z\d!@#$%^&*]{8,}$/; const pt3 = /^(?=.*[A-Z])(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$/; const pt4 = /^(?=.*[a-z])(?=.*\d)[A-Za-z\d!@#$%^&*]{8,}$/; const pt5 = /^(?=.*[a-z])(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$/; const pt6 = /^(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$/; // 문자 ꡬ성 상관없이 10자리 이상 λΉ„λ°€λ²ˆν˜Έ 검사 μ •κ·œμ‹ const pt7 = /^[A-Za-z\d!@#$%^&*]{10,}$/; for (let pt of [pt1, pt2, pt3, pt4, pt5, pt6, pt7]) { console.log(pt.test(password)); if (pt.test(password)) return true; } return false; } if (checkPassword(password)) { con.query( "INSERT INTO user (email, password, name) VALUES (?, ?, ?)", [email, password, name], (err, result) => { if (err) return res.send(err); return res.send("νšŒμ›κ°€μž… 성곡"); } ); } else { return res.send("λΉ„λ°€λ²ˆν˜ΈλŠ” 영문 λŒ€λ¬Έμž, μ†Œλ¬Έμž, 숫자, 특수문자 μ‘°ν•© 쀑 2가지 이상 8μžλ¦¬μ΄κ±°λ‚˜ 문자 ꡬ성 상관없이 10자리 이상이어야 ν•©λ‹ˆλ‹€."); } });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
λΆ€μ μ ˆν•œ μ „μžμ„œλͺ… 확인
ν”„λ‘œκ·Έλž¨, 라이브러리, μ½”λ“œμ˜ μ „μžμ„œλͺ…에 λŒ€ν•œ μœ νš¨μ„± 검증이 μ μ ˆν•˜μ§€ μ•Šμ•„ 곡격자의 μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const crypto = require("crypto"); const fs = require(β€˜fs’); router.post("/vuln", (req, res) => { // ν΄λΌμ΄μ–ΈνŠΈλ‘œλΆ€ν„° 전달받은 데이터(μ „μžμ„œλͺ…을 μˆ˜μ‹  처리 ν•˜μ§€ μ•ŠμŒ) const { encrypted_msg } = req.body; let secret_key; fs.readFile(β€˜/keys/secret_key.out’, β€˜utf8’, (err, data) => { if (err) { console.error(err); return; } secret_key = data; } // λŒ€μΉ­ν‚€λ‘œ ν΄λΌμ΄μ–ΈνŠΈκ°€ μ „λ‹¬ν•œ μ½”λ“œ λ³΅ν˜Έν™” // (decrypt_with_symmetric_key ν•¨μˆ˜λŠ” μž„μ˜μ˜ ν•¨μˆ˜λͺ…μœΌλ‘œ 세뢀적인 λ³΅ν˜Έν™” 과정은 μƒλž΅ν•¨) const decrypted = decrypt_with_symmetric_key(encrypted_msg, secret_key); // ν΄λΌμ΄μ–ΈνŠΈλ‘œλΆ€ν„° 전달 받은 μ½”λ“œ μ‹€ν–‰ eval(decrypted); res.send('μš”μ²­ν•œ μ½”λ“œλ₯Ό μ‹€ν–‰ν–ˆμŠ΅λ‹ˆλ‹€'); });
// μ „μžμ„œλͺ… 검증에 μ‚¬μš©ν•œ μ½”λ“œλŠ” μ˜μ‘΄ν•œ νŒ¨ν‚€μ§€ 및 솑신츑 언어에 따라 // λ‹¬λΌμ§ˆ 수 있으며, μ„œλͺ…을 μ œκ³΅ν•œ μ„œλ²„μ˜ κ³΅κ°œν‚€λ‘œ λ³΅ν˜Έν™”ν•œ μ „μžμ„œλͺ…κ³Ό 원본 데이터 ν•΄μ‰¬κ°’μ˜ // 일치 μ—¬λΆ€λ₯Ό κ²€μ‚¬ν•˜λŠ” μ½”λ“œλ₯Ό 포함 const express = require('express'); const crypto = require("crypto"); router.post("/patched", (req, res) => { const { encrypted_msg, encrypted_sig, client_pub_key } = req.body; let secret_key; fs.readFile(β€˜/keys/secret_key.out’, β€˜utf8’, (err, data) => { if (err) { console.error(err); return; } secret_key = data; } // λŒ€μΉ­ν‚€λ‘œ ν΄λΌμ΄μ–ΈνŠΈ 데이터 및 μ „μžμ„œλͺ… λ³΅ν˜Έν™” const decrypted_msg = decrypt_with_symmetric_key(encrypted_msg); const decrypted_sig = decrypt_with_symmetric_key(encrypted_sig); // μ „μžμ„œλͺ… 검증에 ν†΅κ³Όν•œ κ²½μš°μ—λ§Œ 데이터 μ‹€ν–‰ if (verify_digit_signature(decrypted_msg, decrypted_sig, clint_pub_key)) { eval(decrypted_msg); res.send('μš”μ²­ν•œ μ½”λ“œλ₯Ό μ‹€ν–‰ν–ˆμŠ΅λ‹ˆλ‹€'); } else { res.send('[!] μ—λŸ¬ - μ„œλͺ…이 μ˜¬λ°”λ₯΄μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.'); } });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
λΆ€μ μ ˆν•œ μΈμ¦μ„œ μœ νš¨μ„± 검증
μΈμ¦μ„œμ— λŒ€ν•œ μœ νš¨μ„± 검증이 μ μ ˆν•˜μ§€ μ•Šμ•„ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ 
const https = require('https'); const getServer = () => { const options = { hostname: "dangerous.website", port: 443, method: "GET", path: "/", // μœ νš¨ν•˜μ§€ μ•Šμ€ μΈμ¦μ„œλ₯Ό 가지고 μžˆμ–΄λ„ λ¬΄μ‹œν•˜λŠ” μ˜΅μ…˜μœΌλ‘œ μ•ˆμ „ν•˜μ§€ μ•ŠμŒ rejectUnauthorized: false }; https.request( options, (response) => { console.log('response - ', response.statusCode); } ); });
const express = require('express'); const https = require('https'); const getServer = () => { const options = { hostname: "dangerous.website", port: 443, method: "GET", path: "/", // μœ νš¨ν•˜μ§€ μ•Šμ€ μΈμ¦μ„œ 발견 μ‹œ μ˜ˆμ™Έ λ°œμƒ rejectUnauthorized: true }; const hreq = https.request( options, (response) => { console.log('response - ', response.statusCode); } ); hreq.on('error', (e) => { console.error('μ—λŸ¬λ°œμƒ - ', e); }); });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μ‚¬μš©μž ν•˜λ“œλ””μŠ€ν¬μ— μ €μž₯λ˜λŠ” μΏ ν‚€λ₯Ό ν†΅ν•œ μ •λ³΄λ…ΈμΆœ
μΏ ν‚€(μ„Έμ…˜ ID, μ‚¬μš©μž κΆŒν•œμ •λ³΄ λ“± μ€‘μš”μ •λ³΄)λ₯Ό μ‚¬μš©μž ν•˜λ“œλ””μŠ€ν¬μ— μ €μž₯ν•˜μ—¬ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); router.get("/vuln", (req, res) => { // μΏ ν‚€μ˜ 만료 μ‹œκ°„μ„ 1λ…„μœΌλ‘œ κ³Όλ„ν•˜κ²Œ 길게 μ„€μ •ν•˜κ³  μžˆμ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ res.cookie('rememberme', '1', { expires: new Date(Date.now() + 365*24*60*60*1000) }); return res.send("μΏ ν‚€ λ°œκΈ‰ μ™„λ£Œ"); });
const express = require('express'); router.get("/patched", (req, res) => { // μΏ ν‚€μ˜ 만료 μ‹œκ°„μ„ μ μ ˆν•˜κ²Œ λΆ€μ—¬ν•˜κ³  secure μ˜΅μ…˜μ„ ν™œμ„±ν™” res.cookie('rememberme', '1', { expires: new Date(Date.now() + 60*60*1000), secure: true, httpOnly: true }); return res.send("μΏ ν‚€ λ°œκΈ‰ μ™„λ£Œ"); });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
주석문 μ•ˆμ— ν¬ν•¨λœ μ‹œμŠ€ν…œ μ£Όμš”μ •λ³΄
μ†ŒμŠ€μ½”λ“œ 주석문에 인증정보 λ“± μ‹œμŠ€ν…œ μ£Όμš”μ •λ³΄κ°€ ν¬ν•¨λ˜μ–΄ μ†ŒμŠ€μ½”λ“œ λ…ΈμΆœ μ‹œ μ£Όμš”μ •λ³΄λ„ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); router.post("/vuln", (req, res) => { // 주석문에 ν¬ν•¨λœ μ€‘μš” μ‹œμŠ€ν…œμ˜ 인증 정보 // id = admin // password = 1234 const result = login(req.body.id, req.body.password); return res.send(result); });
const express = require('express'); router.post("/vuln", (req, res) => { // 주석문에 ν¬ν•¨λœ λ―Όκ°ν•œ μ •λ³΄λŠ” μ‚­μ œ const result = login(req.body.id, req.body.password); return res.send(result); });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
μ†”νŠΈ 없이 일방ν–₯ 해쉬 ν•¨μˆ˜ μ‚¬μš©
μ†”νŠΈλ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³  μƒμ„±λœ 해쉬 κ°’μœΌλ‘œλΆ€ν„° κ³΅κ²©μžκ°€ 미리 κ³„μ‚°λœ 레인보우 ν…Œμ΄λΈ”μ„ μ΄μš©ν•˜μ—¬ 해쉬 적용 이전 원본 정보λ₯Ό 볡원가λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const crypto = require("crypto"); function getHashFromPwd(pw) { // saltκ°€ 없이 μƒμ„±λœ 해쉬값은 강도가 μ•½ν•΄ μ·¨μ•½ const hash = crypto.createHash('sha256').update(pw).digest('hex'); return hash; }
const crypto = require("crypto"); function getHashFromPwd(pw) { // μ†”νŠΈ 값을 μ‚¬μš©ν•˜λ©΄ 길이가 짧은 νŒ¨μŠ€μ›Œλ“œλ‘œλ„ κ³ κ°•λ„μ˜ 해쉬λ₯Ό 생성할 수 있음 // μ†”νŠΈ 값은 μ‚¬μš©μžλ³„λ‘œ μœ μΌν•˜κ²Œ 생성해야 ν•˜λ©°, νŒ¨μŠ€μ›Œλ“œμ™€ ν•¨κ»˜ DB에 μ €μž₯ν•΄μ•Ό 함 const salt = crypto.randomBytes(16).toString('hex'); const hash = crypto.createHash('sha256').update(pw + salt).digest('hex'); return { hash, salt }; }
Javascript
λ³΄μ•ˆκΈ°λŠ₯
무결성 검사 μ—†λŠ” μ½”λ“œ λ‹€μš΄λ‘œλ“œ
μ†ŒμŠ€μ½”λ“œ λ˜λŠ” μ‹€ν–‰νŒŒμΌμ„ 무결성 검사 없이 λ‹€μš΄λ‘œλ“œ λ°›μ•„ μ‹€ν–‰ν•˜λŠ” 경우, 곡격자의 μ•…μ˜ 적인 μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const fs = require("fs"); const http = require("http"); router.get("/vuln", (req, res) => { // μ‹ λ’°ν•  수 μ—†λŠ” μ‚¬μ΄νŠΈμ—μ„œ μ½”λ“œλ₯Ό λ‹€μš΄λ‘œλ“œ const url = "https://www.somewhere.com/storage/code.js"; // 원격 μ½”λ“œ λ‹€μš΄λ‘œλ“œ http.get(url, (res) => { const path = "./temp/sample1.js" const writeStream = fs.createWriteStream(path); res.pipe(writeStream); writeStream.on("finish", () => { writeStream.close(); }); }); // 무결성 검증 없이 파일 μ‚¬μš© fs.readFile("./temp/sample1.js", "utf8", function (err, buf) { res.end(buf); }) });
const express = require('express'); const fs = require("fs"); const http = require("http"); const crypto = require("crypto"); router.get("/patched", async (req, res) => { const url = "https://www.somewhere.com/storage/code.js"; const codeHash = req.body.codeHash; http.get(url, (res) => { const path = "./temp/sample1.js" const writeStream = fs.createWriteStream(path); res.pipe(writeStream); writeStream.on("finish", () => { writeStream.close(); }); }); const hash = crypto.createHash('sha256'); const input = fs.createReadStream("./temp/sample1.js"); let promise = new Promise ((resolve, reject) => { input.on("readable", () => { const data = input.read(); if (data) { hash.update(data); } else { resolve(); } }) }); await promise; const fileHash = hash.digest('hex'); # 무결성 검증에 톡과할 κ²½μš°μ—λ§Œ 파일 μ‚¬μš© if (fileHash === codeHash) { fs.readFile("./temp/sample1.js", "utf8", function (err, buf) { res.end(buf); }) } else { return res.send("파일이 μ†μƒλ˜μ—ˆμŠ΅λ‹ˆλ‹€.") } });
Javascript
λ³΄μ•ˆκΈ°λŠ₯
반볡된 μΈμ¦μ‹œλ„ μ œν•œ κΈ°λŠ₯ λΆ€μž¬
인증 μ‹œλ„ 수λ₯Ό μ œν•œν•˜μ§€ μ•Šμ•„ κ³΅κ²©μžκ°€ 반볡적으둜 μž„μ˜ 값을 μž…λ ₯ν•˜μ—¬ 계정 κΆŒν•œμ„ νšλ“ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const crypto = require('crypto'); router.post("/vuln", (req, res) => { const id = req.body.id; const password = req.body.password; const hashPassword = crypto.createHash("sha512").update(password).digest("base64"); const currentHashPassword = getUserPasswordFromDB(id); // 인증 μ‹œλ„μ— λ”°λ₯Έ μ œν•œμ΄ μ—†μ–΄ 반볡적인 인증 μ‹œλ„κ°€ κ°€λŠ₯ if (hashPassword === currentHashPassword) { return res.send("login success"); } else { return res.send("login fail") } });
const express = require('express'); const crypto = require('crypto'); const LOGIN_TRY_LIMIT = 5; router.post("/patched", (req, res) => { const id = req.body.id; const password = req.body.password; // 둜그인 μ‹€νŒ¨κΈ°λ‘ κ°€μ Έμ˜€κΈ° const loginFailCount = getUserLoginFailCount(id); // 둜그인 μ‹€νŒ¨νšŸμˆ˜ 초과둜 인해 잠금된 계정에 λŒ€ν•œ 인증 μ‹œλ„ μ œν•œ if (loginFailCount >= LOGIN_TRY_LIMIT) { return res.send("account lock(too many failed)") } // ν•΄μ‹œ μƒμ„±μ‹œ μ†”νŠΈλ₯Ό μ‚¬μš©ν•˜λŠ” 것이 μ•ˆμ „ν•˜λ‚˜, μ½”λ“œμ˜ λ³΅μž‘μ„±μ„ ν”Όν•˜κΈ° μœ„ν•΄ μƒλž΅ const hashPassword = crypto.createHash("sha512").update(password).digest("base64"); const currentHashPassword = getUserPasswordFromDB(id); if (hashPassword === currentHashPassword) { deleteUserLoginFailCount(id); return res.send("login success"); } else { updateUserLoginFailCount(id); return res.send("login fail") } });
Javascript
μ‹œκ°„ 및 μƒνƒœ
μ’…λ£Œλ˜μ§€ μ•ŠλŠ” 반볡문 λ˜λŠ” μž¬κ·€ν•¨μˆ˜
μ’…λ£Œμ‘°κ±΄ μ—†λŠ” μ œμ–΄λ¬Έ μ‚¬μš©μœΌλ‘œ 반볡문 λ˜λŠ” μž¬κ·€ν•¨μˆ˜κ°€ λ¬΄ν•œνžˆ λ°˜λ³΅λ˜μ–΄ λ°œμƒν•  수 μžˆλŠ” λ³΄μ•ˆμ•½μ 
function factorial(x) { # μž¬κ·€ν•¨μˆ˜ νƒˆμΆœμ‘°κ±΄μ„ μ„€μ •ν•˜μ§€ μ•Šμ•„ λ™μž‘ 쀑 μ—λŸ¬ λ°œμƒ return x * factorial(x - 1); });
function factorial(x) { # μž¬κ·€ν•¨μˆ˜ μ‚¬μš© μ‹œμ—λŠ” νƒˆμΆœ 쑰건을 λͺ…μ‹œν•΄μ•Ό ν•œλ‹€ if ( x === 0 ) { return; } else { return x * factorial(x - 1); } }
Javascript
μ—λŸ¬μ²˜λ¦¬
였λ₯˜ λ©”μ‹œμ§€ μ •λ³΄λ…ΈμΆœ
였λ₯˜λ©”μ‹œμ§€λ‚˜ μŠ€νƒμ •λ³΄μ— μ‹œμŠ€ν…œ 내뢀ꡬ쑰가 ν¬ν•¨λ˜μ–΄ λ―Όκ°ν•œ 정보, 디버깅 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const fs = require("fs"); router.get("/vuln", (req, res) => { const filePath = "./file/secret/password"; fs.readFile(filePath, (err, data) => { if (err) { // μ„œλ²„ λ‚΄λΆ€μ—μ„œ λ°œμƒν•œ μ—λŸ¬ λ©”μ‹œμ§€λ₯Ό κ·ΈλŒ€λ‘œ μ‚¬μš©μžμ— 전달해 μ£Όμš” 정보 λ…ΈμΆœ μœ„ν—˜ return res.status(500).send(err); } else { return res.send(data); } }) });
const express = require('express'); const fs = require("fs"); router.get("/vuln", (req, res) => { const filePath = "./file/secret/password"; fs.readFile(filePath, (err, data) => { if (err) { // μ—λŸ¬ λ‚΄μš©μ„ κ·ΈλŒ€λ‘œ μ „λ‹¬ν•˜μ§€ μ•Šκ³  필터링 처리 return res.status(500).send({ message: β€œμž˜λͺ»λœ μš”μ²­μž…λ‹ˆλ‹€β€ }); } else { return res.send(data); } }) });
Javascript
μ—λŸ¬μ²˜λ¦¬
였λ₯˜ λ©”μ‹œμ§€ μ •λ³΄λ…ΈμΆœ
였λ₯˜λ©”μ‹œμ§€λ‚˜ μŠ€νƒμ •λ³΄μ— μ‹œμŠ€ν…œ 내뢀ꡬ쑰가 ν¬ν•¨λ˜μ–΄ λ―Όκ°ν•œ 정보, 디버깅 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
Expressμ—μ„œ μ œκ³΅ν•˜λŠ” errorHandler 미듀웨어λ₯Ό μ •μ˜ν•˜μ§€ μ•ŠμŒ.
const express = require("express"); const app = express(); // errorHandler λ―Έλ“€μ›¨μ–΄λŠ” λ‹€λ₯Έ app.use() 및 λΌμš°ν„° μ •μ˜ ν›„ κ°€μž₯ λ§ˆμ§€λ§‰μ— μ •μ˜ν•΄μ•Ό ν•˜λ©°, // errorHandler 미듀웨어λ₯Ό μ»€μŠ€ν…€ν•˜μ—¬ μ—λŸ¬λ³„ μ—λŸ¬νŽ˜μ΄μ§€λ₯Ό λ°˜ν™˜ν•  수 μžˆλ‹€ app.use(clientErrorHandler); app.use(errorHandler); function clientErrorHandler (err, req, res, next) { if (req.xhr) { res.status(500).send({ error: 'Something failed!' }); } else { next(err); } } function errorHandler (err, req, res, next) { if (err.name = "ValidError") { res.status(400) res.render('400error', { error: err }) } else if (err.name = "AuthError") { res.status(401) res.render('401error', { error: err }) } else if (err.name = "ForbiddenError") { res.status(403) res.render('403error', { error: err }) } else if (err.name = "DBError") { res.status(500) res.render('500error', { error: err }) } }
Javascript
μ—λŸ¬μ²˜λ¦¬
였λ₯˜μƒν™© λŒ€μ‘ λΆ€μž¬
μ‹œμŠ€ν…œ 였λ₯˜μƒν™©μ„ μ²˜λ¦¬ν•˜μ§€ μ•Šμ•„ ν”„λ‘œκ·Έλž¨ 싀행정지 λ“± μ˜λ„ν•˜μ§€ μ•Šμ€ 상황이 λ°œμƒ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); const crypto = require("crypto"); const staticKeys = [ { "key" : "a6823ecf34012b1ca5ca7889f4eabb51", "iv" : "e79ce03b4563647a" }, { "key" : "9e7c30e899f296a1daca7d9a0f92e71c", "iv" : "ab39941053fb5f6a" } ]; router.post("/vuln", (req, res) => { let statickKey = { "key" : "00000000000000000000000000000000", "iv" : "0000000000000000" }; const inputText = req.body.text; const keyId = req.body.id; try { staticKey.key = staticKeys[keyId].key; staticKey.iv = staticKeys[keyId].iv; } catch (err) { // key 선택 쀑 였λ₯˜ λ°œμƒ μ‹œ 기본으둜 μ„€μ •λœ μ•”ν˜Έν™” 킀인 // β€˜0000000000000000’ 으둜 μ•”ν˜Έν™”κ°€ μˆ˜ν–‰λ¨ console.log(err); } const cipher = crypto.createCipheriv('aes-256-cbc', statickKey.key, statickKey.iv); const encryptedText = cipher.update(inputText, 'utf8', 'base64') + cipher.final('base64'); return res.send(encryptedText); });
const express = require('express'); const crypto = require("crypto"); const staticKeys = [ { "key" : "a6823ecf34012b1ca5ca7889f4eabb51", "iv" : "e79ce03b4563647a" }, { "key" : "9e7c30e899f296a1daca7d9a0f92e71c", "iv" : "ab39941053fb5f6a" } ]; router.post("/vuln", (req, res) => { let statickKey = { "key" : "00000000000000000000000000000000", "iv" : "0000000000000000" }; const inputText = req.body.text; const keyId = req.body.id; try { staticKey.key = staticKeys[keyId].key; staticKey.iv = staticKeys[keyId].iv; } catch (err) { // ν‚€ 선택 쀑 였λ₯˜ λ°œμƒ μ‹œ 랜덀으둜 μ•”ν˜Έν™” ν‚€λ₯Ό μƒμ„±ν•˜λ„λ‘ μ„€μ • staticKey.key = crypto.randomBytes(16).toString('hex'); staticKey.iv = crypto.randomBytes(8).toString('hex'); } const cipher = crypto.createCipheriv('aes-256-cbc', statickKey.key, statickKey.iv); const encryptedText = cipher.update(inputText, 'utf8', 'base64') + cipher.final('base64'); return res.send(encryptedText); });
Javascript
μ—λŸ¬μ²˜λ¦¬
λΆ€μ μ ˆν•œ μ˜ˆμ™Έμ²˜λ¦¬
μ˜ˆμ™Έμ‚¬ν•­μ„ λΆ€μ μ ˆν•˜κ²Œ μ²˜λ¦¬ν•˜μ—¬ μ˜λ„ν•˜μ§€ μ•Šμ€ 상황이 λ°œμƒ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
const express = require('express'); router.post("/vuln", (req, res) => { const password = req.body.password; const user = { user: "user", password: password, }; function getUser() { return new Promise((resolve, reject) => { resolve(user); }); } function getUserPassword(user) { return new Promise((resolve, reject) => { if (user.password === undefined) { reject(new Error("login fail")); } else { resolve(user); } }); } function checkPassword(user) { return new Promise((resolve, reject) => { if (user.password == "abc") { resolve(user); } else { reject(new Error("login fail")); } }); } return getUser() .then(getUserPassword) .then(checkPassword) .then((result) => res.send(result)) .catch((err) => { // μ„œλ‘œ λ‹€λ₯Έ μ˜ˆμ™Έ μƒν™©μ—μ„œλ„ λ™μΌν•œ μ—λŸ¬ λ©”μ‹œμ§€λ§Œ 좜λ ₯ res.send(err.message); }); });
const express = require('express'); router.post("/patched", (req, res) => { const password = req.body.password; const user = { user: "user", password: password, }; function getUser() { return new Promise((resolve, reject) => { resolve(user); }); } function getUserPassword(user) { return new Promise((resolve, reject) => { if (user.password === undefined) { reject(new Error("password required")); } resolve(user); }); } function checkPassword(user) { return new Promise((resolve, reject) => { if (user.password == "abc") { resolve(user); } else { reject(new Error("wrong password")); } }); } return getUser() .then(getUserPassword) .then(checkPassword) .then((result) => res.send(result)) .catch((err) => { // μ˜ˆμ™Έ 상황에 λ§žλŠ” 처리 κ²°κ³Ό λ©”μ‹œμ§€λ₯Ό λ‘œκ·Έμ— 기둝(λ‚΄μž₯ ν•¨μˆ˜ logκ°€ μžˆλ‹€κ³  κ°€μ •) log(err.messsage); // ν΄λΌμ΄μ–ΈνŠΈμ—λŠ” μ—λŸ¬ λ°œμƒ μ—¬λΆ€λ§Œ 전달 res.send(β€˜login failed’); }); );
Javascript
μ½”λ“œμ˜€λ₯˜
Null Pointer μ—­μ°Έμ‘°
λ³€μˆ˜μ˜ μ£Όμ†Œ 값이 Null인 객체λ₯Ό μ°Έμ‘°ν•˜λŠ” λ³΄μ•ˆμ•½μ 
const express = require('express'); router.get("/vuln", (req, res) => { const id = req.query.id; // μ‚¬μš©μžκ°€ id 값을 μ „λ‹¬ν•˜μ§€ μ•Šμ„ 경우(undefined) μ—λŸ¬ λ°œμƒ return res.send("length = " + id.length); });
const express = require('express'); router.get("/patched", (req, res) => { const id = req.query.id; if (id === undefined) { // id 값이 μ „λ‹¬λ˜μ§€ μ•Šμ„ 경우 μ‚¬μš©μžμ—κ²Œ μš”κ΅¬ν•˜λŠ” μ˜ˆμ™Έ μ½”λ“œ μΆ”κ°€ return res.send("id is required"); } else { return res.send("length = " + id.length); } });
Javascript
μ½”λ“œμ˜€λ₯˜
λΆ€μ μ ˆν•œ μžμ› ν•΄μ œ
μ‚¬μš© μ™„λ£Œλœ μžμ›μ„ ν•΄μ œν•˜μ§€ μ•Šμ•„ μžμ›μ΄ κ³ κ°ˆλ˜μ–΄ μƒˆλ‘œμš΄ μž…λ ₯을 μ²˜λ¦¬ν•  수 μ—†λŠ” λ³΄μ•ˆμ•½μ 
const express = require('express'); const fs = require('fs'); router.get("/vuln", (req, res) => { const configPath = './config.cfg'; let fid = null; let fdata = null; try { fid = fs.openSync(configPath, 'r'); fdata = fs.readFileSync(fid, 'utf8'); // μ˜ˆμ™Έ λ°œμƒ 상황 κ°€μ •: μœ νš¨ν•˜μ§€ μ•Šμ€ 파일 λ””μŠ€ν¬λ¦½ν„°λ‘œ 파일 읽기 μ‹œλ„ fdata = fs.readFileSync('100', 'utf8'); // try μ ˆμ—μ„œ ν• λ‹Ήλœ μžμ›μ΄ λ°˜ν™˜(close)되기 전에 μ˜ˆμ™Έκ°€ λ°œμƒν•˜λ©΄ // ν• λ‹Ήλœ μžμ›μ΄ μ‹œμŠ€ν…œμ— λ°”λ‘œ λ°˜ν™˜λ˜μ§€ μ•ŠμŒ fs.close(fid, err => { if (err) { console.log('error occured while flle closing'); } else { console.log('file closed'); } }); } catch (e) { console.log('error occured!' , e); } return res.send(fdata); });
const express = require('express'); const fs = require('fs'); router.get("/patched", (req, res) => { const configPath = './5_code_error/40_improper_resource_shutdown/config.cfg'; let fid = null; let fdata = null; try { fid = fs.openSync(configPath, 'r'); fdata = fs.readFileSync(fid, 'utf8'); fdata = fs.readFileSync(100, 'utf8'); } catch (e) { console.log('error occured!' , e); // try μ ˆμ—μ„œ ν• λ‹Ήλœ μžμ›μ€ finally μ ˆμ—μ„œ μ‹œμŠ€ν…œμ— λ°˜ν™˜μ„ ν•΄μ•Ό 함 } finally { fs.close(fid, err => { if (err) { console.log('error occured while flle closing'); } else { console.log('file closed'); } }); } return res.send(fdata); });
Javascript
μ½”λ“œμ˜€λ₯˜
μ‹ λ’°ν•  수 μ—†λŠ” λ°μ΄ν„°μ˜ 역직렬화
μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‚½μž…Β·μˆ˜μ •λœ 직렬화 데이터λ₯Ό μ μ ˆν•œ 검증 없이 μ—­μ§λ ¬ν™”ν•˜μ—¬ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ  * 직렬화: 객체λ₯Ό 전솑 κ°€λŠ₯ν•œ λ°μ΄ν„°ν˜•μ‹μœΌλ‘œ λ³€ν™˜ * 역직렬화: μ§λ ¬ν™”λœ 데이터λ₯Ό μ›λž˜ 객체둜 볡원
const express = require('express'); def load_user_object(request): const serializedData = req.query.data; # μ‚¬μš©μžλ‘œλΆ€ν„° μž…λ ₯받은 μ•Œ 수 μ—†λŠ” 데이터λ₯Ό 역직렬화 const user = JSON.parse(serializedData); return res.send({user: user.user, isAdmin: user.isAdmin});
const express = require('express'); const crypto = require('crypto'); def load_user_object(request): const serializedData = req.query.data; # 데이터 ν˜•μ‹: '{"userInfo":{"user":"admin","isAdmin":true},"hashed":"cf8cd...7"}'; const body = JSON.parse(serializedData); # 데이터 λ³€μ‘°λ₯Ό ν™•μΈν•˜κΈ° μœ„ν•œ ν•΄μ‹œκ°’ const hashedMac = body.hashed; # μ‚¬μš©μžλ‘œλΆ€ν„° μž…λ ₯받은 데이터λ₯Ό 직렬화 const userInfo = JSON.stringify(body.userInfo); const secretKey = 'secret_key'; const hmac = crypto.createHmac('sha512', secretKey); # μ§λ ¬ν™”λœ μ‚¬μš©μž μž…λ ₯값을 ν•΄μ‹± hmac.update(userInfo); const calculatedHMAC = hmac.digest('hex'); # 전달받은 ν•΄μ‹œκ°’(hashedMAC)κ³Ό 직렬화 데이터(calculaedHMAC)의 ν•΄μ‹œκ°’μ„ λΉ„κ΅ν•˜μ—¬ 검증 if (calculatedHMAC === hashedMac) { const userObj = JSON.parse(userInfo); return res.send(userObj); } else { console.log('hmac -', calculatedHMAC); return res.send('μ‹ λ’°ν•  수 μ—†λŠ” λ°μ΄ν„°μž…λ‹ˆλ‹€. '); }
Javascript
μΊ‘μŠν™”
잘λͺ»λœ μ„Έμ…˜μ— μ˜ν•œ 데이터 μ •λ³΄λ…ΈμΆœ
잘λͺ»λœ μ„Έμ…˜μ— μ˜ν•΄ μΈκ°€λ˜μ§€ μ•Šμ€ μ‚¬μš©μžμ—κ²Œ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
let instance; class UserSingleton { constructor() { this.userName = 'testUser'; if (instance) { return instance; } instance = this; } getUserProfile() { return this.userName; } }; router.get("/vuln", (req, res) => { const user = new UserSingleton(); const profile = user.getUserProfile(); // μ„œλ‘œ λ‹€λ₯Έ μ„Έμ…˜μ—μ„œ κ³΅μœ λ˜λŠ” 값을 μ‚¬μš©ν•˜λŠ” 경우 λ‹€λ₯Έ μ„Έμ…˜μ— μ˜ν•΄ 데이터가 λ…ΈμΆœλ  수 있음 return res.send(profile); });
class User { constructor() { this.userName = 'testUser'; } getUserProfile() { return this.userName; } }; router.get("/patched", (req, res) => { const user = new User(); const profile = user.getUserProfile(); // μ„œλ‘œ λ‹€λ₯Έ μ„Έμ…˜μ—μ„œ κ³΅μœ λ˜μ§€ μ•ŠλŠ” 클래슀 μ •μ˜λ₯Ό μ‚¬μš©ν•΄ μ•ˆμ „ν•¨ return res.send(profile); });
Javascript
μΊ‘μŠν™”
μ œκ±°λ˜μ§€ μ•Šκ³  남은 디버그 μ½”λ“œ
디버깅을 μœ„ν•œ μ½”λ“œλ₯Ό μ œκ±°ν•˜μ§€ μ•Šμ•„ μΈκ°€λ˜μ§€ μ•Šμ€ μ‚¬μš©μžμ—κ²Œ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
디버깅 λͺ©μ μœΌλ‘œ μ‚½μž…λœ μ½”λ“œλŠ” 개발이 μ™„λ£Œλ˜λ©΄ μ œκ±°ν•΄μ•Ό ν•œλ‹€. 디버그 μ½”λ“œλŠ” μ„€μ • λ“±μ˜ λ―Όκ°ν•œ 정보 λ˜λŠ” μ˜λ„ν•˜μ§€ μ•Šμ€ μ‹œμŠ€ν…œ μ œμ–΄λ‘œ μ΄μ–΄μ§€λŠ” 정보λ₯Ό λ‹΄κ³  μžˆμ„ 수 μžˆλ‹€. 만일 디버그 μ½”λ“œκ°€ 남겨진 μ±„λ‘œ 배포될 경우 κ³΅κ²©μžκ°€ 식별 과정을 μš°νšŒν•˜κ±°λ‚˜ μ˜λ„ν•˜μ§€ μ•Šμ€ 정보 λ…ΈμΆœ λ¬Έμ œκ°€ λ°œμƒν•  수 μžˆλ‹€. 기본적으둜 μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œλŠ” console.log λ˜λŠ” console.error ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄ 디버그 λ©”μ‹œμ§€λ₯Ό 좜λ ₯ν•œλ‹€. 개발 μ™„λ£Œ 후에 λ””λ²„κΉ…μš©μœΌλ‘œ μž‘μ„±ν•œ μ½”λ“œλ₯Ό μ˜€λ²„λΌμ΄λ“œ(override) ν•΄ μ• ν”Œλ¦¬μΌ€μ΄μ…˜ λ™μž‘ μ‹œ μ½˜μ†” λ‘œκ·Έκ°€ 좜λ ₯ λ˜μ§€ μ•Šλ„λ‘ ν•œλ‹€. λ˜ν•œ 기본적으둜 ExpressJSλŠ” 디버그 λͺ¨λ“œκ°€ λΉ„ν™œμ„±ν™” 된 μƒνƒœμ—μ„œ λ™μž‘ν•˜λ©° μ„œλ²„ ꡬ동 μ‹œ β€˜DEBUG=’ prefix 섀정을 ν•˜μ§€ μ•ŠλŠ” ν•œ μ„œλ²„ 디버깅 λ©”μ‹œμ§€λŠ” 좜λ ₯ν•˜μ§€ μ•ŠλŠ”λ‹€.
// μ• ν”Œλ¦¬μΌ€μ΄μ…˜ μ§„μž… μ½”λ“œμΈ Index.js에 λ‹€μŒ μ½”λ“œλ₯Ό μΆ”κ°€ν•˜λ©΄ // μ½”λ“œ 내에 μ‚­μ œλ˜μ§€ μ•Šμ€ λͺ¨λ“  console.log μ½”λ“œλ‘œ 인해 μ•„λ¬΄λŸ° λ‚΄μš©λ„ 좜λ ₯λ˜μ§€ μ•ŠμŒ // ReactJS 예제 if (process.env.NODE_ENV === β€˜production’ && typeof window !== β€˜undefined’) { console.log = () => {}; }
Javascript
μΊ‘μŠν™”
μ œκ±°λ˜μ§€ μ•Šκ³  남은 디버그 μ½”λ“œ
디버깅을 μœ„ν•œ μ½”λ“œλ₯Ό μ œκ±°ν•˜μ§€ μ•Šμ•„ μΈκ°€λ˜μ§€ μ•Šμ€ μ‚¬μš©μžμ—κ²Œ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
디버깅 λͺ©μ μœΌλ‘œ μ‚½μž…λœ μ½”λ“œλŠ” 개발이 μ™„λ£Œλ˜λ©΄ μ œκ±°ν•΄μ•Ό ν•œλ‹€. 디버그 μ½”λ“œλŠ” μ„€μ • λ“±μ˜ λ―Όκ°ν•œ 정보 λ˜λŠ” μ˜λ„ν•˜μ§€ μ•Šμ€ μ‹œμŠ€ν…œ μ œμ–΄λ‘œ μ΄μ–΄μ§€λŠ” 정보λ₯Ό λ‹΄κ³  μžˆμ„ 수 μžˆλ‹€. 만일 디버그 μ½”λ“œκ°€ 남겨진 μ±„λ‘œ 배포될 경우 κ³΅κ²©μžκ°€ 식별 과정을 μš°νšŒν•˜κ±°λ‚˜ μ˜λ„ν•˜μ§€ μ•Šμ€ 정보 λ…ΈμΆœ λ¬Έμ œκ°€ λ°œμƒν•  수 μžˆλ‹€. 기본적으둜 μžλ°”μŠ€ν¬λ¦½νŠΈμ—μ„œλŠ” console.log λ˜λŠ” console.error ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄ 디버그 λ©”μ‹œμ§€λ₯Ό 좜λ ₯ν•œλ‹€. 개발 μ™„λ£Œ 후에 λ””λ²„κΉ…μš©μœΌλ‘œ μž‘μ„±ν•œ μ½”λ“œλ₯Ό μ˜€λ²„λΌμ΄λ“œ(override) ν•΄ μ• ν”Œλ¦¬μΌ€μ΄μ…˜ λ™μž‘ μ‹œ μ½˜μ†” λ‘œκ·Έκ°€ 좜λ ₯ λ˜μ§€ μ•Šλ„λ‘ ν•œλ‹€. λ˜ν•œ 기본적으둜 ExpressJSλŠ” 디버그 λͺ¨λ“œκ°€ λΉ„ν™œμ„±ν™” 된 μƒνƒœμ—μ„œ λ™μž‘ν•˜λ©° μ„œλ²„ ꡬ동 μ‹œ β€˜DEBUG=’ prefix 섀정을 ν•˜μ§€ μ•ŠλŠ” ν•œ μ„œλ²„ 디버깅 λ©”μ‹œμ§€λŠ” 좜λ ₯ν•˜μ§€ μ•ŠλŠ”λ‹€.
// μ„œλ²„ μ§„μž… μ½”λ“œμΈ index.js λ‚΄μ˜ μ„œλ²„ ꡬ동 뢀뢄에 λ‹€μŒ μ½”λ“œ μΆ”κ°€ // ExpressJS 예제 app.listen(80, () => { if (!process.env.DEBUG) { console.log = function(){} } });
Javascript
μΊ‘μŠν™”
Public λ©”μ†Œλ“œλ‘œλΆ€ν„° λ°˜ν™˜λœ Private λ°°μ—΄
Public으둜 μ„ μ–Έλœ λ©”μ†Œλ“œμ—μ„œ Private둜 μ„ μ–Έλœ 배열을 λ°˜ν™˜(return)ν•˜λ©΄ Private λ°°μ—΄μ˜ μ£Όμ†Œ 값이 외뢀에 λ…ΈμΆœλ˜μ–΄ ν•΄λ‹Ή Private 배열값을 μ™ΈλΆ€μ—μ„œ μˆ˜μ • κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
class UserObj { #privArray = []; // private 배열을 λ¦¬ν„΄ν•˜λŠ” public λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•˜λŠ” 경우 μ·¨μ•½ get_private_member = () => { return this.#privArray; } }
class UserObj { #privArray = []; // private 배열을 λ°˜ν™˜ν•˜λŠ” 경우 볡사본을 μ‚¬μš©ν•΄ 외뢀와 λ‚΄λΆ€μ˜ // 배열이 μ„œλ‘œ μ°Έμ‘°λ˜μ§€ μ•Šλ„λ‘ ν•΄μ•Ό 함 get_private_member = () => { const copied = Object.assign([], this.#privArray); return copied; } }
Javascript
μΊ‘μŠν™”
Private 배열에 Public 데이터 ν• λ‹Ή
Public으둜 μ„ μ–Έλœ 데이터 λ˜λŠ” λ©”μ†Œλ“œμ˜ μΈμžκ°€ Private둜 μ„ μ–Έλœ 배열에 μ €μž₯되면 Private 배열을 μ™ΈλΆ€μ—μ„œ μ ‘κ·Όν•˜μ—¬ μˆ˜μ • κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
class UserObj { #privArray = []; // private 배열에 μ™ΈλΆ€ 값을 λ°”λ‘œ λŒ€μž…ν•˜λŠ” public λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•˜λŠ” 경우 μ·¨μ•½ set_private_member = (input_list) => { this.#privArray = input_list; } }
class UserObj2 { #privArray = []; // μ‚¬μš©μžκ°€ μ „λ‹¬ν•œ 값을 privateκ°€ μ•„λ‹Œ public λ°°μ—΄λ‘œ μ €μž₯ set_private_member = (input_list) => { this.userInput = input_list; } }
Javascript
API 였용
DNS lookup에 μ˜μ‘΄ν•œ λ³΄μ•ˆκ²°μ •
도메인λͺ… 확인(DNS lookup)으둜 λ³΄μ•ˆκ²°μ •μ„ μˆ˜ν–‰ν•  λ•Œ μ•…μ˜μ μœΌλ‘œ λ³€μ‘°λœ DNS μ •λ³΄λ‘œ 예기치 μ•Šμ€ λ³΄μ•ˆμœ„ν˜‘μ— λ…ΈμΆœλ˜λŠ” λ³΄μ•ˆμ•½μ 
const express = require('express'); const dns = require("dns"); router.get("/vuln", (req, res) => { let trusted = false; const trustedHost = "www.google.com"; const hostName = req.query.host; // κ³΅κ²©μžμ— μ˜ν•΄ μ‹€ν–‰λ˜λŠ” μ„œλ²„μ˜ DNSκ°€ 변경될 수 μžˆμœΌλ―€λ‘œ // μ•ˆμ „ν•˜μ§€ μ•ŠμŒ if (hostName === trustedHost) { trusted = true; } return res.send({trusted}); });
const express = require('express'); const dns = require("dns"); router.get("/patched", async (req, res) => { let trusted = false; const trustedHost = "142.250.207.100"; // μ‹€μ œ μ„œλ²„μ˜ IP μ£Όμ†Œλ₯Ό λΉ„κ΅ν•˜μ—¬ DNS 변쑰에 λŒ€μ‘ async function dnsLookup() { return new Promise((resolve, reject) => { dns.lookup(req.query.host, 4, (err, address, family) => { if (err) reject(err); resolve(address); }) }) } const hostName = await dnsLookup(); if (hostName === trustedHost) { trusted = true; } return res.send({trusted}); });
Javascript
API 였용
μ·¨μ•½ν•œ API μ‚¬μš©
eval() ν•¨μˆ˜μ˜ λΆ€μ μ ˆν•œ μ‚¬μš©
const userInput = "2 + 2"; const result = eval(userInput); // μ‚¬μš©μž μž…λ ₯을 ν‰κ°€ν•˜μ—¬ μ‹€ν–‰ console.log(result);
const math = require('mathjs'); const userInput = "2 + 2"; const result = math.evaluate(userInput); // μ•ˆμ „ν•œ μˆ˜ν•™ ν‘œν˜„μ‹ 평가 console.log(result);
Javascript
API 였용
μ·¨μ•½ν•œ API μ‚¬μš©
innerHTML μ†μ„±μ˜ λΆ€μ μ ˆν•œ μ‚¬μš©
const userInput = "<img src='x' onerror='alert(1)'>"; document.getElementById('output').innerHTML = userInput;
const userInput = "<img src='x' onerror='alert(1)'>"; const outputElement = document.getElementById('output'); const textNode = document.createTextNode(userInput); outputElement.appendChild(textNode);
Javascript
API 였용
μ·¨μ•½ν•œ API μ‚¬μš©
setTimeout() 및 setInterval() ν•¨μˆ˜μ˜ λΆ€μ μ ˆν•œ μ‚¬μš©
const userInput = "alert('Hello')"; setTimeout(userInput, 1000); // μ‚¬μš©μž μž…λ ₯을 μ½”λ“œλ‘œ μ‹€ν–‰
const userInput = "Hello"; setTimeout(() => { alert(userInput); }, 1000);
Javascript
API 였용
μ·¨μ•½ν•œ API μ‚¬μš©
Function μƒμ„±μžμ˜ λΆ€μ μ ˆν•œ μ‚¬μš©
const userInput = "return 2 + 2"; const func = new Function(userInput); console.log(func());
const userInput = "2 + 2"; const result = eval(userInput); // eval μ‚¬μš©μ€ 지양해야 ν•˜μ§€λ§Œ, μ˜ˆμ‹œλ₯Ό μœ„ν•΄ μ‚¬μš© console.log(result);
Javascript
API 였용
μ·¨μ•½ν•œ API μ‚¬μš©
document.write() ν•¨μˆ˜μ˜ λΆ€μ μ ˆν•œ μ‚¬μš©
const userInput = "<script>alert('XSS')</script>"; document.write(userInput);
const userInput = "Hello, World!"; const outputElement = document.getElementById('output'); const textNode = document.createTextNode(userInput); outputElement.appendChild(textNode);
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
SQL μ‚½μž…
SQL μ§ˆμ˜λ¬Έμ„ 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ 질의문이 μ‹€ν–‰κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render from django.db import connection def update_board(request): ...... dbconn = connection with dbconn.cursor() as curs: # μ™ΈλΆ€λ‘œλΆ€ν„° μž…λ ₯받은 값을 검증 없이 μ‚¬μš©ν•  경우 μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ name = request.POST.get('name', '') content_id = request.POST.get('content_id', '') # μ‚¬μš©μžμ˜ κ²€μ¦λ˜μ§€ μ•Šμ€ μž…λ ₯값을 μ‚¬μš©ν•΄ 동적 쿼리문 생성 sql_query = "update board set name='" + name + "' where content_id='β€œ + content_id + "'" # μ™ΈλΆ€ μž…λ ₯값이 검증 없이 쿼리둜 ν¬ν•¨λ˜μ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ curs.execute(sql_query) dbconn.commit() return render(request, '/success.html')
from django.shortcuts import render from django.db import connection def update_board(request): ...... dbconn = connection with dbconn.cursor() as curs: name = request.POST.get('name', '') content_id = request.POST.get('content_id', '') # μ™ΈλΆ€ μž…λ ₯κ°’ μ‘°μž‘μœΌλ‘œλΆ€ν„° μ•ˆμ „ν•œ μΈμžν™”λœ 쿼리λ₯Ό μƒμ„±ν•œλ‹€. sql_query = 'update board set name=%s where content_id=%s' # μ‚¬μš©μžμ˜ μž…λ ₯값이 μΈμžν™”λœ 쿼리에 바인딩 ν›„ μ‹€ν–‰λ˜λ―€λ‘œ μ•ˆμ „ν•˜λ‹€. curs.execute(sql_query, (name, content_id)) dbconn.commit() return render(request, '/success.html')
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
SQL μ‚½μž…
SQL μ§ˆμ˜λ¬Έμ„ 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ 질의문이 μ‹€ν–‰κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render from app.models import Member def member_search(request): name = request.POST.get('name', '') # μž…λ ₯값을 검증 없이 쿼리문 생성에 μ‚¬μš©ν•΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ query=β€œselect * from member where name=β€˜β€ + name + β€œβ€™β€ # μ™ΈλΆ€ μž…λ ₯값을 검증 없이 μ‚¬μš©ν•œ 쿼리문을 raw()ν•¨μˆ˜λ‘œ μ‹€ν–‰ν•˜λ©΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ data = Member.objects.raw(query) return render(request, '/member_list.html', {'member_list':data})
from django.shortcuts import render from app.models import Member def member_search(request): name = request.POST.get('name', '') # μ™ΈλΆ€ μž…λ ₯값을 raw() ν•¨μˆ˜ μ‹€ν–‰ μ‹œ 바인딩 λ³€μˆ˜λ‘œ μ‚¬μš©ν•˜μ—¬ 쿼리 ꡬ쑰가 # λ³€κ²½λ˜μ§€ μ•Šλ„λ‘ ν•œλ‹€.(list ν˜•μ€ %s, dictionary ν˜•μ€ %(key)sλ₯Ό μ‚¬μš©) query='select * from member where name=%s' # μΈμžν™”λœ 쿼리문을 μ‚¬μš©ν•˜μ—¬ raw() ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•΄ μ•ˆμ „ν•˜λ‹€ data = Member.objects.raw(query, [name]) return render(request, '/member_list.html', {'member_list':data})
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
μ½”λ“œ μ‚½μž…
ν”„λ‘œμ„ΈμŠ€κ°€ μ™ΈλΆ€ μž…λ ₯값을 μ½”λ“œ(λͺ…λ Ήμ–΄)둜 해석·싀행할 수 있고 ν”„λ‘œμ„ΈμŠ€μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•œ 경우 μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render def route(request): # μ™ΈλΆ€μ—μ„œ μž…λ ₯받은 값을 검증 없이 μ‚¬μš©ν•˜λ©΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ message = request.POST.get('message', '') # μ™ΈλΆ€ μž…λ ₯값을 검증 없이 eval ν•¨μˆ˜μ— 전달할 경우 μ˜λ„ν•˜μ§€ μ•Šμ€ μ½”λ“œκ°€ # 싀행될 수 μžˆμ–΄ μœ„ν—˜ν•˜λ‹€ ret = eval(message) return render(request, '/success.html', {'data':ret})
from django.shortcuts import render def route(request): message = request.POST.get('message', '') # μ‚¬μš©μž μž…λ ₯을 영문, 숫자둜 μ œν•œν•˜λ©°, λ§Œμ•½ μž…λ ₯κ°’ 내에 νŠΉμˆ˜λ¬Έμžκ°€ ν¬ν•¨λ˜μ–΄ # μžˆμ„ 경우 μ—λŸ¬ λ©”μ‹œμ§€λ₯Ό λ°˜ν™˜ ν•œλ‹€ if message.isalnum(): ret = eval(message) return render(request, '/success.html', {'data':ret}) return render(request, '/error.html')
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
μ½”λ“œ μ‚½μž…
ν”„λ‘œμ„ΈμŠ€κ°€ μ™ΈλΆ€ μž…λ ₯값을 μ½”λ“œ(λͺ…λ Ήμ–΄)둜 해석·싀행할 수 있고 ν”„λ‘œμ„ΈμŠ€μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•œ 경우 μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render def request_rest_api(request): function_name = request.POST.get('function_name', '') # μ‚¬μš©μžμ—κ²Œ 전달받은 ν•¨μˆ˜λͺ…을 κ²€μ¦ν•˜μ§€ μ•Šκ³  μ‹€ν–‰ # μž…λ ₯κ°’μœΌλ‘œ β€œ__import__(β€˜platform’).system()” 등을 μž…λ ₯ μ‹œ # μ‹œμŠ€ν…œ 정보 λ…ΈμΆœ μœ„ν—˜μ΄ μžˆλ‹€ exec('{}()'.format(function_name)) return render(request, '/success.html')
from django.shortcuts import render WHITE_LIST = ['get_friends_list', 'get_address', 'get_phone_number'] def request_rest_api(request): function_name = request.POST.get('function_name', '') # μ‚¬μš© κ°€λŠ₯ν•œ ν•¨μˆ˜λ₯Ό ν™”μ΄νŠΈλ¦¬μŠ€νŠΈ λͺ©λ‘ λ‚΄μ˜ ν•¨μˆ˜λ‘œ μ œν•œ if function_name in WHITE_LIST: exec('{}()'.format(function_name)) return render(request, '/success.html') return render(request, '/error.html', {'error':'ν—ˆμš©λ˜μ§€ μ•Šμ€ ν•¨μˆ˜μž…λ‹ˆλ‹€.'})
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
경둜 μ‘°μž‘ 및 μžμ› μ‚½μž…
μ‹œμŠ€ν…œ μžμ› μ ‘κ·Όκ²½λ‘œ λ˜λŠ” μžμ›μ œμ–΄ λͺ…령어에 κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‹œμŠ€ν…œ μžμ›μ— 무단 μ ‘κ·Ό 및 μ•…μ˜μ μΈ ν–‰μœ„κ°€ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import os from django.shortcuts import render def get_info(request): # μ™ΈλΆ€ μž…λ ₯κ°’μœΌλ‘œλΆ€ν„° 파일λͺ…을 μž…λ ₯ λ°›λŠ”λ‹€ request_file = request.POST.get('request_file') (filename, file_ext) = os.path.splitext(request_file) file_ext = file_ext.lower() if file_ext not in ['.txt', '.csv']: return render(request, '/error.html', {'error':'νŒŒμΌμ„ μ—΄ 수 μ—†μŠ΅λ‹ˆλ‹€.'}) # μž…λ ₯값을 검증 없이 파일 μ²˜λ¦¬μ— μ‚¬μš©ν–ˆλ‹€ with open(request_file) as f: data = f.read() return render(request, '/success.html', {'data':data})
import os from django.shortcuts import render def get_info(request): request_file = request.POST.get('request_file') (filename, file_ext) = os.path.splitext(request_file) file_ext = file_ext.lower() # μ™ΈλΆ€ μž…λ ₯κ°’μœΌλ‘œ 받은 파일 이름은 κ²€μ¦ν•˜μ—¬ μ‚¬μš©ν•œλ‹€. if file_ext not in ['.txt', '.csv']: return render(request, '/error.html', {'error':'νŒŒμΌμ„ μ—΄μˆ˜ μ—†μŠ΅λ‹ˆλ‹€.'}) # 파일 λͺ…μ—μ„œ 경둜 μ‘°μž‘ λ¬Έμžμ—΄μ„ 필터링 ν•œλ‹€. filename = filename.replace('.', '') filename = filename.replace('/', '') filename = filename.replace('\\', '') try: with open(filename + file_ext) as f: data = f.read() except Exception: return render( request, "/error.html", {"error": "파일이 μ‘΄μž¬ν•˜μ§€ μ•Šκ±°λ‚˜ μ—΄ 수 μ—†λŠ” νŒŒμΌμž…λ‹ˆλ‹€."} ) return render(request, '/success.html', {'data':data})
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
경둜 μ‘°μž‘ 및 μžμ› μ‚½μž…
μ‹œμŠ€ν…œ μžμ› μ ‘κ·Όκ²½λ‘œ λ˜λŠ” μžμ›μ œμ–΄ λͺ…령어에 κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‹œμŠ€ν…œ μžμ›μ— 무단 μ ‘κ·Ό 및 μ•…μ˜μ μΈ ν–‰μœ„κ°€ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import socket from django.shortcuts import render def get_info(request): port = int(request.POST.get('port')) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: # μ™ΈλΆ€λ‘œλΆ€ν„° μž…λ ₯받은 κ²€μ¦λ˜μ§€ μ•Šμ€ 포트 번호λ₯Ό μ΄μš©ν•˜μ—¬ # μ†ŒμΌ“μ„ λ°”μΈλ”©ν•˜μ—¬ μ‚¬μš©ν•˜κ³  μžˆμ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ s.bind(('127.0.0.1', port)) ... return render(request, '/success.html') return render(request, '/error.html', {'error':'μ†ŒμΌ“μ—°κ²° μ‹€νŒ¨'})
import socket from django.shortcuts import render ALLOW_PORT = [4000, 6000, 9000] def get_info(request): port = int(request.POST.get('port')) # μ‚¬μš© κ°€λŠ₯ν•œ 포트 번호λ₯Ό ν™”μ΄νŠΈλ¦¬μŠ€νŠΈ λ‚΄μ˜ 포트둜 μ œν•œ if port not in ALLOW_PORT: return render(request, '/error.html', {'error':'μ†ŒμΌ“μ—°κ²° μ‹€νŒ¨'}) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(('127.0.0.1', port)) ...... return render(request, '/success.html')
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ 슀크립트(XSS)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ μŠ€ν¬λ¦½νŠΈκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render from django.utils.safestring import mark_safe def profile_link(request): # μ™ΈλΆ€ μž…λ ₯값을 검증 없이 HTML νƒœκ·Έ μƒμ„±μ˜ 인자둜 μ‚¬μš© profile_url = request.POST.get('profile_url') profile_name = requst.POST.get('profile_name') object_link = '<a href="{}">{}</a>'.format(profile_url, profile_name) # mark_safeν•¨μˆ˜λŠ” Django의 XSS escape 정책을 λ”°λ₯΄μ§€ μ•ŠλŠ”λ‹€ object_link = mark_safe(object_link) return render(request, 'my_profile.html',{'object_link':object_link})
from django.shortcuts import render def profile_link(request): # μ™ΈλΆ€ μž…λ ₯값을 검증 없이 HTML νƒœκ·Έ μƒμ„±μ˜ 인자둜 μ‚¬μš© profile_url = request.POST.get('profile_url') profile_name = requst.POST.get('profile_name') object_link = '<a href="{}">{}</a>'.format(profile_url, profile_name) # μ‹ λ’°ν•  수 μ—†λŠ” 데이터에 λŒ€ν•΄μ„œλŠ” mark_safe ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄μ„  μ•ˆ λœλ‹€ return render(request, 'my_profile.html',{'object_link':object_link})
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ 슀크립트(XSS)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ μŠ€ν¬λ¦½νŠΈκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
<!doctype html> <html> <body> <div class="content"> {% autoescape off %} <!-- autoescape off둜 μ„€μ •ν•˜λ©΄ ν•΄λ‹Ή λΈ”λ‘λ‚΄μ˜ λ°μ΄ν„°λŠ” XSS 곡격에 λ…ΈμΆœλ  수 μžˆλ‹€ --> {{ content }} {% endautoescape %} </div> <div class="content2"> <!-- safe ν•„ν„° μ‚¬μš©μœΌλ‘œ XSS 곡격에 λ…ΈμΆœλ  수 μžˆλ‹€ --> {{ content | safe }} </div> </body> </html>
<!doctype html> <html> <body> <div class="content"> {% autoescape on %} <!--autoescape on으둜 ν•΄λ‹Ή λΈ”λ‘λ‚΄μ˜ λ°μ΄ν„°λŠ” XSS 곡격에 λ…ΈμΆœλ˜μ§€ μ•ŠμŒ. --> {{ content }} {% endautoescape %} </div> <div class="content2"> <!-- κ²€μ¦λ˜μ§€ μ•Šμ€ λ°μ΄ν„°μ—λŠ” safe ν•„ν„°λ₯Ό μ‚¬μš©ν•˜μ§€ μ•ŠλŠ”λ‹€. --> {{ content }} </div> </body> </html>
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ 슀크립트(XSS)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ μŠ€ν¬λ¦½νŠΈκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from flask import Flask, request, render_template @app.route('/search', methods=['POST']) def search(): search_keyword = request.form.get('search_keyword') # μ‚¬μš©μžμ˜ μž…λ ₯을 μ•„λ¬΄λŸ° 검증 λ˜λŠ” μΉ˜ν™˜ 없이 동적 μ›ΉνŽ˜μ΄μ§€μ— μ‚¬μš©ν•˜κ³  μžˆμ–΄ # XSS 곡격이 λ°œμƒν•  수 μžˆλ‹€ return render_template('search.html', search_keyword=search_keyword)
import html from flask import Flask, request, render_template @app.route('/search', methods=['POST']) def search(): search_keyword = request.form.get('search_keyword') # 동적 μ›ΉνŽ˜μ΄μ§€ 생성에 μ‚¬μš©λ˜λŠ” λ°μ΄ν„°λŠ” # HTML μ—”ν‹°ν‹°μ½”λ“œλ‘œ μΉ˜ν™˜ν•˜μ—¬ ν‘œν˜„ν•΄μ•Ό ν•œλ‹€ escape_keyword = html.escape(search_keyword) return render_template('search.html', search_keyword=escape_keyword)
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
운영체제 λͺ…λ Ήμ–΄ μ‚½μž…
운영체제 λͺ…λ Ήμ–΄λ₯Ό 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ λͺ…λ Ήμ–΄κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import os from django.shortcuts import render def execute_command(request): app_name_string = request.POST.get('app_name','') # μž…λ ₯ νŒŒλΌλ―Έν„°λ₯Ό μ œν•œν•˜μ§€ μ•Šμ•„ μ™ΈλΆ€ μž…λ ₯κ°’μœΌλ‘œ μ „λ‹¬λœ # λͺ¨λ“  ν”„λ‘œκ·Έλž¨μ΄ 싀행될 수 있음 os.system(app_name_string) return render(request, '/success.html')
import os from django.shortcuts import render ALLOW_PROGRAM = ['notepad', 'calc'] def execute_command(request): app_name_string = request.POST.get('app_name','') # μž…λ ₯받은 νŒŒλΌλ―Έν„°κ°€ ν—ˆμš©λœ μ‹œμŠ€ν…œ λͺ…λ Ήμ–΄ λͺ©λ‘μ— ν¬ν•¨λ˜λŠ”μ§€ 검사 if app_name_string not in ALLOW_PROGRAM: return render(request, '/error.html', {'error':'ν—ˆμš©λ˜μ§€ μ•Šμ€ ν”„λ‘œκ·Έλž¨μž…λ‹ˆλ‹€.'}) os.system(app_name_string) return render(request, '/success.html')
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
운영체제 λͺ…λ Ήμ–΄ μ‚½μž…
운영체제 λͺ…λ Ήμ–΄λ₯Ό 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ λͺ…λ Ήμ–΄κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import subprocess from django.shortcuts import render def execute_command(request): date = request.POST.get('date','') # μž…λ ₯받은 νŒŒλΌλ―Έν„°λ₯Ό μ œν•œν•˜μ§€ μ•Šμ•„ μ „λ‹¬λœ λͺ¨λ“  ν”„λ‘œκ·Έλž¨μ΄ 싀행될 수 있음 cmd_str = β€œcmd /c backuplog.bat ” + date subprocess.run(cmd_str, shell=True) return render(request, '/success.html')
import subprocess from django.shortcuts import render def execute_command(request): date = request.POST.get('date','') # λͺ…λ Ήμ–΄λ₯Ό μΆ”κ°€λ‘œ μ‹€ν–‰ λ˜λŠ” 또 λ‹€λ₯Έ λͺ…령이 싀행될 수 μžˆλŠ” ν‚€μ›Œλ“œμ— # λŒ€ν•œ μ˜ˆμ™Έμ²˜λ¦¬ for word in ['|', ';', '&', ':', '>', '<', '`', '\\', '!']: date = date.replace(word, β€œβ€) # re.sub ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄ 특수문자λ₯Ό μ œκ±°ν•˜λŠ” 방법도 μžˆλ‹€ # date = re.sub('[|;&:><`\\\!]', '', date) # shell=True μ˜΅μ…˜μ€ 제거 ν•˜κ³  λͺ…λ Ήκ³Ό 인자λ₯Ό λ°°μ—΄λ‘œ μž…λ ₯ subprocess.run(["cmd", "/c", "backuplog.bat", date]) return render(request, '/success.html')
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
μœ„ν—˜ν•œ ν˜•μ‹ 파일 μ—…λ‘œλ“œ
파일의 ν™•μž₯자 λ“± νŒŒμΌν˜•μ‹μ— λŒ€ν•œ 검증없이 파일 μ—…λ‘œλ“œλ₯Ό ν—ˆμš©ν•˜μ—¬ 곡격이 κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render from django.core.files.storage import FileSystemStorage def file_upload(request): if request.FILES['upload_file']: # μ‚¬μš©μžκ°€ μ—…λ‘œλ“œν•˜λŠ” νŒŒμΌμ„ 검증 없이 μ €μž₯ν•˜κ³  μžˆμ–΄ # μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ upload_file = request.FILES['upload_file'] fs = FileSystemStorage(location='media/screenshot', base_url='media/screenshot') # μ—…λ‘œλ“œ ν•˜λŠ” νŒŒμΌμ— λŒ€ν•œ 크기, 개수, ν™•μž₯자 등을 κ²€μ¦ν•˜μ§€ μ•ŠμŒ filename = fs.save(upload_file.name, upload_file) return render(request, '/success.html', {'filename':filename}) return render(request, '/error.html', {'error':'파일 μ—…λ‘œλ“œ μ‹€νŒ¨'})
import os from django.shortcuts import render from django.core.files.storage import FileSystemStorage # μ—…λ‘œλ“œ ν•˜λŠ” 파일 개수, 크기, ν™•μž₯자 μ œν•œ FILE_COUNT_LIMIT = 5 # μ—…λ‘œλ“œ ν•˜λŠ” 파일의 μ΅œλŒ€ μ‚¬μ΄μ¦ˆ μ œν•œ 예 ) 5MB - 5*1024*1024 FILE_SIZE_LIMIT = 5242880 # ν—ˆμš©ν•˜λŠ” ν™•μž₯μžλŠ” ν™”μ΄νŠΈλ¦¬μŠ€νŠΈλ‘œ κ΄€λ¦¬ν•œλ‹€. WHITE_LIST_EXT = [ '.jpg', '.jpeg' ] def file_upload(request): # 파일 개수 μ œν•œ if len(request.FILES) == 0 or len(request.FILES) > FILE_COUNT_LIMIT: return render(request, '/error.html', {'error': '파일 개수 초과'}) for filename, upload_file in request.FILES.items(): # 파일 νƒ€μž… 체크 if upload_file.content_type != 'image/jpeg': return render(request, '/error.html', {'error': '파일 νƒ€μž… 였λ₯˜'}) # 파일 크기 μ œν•œ if upload_file.size > FILE_SIZE_LIMIT: return render(request, '/error.html', {'error': 'νŒŒμΌμ‚¬μ΄μ¦ˆ 였λ₯˜'}) # 파일 ν™•μž₯자 검사 file_name, file_ext = os.path.splitext(upload_file.name) if file_ext.lower() not in WHITE_LIST_EXT: return render(request, '/error.html', {'error': '파일 νƒ€μž… 였λ₯˜'}) fs = FileSystemStorage(location='media/screenshot', base_url = 'media/screenshot') for upload_file in request.FILES.values(): filename = fs.save(upload_file.name, upload_file) filename_list.append(filename) return render(request, "/success.html", {"filename_list": filename_list})
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
μ‹ λ’°λ˜μ§€ μ•Šμ€ URLμ£Όμ†Œλ‘œ μžλ™μ ‘μ† μ—°κ²°
URL 링크 생성에 κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ μ‚¬μ΄νŠΈλ‘œ μžλ™ 접속 κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import redirect def redirect_url(request): url_string = request.POST.get('url', '') # μ‚¬μš©μž μž…λ ₯에 ν¬ν•¨λœ URL μ£Όμ†Œλ‘œ λ¦¬λ‹€μ΄λ ‰νŠΈ ν•˜λŠ” 경우 # ν”Όμ‹± μ‚¬μ΄νŠΈλ‘œ μ ‘μ†λ˜λŠ” λ“± μ‚¬μš©μžκ°€ ν”Όμ‹± 곡격에 λ…ΈμΆœλ  수 μžˆλ‹€ return redirect(url_string)
from django.shortcuts import render, redirect ALLOW_URL_LIST = [ '127.0.0.1', '192.168.0.1', '192.168.0.100', 'https://login.myservice.com', '/notice', ] def redirect_url(request): url_string = request.POST.get('url', '') # 이동할 수 μžˆλŠ” URL λ²”μœ„λ₯Ό μ œν•œν•˜μ—¬ # μœ„ν—˜ν•œ μ‚¬μ΄νŠΈμ˜ 접근을 μ°¨λ‹¨ν•˜κ³  μžˆλ‹€ if url_string not in ALLOW_URL_LIST: return render(request, '/error.html', {'error':'ν—ˆμš©λ˜μ§€ μ•ŠλŠ” μ£Όμ†Œμž…λ‹ˆλ‹€.'}) return redirect(url_string)
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
λΆ€μ μ ˆν•œ XML μ™ΈλΆ€ 개체 μ°Έμ‘°
μž„μ˜λ‘œ μ‘°μž‘λœ XML μ™ΈλΆ€κ°œμ²΄μ— λŒ€ν•œ μ μ ˆν•œ 검증 없이 μ°Έμ‘°λ₯Ό ν—ˆμš©ν•˜μ—¬ 곡격이 κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE foo [ <!ELEMENT foo ANY > <!ENTITY xxe1 SYSTEM "file:///etc/passwd" > <!ENTITY xxe2 SYSTEM "http://attacker.com/text.txt"> ]> <foo>&xxe1;&xxe2;</foo> from xml.sax import make_parser from xml.sax.handler import feature_external_ges from xml.dom.pulldom import parseString, START_ELEMENT from django.shortcuts import render from .model import comments def get_xml(request): if request.method == "GET": data = comments.objects.all() com = data[0].comment return render(request, '/xml_view.html', {'com': com}) elif request.method == "POST": parser = make_parser() # μ™ΈλΆ€ 일반 μ—”ν‹°ν‹°λ₯Ό ν¬ν•¨ν•˜λŠ” 섀정을 True둜 μ μš©ν•  경우 μ·¨μ•½ν•˜λ‹€ parser.setFeature(feature_external_ges, True) doc = parseString(request.body.decode('utf-8'), parser=parser) for event, node in doc: if event == START_ELEMENT and node.tagName == "foo": doc.expandNode(node) text = node.toxml() comments.objects.filter(id=1).update(comment=text) return render(request, '/xml_view.html')
from xml.sax import make_parser from xml.sax.handler import feature_external_ges from xml.dom.pulldom import parseString, START_ELEMENT from django.shortcuts import render from .model import comments def get_xml(request): if request.method == β€œGET”: data = comments.objects.all() com = data[0].comment return render(request, '/xml_view.html', {'com':com}) elif request.method == β€œPOST”: parser = make_parser() parser.setFeature(feature_external_ges, False) doc = parseString(request.body.decode(β€˜utf-8’), parser=parser) for event, node in doc: if event == START_ELEMENT and node.tagName == β€œfoo”: doc.expandNode(node) text = node.toxml() comments.objects.filter(id=1).update(comment=text); return render(request, '/xml_view.html')
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
XML μ‚½μž…
XQuery, XPath μ§ˆμ˜λ¬Έμ„ 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ 질의문이 μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render from lxml import etree def parse_xml(request): user_name = request.POST.get('user_name', '') parser = etree.XMLParser(resolve_entities=False) tree = etree.parse('user.xml', parser) root = tree.getroot() # κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯κ°’ user_name을 μ‚¬μš©ν•œ μ•ˆμ „ν•˜μ§€ μ•Šμ€ # 질의문이 query λ³€μˆ˜μ— μ €μž₯ query = "/collection/users/user[@name='" + user_name + "']/home/text()" elmts = root.xpath(query) return render(request, 'parse_xml.html', {'xml_element':elmts})
from django.shortcuts import render from lxml import etree def parse_xml(request): user_name = request.POST.get('user_name', '') parser = etree.XMLParser(resolve_entities=False) tree = etree.parse('user.xml', parser) root = tree.getroot() # μ™ΈλΆ€ μž…λ ₯값을 paramname으둜 μΈμžν™” ν•΄μ„œ μ‚¬μš© query = '/collection/users/user[@name = $paramname]/home/text()' elmts = root.xpath(query, paramname=user_name) return render(request, 'parse_xml.html', {'xml_element':elmts})
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
LDAP μ‚½μž…
LDAP λͺ…령문을 생성할 λ•Œ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ λͺ…λ Ήμ–΄κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from ldap3 import Connection, Server, ALL from django.shortcuts import render config = { "bind_dn": "cn=read-only-admin,dc=example,dc=com", "password": "password", } def ldap_query(request): search_keyword = request.POST.get('search_keyword','') dn = config['bind_dn'] password = config['password'] address = 'ldap.badSoruce.com' server = Server(address, get_info=ALL) conn = Connection(server, user=dn, password, auto_bind=True ) # μ‚¬μš©μž μž…λ ₯을 필터링 ν•˜μ§€ μ•ŠλŠ” 경우 곡격자의 κΆŒν•œ μƒμŠΉμœΌλ‘œ # μ΄μ–΄μ§ˆ 수 μžˆλ‹€ search_str = '(&(objectclass=%s))' % search_keyword conn.search( 'dc=company,dc=com', search_str, attributes=['sn', 'cn', 'address', 'mail', 'mobile', 'uid'], ) return render(request, '/ldap_query_response.html', {'ldap':conn.entries})
from ldap3 import Connection, Server, ALL from ldap3.utils.conv import escape_filter_chars from django.shortcuts import render config = { "bind_dn": "cn=read-only-admin,dc=example,dc=com", "password": "password", } def ldap_query(request): search_keyword = request.POST.get('search_keyword','') dn = config['bind_dn'] password = config['password'] address = 'ldap.goodsource.com' server = Server(address, get_info=ALL) conn = Connection(server, dn, password, auto_bind=True ) # μ‚¬μš©μžμ˜ μž…λ ₯에 필터링을 μ μš©ν•˜μ—¬ 곡격에 μ‚¬μš©λ  수 μžˆλŠ” 문자λ₯Ό # μ΄μŠ€μΌ€μ΄ν”„ν•˜κ³  μžˆλ‹€ escpae_keyword = escape_filter_chars(search_keyword) search_str = '(&(objectclass=%s))' % escpae_keyword conn.search( 'dc=company,dc=com', search_str, attributes=['sn', 'cn', 'address', 'mail', 'mobile', 'uid'], ) return render(request, '/ldap_query_response.html', {'ldap':conn.entries})
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ μš”μ²­ μœ„μ‘°(CSRF)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‚¬μš©μž 본인의 μ˜μ§€μ™€λŠ” λ¬΄κ΄€ν•˜κ²Œ κ³΅κ²©μžκ°€ μ˜λ„ν•œ ν–‰μœ„κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', # MIDDLEWARE λͺ©λ‘μ—μ„œ CSRF ν•­λͺ©μ„ μ‚­μ œ λ˜λŠ” μ£Όμ„μ²˜λ¦¬ ν•˜λ©΄ # Django μ•±μ—μ„œ CSRF μœ νš¨μ„± 검사가 μ „μ—­μ μœΌλ‘œ μ œκ±°λœλ‹€ # 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', ...... ]
MIDDLEWARE = [ 'django.contrib.sessions.middleware.SessionMiddleware', # MIDDLEWARE λͺ©λ‘μ—μ„œ CSRF ν•­λͺ©μ„ ν™œμ„±ν™” ν•œλ‹€ 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', ...... ]
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ μš”μ²­ μœ„μ‘°(CSRF)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‚¬μš©μž 본인의 μ˜μ§€μ™€λŠ” λ¬΄κ΄€ν•˜κ²Œ κ³΅κ²©μžκ°€ μ˜λ„ν•œ ν–‰μœ„κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt # csrf.exempt λ°μ½”λ ˆμ΄ν„°λ‘œ λ―Έλ“€μ›¨μ–΄μ—μ„œ λ³΄ν˜Έλ˜λŠ” CSRF κΈ°λŠ₯을 ν•΄μ œν•œλ‹€ @csrf.exempt def pay_to_point(request): user_id = request.POST.get('user_id', '') pay = request.POST.get('pay', '') product_info = request.POST.get('product_info', '') ret = handle_pay(user_id, pay, product_info) return render(request, '/view_wallet.html', {'wallet':ret})
from django.shortcuts import render from django.template import RequestContext # csrf_exempt λ°μ½”λ ˆμ΄ν„°λ₯Ό μ‚­μ œν•˜κ±°λ‚˜ 주석 μ²˜λ¦¬ν•œλ‹€. # @csrf_exempt def pay_to_point(request): user_id = request.POST.get('user_id', '') pay = request.POST.get('pay', '') product_info = request.POST.get('product_info', '') ret = handle_pay(user_id, pay, product_info) return render(request, '/view_wallet.html', {'wallet':ret})
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ μš”μ²­ μœ„μ‘°(CSRF)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‚¬μš©μž 본인의 μ˜μ§€μ™€λŠ” λ¬΄κ΄€ν•˜κ²Œ κ³΅κ²©μžκ°€ μ˜λ„ν•œ ν–‰μœ„κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
<!--html page--> <form action="" method="POST"> <!-- form νƒœκ·Έ 내뢀에 csrf_token 미적용--> <table> {{form.as_table}} </table> <input type="submit"/> </form>
<!--html page--> <form action="" method="POST"> {% csrf_token %} <!--csrf_token μ‚¬μš©-> <table> {{form.as_table}} </table> <input type="submit"/> </form>
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ μš”μ²­ μœ„μ‘°(CSRF)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‚¬μš©μž 본인의 μ˜μ§€μ™€λŠ” λ¬΄κ΄€ν•˜κ²Œ κ³΅κ²©μžκ°€ μ˜λ„ν•œ ν–‰μœ„κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from flask import Flask app = Flask(__name__)
from flask import Flask from flask_wtf.csrf import CSRFProtect # CSRF μ„€μ • μΆ”κ°€ csrf = CSRFProtect(app) app = Flask(__name__) app.config[β€˜SECRET_KEY’] = os.environ.get('SECRET_KEY') csrf.init_app(app)
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
ν¬λ‘œμŠ€μ‚¬μ΄νŠΈ μš”μ²­ μœ„μ‘°(CSRF)
μ‚¬μš©μž λΈŒλΌμš°μ €μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ‚¬μš©μž 본인의 μ˜μ§€μ™€λŠ” λ¬΄κ΄€ν•˜κ²Œ κ³΅κ²©μžκ°€ μ˜λ„ν•œ ν–‰μœ„κ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
<form action="" method="POST"> <!-- form νƒœκ·Έ 내뢀에 csrf_token 미적용--> <table> {{as_table}} </table> <input type="submit"/> </form>
<form action="" method="POST"> <!-- form νƒœκ·Έ 내뢀에 csrf_token 적용--> <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" /> <table> {{table}} </table> <input type="submit"/> </form>
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
μ„œλ²„μ‚¬μ΄λ“œ μš”μ²­ μœ„μ‘°
μ„œλ²„ κ°„ μ²˜λ¦¬λ˜λŠ” μš”μ²­μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ κ³΅κ²©μžκ°€ μ˜λ„ν•œ μ„œλ²„λ‘œ μ „μ†‘ν•˜κ±°λ‚˜ λ³€μ‘°ν•˜λŠ” λ³΄μ•ˆμ•½μ 
from django.shortcuts import render import requests def call_third_party_api(request): addr = request.POST.get('address', '') # μ‚¬μš©μžκ°€ μž…λ ₯ν•œ μ£Όμ†Œλ₯Ό κ²€μ¦ν•˜μ§€ μ•Šκ³  HTTP μš”μ²­μ„ 보낸 ν›„ # 응닡을 μ‚¬μš©μžμ—κ²Œ λ°˜ν™˜ result = requests.get(addr).text return render(request, '/result.html', {'result':result})
from django.shortcuts import render import requests # ν—ˆμš©ν•˜λŠ” 도메인을 ν™”μ΄νŠΈλ¦¬μŠ€νŠΈμ— μ •μ˜ν•  경우 DNS rebinding 곡격 등에 # λ…ΈμΆœλ  μœ„ν—˜μ΄ μžˆμ–΄ μ‹ λ’°ν•  수 μžˆλŠ” μžμ›μ— λŒ€ν•œ IPλ₯Ό μ‚¬μš©ν•΄ # κ²€μ¦ν•˜λŠ” 것이 쑰금 더 μ•ˆμ „ν•˜λ‹€ ALLOW_SERVER_LIST = [ 'https://127.0.0.1/latest/', 'https://192.168.0.1/user_data', 'https://192.168.0.100/v1/public', ] def call_third_party_api(request): addr = request.POST.get('address', '') # μ‚¬μš©μžκ°€ μž…λ ₯ν•œ URL을 ν™”μ΄νŠΈλ¦¬μŠ€νŠΈλ‘œ κ²€μ¦ν•œ ν›„ κ·Έ κ²°κ³Όλ₯Ό λ°˜ν™˜ν•˜μ—¬ # κ²€μ¦λ˜μ§€ μ•Šμ€ μ£Όμ†Œλ‘œ μš”μ²­μ„ 보내지 μ•Šλ„λ‘ μ œν•œν•œλ‹€ if addr not in ALLOW_SERVER_LIST: return render(request, '/error.html', {β€˜error’ = 'ν—ˆμš©λ˜μ§€ μ•Šμ€ μ„œλ²„μž…λ‹ˆλ‹€.'}) result = requests.get(addr).text return render(request, '/result.html', {'result':result})
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
HTTP 응닡뢄할
HTTP 응닡헀더에 κ°œν–‰λ¬Έμž(CRμ΄λ‚˜ LF)κ°€ ν¬ν•¨λœ κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.http import HttpResponse def route(request): content_type = request.POST.get('content-type') # μ™ΈλΆ€ μž…λ ₯값을 검증 λ˜λŠ” 필터링 ν•˜μ§€ μ•Šκ³  # 응닡 ν—€λ”μ˜ κ°’μœΌλ‘œ ν¬ν•¨μ‹œμΌœ νšŒμ‹ ν•œλ‹€ ...... res = HttpResponse() res['Content-Type'] = content_type return res
from django.http import HttpResponse def route(request): content_type = request.POST.get('content-type') # 응닡헀더에 포함될 수 μžˆλŠ” μ™ΈλΆ€ μž…λ ₯κ°’ λ‚΄μ˜ κ°œν–‰ 문자λ₯Ό μ œκ±°ν•œλ‹€ content_type = content_type.replace('\r', '') content_type = content_type.replace('\n', '') ...... res = HttpResponse() res['Content-Type'] = content_type return res
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
μ •μˆ˜ν˜• μ˜€λ²„ν”Œλ‘œμš°
μ •μˆ˜ν˜• λ³€μˆ˜μ— μ €μž₯된 값이 ν—ˆμš©λœ μ •μˆ˜ κ°’ λ²”μœ„λ₯Ό λ²—μ–΄λ‚˜ ν”„λ‘œκ·Έλž¨μ΄ 예기치 μ•Šκ²Œ λ™μž‘ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import numpy as np def handle_data(number, pow): res = np.power(number, pow, dtype=np.int64) # 64λΉ„νŠΈλ₯Ό λ„˜μ–΄μ„œλŠ” μˆ«μžμ™€ μ§€μˆ˜κ°€ μž…λ ₯될 경우 μ˜€λ²„ν”Œλ‘œμš°κ°€ λ°œμƒν•΄ 결과값이 0이 λœλ‹€ return res
import numpy as np MAX_NUMBER = np.iinfo(np.int64).max MIN_NUMBER = np.iinfo(np.int64).min def handle_data(number, pow): calculated = number ** pow # 파이썬 κΈ°λ³Έ μžλ£Œν˜•μœΌλ‘œ 큰 수λ₯Ό κ³„μ‚°ν•œ ν›„ 이λ₯Ό 검사해 μ˜€λ²„ν”Œλ‘œμš° 탐지 if calculated > MAX_NUMBER or calculated < MIN_NUMBER: # μ˜€λ²„ν”Œλ‘œμš° 탐지 μ‹œ 비정상 μ’…λ£Œλ₯Ό λ‚˜νƒ€λ‚΄λŠ” –1 κ°’ λ°˜ν™˜ return –1 res = np.power(number, pow, dtype=np.int64) return res
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
λ³΄μ•ˆκΈ°λŠ₯ 결정에 μ‚¬μš©λ˜λŠ” λΆ€μ μ ˆν•œ μž…λ ₯κ°’
λ³΄μ•ˆκΈ°λŠ₯(인증, κΆŒν•œλΆ€μ—¬ λ“±) 결정에 κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ λ³΄μ•ˆκΈ°λŠ₯을 μš°νšŒν•˜λŠ” λ³΄μ•ˆμ•½μ 
from django.shortcuts import render def init_password(request): # μΏ ν‚€μ—μ„œ κΆŒν•œ 정보λ₯Ό κ°€μ Έ μ˜¨λ‹€ role = request.COOKIE['role'] request_id = request.POST.get('user_id', '') request_mail = request.POST.get('user_email','') # μΏ ν‚€μ—μ„œ κ°€μ Έμ˜¨ κΆŒν•œμ΄ κ΄€λ¦¬μžμΈμ§€ 비ꡐ if role == 'admin': # μ‚¬μš©μžμ˜ νŒ¨μŠ€μ›Œλ“œ μ΄ˆκΈ°ν™” 및 메일 λ°œμ†‘ 처리 password_init_and_sendmail(request_id, request_mail) return render(request, '/success.html') else: return render(request, '/failed.html')
from django.shortcuts import render def init_password(request): # μ„Έμ…˜μ—μ„œ κΆŒν•œ 정보λ₯Ό κ°€μ Έμ˜΄ role = request.session['role'] request_id = request.POST.get('user_id', '') request_mail = request.POST.get('user_email','') # μ„Έμ…˜μ—μ„œ κ°€μ Έμ˜¨ κΆŒν•œμ΄ κ΄€λ¦¬μžμΈμ§€ 비ꡐ if role == β€˜admin’: # μ‚¬μš©μžμ˜ νŒ¨μŠ€μ›Œλ“œ μ΄ˆκΈ°ν™” 및 메일 λ°œμ†‘ 처리 password_init_and_sendmail(request_id, request_mail) return render(request, '/sucess.html') else: return render(request, '/failed.html')
Python
μž…λ ₯데이터 검증 및 ν‘œν˜„
포맷 슀트링 μ‚½μž…
str.formatλ“± 포맷 슀트링 μ œμ–΄ν•¨μˆ˜μ— κ²€μ¦λ˜μ§€ μ•Šμ€ μ™ΈλΆ€ μž…λ ₯값을 ν—ˆμš©ν•˜μ—¬ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ * 포맷 슀트링: μž…Β·μΆœλ ₯μ—μ„œ ν˜•μ‹μ΄λ‚˜ ν˜•νƒœλ₯Ό μ§€μ •ν•΄μ£ΌλŠ” λ¬Έμžμ—΄
from django.shortcuts import render AUTHENTICATE_KEY = 'Passw0rd' def make_user_message(request): user_info = get_user_info(request.POST.get('user_id', '')) format_string = request.POST.get('msg_format', '') # λ‚΄λΆ€μ˜ λ―Όκ°ν•œ 정보가 μ™ΈλΆ€λ‘œ λ…ΈμΆœλ  수 μžˆλ‹€. # μ‚¬μš©μžκ°€ μž…λ ₯ν•œ λ¬Έμžμ—΄μ„ 포맷 λ¬Έμžμ—΄λ‘œ μ‚¬μš©ν•˜κ³  μžˆμ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ message = format_string.format(user=user_info) return render(request, '/user_page.html', {'message':message})
from django.shortcuts import render AUTHENTICATE_KEY = 'Passw0rd' def make_user_message(request): user_info = get_user_info(request.POST.get('user_id', '')) # μ‚¬μš©μžκ°€ μž…λ ₯ν•œ λ¬Έμžμ—΄μ„ 포맷 λ¬Έμžμ—΄λ‘œ μ‚¬μš©ν•˜μ§€ μ•Šμ•„ μ•ˆμ „ν•˜λ‹€ message = 'user name is {}'.format(user_info.name) return render(request, '/user_page.html', {'message':message})
Python
λ³΄μ•ˆκΈ°λŠ₯
μ μ ˆν•œ 인증 μ—†λŠ” μ€‘μš” κΈ°λŠ₯ ν—ˆμš©
μ€‘μš”μ •λ³΄(κΈˆμœ΅μ •λ³΄, κ°œμΈμ •λ³΄, 인증정보 λ“±)λ₯Ό μ μ ˆν•œ 인증없이 μ—΄λžŒ(λ˜λŠ” λ³€κ²½) κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render from re import escape import hashlib def change_password(request): new_pwd = request.POST.get('new_password','') # λ‘œκ·ΈμΈν•œ μ‚¬μš©μž 정보 user = '%s' % escape(request.session['userid']) # ν˜„μž¬ password와 일치 μ—¬λΆ€λ₯Ό ν™•μΈν•˜μ§€ μ•Šκ³  μˆ˜μ •ν•¨ sha = hashlib.sha256(new_pwd.encode()) update_password_from_db(user, sha.hexdigest()) return render(request, '/success.html')
from django.contrib.auth.decorators import login_required from django.shortcuts import render from re import escape import hashlib # login_required decoratorλ₯Ό μ‚¬μš©ν•΄ login된 μ‚¬μš©μžλ§Œ μ ‘κ·Όν•˜λ„λ‘ 처리 @login_required def change_password(request): new_pwd = request.POST.get('new_password','') crnt_pwd = request.POST.get('current_password','') # λ‘œκ·ΈμΈν•œ μ‚¬μš©μž 정보λ₯Ό μ„Έμ…˜μ—μ„œ κ°€μ Έμ˜¨λ‹€. user = '%s' % escape(request.session['userid']) crnt_h = hashlib.sha256(crnt_pwd.encode()) h_pwd = crnt_h.hexdigest() # DBμ—μ„œ κΈ°μ‘΄ μ‚¬μš©μžμ˜ Hash된 νŒ¨μŠ€μ›Œλ“œ κ°€μ Έμ˜€κΈ° old_pwd = get_password_from_db(user) # νŒ¨μŠ€μ›Œλ“œλ₯Ό λ³€κ²½ν•˜κΈ° μ „ μ‚¬μš©μžμ— λŒ€ν•œ μž¬μΈμ¦μ„ μˆ˜ν–‰ν•œλ‹€. if old_pwd == h_pwd: new_h = hashlib.sha256(new_pwd.encode()) update_password_from_db(user, new_h.hexdigest()) return render(request, '/success.html') else: return render(request, 'failed.html', {'error': 'νŒ¨μŠ€μ›Œλ“œκ°€ μΌμΉ˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€'})
Python
λ³΄μ•ˆκΈ°λŠ₯
λΆ€μ μ ˆν•œ 인가
μ€‘μš”μžμ›μ— μ ‘κ·Όν•  λ•Œ μ μ ˆν•œ μ œμ–΄κ°€ μ—†μ–΄ λΉ„μΈκ°€μžμ˜ 접근이 κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render from .model import Content def delete_content(request): action = request.POST.get('action', '') content_id = request.POST.get('content_id', '') # μž‘μ—… μš”μ²­μ„ ν•˜λŠ” μ‚¬μš©μžμ˜ κΆŒν•œ 확인 없이 deleteλ₯Ό μˆ˜ν–‰ if action is not None and action == "delete": Content.objects.filter(id=content_id).delete() return render(request, '/success.html') else: return render(request, '/error.html', {'error':'μ ‘κ·Ό κΆŒν•œμ΄ μ—†μŠ΅λ‹ˆλ‹€.'})
from django.contrib.auth.decorators import login_required, permission_required from django.shortcuts import render from .model import Content @login_required # ν•΄λ‹Ή κΈ°λŠ₯을 μˆ˜ν–‰ν•  κΆŒν•œμ΄ μžˆλŠ”μ§€ 확인 @permission_required('content.delete', raise_exception=True) def delete_content(request): action = request.POST.get('action', '') content_id = request.POST.get('content_id', '') if action is not None and action == "delete": Content.objects.filter(id=content_id).delete() return render(request, '/success.html') else: return render(request, '/error.html', {'error':'μ‚­μ œ μ‹€νŒ¨'})
Python
λ³΄μ•ˆκΈ°λŠ₯
μ€‘μš”ν•œ μžμ›μ— λŒ€ν•œ 잘λͺ»λœ κΆŒν•œ μ„€μ •
μ€‘μš”μžμ›μ— μ μ ˆν•œ μ ‘κ·Ό κΆŒν•œμ„ λΆ€μ—¬ν•˜μ§€ μ•Šμ•„ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœΒ·μˆ˜μ • κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import os def write_file(): # λͺ¨λ“  μ‚¬μš©μžκ°€ 읽기, μ“°κΈ°, μ‹€ν–‰ κΆŒν•œμ„ κ°€μ§€κ²Œ λœλ‹€. os.chmod('/root/system_config', 0o777) with open("/root/system_config", 'w') as f: f.write("your config is broken")
import os def write_file(): # μ†Œμœ μž μ™Έμ—λŠ” μ•„λ¬΄λŸ° κΆŒν•œμ„ 주지 μ•ŠμŒ. os.chmod('/root/system_config', 0o700) with open("/root/system_config", β€˜'w') as f: f.write("your config is broken")
Python
λ³΄μ•ˆκΈ°λŠ₯
μ·¨μ•½ν•œ μ•”ν˜Έν™” μ•Œκ³ λ¦¬μ¦˜ μ‚¬μš©
μ€‘μš”μ •λ³΄ (κΈˆμœ΅μ •λ³΄, κ°œμΈμ •λ³΄, 인증정보 λ“±)의 기밀성을 보μž₯ν•  수 μ—†λŠ” μ·¨μ•½ν•œ μ•”ν˜Έν™” μ•Œκ³ λ¦¬μ¦˜μ„ μ‚¬μš©ν•˜μ—¬ 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import base64 from Crypto.Cipher import DES from Crypto.Util.Padding import pad def get_enc_text(plain_text, key): # 취약함 μ•”ν˜Έν™” μ•Œκ³ λ¦¬μ¦˜μΈ DESλ₯Ό μ‚¬μš©ν•˜μ—¬ μ•ˆμ „ν•˜μ§€ μ•ŠμŒ cipher_des = DES.new(key, DES.MODE_ECB) encrypted_data = base64.b64encode(cipher_aes.encrypt(pad(plain_text, 32))) return encrypted_data.decode('ASCII')
import base64 from Crypto.Cipher import AES from Crypto.Util.Padding import pad def get_enc_text(plain_text, key, iv): # μ•ˆμ „ν•œ μ•Œκ³ λ¦¬μ¦˜μΈ AES λ₯Ό μ‚¬μš©ν•˜μ—¬ μ•ˆμ „ν•¨. cipher_aes = AES.new(key, AES.MODE_CBC, iv) encrypted_data = base64.b64encode(cipher_aes.encrypt(pad(plain_text, 32))) return encrypted_data.decode('ASCII')
Python
λ³΄μ•ˆκΈ°λŠ₯
μ·¨μ•½ν•œ μ•”ν˜Έν™” μ•Œκ³ λ¦¬μ¦˜ μ‚¬μš©
μ€‘μš”μ •λ³΄ (κΈˆμœ΅μ •λ³΄, κ°œμΈμ •λ³΄, 인증정보 λ“±)의 기밀성을 보μž₯ν•  수 μ—†λŠ” μ·¨μ•½ν•œ μ•”ν˜Έν™” μ•Œκ³ λ¦¬μ¦˜μ„ μ‚¬μš©ν•˜μ—¬ 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import hashlib def make_md5(plain_text): # μ·¨μ•½ν•œ md5 ν•΄μ‹œν•¨μˆ˜ μ‚¬μš© hash_text = hashlib.md5(plain_text.encode('utf-8')).hexdigest() return hash_text
import hashlib def make_sha256(plain_text): # μ•ˆμ „ν•œ sha-256 ν•΄μ‹œν•¨μˆ˜ μ‚¬μš© hash_text = hashlib.sha256(plain_text.encode('utf-8')).hexdigest() return hash_text
Python
λ³΄μ•ˆκΈ°λŠ₯
μ•”ν˜Έν™”λ˜μ§€ μ•Šμ€ μ€‘μš”μ •λ³΄
μ€‘μš”μ •λ³΄(νŒ¨μŠ€μ›Œλ“œ, κ°œμΈμ •λ³΄ λ“±) 전솑 μ‹œ μ•”ν˜Έν™” λ˜λŠ” μ•ˆμ „ν•œ 톡신채널을 μ΄μš©ν•˜μ§€ μ•Šκ±°λ‚˜, μ €μž₯ μ‹œ μ•”ν˜Έν™” ν•˜μ§€ μ•Šμ•„ 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
def update_pass(dbconn, password, user_id): curs = dbconn.cursor() # μ•”ν˜Έν™”λ˜μ§€ μ•Šμ€ νŒ¨μŠ€μ›Œλ“œλ₯Ό DB에 μ €μž₯ curs.execute( 'UPDATE USERS SET PASSWORD=%s WHERE USER_ID=%s', password, user_id ) dbconn.commit()
from Crypto.Hash import SHA256 def update_pass(dbconn, password, user_id, salt): # 단방ν–₯ μ•”ν˜Έν™”λ₯Ό μ΄μš©ν•˜μ—¬ νŒ¨μŠ€μ›Œλ“œλ₯Ό μ•”ν˜Έν™” hash_obj = SHA256.new() hash_obj.update(bytes(password + salt, 'utf-8')) hash_pwd = hash_obj.hexdigest() curs = dbconn.cursor() curs.execute( 'UPDATE USERS SET PASSWORD=%s WHERE USER_ID=%s', (hash_pwd, user_id) ) dbconn.commit()
Python
λ³΄μ•ˆκΈ°λŠ₯
μ•”ν˜Έν™”λ˜μ§€ μ•Šμ€ μ€‘μš”μ •λ³΄
μ€‘μš”μ •λ³΄(νŒ¨μŠ€μ›Œλ“œ, κ°œμΈμ •λ³΄ λ“±) 전솑 μ‹œ μ•”ν˜Έν™” λ˜λŠ” μ•ˆμ „ν•œ 톡신채널을 μ΄μš©ν•˜μ§€ μ•Šκ±°λ‚˜, μ €μž₯ μ‹œ μ•”ν˜Έν™” ν•˜μ§€ μ•Šμ•„ 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import socket HOST = '127.0.0.1' PORT = 65434 def send_password(password): ...... with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) # νŒ¨μŠ€μ›Œλ“œλ₯Ό μ•”ν˜Έν™” ν•˜μ§€ μ•Šκ³  μ „μ†‘ν•˜μ—¬ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. s.sendall(password.encode('utf-8')) data = s.recv(1024) .......
import socket import os from Crypto.Cipher import AES HOST = '127.0.0.1' PORT = 65434 def send_password(password): # λ¬Έμžμ—΄λ‘œ μ €μž₯λ˜μ–΄ μžˆλŠ” 블둝킀λ₯Ό λ‘œλ“œ block_key = os.environ.get('BLOCK_KEY') aes = AEScipher(block_key) # νŒ¨μŠ€μ›Œλ“œ λ“± μ€‘μš” μ •λ³΄λŠ” μ•”ν˜Έν™”ν•˜μ—¬ μ „μ†‘ν•˜λŠ” 것이 μ•ˆμ „ν•˜λ‹€ enc_passowrd = aes.encrypt(passowrd) with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) s.sendall(enc_passowrd.encode('utf-8')) data = s.recv(1024) ....... class AEScipher: BS = AES.block_size def __init__(self, s_key): self.s_key = hashlib.sha256(s_key.encode("utf-8")).digest() def pad(self, m): return m + bytes([self.BS - len(m) % self.BS] * (self.BS - len(m) % self.BS)) def encrypt(self, plain): plain = self.pad(plain.encode()) iv = Random.new().read(AES.block_size) cipher = AES.new(self.s_key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(plain)).decode("utf-8") .......
Python
λ³΄μ•ˆκΈ°λŠ₯
ν•˜λ“œμ½”λ“œλœ μ€‘μš”μ •λ³΄
μ†ŒμŠ€μ½”λ“œμ— μ€‘μš”μ •λ³΄(νŒ¨μŠ€μ›Œλ“œ, μ•”ν˜Έν™”ν‚€ λ“±)λ₯Ό 직접 μ½”λ”©ν•˜μ—¬ μ†ŒμŠ€μ½”λ“œ 유좜 μ‹œ μ€‘μš”μ •λ³΄κ°€λ…ΈμΆœλ˜κ³  주기적 변경이 μ–΄λ €μš΄ λ³΄μ•ˆμ•½μ 
import pymysql def query_execute(query): # user, passwdκ°€ μ†ŒμŠ€μ½”λ“œμ— ν‰λ¬ΈμœΌλ‘œ ν•˜λ“œμ½”λ”©λ˜μ–΄ 있음 dbconn = pymysql.connect( host='127.0.0.1', port='1234', user='root', passwd='1234', db='mydb', charset='utf8', ) curs = dbconn.cursor() curs.execute(query) dbconn.commit() dbconn.close()
import pymysql import json def query_execute(query, config_path): with open(config_path, 'r') as config: # μ„€μ • νŒŒμΌμ—μ„œ user, passwdλ₯Ό 가져와 μ‚¬μš© dbconf = json.load(fp=config) # μ•”ν˜Έν™”λ˜μ–΄ μžˆλŠ” 블둝 μ•”ν˜Έν™” ν‚€λ₯Ό λ³΅ν˜Έν™” ν•΄μ„œ κ°€μ Έμ˜€λŠ” # μ‚¬μš©μž μ •μ˜ ν•¨μˆ˜ blockKey = get_decrypt_key(dbconf['blockKey']) # μ„€μ • νŒŒμΌμ— μ•”ν˜Έν™”λ˜μ–΄ μžˆλŠ” 값을 가져와 λ³΅ν˜Έν™”ν•œ 후에 μ‚¬μš© dbUser = decrypt(blockKey, dbconf['user']) dbPasswd = decrypt(blockKey, dbconf['passwd']) dbconn = pymysql.connect( host=dbconf['host'] port=dbconf['port'], user=dbUser, passwd=dbPasswd, db=dbconf['db_name'], charset='utf8', ) curs = dbconn.cursor() curs.execute(query) dbconn.commit() dbconn.close()
Python
λ³΄μ•ˆκΈ°λŠ₯
μΆ©λΆ„ν•˜μ§€ μ•Šμ€ ν‚€ 길이 μ‚¬μš©
μ•”ν˜Έν™” 등에 μ‚¬μš©λ˜λŠ” ν‚€μ˜ 길이가 μΆ©λΆ„ν•˜μ§€ μ•Šμ•„ λ°μ΄ν„°μ˜ 기밀성·무결성을 보μž₯ν•  수 μ—†λŠ”λ³΄μ•ˆμ•½μ 
from Crypto.PublicKey import RSA, DSA, ECC from tinyec import registry import secrets def make_rsa_key_pair(): # RSAν‚€ 길이λ₯Ό 2048 λΉ„νŠΈ μ΄ν•˜λ‘œ μ„€μ •ν•˜λŠ” 경우 μ•ˆμ „ν•˜μ§€ μ•ŠμŒ private_key = RSA.generate(1024) public_key = private_key.publickey() def make_ecc(): # ECC의 ν‚€ 길이λ₯Ό 224λΉ„νŠΈ μ΄ν•˜λ‘œ μ„€μ •ν•˜λŠ” 경우 μ•ˆμ „ν•˜μ§€ μ•ŠμŒ ecc_curve = registry.get_curve('secp192r1') private_key = secrets.randbelow(ecc_curve.field.n) public_key = private_key * ecc_curve.g
from Crypto.PublicKey import RSA, DSA, ECC from tinyec import registry import secrets def make_rsa_key_pair(): # RSA ν‚€ 길이λ₯Ό 2048 λΉ„νŠΈ μ΄μƒμœΌλ‘œ 길게 μ„€μ • private_key = RSA.generate(2048) public_key = private_key.publickey() def make_ecc(): # ECC ν‚€ 길이λ₯Ό 224 λΉ„νŠΈ μ΄μƒμœΌλ‘œ μ„€μ • ecc_curve = registry.get_curve('secp224r1') private_key = secrets.randbelow(ecc_curve.field.n) public_key = private_key * ecc_curve.g
Python
λ³΄μ•ˆκΈ°λŠ₯
μ μ ˆν•˜μ§€ μ•Šμ€ λ‚œμˆ˜ κ°’ μ‚¬μš©
μ‚¬μš©ν•œ λ‚œμˆ˜κ°€ 예츑 κ°€λŠ₯ν•˜μ—¬, κ³΅κ²©μžκ°€ λ‹€μŒ λ‚œμˆ˜λ₯Ό μ˜ˆμƒν•΄μ„œ μ‹œμŠ€ν…œμ„ 곡격 κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import random def get_otp_number(): random_str = '' # μ‹œμŠ€ν…œ ν˜„μž¬ μ‹œκ°„ 값을 μ‹œλ“œλ‘œ μ‚¬μš©ν•˜κ³  있으며, μ£Όμš” λ³΄μ•ˆ κΈ°λŠ₯을 μœ„ν•œ # λ‚œμˆ˜λ‘œ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ for i in range(6): random_str += str(random.randrange(10)) return random_str
import secrets def get_otp_number(): random_str = '' # λ³΄μ•ˆκΈ°λŠ₯에 μ ν•©ν•œ λ‚œμˆ˜ μƒμ„±μš© secrets 라이브러리 μ‚¬μš© for i in range(6): random_str += str(secrets.randbelow(10)) return random_str
Python
λ³΄μ•ˆκΈ°λŠ₯
μ μ ˆν•˜μ§€ μ•Šμ€ λ‚œμˆ˜ κ°’ μ‚¬μš©
μ‚¬μš©ν•œ λ‚œμˆ˜κ°€ 예츑 κ°€λŠ₯ν•˜μ—¬, κ³΅κ²©μžκ°€ λ‹€μŒ λ‚œμˆ˜λ₯Ό μ˜ˆμƒν•΄μ„œ μ‹œμŠ€ν…œμ„ 곡격 κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import random import string def generate_session_key(): RANDOM_STRING_CHARS = string.ascii_letters + string.digits # random 라이브러리λ₯Ό λ³΄μ•ˆ κΈ°λŠ₯에 μ‚¬μš©ν•˜λ©΄ μœ„ν—˜ν•˜λ‹€ return β€œβ€.join(random.choice(RANDOM_STRING_CHARS) for i in range(32))
import secrets import string def generate_session_key(): RANDOM_STRING_CHARS = string.ascii_letters+string.digits # λ³΄μ•ˆ κΈ°λŠ₯κ³Ό κ΄€λ ¨λœ λ‚œμˆ˜λŠ” secrets 라이브러리λ₯Ό μ‚¬μš©ν•΄μ•Ό μ•ˆμ „ν•˜λ‹€ return β€œβ€.join(secrets.choice(RANDOM_STRING_CHARS) for i in range(32))
Python
λ³΄μ•ˆκΈ°λŠ₯
μ·¨μ•½ν•œ νŒ¨μŠ€μ›Œλ“œ ν—ˆμš©
νŒ¨μŠ€μ›Œλ“œ μ‘°ν•©κ·œμΉ™(영문, 숫자, 특수문자 λ“±) 미흑 및 길이가 μΆ©λΆ„ν•˜μ§€ μ•Šμ•„ νŒ¨μŠ€μ›Œλ“œκ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from flask import request, redirect from Models import User from Models import db @app.route('/register', methods=['POST']) def register(): userid = request.form.get('userid') password = request.form.get('password') confirm_password = request.form.get('confirm_password') if password != confirm_password: return make_response("νŒ¨μŠ€μ›Œλ“œκ°€ μΌμΉ˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€", 400) else: usertable = User() usertable.userid = userid usertable.password = password # νŒ¨μŠ€μ›Œλ“œ 생성 κ·œμΉ™μ„ ν™•μΈν•˜μ§€ μ•Šκ³  νšŒμ› κ°€μž… db.session.add(usertable) db.session.commit() return make_response("νšŒμ›κ°€μž… 성곡", 200)
from flask import request, redirect from Models import User from Models import db import re @app.route('/register', methods=['POST']) def register(): userid = request.form.get('userid') password = request.form.get('password') confirm_password = request.form.get('confirm_password') if password != confirm_password: return make_response("νŒ¨μŠ€μ›Œλ“œκ°€ μΌμΉ˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.", 400) if not check_password(password): return make_response("νŒ¨μŠ€μ›Œλ“œ μ‘°ν•©κ·œμΉ™μ— λ§žμ§€ μ•ŠμŠ΅λ‹ˆλ‹€.", 400) else: usertable = User() usertable.userid = userid usertable.password = password db.session.add(usertable) db.session.commit() return make_response("νšŒμ›κ°€μž… 성곡", 200) def check_password(password): # 3μ’… 이상 문자둜 κ΅¬μ„±λœ 8자리 이상 νŒ¨μŠ€μ›Œλ“œ 검사 μ •κ·œμ‹ 적용 PT1 = re.compile('^(?=.*[A-Z])(?=.*[a-z])[A-Za-z\d!@#$%^&*]{8,}$') PT2 = re.compile('^(?=.*[A-Z])(?=.*\d)[A-Za-z\d!@#$%^&*]{8,}$') PT3 = re.compile('^(?=.*[A-Z])(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$') PT4 = re.compile('^(?=.*[a-z])(?=.*\d)[A-Za-z\d!@#$%^&*]{8,}$') PT5 = re.compile('^(?=.*[a-z])(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$') PT6 = re.compile('^(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$') # 문자 ꡬ성 상관없이 10자리 이상 νŒ¨μŠ€μ›Œλ“œ 검사 μ •κ·œμ‹ PT7 = re.compile('^[A-Za-z\d!@#$%^&*]{10,}$') for pattern in [PT1, PT2, PT3, PT4, PT5, PT6, PT7]: if pattern.match(password): return True return False
Python
λ³΄μ•ˆκΈ°λŠ₯
μ·¨μ•½ν•œ νŒ¨μŠ€μ›Œλ“œ ν—ˆμš©
νŒ¨μŠ€μ›Œλ“œ μ‘°ν•©κ·œμΉ™(영문, 숫자, 특수문자 λ“±) 미흑 및 길이가 μΆ©λΆ„ν•˜μ§€ μ•Šμ•„ νŒ¨μŠ€μ›Œλ“œκ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.shortcuts import render, redirect from django.http import HttpResponse from .models import User from django.views.decorators.http import require_POST @require_POST def register(request): userid = request.POST.get('userid') password = request.POST.get('password') confirm_password = request.POST.get('confirm_password') if password != confirm_password: return HttpResponse("νŒ¨μŠ€μ›Œλ“œκ°€ μΌμΉ˜ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€", status=400) else: usertable = User() usertable.userid = userid usertable.password = password # νŒ¨μŠ€μ›Œλ“œ 생성 κ·œμΉ™μ„ ν™•μΈν•˜μ§€ μ•Šκ³  νšŒμ› κ°€μž… usertable.save() return HttpResponse("νšŒμ›κ°€μž… 성곡", status=200)
import re from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ class CustomValidator(object): def validate(self, password, user=None): # 3μ’… 이상 문자둜 κ΅¬μ„±λœ 8자리 이상 νŒ¨μŠ€μ›Œλ“œ 검사 μ •κ·œμ‹ PT1 = re.compile('^(?=.*[A-Z])(?=.*[a-z])[A-Za-z\d!@#$%^&*]{8,}$') PT2 = re.compile('^(?=.*[A-Z])(?=.*\d)[A-Za-z\d$@$!%*?&]{8,}$') PT3 = re.compile('^(?=.*[A-Z])(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$') PT4 = re.compile('^(?=.*[a-z])(?=.*\d)[A-Za-z\d!@#$%^&*]{8,}$') PT5 = re.compile('^(?=.*[a-z])(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$') PT6 = re.compile('^(?=.*\d)(?=.*[!@#$%^&*])[A-Za-z\d!@#$%^&*]{8,}$') # 문자 ꡬ성 상관없이 10자리 이상 νŒ¨μŠ€μ›Œλ“œ 검사 μ •κ·œμ‹ PT7 = re.compile('^[A-Za-z\d!@#$%^&*]{10,}$') for pattern in [PT1, PT2, PT3, PT4, PT5, PT6, PT7]: if pattern.match(password): return None raise ValidationError( _("νŒ¨μŠ€μ›Œλ“œ μ‘°ν•©κ·œμΉ™μ— μ ν•©ν•˜μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.."), code='improper_password', ) def get_help_text(self): return _( "νŒ¨μŠ€μ›Œλ“œλŠ” 영문 λŒ€λ¬Έμž, μ†Œλ¬Έμž, 숫자, 특수문자 μ‘°ν•© 쀑 2가지 이상 8μžλ¦¬μ΄κ±°λ‚˜ 문자 ꡬ성 상관없이 10자리 이상이어야 ν•©λ‹ˆλ‹€." )
Python
λ³΄μ•ˆκΈ°λŠ₯
λΆ€μ μ ˆν•œ μ „μžμ„œλͺ… 확인
ν”„λ‘œκ·Έλž¨, 라이브러리, μ½”λ“œμ˜ μ „μžμ„œλͺ…에 λŒ€ν•œ μœ νš¨μ„± 검증이 μ μ ˆν•˜μ§€ μ•Šμ•„ 곡격자의 μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
import base64 from Crypto.PublicKey import RSA from Crypto.Hash import SHA256 from Crypto.Signature import PKCS1_v1_5 as SIGNATURE_PKCS1_v1_5 from Crypto.Cipher import PKCS1_v1_5, AES from Crypto.Util.Padding import unpad ... def verify_data(request): # ν΄λΌμ΄μ–ΈνŠΈλ‘œλΆ€ν„° 전달받은 데이터(μ „μžμ„œλͺ…을 μˆ˜μ‹  처리 ν•˜μ§€ μ•ŠμŒ) encrypted_code = request.POST.get("encrypted_msg", "") # μ•”ν˜Έν™”λœ 파이썬 μ½”λ“œ # μ„œλ²„μ˜ λŒ€μΉ­ν‚€ λ‘œλ“œ (μ†‘μˆ˜μ‹ μΈ‘μ΄ λŒ€μΉ­ν‚€λ₯Ό 이미 κ³΅μœ ν–ˆλ‹€κ³  κ°€μ •) with open(f"{PATH}/keys/secret_key.out", "rb") as f: secret_key = f.read() # λŒ€μΉ­ν‚€λ‘œ ν΄λΌμ΄μ–ΈνŠΈκ°€ μ „λ‹¬ν•œ 파이썬 μ½”λ“œ λ³΅ν˜Έν™” # (decrypt_with_symmetric_key ν•¨μˆ˜λŠ” μž„μ˜μ˜ ν•¨μˆ˜λͺ…μœΌλ‘œ 세뢀적인 λ³΅ν˜Έν™” 과정은 μƒλž΅ν•¨) origin_python_code = decrypt_with_symmetric_key(secret_key, encrypted_code) # ν΄λΌμ΄μ–ΈνŠΈλ‘œλΆ€ν„° 전달 받은 파이썬 μ½”λ“œ μ‹€ν–‰ eval(origin_python_code) return render( request, "/verify_success.html", {"result": "파이썬 μ½”λ“œλ₯Ό μ‹€ν–‰ν–ˆμŠ΅λ‹ˆλ‹€."}, )
# μ „μžμ„œλͺ… 검증에 μ‚¬μš©ν•œ μ½”λ“œλŠ” μ˜μ‘΄ν•œ 파이썬 νŒ¨ν‚€μ§€ 및 솑신츑 언어에 따라 # λ‹¬λΌμ§ˆ 수 있으며, 사전에 κ³΅μœ ν•œ κ³΅κ°œν‚€λ‘œ λ³΅ν˜Έν™”ν•œ μ „μžμ„œλͺ…κ³Ό 원본 데이터 ν•΄μ‹œκ°’μ˜ # 일치 μ—¬λΆ€λ₯Ό κ²€μ‚¬ν•˜λŠ” μ½”λ“œλ₯Ό 포함 def verify_digit_signature ( origin_data: bytes, origin_signature: bytes, client_pub_key: str ) -> bool: hashed_data = SHA256.new(origin_data) signer = SIGNATURE_PKCS1_v1_5.new(RSA.importKey(client_pub_key)) return signer.verify(hashed_data, base64.b64decode(origin_signature)) def verify_data(request): # ν΄λΌμ΄μ–ΈνŠΈλ‘œλΆ€ν„° 전달받은 데이터 encrypted_code = request.POST.get("encrypted_msg", "") # μ•”ν˜Έν™”λœ 파이썬 μ½”λ“œ encrypted_sig = request.POST.get("encrypted_sig", "") # μ•”ν˜Έν™”λœ μ „μžμ„œλͺ… # μ„œλ²„μ˜ λŒ€μΉ­(λΉ„λ°€)ν‚€ 및 κ³΅κ°œν‚€ λ‘œλ“œ with open(f"/keys/secret_key.out", "rb") as f: secret_key = f.read() with open(f"/keys/public_key.out", "rb") as f: public_key = f.read() # λŒ€μΉ­ν‚€λ‘œ 파이썬 μ½”λ“œ 및 μ „μžμ„œλͺ… λ³΅ν˜Έν™” origin_python_code = decrypt_with_symmetric_key(symmetric_key, encrypted_code) origin_signature = decrypt_with_symmetric_key(symmetric_key, encrypted_sig) # ν΄λΌμ΄μ–ΈνŠΈμ˜ κ³΅κ°œν‚€λ₯Ό 톡해 파이썬 μ½”λ“œ(원문)와 μ „μžμ„œλͺ…을 검증 verify_result = verify_digit_signature(origin_python_code, origin_signature, client_pub_key) # μ „μžμ„œλͺ… 검증을 ν†΅κ³Όν–ˆλ‹€λ©΄ 파이썬 μ½”λ“œ μ‹€ν–‰ if verify_result: eval(origin_python_code) return render(request, "/verify_success.html", {"result": "μ „μžμ„œλͺ… 검증 톡과 및 파이썬 μ½”λ“œλ₯Ό μ‹€ν–‰ν–ˆμŠ΅λ‹ˆλ‹€."}, ) else: return render(request, "/verify_failed.html", {"result": "μ „μžμ„œλͺ… λ˜λŠ” 파이썬 μ½”λ“œκ°€ μœ„/λ³€μ‘°λ˜μ—ˆμŠ΅λ‹ˆλ‹€."}, )
Python
λ³΄μ•ˆκΈ°λŠ₯
λΆ€μ μ ˆν•œ μΈμ¦μ„œ μœ νš¨μ„± 검증
μΈμ¦μ„œμ— λŒ€ν•œ μœ νš¨μ„± 검증이 μ μ ˆν•˜μ§€ μ•Šμ•„ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ 
import os import socket import ssl HOST, PORT = "127.0.0.1", 7917 def connect_with_server(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: # λ³΄μ•ˆ μ •μ±… μˆ˜λ™ μ„€μ • context = ssl.SSLContext() # SSLContext μƒμ„±μžλ₯Ό 직접 ν˜ΈμΆœν•  λ•Œ, CERT_NONE이 κΈ°λ³Έκ°’ # μƒλŒ€λ°©μ„ μΈμ¦ν•˜μ§€ μ•ŠκΈ° λ•Œλ¬Έμ— ν†΅μ‹ ν•˜κ³ μžν•˜λŠ” μ„œλ²„μ˜ 신뒰성을 보μž₯ν•  수 μ—†μŒ context.verify_mode = ssl.CERT_NONE with context.wrap_socket(sock) as ssock: try: ssock.connect((HOST, PORT)) ssock.send("Hello I'm a vulnerable client :)".encode("utf-8")) data = ssock.recv(1024).decode("utf-8") print(f">> server from ({HOST}, {PORT}): {data}\n") finally: ssock.close()
import os import socket import ssl CURRENT_PATH = os.getcwd() HOST_NAME = "test-server" HOST, PORT = "127.0.0.1", 7917 SERVER_CA_PEM = f"{CURRENT_PATH}/rsa_server/CA.pem" # μ„œλ²„λ‘œλΆ€ν„° 전달받은 CA μΈμ¦μ„œ def connect_with_server(): with socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) as sock: # PROTOCOL_TLS_CLIENT ν”„λ‘œν† μ½œμ„ μΆ”κ°€ν•˜μ—¬ μΈμ¦μ„œ μœ νš¨μ„± 검사와 호슀트 이름 확인을 μœ„ν•œ # contextλ₯Ό ꡬ성. verify_modeκ°€ CERT_REQUIRED둜 섀정됨 # check_hostname이 True둜 섀정됨 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # μ„œλ²„λ‘œλΆ€ν„° 전달받은 CA μΈμ¦μ„œλ₯Ό context에 λ‘œλ“œ # CERT_REQUIRED둜 인해 ν•„μˆ˜ context.load_verify_locations(SERVER_CA_PEM) # 호슀트 이름(HOST_NAME)이 μΌμΉ˜ν•˜μ§€ μ•ŠμœΌλ©΄ 톡신 λΆˆκ°€ # μƒμ„±λœ μ†ŒμΌ“κ³Ό context wrapping μ‹œ server_hostname이 μ‹€μ œ μ„œλ²„μ—μ„œ # 등둝(server.csr)ν•œ 호슀트 λͺ…κ³Ό μΌμΉ˜ν•΄μ•Ό 함 with context.wrap_socket(sock, server_hostname=HOST_NAME) as ssock: try: ssock.connect((HOST, PORT)) ssock.send("Hello I'm a patched client :)".encode("utf-8")) data = ssock.recv(1024).decode("utf-8") print(f">> server from ({HOST}, {PORT}): {data}\n") finally: ssock.close()
Python
λ³΄μ•ˆκΈ°λŠ₯
μ‚¬μš©μž ν•˜λ“œλ””μŠ€ν¬μ— μ €μž₯λ˜λŠ” μΏ ν‚€λ₯Ό ν†΅ν•œ 정보 λ…ΈμΆœ
μΏ ν‚€(μ„Έμ…˜ ID, μ‚¬μš©μž κΆŒν•œμ •λ³΄ λ“± μ€‘μš”μ •λ³΄)λ₯Ό μ‚¬μš©μž ν•˜λ“œλ””μŠ€ν¬μ— μ €μž₯ν•˜μ—¬ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.http import HttpResponse def remind_user_state(request): res = HttpResponse() # μΏ ν‚€μ˜ λ§Œλ£Œμ‹œκ°„μ„ 1λ…„μœΌλ‘œ κ³Όλ„ν•˜κ²Œ 길게 μ„€μ •ν•˜κ³  μžˆμ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ res.set_cookie('rememberme', 1, max_age=60*60*24*365) return res
from django.http import HttpResponse def remind_user_state(request): res = HttpResponse() # μΏ ν‚€μ˜ λ§Œλ£Œμ‹œκ°„μ„ μ μ ˆν•˜κ²Œ λΆ€μ—¬ν•˜κ³  secure 및 httpOnly μ˜΅μ…˜μ„ ν™œμ„±ν™” ν•œλ‹€. res.set_cookie('rememberme', 1, max_age=60*60, secure=True, httponly=True) return res
Python
λ³΄μ•ˆκΈ°λŠ₯
μ‚¬μš©μž ν•˜λ“œλ””μŠ€ν¬μ— μ €μž₯λ˜λŠ” μΏ ν‚€λ₯Ό ν†΅ν•œ 정보 λ…ΈμΆœ
μΏ ν‚€(μ„Έμ…˜ ID, μ‚¬μš©μž κΆŒν•œμ •λ³΄ λ“± μ€‘μš”μ •λ³΄)λ₯Ό μ‚¬μš©μž ν•˜λ“œλ””μŠ€ν¬μ— μ €μž₯ν•˜μ—¬ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
from django.http import HttpResponse def remind_user_state(request): res = HttpResponse() # μΏ ν‚€μ˜ λ§Œλ£Œμ‹œκ°„μ„ 1λ…„μœΌλ‘œ κ³Όλ„ν•˜κ²Œ 길게 μ„€μ •ν•˜κ³  μžˆμ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€ res.set_cookie('rememberme', 1, max_age=60*60*24*366) return res
from django.http import HttpResponse from django.conf.global_settings import ( SESSION_COOKIE_AGE, SESSION_COOKIE_HTTPONLY, SESSION_COOKIE_HTTPONLY, ) """ # settings.py SESSION_COOKIE_AGE = 60 * 60 * 24 * 14 SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_SECURE = True """ def remind_user_state(request): res = HttpResponse() # μ„œλ²„ μ„ΈνŒ…(setting.py)μ—μ„œ default둜 μΏ ν‚€ μ˜΅μ…˜μ„ μ„€μ •ν•œ μƒνƒœ res.set_cookie( "rememerme", 1, max_age=SESSION_COOKIE_AGE, secure=SESSION_COOKIE_HTTPONLY, httponly=SESSION_COOKIE_HTTPONLY, ) return res

No dataset card yet

Downloads last month
36