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(); } GameEntry t = (GameEntry) that; return (value == t.value) ? 0 : (value == Roshambo.ROCK && t.value == Roshambo.PAPER) ? -1 : (value == Roshambo.PAPER && t.value == Roshambo.SCISSORS) ? -1 : (value == Roshambo.SCISSORS && t.value == Roshambo.ROCK) ? -1 : 1; } }
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) that; return (value == t.value) ? 0 : (value == Roshambo.ROCK && t.value == Roshambo.PAPER) ? -1 : (value == Roshambo.PAPER && t.value == Roshambo.SCISSORS) ? -1 : (value == Roshambo.SCISSORS && t.value == Roshambo.ROCK) ? -1 : 1; } }
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(double empSalary) { this.salary = empSalary; } @Override public boolean equals(Object o) { if (!(o instanceof Employee)) { return false; } Employee emp = (Employee)o; return emp.name.equals(name); } public int hashCode() {/* ... */} } // Client code Map<Employee, Calendar> map = new ConcurrentHashMap<Employee, Calendar>(); // ...
// 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; } // ... @Override public boolean equals(Object o) { if (!(o instanceof Employee)) { return false; } Employee emp = (Employee)o; return emp.employeeID == employeeID; } } // Client code remains same Map<Employee, Calendar> map = new ConcurrentHashMap<Employee, Calendar>(); // ...
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, "Value"); System.out.println("Entry: " + ht.get(key)); // Retrieve using the key, works // Serialize the Hashtable object FileOutputStream fos = new FileOutputStream("hashdata.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(ht); oos.close(); // Deserialize the Hashtable object FileInputStream fis = new FileInputStream("hashdata.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Hashtable<MyKey, String> ht_in = (Hashtable<MyKey, String>)(ois.readObject()); ois.close(); if (ht_in.contains("Value")) // Check whether the object actually exists in the hash table System.out.println("Value was found in deserialized object."); if (ht_in.get(key) == null) // Gets printed System.out.println( "Object was not found when retrieved using the key."); } }
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 // Serialize the Hashtable object FileOutputStream fos = new FileOutputStream("hashdata.ser"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(ht); oos.close(); // Deserialize the Hashtable object FileInputStream fis = new FileInputStream("hashdata.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Hashtable<Integer, String> ht_in = (Hashtable<Integer, String>)(ois.readObject()); ois.close(); if (ht_in.contains("Value")) // Check whether the object actually exists in the Hashtable System.out.println("Value was found in deserialized object."); if (ht_in.get(1) == null) // Not printed System.out.println( "Object was not found when retrieved using the key."); } }
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 field protected SubClass() { d = new Date(); } protected void finalize() throws Throwable { System.out.println("Subclass finalize!"); try { // Cleanup resources d = null; } finally { super.finalize(); // Call BaseClass's finalizer } } public void doLogic() throws Throwable { // Any resource allocations made here will persist // Inconsistent object state System.out.println( "This is sub-class! The date object is: " + d); // 'd' is already null } } public class BadUse { public static void main(String[] args) { try { BaseClass bc = new SubClass(); // Artificially simulate finalization (do not do this) System.runFinalizersOnExit(true); } catch (Throwable t) { // Handle error } } }
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 field protected SubClass() { d = new Date(); } protected void finalize() throws Throwable { System.out.println("Subclass finalize!"); try { // Cleanup resources d = null; } finally { super.finalize(); // Call BaseClass's finalizer } } public void doLogic() throws Throwable { // Any resource allocations made here will persist // Inconsistent object state System.out.println( "This is sub-class! The date object is: " + d); // 'd' is already null } } public class BadUse { public static void main(String[] args) { try { BaseClass bc = new SubClass(); // Artificially simulate finalization (do not do this) System.runFinalizersOnExit(true); } catch (Throwable t) { // Handle error } } }
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); // Use the file
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; } } catch (IOException x) { System.out.println("Invalid file"); return; } try { FileInputStream fis = new FileInputStream(file); } catch (FileNotFoundException x) { 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"); break; //... default: System.out.println("Invalid option"); break; } } catch (Throwable t) { MyExceptionReporter.report(t); // Sanitize } } }
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; } 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 || weight <= 0 || weight > 20) { throw new IllegalArgumentException(); } int volume = length * width * height; length -= PADDING; width -= PADDING; height -= PADDING; // Revert return volume; } catch (Throwable t) { MyExceptionReporter mer = new MyExceptionReporter(); mer.report(t); // Sanitize return -1; // Non-positive error code } } public static void main(String[] args) { Dimensions d = new Dimensions(8, 8, 8); System.out.println(d.getVolumePackage(21)); // Prints -1 (error) System.out.println(d.getVolumePackage(19)); // Prints 1728 (12x12x12) instead of 1000 (10x10x10) } }
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 || weight <= 0 || weight > 20) { throw new IllegalArgumentException(); } int volume = length * width * height; return volume; } catch (Throwable t) { MyExceptionReporter mer = new MyExceptionReporter(); mer.report(t); // Sanitize return -1; // Non-positive error code } finally { // Revert length -= PADDING; width -= PADDING; height -= PADDING; } }
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(); // ... Other cleanup code ... } } catch (IOException x) { // Forward to handler } } }
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.close(); } catch (IOException ie) { // Forward to handler } // ... Other cleanup code ... } } catch (IOException x) { // Forward to handler } } }
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 || throwable instanceof InstantiationException) { // Unchecked, no declaration required throw new IllegalArgumentException(); } NewInstance.throwable = throwable; try { // Next line throws the Throwable argument passed in above, // even though the throws clause of class.newInstance fails // to declare that this may happen NewInstance.class.newInstance(); } catch (InstantiationException e) { /* Unreachable */ } catch (IllegalAccessException e) { /* Unreachable */ } finally { // Avoid memory leak NewInstance.throwable = null; } } } public class UndeclaredException { public static void main(String[] args) { // No declared checked exceptions NewInstance.undeclaredThrow( new Exception("Any checked exception")); } }
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(); } NewInstance.throwable = throwable; try { Constructor constructor = NewInstance.class.getConstructor(new Class<?>[0]); constructor.newInstance(); } catch (InstantiationException e) { /* Unreachable */ } catch (IllegalAccessException e) { /* Unreachable */ } catch (InvocationTargetException e) { System.out.println("Exception thrown: " + e.getCause().toString()); } finally { // Avoid memory leak NewInstance.throwable = null; } }
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 } } public class ConsoleLog implements Log { public void write(String messageToLog) { System.out.println(messageToLog); // Write message to console } } class Service { private Log log; Service() { this.log = null; // No logger } Service(Log log) { this.log = log; // Set the specified logger } public void handle() { try { log.write("Request received and handled"); } catch (NullPointerException npe) { // Ignore } } public static void main(String[] args) throws IOException { Service s = new Service(new FileLog("logfile.log")); s.handle(); s = new Service(new ConsoleLog()); s.handle(); } }
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(String[] args) { try { division(200, 5); division(200, 0); // Divide by zero } catch (Exception e) { System.out.println("Divide by zero exception : " + e.getMessage()); } } }
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(); } catch (IOException ex) { ExceptionReporter.report(ex); } } 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); } }
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 (!isExitAllowed()) { throw new SecurityException(); } super.checkExit(status); } public void setExitAllowed(boolean f) { isExitAllowedFlag = f; } } public class InterceptExit { public static void main(String[] args) { PasswordSecurityManager secManager = new PasswordSecurityManager(); System.setSecurityManager(secManager); try { // ... System.exit(1); // Abrupt exit call } catch (Throwable x) { if (x instanceof SecurityException) { System.out.println("Intercepted System.exit()"); // Log exception } else { // Forward to exception handler } } // ... secManager.setExitAllowed(true); // Permit exit // System.exit() will work subsequently // ... } }
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 interrupted status } } } public void shutdown() { done = true; } }
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(); // Reset interrupted status } } } public void shutdown() { done = true; } }
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 interrupted status } } } public void shutdown() { done = true; } }
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.currentThread().interrupt(); // Reset interrupted status } } } public void shutdown() { done.set(true); } }
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 interrupted status } } } public void shutdown() { done = true; } }
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 interrupted status } } } public synchronized boolean isDone() { return done; } public synchronized void shutdown() { done = true; } }
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 s) { // Unsafe first.set(f); second.set(s); } public BigInteger add() { // Unsafe return first.get().add(second.get()); } }
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(BigInteger f, BigInteger s){ first.set(f); second.set(s); } public synchronized BigInteger add() { return first.get().add(second.get()); } }
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 through array addressCopy ... } }
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 InetAddress[0]); // Iterate through array addressCopy ... } } }
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 ArithmeticException("Out of range"); } map.put( key, oldValue + 1); } public Integer getCount(String key) { return map.get(key); } }
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 (oldValue == Integer.MAX_VALUE) { throw new ArithmeticException("Out of range"); } map.put(key, oldValue + 1); } } public Integer getCount(String key) { synchronized (lock) { return map.get(key); } } }
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 this; } public USCurrency setDimes(int quantity) { dimes = quantity; return this; } public USCurrency setNickels(int quantity) { nickels = quantity; return this; } public USCurrency setPennies(int quantity) { pennies = quantity; return this; } } // Client code: class ExampleClientCode { private final USCurrency currency = new USCurrency(); // ... public ExampleClientCode() { Thread t1 = new Thread(new Runnable() { @Override public void run() { currency.setQuarters(1).setDimes(1); } }); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { currency.setQuarters(2).setDimes(2); } }); t2.start(); //... } }
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.pennies; } // Static class member public static class Builder { private int quarters = 0; private int dimes = 0; private int nickels = 0; private int pennies = 0; public static Builder newInstance() { return new Builder(); } private Builder() {} // Setter methods public Builder setQuarters(int quantity) { this.quarters = quantity; return this; } public Builder setDimes(int quantity) { this.dimes = quantity; return this; } public Builder setNickels(int quantity) { this.nickels = quantity; return this; } public Builder setPennies(int quantity) { this.pennies = quantity; return this; } public USCurrency build() { return new USCurrency(this); } } } // Client code: class ExampleClientCode { private volatile USCurrency currency; // ... public ExampleClientCode() { Thread t1 = new Thread(new Runnable() { @Override public void run() { currency = USCurrency.Builder.newInstance(). setQuarters(1).setDimes(1).build(); } }); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { currency = USCurrency.Builder.newInstance(). setQuarters(2).setDimes(2).build(); } }); t2.start(); //... } }
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 ParseException { synchronized (Base.class) { // ... return format.parse(str); } } }
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 setView for (Integer k : setView) { // ... } } }
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 set for (Integer k : setView) { // ... } } }
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++) { new Thread(new CountBoxes()).start(); } } }
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 > balanceAmount) { throw new IllegalArgumentException("이체λ₯Ό μ™„λ£Œν•  수 μ—†μŠ΅λ‹ˆλ‹€"); } ba.balanceAmount += amount; this.balanceAmount -= amount; } } } public static void initiateTransfer(final BankAccount first, final BankAccount second, final double amount) { Thread transfer = new Thread(new Runnable() { public void run() { first.depositAmount(second, amount); } }); transfer.start(); } }
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 = nextID.getAndIncrement(); } @Override public int compareTo(BankAccount ba) { return Long.compare(this.id, ba.id); } // 이 객체 μΈμŠ€ν„΄μŠ€μ—μ„œ μ£Όμ–΄μ§„ BankAccount μΈμŠ€ν„΄μŠ€λ‘œ κΈˆμ•‘μ„ μž…κΈˆ public void depositAmount(BankAccount ba, double amount) { BankAccount former, latter; if (compareTo(ba) < 0) { former = this; latter = ba; } else { former = ba; latter = this; } synchronized (former) { synchronized (latter) { if (amount > balanceAmount) { throw new IllegalArgumentException("이체λ₯Ό μ™„λ£Œν•  수 μ—†μŠ΅λ‹ˆλ‹€"); } ba.balanceAmount += amount; this.balanceAmount -= amount; } } } public static void initiateTransfer(final BankAccount first, final BankAccount second, final double amount) { Thread transfer = new Thread(new Runnable() { public void run() { first.depositAmount(second, amount); } }); transfer.start(); } }
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.unlock(); if (in != null) { try { in.close(); } catch (IOException e) { // μ˜ˆμ™Έ 처리 } } } } }
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 != null) { try { in.close(); } catch (IOException e) { // μ˜ˆμ™Έ 처리 } } lock.unlock(); } } }
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 ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); // Find the Page requested by the client // (this operation requires synchronization) Page targetPage = null; for (Page p : pageBuff) { if (p.getName().compareTo(pageName) == 0) { targetPage = p; } } // Requested Page does not exist if (targetPage == null) { return false; } // Send the Page to the client // (does not require any synchronization) out.writeObject(targetPage); out.flush(); out.close(); return true; }
// 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 = null; for (Page p : pageBuff) { if (p.getName().equals(pageName)) { targetPage = p; } } return targetPage; } // Return false if an error occurs, true if successful public boolean deliverPage(Socket socket, Page page) { ObjectOutputStream out = null; boolean result = true; try { // Get the output stream to write the Page to out = new ObjectOutputStream(socket.getOutputStream()); // Send the page to the client out.writeObject(page);out.flush(); } catch (IOException io) { result = false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { result = false; } } } return result; }
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() { return dateDue; } } public class BookWrapper { private final Book book; public BookWrapper(Book book) { this.book = book; } public void renew() { synchronized (book) { if (book.getDueDate().before(Calendar.getInstance())) { throw new IllegalStateException("Book overdue"); } else { book.issue(14); } } } }
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.DATE, days); } } public Calendar getDueDate() { synchronized (lock) { return dateDue; } } public void renew() { synchronized (lock) { if (getDueDate().before(Calendar.getInstance())) { throw new IllegalStateException("Book overdue"); } else { issue(14); } } } }
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 Thread(tg, new HandleRequest(), "thread2").start(); new Thread(tg, new HandleRequest(), "thread3").start(); } public static void printActiveCount(int point) { System.out.println("Active Threads in Thread Group " + tg.getName() + " at point(" + point + "):" + " " + tg.activeCount()); } public static void printEnumeratedThreads(Thread[] ta, int len) { System.out.println("Enumerating all threads..."); for (int i = 0; i < len; i++) { System.out.println("Thread " + i + " = " + ta[i].getName()); } } public static void main(String[] args) throws InterruptedException { // Start thread controller Thread thread = new Thread(tg, new NetworkHandler(), "controller"); thread.start(); // Gets the active count (insecure) Thread[] ta = new Thread[tg.activeCount()]; printActiveCount(1); // P1 // Delay to demonstrate TOCTOU condition (race window) Thread.sleep(1000); // P2: the thread count changes as new threads are initiated printActiveCount(2); // Incorrectly uses the (now stale) thread count obtained at P1 int n = tg.enumerate(ta); // Silently ignores newly initiated threads printEnumeratedThreads(ta, n); // (between P1 and P2) // This code destroys the thread group if it does // not have any live threads for (Thread thr : ta) { thr.interrupt(); while(thr.isAlive()); } tg.destroy(); } }
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 shutdownPool() { executor.shutdown(); } public static void main(String[] args) { NetworkHandler nh = new NetworkHandler(3); nh.startThreads(); nh.shutdownPool(); } }
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); this.in = new BufferedReader( new InputStreamReader(this.socket.getInputStream()) ); } @Override public void run() { try { synchronized (lock) { readData(); } } catch (IOException ie) { // μ˜ˆμ™Έ 처리 } } public void readData() throws IOException { String string; while (!done && (string = in.readLine()) != null) { // 데이터 처리 } } public void shutdown() { done = true; } public static void main(String[] args) throws IOException, InterruptedException { SocketReader reader = new SocketReader("somehost", 25); Thread thread = new Thread(reader); thread.start(); Thread.sleep(1000); reader.shutdown(); // μŠ€λ ˆλ“œ μ’…λ£Œ μ‹œλ„ } }
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); this.in = new BufferedReader( new InputStreamReader(this.socket.getInputStream()) ); } @Override public void run() { try { synchronized (lock) { readData(); } } catch (IOException ie) { // μ˜ˆμ™Έ 처리 } } public void readData() throws IOException { String string; while (!done && (string = in.readLine()) != null) { // 데이터 처리 } } public void shutdown() throws IOException { done = true; socket.close(); // μ†ŒμΌ“μ„ λ‹«μ•„ λΈ”λ‘œν‚Ή μƒνƒœ ν•΄μ œ } public static void main(String[] args) throws IOException, InterruptedException { SocketReader reader = new SocketReader("somehost", 25); Thread thread = new Thread(reader); thread.start(); Thread.sleep(1000); reader.shutdown(); // μŠ€λ ˆλ“œ μ’…λ£Œ } }
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 static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Container()); thread.start(); Thread.sleep(5000); thread.stop(); // λΉ„κΆŒμž₯: μŠ€λ ˆλ“œλ₯Ό κ°•μ œ μ’…λ£Œ } }
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(); while (!done && i > 0) { vector.add(number.nextInt(100)); i--; } } public static void main(String[] args) throws InterruptedException { Container container = new Container(); Thread thread = new Thread(container); thread.start(); Thread.sleep(5000); container.shutdown(); // μ•ˆμ „ν•˜κ²Œ μŠ€λ ˆλ“œ μ’…λ£Œ μš”μ²­ } }
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 static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new Container()); thread.start(); Thread.sleep(5001); thread.stop(); // λΉ„κΆŒμž₯: μŠ€λ ˆλ“œλ₯Ό κ°•μ œ μ’…λ£Œ } }
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--; } } public static void main(String[] args) throws InterruptedException { Container container = new Container(); Thread thread = new Thread(container); thread.start(); Thread.sleep(5000); thread.interrupt(); // μŠ€λ ˆλ“œμ— μΈν„°λŸ½νŠΈ μ‹ ν˜Έ 전솑 } }
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 newInstance() throws IOException { return new RequestHandler(0); // Selects next available port } public void handleRequest() { new Thread(new Runnable() { public void run() { try { helper.handle(server.accept()); } catch (IOException e) { // Forward to handler } } }).start(); } }
// 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.newFixedThreadPool(poolSize); } public static RequestHandler newInstance(int poolSize) throws IOException { return new RequestHandler(0, poolSize); } public void handleRequest() { Future<?> future = exec.submit(new Runnable() { @Override public void run() { try { helper.handle(server.accept()); } catch (IOException e) { // Forward to handler } } }); } // ... Other methods such as shutting down the thread pool // and task cancellation ... }
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 InterruptedException, ExecutionException { StringBuilder sb = new StringBuilder(); // Stores the results Future<String>[] results = new Future[inputs.length]; // Submits the tasks to thread pool for (int i = 0; i < inputs.length; i++) { results[i] = pool.submit( new ValidateInput<String>(inputs[i], pool)); } for (int i = 0; i < inputs.length; i++) { // Aggregates the results sb.append(results[i].get()); } return sb; } } public final class ValidateInput<V> implements Callable<V> { private final V input; private final ExecutorService pool; ValidateInput(V input, ExecutorService pool) { this.input = input; this.pool = pool; } @Override public V call() throws Exception { // If validation fails, throw an exception here // Subtask Future<V> future = pool.submit(new SanitizeInput<V>(input)); return (V) future.get(); } } public final class SanitizeInput<V> implements Callable<V> { private final V input; SanitizeInput(V input) { this.input = input; } @Override public V call() throws Exception { // Sanitize input and return return (V) input; } }
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])); } // ... } } // Does not use same thread pool public final class ValidateInput<V> implements Callable<V> { private final V input; ValidateInput(V input) { this.input = input; } @Override public V call() throws Exception { // If validation fails, throw an exception here return (V) new SanitizeInput().sanitize(input); } } public final class SanitizeInput<V> { // No longer a Callable task public SanitizeInput() {} public V sanitize(V input) { // Sanitize input and return return input; } }
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() { methodInvoker(numberOfTimes, "perProfile"); pool.shutdown(); } public void perProfile() { methodInvoker(numberOfTimes, "perTab"); } public void perTab() { methodInvoker(numberOfTimes, "doSomething"); } public void doSomething() { System.out.println(count.getAndIncrement()); } public void methodInvoker(int n, final String method) { final BrowserManager manager = this; Callable<Object> callable = new Callable<Object>() { @Override public Object call() throws Exception { Method meth = manager.getClass().getMethod(method); return meth.invoke(manager); } }; Collection<Callable<Object>> collection = Collections.nCopies(n, callable); try { Collection<Future<Object>> futures = pool.invokeAll(collection); } catch (InterruptedException e) { // Forward to handler Thread.currentThread().interrupt(); // Reset interrupted status } // ... } public static void main(String[] args) { BrowserManager manager = new BrowserManager(5); manager.perUser(); } }
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 static { pool.setRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy()); } // ... }
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 BufferedReader( new InputStreamReader(this.socket.getInputStream()) ); } // Only one thread can use the socket at a particular time @Override public void run() { try { synchronized (lock) { readData(); } } catch (IOException ie) { // Forward to handler } } public void readData() throws IOException { String string; try { while ((string = in.readLine()) != null) { // Blocks until end of stream (null) } } finally { shutdown(); } } public void shutdown() throws IOException { socket.close(); } } public final class PoolService { private final ExecutorService pool; public PoolService(int poolSize) { pool = Executors.newFixedThreadPool(poolSize); } public void doSomething() throws InterruptedException, IOException { pool.submit(new SocketReader("somehost", 8080)); // ... List<Runnable> awaitingTasks = pool.shutdownNow(); } public static void main(String[] args) throws InterruptedException, IOException { PoolService service = new PoolService(5); service.doSomething(); } }
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 = ByteBuffer.allocate(1024); try { synchronized (lock) { while (!Thread.interrupted()) { sc.read(buf); // ... } } } catch (IOException ie) { // Forward to handler } } } public final class PoolService { // ... }
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 keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue ) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); if (t != null) { // μ˜ˆμ™Έ 처리 둜직 } } @Override protected void terminated() { super.terminated(); // μ΅œμ’… 정리 μž‘μ—… } }
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 ExceptionThreadFactory implements ThreadFactory { private static final ThreadFactory defaultFactory = Executors.defaultThreadFactory(); private final Thread.UncaughtExceptionHandler handler; public ExceptionThreadFactory(Thread.UncaughtExceptionHandler handler) { this.handler = handler; } @Override public Thread newThread(Runnable r) { Thread thread = defaultFactory.newThread(r); thread.setUncaughtExceptionHandler(handler); return thread; } } public static class MyExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { // μ˜ˆμ™Έ 처리 둜직 } } }
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 days.get(); } public static void setDay(Day newDay) { days.set(newDay); } public void threadSpecificTask() { // μŠ€λ ˆλ“œλ³„ μž‘μ—… μˆ˜ν–‰ } } 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() { diary.setDay(Day.FRIDAY); diary.threadSpecificTask(); } }); } public void doSomething2() { exec.execute(new Runnable() { @Override public void run() { diary.threadSpecificTask(); } }); } public static void main(String[] args) { DiaryPool dp = new DiaryPool(); dp.doSomething1(); // μŠ€λ ˆλ“œ 1: ν˜„μž¬ μš”μΌμ„ κΈˆμš”μΌλ‘œ μ„€μ • dp.doSomething2(); // μŠ€λ ˆλ“œ 2: ν˜„μž¬ μš”μΌμ„ μ›”μš”μΌλ‘œ κΈ°λŒ€ dp.doSomething2(); // μŠ€λ ˆλ“œ 3: ν˜„μž¬ μš”μΌμ„ μ›”μš”μΌλ‘œ κΈ°λŒ€ } }
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.threadSpecificTask(); } finally { diary.setDay(Day.MONDAY); // μž‘μ—… ν›„ μ΄ˆκΈ°ν™” } } }); } public void doSomething2() { exec.execute(new Runnable() { @Override public void run() { try { diary.threadSpecificTask(); } finally { diary.setDay(Day.MONDAY); // μž‘μ—… ν›„ μ΄ˆκΈ°ν™” } } }); } public static void main(String[] args) { DiaryPool dp = new DiaryPool(); dp.doSomething1(); // μŠ€λ ˆλ“œ 1: ν˜„μž¬ μš”μΌμ„ κΈˆμš”μΌλ‘œ μ„€μ • dp.doSomething2(); // μŠ€λ ˆλ“œ 2: ν˜„μž¬ μš”μΌμ„ μ›”μš”μΌλ‘œ μ„€μ • dp.doSomething2(); // μŠ€λ ˆλ“œ 3: ν˜„μž¬ μš”μΌμ„ μ›”μš”μΌλ‘œ μ„€μ • } }
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 EventListener() { public void onEvent(Event e) { doSomething(e); } }); } void doSomething(Event 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) { SafeListener safe = new SafeListener(); source.registerListener(safe.listener); return safe; } void doSomething(Event e) { // 이벀트 처리 둜직 } }
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("μ—°κ²° λ¬Έμžμ—΄"); } catch (SQLException e) { dbConnection = null; } } }); // 기타 μ΄ˆκΈ°ν™” μž‘μ—…, 예: λ‹€λ₯Έ μŠ€λ ˆλ“œ μ‹œμž‘ dbInitializerThread.start(); try { dbInitializerThread.join(); } catch (InterruptedException ie) { throw new AssertionError(ie); } } public static Connection getConnection() { if (dbConnection == null) { throw new IllegalStateException("μ—°κ²° μ΄ˆκΈ°ν™” 였λ₯˜"); } return dbConnection; } public static void main(String[] args) { // ... Connection connection = getConnection(); } }
public final class ConnectionFactory { private static Connection dbConnection; // 기타 ν•„λ“œ... static { // 메인 μŠ€λ ˆλ“œμ—μ„œ λ°μ΄ν„°λ² μ΄μŠ€ μ—°κ²° μ΄ˆκΈ°ν™” try { dbConnection = DriverManager.getConnection("μ—°κ²° λ¬Έμžμ—΄"); } catch (SQLException e) { dbConnection = null; } // 기타 μ΄ˆκΈ°ν™” μž‘μ—… } public static Connection getConnection() { if (dbConnection == null) { throw new IllegalStateException("μ—°κ²° μ΄ˆκΈ°ν™” 였λ₯˜"); } return dbConnection; } public static void main(String[] args) { // ... Connection connection = getConnection(); } }
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(tempFile)) { writer.write("μž„μ‹œ 데이터"); } catch (IOException e) { e.printStackTrace(); } } }
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 = new File(secureDir, "temp.txt"); try (FileWriter writer = new FileWriter(tempFile)) { writer.write("μž„μ‹œ 데이터"); } catch (IOException e) { e.printStackTrace(); } } }
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<PosixFilePermission> perms = PosixFilePermissions.fromString("rw-------"); FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms); try (SeekableByteChannel sbc = Files.newByteChannel(file, options, attr)) { // Write data };
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"); return; } FileOutputStream fop = null; try { fop = new FileOutputStream(f); String str = "Data"; fop.write(str.getBytes()); } finally { if (fop != null) { try { fop.close(); } catch (IOException x) { // 였λ₯˜ 처리 } } } } }
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"); return; } FileOutputStream fop = null; try { fop = new FileOutputStream(f); String str = "Data"; fop.write(str.getBytes()); } finally { if (fop != null) { try { fop.close(); } catch (IOException x) { // 였λ₯˜ 처리 } } if (!f.delete()) { // 파일 μ‚­μ œ μ‹€νŒ¨ μ‹œ 처리 } } } }
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 = new BufferedReader(new InputStreamReader(stream)); String line; while ((line = bufRead.readLine()) != null) { sendLine(line); } return 1; } private void sendLine(String line) { // 라인 처리 둜직 } }
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 bufRead = new BufferedReader(new InputStreamReader(stream))) { String line; while ((line = bufRead.readLine()) != null) { sendLine(line); } } catch (IOException e) { // μ˜ˆμ™Έ 처리 둜직 } return 1; } private void sendLine(String line) { // 라인 처리 둜직 } }
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 void main(String[] args) { try { System.out.print("Enter first initial: "); char first = getChar(); System.out.println("Your first initial is " + first); System.out.print("Enter last initial: "); char last = getChar(); System.out.println("Your last initial is " + last); } catch (EOFException e) { System.err.println("ERROR"); } catch (IOException e) { System.err.println("ERROR"); } } }
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 main(String[] args) { try { System.out.print("Enter first initial: "); char first = getChar(); System.out.println("Your first initial is " + first); System.out.print("Enter last initial: "); char last = getChar(); System.out.println("Your last initial is " + last); } catch (EOFException e) { System.err.println("ERROR"); } catch (IOException e) { System.err.println("ERROR"); } } }
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"); // 였λ₯˜ 슀트림 처리 StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "ERROR"); // 슀트림 κ³ λΈ”λŸ¬ μŠ€λ ˆλ“œ μ‹œμž‘ outputGobbler.start(); errorGobbler.start(); int exitVal = proc.waitFor(); } }
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 = inputStream; this.type = type; } public void run() { try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = br.readLine()) != null) { System.out.println(type + "> " + line); } } catch (IOException e) { e.printStackTrace(); } } }
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(); } return new String(data, 0, bytesRead, "UTF-8"); }
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(ByteOrder.LITTLE_ENDIAN) .getInt(); } catch (IOException e) { // 였λ₯˜ 처리 }
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 void writeLittleEndianInteger(OutputStream os, int value) throws IOException { os.write(value & 0xFF); os.write((value >> 8) & 0xFF); os.write((value >> 16) & 0xFF); os.write((value >> 24) & 0xFF); }
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 e = MyExceptionReporter.handle(e); logger.severe(name + "," + machine.getHostAddress() + "," + e.toString()); } }
// ... 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(1); } }
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.close(); } })); out.println("hello"); Runtime.getRuntime().exit(1); } }
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.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
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.getOutputStream(); try { out.println("<html>"); // ... 응닡 λ‚΄μš© μž‘μ„± } catch (IOException x) { // 좜λ ₯ 슀트림 μ‚¬μš© 쀑 μ˜ˆμ™Έ λ°œμƒ μ‹œ μ μ ˆν•œ 처리 } finally { out.flush(); } }
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.println(x.getMessage()); out.flush(); } }
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.getOutputStream(); try { out.println("<html>"); // ... 응닡 λ‚΄μš© μž‘μ„± } catch (IOException x) { // 좜λ ₯ 슀트림 μ‚¬μš© 쀑 μ˜ˆμ™Έ λ°œμƒ μ‹œ μ μ ˆν•œ 처리 } finally { out.flush(); } }
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 void writeObject(ObjectOutputStream oos) throws IOException { ObjectOutputStream.PutField pf = oos.putFields(); pf.put("ws", ws); oos.writeFields(); } private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ObjectInputStream.GetField gf = ois.readFields(); this.ws = (WeaponStore) gf.get("ws", ws); } public String toString() { return String.valueOf(ws); } }