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
Methods (MET), λ©”μ„œλ“œ
compareTo() λ©”μ„œλ“œλ₯Ό κ΅¬ν˜„ν•  λ•Œ 일반 계약을 μ€€μˆ˜ν•˜μ‹­μ‹œμ˜€.
CWE-573
class GameEntry implements Comparable { public enum Roshambo {ROCK, PAPER, SCISSORS} private Roshambo value; public GameEntry(Roshambo value) { this.value = value; } public int compareTo(Object that) { if (!(that instanceof GameEntry)) { throw new ClassCastException(); } ...
class GameEntry { public enum Roshambo {ROCK, PAPER, SCISSORS} private Roshambo value; public GameEntry(Roshambo value) { this.value = value; } public int beats(Object that) { if (!(that instanceof GameEntry)) { throw new ClassCastException(); } GameEntry t = (GameEntry) ...
JAVA
Methods (MET), λ©”μ„œλ“œ
비ꡐ 연산에 μ‚¬μš©λ˜λŠ” ν‚€κ°€ λΆˆλ³€μž„μ„ 보μž₯ν•˜μ‹­μ‹œμ˜€.
null
// Mutable class Employee class Employee { private String name; private double salary; Employee(String empName, double empSalary) { this.name = empName; this.salary = empSalary; } public void setEmployeeName(String empName) { this.name = empName; } public void setSalary(dou...
// Mutable class Employee class Employee { private String name; private double salary; private final long employeeID; // Unique for each Employee Employee(String name, double salary, long empID) { this.name = name; this.salary = salary; this.employeeID = empID; } // ... @O...
JAVA
Methods (MET), λ©”μ„œλ“œ
비ꡐ 연산에 μ‚¬μš©λ˜λŠ” ν‚€κ°€ λΆˆλ³€μž„μ„ 보μž₯ν•˜μ‹­μ‹œμ˜€.
null
class MyKey implements Serializable { // Does not override hashCode() } class HashSer { public static void main(String[] args) throws IOException, ClassNotFoundException { Hashtable<MyKey,String> ht = new Hashtable<MyKey, String>(); MyKey key = new MyKey(); ht.put(key, "V...
class HashSer { public static void main(String[] args) throws IOException, ClassNotFoundException { Hashtable<Integer, String> ht = new Hashtable<Integer, String>(); ht.put(new Integer(1), "Value"); System.out.println("Entry: " + ht.get(1)); // Retrieve using the key // S...
JAVA
Methods (MET), λ©”μ„œλ“œ
finalizerλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-586, CWE-583, CWE-568
class MyFrame extends JFrame { private byte[] buffer = new byte[16 * 1024 * 1024]; // Persists for at least two GC cycles }
class MyFrame { private JFrame frame; private byte[] buffer = new byte[16 * 1024 * 1024]; // Now decoupled }
JAVA
Methods (MET), λ©”μ„œλ“œ
finalizerλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-586, CWE-583, CWE-568
class BaseClass { protected void finalize() throws Throwable { System.out.println("Superclass finalize!"); doLogic(); } public void doLogic() throws Throwable { System.out.println("This is super-class!"); } } class SubClass extends BaseClass { private Date d; // Mutable instance fi...
protected void finalize() throws Throwable { try { //... } finally { super.finalize(); } }
JAVA
Methods (MET), λ©”μ„œλ“œ
finalizerλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-586, CWE-583, CWE-568
class BaseClass { protected void finalize() throws Throwable { System.out.println("Superclass finalize!"); doLogic(); } public void doLogic() throws Throwable { System.out.println("This is super-class!"); } } class SubClass extends BaseClass { private Date d; // Mutable instance fi...
public class Foo { // The finalizeGuardian object finalizes the outer Foo object private final Object finalizerGuardian = new Object() { protected void finalize() throws Throwable { // Finalize outer Foo object } }; //... }
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
ν™•μΈλœ μ˜ˆμ™Έλ₯Ό μ–΅μ œν•˜κ±°λ‚˜ λ¬΄μ‹œν•˜μ§€ λ§ˆμ„Έμš”.
CWE-390, 쑰치 없이 였λ₯˜ μƒνƒœ 감지
try { //... } catch (IOException ioe) { ioe.printStackTrace(); }
boolean validFlag = false; do { try { // ... // If requested file does not exist, throws FileNotFoundException // If requested file exists, sets validFlag to true validFlag = true; } catch (FileNotFoundException e) { // Ask the user for a different file name } } while (validFlag != true); // U...
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
ν™•μΈλœ μ˜ˆμ™Έλ₯Ό μ–΅μ œν•˜κ±°λ‚˜ λ¬΄μ‹œν•˜μ§€ λ§ˆμ„Έμš”.
CWE-390, 쑰치 없이 였λ₯˜ μƒνƒœ 감지
class Foo implements Runnable { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } }
class Foo implements Runnable { public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // Reset interrupted status } } }
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
μ˜ˆμ™Έλ‘œ 인해 λ―Όκ°ν•œ 정보가 λ…ΈμΆœλ˜λŠ” 것을 ν—ˆμš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-209 , 였λ₯˜ λ©”μ‹œμ§€λ₯Ό ν†΅ν•œ 정보 λ…ΈμΆœ CWE-497 , ν—ˆκ°€λ˜μ§€ μ•Šμ€ μ œμ–΄ μ˜μ—­μ— λŒ€ν•œ μ‹œμŠ€ν…œ 데이터 λ…ΈμΆœ CWE-600 , μ„œλΈ”λ¦Ώμ—μ„œ λ°œμƒν•˜μ§€ μ•Šμ€ μ˜ˆμ™Έ
class ExceptionExample { public static void main(String[] args) throws FileNotFoundException { // Linux stores a user's home directory path in // the environment variable $HOME, Windows in %APPDATA% FileInputStream fis = new FileInputStream(System.getenv("APPDATA") + args[0]); } }
class ExceptionExample { public static void main(String[] args) { File file = null; try { file = new File(System.getenv("APPDATA") + args[0]).getCanonicalFile(); if (!file.getPath().startsWith("c:\\homepath")) { System.out.println("Invalid file"); return; } ...
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
μ˜ˆμ™Έλ‘œ 인해 λ―Όκ°ν•œ 정보가 λ…ΈμΆœλ˜λŠ” 것을 ν—ˆμš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-209 , 였λ₯˜ λ©”μ‹œμ§€λ₯Ό ν†΅ν•œ 정보 λ…ΈμΆœ CWE-497 , ν—ˆκ°€λ˜μ§€ μ•Šμ€ μ œμ–΄ μ˜μ—­μ— λŒ€ν•œ μ‹œμŠ€ν…œ 데이터 λ…ΈμΆœ CWE-601 , μ„œλΈ”λ¦Ώμ—μ„œ λ°œμƒν•˜μ§€ μ•Šμ€ μ˜ˆμ™Έ
try { FileInputStream fis = new FileInputStream(System.getenv("APPDATA") + args[0]); } catch (FileNotFoundException e) { // Log the exception throw new IOException("Unable to retrieve file", e); }
class ExceptionExample { public static void main(String[] args) { FileInputStream fis = null; try { switch(Integer.valueOf(args[0])) { case 1: fis = new FileInputStream("c:\\homepath\\file1"); break; case 2: fis = new FileInputStream("c:\\homepath\\file2"); ...
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
데이터λ₯Ό λ‘œκΉ…ν•  λ•Œ μ˜ˆμ™Έκ°€ λ°œμƒν•˜μ§€ μ•Šλ„λ‘ λ°©μ§€ν•˜μ‹­μ‹œμ˜€.
null
try { // ... } catch (SecurityException se) { System.err.println(se); // Recover from exception }
try { // ... } catch(SecurityException se) { logger.log(Level.SEVERE, se); // Recover from exception }
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
λ©”μ„œλ“œ μ‹€νŒ¨ μ‹œ 이전 객체 μƒνƒœ 볡원
CWE-460, λ˜μ Έμ§„ μ˜ˆμ™Έμ— λŒ€ν•œ λΆ€μ μ ˆν•œ 정리
class Dimensions { private int length; private int width; private int height; static public final int PADDING = 2; static public final int MAX_DIMENSION = 10; public Dimensions(int length, int width, int height) { this.length = length; this.width = width; this.height = height; } protecte...
protected int getVolumePackage(int weight) { length += PADDING; width += PADDING; height += PADDING; try { if (length <= PADDING || width <= PADDING || height <= PADDING || length > MAX_DIMENSION + PADDING || width > MAX_DIMENSION + PADDING || height > MAX_DIMENSION + PADDING || wei...
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
finally λΈ”λ‘μ—μ„œ κ°‘μž‘μŠ€λŸ½κ²Œ μ’…λ£Œν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-459, λΆˆμ™„μ „ν•œ 정리 CWE-584, finally 블둝 λ‚΄μ—μ„œ λ°˜ν™˜
class TryFinally { private static boolean doLogic() { try { throw new IllegalStateException(); } finally { System.out.println("logic done"); return true; } } }
class TryFinally { private static boolean doLogic() { try { throw new IllegalStateException(); } finally { System.out.println("logic done"); } // Any return statements must go here; // applicable only when exception is thrown conditionally } }
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
finally λΈ”λ‘μ—μ„œ κ²€μ‚¬λœ μ˜ˆμ™Έκ°€ νƒˆμΆœν•˜μ§€ μ•Šλ„λ‘ ν•˜μ‹­μ‹œμ˜€.
CWE-248, ν¬μ°©λ˜μ§€ μ•Šμ€ μ˜ˆμ™Έ CWE-460, μ˜ˆμ™Έ λ°œμƒ μ‹œ λΆ€μ μ ˆν•œ 정리 CWE-584, finally 블둝 λ‚΄μ—μ„œ λ°˜ν™˜ CWE-705, μ œμ–΄ 흐름 λ²”μœ„ μ„€μ •μ˜ 였λ₯˜ CWE-754, λΉ„μ •μƒμ μ΄κ±°λ‚˜ μ˜ˆμ™Έμ μΈ 쑰건에 λŒ€ν•œ λΆ€μ μ ˆν•œ 검사
public class Operation { public static void doOperation(String some_file) { // ... Code to check or set character encoding ... try { BufferedReader reader = new BufferedReader(new FileReader(some_file)); try { // Do operations } finally { reader.close(); // ...
public class Operation { public static void doOperation(String some_file) { // ... Code to check or set character encoding ... try { BufferedReader reader = new BufferedReader(new FileReader(some_file)); try { // Do operations } finally { try { reader.clos...
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
μ„ μ–Έλ˜μ§€ μ•Šμ€ κ²€μ‚¬λœ μ˜ˆμ™Έλ₯Ό λ˜μ§€μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-703, λΉ„μ •μƒμ μ΄κ±°λ‚˜ μ˜ˆμ™Έμ μΈ 쑰건에 λŒ€ν•œ λΆ€μ μ ˆν•œ 검사 λ˜λŠ” 처리 CWE-248, ν¬μ°©λ˜μ§€ μ•Šμ€ μ˜ˆμ™Έ
public class NewInstance { private static Throwable throwable; private NewInstance() throws Throwable { throw throwable; } public static synchronized void undeclaredThrow(Throwable throwable) { // These exceptions should not be passed if (throwable instanceof IllegalAccessException || th...
public static synchronized void undeclaredThrow(Throwable throwable) { // These exceptions should not be passed if (throwable instanceof IllegalAccessException || throwable instanceof InstantiationException) { // Unchecked, no declaration required throw new IllegalArgumentException(); } NewInsta...
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
RuntimeException, Exception, λ˜λŠ” Throwable을 λ˜μ§€μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-397, 일반 μ˜ˆμ™Έμ— λŒ€ν•œ throws μ„ μ–Έ
boolean isCapitalized(String s) { if (s == null) { throw new RuntimeException("Null String"); } if (s.equals("")) { return true; } String first = s.substring(0, 1); String rest = s.substring(1); return (first.equals(first.toUpperCase()) && rest.equals(rest.toLowerCase())); }
boolean isCapitalized(String s) { if (s == null) { throw new NullPointerException(); } if (s.equals("")) { return true; } String first = s.substring(0, 1); String rest = s.substring(1); return (first.equals(first.toUpperCase()) && rest.equals(rest.toLowerCase())); }
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
RuntimeException, Exception, λ˜λŠ” Throwable을 λ˜μ§€μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-398, 일반 μ˜ˆμ™Έμ— λŒ€ν•œ throws μ„ μ–Έ
private void doSomething() throws Exception { //... }
private void doSomething() throws IOException { //... }
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
NullPointerException λ˜λŠ” κ·Έ μƒμœ„ μ˜ˆμ™Έλ₯Ό μž‘μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
boolean isName(String s) { try { String names[] = s.split(" "); if (names.length != 2) { return false; } return (isCapitalized(names[0]) && isCapitalized(names[1])); } catch (NullPointerException e) { return false; } }
boolean isName(String s) { if (s == null) { return false; } String names[] = s.split(" "); if (names.length != 2) { return false; } return (isCapitalized(names[0]) && isCapitalized(names[1])); }
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
NullPointerException λ˜λŠ” κ·Έ μƒμœ„ μ˜ˆμ™Έλ₯Ό μž‘μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
boolean isName(String s) { try { String names[] = s.split(" "); if (names.length != 2) { return false; } return (isCapitalized(names[0]) && isCapitalized(names[2])); } catch (NullPointerException e) { return false; } }
boolean isName(String s) /* Throws NullPointerException */ { String names[] = s.split(" "); if (names.length != 2) { return false; } return (isCapitalized(names[0]) && isCapitalized(names[1])); }
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
NullPointerException λ˜λŠ” κ·Έ μƒμœ„ μ˜ˆμ™Έλ₯Ό μž‘μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public interface Log { void write(String messageToLog); } public class FileLog implements Log { private final FileWriter out; FileLog(String logFileName) throws IOException { out = new FileWriter(logFileName, true); } public void write(String messageToLog) { // Write message to file } } publ...
public interface Log { public static final Log NULL = new Log() { public void write(String messageToLog) { // Do nothing } }; void write(String messageToLog); } class Service { private final Log log; Service(){ this.log = Log.NULL; } // ... }
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
NullPointerException λ˜λŠ” κ·Έ μƒμœ„ μ˜ˆμ™Έλ₯Ό μž‘μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public class DivideException { public static void division(int totalSum, int totalNumber) throws ArithmeticException, IOException { int average = totalSum / totalNumber; // Additional operations that may throw IOException... System.out.println("Average: " + average); } public static void main(St...
import java.io.IOException; public class DivideException { public static void main(String[] args) { try { division(200, 5); division(200, 0); // Divide by zero } catch (ArithmeticException ae) { // DivideByZeroException extends Exception so is checked throw new DivideByZeroException(...
JAVA
μ˜ˆμ™Έμ μΈ λ™μž‘ (ERR)
μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œκ°€ JVM을 μ’…λ£Œν•˜λ„λ‘ ν—ˆμš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-382, J2EE Bad Practices: Use of System.exit()
public class InterceptExit { public static void main(String[] args) { // ... System.exit(1); // Abrupt exit System.out.println("This never executes"); } }
class PasswordSecurityManager extends SecurityManager { private boolean isExitAllowedFlag; public PasswordSecurityManager(){ super(); isExitAllowedFlag = false; } public boolean isExitAllowed(){ return isExitAllowedFlag; } @Override public void checkExit(int status) { if (!is...
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
곡유된 μ›μ‹œ λ³€μˆ˜μ— μ ‘κ·Όν•  λ•Œ κ°€μ‹œμ„±μ„ 보μž₯ν•˜μ‹­μ‹œμ˜€.
CWE-413, λΆ€μ μ ˆν•œ μžμ› 잠금 CWE-567, 닀쀑 μŠ€λ ˆλ“œ ν™˜κ²½μ—μ„œ 곡유 데이터에 λŒ€ν•œ λΉ„λ™κΈ°ν™”λœ μ ‘κ·Ό CWE-667, λΆ€μ μ ˆν•œ 잠금
final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset int...
final class ControlledStop implements Runnable { private volatile boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // ...
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
곡유된 μ›μ‹œ λ³€μˆ˜μ— μ ‘κ·Όν•  λ•Œ κ°€μ‹œμ„±μ„ 보μž₯ν•˜μ‹­μ‹œμ˜€.
CWE-413, λΆ€μ μ ˆν•œ μžμ› 잠금 CWE-567, 닀쀑 μŠ€λ ˆλ“œ ν™˜κ²½μ—μ„œ 곡유 데이터에 λŒ€ν•œ λΉ„λ™κΈ°ν™”λœ μ ‘κ·Ό CWE-667, λΆ€μ μ ˆν•œ 잠금
final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1001); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset int...
final class ControlledStop implements Runnable { private final AtomicBoolean done = new AtomicBoolean(false); @Override public void run() { while (!done.get()) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.curr...
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
곡유된 μ›μ‹œ λ³€μˆ˜μ— μ ‘κ·Όν•  λ•Œ κ°€μ‹œμ„±μ„ 보μž₯ν•˜μ‹­μ‹œμ˜€.
CWE-413, λΆ€μ μ ˆν•œ μžμ› 잠금 CWE-567, 닀쀑 μŠ€λ ˆλ“œ ν™˜κ²½μ—μ„œ 곡유 데이터에 λŒ€ν•œ λΉ„λ™κΈ°ν™”λœ μ ‘κ·Ό CWE-667, λΆ€μ μ ˆν•œ 잠금
final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1002); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset int...
final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!isDone()) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset...
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
λΆˆλ³€ 객체에 λŒ€ν•œ 곡유 참쑰의 κ°€μ‹œμ„±μ„ 보μž₯ν•˜μ‹­μ‹œμ˜€.
null
// Immutable Helper public final class Helper { private final int n; public Helper(int n) { this.n = n; } // ... } final class Foo { private Helper helper; public Helper getHelper() { return helper; } public void setHelper(int num) { helper = new Helper(num); } }
final class Foo { private Helper helper; public synchronized Helper getHelper() { return helper; } public synchronized void setHelper(int num) { helper = new Helper(num); } }
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
λΆˆλ³€ 객체에 λŒ€ν•œ 곡유 참쑰의 κ°€μ‹œμ„±μ„ 보μž₯ν•˜μ‹­μ‹œμ˜€.
null
// Immutable Helper public final class Helper { private final int n; public Helper(int n) { this.n = n; } // ... } final class Foo { private Helper helper; public Helper getHelper() { return helper; } public void setHelper(int num) { helper = new Helper(num); } }
final class Foo { private volatile Helper helper; public Helper getHelper() { return helper; } public void setHelper(int num) { helper = new Helper(num); } }
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
λΆˆλ³€ 객체에 λŒ€ν•œ 곡유 참쑰의 κ°€μ‹œμ„±μ„ 보μž₯ν•˜μ‹­μ‹œμ˜€.
null
// Immutable Helper public final class Helper { private final int n; public Helper(int n) { this.n = n; } // ... } final class Foo { private Helper helper; public Helper getHelper() { return helper; } public void setHelper(int num) { helper = new Helper(num); } }
final class Foo { private final AtomicReference<Helper> helperRef = new AtomicReference<Helper>(); public Helper getHelper() { return helperRef.get(); } public void setHelper(int num) { helperRef.set(new Helper(num)); } }
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
곡유 λ³€μˆ˜μ— λŒ€ν•œ 볡합 연산이 μ›μžμ μœΌλ‘œ μˆ˜ν–‰λ˜λ„λ‘ 보μž₯ν•˜μ‹­μ‹œμ˜€.
CWE-366, μŠ€λ ˆλ“œ λ‚΄μ—μ„œμ˜ 경쟁 쑰건 CWE-413, λΆ€μ μ ˆν•œ μžμ› 잠금 CWE-567, 닀쀑 μŠ€λ ˆλ“œ ν™˜κ²½μ—μ„œ 곡유 데이터에 λŒ€ν•œ λΉ„λ™κΈ°ν™”λœ μ ‘κ·Ό CWE-667, λΆ€μ μ ˆν•œ 잠금
final class Flag { private boolean flag = true; public void toggle() { // Unsafe flag = !flag; } public boolean getFlag() { // Unsafe return flag; } }
final class Flag { private boolean flag = true; public synchronized void toggle() { flag = !flag; } public synchronized boolean getFlag() { return flag; } }
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
곡유 λ³€μˆ˜μ— λŒ€ν•œ 볡합 연산이 μ›μžμ μœΌλ‘œ μˆ˜ν–‰λ˜λ„λ‘ 보μž₯ν•˜μ‹­μ‹œμ˜€.
CWE-366, μŠ€λ ˆλ“œ λ‚΄μ—μ„œμ˜ 경쟁 쑰건 CWE-413, λΆ€μ μ ˆν•œ μžμ› 잠금 CWE-567, 닀쀑 μŠ€λ ˆλ“œ ν™˜κ²½μ—μ„œ 곡유 데이터에 λŒ€ν•œ λΉ„λ™κΈ°ν™”λœ μ ‘κ·Ό CWE-667, λΆ€μ μ ˆν•œ 잠금
final class Flag { private boolean flag = true; public void toggle() { // μ•ˆμ „ν•˜μ§€ μ•ŠμŒ flag ^= true; // flag = !flag;와 동일 } public boolean getFlag() { // μ•ˆμ „ν•˜μ§€ μ•ŠμŒ return flag; } }
final class Flag { private boolean flag = true; public synchronized void toggle() { flag ^= true; // flag = !flag;와 동일 } public synchronized boolean getFlag() { return flag; } }
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
곡유 λ³€μˆ˜μ— λŒ€ν•œ 볡합 연산이 μ›μžμ μœΌλ‘œ μˆ˜ν–‰λ˜λ„λ‘ 보μž₯ν•˜μ‹­μ‹œμ˜€.
CWE-366, μŠ€λ ˆλ“œ λ‚΄μ—μ„œμ˜ 경쟁 쑰건 CWE-413, λΆ€μ μ ˆν•œ μžμ› 잠금 CWE-567, 닀쀑 μŠ€λ ˆλ“œ ν™˜κ²½μ—μ„œ 곡유 데이터에 λŒ€ν•œ λΉ„λ™κΈ°ν™”λœ μ ‘κ·Ό CWE-667, λΆ€μ μ ˆν•œ 잠금
final class Flag { private volatile boolean flag = true; public void toggle() { // μ•ˆμ „ν•˜μ§€ μ•ŠμŒ flag ^= true; } public boolean getFlag() { // μ•ˆμ „ν•¨ return flag; } }
final class Flag { private volatile boolean flag = true; public synchronized void toggle() { flag ^= true; } public boolean getFlag() { return flag; } }
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
λ…λ¦½μ μœΌλ‘œ μ›μžμ μΈ λ©”μ„œλ“œμ— λŒ€ν•œ 호좜 그룹이 μ›μžμ μ΄λΌκ³  κ°€μ •ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-362, μ μ ˆν•˜μ§€ μ•Šμ€ λ™κΈ°ν™”λ‘œ 곡유 μžμ›μ„ μ‚¬μš©ν•˜λŠ” λ™μ‹œ μ‹€ν–‰ ("경쟁 쑰건") CWE-366, μŠ€λ ˆλ“œ λ‚΄μ—μ„œμ˜ 경쟁 쑰건 CWE-662, λΆ€μ μ ˆν•œ 동기화
final class Adder { private final AtomicReference<BigInteger> first; private final AtomicReference<BigInteger> second; public Adder(BigInteger f, BigInteger s) { first = new AtomicReference<BigInteger>(f); second = new AtomicReference<BigInteger>(s); } public void update(BigInteger f, BigInteger ...
final class Adder { // ... private final AtomicReference<BigInteger> first; private final AtomicReference<BigInteger> second; public Adder(BigInteger f, BigInteger s) { first = new AtomicReference<BigInteger>(f); second = new AtomicReference<BigInteger>(s); } public synchronized void update...
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
λ…λ¦½μ μœΌλ‘œ μ›μžμ μΈ λ©”μ„œλ“œμ— λŒ€ν•œ 호좜 그룹이 μ›μžμ μ΄λΌκ³  κ°€μ •ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-362, μ μ ˆν•˜μ§€ μ•Šμ€ λ™κΈ°ν™”λ‘œ 곡유 μžμ›μ„ μ‚¬μš©ν•˜λŠ” λ™μ‹œ μ‹€ν–‰ ("경쟁 쑰건") CWE-366, μŠ€λ ˆλ“œ λ‚΄μ—μ„œμ˜ 경쟁 쑰건 CWE-662, λΆ€μ μ ˆν•œ 동기화
final class IPHolder { private final List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>()); public void addAndPrintIPAddresses(InetAddress address) { ips.add(address); InetAddress[] addressCopy = (InetAddress[]) ips.toArray(new InetAddress[0]); // Iterate thr...
final class IPHolder { private final List<InetAddress> ips = Collections.synchronizedList(new ArrayList<InetAddress>()); public void addAndPrintIPAddresses(InetAddress address) { synchronized (ips) { ips.add(address); InetAddress[] addressCopy = (InetAddress[]) ips.toArray(new Inet...
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
λ…λ¦½μ μœΌλ‘œ μ›μžμ μΈ λ©”μ„œλ“œμ— λŒ€ν•œ 호좜 그룹이 μ›μžμ μ΄λΌκ³  κ°€μ •ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-362, μ μ ˆν•˜μ§€ μ•Šμ€ λ™κΈ°ν™”λ‘œ 곡유 μžμ›μ„ μ‚¬μš©ν•˜λŠ” λ™μ‹œ μ‹€ν–‰ ("경쟁 쑰건") CWE-366, μŠ€λ ˆλ“œ λ‚΄μ—μ„œμ˜ 경쟁 쑰건 CWE-662, λΆ€μ μ ˆν•œ 동기화
final class KeyedCounter { private final Map<String, Integer> map = Collections.synchronizedMap(new HashMap<String, Integer>()); public void increment(String key) { Integer old = map.get(key); int oldValue = (old == null) ? 0 : old.intValue(); if (oldValue == Integer.MAX_VALUE) { throw new...
final class KeyedCounter { private final Map<String, Integer> map = new HashMap<String, Integer>(); private final Object lock = new Object(); public void increment(String key) { synchronized (lock) { Integer old = map.get(key); int oldValue = (old == null) ? 0 : old.intValue(); if (o...
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
체인된 λ©”μ„œλ“œ 호좜이 μ›μžμ μœΌλ‘œ μˆ˜ν–‰λ˜λ„λ‘ 보μž₯ν•˜μ‹­μ‹œμ˜€.
null
final class USCurrency { // Change requested, denomination (optional fields) private int quarters = 0; private int dimes = 0; private int nickels = 0; private int pennies = 0; public USCurrency() {} // Setter methods public USCurrency setQuarters(int quantity) { quarters = quantity; return t...
final class USCurrency { private final int quarters; private final int dimes; private final int nickels; private final int pennies; public USCurrency(Builder builder) { this.quarters = builder.quarters; this.dimes = builder.dimes; this.nickels = builder.nickels; this.pennies = builder.pennie...
JAVA
κ°€μ‹œμ„±κ³Ό μ›μžμ„± (VNA)
64λΉ„νŠΈ 값을 읽고 μ“Έ λ•Œ μ›μžμ„±μ„ 보μž₯ν•˜μ‹­μ‹œμ˜€.
CWE-667, λΆ€μ μ ˆν•œ 잠금
class LongContainer { private long i = 0; void assignValue(long j) { i = j; } void printLong() { System.out.println("i = " + i); } }
class LongContainer { private volatile long i = 0; void assignValue(long j) { i = j; } void printLong() { System.out.println("i = " + i); } }
JAVA
Locking (LCK)
private final 잠금 객체λ₯Ό μ‚¬μš©ν•˜μ—¬ μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ™€ μƒν˜Έ μž‘μš©ν•  수 μžˆλŠ” 클래슀λ₯Ό λ™κΈ°ν™”ν•˜μ‹­μ‹œμ˜€.
CWE-412, μ™ΈλΆ€μ—μ„œ μ ‘κ·Ό κ°€λŠ₯ν•œ 잠금의 μ œν•œ μ—†μŒ CWE-413, λΆ€μ μ ˆν•œ μžμ› 잠금
public class SomeObject { public final Object lock = new Object(); public void changeValue() { synchronized (lock) { // ... } } }
public class SomeObject { private final Object lock = new Object(); // private final lock object public void changeValue() { synchronized (lock) { // Locks on the private Object // ... } } }
JAVA
Locking (LCK)
private final 잠금 객체λ₯Ό μ‚¬μš©ν•˜μ—¬ μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ™€ μƒν˜Έ μž‘μš©ν•  수 μžˆλŠ” 클래슀λ₯Ό λ™κΈ°ν™”ν•˜μ‹­μ‹œμ˜€.
CWE-412, μ™ΈλΆ€μ—μ„œ μ ‘κ·Ό κ°€λŠ₯ν•œ 잠금의 μ œν•œ μ—†μŒ CWE-413, λΆ€μ μ ˆν•œ μžμ› 잠금
public class SomeObject { //changeValue locks on the class object's monitor public static synchronized void changeValue() { // ... } } // Untrusted code synchronized (SomeObject.class) { while (true) { Thread.sleep(Integer.MAX_VALUE); // Indefinitely delay someObject } }
public class SomeObject { private static final Object lock = new Object(); public static void changeValue() { synchronized (lock) { // Locks on the private Object // ... } } }
JAVA
Locking (LCK)
μž¬μ‚¬μš©λ  수 μžˆλŠ” κ°μ²΄μ—μ„œ λ™κΈ°ν™”ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
private final Boolean initialized = Boolean.FALSE; public void doSomething() { synchronized (initialized) { // ... } }
private final Object lock = new Object(); public void doSomething() { synchronized (lock) { // ... } }
JAVA
Locking (LCK)
μž¬μ‚¬μš©λ  수 μžˆλŠ” κ°μ²΄μ—μ„œ λ™κΈ°ν™”ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
private int count = 0; private final Integer Lock = count; // λ°•μ‹±λœ ν”„λ¦¬λ―Έν‹°λΈŒ Lock이 곡유됨 public void doSomething() { synchronized (Lock) { count++; // ... } }
private int count = 0; private final Object lock = new Object(); public void doSomething() { synchronized (lock) { count++; // ... } }
JAVA
Locking (LCK)
μž¬μ‚¬μš©λ  수 μžˆλŠ” κ°μ²΄μ—μ„œ λ™κΈ°ν™”ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
private final String lock = new String("LOCK").intern(); public void doSomething() { synchronized (lock) { // ... } }
private final Object lock = new Object(); public void doSomething() { synchronized (lock) { // ... } }
JAVA
Locking (LCK)
getClass()κ°€ λ°˜ν™˜ν•˜λŠ” 클래슀 객체에 λ™κΈ°ν™”ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
class Base { static DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM); public Date parse(String str) throws ParseException { synchronized (getClass()) { return format.parse(str); } } } class Derived extends Base { public Date doSomethingAndParse(String str) throws ParseEx...
class Base { static DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM); public Date parse(String str) throws ParseException { synchronized (Base.class) { return format.parse(str); } } }
JAVA
Locking (LCK)
κ³ μˆ˜μ€€ λ™μ‹œμ„± 객체의 λ‚΄μž¬μ  μž κΈˆμ— λ™κΈ°ν™”ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
private final Lock lock = new ReentrantLock(); public void doSomething() { synchronized(lock) { // ... } }
private final Lock lock = new ReentrantLock(); public void doSomething() { lock.lock(); try { // ... } finally { lock.unlock(); } }
JAVA
Locking (LCK)
λ°±μ—… μ»¬λ ‰μ…˜μ΄ μ ‘κ·Ό κ°€λŠ₯ν•œ 경우, μ»¬λ ‰μ…˜ 뷰에 λ™κΈ°ν™”ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
private final Map<Integer, String> mapView = Collections.synchronizedMap(new HashMap<Integer, String>()); private final Set<Integer> setView = mapView.keySet(); public Map<Integer, String> getMap() { return mapView; } public void doSomething() { synchronized (setView) { // Incorrectly synchronizes on setVi...
private final Map<Integer, String> mapView = Collections.synchronizedMap(new HashMap<Integer, String>()); private final Set<Integer> setView = mapView.keySet(); public Map<Integer, String> getMap() { return mapView; } public void doSomething() { synchronized (mapView) { // Synchronize on map, rather than s...
JAVA
Locking (LCK)
μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ— μ˜ν•΄ μˆ˜μ •λ  수 μžˆλŠ” 정적 ν•„λ“œμ— λŒ€ν•œ 접근을 λ™κΈ°ν™”ν•˜μ‹­μ‹œμ˜€.
CWE-820, 동기화 λˆ„λ½
/* This class is not thread-safe */ public final class CountHits { private static int counter; public void incrementCounter() { counter++; } }
/* This class is thread-safe */ public final class CountHits { private static int counter; private static final Object lock = new Object(); public void incrementCounter() { synchronized (lock) { counter++; } } }
JAVA
Locking (LCK)
곡유된 정적 데이터λ₯Ό λ³΄ν˜Έν•˜κΈ° μœ„ν•΄ μΈμŠ€ν„΄μŠ€ μž κΈˆμ„ μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-667, λΆ€μ μ ˆν•œ 잠금
public final class CountBoxes implements Runnable { private static volatile int counter; // ... private final Object lock = new Object(); @Override public void run() { synchronized (lock) { counter++; // ... } } public static void main(String[] args) { for (int i = 0; i < 2; i++)...
public class CountBoxes implements Runnable { private static int counter; // ... private static final Object lock = new Object(); public void run() { synchronized (lock) { counter++; // ... } } // ... }
JAVA
Locking (LCK)
λ™μΌν•œ μˆœμ„œλ‘œ μž κΈˆμ„ μš”μ²­ν•˜κ³  ν•΄μ œν•˜μ—¬ ꡐ착 μƒνƒœλ₯Ό ν”Όν•˜μ‹­μ‹œμ˜€.
CWE-833, Deadlock
final class BankAccount { private double balanceAmount; // 총 κ³„μ’Œ μž”μ•‘ BankAccount(double balance) { this.balanceAmount = balance; } // 이 객체 μΈμŠ€ν„΄μŠ€μ—μ„œ μ£Όμ–΄μ§„ BankAccount μΈμŠ€ν„΄μŠ€λ‘œ κΈˆμ•‘μ„ μž…κΈˆ private void depositAmount(BankAccount ba, double amount) { synchronized (this) { synchronized (ba) { if (amount...
final class BankAccount implements Comparable<BankAccount> { private double balanceAmount; // 총 κ³„μ’Œ μž”μ•‘ private final long id; // 각 BankAccount에 λŒ€ν•œ 고유 ID private static final AtomicLong nextID = new AtomicLong(0); // λ‹€μŒ μ‚¬μš© κ°€λŠ₯ν•œ ID BankAccount(double balance) { this.balanceAmount = balance; this.id = ne...
JAVA
Locking (LCK)
μ˜ˆμ™Έ μƒν™©μ—μ„œ 보유 쀑인 락을 ν•΄μ œν•˜λΌ
CWE-834, Deadlock
public final class Client { private final Lock lock = new ReentrantLock(); public void doSomething(File file) { InputStream in = null; try { in = new FileInputStream(file); lock.lock(); // νŒŒμΌμ— λŒ€ν•œ μž‘μ—… μˆ˜ν–‰ } catch (FileNotFoundException fnf) { // μ˜ˆμ™Έ 처리 } finally { lock.unl...
public final class Client { private final Lock lock = new ReentrantLock(); public void doSomething(File file) { InputStream in = null; lock.lock(); try { in = new FileInputStream(file); // νŒŒμΌμ— λŒ€ν•œ μž‘μ—… μˆ˜ν–‰ } catch (FileNotFoundException fnf) { // μ˜ˆμ™Έ 처리 } finally { if (in != ...
JAVA
Locking (LCK)
μž κΈˆμ„ λ³΄μœ ν•œ μƒνƒœμ—μ„œ 차단될 수 μžˆλŠ” μž‘μ—…μ„ μˆ˜ν–‰ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public synchronized void doSomething(long time) throws InterruptedException { // ... Thread.sleep(time); }
public synchronized void doSomething(long timeout) throws InterruptedException { // ... while (<condition does not hold>) { wait(timeout); // Immediately releases the current monitor } }
JAVA
Locking (LCK)
μž κΈˆμ„ λ³΄μœ ν•œ μƒνƒœμ—μ„œ 차단될 수 μžˆλŠ” μž‘μ—…μ„ μˆ˜ν–‰ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
// Class Page is defined separately. // It stores and returns the Page name via getName() Page[] pageBuff = new Page[MAX_PAGE_SIZE]; public synchronized boolean sendPage(Socket socket, String pageName) throws IOException { // Get the output stream to write the Page to ObjectOu...
// No synchronization public boolean sendPage(Socket socket, String pageName) { Page targetPage = getPage(pageName); if (targetPage == null){ return false; } return deliverPage(socket, targetPage); } // Requires synchronization private synchronized Page getPage(String pageName) { Page targetPage = nul...
JAVA
Locking (LCK)
μ˜¬λ°”λ₯Έ ν˜•νƒœμ˜ 이쀑 검사 잠금 νŒ¨ν„΄μ„ μ‚¬μš©ν•˜λΌ
CWE-609, Double-checked Locking
final class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized (this) { if (helper == null) { helper = new Helper(); } } } return helper; } // 기타 λ©”μ„œλ“œ 및 멀버... }
final class Foo { private volatile Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized (this) { if (helper == null) { helper = new Helper(); } } } return helper; } // 기타 λ©”μ„œλ“œ 및 멀버... }
JAVA
Locking (LCK)
μΌκ΄€λœ 락 μ „λž΅μ„ λͺ…μ‹œν•˜μ§€ μ•Šμ€ 클래슀 μ‚¬μš© μ‹œ ν΄λΌμ΄μ–ΈνŠΈ μΈ‘ 락을 ν”Όν•˜λΌ
null
final class Book { private final String title; private Calendar dateIssued; private Calendar dateDue; public synchronized void issue(int days) { dateIssued = Calendar.getInstance(); dateDue = Calendar.getInstance(); dateDue.add(Calendar.DATE, days); } public synchronized Calendar getDueDate() ...
final class Book { private final String title; private Calendar dateIssued; private Calendar dateDue; private final Object lock = new Object(); public void issue(int days) { synchronized (lock) { dateIssued = Calendar.getInstance(); dateDue = Calendar.getInstance(); dateDue.add(Calendar...
JAVA
Thread APIs (THI)
Do not invoke Thread.run()
CWE-572, Call to Thread run() instead of start()
public final class Foo implements Runnable { @Override public void run() { // ... } public static void main(String[] args) { Foo foo = new Foo(); new Thread(foo).run(); // 잘λͺ»λœ 호좜 } }
public final class Foo implements Runnable { @Override public void run() { // ... } public static void main(String[] args) { Foo foo = new Foo(); new Thread(foo).start(); // μ˜¬λ°”λ₯Έ 호좜 } }
JAVA
Thread APIs (THI)
Do not invoke ThreadGroup methods
null
final class HandleRequest implements Runnable { public void run() { // Do something } } public final class NetworkHandler implements Runnable { private static ThreadGroup tg = new ThreadGroup("Chief"); @Override public void run() { new Thread(tg, new HandleRequest(), "thread1").start(); new Thre...
public final class NetworkHandler { private final ExecutorService executor; NetworkHandler(int poolSize) { this.executor = Executors.newFixedThreadPool(poolSize); } public void startThreads() { for (int i = 0; i < 3; i++) { executor.execute(new HandleRequest()); } } public void shutd...
JAVA
Thread APIs (THI)
단일 μŠ€λ ˆλ“œκ°€ μ•„λ‹Œ λͺ¨λ“  λŒ€κΈ° 쀑인 μŠ€λ ˆλ“œμ— μ•Œλ¦Όμ„ 보내라
null
class SharedResource { private boolean condition = false; public synchronized void awaitCondition() throws InterruptedException { while (!condition) { wait(); } // 쑰건이 μΆ©μ‘±λ˜μ—ˆμ„ λ•Œ μˆ˜ν–‰ν•  μž‘μ—… } public synchronized void signalCondition() { condition = true; notify(); // 단일 μŠ€λ ˆλ“œμ—λ§Œ μ•Œλ¦Ό } }
class SharedResource { private boolean condition = false; public synchronized void awaitCondition() throws InterruptedException { while (!condition) { wait(); } // 쑰건이 μΆ©μ‘±λ˜μ—ˆμ„ λ•Œ μˆ˜ν–‰ν•  μž‘μ—… } public synchronized void signalCondition() { condition = true; notifyAll(); // λͺ¨λ“  λŒ€κΈ° 쀑인 μŠ€λ ˆλ“œμ— μ•Œλ¦Ό }...
JAVA
Thread APIs (THI)
항상 wait() 및 await() λ©”μ„œλ“œλ₯Ό 반볡문 λ‚΄μ—μ„œ ν˜ΈμΆœν•˜μ‹­μ‹œμ˜€.
null
synchronized (object) { if (<condition does not hold>) { object.wait(); } // Proceed when condition holds }
synchronized (object) { while (<condition does not hold>) { object.wait(); } // Proceed when condition holds }
JAVA
Thread APIs (THI)
λΈ”λ‘œν‚Ή μž‘μ—…μ„ μˆ˜ν–‰ν•˜λŠ” μŠ€λ ˆλ“œκ°€ μ’…λ£Œλ  수 μžˆλ„λ‘ 보μž₯ν•˜λΌ
null
public final class SocketReader implements Runnable { private final Socket socket; private final BufferedReader in; private volatile boolean done = false; private final Object lock = new Object(); public SocketReader(String host, int port) throws IOException { this.socket = new Socket(host, port); th...
public final class SocketReader implements Runnable { private final Socket socket; private final BufferedReader in; private volatile boolean done = false; private final Object lock = new Object(); public SocketReader(String host, int port) throws IOException { this.socket = new Socket(host, port); th...
JAVA
Thread APIs (THI)
Thread.stop()을 μ‚¬μš©ν•˜μ—¬ μŠ€λ ˆλ“œλ₯Ό μ’…λ£Œν•˜μ§€ 마라
null
public final class Container implements Runnable { private final Vector<Integer> vector = new Vector<>(1000); @Override public synchronized void run() { Random number = new Random(123L); int i = vector.capacity(); while (i > 0) { vector.add(number.nextInt(100)); i--; } } public s...
public final class Container implements Runnable { private final Vector<Integer> vector = new Vector<>(1000); private volatile boolean done = false; public void shutdown() { done = true; } @Override public synchronized void run() { Random number = new Random(123L); int i = vector.capacity(); ...
JAVA
Thread APIs (THI)
Thread.stop()을 μ‚¬μš©ν•˜μ—¬ μŠ€λ ˆλ“œλ₯Ό μ’…λ£Œν•˜μ§€ 마라
null
public final class Container implements Runnable { private final Vector<Integer> vector = new Vector<>(1000); @Override public synchronized void run() { Random number = new Random(123L); int i = vector.capacity(); while (i > 0) { vector.add(number.nextInt(100)); i--; } } public s...
public final class Container implements Runnable { private final Vector<Integer> vector = new Vector<>(1000); @Override public synchronized void run() { Random number = new Random(123L); int i = vector.capacity(); while (!Thread.interrupted() && i > 0) { vector.add(number.nextInt(100)); i...
JAVA
Thread Pools (TPS)
νŠΈλž˜ν”½ 급증 μ‹œ μ„œλΉ„μŠ€μ˜ μ›ν™œν•œ μ €ν•˜λ₯Ό κ°€λŠ₯ν•˜κ²Œ ν•˜κΈ° μœ„ν•΄ μŠ€λ ˆλ“œ 풀을 μ‚¬μš©ν•˜μ‹­μ‹œμ˜€.
CWE-405, λΉ„λŒ€μΉ­ μžμ› μ†ŒλΉ„ (증폭) CWE-410, μžμ› ν’€ λΆ€μ‘±
class Helper { public void handle(Socket socket) { // ... } } final class RequestHandler { private final Helper helper = new Helper(); private final ServerSocket server; private RequestHandler(int port) throws IOException { server = new ServerSocket(port); } public static RequestHandler newI...
// class Helper remains unchanged final class RequestHandler { private final Helper helper = new Helper(); private final ServerSocket server; private final ExecutorService exec; private RequestHandler(int port, int poolSize) throws IOException { server = new ServerSocket(port); exec = Executors.newF...
JAVA
Thread Pools (TPS)
μƒν˜Έ 의쑴적인 μž‘μ—…μ„ μ œν•œλœ μŠ€λ ˆλ“œ ν’€μ—μ„œ μ‹€ν–‰ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public final class ValidationService { private final ExecutorService pool; public ValidationService(int poolSize) { pool = Executors.newFixedThreadPool(poolSize); } public void shutdown() { pool.shutdown(); } public StringBuilder fieldAggregator(String... inputs) throws InterruptedExcept...
public final class ValidationService { // ... public StringBuilder fieldAggregator(String... inputs) throws InterruptedException, ExecutionException { // ... for (int i = 0; i < inputs.length; i++) { // Don't pass-in thread pool results[i] = pool.submit(new ValidateInput<String>(inputs[i]...
JAVA
Thread Pools (TPS)
μƒν˜Έ 의쑴적인 μž‘μ—…μ„ μ œν•œλœ μŠ€λ ˆλ“œ ν’€μ—μ„œ μ‹€ν–‰ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public final class BrowserManager { private final ExecutorService pool = Executors.newFixedThreadPool(10); private final int numberOfTimes; private static AtomicInteger count = new AtomicInteger(); // count = 0 public BrowserManager(int n) { numberOfTimes = n; } public void perUser() { methodInv...
public final class BrowserManager { private final static ThreadPoolExecutor pool = new ThreadPoolExecutor(0, 10, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); private final int numberOfTimes; private static AtomicInteger count = new AtomicInteger(); // count = 0 ...
JAVA
Thread Pools (TPS)
μŠ€λ ˆλ“œ 풀에 제좜된 μž‘μ—…μ΄ μΈν„°λŸ½νŠΈ κ°€λŠ₯ν•˜λ„λ‘ 보μž₯ν•˜μ‹­μ‹œμ˜€.
null
public final class SocketReader implements Runnable { // Thread-safe class private final Socket socket; private final BufferedReader in; private final Object lock = new Object(); public SocketReader(String host, int port) throws IOException { this.socket = new Socket(host, port); this.in = new Buffere...
public final class SocketReader implements Runnable { private final SocketChannel sc; private final Object lock = new Object(); public SocketReader(String host, int port) throws IOException { sc = SocketChannel.open(new InetSocketAddress(host, port)); } @Override public void run() { ByteBuffer buf...
JAVA
Thread Pools (TPS)
μŠ€λ ˆλ“œ ν’€μ—μ„œ μ‹€ν–‰λ˜λŠ” μž‘μ—…μ΄ 쑰용히 μ‹€νŒ¨ν•˜μ§€ μ•Šλ„λ‘ 보μž₯ν•˜λΌ
CWE-392, 였λ₯˜ μƒνƒœ 보고 λˆ„λ½
final class PoolService { private final ExecutorService pool = Executors.newFixedThreadPool(10); public void doSomething() { pool.execute(new Task()); } } final class Task implements Runnable { @Override public void run() { // ... throw new NullPointerException(); // μ˜ˆμ™Έ λ°œμƒ // ... } }
final class PoolService { private final ExecutorService pool = new CustomThreadPoolExecutor( 10, 10, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10) ); // ... } class CustomThreadPoolExecutor extends ThreadPoolExecutor { public CustomThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long k...
JAVA
Thread Pools (TPS)
μŠ€λ ˆλ“œ ν’€μ—μ„œ μ‹€ν–‰λ˜λŠ” μž‘μ—…μ΄ 쑰용히 μ‹€νŒ¨ν•˜μ§€ μ•Šλ„λ‘ 보μž₯ν•˜λΌ
CWE-392, 였λ₯˜ μƒνƒœ 보고 λˆ„λ½
final class PoolService { private final ExecutorService pool = Executors.newFixedThreadPool(10); public void doSomething() { pool.execute(new Task()); } } final class Task implements Runnable { @Override public void run() { // ... throw new NullPointerException(); // μ˜ˆμ™Έ λ°œμƒ // ... } }
final class PoolService { private static final ThreadFactory factory = new ExceptionThreadFactory(new MyExceptionHandler()); private static final ExecutorService pool = Executors.newFixedThreadPool(10, factory); public void doSomething() { pool.execute(new Task()); } public static class Exceptio...
JAVA
Thread Pools (TPS)
μŠ€λ ˆλ“œ ν’€μ—μ„œ μ‹€ν–‰λ˜λŠ” μž‘μ—…μ΄ 쑰용히 μ‹€νŒ¨ν•˜μ§€ μ•Šλ„λ‘ 보μž₯ν•˜λΌ
CWE-392, 였λ₯˜ μƒνƒœ 보고 λˆ„λ½
final class PoolService { private final ExecutorService pool = Executors.newFixedThreadPool(10); public void doSomething() { pool.execute(new Task()); } } final class Task implements Runnable { @Override public void run() { // ... throw new NullPointerException(); // μ˜ˆμ™Έ λ°œμƒ // ... } }
final class PoolService { private final ExecutorService pool = Executors.newFixedThreadPool(10); public void doSomething() { Future<?> future = pool.submit(new Task()); try { future.get(); // μž‘μ—… μ™„λ£Œλ₯Ό 기닀리고 μ˜ˆμ™Έλ₯Ό 확인 } catch (InterruptedException | ExecutionException e) { // μ˜ˆμ™Έ 처리 둜직 } } }
JAVA
Thread Pools (TPS)
μŠ€λ ˆλ“œ ν’€ μ‚¬μš© μ‹œ ThreadLocal λ³€μˆ˜λ₯Ό μž¬μ΄ˆκΈ°ν™”ν•˜λΌ
null
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; } public final class Diary { private static final ThreadLocal<Day> days = new ThreadLocal<Day>() { @Override protected Day initialValue() { return Day.MONDAY; } }; public static Day getCurrentDay() { return...
public final class DiaryPool { private final Executor exec = Executors.newFixedThreadPool(2); private final Diary diary = new Diary(); public void doSomething1() { exec.execute(new Runnable() { @Override public void run() { try { diary.setDay(Day.FRIDAY); diary.threadS...
JAVA
Thread-Safety Miscellaneous (TSM)
μŠ€λ ˆλ“œ μ•ˆμ „ν•œ λ©”μ„œλ“œλ₯Ό μŠ€λ ˆλ“œ μ•ˆμ „ν•˜μ§€ μ•Šμ€ λ©”μ„œλ“œλ‘œ μž¬μ •μ˜ν•˜μ§€ 마라
null
class Base { public synchronized void doSomething() { // ... } } class Derived extends Base { @Override public void doSomething() { // ... } }
class Base { public synchronized void doSomething() { // ... } } class Derived extends Base { @Override public synchronized void doSomething() { // ... } }
JAVA
Thread-Safety Miscellaneous (TSM)
μŠ€λ ˆλ“œ μ•ˆμ „ν•œ λ©”μ„œλ“œλ₯Ό μŠ€λ ˆλ“œ μ•ˆμ „ν•˜μ§€ μ•Šμ€ λ©”μ„œλ“œλ‘œ μž¬μ •μ˜ν•˜μ§€ 마라
null
class Base { public synchronized void doSomething() { // ... } } class Derived extends Base { @Override public void doSomething() { // ... } }
class Base { public synchronized void doSomething() { // ... } } class Derived extends Base { private final Object lock = new Object(); @Override public void doSomething() { synchronized (lock) { // ... } } }
JAVA
Thread-Safety Miscellaneous (TSM)
객체 생성 쀑 this μ°Έμ‘°λ₯Ό λ…ΈμΆœν•˜μ§€ 마라
null
public class EventSource { private final List<EventListener> listeners = new ArrayList<>(); public void registerListener(EventListener listener) { listeners.add(listener); } // 기타 λ©”μ„œλ“œ } public class ThisEscape { public ThisEscape(EventSource source) { source.registerListener(new E...
public class SafeListener { private final EventListener listener; private SafeListener() { listener = new EventListener() { public void onEvent(Event e) { doSomething(e); } }; } public static SafeListener newInstance(EventSource source) { ...
JAVA
Thread-Safety Miscellaneous (TSM)
클래슀 μ΄ˆκΈ°ν™” 쀑 λ°±κ·ΈλΌμš΄λ“œ μŠ€λ ˆλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ 마라
null
public final class ConnectionFactory { private static Connection dbConnection; // 기타 ν•„λ“œ... static { Thread dbInitializerThread = new Thread(new Runnable() { @Override public void run() { // λ°μ΄ν„°λ² μ΄μŠ€ μ—°κ²° μ΄ˆκΈ°ν™” try { dbConnection = DriverManager.getConnection("μ—°κ²° λ¬Έμžμ—΄"); ...
public final class ConnectionFactory { private static Connection dbConnection; // 기타 ν•„λ“œ... static { // 메인 μŠ€λ ˆλ“œμ—μ„œ λ°μ΄ν„°λ² μ΄μŠ€ μ—°κ²° μ΄ˆκΈ°ν™” try { dbConnection = DriverManager.getConnection("μ—°κ²° λ¬Έμžμ—΄"); } catch (SQLException e) { dbConnection = null; } // 기타 μ΄ˆκΈ°ν™” μž‘μ—… } public static Connection...
JAVA
Thread-Safety Miscellaneous (TSM)
λΆ€λΆ„μ μœΌλ‘œ μ΄ˆκΈ°ν™”λœ 객체λ₯Ό κ³΅κ°œν•˜μ§€ 마라
null
class Foo { private Helper helper; public Helper getHelper() { return helper; } public void initialize() { helper = new Helper(42); } } class Helper { private int n; public Helper(int n) { this.n = n; } // ... }
class Foo { private Helper helper; public synchronized Helper getHelper() { return helper; } public synchronized void initialize() { helper = new Helper(42); } }
JAVA
Input Output (FIO)
곡유 λ””λ ‰ν„°λ¦¬μ—μ„œ νŒŒμΌμ„ μ‘°μž‘ν•˜μ§€ 마라
CWE-67, Windows λ””λ°”μ΄μŠ€ μ΄λ¦„μ˜ λΆ€μ μ ˆν•œ 처리
import java.io.File; import java.io.FileWriter; import java.io.IOException; public class SharedDirectoryExample { public static void main(String[] args) { File sharedDir = new File("/shared/tmp"); File tempFile = new File(sharedDir, "temp.txt"); try (FileWriter writer = new FileWriter(temp...
import java.io.File; import java.io.FileWriter; import java.io.IOException; public class SecureDirectoryExample { public static void main(String[] args) { File secureDir = new File("/home/user/secure_tmp"); if (!secureDir.exists()) { secureDir.mkdirs(); } File tempFile =...
JAVA
Input Output (FIO)
μ μ ˆν•œ μ ‘κ·Ό κΆŒν•œμœΌλ‘œ νŒŒμΌμ„ μƒμ„±ν•˜μ‹­μ‹œμ˜€.
CWE-279, 싀행에 ν• λ‹Ήλœ κΆŒν•œμ˜ λΆ€μ •ν™•μ„± CWE-276, κΈ°λ³Έ κΆŒν•œμ˜ λΆ€μ •ν™•μ„± CWE-732, μ€‘μš”ν•œ λ¦¬μ†ŒμŠ€μ— λŒ€ν•œ κΆŒν•œ ν• λ‹Ήμ˜ λΆ€μ •ν™•μ„±
Writer out = new FileWriter("file");
Path file = new File("file").toPath(); // Throw exception rather than overwrite existing file Set<OpenOption> options = new HashSet<OpenOption>(); options.add(StandardOpenOption.CREATE_NEW); options.add(StandardOpenOption.APPEND); // File permissions should be such that only user may read/write file Set<PosixFilePe...
JAVA
Input Output (FIO)
파일 κ΄€λ ¨ 였λ₯˜λ₯Ό κ°μ§€ν•˜κ³  μ²˜λ¦¬ν•˜μ‹­μ‹œμ˜€.
null
File file = new File(args[0]); file.delete();
File file = new File("file"); if (!file.delete()) { // Deletion failed, handle error }
JAVA
Input Output (FIO)
파일 κ΄€λ ¨ 였λ₯˜λ₯Ό κ°μ§€ν•˜κ³  μ²˜λ¦¬ν•˜μ‹­μ‹œμ˜€.
null
File file = new File(args[0]); file.delete();
Path file = new File(args[0]).toPath(); try { Files.delete(file); } catch (IOException x) { // Deletion failed, handle error }
JAVA
Input Output (FIO)
ν”„λ‘œκ·Έλž¨ μ’…λ£Œ 전에 μž„μ‹œ νŒŒμΌμ„ μ œκ±°ν•˜λΌ
CWE-377, λΉ„λ³΄μ•ˆ μž„μ‹œ 파일 CWE-459, λΆˆμ™„μ „ν•œ 정리
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class TempFileExample { public static void main(String[] args) throws IOException { File f = new File("tempnam.tmp"); if (f.exists()) { System.out.println("This file already exists"); re...
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; public class TempFileExample { public static void main(String[] args) throws IOException { File f = new File("tempnam.tmp"); if (f.exists()) { System.out.println("This file already exists"); re...
JAVA
Input Output (FIO)
ν•„μš”ν•˜μ§€ μ•Šμ€ λ¦¬μ†ŒμŠ€λŠ” ν•΄μ œν•˜λΌ
CWE-404, λΆ€μ μ ˆν•œ μžμ› μ’…λ£Œ λ˜λŠ” ν•΄μ œ CWE-405, λΉ„λŒ€μΉ­ μžμ› μ†ŒλΉ„ (증폭) CWE-459, λΆˆμ™„μ „ν•œ 정리 CWE-770, μ œν•œ λ˜λŠ” 쑰절 없이 μžμ› ν• λ‹Ή
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class ResourceExample { public int processFile(String fileName) throws IOException { FileInputStream stream = new FileInputStream(fileName); BufferedReader bufRead = n...
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; public class ResourceExample { public int processFile(String fileName) throws IOException { try (FileInputStream stream = new FileInputStream(fileName); BufferedReader b...
JAVA
Input Output (FIO)
μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ— λ²„νΌλ‚˜ κ·Έ λ°±μ—… λ°°μ—΄ λ©”μ„œλ“œλ₯Ό λ…ΈμΆœν•˜μ§€ 마라
null
final class Wrap { private char[] dataArray; public Wrap() { dataArray = new char[10]; // μ΄ˆκΈ°ν™” } public CharBuffer getBufferCopy() { return CharBuffer.wrap(dataArray); } }
final class Wrap { private char[] dataArray; public Wrap() { dataArray = new char[10]; // μ΄ˆκΈ°ν™” } public CharBuffer getBufferCopy() { return CharBuffer.wrap(dataArray).asReadOnlyBuffer(); } }
JAVA
Input Output (FIO)
μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ— λ²„νΌλ‚˜ κ·Έ λ°±μ—… λ°°μ—΄ λ©”μ„œλ“œλ₯Ό λ…ΈμΆœν•˜μ§€ 마라
null
final class Wrap { private char[] dataArray; public Wrap() { dataArray = new char[10]; // μ΄ˆκΈ°ν™” } public CharBuffer getBufferCopy() { return CharBuffer.wrap(dataArray); } }
final class Wrap { private char[] dataArray; public Wrap() { dataArray = new char[10]; // μ΄ˆκΈ°ν™” } public CharBuffer getBufferCopy() { CharBuffer cb = CharBuffer.allocate(dataArray.length); cb.put(dataArray); cb.flip(); // 버퍼λ₯Ό 읽기 λͺ¨λ“œλ‘œ μ „ν™˜ return cb; } }
JAVA
Input Output (FIO)
μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ— λ²„νΌλ‚˜ κ·Έ λ°±μ—… λ°°μ—΄ λ©”μ„œλ“œλ₯Ό λ…ΈμΆœν•˜μ§€ 마라
null
final class Dup { CharBuffer cb; public Dup() { cb = CharBuffer.allocate(10); // μ΄ˆκΈ°ν™” } public CharBuffer getBufferCopy() { return cb.duplicate(); } }
final class Dup { CharBuffer cb; public Dup() { cb = CharBuffer.allocate(10); // μ΄ˆκΈ°ν™” } public CharBuffer getBufferCopy() { return cb.asReadOnlyBuffer(); } }
JAVA
Input Output (FIO)
단일 λ°”μ΄νŠΈ λ˜λŠ” 문자 μŠ€νŠΈλ¦Όμ— μ—¬λŸ¬ 개의 버퍼링 래퍼λ₯Ό μƒμ„±ν•˜μ§€ 마라
null
public final class InputLibrary { public static char getChar() throws EOFException, IOException { BufferedInputStream in = new BufferedInputStream(System.in); // λ§€ 호좜 μ‹œ μƒˆλ‘œμš΄ 래퍼 생성 int input = in.read(); if (input == -1) { throw new EOFException(); } return (char) input; } public static v...
public final class InputLibrary { private static BufferedInputStream in = new BufferedInputStream(System.in); public static char getChar() throws EOFException, IOException { int input = in.read(); if (input == -1) { throw new EOFException(); } return (char) input; } public static void ma...
JAVA
Input Output (FIO)
μ™ΈλΆ€ ν”„λ‘œμ„ΈμŠ€κ°€ I/O λ²„νΌμ—μ„œ λΈ”λ‘λ˜μ§€ μ•Šλ„λ‘ ν•˜λΌ
null
public class Exec { public static void main(String args[]) throws IOException { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("notemaker"); int exitVal = proc.exitValue(); } }
public class Exec { public static void main(String args[]) throws IOException, InterruptedException { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("notemaker"); // 좜λ ₯ 슀트림 처리 StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "OUTPUT"); // 였λ₯˜ 슀트림 처리 StreamGobbl...
JAVA
Input Output (FIO)
μ™ΈλΆ€ ν”„λ‘œμ„ΈμŠ€κ°€ I/O λ²„νΌμ—μ„œ λΈ”λ‘λ˜μ§€ μ•Šλ„λ‘ ν•˜λΌ
null
public class Exec { public static void main(String args[]) throws IOException, InterruptedException { Runtime rt = Runtime.getRuntime(); Process proc = rt.exec("notemaker"); int exitVal = proc.waitFor(); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class StreamGobbler extends Thread { private InputStream inputStream; private String type; public StreamGobbler(InputStream inputStream, String type) { this.inputStream = inputStre...
JAVA
Input Output (FIO)
μŠ€νŠΈλ¦Όμ—μ„œ 읽은 λ¬Έμžλ‚˜ λ°”μ΄νŠΈμ™€ -1을 κ΅¬λΆ„ν•˜μ‹­μ‹œμ˜€.
null
FileInputStream in; // Initialize stream byte data; while ((data = (byte) in.read()) != -1) { // ... }
FileInputStream in; // Initialize stream int inbuff; byte data; while ((inbuff = in.read()) != -1) { data = (byte) inbuff; // ... }
JAVA
Input Output (FIO)
μŠ€νŠΈλ¦Όμ—μ„œ 읽은 λ¬Έμžλ‚˜ λ°”μ΄νŠΈμ™€ -1을 κ΅¬λΆ„ν•˜μ‹­μ‹œμ˜€.
null
FileReader in; // Initialize stream char data; while ((data = (char) in.read()) != -1) { // ... }
FileReader in; // Initialize stream int inbuff; char data; while ((inbuff = in.read()) != -1) { data = (char) inbuff; // ... }
JAVA
Input Output (FIO)
write() λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•  λ•Œ 0μ—μ„œ 255 λ²”μœ„λ₯Ό λ²—μ–΄λ‚˜λŠ” μ •μˆ˜λ₯Ό 좜λ ₯ν•˜μ§€ 마라
CWE-252, Unchecked Return Value
class ConsoleWrite { public static void main(String[] args) { // 255λ₯Ό μ΄ˆκ³Όν•˜λŠ” 값은 예기치 μ•Šμ€ 좜λ ₯을 μ΄ˆλž˜ν•  수 있음 System.out.write(Integer.valueOf(args[0])); System.out.flush(); } }
class FileWrite { public static void main(String[] args) throws NumberFormatException, IOException { // λ²”μœ„ 검사 μˆ˜ν–‰ int value = Integer.valueOf(args[0]); if (value < 0 || value > 255) { throw new ArithmeticException("값이 λ²”μœ„λ₯Ό λ²—μ–΄λ‚¬μŠ΅λ‹ˆλ‹€."); } System.out.write(value); System.out.flush(); } }
JAVA
Input Output (FIO)
write() λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•  λ•Œ 0μ—μ„œ 255 λ²”μœ„λ₯Ό λ²—μ–΄λ‚˜λŠ” μ •μˆ˜λ₯Ό 좜λ ₯ν•˜μ§€ 마라
CWE-252, Unchecked Return Value
class ConsoleWrite { public static void main(String[] args) { // 255λ₯Ό μ΄ˆκ³Όν•˜λŠ” 값은 예기치 μ•Šμ€ 좜λ ₯을 μ΄ˆλž˜ν•  수 있음 System.out.write(Integer.valueOf(args[0])); System.out.flush(); } }
import java.io.DataOutputStream; import java.io.IOException; class FileWrite { public static void main(String[] args) throws NumberFormatException, IOException { DataOutputStream dos = new DataOutputStream(System.out); dos.writeInt(Integer.valueOf(args[0])); dos.flush(); } }
JAVA
Input Output (FIO)
배열을 μ±„μš°κΈ° μœ„ν•΄ read() λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•  λ•Œ 배열이 μ™„μ „νžˆ μ±„μ›Œμ‘ŒλŠ”μ§€ ν™•μΈν•˜λΌ
CWE-135, 닀쀑 λ°”μ΄νŠΈ λ¬Έμžμ—΄ 길이의 λΆ€μ •ν™•ν•œ 계산
public static String readBytes(InputStream in) throws IOException { byte[] data = new byte[1024]; if (in.read(data) == -1) { throw new EOFException(); } return new String(data, "UTF-8"); }
public static String readBytes(InputStream in) throws IOException { byte[] data = new byte[1024]; int bytesRead = 0; int n; while (bytesRead < data.length && (n = in.read(data, bytesRead, data.length - bytesRead)) != -1) { bytesRead += n; } if (bytesRead == 0) { throw new EOFException(); } retur...
JAVA
Input Output (FIO)
리틀 μ—”λ””μ•ˆ 데이터λ₯Ό 읽고 μ“°λŠ” λ©”μ„œλ“œλ₯Ό μ œκ³΅ν•˜μ‹­μ‹œμ˜€.
CWE-198, 잘λͺ»λœ λ°”μ΄νŠΈ μˆœμ„œ μ‚¬μš©
try { DataInputStream dis = new DataInputStream(new FileInputStream("data")); // λ¦¬ν‹€μ—”λ””μ•ˆ ν˜•μ‹μ˜ 데이터λ₯Ό λΉ…μ—”λ””μ•ˆμœΌλ‘œ 읽음 int serialNumber = dis.readInt(); } catch (IOException e) { // 였λ₯˜ 처리 }
try { DataInputStream dis = new DataInputStream(new FileInputStream("data")); byte[] buffer = new byte[4]; int bytesRead = dis.read(buffer); // 버퍼에 λ°”μ΄νŠΈλ₯Ό μ½μ–΄λ“€μž„ if (bytesRead != 4) { throw new IOException("μ˜ˆμƒμΉ˜ λͺ»ν•œ 슀트림 μ’…λ£Œ"); } int serialNumber = ByteBuffer.wrap(buffer) .order(...
JAVA
Input Output (FIO)
리틀 μ—”λ””μ•ˆ 데이터λ₯Ό 읽고 μ“°λŠ” λ©”μ„œλ“œλ₯Ό μ œκ³΅ν•˜μ‹­μ‹œμ˜€.
CWE-198, 잘λͺ»λœ λ°”μ΄νŠΈ μˆœμ„œ μ‚¬μš©
try { DataInputStream dis = new DataInputStream(new FileInputStream("data")); // λ¦¬ν‹€μ—”λ””μ•ˆ ν˜•μ‹μ˜ 데이터λ₯Ό λΉ…μ—”λ””μ•ˆμœΌλ‘œ 읽음 int serialNumber = dis.readInt(); } catch (IOException e) { // 였λ₯˜ 처리 }
public static int readLittleEndianInteger(InputStream is) throws IOException { byte[] buffer = new byte[4]; if (is.read(buffer) != 4) { throw new IOException("μ˜ˆμƒμΉ˜ λͺ»ν•œ 슀트림 μ’…λ£Œ"); } return (buffer[3] << 24) | ((buffer[2] & 0xFF) << 16) | ((buffer[1] & 0xFF) << 8) | (buffer[0] & 0xFF); } public static ...
JAVA
Input Output (FIO)
μ‹ λ’° 경계λ₯Ό λ²—μ–΄λ‚œ 곳에 λ―Όκ°ν•œ 정보λ₯Ό κΈ°λ‘ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-359 ν”„λΌμ΄λ²„μ‹œ μΉ¨ν•΄, CWE-532 둜그 νŒŒμΌμ„ ν†΅ν•œ 정보 λ…ΈμΆœ, CWE-533 μ„œλ²„ 둜그 νŒŒμΌμ„ ν†΅ν•œ 정보 λ…ΈμΆœ, CWE-542 정리 둜그 νŒŒμΌμ„ ν†΅ν•œ 정보 λ…ΈμΆœ
public void logRemoteIPAddress(String name) { Logger logger = Logger.getLogger("com.organization.Log"); InetAddress machine = null; try { machine = InetAddress.getByName(name); } catch (UnknownHostException e) { Exception e = MyExceptionReporter.handle(e); } catch (SecurityException e) { Exception...
// ... catch (SecurityException e) { Exception e = MyExceptionReporter.handle(e); }
JAVA
Input Output (FIO)
μ‹ λ’° 경계λ₯Ό λ²—μ–΄λ‚œ 곳에 λ―Όκ°ν•œ 정보λ₯Ό κΈ°λ‘ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-359 ν”„λΌμ΄λ²„μ‹œ μΉ¨ν•΄, CWE-532 둜그 νŒŒμΌμ„ ν†΅ν•œ 정보 λ…ΈμΆœ, CWE-533 μ„œλ²„ 둜그 νŒŒμΌμ„ ν†΅ν•œ 정보 λ…ΈμΆœ, CWE-542 정리 둜그 νŒŒμΌμ„ ν†΅ν•œ 정보 λ…ΈμΆœ
logger.info("Age: " + passengerAge);
// Make sure that all handlers only print log messages rated INFO or higher Handler handlers[] = logger.getHandlers(); for (int i = 0; i < handlers.length; i++) { handlers[i].setLevel(Level.INFO); } // ... logger.finest("Age: " + passengerAge);
JAVA
Input Output (FIO)
ν”„λ‘œκ·Έλž¨ μ’…λ£Œ μ‹œ μ μ ˆν•œ 정리 μž‘μ—…μ„ μˆ˜ν–‰ν•˜λΌ
CWE-705 잘λͺ»λœ μ œμ–΄ 흐름 λ²”μœ„ μ§€μ •
public class CreateFile { public static void main(String[] args) throws FileNotFoundException { final PrintStream out = new PrintStream(new BufferedOutputStream( new FileOutputStream("foo.txt"))); out.println("hello"); Runtime.getRuntime().exit(1); } }
public class CreateFile { public static void main(String[] args) throws FileNotFoundException { final PrintStream out = new PrintStream(new BufferedOutputStream( new FileOutputStream("foo.txt"))); try { out.println("hello"); } finally { out.close(); } Runtime.getRuntime().exit(...
JAVA
Input Output (FIO)
ν”„λ‘œκ·Έλž¨ μ’…λ£Œ μ‹œ μ μ ˆν•œ 정리 μž‘μ—…μ„ μˆ˜ν–‰ν•˜λΌ
CWE-705 잘λͺ»λœ μ œμ–΄ 흐름 λ²”μœ„ μ§€μ •
public class CreateFile { public static void main(String[] args) throws FileNotFoundException { final PrintStream out = new PrintStream(new BufferedOutputStream( new FileOutputStream("foo.txt"))); out.println("hello"); Runtime.getRuntime().exit(1); } }
public class CreateFile { public static void main(String[] args) throws FileNotFoundException { final PrintStream out = new PrintStream(new BufferedOutputStream( new FileOutputStream("foo.txt"))); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { out.cl...
JAVA
Input Output (FIO)
μ»€λ°‹λœ μ„œλΈ”λ¦Ώμ˜ 좜λ ₯ μŠ€νŠΈλ¦Όμ„ μž¬μ„€μ •ν•˜μ§€ 마라
null
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ServletOutputStream out = response.getOutputStream(); try { out.println("<html>"); // ... 응닡 λ‚΄μš© μž‘μ„± out.flush(); // μŠ€νŠΈλ¦Όμ„ 컀밋함 // ... μΆ”κ°€ μž‘μ—… μˆ˜ν–‰ } catch (IOException x) { response....
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { // 좜λ ₯ μŠ€νŠΈλ¦Όμ„ μ‚¬μš©ν•˜μ§€ μ•ŠλŠ” μž‘μ—… μˆ˜ν–‰ } catch (IOException x) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } ServletOutputStream out = response.getOutputStre...
JAVA
Input Output (FIO)
μ»€λ°‹λœ μ„œλΈ”λ¦Ώμ˜ 좜λ ₯ μŠ€νŠΈλ¦Όμ„ μž¬μ„€μ •ν•˜μ§€ 마라
null
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ServletOutputStream out = response.getOutputStream(); try { out.println("<html>"); // ... 응닡 λ‚΄μš© μž‘μ„± out.flush(); // μŠ€νŠΈλ¦Όμ„ 컀밋함 // ... μΆ”κ°€ μž‘μ—… μˆ˜ν–‰ } catch (IOException x) { out.print...
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { try { // 좜λ ₯ μŠ€νŠΈλ¦Όμ„ μ‚¬μš©ν•˜μ§€ μ•ŠλŠ” μž‘μ—… μˆ˜ν–‰ } catch (IOException x) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } ServletOutputStream out = response.getOutputStre...
JAVA
Input Output (FIO)
경둜 이름을 κ²€μ¦ν•˜κΈ° 전에 μ •κ·œν™”ν•˜λΌ
CWE-171 정리, ν‘œμ€€ν™” 및 비ꡐ 였λ₯˜, CWE-647 κΆŒν•œ λΆ€μ—¬ 결정에 ν‘œμ€€ν™”λ˜μ§€ μ•Šμ€ URL 경둜 μ‚¬μš©
public void processFile(String filename) throws IOException { // /img/ 디렉토리 λ‚΄μ˜ 파일만 μ²˜λ¦¬ν•˜λ €κ³  μ‹œλ„ File file = new File("/img/" + filename); if (!file.getCanonicalPath().startsWith("/img/")) { throw new SecurityException("ν—ˆμš©λ˜μ§€ μ•Šμ€ 파일 μ ‘κ·Ό μ‹œλ„"); } // 파일 처리 둜직 }
public void processFile(String filename) throws IOException { // μ‚¬μš©μžκ°€ μ œκ³΅ν•œ 경둜λ₯Ό μ •κ·œν™” File file = new File("/img/", filename).getCanonicalFile(); // μ •κ·œν™”λœ κ²½λ‘œκ°€ /img/ λ””λ ‰ν† λ¦¬λ‘œ μ‹œμž‘ν•˜λŠ”μ§€ 확인 if (!file.getPath().startsWith(new File("/img/").getCanonicalPath())) { throw new SecurityException("ν—ˆμš©λ˜μ§€ μ•Šμ€ 파일 μ ‘κ·Ό μ‹œλ„"); ...
JAVA
Serialization (SER)
클래슀 μ§„ν™” μ‹œ 직렬화 ν˜Έν™˜μ„±μ„ ν™œμ„±ν™”ν•˜λΌ
CWE-589, Call to Non-ubiquitous API
class GameWeapon implements Serializable { int numOfWeapons = 10; public String toString() { return String.valueOf(numOfWeapons); } }
class GameWeapon implements Serializable { private static final long serialVersionUID = 24L; // λͺ…μ‹œμ μΈ serialVersionUID μ •μ˜ int numOfWeapons = 10; public String toString() { return String.valueOf(numOfWeapons); } }
JAVA
Serialization (SER)
클래슀 μ§„ν™” μ‹œ 직렬화 ν˜Έν™˜μ„±μ„ ν™œμ„±ν™”ν•˜λΌ
CWE-589, Call to Non-ubiquitous API
class GameWeapon implements Serializable { int numOfWeapons = 10; public String toString() { return String.valueOf(numOfWeapons); } }
class WeaponStore implements Serializable { int numOfWeapons = 10; // 총 무기 수 } public class GameWeapon implements Serializable { WeaponStore ws = new WeaponStore(); private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField("ws", WeaponStore.class) }; private vo...