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
JAVA
λ³΄μ•ˆκΈ°λŠ₯
λΆ€μ μ ˆν•œ μ „μžμ„œλͺ… 확인
ν”„λ‘œκ·Έλž¨, 라이브러리, μ½”λ“œμ˜ μ „μžμ„œλͺ…에 λŒ€ν•œ μœ νš¨μ„± 검증이 μ μ ˆν•˜μ§€ μ•Šμ•„ 곡격자의 μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
File f = new File(downloadedFilePath); JarFile jf = new JarFile(f);
File f = new File(downloadedFilePath); JarFile jf = new JarFile(f, true); Enumeration<JarEntry> ens = jf.entries(); while (ens.hasMoreElements()) { JarEntry en = ens.nextElement(); if (!en.isDirectory()) { if (en.toString().equals(path)) { byte[] data = readAll(jar.getInputStream(en), en.getSize()); CodeSigner[] signers = en.getCodeSigners(); ... } } } jf.close();
C
λ³΄μ•ˆκΈ°λŠ₯
λΆ€μ μ ˆν•œ μΈμ¦μ„œ μœ νš¨μ„± 검증
μΈμ¦μ„œμ— λŒ€ν•œ μœ νš¨μ„± 검증이 μ μ ˆν•˜μ§€ μ•Šμ•„ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ 
if ((cert = SSL_get_peer_certificate(ssl)) && host) foo=SSL_get_verify_result(ssl); if ((X509_V_OK==foo) || X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN==foo)) // 자체 μ„œλͺ…λœ μΈμ¦μ„œμΌ 수 μžˆλ‹€.
private boolean verifySignature(X509Certificate toVerify, X509Certificate signingCert) { /* κ²€μ¦ν•˜λ €λŠ” 호슀트 μΈμ¦μ„œ(toVerify)와 CAμΈμ¦μ„œ(signing Cert)의 DN(Distinguished Name)이 μΌμΉ˜ν•˜λŠ”μ§€ μ—¬λΆ€λ₯Ό ν™•μΈν•œλ‹€.*/ if (!toVerify.getIssuerDN().equals(signingCert.getSubjectDN())) return false; try { // 호슀트 μΈμ¦μ„œκ°€ CAμΈμ¦μ„œλ‘œ μ„œλͺ… λ˜μ—ˆλŠ”μ§€ ν™•μΈν•œλ‹€. toVerify.verify(signingCert.getPublicKey()); // 호슀트 μΈμ¦μ„œκ°€ μœ νš¨κΈ°κ°„μ΄ λ§Œλ£Œλ˜μ—ˆλŠ”μ§€ ν™•μΈν•œλ‹€. toVerify.checkValidity(); return true; } catch (GeneralSecurityException verifyFailed) { return false; } }
C, JAVA
λ³΄μ•ˆκΈ°λŠ₯
λΆ€μ μ ˆν•œ μΈμ¦μ„œ μœ νš¨μ„± 검증
μΈμ¦μ„œμ— λŒ€ν•œ μœ νš¨μ„± 검증이 μ μ ˆν•˜μ§€ μ•Šμ•„ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ 
cert = SSL_get_peer_certificate(ssl); if (cert && (SSL_get_verify_result(ssl)==X509_V_OK)) { /* CN 을 ν™•μΈν•˜μ§€ μ•Šμ•˜μ§€λ§Œ μ‹ λ’°ν•˜κ³  μ§„ν–‰ν•œλ‹€. 이럴 경우, κ³΅κ²©μžκ°€ Common Name을 www.attack.com으둜 μ„€μ •ν•˜μ—¬ μ€‘κ°„μž 곡격에 μ‚¬μš©ν•  경우 데이터가 μ€‘κ°„μ—μ„œ λ³΅ν˜Έν™” 되고 μžˆμŒμ„ νƒμ§€ν•˜μ§€ λͺ»ν•œλ‹€. */ }
private boolean verifySignature(X509Certificate toVerify, X510Certificate signingCert) { /* κ²€μ¦ν•˜λ €λŠ” 호슀트 μΈμ¦μ„œ(toVerify)와 CAμΈμ¦μ„œ(signing Cert)의 DN(Distinguished Name)이 μΌμΉ˜ν•˜λŠ”μ§€ μ—¬λΆ€λ₯Ό ν™•μΈν•œλ‹€.*/ if (!toVerify.getIssuerDN().equals(signingCert.getSubjectDN())) return false; try { // 호슀트 μΈμ¦μ„œκ°€ CAμΈμ¦μ„œλ‘œ μ„œλͺ… λ˜μ—ˆλŠ”μ§€ ν™•μΈν•œλ‹€. toVerify.verify(signingCert.getPublicKey()); // 호슀트 μΈμ¦μ„œκ°€ μœ νš¨κΈ°κ°„μ΄ λ§Œλ£Œλ˜μ—ˆλŠ”μ§€ ν™•μΈν•œλ‹€. toVerify.checkValidity(); return true; } catch (GeneralSecurityException verifyFailed) { return false; } }
JAVA
λ³΄μ•ˆκΈ°λŠ₯
μ‚¬μš©μž ν•˜λ“œλ””μŠ€ν¬μ— μ €μž₯λ˜λŠ” μΏ ν‚€λ₯Ό ν†΅ν•œ μ •λ³΄λ…ΈμΆœ
μΏ ν‚€(μ„Έμ…˜ ID, μ‚¬μš©μž κΆŒν•œμ •λ³΄ λ“± μ€‘μš”μ •λ³΄)λ₯Ό μ‚¬μš©μž ν•˜λ“œλ””μŠ€ν¬μ— μ €μž₯λ˜μ–΄ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
Cookie loginCookie = new Cookie("rememberme", "YES"); // μΏ ν‚€μ˜ λ§Œλ£Œμ‹œκ°„μ„ 1λ…„μœΌλ‘œ κ³Όλ„ν•˜κ²Œ 길게 μ„€μ •ν•˜κ³  μžˆμ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. loginCookie.setMaxAge(60*60*24*365); response.addCookie(loginCookie);
Cookie loginCookie = new Cookie("rememberme", "YES"); // μΏ ν‚€μ˜ λ§Œλ£Œμ‹œκ°„μ€ ν•΄λ‹Ή κΈ°λŠ₯에 맞좰 μ΅œμ†Œλ‘œ μ‚¬μš©ν•œλ‹€. loginCookie.setMaxAge(60*60*24); response.addCookie(loginCookie);
C#
λ³΄μ•ˆκΈ°λŠ₯
μ‚¬μš©μž ν•˜λ“œλ””μŠ€ν¬μ— μ €μž₯λ˜λŠ” μΏ ν‚€λ₯Ό ν†΅ν•œ μ •λ³΄λ…ΈμΆœ
μΏ ν‚€(μ„Έμ…˜ ID, μ‚¬μš©μž κΆŒν•œμ •λ³΄ λ“± μ€‘μš”μ •λ³΄)λ₯Ό μ‚¬μš©μž ν•˜λ“œλ””μŠ€ν¬μ— μ €μž₯λ˜μ–΄ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
HttpCookie cookie = Request.Cookies.Get(β€œExampleCookie”); // μΏ ν‚€μ˜ λ§Œλ£Œμ‹œκ°„μ„ 1λ…„μœΌλ‘œ κ³Όλ„ν•˜κ²Œ 길게 μ„€μ •ν•˜κ³  μžˆμ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. cookie.Expires = DateTime.Now.AddMinutes(60.0*24.0*365.0); Response.Cookies.Add(cookie);
HttpCookie cookie = Request.Cookies.Get(β€œExampleCookie”); // μΏ ν‚€μ˜ λ§Œλ£Œμ‹œκ°„μ€ ν•΄λ‹Ή κΈ°λŠ₯에 맞좰 μ΅œμ†Œλ‘œ μ‚¬μš©ν•œλ‹€. cookie.Expires = DateTime.Now.AddMinutes(10d); Response.Cookies.Add(cookie);
JAVA
λ³΄μ•ˆκΈ°λŠ₯
주석문 μ•ˆμ— ν¬ν•¨λœ μ‹œμŠ€ν…œ μ£Όμš”μ •λ³΄
μ†ŒμŠ€μ½”λ“œ 주석문에 인증정보 λ“± μ‹œμŠ€ν…œ μ£Όμš”μ •λ³΄κ°€ ν¬ν•¨λ˜μ–΄ μ†ŒμŠ€μ½”λ“œ λ…ΈμΆœ μ‹œμ£Όμš”μ •λ³΄λ„ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
// μ£Όμ„λ¬ΈμœΌλ‘œ DBμ—°κ²° ID, νŒ¨μŠ€μ›Œλ“œμ˜ μ€‘μš”ν•œ 정보λ₯Ό λ…ΈμΆœμ‹œμΌœ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. // DBμ—°κ²° root / a1q2w3r3f2!@ con = DriverManager.getConnection(URL, USER, PASS);
// ID, νŒ¨μŠ€μ›Œλ“œλ“±μ˜ μ€‘μš” μ •λ³΄λŠ” 주석에 ν¬ν•¨ν•΄μ„œλŠ” μ•ˆλœλ‹€. con = DriverManager.getConnection(URL, USER, PASS);
C#
λ³΄μ•ˆκΈ°λŠ₯
주석문 μ•ˆμ— ν¬ν•¨λœ μ‹œμŠ€ν…œ μ£Όμš”μ •λ³΄
μ†ŒμŠ€μ½”λ“œ 주석문에 인증정보 λ“± μ‹œμŠ€ν…œ μ£Όμš”μ •λ³΄κ°€ ν¬ν•¨λ˜μ–΄ μ†ŒμŠ€μ½”λ“œ λ…ΈμΆœ μ‹œμ£Όμš”μ •λ³΄λ„ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
// μ£Όμ„λ¬ΈμœΌλ‘œ DBμ—°κ²° ID, νŒ¨μŠ€μ›Œλ“œμ˜ μ€‘μš”ν•œ 정보λ₯Ό λ…ΈμΆœμ‹œμΌœ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. // DBμ—°κ²° root / a1q2w3r3f2!@ conn = customGetConnection(USER, PASS);
// ID, νŒ¨μŠ€μ›Œλ“œλ“±μ˜ μ€‘μš” μ •λ³΄λŠ” 주석에 ν¬ν•¨ν•΄μ„œλŠ” μ•ˆλœλ‹€. conn = customGetConnection(USER, PASS);
C
λ³΄μ•ˆκΈ°λŠ₯
주석문 μ•ˆμ— ν¬ν•¨λœ μ‹œμŠ€ν…œ μ£Όμš”μ •λ³΄
μ†ŒμŠ€μ½”λ“œ 주석문에 인증정보 λ“± μ‹œμŠ€ν…œ μ£Όμš”μ •λ³΄κ°€ ν¬ν•¨λ˜μ–΄ μ†ŒμŠ€μ½”λ“œ λ…ΈμΆœ μ‹œμ£Όμš”μ •λ³΄λ„ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
/* password is "admin" */ /* passwd is "admin" */ int verfiyAuth(char *ipasswd, char *orgpasswd) { char *admin = "admin"; if(strncmp(ipasswd, oprgpasswd, sizeof(ipasswd)) != 0) { printf("Authentication Fail! \n"); } return admin;
int verfiyAuth(char *ipasswd, char *orgpasswd) { char *admin = "admin"; if(strncmp(ipasswd, oprgpasswd, sizeof(ipasswd)) != 0) { printf("Authentication Fail! \n"); } return admin; }
JAVA
λ³΄μ•ˆκΈ°λŠ₯
μ†”νŠΈ 없이 일방ν–₯ ν•΄μ‰¬ν•¨μˆ˜ μ‚¬μš©
μ†”νŠΈλ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³  μƒμ„±λœ 해쉬 κ°’μœΌλ‘œλΆ€ν„° κ³΅κ²©μžκ°€ 미리 κ³„μ‚°λœ 레인보우 ν…Œμ΄λΈ”μ„ μ΄μš©ν•˜μ—¬ 해쉬 적용 이전 원본 정보λ₯Ό 볡원가λŠ₯ν•œ λ³΄μ•ˆμ•½μ  * μ†”νŠΈ: 해쉬 μ μš©ν•˜κΈ° μ „ 평문인 전솑정보에 덧뢙인 λ¬΄μ˜λ―Έν•œ 데이터
public String getPasswordHash(String password) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA-256"); // 해쉬에 μ†”νŠΈλ₯Ό μ μš©ν•˜μ§€ μ•Šμ•„ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. md.update(password.getBytes()); byte byteData[] = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i=0; i<byteData.length i++) { String hex=Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); }
public String getPasswordHash(String password, byte[] salt) throws Exception { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(password.getBytes()); // 해쉬 μ‚¬μš© μ‹œμ—λŠ” 원문을 찾을 수 없도둝 μ†”νŠΈλ₯Ό μ‚¬μš©ν•˜μ—¬μ•Ό ν•œλ‹€. md.update(salt); byte byteData[] = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i=0; i<byteData.length i++) { String hex=Integer.toHexString(0xff & byteData[i]); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString() }
C#
λ³΄μ•ˆκΈ°λŠ₯
μ†”νŠΈ 없이 일방ν–₯ ν•΄μ‰¬ν•¨μˆ˜ μ‚¬μš©
μ†”νŠΈλ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³  μƒμ„±λœ 해쉬 κ°’μœΌλ‘œλΆ€ν„° κ³΅κ²©μžκ°€ 미리 κ³„μ‚°λœ 레인보우 ν…Œμ΄λΈ”μ„ μ΄μš©ν•˜μ—¬ 해쉬 적용 이전 원본 정보λ₯Ό 볡원가λŠ₯ν•œ λ³΄μ•ˆμ•½μ  * μ†”νŠΈ: 해쉬 μ μš©ν•˜κΈ° μ „ 평문인 전솑정보에 덧뢙인 λ¬΄μ˜λ―Έν•œ 데이터
static void HashWithoutSalt() { // 해쉬에 μ†”νŠΈλ₯Ό μ μš©ν•˜μ§€ μ•Šμ•„ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. var bytes = new byte[100]; (new Random()).NextBytes(bytes); var source = bytes; var sha256 = new SHA256CryptoServiceProvider(); sha256.ComputeHash(source); }
static void HashWithSalt(int saltLength) { // 해쉬에 μ†”νŠΈλ₯Ό μ μš©ν•˜μ—¬ 원문을 찾을 수 μ—†κ²Œ ν•œλ‹€. var bytes = new byte[100]; (new Random()).NextBytes(bytes); var source = bytes; var sha256 = new SHA256CryptoServiceProvider(); byte[] saltBytes = GenerateRandomCryptographicBytes(saltLength); List<byte> sourceWithSaltBytes = new List<byte>(); sourceWithSaltBytes.AddRange(source); sourceWithSaltBytes.AddRange(sourceWithSaltBytes); sha256.ComputeHash(sourceWithSaltBytes.ToArray()); }
C
λ³΄μ•ˆκΈ°λŠ₯
μ†”νŠΈ 없이 일방ν–₯ ν•΄μ‰¬ν•¨μˆ˜ μ‚¬μš©
μ†”νŠΈλ₯Ό μ‚¬μš©ν•˜μ§€ μ•Šκ³  μƒμ„±λœ 해쉬 κ°’μœΌλ‘œλΆ€ν„° κ³΅κ²©μžκ°€ 미리 κ³„μ‚°λœ 레인보우 ν…Œμ΄λΈ”μ„ μ΄μš©ν•˜μ—¬ 해쉬 적용 이전 원본 정보λ₯Ό 볡원가λŠ₯ν•œ λ³΄μ•ˆμ•½μ  * μ†”νŠΈ: 해쉬 μ μš©ν•˜κΈ° μ „ 평문인 전솑정보에 덧뢙인 λ¬΄μ˜λ―Έν•œ 데이터
void GenerateHash(char* data) { char[512] hashedData = {0 }; //μ†”νŠΈ κ°’ 뢀뢄이 NULL 둜 λ˜μ–΄μžˆμ–΄ λ“€μ–΄κ°€μ§€ μ•ŠλŠ”λ‹€. MD5HashAlgorithm( data, hashedData, NULL ); ... }
void GenerateHash(char* data, char* salt) { char hashedData[512] = {0 }; MD5HashAlgorithm( data, hashedData, salt ); ... }
JAVA
λ³΄μ•ˆκΈ°λŠ₯
무결성 검사 μ—†λŠ” μ½”λ“œ λ‹€μš΄λ‘œλ“œ
μ†ŒμŠ€μ½”λ“œ λ˜λŠ” μ‹€ν–‰νŒŒμΌμ„ 무결성 검사 없이 λ‹€μš΄λ‘œλ“œ λ°›μ•„ μ‹€ν–‰ν•˜λŠ” 경우, 곡격자의 μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
URL[] classURLs = new URL[] { new URL("file:subdir/") }; URLClassLoader loader = new URLClassLoader(classURLs); Class loadedClass = Class.forName("LoadMe", true, loader);
// κ³΅κ°œν‚€ λ°©μ‹μ˜ μ•”ν˜Έν™” μ•Œκ³ λ¦¬μ¦˜κ³Ό λ©”μ»€λ‹ˆμ¦˜μ„ μ΄μš©ν•˜μ—¬ μ „μ†‘νŒŒμΌμ— λŒ€ν•œ μ‹œκ·Έλ‹ˆμ²˜λ₯Ό μƒμ„±ν•˜κ³  파일의 λ³€μ‘°μœ λ¬΄λ₯Ό νŒλ‹¨ν•œλ‹€. μ„œλ²„μ—μ„œλŠ” Private Keyλ₯Ό κ°€μ§€κ³  MyClassλ₯Ό μ•”ν˜Έν™”ν•œλ‹€. String jarFile = "./download/util.jar"; byte[] loadFile = FileManager.getBytes(jarFile); loadFile = encrypt(loadFile, privateKey); // jarFileName으둜 μ•”ν˜Έν™”λœ νŒŒμΌμ„ μƒμ„±ν•œλ‹€. FileManager.createFile(loadFile, jarFileName); // ν΄λΌμ΄μ–ΈνŠΈμ—μ„œλŠ” νŒŒμΌμ„ λ‹€μš΄λ‘œλ“œ 받을 경우 Public Key둜 λ³΅ν˜Έν™”ν•œλ‹€. URL[] classURLs = new URL[] { new URL("http://filesave.com/download/util.jar") }; URLConnection conn = classURLs.openConnection(); InputStream is = conn.getInputStream(); // μž…λ ₯ μŠ€νŠΈλ¦Όμ„ jarFileλͺ…μœΌλ‘œ νŒŒμΌμ„ 좜λ ₯ν•œλ‹€. FileOutputStream fos = new FileOutputStream(new File(jarFile)); While (is.read(buf) != -1) { ...... } byte[] loadFile = FileManager.getBytes(jarFile); loadFile = decrypt(loadFile, publicKey); // λ³΅ν˜Έν™”λœ νŒŒμΌμ„ μƒμ„±ν•œλ‹€. FileManager.createFile(loadFile, jarFile); URLClassLoader loader = new URLClassLoader(classURLs); Class loadedClass = Class.forName("MyClass", true, loader);
C#
λ³΄μ•ˆκΈ°λŠ₯
무결성 검사 μ—†λŠ” μ½”λ“œ λ‹€μš΄λ‘œλ“œ
μ†ŒμŠ€μ½”λ“œ λ˜λŠ” μ‹€ν–‰νŒŒμΌμ„ 무결성 검사 없이 λ‹€μš΄λ‘œλ“œ λ°›μ•„ μ‹€ν–‰ν•˜λŠ” 경우, 곡격자의 μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
public override bool DownloadFile() { var url = "https://www.somewhere.untrusted.com"; var desDir = "D:/DestinationPath"; string fileName = Path.GetFileName(url); string descFilePath = Path.Combine(desDir, fileName); try { WebRequest myre = WebRequest.Create(url); } catch (Exception ex) { throw new Exception(ex.Message); } try { byte[] fileData; // 파일 무결성 검사 없이 λ‹€μš΄λ‘œλ“œ using (WebClient client = new WebClient()) { fileData = client.DownloadData(url); } using (FileStream fs = new FileStream(descFilePath, FileMode.OpenOrCreate)) { fs.Write(fileData, 0, fileData.Length); } return true; } catch (Exception ex) { throw new Exception(ex.Message); } }
public override bool DownloadFile() { var url = "https://www.somewhere.untrusted.com"; var desDir = "D:/DestinationPath"; string fileName = Path.GetFileName(url); string descFilePath = Path.Combine(desDir, fileName); try { WebRequest myre = WebRequest.Create(url); } catch (Exception ex) { throw new Exception(ex.Message); } try { byte[] fileData; using (WebClient client = new WebClient()) { fileData = client.DownloadData(url); } // 해쉬 κ°’ 등을 μ‚¬μš©ν•˜μ—¬ λ‹€μš΄λ‘œλ“œ 받은 파일 무결성 검사 CheckIntegrity(fileData); using (FileStream fs = new FileStream(descFilePath, FileMode.OpenOrCreate)) { fs.Write(fileData, 0, fileData.Length); } return true; } catch (Exception ex) { throw new Exception(ex.Message); } }
C
λ³΄μ•ˆκΈ°λŠ₯
무결성 검사 μ—†λŠ” μ½”λ“œ λ‹€μš΄λ‘œλ“œ
μ†ŒμŠ€μ½”λ“œ λ˜λŠ” μ‹€ν–‰νŒŒμΌμ„ 무결성 검사 없이 λ‹€μš΄λ‘œλ“œ λ°›μ•„ μ‹€ν–‰ν•˜λŠ” 경우, 곡격자의 μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‹€ν–‰ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
void foo() { /* ... */ hFile = CreateFile((LPCWSTR)data,GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); InternetQueryDataAvailable(m_hURL, &dwSize,0,0); InternetReadFile(m_hURL, lpBuffer, dwSize, &dwRead); WriteFile(hFile, lpBuffer, dwRead, &dwWritten, NULL); /* ... */
void foo() { /* ... */ hFile = CreateFile((LPCWSTR)data,GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); InternetQueryDataAvailable(m_hURL, &dwSize,0,0); bool result = InternetReadFile(m_hURL, lpBuffer, dwSize, &dwRead); if, lp( result == true) { WriteFile(hFileBuffer, dwRead, &dwWritten, NULL); } /* ... */ }
JAVA
λ³΄μ•ˆκΈ°λŠ₯
반볡된 μΈμ¦μ‹œλ„ μ œν•œ κΈ°λŠ₯ λΆ€μž¬
인증 μ‹œλ„ 수λ₯Ό μ œν•œν•˜μ§€ μ•Šμ•„ κ³΅κ²©μžκ°€ 반볡적으둜 μž„μ˜ 값을 μž…λ ₯ν•˜μ—¬ 계정 κΆŒν•œμ„ νšλ“ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
private static final String SERVER_IP = "127.0.0.1"; private static final int SERVER_PORT = 8080; private static final int FAIL = -1; public void login() { String username = null; String password = null; Socket socket = null; int result = FAIL; try { socket = new Socket(SERVER_IP, SERVER_PORT); //인증 μ‹€νŒ¨μ— λŒ€ν•΄ μ œν•œμ„ 두지 μ•Šμ•„ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. while (result == FAIL) { ... result = verifyUser(username, password); }
private static final String SERVER_IP = "127.0.0.1"; private static final int SERVER_PORT = 8080; private static final int FAIL = -1; private static final int MAX_ATTEMPTS = 5; public void login() { String username = null; String password = null; Socket socket = null; int result = FAIL; int count = 0; try { socket = new Socket(SERVER_IP, SERVER_PORT); // 인증 μ‹€νŒ¨ 및 μ‹œλ„ νšŸμˆ˜μ— μ œν•œμ„ 두어 μ•ˆμ „ν•˜λ‹€. while (result == FAIL && count < MAX_ATTEMPTS) { ... result = verifyUser(username, password); count++; }
C
λ³΄μ•ˆκΈ°λŠ₯
반볡된 μΈμ¦μ‹œλ„ μ œν•œ κΈ°λŠ₯ λΆ€μž¬
인증 μ‹œλ„ 수λ₯Ό μ œν•œν•˜μ§€ μ•Šμ•„ κ³΅κ²©μžκ°€ 반볡적으둜 μž„μ˜ 값을 μž…λ ₯ν•˜μ—¬ 계정 κΆŒν•œμ„ νšλ“ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
int validateUser(char *host, int port) { int socket = openSocketConnection(host, port); if (socket < 0) { printf("Unable to open socket connection"); return(FAIL); } int isValidUser = 0; char nm[NAME_SIZE]; char pw[PSWD_SIZE]; // μΈμ¦μ‹œλ„ 횟수λ₯Ό μ œν•œν•˜κ³  μžˆμ§€ μ•Šλ‹€. while (isValidUser==0) { if (getNextMsg(socket, nm, NAME_SIZE) > 0) { if (getNextMsg(socket, pw, PSWD_SIZE) > 0) { isValidUser = AuthenticateUser(nm, pw); } } } return(SUCCESS); }
#define MAX_ATTEMPTS 5 int validateUser(char *host, int port) { ...... // 연속적인 μ‚¬μš©μž 인증 μ‹œλ„μ— λŒ€ν•œ 횟수λ₯Ό μ œν•œ int count = 0; while ((isValidUser==0) && (count<MAX_ATTEMPTS)) { if (getNextMsg(socket, nm, NAME_SIZE) > 0) { if (getNextMsg(socket, pw, PSWD_SIZE) > 0) { isValidUser = AuthenticateUser(nm, pw); } } count++; } if (isValidUser) { return(SUCCESS); } else { return(FAIL); } }
C#
λ³΄μ•ˆκΈ°λŠ₯
반볡된 μΈμ¦μ‹œλ„ μ œν•œ κΈ°λŠ₯ λΆ€μž¬
인증 μ‹œλ„ 수λ₯Ό μ œν•œν•˜μ§€ μ•Šμ•„ κ³΅κ²©μžκ°€ 반볡적으둜 μž„μ˜ 값을 μž…λ ₯ν•˜μ—¬ 계정 κΆŒν•œμ„ νšλ“ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
// 둜그인 μ‹€νŒ¨ μ‹œ μ•„λ¬΄λŸ° μ œμ•½μ΄ μ—†μŒ override protected void OnLoginError(EventArgs e) { //do nothing }
override protected void OnLoginError(EventArgs e) { // 연속적인 μ‚¬μš©μž 인증 μ‹œλ„μ— λŒ€ν•œ 횟수λ₯Ό μ œν•œ if(ViewState["LoginErrors"] == null) ViewState["LoginErrors"] = 0; int ErrorCount = (int)ViewState["LoginErrors"] + 1; ViewState["LoginErrors"] = ErrorCount; if((ErrorCount > 3) && Login1.PasswordRecoveryUrl != string.Empty) Response.Redirect(Login1.PasswordRecoveryUrl); }
JAVA
μ‹œκ°„ 및 μƒνƒœ
경쟁쑰건: κ²€μ‚¬μ‹œμ κ³Ό μ‚¬μš©μ‹œμ (TOCTOU)
λ©€ν‹° ν”„λ‘œμ„ΈμŠ€ μƒμ—μ„œ μžμ›μ„ κ²€μ‚¬ν•˜λŠ” μ‹œμ κ³Ό μ‚¬μš©ν•˜λŠ” μ‹œμ μ΄ λ‹¬λΌμ„œ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ 
class FileMgmtThread extends Thread { private String manageType = ""; public FileMgmtThread (String type) { manageType = type; } // λ©€ν‹°μ“°λ ˆλ“œ ν™˜κ²½μ—μ„œ κ³΅μœ μžμ›μ— μ—¬λŸ¬ν”„λ‘œμ„ΈμŠ€κ°€ μ‚¬μš©ν•˜μ—¬ λ™μ‹œμ— μ ‘κ·Όν•  κ°€λŠ₯성이 μžˆμ–΄ μ•ˆμ „ ν•˜μ§€ μ•Šλ‹€. public void run() { try { if (manageType.equals("READ")) { File f = new File("Test_367.txt"); if (f.exists()) { BufferedReader br = new BufferedReader(new FileReader(f)); br.close(); } } else if (manageType.equals("DELETE")) { File f = new File("Test_367.txt"); if (f.exists()) { f.delete(); } else { … } } } catch (IOException e) { … } } } public class CWE367 { public static void main (String[] args) { FileMgmtThread fileAccessThread = new FileMgmtThread("READ"); FileMgmtThread fileDeleteThread = new FileMgmtThread("DELETE"); // 파일의 읽기와 μ‚­μ œκ°€ λ™μ‹œμ— μˆ˜ν–‰λ˜μ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. fileAccessThread.start(); fileDeleteThread.start(); } }
class FileMgmtThread extends Thread { private static final String SYNC = "SYNC"; private String manageType = ""; public FileMgmtThread (String type) { manageType = type; } public void run() { // λ©€ν‹°μ“°λ ˆλ“œ ν™˜κ²½μ—μ„œ synchronizedλ₯Ό μ‚¬μš©ν•˜μ—¬ λ™μ‹œμ— μ ‘κ·Όν•  수 없도둝 μ‚¬μš©ν•΄μ•Όν•œλ‹€. synchronized(SYNC) { try { if (manageType.equals("READ")) { File f = new File("Test_367.txt"); if (f.exists()) { BufferedReader br = new BufferedReader(new FileReader(f)); br.close(); } } else if (manageType.equals("DELETE")) { File f = new File("Test_367.txt"); if (f.exists()) { f.delete(); } else { … } } } catch (IOException e) { … } } } } public class CWE367 { public static void main (String[] args) { FileMgmtThread fileAccessThread = new FileMgmtThread("READ"); FileMgmtThread fileDeleteThread = new FileMgmtThread("DELETE"); fileAccessThread.start(); fileDeleteThread.start(); } }
C#
μ‹œκ°„ 및 μƒνƒœ
경쟁쑰건: κ²€μ‚¬μ‹œμ κ³Ό μ‚¬μš©μ‹œμ (TOCTOU)
λ©€ν‹° ν”„λ‘œμ„ΈμŠ€ μƒμ—μ„œ μžμ›μ„ κ²€μ‚¬ν•˜λŠ” μ‹œμ κ³Ό μ‚¬μš©ν•˜λŠ” μ‹œμ μ΄ λ‹¬λΌμ„œ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ 
// λ©€ν‹°μ“°λ ˆλ“œ ν™˜κ²½μ—μ„œ λ™μ‹œμ— μ ‘κ·Όν•  수 없도둝 μ‚¬μš©ν•΄μ•Όν•œλ‹€. public void ReadFile(String f) { if(File.Exists(f)) { File.ReadAllLines(f); } }
// λ©€ν‹°μ“°λ ˆλ“œ ν™˜κ²½μ—μ„œ λ™μ‹œμ— μ ‘κ·Όν•  수 없도둝 μ‚¬μš©ν•΄μ•Όν•œλ‹€. [MethodImpl(MethodImplOptions.Synchronized)] public void ReadFile(String f) { if(File.Exists(f)) { File.ReadAllLines(f); } }
C
μ‹œκ°„ 및 μƒνƒœ
경쟁쑰건: κ²€μ‚¬μ‹œμ κ³Ό μ‚¬μš©μ‹œμ (TOCTOU)
λ©€ν‹° ν”„λ‘œμ„ΈμŠ€ μƒμ—μ„œ μžμ›μ„ κ²€μ‚¬ν•˜λŠ” μ‹œμ κ³Ό μ‚¬μš©ν•˜λŠ” μ‹œμ μ΄ λ‹¬λΌμ„œ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ 
static volatile double account; void deposit(int amount) { // lock 없이 곡유 μžμ›μ— μ ‘κ·Ό account += amount; } void withdraw(int amount) { account -= amount; }
static volatile double account; static mtx_t account_lock; void deposit(int amount) { // mutex_lock, mutex_unlock을 μ΄μš©ν•΄ 곡유 μžμ› 접근을 μ œν•œν•œλ‹€. mutex_lock(&account_lock); account += amount; mutex_unlock(&account_lock); } void withdraw(int amount) { mutex_lock(&account_lock); account -= amount; mutex_unlock(&account_lock); }
C
μ‹œκ°„ 및 μƒνƒœ
μ’…λ£Œλ˜μ§€ μ•ŠλŠ” 반볡문 λ˜λŠ” μž¬κ·€ν•¨μˆ˜
μ’…λ£Œμ‘°κ±΄ μ—†λŠ” μ œμ–΄λ¬Έ μ‚¬μš©μœΌλ‘œ 반볡문 λ˜λŠ” μž¬κ·€ν•¨μˆ˜κ°€ λ¬΄ν•œνžˆ λ°˜λ³΅λ˜μ–΄ λ°œμƒν•  수 μžˆλŠ” λ³΄μ•ˆμ•½μ 
#include <stdio.h> int factorial(int i) { // μž¬κ·€ν•¨μˆ˜ νƒˆμΆœ 쑰건을 μ„€μ •ν•˜μ§€ μ•Šμ•„ λ¬΄ν•œλ£¨ν”„κ°€ λœλ‹€. return i * factorial(i - 1); } int main() { int num = 5; int result = factorial(num); printf("%d! : %d\n", num, result); return 0; }
#include <stdio.h> int factorial(int I) { // μž¬κ·€ν•¨μˆ˜ μ‚¬μš© μ‹œμ—λŠ” μ•„λž˜μ™€ 같이 νƒˆμΆœ 쑰건을 μ‚¬μš©ν•΄μ•Ό ν•œλ‹€. if (i <= 1) { return 1; } return i * factorial(i – 1); } int main() { int num = 5; int result = factorial(num); printf("%d! : %d\n", num, result); return 0; }
JAVA
μ—λŸ¬μ²˜λ¦¬
였λ₯˜ λ©”μ‹œμ§€ μ •λ³΄λ…ΈμΆœ
였λ₯˜λ©”μ‹œμ§€λ‚˜ μŠ€νƒμ •λ³΄μ— μ‹œμŠ€ν…œ 내뢀ꡬ쑰가 ν¬ν•¨λ˜μ–΄ λ―Όκ°ν•œ 정보, 디버깅 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
try { rd = new BufferedReader(new FileReader(new File(filename))); } catch(IOException e) { // μ—λŸ¬ λ©”μ‹œμ§€λ‘œ μŠ€νƒ 정보가 λ…ΈμΆœλ¨ e.printStackTrace(); }
try { rd = new BufferedReader(new FileReader(new File(filename))); } catch(IOException e) { // μ—λŸ¬ μ½”λ“œμ™€ 정보λ₯Ό λ³„λ„λ‘œ μ •μ˜ν•˜κ³  μ΅œμ†Œ μ •λ³΄λ§Œ λ‘œκΉ… logger.error("ERROR-01: 파일 μ—΄κΈ° μ—λŸ¬"); }
JAVA
μ—λŸ¬μ²˜λ¦¬
였λ₯˜ λ©”μ‹œμ§€ μ •λ³΄λ…ΈμΆœ
였λ₯˜λ©”μ‹œμ§€λ‚˜ μŠ€νƒμ •λ³΄μ— μ‹œμŠ€ν…œ 내뢀ꡬ쑰가 ν¬ν•¨λ˜μ–΄ λ―Όκ°ν•œ 정보, 디버깅 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
catch(IOException e) { // 였λ₯˜λ°œμƒμ‹œ 화면에 좜λ ₯된 μ‹œμŠ€ν…œ μ •λ³΄λ‘œ λ‹€λ₯Έ 곡격의 빌미λ₯Ό μ œκ³΅ν•œλ‹€. System.err.print(e.getMessage()); }
try { rd = new BufferedReader(new FileReader(new File(filename))); } catch(IOException e) { // μ—λŸ¬ μ½”λ“œμ™€ 정보λ₯Ό λ³„λ„λ‘œ μ •μ˜ν•˜κ³  μ΅œμ†Œ μ •λ³΄λ§Œ λ‘œκΉ… logger.error("ERROR-01: 파일 μ—΄κΈ° μ—λŸ¬"); }
C#
μ—λŸ¬μ²˜λ¦¬
였λ₯˜ λ©”μ‹œμ§€ μ •λ³΄λ…ΈμΆœ
였λ₯˜λ©”μ‹œμ§€λ‚˜ μŠ€νƒμ •λ³΄μ— μ‹œμŠ€ν…œ 내뢀ꡬ쑰가 ν¬ν•¨λ˜μ–΄ λ―Όκ°ν•œ 정보, 디버깅 정보가 λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
try { //do something } catch (CustomException e) { Console.WriteLine(e); }
try { //do something } catch (CustomException e) { _log.Debug(β€œERROR-01 : error information”); }
JAVA
μ—λŸ¬μ²˜λ¦¬
였λ₯˜ 상황 λŒ€μ‘ λΆ€μž¬
μ‹œμŠ€ν…œ 였λ₯˜μƒν™©μ„ μ²˜λ¦¬ν•˜μ§€ μ•Šμ•„ ν”„λ‘œκ·Έλž¨ μ‹€ν–‰μ •μ§€ λ“± μ˜λ„ν•˜μ§€ μ•Šμ€ 상황이 λ°œμƒ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
protected Element createContent(WebSession s) { …… try { username = s.getParser().getRawParameter(USERNAME); password = s.getParser().getRawParameter(PASSWORD); if (!"webgoat".equals(username) || !password.equals("webgoat")) { s.setMessage("Invalid username and password entered."); return (makeLogin(s)); } } catch (NullPointerException e) { // μš”μ²­ νŒŒλΌλ―Έν„°μ— PASSWORDκ°€ μ‘΄μž¬ν•˜μ§€ μ•Šμ„ 경우 Null Pointer Exception이 λ°œμƒν•˜κ³  ν•΄λ‹Ή 였λ₯˜μ— λŒ€ν•œ λŒ€μ‘μ΄ μ‘΄μž¬ν•˜μ§€ μ•Šμ•„ 인증이 된 κ²ƒμœΌλ‘œ 처리 }
protected Element createContent(WebSession s) { …… try { username = s.getParser().getRawParameter(USERNAME); password = s.getParser().getRawParameter(PASSWORD); if (!"webgoat".equals(username) || !password.equals("webgoat")) { s.setMessage("Invalid username and password entered."); return (makeLogin(s)); } } catch (NullPointerException e) { // μ˜ˆμ™Έ 사항에 λŒ€ν•΄ μ μ ˆν•œ 쑰치λ₯Ό μˆ˜ν–‰ν•˜μ—¬μ•Ό ν•œλ‹€. s.setMessage(e.getMessage()); return (makeLogin(s)); }
C#
μ—λŸ¬μ²˜λ¦¬
였λ₯˜ 상황 λŒ€μ‘ λΆ€μž¬
μ‹œμŠ€ν…œ 였λ₯˜μƒν™©μ„ μ²˜λ¦¬ν•˜μ§€ μ•Šμ•„ ν”„λ‘œκ·Έλž¨ μ‹€ν–‰μ •μ§€ λ“± μ˜λ„ν•˜μ§€ μ•Šμ€ 상황이 λ°œμƒ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
try { InvokeMtd(); } catch (CustomException e) { // μ˜ˆμ™Έ 상황에 λŒ€ν•œ λŒ€μ‘ λΆ€μž¬ }
try { InvokeMtd(); } catch (CustomException e) { // μ˜ˆμ™Έ 상황에 λŒ€ν•΄ μ μ ˆν•œ 쑰치λ₯Ό μˆ˜ν–‰ν•˜μ—¬μ•Ό ν•œλ‹€. logger.Debug(β€œlog message”); }
JAVA
μ—λŸ¬μ²˜λ¦¬
λΆ€μ μ ˆν•œ μ˜ˆμ™Έ 처리
μ˜ˆμ™Έμ‚¬ν•­μ„ λΆ€μ μ ˆν•˜κ²Œ μ²˜λ¦¬ν•˜μ—¬ μ˜λ„ν•˜μ§€ μ•Šμ€ 상황이 λ°œμƒ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
try { ... reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = reader.readLine(); SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY"); Date date = format.parse(line); // μ˜ˆμ™Έμ²˜λ¦¬λ₯Ό μ„ΈλΆ„ν™” ν•  수 μžˆμŒμ—λ„ κ΄‘λ²”μœ„ν•˜κ²Œ μ‚¬μš©ν•˜μ—¬ 예기치 μ•Šμ€ λ¬Έμ œκ°€ λ°œμƒ ν•  수 μžˆλ‹€. } catch (Exception e) { System.err.println("Exception : " + e.getMessage()); }
try { ... reader = new BufferedReader(new InputStreamReader(url.openStream())); String line = reader.readLine(); SimpleDateFormat format = new SimpleDateFormat("MM/DD/YY"); Date date = format.parse(line); // λ°œμƒν•  수 μžˆλŠ” 였λ₯˜μ˜ μ’…λ₯˜μ™€ μˆœμ„œμ— λ§žμΆ°μ„œ μ˜ˆμ™Έμ²˜λ¦¬ ν•œλ‹€. } catch (MalformedURLException e) { System.err.println("MalformedURLException : " + e.getMessage()); } catch (IOException e) { System.err.println("IOException : " + e.getMessage()); } catch (ParseException e) { System.err.println("ParseException : " + e.getMessage()); }
C#
μ—λŸ¬μ²˜λ¦¬
λΆ€μ μ ˆν•œ μ˜ˆμ™Έ 처리
μ˜ˆμ™Έμ‚¬ν•­μ„ λΆ€μ μ ˆν•˜κ²Œ μ²˜λ¦¬ν•˜μ—¬ μ˜λ„ν•˜μ§€ μ•Šμ€ 상황이 λ°œμƒ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
try { InvokeMtd(); // μ˜ˆμ™Έμ²˜λ¦¬λ₯Ό μ„ΈλΆ„ν™”ν•  수 μžˆμŒμ—λ„ κ΄‘λ²”μœ„ν•˜κ²Œ μ‚¬μš©ν•˜μ—¬ 예기치 μ•Šμ€ λ¬Έμ œκ°€ λ°œμƒν•  수 μžˆλ‹€. } catch (Exception e) { }
try { InvokeMtd(); // λ°œμƒν•  수 μžˆλŠ” 였λ₯˜μ˜ μ’…λ₯˜μ™€ μˆœμ„œμ— λ§žμΆ°μ„œ μ˜ˆμ™Έμ²˜λ¦¬ ν•œλ‹€. } catch (IOException e) { logger.Debug(β€œIOException log here”); } catch (SQLException e){ logger.Debug(β€œSQLException log here”); }
JAVA
μ½”λ“œμ˜€λ₯˜
Null Pointer μ—­μ°Έμ‘°
λ³€μˆ˜μ˜ μ£Όμ†Œ 값이 Null인 객체λ₯Ό μ°Έμ‘°ν•˜λŠ” λ³΄μ•ˆμ•½μ 
public static int cardinality (Object obj, final Collection col) { int count = 0; if (col == null) { return count; } Iterator it = col.iterator(); while (it.hasNext()) { Object elt = it.next(); // objκ°€ null이고 eltκ°€ null이 아닐 경우, Null.equals κ°€ λ˜μ–΄ 널(Null) 포인터 μ—­μ°Έμ‘°κ°€ λ°œμƒν•œλ‹€. if ((null == obj && null == elt) || obj.equals(elt)) { count++; } } return count; }
public static int cardinality (Object obj, final Collection col) { int count = 0; if (col == null) { return count; } Iterator it = col.iterator(); while (it.hasNext()) { Object elt = it.next(); // objλ₯Ό μ°Έμ‘°ν•˜λŠ” equalsκ°€ null이 if ((null == obj && null == elt) || (null != obj && obj.equals(elt))) { count++; } } return count; }
JAVA
μ½”λ“œμ˜€λ₯˜
Null Pointer μ—­μ°Έμ‘°
λ³€μˆ˜μ˜ μ£Όμ†Œ 값이 Null인 객체λ₯Ό μ°Έμ‘°ν•˜λŠ” λ³΄μ•ˆμ•½μ 
String url = reuqest.getParamter("url"); // url 에 null이 λ“€μ–΄μ˜€λ©΄ 널(Null) 포인터 μ—­μ°Έμ‘°κ°€ λ°œμƒν•œλ‹€. if ( url.equals("") )
String url = reuqest.getParamter("url"); // null값을 κ°€μ§€λŠ” μ°Έμ‘° λ³€μˆ˜λ₯Ό μ‚¬μš©ν•  경우, null 검사λ₯Ό μˆ˜ν–‰ν•˜κ³  μ‚¬μš©ν•œλ‹€. if ( url != null || url.equals("") )
C#
μ½”λ“œμ˜€λ₯˜
Null Pointer μ—­μ°Έμ‘°
λ³€μˆ˜μ˜ μ£Όμ†Œ 값이 Null인 객체λ₯Ό μ°Έμ‘°ν•˜λŠ” λ³΄μ•ˆμ•½μ 
protected void Page_Load(object sender, EventArgs e) { // url νŒŒλΌλ―Έν„°μ— name 이 μ—†μœΌλ©΄ username은 null 값을 κ°€μ§€κ²Œ λœλ‹€. string username = Request.QueryString[β€œname”]; // null 값을 κ°€μ§€λŠ” username을 μ°Έμ‘°ν•˜μ—¬ 널(Null) 포인터 μ—­μ°Έμ‘°κ°€ λ°œμƒν•œλ‹€. if (username.Length > 20) { // length error } }
protected void Page_Load(object sender, EventArgs e) { // url νŒŒλΌλ―Έν„°μ— name 이 μ—†μœΌλ©΄ username은 null 값을 κ°€μ§€κ²Œ λœλ‹€. string username = Request.QueryString[β€œname”]; // null 값을 κ°€μ§€λŠ” username을 μ°Έμ‘°ν•˜κΈ° 전에 null 검사λ₯Ό μˆ˜ν–‰ν•˜λ―€λ‘œ μ•ˆμ „ν•˜λ‹€. if ( username != null && username > 20) { // length error } }
C
μ½”λ“œμ˜€λ₯˜
Null Pointer μ—­μ°Έμ‘°
λ³€μˆ˜μ˜ μ£Όμ†Œ 값이 Null인 객체λ₯Ό μ°Έμ‘°ν•˜λŠ” λ³΄μ•ˆμ•½μ 
void NullPointerDereference(int count) { // IntegerAddressReturn()이 0을 return ν•˜λ©΄ pλŠ” null 값을 κ°€μ§€κ²Œ λœλ‹€. int *p = IntegerAddressReturn(); // null 값을 κ°€μ§€λŠ” p 값을 μ°Έμ‘°ν•˜μ—¬ 널(Null) 포인터 μ—­μ°Έμ‘°κ°€ λ°œμƒν•œλ‹€. *p = count; }
void NullPointerDereference(int count) { // IntegerAddressReturn()이 0을 return ν•˜λ©΄ pλŠ” null 값을 κ°€μ§€κ²Œ λœλ‹€. int *p = IntegerAddressReturn(); // μ°Έμ‘°ν•˜κΈ°μ „μ— null 검사λ₯Ό μˆ˜ν–‰ν•˜λ―€λ‘œ μ•ˆμ „ν•˜λ‹€. If(p != 0) *p = count;
JAVA
μ½”λ“œμ˜€λ₯˜
λΆ€μ μ ˆν•œ μžμ› ν•΄μ œ
μ‚¬μš© μ™„λ£Œλœ μžμ›μ„ ν•΄μ œν•˜μ§€ μ•Šμ•„ μžμ›μ΄ κ³ κ°ˆλ˜μ–΄ μƒˆλ‘œμš΄ μž…λ ₯을 μ²˜λ¦¬ν•  수 μ—†λŠ” λ³΄μ•ˆμ•½μ 
InputStream in = null; OutputStream out = null; try { in = new FileInputStream(inputFile); out = new FileOutputStream(outputFile); ... FileCopyUtils.copy(fis, os); // μžμ›λ°˜ν™˜ μ‹€ν–‰ 전에 였λ₯˜κ°€ λ°œμƒν•  경우 μžμ›μ΄ λ°˜ν™˜λ˜μ§€ μ•ŠμœΌλ©°, ν• λ‹Ήλœ λͺ¨λ“  μžμ›μ„ λ°˜ν™˜ν•΄μ•Ό ν•œλ‹€. in.close(); out.close(); } catch (IOException e) { logger.error(e); }
InputStream in = null; OutputStream out = null; try { in = new FileInputStream(inputFile); out = new FileOutputStream(outputFile); ... FileCopyUtils.copy(fis, os); } catch (IOException e) { logger.error(e); // 항상 μˆ˜ν–‰λ˜λŠ” finally λΈ”λ‘μ—μ„œ 할당받은 λͺ¨λ“  μžμ›μ— λŒ€ν•΄ 각각 null검사λ₯Ό μˆ˜ν–‰ ν›„ μ˜ˆμ™Έμ²˜λ¦¬λ₯Ό ν•˜μ—¬ μžμ›μ„ ν•΄μ œν•˜μ—¬μ•Ό ν•œλ‹€. } finally { if (in != null) { try { in.close(); } catch (IOException e) { logger.error(e); } } if (out != null) { try { out.close(); } catch (IOException e) { logger.error(e); } } }
C#
μ½”λ“œμ˜€λ₯˜
λΆ€μ μ ˆν•œ μžμ› ν•΄μ œ
μ‚¬μš© μ™„λ£Œλœ μžμ›μ„ ν•΄μ œν•˜μ§€ μ•Šμ•„ μžμ›μ΄ κ³ κ°ˆλ˜μ–΄ μƒˆλ‘œμš΄ μž…λ ₯을 μ²˜λ¦¬ν•  수 μ—†λŠ” λ³΄μ•ˆμ•½μ 
public void FileStreamTest() { // fsSource에 μžμ›μ΄ ν• λ‹Ήλ˜μ—ˆμœΌλ‚˜ ν•΄μ œλ˜μ§€ μ•ŠλŠ”λ‹€. FileStream fsSource = new FileStream(pathSource, FileMode.Open, FileAccess.Read); byte[] bytes = new byte[fsSource.Length]; int numBytesToRead = (int)fsSource.Length; int numBytesRead = 0; while(numBytesToRead > 0) { int n = fsSource.Read(bytes, numBytesRead, numBytesToRead); if(n==0) break; numBytesToRead += n; numBytesToRead -= n; } using(FileStream fsNew = new FileStream(pathNew, FileMode.Create, FileAccess.Write)) { /* OK */ fsNew.Write(bytes, 0, numBytesToRead); } }
public void FileStreamTest() { // using ꡬ문으둜 μžμ›μ„ ν• λ‹Ήν•˜λ©΄ ꡬ문이 λλ‚˜λŠ” μ§€μ μ—μ„œ μžλ™μœΌλ‘œ μžμ›μ΄ ν•΄μ œλœλ‹€. using(FileStream fsSource = new FileStream(pathSource, FileMode.Open, FileAccess.Read)){ byte[] bytes = new byte[fsSource.Length]; int numBytesToRead = (int)fsSource.Length; int numBytesRead = 0; while(numBytesToRead > 0) { int n = fsSource.Read(bytes, numBytesRead, numBytesToRead); if(n==0) break; numBytesToRead += n; numBytesToRead -= n; } } using(FileStream fsNew = new FileStream(pathNew, FileMode.Create, FileAccess.Write)) { /* OK */ fsNew.Write(bytes, 0, numBytesToRead); } }
C
μ½”λ“œμ˜€λ₯˜
λΆ€μ μ ˆν•œ μžμ› ν•΄μ œ
μ‚¬μš© μ™„λ£Œλœ μžμ›μ„ ν•΄μ œν•˜μ§€ μ•Šμ•„ μžμ›μ΄ κ³ κ°ˆλ˜μ–΄ μƒˆλ‘œμš΄ μž…λ ₯을 μ²˜λ¦¬ν•  수 μ—†λŠ” λ³΄μ•ˆμ•½μ 
void ImproperResourceRelease(char* filename) { char buf[BUF_SIZE]; FILE *f = fopen(filename, β€œr”); if(!checkSomething()) { printf(β€œSomething is wrong”); return; } // checkSomethingμ—μ„œ falseλ₯Ό λ°˜ν™˜ν•˜λŠ” 경우, 파일 ν•Έλ“€λŸ¬λ₯Ό μ’…λ£Œν•  수 μ—†λ‹€. fclose(f); }
void ImproperResourceRelease(char* filename) { char buf[BUF_SIZE]; FILE *f = fopen(filename, β€œr”); if(!checkSomething()) { printf(β€œSomething is wrong”); // checkSomthingμ—μ„œ falseλ₯Ό λ°˜ν™˜ν•΄λ„ 파일 ν•Έλ“€λŸ¬λ₯Ό μ’…λ£Œν•˜λ„λ‘ μˆ˜μ • fclose(f); return; } fclose(f); }
C
μ½”λ“œμ˜€λ₯˜
ν•΄μ œλœ μžμ› μ‚¬μš©
λ©”λͺ¨λ¦¬ λ“± ν•΄μ œλœ μžμ›μ„ μ°Έμ‘°ν•˜μ—¬ 예기치 μ•Šμ€ 였λ₯˜κ°€ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ 
int main(int argc, const char *argv[]) { char *temp; temp = (char *)malloc(BUFFER_SIZE); …… free(temp); // ν•΄μ œν•œ μžμ›μ„ μ‚¬μš©ν•˜κ³  μžˆμ–΄ μ˜λ„ν•˜μ§€ μ•Šμ€ κ²°κ³Όκ°€ λ°œμƒν•˜κ²Œ λœλ‹€. stmcpy(temp, argv[1], BUFFER_SIZE-1); }
int main(int argc,const char *argv[]) { char *temp; temp = (char *)malloc(BUFFER_SIZE); …… // ν• λ‹Ήλœ μžμ›μ„ μ΅œμ’…μ μœΌλ‘œ μ‚¬μš©ν•˜κ³  ν•΄μ œν•˜μ—¬μ•Ό ν•œλ‹€. stmcpy(temp,argv[1], BUFFER_SIZE-1); free(temp); }
C
μ½”λ“œμ˜€λ₯˜
ν•΄μ œλœ μžμ› μ‚¬μš©
λ©”λͺ¨λ¦¬ λ“± ν•΄μ œλœ μžμ›μ„ μ°Έμ‘°ν•˜μ—¬ 예기치 μ•Šμ€ 였λ₯˜κ°€ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ 
char *data; int data_type if (data_type==val_1) { free(data); } …… // 이미 ν•΄μ œλœ μžμ›μ„ 이쀑 ν•΄μ œν•˜μ—¬ λ¬Έμ œκ°€ λ°œμƒν•œλ‹€. if (data_type==val_2) { free(data); }
char *data; int data_type if (data_type==val_1) { free(data); // λ©”λͺ¨λ¦¬λ₯Ό ν•΄μ œν•œ ν›„ 항상 포인터에 NULL을 ν• λ‹Ήν•˜μ—¬ 이쀑 ν•΄μ œν•˜λ”λΌλ„ λ¬΄μ‹œλ˜κ²Œ ν•œλ‹€. data = NULL; } …… if (data_type==val_2) { free(data); // λ©”λͺ¨λ¦¬λ₯Ό ν•΄μ œν•œ ν›„ 항상 포인터에 NULL을 ν• λ‹Ήν•˜μ—¬ 이쀑 ν•΄μ œν•˜λ”λΌλ„ λ¬΄μ‹œλ˜κ²Œ ν•œλ‹€. data = NULL; }
C
μ½”λ“œμ˜€λ₯˜
μ΄ˆκΈ°ν™”λ˜μ§€ μ•Šμ€ λ³€μˆ˜ μ‚¬μš©
λ³€μˆ˜λ₯Ό μ΄ˆκΈ°ν™”ν•˜μ§€ μ•Šκ³  μ‚¬μš©ν•˜μ—¬ 예기치 μ•Šμ€ 였λ₯˜κ°€ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ 
// λ³€μˆ˜μ˜ μ΄ˆκΈ°κ°’μ„ μ§€μ •ν•˜μ§€ μ•Šμ„ 경우 곡격에 μ‚¬μš© 될 수 μžˆμ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. int x, y; switch(position) { case 0: x = base_position; y = base_position beak; case 1: x = base_position + i; y = base_position - i break; default: x=1; break; } setCursorPosition(x,y);
// λ³€μˆ˜μ˜ μ΄ˆκΈ°κ°’μ€ 항상 μ§€μ •ν•˜μ—¬μ•Ό ν•œλ‹€. int x=1, y=1; switch(position) { case 0: x = base_position; y = base_position beak; case 1: x = base_position + i; y = base_position - i break; default: x=1; break; } setCursorPosition(x,y);
JAVA
μ½”λ“œμ˜€λ₯˜
μ‹ λ’°ν•  수 μ—†λŠ” λ°μ΄ν„°μ˜ 역직렬화
μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‚½μž…Β·μˆ˜μ •λœ 직렬화 데이터λ₯Ό μ μ ˆν•œ 검증 없이 μ—­μ§λ ¬ν™”ν•˜μ—¬ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ  * 직렬화: 객체λ₯Ό 전솑 κ°€λŠ₯ν•œ λ°μ΄ν„°ν˜•μ‹μœΌλ‘œ λ³€ν™˜ * 역직렬화: μ§λ ¬ν™”λœ 데이터λ₯Ό μ›λž˜ 객체둜 볡원
public static void main(String[] args) throws IOException, GeneralSecurityException, ClassNotFoundException { .... // map을 역직렬화 ν•œλ‹€. ObjectInputStream in = new ObjectInputStream(new FileInputStream("data")); sealedMap = (SealedObject) in.readObject(); in.close(); // 객체λ₯Ό μΆ”μΆœν•œλ‹€. cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); signedMap = (SignedObject) sealedMap.getObject(cipher); // μ„œλͺ…κ°’ 검증 κ³Όμ •μ—μ„œ 뢈일치 μ‹œ μ˜ˆμ™Έλ₯Ό λ¦¬ν„΄ν•˜κ³ , 일치 μ‹œ map 값을 μ½λŠ”λ‹€. if (!signedMap.verify(kp.getPublic(), sig)) { throw new GeneralSecurityException("Map failed verification"); } map = (SerializableMap<String, Integer>) signedMap.getObject(); }
public static void main(String[] args) throws IOException, GeneralSecurityException, ClassNotFoundException { .... // map을 역직렬화 ν•œλ‹€. ObjectInputStream in = new ObjectInputStream(new FileInputStream("data")); sealedMap = (SealedObject) in.readObject(); in.close(); // 객체λ₯Ό μΆ”μΆœν•œλ‹€. cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); signedMap = (SignedObject) sealedMap.getObject(cipher); // μ„œλͺ…κ°’ 검증 κ³Όμ •μ—μ„œ 뢈일치 μ‹œ μ˜ˆμ™Έλ₯Ό λ¦¬ν„΄ν•˜κ³ , 일치 μ‹œ map 값을 μ½λŠ”λ‹€. if (!signedMap.verify(kp.getPublic(), sig)) { throw new GeneralSecurityException("Map failed verification"); } map = (SerializableMap<String, Integer>) signedMap.getObject(); }
JAVA
μ½”λ“œμ˜€λ₯˜
μ‹ λ’°ν•  수 μ—†λŠ” λ°μ΄ν„°μ˜ 역직렬화
μ•…μ˜μ μΈ μ½”λ“œκ°€ μ‚½μž…Β·μˆ˜μ •λœ 직렬화 데이터λ₯Ό μ μ ˆν•œ 검증 없이 μ—­μ§λ ¬ν™”ν•˜μ—¬ λ°œμƒν•˜λŠ” λ³΄μ•ˆμ•½μ  * 직렬화: 객체λ₯Ό 전솑 κ°€λŠ₯ν•œ λ°μ΄ν„°ν˜•μ‹μœΌλ‘œ λ³€ν™˜ * 역직렬화: μ§λ ¬ν™”λœ 데이터λ₯Ό μ›λž˜ 객체둜 볡원
class DeserializeExample { public static Object deserialize(byte[] buffer) throws IOException, ClassNotFoundException { Object ret = null; try (ByteArrayInputStream bais = new ByteArrayInputStream(buffer)) { try (ObjectInputStream ois = new ObjectInputStream(bais)) { ret = ois.readObject(); } } return ret; } }
public class WhitelistedObjectInputStream extends ObjectInputStream { public Set<String> whitelist; // WhilelistedObjectInputStream을 생성할 λ•Œ ν™”μ΄νŠΈλ¦¬μŠ€νŠΈλ₯Ό μž…λ ₯λ°›λŠ”λ‹€. public WhitelistedObjectInputStream(InputStream inputStream, Set<String> wl) throws IOException { super(inputStream); whitelist = wl; } @Override protected Class<?> resolveClass(ObjectStreamClass cls) throws IOException, ClassNotFoundException { // ObjectStreamClass의 클래슀λͺ…이 ν™”μ΄νŠΈλ¦¬μŠ€νŠΈμ— μžˆλŠ”μ§€ ν™•μΈν•œλ‹€. if (!whitelist.contains(cls.getName())) { throw new InvalidClassException("Unexpected serialized class", cls.getName()); } return super.resolveClass(cls); } } @RequestMapping(value = "/upload", method = RequestMethod.POST) public Student upload(@RequestParam("file") MultipartFile multipartFile) throws ClassNotFoundException, IOException { Student student = null; File targetFile = new File("/temp/" + multipartFile.getOriginalFilename()); // 역직렬화 λŒ€μƒ 클래슀 μ΄λ¦„μ˜ ν™”μ΄νŠΈλ¦¬μŠ€νŠΈ μƒμ„±ν•œλ‹€. Set<String> whitelist = new HashSet<String>(Arrays.asList( new String[] { "Student" })); try (InputStream fileStream = multipartFile.getInputStream()) { try (WhitelistedObjectInputStream ois = new WhitelistedObjectInputStream(fileStream, whitelist)) { // ν™”μ΄νŠΈλ¦¬μŠ€νŠΈμ— μ—†λŠ” 역직렬화 λ°μ΄ν„°μ˜ 경우 μ˜ˆμ™Έ λ°œμƒμ‹œν‚¨λ‹€. student = (Student) ois.readObject(); } } return student; }
JAVA
μΊ‘μŠν™”
잘λͺ»λœ μ„Έμ…˜μ— μ˜ν•œ 데이터 μ •λ³΄λ…ΈμΆœ
잘λͺ»λœ μ„Έμ…˜μ— μ˜ν•΄ μΈκ°€λ˜μ§€ μ•Šμ€ μ‚¬μš©μžμ—κ²Œ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
<%@page import="javax.xml.namespace.*"%> <%@page import="gov.mogaha.ntis.web.frs.gis.cmm.util.*" %> <%! // JSPμ—μ„œ String ν•„λ“œλ“€μ΄ 멀버 λ³€μˆ˜λ‘œ 선언됨 String username = "/"; String imagePath = commonPath + "img/"; String imagePath_gis = imagePath + "gis/cmm/btn/"; ...... %>
<%@page import="javax.xml.namespace.*"%> <%@page import="gov.mogaha.ntis.web.frs.gis.cmm.util.*" %> <% // JSPμ—μ„œ String ν•„λ“œλ“€μ΄ 둜컬 λ³€μˆ˜λ‘œ 선언됨 String commonPath = "/"; String imagePath = commonPath + "img/"; String imagePath_gis = imagePath + "gis/cmm/btn/"; ...... %>
JAVA
μΊ‘μŠν™”
잘λͺ»λœ μ„Έμ…˜μ— μ˜ν•œ 데이터 μ •λ³΄λ…ΈμΆœ
잘λͺ»λœ μ„Έμ…˜μ— μ˜ν•΄ μΈκ°€λ˜μ§€ μ•Šμ€ μ‚¬μš©μžμ—κ²Œ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
/* * @Controller * public class TrendForecastController { * // Controllerμ—μ„œ int ν•„λ“œκ°€ 멀버 λ³€μˆ˜λ‘œ μ„ μ–Έλ˜μ–΄ μŠ€λ ˆλ“œκ°„μ— 곡유됨 * private int currentPage = 1; * * public void doSomething(HttpServletRequest request) { * currentPage = Integer.parseInt(request.getParameter("page")); * }...... * } */
/* * @Controller * public class TrendForecastController { * public void doSomething(HttpServletRequest request) { * // μ§€μ—­λ³€μˆ˜λ‘œ μ‚¬μš©ν•˜μ—¬ μŠ€λ ˆλ“œκ°„ κ³΅μœ λ˜μ§€ λͺ»ν•˜λ„둝 ν•œλ‹€. * int currentPage = Integer.parseInt(request.getParameter("page")); * }...... * } */
C#
μΊ‘μŠν™”
잘λͺ»λœ μ„Έμ…˜μ— μ˜ν•œ 데이터 μ •λ³΄λ…ΈμΆœ
잘λͺ»λœ μ„Έμ…˜μ— μ˜ν•΄ μΈκ°€λ˜μ§€ μ•Šμ€ μ‚¬μš©μžμ—κ²Œ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
class DataLeakBetweenSessions : IHttpHandler { // 닀쀑 μŠ€λ ˆλ“œ ν™˜κ²½μ—μ„œ IHttpHandler λ₯Ό κ΅¬ν˜„ν•˜λŠ” ν΄λž˜μŠ€μ— 정보λ₯Ό μ €μž₯ν•˜λŠ” ν•„λ“œκ°€ ν¬ν•¨λ˜λ©΄ μ•ˆλœλ‹€. private String id; public void ProcessRequest(HttpContext ctx) { var json = new JSONResonse() { Success = ctx.Request.QueryString["name"] != null, Name = ctx.Request.QueryString["name"] }; ctx.Response.ContentType = "application/json"; ctx.Response.Write(JsonConvert.SerializeObject(json)); } public bool IsReusable { get { return false; } } }
class DataLeakBetweenSessions : IHttpHandler { public void ProcessRequest(HttpContext ctx) { // μ§€μ—­λ³€μˆ˜λ‚˜ μ„Έμ…˜λ³€μˆ˜λ₯Ό μ„ μ–Έν•΄μ„œ μ‚¬μš©ν•΄μ•Όν•œλ‹€. ctx.Session["id"] = ctx.Request.QueryString["id"]; ctx.Response.ContentType = "application/json"; ctx.Response.Write(JsonConvert.SerializeObject(json)); } public bool IsReusable { get { return false; } } } var json = new JSONResonse() { Success = ctx.Request.QueryString["name"] != null, Name = ctx.Request.QueryString["name"] };
JAVA
μΊ‘μŠν™”
μ œκ±°λ˜μ§€ μ•Šκ³  남은 디버그 μ½”λ“œ
디버깅을 μœ„ν•œ μ½”λ“œλ₯Ό μ œκ±°ν•˜μ§€ μ•Šμ•„ μΈκ°€λ˜μ§€ μ•Šμ€ μ‚¬μš©μžμ—κ²Œ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
class Base64 { public static void main(String[] args) { if (debug) { byte[] a = { (byte) 0xfc, (byte) 0x0f, (byte) 0xc0 }; byte[] b = { (byte) 0x03, (byte) 0xf0, (byte) 0x3f }; ...... } } public void otherMethod() { ... } }
class Base64 { public void otherMethod() { ... } }
C#
μΊ‘μŠν™”
μ œκ±°λ˜μ§€ μ•Šκ³  남은 디버그 μ½”λ“œ
디버깅을 μœ„ν•œ μ½”λ“œλ₯Ό μ œκ±°ν•˜μ§€ μ•Šμ•„ μΈκ°€λ˜μ§€ μ•Šμ€ μ‚¬μš©μžμ—κ²Œ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
class Example { public void Log() { // Console.WriteLine λ“±μ˜ λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•œ λ””λ²„κ·Έμš© μ½”λ“œκ°€ λ‚¨μ•„μžˆλ‹€. Console.WriteLine("sensitive info"); } }
class Example { public void Log() { // λ””λ²„κ·Έμš© μ½”λ“œλ₯Ό μ‚­μ œν•΄μ•Όν•œλ‹€. //Console.WriteLine("sensitive info"); } }
C
μΊ‘μŠν™”
μ œκ±°λ˜μ§€ μ•Šκ³  남은 디버그 μ½”λ“œ
디버깅을 μœ„ν•œ μ½”λ“œλ₯Ό μ œκ±°ν•˜μ§€ μ•Šμ•„ μΈκ°€λ˜μ§€ μ•Šμ€ μ‚¬μš©μžμ—κ²Œ μ€‘μš”μ •λ³΄κ°€ λ…ΈμΆœ κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
void LeftoverDebugCode() { int i, ntprs; char **strings; nptrs = backtrace(buffer, 100); strings = backtrace_symbols(buffer, nptrs); ... // 디버그 λͺ¨λ“œμΌ μ‹œ μ½œμŠ€νƒμ„ 좜λ ₯ν•œλ‹€. if(debug) { for(i=0; i < nptr; i++) printf(β€œ%s\n”, strings[j]); } }
void LeftoverDebugCode() { ... // 디버그 μ½”λ“œλ₯Ό μ‚­μ œν•˜κ³  λ™μž‘ μ½”λ“œλ§Œ 남긴닀. }
JAVA
μΊ‘μŠν™”
Public λ©”μ†Œλ“œλΆ€ν„° λ°˜ν™˜λœ Private λ°°μ—΄
Public으둜 μ„ μ–Έλœ λ©”μ†Œλ“œμ—μ„œ Private둜 μ„ μ–Έλœ 배열을 λ°˜ν™˜(return)ν•˜λ©΄ Private λ°°μ—΄μ˜ μ£Όμ†Œ 값이 외뢀에 λ…ΈμΆœλ˜μ–΄ ν•΄λ‹Ή Private 배열값을 μ™ΈλΆ€μ—μ„œ μˆ˜μ • κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
// private 인 배열을 public인 λ©”μ†Œλ“œκ°€ returnν•œλ‹€. private Color[] colors; public Color[] getUserColors(Color[] userColors) { return colors; }
// μ•ˆμ „ν•œ μ½”λ“œμ˜ 예 JAVA (λ°°μ—΄μ˜ μ›μ†Œκ°€ 일반객체일 경우) private Color[] colors; // λ©”μ†Œλ“œλ₯Ό private으둜 ν•˜κ±°λ‚˜, 볡제본 λ°˜ν™˜, μˆ˜μ •ν•˜λŠ” public λ©”μ†Œλ“œλ₯Ό λ³„λ„λ‘œ λ§Œλ“ λ‹€. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Color[] newColors = getUserColors(); ...... } public Color[] getUserColors(Color[] userColors) { // 배열을 λ³΅μ‚¬ν•œλ‹€. Color[] colors = new Color[userColors.length]; for (int i = 0; i < colors.length; i++) // clone()λ©”μ†Œλ“œλ₯Ό μ΄μš©ν•˜μ—¬ λ°°μ—΄μ˜ μ›μ†Œλ„ λ³΅μ‚¬ν•œλ‹€. colors[i] = this.colors[i].clone(); return colors; }
JAVA
μΊ‘μŠν™”
Public λ©”μ†Œλ“œλΆ€ν„° λ°˜ν™˜λœ Private λ°°μ—΄
Public으둜 μ„ μ–Έλœ λ©”μ†Œλ“œμ—μ„œ Private둜 μ„ μ–Έλœ 배열을 λ°˜ν™˜(return)ν•˜λ©΄ Private λ°°μ—΄μ˜ μ£Όμ†Œ 값이 외뢀에 λ…ΈμΆœλ˜μ–΄ ν•΄λ‹Ή Private 배열값을 μ™ΈλΆ€μ—μ„œ μˆ˜μ • κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
// private 인 배열을 public인 λ©”μ†Œλ“œκ°€ returnν•œλ‹€. private String[] colors; public String[] getColors() { return colors; }
// μ•ˆμ „ν•œ μ½”λ“œμ˜ 예 JAVA (λ°°μ—΄μ˜ μ›μ†Œκ°€ String νƒ€μž… λ“±κ³Ό 같이 μˆ˜μ •μ΄ λ˜μ§€ μ•ŠλŠ” 경우) private String[] colors; // λ©”μ†Œλ“œλ₯Ό private으둜 ν•˜κ±°λ‚˜, 볡제본 λ°˜ν™˜, μˆ˜μ •ν•˜λŠ” public λ©”μ†Œλ“œλ₯Ό λ³„λ„λ‘œ λ§Œλ“ λ‹€. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] newColors = getColors(); ...... } public String[] getColors() { String[] ret = null; if (this.colors != null) { ret = new String[colors.length]; for (int i = 0; i < colors.length; i++) { ret[i] = this.colors[i]; } } return ret; }
C#
μΊ‘μŠν™”
Public λ©”μ†Œλ“œλΆ€ν„° λ°˜ν™˜λœ Private λ°°μ—΄
Public으둜 μ„ μ–Έλœ λ©”μ†Œλ“œμ—μ„œ Private둜 μ„ μ–Έλœ 배열을 λ°˜ν™˜(return)ν•˜λ©΄ Private λ°°μ—΄μ˜ μ£Όμ†Œ 값이 외뢀에 λ…ΈμΆœλ˜μ–΄ ν•΄λ‹Ή Private 배열값을 μ™ΈλΆ€μ—μ„œ μˆ˜μ • κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
// private 인 collection을 public인 λ©”μ†Œλ“œκ°€ returnν•œλ‹€. private List<Color> colors; public List<Color> getUserColors() { return colors; }
private List<Color> colors; // λ©”μ†Œλ“œλ₯Ό private으둜 ν•˜κ±°λ‚˜, 볡제본 λ°˜ν™˜, μˆ˜μ •ν•˜λŠ” public λ©”μ†Œλ“œλ₯Ό λ³„λ„λ‘œ λ§Œλ“ λ‹€. public List<Color> getUserColors() { // 배열을 λ³΅μ‚¬ν•œλ‹€. List< ICloneable> newList = new List< ICloneable>(colors.Count); //Clone()λ©”μ†Œλ“œλ₯Ό μ΄μš©ν•˜μ—¬ collection의 μ›μ†Œλ„ λ³΅μ‚¬ν•œλ‹€. colors.ForEach((item) => { newList.Add((ICloneable)item.Clone()); }); return newList; }
JAVA
μΊ‘μŠν™”
Private 배열에 Public 데이터 ν• λ‹Ή
Public으둜 μ„ μ–Έλœ 데이터 λ˜λŠ” λ©”μ†Œλ“œμ˜ μΈμžκ°€ Private으둜 μ„ μ–Έλœ 배열에 μ €μž₯되면 이 Private 배열을 μ™ΈλΆ€μ—μ„œ μ ‘κ·Όν•˜μ—¬ μˆ˜μ • κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
// userRoles ν•„λ“œλŠ” privateμ΄μ§€λ§Œ, public인 setUserRoles()둜 μ™ΈλΆ€μ˜ 배열이 ν• λ‹Ήλ˜λ©΄, 사싀상 public ν•„λ“œκ°€ λœλ‹€. private UserRole[] userRoles; public void setUserRoles(UserRole[] userRoles) { this.userRoles = userRoles; }
// μ•ˆμ „ν•œ μ½”λ“œμ˜ 예 JAVA (λ°°μ—΄μ˜ μ›μ†Œκ°€ 일반객체일 경우) // 객체가 클래슀의 private memberλ₯Ό μˆ˜μ •ν•˜μ§€ μ•Šλ„λ‘ ν•œλ‹€. private UserRole[] userRoles; public void setUserRoles(UserRole[] userRoles) { this.userRoles = new UserRole[userRoles.length]; for (int i = 0; i < userRoles.length; ++i) this.userRoles[i] = userRoles[i].clone(); }
JAVA
μΊ‘μŠν™”
Private 배열에 Public 데이터 ν• λ‹Ή
Public으둜 μ„ μ–Έλœ 데이터 λ˜λŠ” λ©”μ†Œλ“œμ˜ μΈμžκ°€ Private으둜 μ„ μ–Έλœ 배열에 μ €μž₯되면 이 Private 배열을 μ™ΈλΆ€μ—μ„œ μ ‘κ·Όν•˜μ—¬ μˆ˜μ • κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
// userRoles ν•„λ“œλŠ” privateμ΄μ§€λ§Œ, public인 setUserRoles()둜 μ™ΈλΆ€μ˜ 배열이 ν• λ‹Ήλ˜λ©΄, 사싀상 public ν•„λ“œκ°€ λœλ‹€. private String[] userRoles; public void setUserRoles(String[] userRoles) { this.userRoles = userRoles; }
// μ•ˆμ „ν•œ μ½”λ“œμ˜ 예 (λ°°μ—΄μ˜ μ›μ†Œκ°€ String νƒ€μž… λ“±κ³Ό 같이 μˆ˜μ •μ΄ λ˜μ§€ μ•ŠλŠ” 경우) // 객체가 클래슀의 private memberλ₯Ό μˆ˜μ •ν•˜μ§€ μ•Šλ„λ‘ ν•œλ‹€. private String[] userRoles; public void setUserRoles(String[] userRoles) { this.userRoles = new String[userRoles.length]; for (int i = 0; i < userRoles.length; ++i) this.userRoles[i] = userRoles[i]; }
C#
μΊ‘μŠν™”
Private 배열에 Public 데이터 ν• λ‹Ή
Public으둜 μ„ μ–Έλœ 데이터 λ˜λŠ” λ©”μ†Œλ“œμ˜ μΈμžκ°€ Private으둜 μ„ μ–Έλœ 배열에 μ €μž₯되면 이 Private 배열을 μ™ΈλΆ€μ—μ„œ μ ‘κ·Όν•˜μ—¬ μˆ˜μ • κ°€λŠ₯ν•œ λ³΄μ•ˆμ•½μ 
class Program { // userRoles ν•„λ“œλŠ” privateμ΄μ§€λ§Œ, public인 setUserRoles()으둜 μ™ΈλΆ€μ˜ 배열이 ν• λ‹Ήλ˜λ©΄, 사싀상 public ν•„λ“œκ°€ λœλ‹€. private String[] userRoles; public void SetUserRoles(String[] userRoles) { this.userRoles = userRoles; } }
class Program { // 객체가 클래슀의 private memberλ₯Ό μˆ˜μ •ν•˜μ§€ μ•Šλ„λ‘ ν•œλ‹€. private String[] userRoles; public void SetUserRoles(String[] userRoles) { int length = userRoles.Length; this.userRoles = new String[length]; for(int i = 0; i < length; i++) { \ this.userRoles[i] = userRoles[i]; } } }
JAVA
API 였용
DNS lookup에 μ˜μ‘΄ν•œ λ³΄μ•ˆκ²°μ •
도메인λͺ… 확인(DNS lookup)으둜 λ³΄μ•ˆκ²°μ •μ„ μˆ˜ν–‰ν•  λ•Œ μ•…μ˜μ μœΌλ‘œ λ³€μ‘°λœ DNS μ •λ³΄λ‘œ 예기치 μ•Šμ€ λ³΄μ•ˆμœ„ν˜‘μ— λ…ΈμΆœλ˜λŠ” λ³΄μ•ˆμ•½μ 
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { boolean trusted = false; String ip = req.getRemoteAddr(); InetAddress addr = InetAddress.getByName(ip); // 도메인은 κ³΅κ²©μžμ— μ˜ν•΄ μ‹€ν–‰λ˜λŠ” μ„œλ²„μ˜ DNSκ°€ 변경될 수 μžˆμœΌλ―€λ‘œ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. if (addr.getCanonicalHostName().endsWith("trustme.com")) { do_something_for_Trust_System(); }
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String ip = req.getRemoteAddr(); if (ip == null || "".equals(ip)) return ; // μ΄μš©ν•˜λ €λŠ” μ‹€μ œ μ„œλ²„μ˜ IP μ£Όμ†Œλ₯Ό μ‚¬μš©ν•˜μ—¬ DNS변쑰에 λ°©μ–΄ν•œλ‹€. String trustedAddr = "127.0.0.1"; if (ip.equals(trustedAddr)) { do_something_for_Trust_System(); }
C#
API 였용
DNS lookup에 μ˜μ‘΄ν•œ λ³΄μ•ˆκ²°μ •
도메인λͺ… 확인(DNS lookup)으둜 λ³΄μ•ˆκ²°μ •μ„ μˆ˜ν–‰ν•  λ•Œ μ•…μ˜μ μœΌλ‘œ λ³€μ‘°λœ DNS μ •λ³΄λ‘œ 예기치 μ•Šμ€ λ³΄μ•ˆμœ„ν˜‘μ— λ…ΈμΆœλ˜λŠ” λ³΄μ•ˆμ•½μ 
bool trusted; string remoteIpAddress = Request.ServerVariables["REMOTE_HOST"]; IPAddress hostIPAddress = IPAddress.Parse(remoteIpAddress); IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress); string hostName = hostInfo.HostName; if (hostName.EndsWith("trust.com")) { trusted = true; }
bool trusted; string remoteIpAddress = Request.ServerVariables["REMOTE_HOST"]; if ( remoteIpAddress.Equals(trustedAddr)) { trusted = true; Do_something_for_Trust_System(); }
C
API 였용
DNS lookup에 μ˜μ‘΄ν•œ λ³΄μ•ˆκ²°μ •
도메인λͺ… 확인(DNS lookup)으둜 λ³΄μ•ˆκ²°μ •μ„ μˆ˜ν–‰ν•  λ•Œ μ•…μ˜μ μœΌλ‘œ λ³€μ‘°λœ DNS μ •λ³΄λ‘œ 예기치 μ•Šμ€ λ³΄μ•ˆμœ„ν˜‘μ— λ…ΈμΆœλ˜λŠ” λ³΄μ•ˆμ•½μ 
struct hostent *hp;struct in_addr myaddr; char* tHost = "trustme.example.com"; myaddr.s_addr=inet_addr(ip_addr_string); hp = gethostbyaddr((char *) &myaddr, sizeof(struct in_addr), AF_INET); // μš”μ²­μ˜ 신뒰성을 호슀트의 μ΄λ¦„μœΌλ‘œ νŒλ³„ν•˜κ³  μžˆλ‹€. if (hp && !strncmp(hp->h_name, tHost, sizeof(tHost))) { trusted = true; } else { trusted = false; }
struct hostent *hp;struct in_addr myaddr; char* tHost = "127.0.0.1"; myaddr.s_addr=inet_addr(ip_addr_string); hp = gethostbyaddr((char *) &myaddr, sizeof(struct in_addr), AF_INET); // 호슀트의 이름이 μ•„λ‹ˆλΌ IP둜 직접 λΉ„κ΅ν•œλ‹€. if (hp && !strncmp(hp->h_name, tHost, sizeof(tHost))) { trusted = true; } else { trusted = false; }
C
API 였용
μ·¨μ•½ν•œ API μ‚¬μš©
μ·¨μ•½ν•œ ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄μ„œ 예기치 μ•Šμ€ λ³΄μ•ˆμœ„ν˜‘μ— λ…ΈμΆœλ˜λŠ” λ³΄μ•ˆμ•½μ 
#include <stdio.h> void requestString() { char str[100]; // gets() ν•¨μˆ˜λŠ” λ¬Έμžμ—΄ 길이λ₯Ό μ œν•œ ν•  수 μ—†μ–΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. gets(str); }
#include <stdio.h> void requestString() { char str[100]; // gets_s() ν•¨μˆ˜λŠ” λ¬Έμžμ—΄ 길이 μ œν•œμ΄ κ°€λŠ₯ν•˜λ‹€. gets_s(str, sizeof(str)); }
JAVA
API 였용
μ·¨μ•½ν•œ API μ‚¬μš©
μ·¨μ•½ν•œ ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄μ„œ 예기치 μ•Šμ€ λ³΄μ•ˆμœ„ν˜‘μ— λ…ΈμΆœλ˜λŠ” λ³΄μ•ˆμ•½μ 
public class S246 extends javax.servlet.http.HttpServlet { private Socket socket protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { // ν”„λ ˆμž„μ›Œν¬μ˜ λ©”μ†Œλ“œ 호좜 λŒ€μ‹  μ†ŒμΌ“μ„ 직접 μ‚¬μš©ν•˜κ³  μžˆμ–΄ ν”„λ ˆμž„μ›Œν¬μ—μ„œ μ œκ³΅ν•˜λŠ” λ³΄μ•ˆκΈ°λŠ₯을 제곡 λ°›μ§€ λͺ»ν•΄ μ•ˆμ „ν•˜μ§€ μ•Šλ‹€. socket = new Socket("kisa.or.kr", 8080); } catch (UnknownHostException e) { ......
public class S246 extends javax.servlet.http.HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { URL url = new URL("http://127.0.0.1:8080/DataServlet"); // λ³΄μ•ˆκΈ°λŠ₯을 μ œκ³΅ν•˜λŠ” ν”„λ ˆμž„μ›Œν¬μ˜ λ©”μ†Œλ“œλ₯Ό μ‚¬μš©ν•˜μ—¬μ•Όν•œλ‹€. URLConnection urlConn = url.openConnection(); urlConn.setDoOutput(true); .......
JAVA
API 였용
μ·¨μ•½ν•œ API μ‚¬μš©
μ·¨μ•½ν•œ ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄μ„œ 예기치 μ•Šμ€ λ³΄μ•ˆμœ„ν˜‘μ— λ…ΈμΆœλ˜λŠ” λ³΄μ•ˆμ•½μ 
public class U382 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { do_something(logger); } catch (IOException ase) { logger.info("ERROR"); // J2EE ν”„λ‘œκ·Έλž¨μ—μ„œ System.exit()을 μ‚¬μš©ν•˜μ—¬ μ„œλΉ„μŠ€κ°€ μ’…λ£Œ 될 수 μžˆλ‹€. System.exit(1); }
public class U382 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { do_something(logger); } catch (IOException ase) { logger.info("ERROR"); // μ„œλΉ„μŠ€ μ’…λ£Œλ₯Ό 막기 μœ„ν•΄ J2EEμ—μ„œλŠ” System.exit()λ₯Ό μ‚¬μš©ν•˜μ§€ μ•ŠλŠ”λ‹€. }
C#
API 였용
μ·¨μ•½ν•œ API μ‚¬μš©
μ·¨μ•½ν•œ ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄μ„œ 예기치 μ•Šμ€ λ³΄μ•ˆμœ„ν˜‘μ— λ…ΈμΆœλ˜λŠ” λ³΄μ•ˆμ•½μ 
try { ... } catch (Exception e) { ... // Application.Exit() 은 μ¦‰μ‹œ ν”„λ‘œκ·Έλž¨μ„ μ’…λ£Œν•˜κΈ° λ•Œλ¬Έμ—, Form.Closed ν˜Ήμ€ Form.Closing μ΄λ²€νŠΈκ°€ μ²˜λ¦¬λ˜μ§€ μ•ŠλŠ”λ‹€. Application.Exit(); }
try { ... } catch (Exception e) { ... // Application.Exit() 을 μ‚¬μš©ν•˜μ§€ μ•ŠμœΌλ©΄, 이벀트λ₯Ό μ²˜λ¦¬ν•˜μ§€ λͺ»ν•˜κ³  ν”„λ‘œκ·Έλž¨μ΄ μ’…λ£Œλ˜λŠ” 것을 λ°©μ§€ν•  수 μžˆλ‹€. this.Close(); }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
SQL μΈμ μ…˜ λ°©μ§€
null
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; class Login { public Connection getConnection() throws SQLException { DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver()); String dbConnection = PropertyManager.getProperty("db.connection"); // Can hold some value like // "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>" return DriverManager.getConnection(dbConnection); } String hashPassword(char[] password) { // Create hash of password } public void doPrivilegedAction(String username, char[] password) throws SQLException { Connection connection = getConnection(); if (connection == null) { // Handle error } try { String pwd = hashPassword(password); String sqlString = "SELECT * FROM db_user WHERE username = '" + username + "' AND password = '" + pwd + "'"; Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery(sqlString); if (!rs.next()) { throw new SecurityException( "User name or password incorrect" ); } // Authenticated; proceed } finally { try { connection.close(); } catch (SQLException x) { // Forward to handler } } } }
public void doPrivilegedAction( String username, char[] password) throws SQLException { Connection connection = getConnection(); if (connection == null) { // Handle error } try { String pwd = hashPassword(password); // Validate username length if (username.length() > 8) { // Handle error } String sqlString = "select * from db_user where username=? and password=?"; PreparedStatement stmt = connection.prepareStatement(sqlString); stmt.setString(1, username); stmt.setString(2, pwd); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { throw new SecurityException("User name or password incorrect"); } // Authenticated; proceed } finally { try { connection.close(); } catch (SQLException x) { // Forward to handler } } }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
SQL μΈμ μ…˜ λ°©μ§€
null
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; class Login { public Connection getConnection() throws SQLException { DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver()); String dbConnection = PropertyManager.getProperty("db.connection"); // Can hold some value like // "jdbc:microsoft:sqlserver://<HOST>:1433,<UID>,<PWD>" return DriverManager.getConnection(dbConnection); } String hashPassword(char[] password) { // Create hash of password } public void doPrivilegedAction( String username, char[] password) throws SQLException { Connection connection = getConnection(); if (connection == null) { // Handle error } try { String pwd = hashPassword(password); String sqlString = "select * from db_user where username=" + username + " and password =" + pwd; PreparedStatement stmt = connection.prepareStatement(sqlString); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { throw new SecurityException("User name or password incorrect"); } // Authenticated; proceed } finally { try { connection.close(); } catch (SQLException x) { // Forward to handler } } } }
public void doPrivilegedAction( String username, char[] password) throws SQLException { Connection connection = getConnection(); if (connection == null) { // Handle error } try { String pwd = hashPassword(password); // Validate username length if (username.length() > 8) { // Handle error } String sqlString = "select * from db_user where username=? and password=?"; PreparedStatement stmt = connection.prepareStatement(sqlString); stmt.setString(1, username); stmt.setString(2, pwd); ResultSet rs = stmt.executeQuery(); if (!rs.next()) { throw new SecurityException("User name or password incorrect"); } // Authenticated; proceed } finally { try { connection.close(); } catch (SQLException x) { // Forward to handler } } }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
μœ νš¨μ„± 검사 μ „ λ¬Έμžμ—΄ μ •κ·œν™”
null
// String s may be user controllable // \uFE64 is normalized to < and \uFE65 is normalized to > using the NFKC normalization form String s = "\uFE64" + "script" + "\uFE65"; // Validate Pattern pattern = Pattern.compile("[<>]"); // Check for angle brackets Matcher matcher = pattern.matcher(s); if (matcher.find()) { // Found black listed tag throw new IllegalStateException(); } else { // ... } // Normalize s = Normalizer.normalize(s, Form.NFKC);
String s = "\uFE64" + "script" + "\uFE65"; // Normalize s = Normalizer.normalize(s, Form.NFKC); // Validate Pattern pattern = Pattern.compile("[<>]"); Matcher matcher = pattern.matcher(s); if (matcher.find()) { // Found blacklisted tag throw new IllegalStateException(); } else { // ... }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
μ²˜λ¦¬λ˜μ§€ μ•Šμ€ μ‚¬μš©μž μž…λ ₯ κΈ°λ‘ν•˜μ§€ μ•ŠκΈ°
null
if (loginSuccessful) { logger.severe("User login succeeded for: " + username); } else { logger.severe("User login failed for: " + username); }
if(loginSuccessful){logger.severe("User login succeeded for: "+sanitizeUser(username));}else{logger.severe("User login failed for: "+sanitizeUser(username));} public String sanitizeUser(String username){return Pattern.matches("[A-Za-z0-9_]+",username))?username:"unauthorized user";} Logger sanLogger=new SanitizedTextLogger(logger); if(loginSuccessful){sanLogger.severe("User login succeeded for: "+username);}else{sanLogger.severe("User login failed for: "+username);} class SanitizedTextLogger extends Logger { Logger delegate; public SanitizedTextLogger(Logger delegate) { super(delegate.getName(), delegate.getResourceBundleName()); this.delegate = delegate; } public String sanitize(String msg) { Pattern newline = Pattern.compile("\n"); Matcher matcher = newline.matcher(msg); return matcher.replaceAll("\n "); } public void severe(String msg) { delegate.severe(sanitize(msg)); } // .. Other Logger methods which must also sanitize their log messages }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
ZipInputStreamμ—μ„œ νŒŒμΌμ„ μ•ˆμ „ν•˜κ²Œ μΆ”μΆœν•˜κΈ°
null
static final int BUFFER = 512; // ... public final void unzip(String filename) throws java.io.IOException{ FileInputStream fis = new FileInputStream(filename); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; try { while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); int count; byte data[] = new byte[BUFFER]; // Write the files to the disk FileOutputStream fos = new FileOutputStream(entry.getName()); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); zis.closeEntry(); } } finally { zis.close(); } }
static final int BUFFER = 512; static final long TOOBIG = 0x6400000; // Max size of unzipped data, 100MB static final int TOOMANY = 1024; // Max number of files // ... private String validateFilename(String filename, String intendedDir) throws java.io.IOException { File f = new File(filename); String canonicalPath = f.getCanonicalPath(); File iD = new File(intendedDir); String canonicalID = iD.getCanonicalPath(); if (canonicalPath.startsWith(canonicalID)) { return canonicalPath; } else { throw new IllegalStateException("File is outside extraction target directory."); } } public final void unzip(String filename) throws java.io.IOException { FileInputStream fis = new FileInputStream(filename); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; int entries = 0; long total = 0; try { while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); int count; byte data[] = new byte[BUFFER]; // Write the files to the disk, but ensure that the filename is valid, // and that the file is not insanely big String name = validateFilename(entry.getName(), "."); if (entry.isDirectory()) { System.out.println("Creating directory " + name); new File(name).mkdir(); continue; } FileOutputStream fos = new FileOutputStream(name); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while (total + BUFFER <= TOOBIG && (count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); total += count; } dest.flush(); dest.close(); zis.closeEntry(); entries++; if (entries > TOOMANY) { throw new IllegalStateException("Too many files to unzip."); } if (total + BUFFER > TOOBIG) { throw new IllegalStateException("File being unzipped is too big."); } } } finally { zis.close(); } }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
ZipInputStreamμ—μ„œ νŒŒμΌμ„ μ•ˆμ „ν•˜κ²Œ μΆ”μΆœν•˜κΈ°
null
static final int BUFFER = 512; static final int TOOBIG = 0x6400000; // 100MB // ... public final void unzip(String filename) throws java.io.IOException{ FileInputStream fis = new FileInputStream(filename); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; try { while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); int count; byte data[] = new byte[BUFFER]; // Write the files to the disk, but only if the file is not insanely big if (entry.getSize() > TOOBIG ) { throw new IllegalStateException("File to be unzipped is huge."); } if (entry.getSize() == -1) { throw new IllegalStateException("File to be unzipped might be huge."); } FileOutputStream fos = new FileOutputStream(entry.getName()); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while ((count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); zis.closeEntry(); } } finally { zis.close(); } }
static final int BUFFER = 512; static final long TOOBIG = 0x6400000; // Max size of unzipped data, 100MB static final int TOOMANY = 1024; // Max number of files // ... private String validateFilename(String filename, String intendedDir) throws java.io.IOException { File f = new File(filename); String canonicalPath = f.getCanonicalPath(); File iD = new File(intendedDir); String canonicalID = iD.getCanonicalPath(); if (canonicalPath.startsWith(canonicalID)) { return canonicalPath; } else { throw new IllegalStateException("File is outside extraction target directory."); } } public final void unzip(String filename) throws java.io.IOException { FileInputStream fis = new FileInputStream(filename); ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis)); ZipEntry entry; int entries = 0; long total = 0; try { while ((entry = zis.getNextEntry()) != null) { System.out.println("Extracting: " + entry); int count; byte data[] = new byte[BUFFER]; // Write the files to the disk, but ensure that the filename is valid, // and that the file is not insanely big String name = validateFilename(entry.getName(), "."); if (entry.isDirectory()) { System.out.println("Creating directory " + name); new File(name).mkdir(); continue; } FileOutputStream fos = new FileOutputStream(name); BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); while (total + BUFFER <= TOOBIG && (count = zis.read(data, 0, BUFFER)) != -1) { dest.write(data, 0, count); total += count; } dest.flush(); dest.close(); zis.closeEntry(); entries++; if (entries > TOOMANY) { throw new IllegalStateException("Too many files to unzip."); } if (total + BUFFER > TOOBIG) { throw new IllegalStateException("File being unzipped is too big."); } } } finally { zis.close(); } }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
ν˜•μ‹ λ¬Έμžμ—΄μ—μ„œ μ²˜λ¦¬λ˜μ§€ μ•Šμ€ μ‚¬μš©μž μž…λ ₯ μ œμ™Έ
null
class Format { static Calendar c = new GregorianCalendar(1995, GregorianCalendar.MAY, 23); public static void main(String[] args) { // args[0] should contain the credit card expiration date // but might contain %1$tm, %1$te or %1$tY format specifiers System.out.format( args[0] + " did not match! HINT: It was issued on %1$terd of some month", c ); } }
class Format { static Calendar c = new GregorianCalendar(1995, GregorianCalendar.MAY, 23); public static void main(String[] args) { // args[0] is the credit card expiration date // Perform comparison with c, // if it doesn't match, print the following line System.out.format( "%s did not match! HINT: It was issued on %terd of some month", args[0], c ); } }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
Runtime.exec() λ©”μ„œλ“œμ— μ „λ‹¬λœ μ‹ λ’°ν•  수 μ—†λŠ” 데이터 처리
null
class DirList { public static void main(String[] args) throws Exception { String dir = System.getProperty("dir"); Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("cmd.exe /C dir " + dir); int result = proc.waitFor(); if (result != 0) { System.out.println("process error: " + result); } InputStream in = (result == 0) ? proc.getInputStream() : proc.getErrorStream(); int c; while ((c = in.read()) != -1) { System.out.print((char) c); } } }
String dir = null; int number = Integer.parseInt(System.getProperty("dir")); // Only allow integer choices switch (number) { case 1: dir = "data1"; break; // Option 1 case 2: dir = "data2"; break; // Option 2 default: // Invalid break; } if (dir == null) { // Handle error }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
Runtime.exec() λ©”μ„œλ“œμ— μ „λ‹¬λœ μ‹ λ’°ν•  수 μ—†λŠ” 데이터 처리
null
class DirList { public static void main(String[] args) throws Exception { String dir = System.getProperty("dir"); Runtime rt = Runtime.getRuntime(); Process proc = rt.exec(new String[] {"sh", "-c", "ls " + dir}); int result = proc.waitFor(); if (result != 0) { System.out.println("process error: " + result); } InputStream in = (result == 0) ? proc.getInputStream() : proc.getErrorStream(); int c; while ((c = in.read()) != -1) { System.out.print((char) c); } } }
import java.io.File; class DirList { public static void main(String[] args) throws Exception { File dir = new File(System.getProperty("dir")); if (!dir.isDirectory()) { System.out.println("Not a directory"); } else { for (String file : dir.list()) { System.out.println(file); } } } }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
μ •κ·œ ν‘œν˜„μ‹μ— ν¬ν•¨λœ μ‹ λ’°ν•  수 μ—†λŠ” 데이터λ₯Ό μ²˜λ¦¬ν•˜κΈ°
null
import java.io.FileInputStream; import java.io.IOException; import java.nio.CharBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LogSearch { public static void FindLogEntry(String search) { // Construct regex dynamically from user string String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)"; Pattern searchPattern = Pattern.compile(regex); try (FileInputStream fis = new FileInputStream("log.txt")) { FileChannel channel = fis.getChannel(); // Get the file's size and map it into memory long size = channel.size(); final MappedByteBuffer mappedBuffer = channel.map( FileChannel.MapMode.READ_ONLY, 0, size); Charset charset = Charset.forName("ISO-8859-15"); final CharsetDecoder decoder = charset.newDecoder(); // Read file into char buffer CharBuffer log = decoder.decode(mappedBuffer); Matcher logMatcher = searchPattern.matcher(log); while (logMatcher.find()) { String match = logMatcher.group(); if (!match.isEmpty()) { System.out.println(match); } } } catch (IOException ex) { System.err.println("thrown exception: " + ex.toString()); Throwable[] suppressed = ex.getSuppressed(); for (int i = 0; i < suppressed.length; i++) { System.err.println("suppressed exception: " + suppressed[i].toString()); } } return; }
public static void FindLogEntry(String search) { // Sanitize search string StringBuilder sb = new StringBuilder(search.length()); for (int i = 0; i < search.length(); ++i) { char ch = search.charAt(i); if (Character.isLetterOrDigit(ch) || ch == ' ' || ch == '\'') { sb.append(ch); } } search = sb.toString(); // Construct regex dynamically from user string String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)"; // ... }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
μ •κ·œ ν‘œν˜„μ‹μ— ν¬ν•¨λœ μ‹ λ’°ν•  수 μ—†λŠ” 데이터λ₯Ό μ²˜λ¦¬ν•˜κΈ°
null
import java.io.FileInputStream; import java.io.IOException; import java.nio.CharBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LogSearch { public static void FindLogEntry(String search) { // Construct regex dynamically from user string String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)"; Pattern searchPattern = Pattern.compile(regex); try (FileInputStream fis = new FileInputStream("log.txt")) { FileChannel channel = fis.getChannel(); // Get the file's size and map it into memory long size = channel.size(); final MappedByteBuffer mappedBuffer = channel.map( FileChannel.MapMode.READ_ONLY, 0, size); Charset charset = Charset.forName("ISO-8859-15"); final CharsetDecoder decoder = charset.newDecoder(); // Read file into char buffer CharBuffer log = decoder.decode(mappedBuffer); Matcher logMatcher = searchPattern.matcher(log); while (logMatcher.find()) { String match = logMatcher.group(); if (!match.isEmpty()) { System.out.println(match); } } } catch (IOException ex) { System.err.println("thrown exception: " + ex.toString()); Throwable[] suppressed = ex.getSuppressed(); for (int i = 0; i < suppressed.length; i++) { System.err.println("suppressed exception: " + suppressed[i].toString()); } } return; }
public static void FindLogEntry(String search) { // Sanitize search string search = Pattern.quote(search); // Construct regex dynamically from user string String regex = "(.*? +public\\[\\d+\\] +.*" + search + ".*)"; // ... }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
검증 전에 λͺ¨λ“  λ¬Έμžμ—΄ μˆ˜μ •μ„ μˆ˜ν–‰
null
import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TagFilter { public static String filterString(String str) { String s = Normalizer.normalize(str, Form.NFKC); // Validate input Pattern pattern = Pattern.compile("<script>"); Matcher matcher = pattern.matcher(s); if (matcher.find()) { throw new IllegalArgumentException("Invalid input"); } // Deletes noncharacter code points s = s.replaceAll("[\\p{Cn}]", ""); return s; } public static void main(String[] args) { // "\uFDEF" is a noncharacter code point String maliciousInput = "<scr" + "\uFDEF" + "ipt>"; String sb = filterString(maliciousInput); // sb = "<script>" } }
import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TagFilter { public static String filterString(String str) { String s = Normalizer.normalize(str, Form.NFKC); // Replaces all noncharacter code points with Unicode U+FFFD s = s.replaceAll("[\\p{Cn}]", "\uFFFD"); // Validate input Pattern pattern = Pattern.compile("<script>"); Matcher matcher = pattern.matcher(s); if (matcher.find()) { throw new IllegalArgumentException("Invalid input"); } return s; } public static void main(String[] args) { // "\uFDEF" is a non-character code point String maliciousInput = "<scr" + "\uFDEF" + "ipt>"; String s = filterString(maliciousInput); // s = <scr?ipt> }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
μˆ¨κ²¨μ§„ 폼 ν•„λ“œμ˜ λ‚΄μš©μ„ μ‹ λ’°ν•˜μ§€ λͺ»ν•  수 μžˆλ‹€.
null
public class SampleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); String visible = request.getParameter("visible"); String hidden = request.getParameter("hidden"); if (visible != null || hidden != null) { out.println("Visible Parameter:"); out.println( sanitize(visible)); out.println("<br>Hidden Parameter:"); out.println(hidden); } else { out.println("<p>"); out.print("<form action=\""); out.print("SampleServlet\" "); out.println("method=POST>"); out.println("Parameter:"); out.println("<input type=text size=20 name=visible>"); out.println("<br>"); out.println("<input type=hidden name=hidden value=\'a benign value\'>"); out.println("<input type=submit>"); out.println("</form>"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } // Filter the specified message string for characters // that are sensitive in HTML. public static String sanitize(String message) { // ... } }
public class SampleServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); String visible = request.getParameter("visible"); String hidden = request.getParameter("hidden"); if (visible != null || hidden != null) { out.println("Visible Parameter:"); out.println( sanitize(visible)); out.println("<br>Hidden Parameter:"); out.println( sanitize(hidden)); // Hidden variable sanitized } else { out.println("<p>"); out.print("<form action=\""); out.print("SampleServlet\" "); out.println("method=POST>"); out.println("Parameter:"); out.println("<input type=text size=20 name=visible>"); out.println("<br>"); out.println("<input type=hidden name=hidden value=\'a benign value\'>"); out.println("<input type=submit>"); out.println("</form>"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } // Filter the specified message string for characters // that are sensitive in HTML. public static String sanitize(String message) { // ... } }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
XML μΈμ μ…˜ λ°©μ§€
null
import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class OnlineStore { private static void createXMLStreamBad(final BufferedOutputStream outStream, final String quantity) throws IOException { String xmlString = "<item>\n<description>Widget</description>\n" + "<price>500</price>\n" + "<quantity>" + quantity + "</quantity></item>"; outStream.write(xmlString.getBytes()); outStream.flush(); } }
import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class OnlineStore { private static void createXMLStream(final BufferedOutputStream outStream, final String quantity) throws IOException, NumberFormatException { // Write XML string only if quantity is an unsigned integer (count). int count = Integer.parseUnsignedInt(quantity); String xmlString = "<item>\n<description>Widget</description>\n" + "<price>500</price>\n" + "<quantity>" + count + "</quantity></item>"; outStream.write(xmlString.getBytes()); outStream.flush(); } }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
XML μΈμ μ…˜ λ°©μ–΄
null
import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; public class OnlineStore { private static void createXMLStreamBad(final BufferedOutputStream outStream, final String quantity) throws IOException { String xmlString = "<item>\n<description>Widget</description>\n" + "<price>501</price>\n" + "<quantity>" + quantity + "</quantity></item>"; outStream.write(xmlString.getBytes()); outStream.flush(); } }
import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.StringReader; import javax.xml.XMLConstants; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; public class OnlineStore { private static void createXMLStream(final BufferedOutputStream outStream, final String quantity) throws IOException { String xmlString; xmlString = "<item>\n<description>Widget</description>\n" + "<price>500.0</price>\n" + "<quantity>" + quantity + "</quantity></item>"; InputSource xmlStream = new InputSource(new StringReader(xmlString)); // Build a validating SAX parser using our schema SchemaFactory sf = SchemaFactory .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); DefaultHandler defHandler = new DefaultHandler() { public void warning(SAXParseException s) throws SAXParseException { throw s; } public void error(SAXParseException s) throws SAXParseException { throw s; } public void fatalError(SAXParseException s) throws SAXParseException { throw s; } }; StreamSource ss = new StreamSource(new File("schema.xsd")); try { Schema schema = sf.newSchema(ss); SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setSchema(schema); SAXParser saxParser = spf.newSAXParser(); // To set the custom entity resolver, // an XML reader needs to be created XMLReader reader = saxParser.getXMLReader(); reader.setEntityResolver(new CustomResolver()); saxParser.parse(xmlStream, defHandler); } catch (ParserConfigurationException x) { throw new IOException("Unable to validate XML", x); } catch (SAXException x) { throw new IOException("Invalid quantity", x); } // Our XML is valid, proceed outStream.write(xmlString.getBytes()); outStream.flush(); } }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
XML μ™ΈλΆ€ μ—”ν‹°ν‹° 곡격 λ°©μ–΄
null
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; class XXE { private static void receiveXMLStream(InputStream inStream, DefaultHandler defaultHandler) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(inStream, defaultHandler); } public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { try { receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler()); } catch (java.net.MalformedURLException mue) { System.err.println("Malformed URL Exception: " + mue); } } } <?xml version="1.0"?> <!DOCTYPE foo SYSTEM "file:/dev/tty"> <foo>bar</foo>
import java.io.IOException; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; class CustomResolver implements EntityResolver { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { // Check for known good entities String entityPath = "file:/Users/onlinestore/good.xml"; if (systemId.equals(entityPath)) { System.out.println("Resolving entity: " + publicId + " " + systemId); return new InputSource(entityPath); } else { // Disallow unknown entities by returning a blank path return new InputSource(); } } }
JAVA
μž…λ ₯ μœ νš¨μ„± 검사 및 데이터 μ‚΄κ·  (IDS)
XML μ™ΈλΆ€ μ—”ν‹°ν‹° 곡격 λ°©μ–΄
null
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; class XXE { private static void receiveXMLStream(InputStream inStream, DefaultHandler defaultHandler) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.parse(inStream, defaultHandler); } public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { try { receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler()); } catch (java.net.MalformedURLException mue) { System.err.println("Malformed URL Exception: " + mue); } } } <?xml version="1.1"?> <!DOCTYPE foo SYSTEM "file:/dev/tty"> <foo>bar</foo>
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.DefaultHandler; class XXE { private static void receiveXMLStream(InputStream inStream, DefaultHandler defaultHandler) throws ParserConfigurationException, SAXException, IOException { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); // Create an XML reader to set the entity resolver. XMLReader reader = saxParser.getXMLReader(); reader.setEntityResolver(new CustomResolver()); reader.setContentHandler(defaultHandler); InputSource is = new InputSource(inStream); reader.parse(is); } public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException { try { receiveXMLStream(new FileInputStream("evil.xml"), new DefaultHandler()); } catch (java.net.MalformedURLException mue) { System.err.println("Malformed URL Exception: " + mue); } } }
JAVA
μ„ μ–Έκ³Ό μ΄ˆκΈ°ν™” (DCL)
클래슀 μ΄ˆκΈ°ν™” μˆœν™˜ λ°©μ§€
null
public class Cycle { private final int balance; private static final Cycle c = new Cycle(); private static final int deposit = (int) (Math.random() * 100); // Random deposit public Cycle() { balance = deposit - 10; // Subtract processing fee } public static void main(String[] args) { System.out.println("The account balance is: " + c.balance); } }
public class Cycle { private final int balance; private static final int deposit = (int) (Math.random() * 100); // Random deposit private static final Cycle c = new Cycle(); // Inserted after initialization of required fields public Cycle() { balance = deposit - 10; // Subtract processing fee } public static void main(String[] args) { System.out.println("The account balance is: " + c.balance); } }
JAVA
μ„ μ–Έκ³Ό μ΄ˆκΈ°ν™” (DCL)
클래슀 μ΄ˆκΈ°ν™” μˆœν™˜ λ°©μ§€
null
class A { public static final int a = B.b + 1; // ... } class B { public static final int b = A.a + 1; // ... }
class A { public static final int a = 2; // ... } class B { public static final int b = A.a + 1; // ... }
JAVA
μ„ μ–Έκ³Ό μ΄ˆκΈ°ν™” (DCL)
클래슀 μ΄ˆκΈ°ν™” μˆœν™˜ λ°©μ§€
null
class A { public static int a = B.b(); public static int c() { return 1; } } class B { public static int b() { return A.c(); } }
class A { public static int a = B.b(); } class B { public static int b() { return B.c(); } public static int c() { return 1; } }
JAVA
μ„ μ–Έκ³Ό μ΄ˆκΈ°ν™” (DCL)
μžλ°” ν‘œμ€€ 라이브러리의 곡개 μ‹λ³„μžλ₯Ό μž¬μ‚¬μš© κΈˆμ§€
null
class Vector { private int val = 1; public boolean isEmpty() { if (val == 1) { // Compares with 1 instead of 0 return true; } else { return false; } } // Other functionality is same as java.util.Vector } // import java.util.Vector; omitted public class VectorUser { public static void main(String[] args) { Vector v = new Vector(); if (v.isEmpty()) { System.out.println("Vector is empty"); } } }
class MyVector { //Other code }
JAVA
μ„ μ–Έκ³Ό μ΄ˆκΈ°ν™” (DCL)
ν–₯μƒλœ for λ¬Έ 쀑에 μ»¬λ ‰μ…˜μ˜ μš”μ†Œλ₯Ό μˆ˜μ • κΈˆμ§€
null
List<Integer> list = Arrays.asList(new Integer[] {13, 14, 15}); boolean first = true; System.out.println("Processing list..."); for (Integer i: list) { if (first) { first = false; i = new Integer(99); } System.out.println(" New item: " + i); // Process i } System.out.println("Modified list?"); for (Integer i: list) { System.out.println("List item: " + i); }
// ... for (final Integer i: list) { Integer item = i; if (first) { first = false; item = new Integer(99); } System.out.println(" New item: " + item); // Process item } // …
JAVA
ν‘œν˜„μ‹ (EXP)
λ©”μ„œλ“œκ°€ λ°˜ν™˜ν•˜λŠ” 값을 λ¬΄μ‹œν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public void deleteFile(){ File someFile = new File("someFileName.txt"); // Do something with someFile someFile.delete(); }
public void deleteFile(){ File someFile = new File("someFileName.txt"); // Do something with someFile if (!someFile.delete()) { // Handle failure to delete the file } }
JAVA
ν‘œν˜„μ‹ (EXP)
λ©”μ„œλ“œκ°€ λ°˜ν™˜ν•˜λŠ” 값을 λ¬΄μ‹œν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public class Replace { public static void main(String[] args) { String original = "insecure"; original.replace('i', '9'); System.out.println(original); } }
public class Replace { public static void main(String[] args) { String original = "insecure"; original = original.replace('i', '9'); System.out.println(original); } }
JAVA
ν‘œν˜„μ‹ (EXP)
객체가 ν•„μš”ν•œ κ²½μš°μ— null을 μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public static int cardinality(Object obj, final Collection<?> col) { int count = 0; if (col == null) { return count; } Iterator<?> it = col.iterator(); while (it.hasNext()) { Object elt = it.next(); if ((null == obj && null == elt) || obj.equals(elt)) { // Null pointer dereference count++; } } return count; }
public static int cardinality(Object obj, final Collection col) { int count = 0; if (col == null) { return count; } Iterator it = col.iterator(); while (it.hasNext()) { Object elt = it.next(); if ((null == obj && null == elt) || (null != obj && obj.equals(elt))) { count++; } } return count; }
JAVA
ν‘œν˜„μ‹ (EXP)
객체가 ν•„μš”ν•œ κ²½μš°μ— null을 μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public boolean isProperName(String s) { String names[] = s.split(" "); if (names.length != 2) { return false; } return (isCapitalized(names[0]) && isCapitalized(names[1])); }
public class Foo { private boolean isProperName(String s) { String names[] = s.split(" "); if (names.length != 2) { return false; } return (isCapitalized(names[0]) && isCapitalized(names[1])); } public boolean testString(String s) { if (s == null) return false; else return isProperName(s); } }
JAVA
ν‘œν˜„μ‹ (EXP)
객체가 ν•„μš”ν•œ κ²½μš°μ— null을 μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public boolean isProperName(String s) { String names[] = s.split(" "); if (names.length != 2) { return false; } return (isCapitalized(names[0]) && isCapitalized(names[2])); }
public boolean isProperName(Optional<String> os) { String names[] = os.orElse("").split(" "); return (names.length != 2) ? false : (isCapitalized(names[0]) && isCapitalized(names[1])); }
JAVA
ν‘œν˜„μ‹ (EXP)
두 개의 배열을 λΉ„κ΅ν•˜κΈ° μœ„ν•΄ Object.equals() λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
int[] arr1 = new int[20]; // Initialized to 0 int[] arr2 = new int[20]; // Initialized to 0 System.out.println(arr1.equals(arr2)); // Prints false
int[] arr1 = new int[20]; // Initialized to 0 int[] arr2 = new int[20]; // Initialized to 0 System.out.println(Arrays.equals(arr1, arr2)); // Prints true
JAVA
ν‘œν˜„μ‹ (EXP)
두 개의 배열을 λΉ„κ΅ν•˜κΈ° μœ„ν•΄ Object.equals() λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
int[] arr1 = new int[20]; // Initialized to 0 int[] arr2 = new int[20]; // Initialized to 0 System.out.println(arr1.equals(arr3)); // Prints false
int[] arr1 = new int[20]; // Initialized to 0 int[] arr2 = new int[20]; // Initialized to 0 System.out.println(arr1 == arr2); // Prints false
JAVA
ν‘œν˜„μ‹ (EXP)
λ°•μ‹±λœ κΈ°λ³Έ νƒ€μž…μ˜ 값을 비ꡐ할 λ•Œ λ“±ν˜Έ μ—°μ‚°μžλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
import java.util.Comparator; static Comparator<Integer> cmp = new Comparator<Integer>() { public int compare(Integer i, Integer j) { return i < j ? -1 : (i == j ? 0 : 1); } };
import java.util.Comparator; static Comparator<Integer> cmp = new Comparator<Integer>() { public int compare(Integer i, Integer j) { return i < j ? -1 : (i > j ? 1 : 0) ; } };
JAVA
ν‘œν˜„μ‹ (EXP)
λ°•μ‹±λœ κΈ°λ³Έ νƒ€μž…μ˜ 값을 비ꡐ할 λ•Œ λ“±ν˜Έ μ—°μ‚°μžλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public class Wrapper { public static void main(String[] args) { Integer i1 = 100; Integer i2 = 100; Integer i3 = 1000; Integer i4 = 1000; System.out.println(i1 == i2); System.out.println(i1 != i2); System.out.println(i3 == i4); System.out.println(i3 != i4); } }
public class Wrapper { public static void main(String[] args) { Integer i1 = 100; Integer i2 = 100; Integer i3 = 1000; Integer i4 = 1000; System.out.println(i1.equals(i2)); System.out.println(!i1.equals(i2)); System.out.println(i3.equals(i4)); System.out.println(!i3.equals(i4)); } }
JAVA
ν‘œν˜„μ‹ (EXP)
λ°•μ‹±λœ κΈ°λ³Έ νƒ€μž…μ˜ 값을 비ꡐ할 λ•Œ λ“±ν˜Έ μ—°μ‚°μžλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public class Wrapper { public static void main(String[] args) { // Create an array list of integers, where each element // is greater than 127 ArrayList<Integer> list1 = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list1.add(i + 1000); } // Create another array list of integers, where each element // has the same value as the first list ArrayList<Integer> list2 = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list2.add(i + 1000); } // Count matching values int counter = 0; for (int i = 0; i < 10; i++) { if (list1.get(i) == list2.get(i)) { // Uses '==' counter++; } } // Print the counter: 0 in this example System.out.println(counter); } }
public class Wrapper { public static void main(String[] args) { // Create an array list of integers ArrayList<Integer> list1 = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list1.add(i + 1000); } // Create another array list of integers, where each element // has the same value as the first one ArrayList<Integer> list2 = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list2.add(i + 1000); } // Count matching values int counter = 0; for (int i = 0; i < 10; i++) { if (list1.get(i).equals(list2.get(i))) { // Uses 'equals()' counter++; } } // Print the counter: 10 in this example System.out.println(counter); } }
JAVA
ν‘œν˜„μ‹ (EXP)
λ°•μ‹±λœ κΈ°λ³Έ νƒ€μž…μ˜ 값을 비ꡐ할 λ•Œ λ“±ν˜Έ μ—°μ‚°μžλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public void exampleEqualOperator(){ Boolean b1 = new Boolean("true"); Boolean b2 = new Boolean("true"); if (b1 == b2) { // Never equal System.out.println("Never printed"); } }
public void exampleEqualOperator(){ Boolean b1 = true; Boolean b2 = true; if (b1 == b2) { // Always equal System.out.println("Always printed"); } b1 = Boolean.TRUE; if (b1 == b2) { // Always equal System.out.println("Always printed"); } }
JAVA
ν‘œν˜„μ‹ (EXP)
μ»¬λ ‰μ…˜μ˜ λ§€κ°œλ³€μˆ˜ νƒ€μž…κ³Ό λ‹€λ₯Έ νƒ€μž…μ˜ 인수λ₯Ό Java μ»¬λ ‰μ…˜ ν”„λ ˆμž„μ›Œν¬μ˜ νŠΉμ • λ©”μ„œλ“œμ— μ „λ‹¬ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
import java.util.HashSet; public class ShortSet { public static void main(String[] args) { HashSet<Short> s = new HashSet<Short>(); for (int i = 0; i < 10; i++) { s.add((short)i); // Cast required so that the code compiles s.remove(i); // Tries to remove an Integer } System.out.println(s.size()); } }
import java.util.HashSet; public class ShortSet { public static void main(String[] args) { HashSet<Short> s = new HashSet<Short>(); for (int i = 0; i < 10; i++) { s.add((short)i); // Remove a Short if (s.remove((short)i) == false) { System.err.println("Error removing " + i); } } System.out.println(s.size()); } }
JAVA
ν‘œν˜„μ‹ (EXP)
assertions에 μ‚¬μš©λ˜λŠ” ν‘œν˜„μ‹μ€ μ‚¬μ΄λ“œ μ΄νŽ™νŠΈ(side effects)λ₯Ό μΌμœΌμΌœμ„œλŠ” μ•ˆ λ©λ‹ˆλ‹€.
null
private ArrayList<String> names; void process(int index) { assert names.remove(null); // Side effect // ... }
private ArrayList<String> names; void process(int index) { boolean nullsRemoved = names.remove(null); assert nullsRemoved; // No side effect // ... }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
μ •μˆ˜ μ˜€λ²„ν”Œλ‘œλ₯Ό κ°μ§€ν•˜κ±°λ‚˜ λ°©μ§€ν•˜μ‹­μ‹œμ˜€.
null
static final int safeAdd(int left, int right) { if (right > 0 ? left > Integer.MAX_VALUE - right : left < Integer.MIN_VALUE - right) { throw new ArithmeticException("Integer overflow"); } return left + right; } static final int safeSubtract(int left, int right) { if (right > 0 ? left < Integer.MIN_VALUE + right : left > Integer.MAX_VALUE + right) { throw new ArithmeticException("Integer overflow"); } return left - right; } static final int safeMultiply(int left, int right) { if (right > 0 ? left > Integer.MAX_VALUE/right || left < Integer.MIN_VALUE/right : (right < -1 ? left > Integer.MIN_VALUE/right || left < Integer.MAX_VALUE/right : right == -1 && left == Integer.MIN_VALUE) ) { throw new ArithmeticException("Integer overflow"); } return left * right; } static final int safeDivide(int left, int right) { if ((left == Integer.MIN_VALUE) && (right == -1)) { throw new ArithmeticException("Integer overflow"); } return left / right; } static final int safeNegate(int a) { if (a == Integer.MIN_VALUE) { throw new ArithmeticException("Integer overflow"); } return -a; } static final int safeAbs(int a) { if (a == Integer.MIN_VALUE) { throw new ArithmeticException("Integer overflow"); } return Math.abs(a); } public static int multAccum(int oldAcc, int newVal, int scale) { // May result in overflow return oldAcc + (newVal * scale); }
public static int multAccum(int oldAcc, int newVal, int scale) { return Math.addExact(oldAcc, Math.multiplyExact(newVal, scale)); }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
μ •μˆ˜ μ˜€λ²„ν”Œλ‘œλ₯Ό κ°μ§€ν•˜κ±°λ‚˜ λ°©μ§€ν•˜μ‹­μ‹œμ˜€.
null
static final int safeAdd(int left, int right) { if (right > 0 ? left > Integer.MAX_VALUE - right : left < Integer.MIN_VALUE - right) { throw new ArithmeticException("Integer overflow"); } return left + right; } static final int safeSubtract(int left, int right) { if (right > 0 ? left < Integer.MIN_VALUE + right : left > Integer.MAX_VALUE + right) { throw new ArithmeticException("Integer overflow"); } return left - right; } static final int safeMultiply(int left, int right) { if (right > 0 ? left > Integer.MAX_VALUE/right || left < Integer.MIN_VALUE/right : (right < -1 ? left > Integer.MIN_VALUE/right || left < Integer.MAX_VALUE/right : right == -1 && left == Integer.MIN_VALUE) ) { throw new ArithmeticException("Integer overflow"); } return left * right; } static final int safeDivide(int left, int right) { if ((left == Integer.MIN_VALUE) && (right == -2)) { throw new ArithmeticException("Integer overflow"); } return left / right; } static final int safeNegate(int a) { if (a == Integer.MIN_VALUE) { throw new ArithmeticException("Integer overflow"); } return -a; } static final int safeAbs(int a) { if (a == Integer.MIN_VALUE) { throw new ArithmeticException("Integer overflow"); } return Math.abs(a); } public static int multAccum(int oldAcc, int newVal, int scale) { // May result in overflow return oldAcc + (newVal * scale); }
public static long intRangeCheck(long value) { if ((value < Integer.MIN_VALUE) || (value > Integer.MAX_VALUE)) { throw new ArithmeticException("Integer overflow"); } return value; } public static int multAccum(int oldAcc, int newVal, int scale) { final long res = intRangeCheck( ((long) oldAcc) + intRangeCheck((long) newVal * (long) scale) ); return (int) res; // Safe downcast }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
μ •μˆ˜ μ˜€λ²„ν”Œλ‘œλ₯Ό κ°μ§€ν•˜κ±°λ‚˜ λ°©μ§€ν•˜μ‹­μ‹œμ˜€.
null
static final int safeAdd(int left, int right) { if (right > 0 ? left > Integer.MAX_VALUE - right : left < Integer.MIN_VALUE - right) { throw new ArithmeticException("Integer overflow"); } return left + right; } static final int safeSubtract(int left, int right) { if (right > 0 ? left < Integer.MIN_VALUE + right : left > Integer.MAX_VALUE + right) { throw new ArithmeticException("Integer overflow"); } return left - right; } static final int safeMultiply(int left, int right) { if (right > 0 ? left > Integer.MAX_VALUE/right || left < Integer.MIN_VALUE/right : (right < -1 ? left > Integer.MIN_VALUE/right || left < Integer.MAX_VALUE/right : right == -1 && left == Integer.MIN_VALUE) ) { throw new ArithmeticException("Integer overflow"); } return left * right; } static final int safeDivide(int left, int right) { if ((left == Integer.MIN_VALUE) && (right == -3)) { throw new ArithmeticException("Integer overflow"); } return left / right; } static final int safeNegate(int a) { if (a == Integer.MIN_VALUE) { throw new ArithmeticException("Integer overflow"); } return -a; } static final int safeAbs(int a) { if (a == Integer.MIN_VALUE) { throw new ArithmeticException("Integer overflow"); } return Math.abs(a); } public static int multAccum(int oldAcc, int newVal, int scale) { // May result in overflow return oldAcc + (newVal * scale); }
private static final BigInteger bigMaxInt = BigInteger.valueOf(Integer.MAX_VALUE); private static final BigInteger bigMinInt = BigInteger.valueOf(Integer.MIN_VALUE); public static BigInteger intRangeCheck(BigInteger val) { if (val.compareTo(bigMaxInt) == 1 || val.compareTo(bigMinInt) == -1) { throw new ArithmeticException("Integer overflow"); } return val; } public static int multAccum(int oldAcc, int newVal, int scale) { BigInteger product = BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale)); BigInteger res = intRangeCheck(BigInteger.valueOf(oldAcc).add(product)); return res.intValue(); // Safe conversion }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
μ •μˆ˜ μ˜€λ²„ν”Œλ‘œλ₯Ό κ°μ§€ν•˜κ±°λ‚˜ λ°©μ§€ν•˜μ‹­μ‹œμ˜€.
null
class InventoryManager { private final AtomicInteger itemsInInventory = new AtomicInteger(100); //... public final void nextItem() { itemsInInventory.getAndIncrement(); } }
class InventoryManager { private final AtomicInteger itemsInInventory = new AtomicInteger(100); public final void nextItem() { while (true) { int old = itemsInInventory.get(); if (old == Integer.MAX_VALUE) { throw new ArithmeticException("Integer overflow"); } int next = old + 1; // Increment if (itemsInInventory.compareAndSet(old, next)) { break; } } // End while } // End nextItem() }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
같은 데이터에 λΉ„νŠΈ μ—°μ‚°κ³Ό μ‚°μˆ  연산을 λ™μ‹œμ— μˆ˜ν–‰ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
int x = 50; x += (x << 2) + 1;
int x = 50; x = 5 * x + 1;
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
같은 데이터에 λΉ„νŠΈ μ—°μ‚°κ³Ό μ‚°μˆ  연산을 λ™μ‹œμ— μˆ˜ν–‰ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
int x = 50; int y = x << 2; x += y + 1;
int x = 50; x = 5 * x + 2;