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);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.