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
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
같은 데이터에 λΉ„νŠΈ μ—°μ‚°κ³Ό μ‚°μˆ  연산을 λ™μ‹œμ— μˆ˜ν–‰ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
int x = -50; x >>>= 2;
int x = -50; x /= 4;
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
같은 데이터에 λΉ„νŠΈ μ—°μ‚°κ³Ό μ‚°μˆ  연산을 λ™μ‹œμ— μˆ˜ν–‰ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
int x = -50; x >>= 2;
int x = -50; x /= 5;
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
같은 데이터에 λΉ„νŠΈ μ—°μ‚°κ³Ό μ‚°μˆ  연산을 λ™μ‹œμ— μˆ˜ν–‰ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
// b[] is a byte array, initialized to 0xff byte[] b = new byte[] {-1, -1, -1, -1}; int result = 0; for (int i = 0; i < 4; i++) { result = ((result << 8) + b[i]); }
byte[] b = new byte[] {-1, -1, -1, -1}; int result = 0; for (int i = 0; i < 4; i++) { result = ((result << 8) | (b[i] & 0xff)); }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
같은 데이터에 λΉ„νŠΈ μ—°μ‚°κ³Ό μ‚°μˆ  연산을 λ™μ‹œμ— μˆ˜ν–‰ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
byte[] b = new byte[] {-1, -1, -1, -1}; int result = 0; for (int i = 0; i < 4; i++) { result = ((result << 8) + (b[i] & 0xff)); }
byte[] b = new byte[] {-1, -1, -1, -1}; int result = 0; for (int i = 0; i < 4; i++) { result = ((result << 8) | (b[i] & 1xff)); }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
λ‚˜λˆ—μ…ˆκ³Ό λ‚˜λ¨Έμ§€ 연산이 0으둜 λ‚˜λˆ„κΈ° 였λ₯˜λ₯Ό μΌμœΌν‚€μ§€ μ•Šλ„λ‘ ν•˜μ‹­μ‹œμ˜€.
null
long num1, num2, result; /* Initialize num1 and num2 */ result = num1 / num2;
long num1, num2, result; /* Initialize num1 and num2 */ if (num2 == 0) { // Handle error } else { result = num1 / num2; }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
λ‚˜λˆ—μ…ˆκ³Ό λ‚˜λ¨Έμ§€ 연산이 1으둜 λ‚˜λˆ„κΈ° 였λ₯˜λ₯Ό μΌμœΌν‚€μ§€ μ•Šλ„λ‘ ν•˜μ‹­μ‹œμ˜€.
null
long num1, num2, result; /* Initialize num1 and num2 */ result = num1 % num2;
long num1, num2, result; /* Initialize num1 and num2 */ if (num2 == 0) { // Handle error } else { result = num1 % num2; }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
λΆ€ν˜Έ μ—†λŠ” λ°μ΄ν„°μ˜ κ°€λŠ₯ν•œ λ²”μœ„λ₯Ό μ™„μ „νžˆ ν‘œν˜„ν•  수 μžˆλŠ” μ •μˆ˜ νƒ€μž…μ„ μ‚¬μš©ν•˜μ‹­μ‹œμ˜€.
null
public static int getInteger(DataInputStream is) throws IOException { return is.readInt(); }
public static long getInteger(DataInputStream is) throws IOException { return is.readInt() & 0xFFFFFFFFL; // Mask with 32 one-bits }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
NaN과의 비ꡐλ₯Ό μ‹œλ„ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public class NaNComparison { public static void main(String[] args) { double x = 0.0; double result = Math.cos(1/x); // Returns NaN if input is infinity if (result == Double.NaN) { // Comparison is always false! System.out.println("result is NaN"); } } }
public class NaNComparison { public static void main(String[] args) { double x = 0.0; double result = Math.cos(1/x); // Returns NaN when input is infinity if (Double.isNaN(result)) { System.out.println("result is NaN"); } } }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
뢀동 μ†Œμˆ˜μ  μž…λ ₯에 μ˜ˆμ™Έμ μΈ 값이 μžˆλŠ”μ§€ ν™•μΈν•˜μ‹­μ‹œμ˜€.
null
double currentBalance; // User's cash balance void doDeposit(String userInput) { double val = 0; try { val = Double.valueOf(userInput); } catch (NumberFormatException e) { // Handle input format error } if (val >= Double.MAX_VALUE - currentBalance) { // Handle range error } currentBalance += val; }
double currentBalance; // User's cash balance void doDeposit(String userInput){ double val = 0; try { val = Double.valueOf(userInput); } catch (NumberFormatException e) { // Handle input format error } if (Double.isInfinite(val)){ // Handle infinity error } if (Double.isNaN(val)) { // Handle NaN error } if (val >= Double.MAX_VALUE - currentBalance) { // Handle range error } currentBalance += val; }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
뢀동 μ†Œμˆ˜μ  λ³€μˆ˜λ₯Ό 반볡(loop) μΉ΄μš΄ν„°λ‘œ μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
for (float x = 0.1f; x <= 1.0f; x += 0.1f) { System.out.println(x); }
for (int count = 1; count <= 10; count += 1) { float x = count/10.0f; System.out.println(x); }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
뢀동 μ†Œμˆ˜μ  λ³€μˆ˜λ₯Ό 반볡(loop) μΉ΄μš΄ν„°λ‘œ μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
for (float x = 100000001.0f; x <= 100000010.0f; x += 1.0f) { /* ... */ }
for (int count = 1; count <= 10; count += 1) { double x = 100000000.0 + count; /* ... */ }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
뢀동 μ†Œμˆ˜μ  λ¦¬ν„°λŸ΄λ‘œλΆ€ν„° BigDecimal 객체λ₯Ό μƒμ„±ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
// Prints 0.1000000000000000055511151231257827021181583404541015625 // when run in FP-strict mode System.out.println(new BigDecimal(0.1));
// Prints 0.1 // when run in FP-strict mode System.out.println(new BigDecimal("0.1"));
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
뢀동 μ†Œμˆ˜μ  κ°’μ˜ λ¬Έμžμ—΄ ν‘œν˜„μ„ λΉ„κ΅ν•˜κ±°λ‚˜ κ²€μ‚¬ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
int i = 1; String s = Double.valueOf(i / 10000.0).toString(); if (s.equals("0.0001")) { // ... }
int i = 1; BigDecimal d = new BigDecimal(Double.valueOf(i / 10000.0).toString()); if (d.compareTo(new BigDecimal("0.0001")) == 0) { // ... }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
숫자 νƒ€μž…μ„ 더 쒁은 νƒ€μž…μœΌλ‘œ λ³€ν™˜ν•  λ•Œ 데이터 μ†μ‹€μ΄λ‚˜ 잘λͺ» ν•΄μ„λ˜λŠ” 일이 없도둝 ν•˜μ‹­μ‹œμ˜€.
null
class CastAway { public static void main(String[] args) { int i = 128; workWith(i); } public static void workWith(int i) { byte b = (byte) i; // b has value -128 // Work with b } }
class CastAway { public static void workWith(int i) { // Check whether i is within byte range if ((i < Byte.MIN_VALUE) || (i > Byte.MAX_VALUE)) { throw new ArithmeticException("Value is out of range"); } byte b = (byte) i; // Work with b } }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
숫자 νƒ€μž…μ„ 더 쒁은 νƒ€μž…μœΌλ‘œ λ³€ν™˜ν•  λ•Œ 데이터 μ†μ‹€μ΄λ‚˜ 잘λͺ» ν•΄μ„λ˜λŠ” 일이 없도둝 ν•˜μ‹­μ‹œμ˜€.
null
class CastAway { public static void main(String[] args) { int i = 128; workWith(i); } public static void workWith(int i) { byte b = (byte) i; // b has value -128 // Work with b } }
class CastAway { public static void workWith(int i) { byte b = (byte)(i % 0x100); // 2^8; // Work with b } }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
숫자 νƒ€μž…μ„ 더 쒁은 νƒ€μž…μœΌλ‘œ λ³€ν™˜ν•  λ•Œ 데이터 μ†μ‹€μ΄λ‚˜ 잘λͺ» ν•΄μ„λ˜λŠ” 일이 없도둝 ν•˜μ‹­μ‹œμ˜€.
null
float i = Float.MIN_VALUE; float j = Float.MAX_VALUE; short b = (short) i; short c = (short) j;
float i = Float.MIN_VALUE; float j = Float.MAX_VALUE; if ((i < Short.MIN_VALUE) || (i > Short.MAX_VALUE) || (j < Short.MIN_VALUE) || (j > Short.MAX_VALUE)) { throw new ArithmeticException ("Value is out of range"); } short b = (short) i; short c = (short) j; // Other operations
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
숫자 νƒ€μž…μ„ 더 쒁은 νƒ€μž…μœΌλ‘œ λ³€ν™˜ν•  λ•Œ 데이터 μ†μ‹€μ΄λ‚˜ 잘λͺ» ν•΄μ„λ˜λŠ” 일이 없도둝 ν•˜μ‹­μ‹œμ˜€.
null
double i = Double.MIN_VALUE; double j = Double.MAX_VALUE; float b = (float) i; float c = (float) j;
double i = Double.MIN_VALUE; double j = Double.MAX_VALUE; if ((i < Float.MIN_VALUE) || (i > Float.MAX_VALUE) || (j < Float.MIN_VALUE) || (j > Float.MAX_VALUE)) { throw new ArithmeticException ("Value is out of range"); } float b = (float) i; float c = (float) j; // Other operations
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
μ›μ‹œ μ •μˆ˜λ₯Ό 뢀동 μ†Œμˆ˜μ μœΌλ‘œ λ³€ν™˜ν•  λ•Œ 정밀도 손싀을 ν”Όν•˜μ‹­μ‹œμ˜€.
null
strictfp class WideSample { public static int subFloatFromInt(int op1, float op2) { return op1 - (int)op2; } public static void main(String[] args) { int result = subFloatFromInt(1234567890, 1234567890); // This prints -46, not 0, as may be expected System.out.println(result); } }
strictfp class WideSample { public static int subFloatFromInt(int op1, float op2) throws ArithmeticException { // The significand can store at most 23 bits if ((op2 > 0x007fffff) || (op2 < -0x800000)) { throw new ArithmeticException("Insufficient precision"); } return op1 - (int)op2; } public static void main(String[] args) { int result = subFloatFromInt(1234567890, 1234567890); System.out.println(result); } }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
μ›μ‹œ μ •μˆ˜λ₯Ό 뢀동 μ†Œμˆ˜μ μœΌλ‘œ λ³€ν™˜ν•  λ•Œ 정밀도 손싀을 ν”Όν•˜μ‹­μ‹œμ˜€.
null
strictfp class WideSample { public static int subFloatFromInt(int op1, float op2) { return op1 - (int)op2; } public static void main(String[] args) { int result = subFloatFromInt(1234567890, 1234567890); // This prints -46, not 0, as may be expected System.out.println(result); } }
strictfp class WideSample { public static int subDoubleFromInt(int op1, double op2) { return op1 - (int)op2; } public static void main(String[] args) { int result = subDoubleFromInt(1234567890, 1234567890); // Works as expected System.out.println(result); } }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
μ‹œν”„νŠΈ μ—°μ‚°μžλ₯Ό μ˜¬λ°”λ₯΄κ²Œ μ‚¬μš©ν•˜μ‹­μ‹œμ˜€.
null
static int countOneBits(long value) { int bits = 0; while (value != 0) { bits += value & 1L; value >>= 1; // Signed right shift, by one } return bits; }
static int countOneBits( long value ) { int bits = 0; while (value != 0) { bits += value & 1L; value >>>= 1; } return bits; }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
μ‹œν”„νŠΈ μ—°μ‚°μžλ₯Ό μ˜¬λ°”λ₯΄κ²Œ μ‚¬μš©ν•˜μ‹­μ‹œμ˜€.
null
byte b = /* Initialize */; int result = b >>> 2;
byte b = /* Initialize */; int result = ((int) b & 0xFF) >>> 2;
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
μ‹œν”„νŠΈ μ—°μ‚°μžλ₯Ό μ˜¬λ°”λ₯΄κ²Œ μ‚¬μš©ν•˜μ‹­μ‹œμ˜€.
null
public int doOperation(int exp) { // Compute 2^exp int temp = 1 << exp; // Do other processing return temp; }
public int doOperation(int exp) throws ArithmeticException { if ((exp < 0) || (exp >= 32)) { throw new ArithmeticException("Exponent out of range"); } // Safely compute 2^exp int temp = 1 << exp; // Do other processing return temp; }
JAVA
숫자 νƒ€μž…κ³Ό μ—°μ‚° (NUM)
μ‹œν”„νŠΈ μ—°μ‚°μžλ₯Ό μ˜¬λ°”λ₯΄κ²Œ μ‚¬μš©ν•˜μ‹­μ‹œμ˜€.
null
int i = 0; while ((-1 << i) != 0) { i++; }
for (int val = -1; val != 0; val <<= 1) { /* ... */ }
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
κ°€λ³€ 길이 μΈμ½”λ”©μ—μ„œ λΆ€λΆ„ 문자λ₯Ό ν¬ν•¨ν•˜λŠ” λ¬Έμžμ—΄μ„ λ§Œλ“€μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public final int MAX_SIZE = 1024; public String readBytes(Socket socket) throws IOException { InputStream in = socket.getInputStream(); byte[] data = new byte[MAX_SIZE+1]; int offset = 0; int bytesRead = 0; String str = new String(); while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) { str += new String(data, offset, bytesRead, "UTF-8"); offset += bytesRead; if (offset >= data.length) { throw new IOException("Too much input"); } } in.close(); return str; }
public final int MAX_SIZE = 1024; public String readBytes(Socket socket) throws IOException { InputStream in = socket.getInputStream(); byte[] data = new byte[MAX_SIZE+1]; int offset = 0; int bytesRead = 0; while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) { offset += bytesRead; if (offset >= data.length) { throw new IOException("Too much input"); } } String str = new String(data, 0, offset, "UTF-8"); in.close(); return str; }
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
κ°€λ³€ 길이 μΈμ½”λ”©μ—μ„œ λΆ€λΆ„ 문자λ₯Ό ν¬ν•¨ν•˜λŠ” λ¬Έμžμ—΄μ„ λ§Œλ“€μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public final int MAX_SIZE = 1024; public String readBytes(Socket socket) throws IOException { InputStream in = socket.getInputStream(); byte[] data = new byte[MAX_SIZE+1]; int offset = 0; int bytesRead = 0; String str = new String(); while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) { str += new String(data, offset, bytesRead, "UTF-9"); offset += bytesRead; if (offset >= data.length) { throw new IOException("Too much input"); } } in.close(); return str; }
public final int MAX_SIZE = 1024; public String readBytes(Socket socket) throws IOException { InputStream in = socket.getInputStream(); Reader r = new InputStreamReader(in, "UTF-8"); char[] data = new char[MAX_SIZE+1]; int offset = 0; int charsRead = 0; String str = new String(); while ((charsRead = r.read(data, offset, data.length - offset)) != -1) { str += new String(data, offset, charsRead); offset += charsRead; if (offset >= data.length) { throw new IOException("Too much input"); } } in.close(); return str; }
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
Java의 charκ°€ Unicode μ½”λ“œ 포인트λ₯Ό μ™„μ „νžˆ ν‘œν˜„ν•œλ‹€κ³  κ°€μ •ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
public static String trim(String string) { char ch; int i; for (i = 0; i < string.length(); i += 1) { ch = string.charAt(i); if (!Character.isLetter(ch)) { break; } } return string.substring(i); }
public static String trim(String string) { int ch; int i; for (i = 0; i < string.length(); i += Character.charCount(ch)) { ch = string.codePointAt(i); if (!Character.isLetter(ch)) { break; } } return string.substring(i); }
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
λ‘œμΌ€μΌ 쒅속 데이터λ₯Ό 비ꡐ할 λ•Œ μ μ ˆν•œ λ‘œμΌ€μΌμ„ μ§€μ •ν•˜μ‹­μ‹œμ˜€.
null
public static void processTag(String tag) { if (tag.toUpperCase().equals("SCRIPT")) { return; } // Process tag }
public static void processTag(String tag) { if (tag.toUpperCase(Locale.ENGLISH).equals("SCRIPT")) { return; } // Process tag }
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
λ‘œμΌ€μΌ 쒅속 데이터λ₯Ό 비ꡐ할 λ•Œ μ μ ˆν•œ λ‘œμΌ€μΌμ„ μ§€μ •ν•˜μ‹­μ‹œμ˜€.
null
public static void processTag(String tag) { if (tag.toUpperCase().equals("SCRIPT")) { return; } // Process tag }
public static void processTag(String tag) { Locale.setDefault(Locale.ENGLISH); if (tag.toUpperCase().equals("SCRIPT")) { return; } // Process tag }
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
λ‘œμΌ€μΌ 쒅속 데이터λ₯Ό 비ꡐ할 λ•Œ μ μ ˆν•œ λ‘œμΌ€μΌμ„ μ§€μ •ν•˜μ‹­μ‹œμ˜€.
null
public static void processTag(String tag) { if (tag.toUpperCase().equals("SCRIPT")) { return; } // Process tag }
public static void processTag(String tag) { if (tag.equalsIgnoreCase("SCRIPT")) { return; } // Process tag }
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
λ‘œμΌ€μΌ 쒅속 데이터λ₯Ό 비ꡐ할 λ•Œ μ μ ˆν•œ λ‘œμΌ€μΌμ„ μ§€μ •ν•˜μ‹­μ‹œμ˜€.
null
import java.io.*; public class PrintMyself { private static String inputFile = "PrintMyself.java"; private static String outputFile = "PrintMyself.txt"; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(inputFile)); PrintWriter writer = new PrintWriter(new FileWriter(outputFile)); int line = 0; while (reader.ready()) { line++; writer.println(line + ": " + reader.readLine()); } reader.close(); writer.close(); } }
public static void main(String[] args) throws IOException { Charset encoding = Charset.forName("UTF8"); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), encoding)); PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(outputFile), encoding)); int line = 0; /* Rest of code unchanged */
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
λ‘œμΌ€μΌ 쒅속 데이터λ₯Ό 비ꡐ할 λ•Œ μ μ ˆν•œ λ‘œμΌ€μΌμ„ μ§€μ •ν•˜μ‹­μ‹œμ˜€.
null
import java.util.Date; import java.text.DateFormat; import java.util.Locale; // ... public static void isJune(Date date) { String myString = DateFormat.getDateInstance().format(date); System.out.println("The date is " + myString); if (myString.startsWith("Jun ")) { System.out.println("Enjoy June!"); } else { System.out.println("It's not June."); } }
String myString = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US).format(rightNow.getTime()); /* Rest of code unchanged */ if (rightNow.get(Calendar.MONTH) == Calendar.JUNE) { /* Rest of code unchanged */
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
λ¬Έμžκ°€ μ•„λ‹Œ 데이터λ₯Ό λ¬Έμžμ—΄λ‘œ μΈμ½”λ”©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
BigInteger x = new BigInteger("530500452766"); byte[] byteArray = x.toByteArray(); String s = new String(byteArray); byteArray = s.getBytes(); x = new BigInteger(byteArray);
BigInteger x = new BigInteger("530500452766"); String s = x.toString(); // Valid character data byte[] byteArray = s.getBytes(); String ns = new String(byteArray); x = new BigInteger(ns);
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
λ¬Έμžκ°€ μ•„λ‹Œ 데이터λ₯Ό λ¬Έμžμ—΄λ‘œ μΈμ½”λ”©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
BigInteger x = new BigInteger("530500452766"); byte[] byteArray = x.toByteArray(); String s = new String(byteArray); byteArray = s.getBytes(); x = new BigInteger(byteArray);
BigInteger x = new BigInteger("530500452766"); byte[] byteArray = x.toByteArray(); String s = Base64.getEncoder().encodeToString(byteArray); byteArray = Base64.getDecoder().decode(s); x = new BigInteger(byteArray);
JAVA
λ¬Έμžμ™€ λ¬Έμžμ—΄ (STR)
JVM 간에 λ¬Έμžμ—΄ 데이터λ₯Ό 전달할 λ•Œ ν˜Έν™˜λ˜λŠ” 문자 인코딩을 μ‚¬μš©ν•˜μ‹­μ‹œμ˜€.
null
FileInputStream fis = null; try { fis = new FileInputStream("SomeFile"); DataInputStream dis = new DataInputStream(fis); byte[] data = new byte[1024]; dis.readFully(data); String result = new String(data); } catch (IOException x) { // Handle error } finally { if (fis != null) { try { fis.close(); } catch (IOException x) { // Forward to handler } } }
FileInputStream fis = null; try { fis = new FileInputStream("SomeFile"); DataInputStream dis = new DataInputStream(fis); byte[] data = new byte[1024]; dis.readFully(data); String result = new String(data, "UTF-16LE"); } catch (IOException x) { // Handle error } finally { if (fis != null) { try { fis.close(); } catch (IOException x) { // Forward to handler } } }
JAVA
객체 μ§€ν–₯ (OBJ)
ν•„λ“œμ˜ 접근성을 μ œν•œν•˜μ‹­μ‹œμ˜€.
null
public class Widget { public int total; // Number of elements void add() { if (total < Integer.MAX_VALUE) { total++; // ... } else { throw new ArithmeticException("Overflow"); } } void remove() { if (total > 0) { total--; // ... } else { throw new ArithmeticException("Overflow"); } } }
public class Widget { private int total; // Declared private public int getTotal () { return total; } // Definitions for add() and remove() remain the same }
JAVA
객체 μ§€ν–₯ (OBJ)
ν•„λ“œμ˜ 접근성을 μ œν•œν•˜μ‹­μ‹œμ˜€.
null
public static final HashMap<Integer, String> hm = new HashMap<Integer, String>();
private static final HashMap<Integer, String> hm = new HashMap<Integer, String>(); public static String getElement(int key) { return hm.get(key); }
JAVA
객체 μ§€ν–₯ (OBJ)
ν•„λ“œμ˜ 접근성을 μ œν•œν•˜μ‹­μ‹œμ˜€.
null
public static final String[] items = {/* ... */};
private static final String[] items = {/* ... */}; public static final String getItem(int index) { return items[index]; } public static final int getItemCount() { return items.length; }
JAVA
객체 μ§€ν–₯ (OBJ)
ν•„λ“œμ˜ 접근성을 μ œν•œν•˜μ‹­μ‹œμ˜€.
null
public static final String[] items = {/* ... */};
private static final String[] items = {/* ... */}; public static final String[] getItems() { return items.clone(); }
JAVA
객체 μ§€ν–₯ (OBJ)
ν•„λ“œμ˜ 접근성을 μ œν•œν•˜μ‹­μ‹œμ˜€.
null
public static final String[] items = {/* ... */};
private static final String[] items = { ... }; public static final List<String> itemsList = Collections.unmodifiableList(Arrays.asList(items));
JAVA
객체 μ§€ν–₯ (OBJ)
μƒμœ„ 클래슀λ₯Ό λ³€κ²½ν•  λ•Œ ν•˜μœ„ 클래슀의 μ˜μ‘΄μ„±μ„ μœ μ§€ν•˜μ‹­μ‹œμ˜€.
null
class Account { // Maintains all banking-related data such as account balance private double balance = 100; boolean overdraft() { balance += 300; // Add 300 in case there is an overdraft System.out.println("Added back-up amount. The balance is :" + balance); return true; } // Other Account methods } public class BankAccount extends Account { // Subclass handles authentication // NOTE: unchanged from previous version // NOTE: lacks override of overdraft method } public class Client { public static void main(String[] args) { Account account = new BankAccount(); // Enforce security manager check boolean result = account.withdraw(200.0); if (!result) { result = account.overdraft(); } System.out.println("Withdrawal successful? " + result); } }
class BankAccount extends Account { // ... @Override boolean overdraft() { // Override throw new IllegalAccessException(); } }
JAVA
객체 μ§€ν–₯ (OBJ)
μƒμœ„ 클래슀λ₯Ό λ³€κ²½ν•  λ•Œ ν•˜μœ„ 클래슀의 μ˜μ‘΄μ„±μ„ μœ μ§€ν•˜μ‹­μ‹œμ˜€.
null
class CalendarSubclass extends Calendar { @Override public boolean after(Object when) { // Correctly calls Calendar.compareTo() if (when instanceof Calendar && super.compareTo((Calendar) when) == 0) { return true; } return super.after(when); } @Override public int compareTo(Calendar anotherCalendar) { return compareDays(this.getFirstDayOfWeek(), anotherCalendar.getFirstDayOfWeek()); } private int compareDays(int currentFirstDayOfWeek, int anotherFirstDayOfWeek) { return (currentFirstDayOfWeek > anotherFirstDayOfWeek) ? 1 : (currentFirstDayOfWeek == anotherFirstDayOfWeek) ? 0 : -1; } public static void main(String[] args) { CalendarSubclass cs1 = new CalendarSubclass(); cs1.setTime(new Date()); // Date of last Sunday (before now) cs1.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // Wed Dec 31 19:00:00 EST 1969 CalendarSubclass cs2 = new CalendarSubclass(); // Expected to print true System.out.println(cs1.after(cs2)); } // Implementation of other Calendar abstract methods }
public boolean after(Object when) { return when instanceof Calendar && compareTo((Calendar) when) > 0; }
JAVA
객체 μ§€ν–₯ (OBJ)
νž™ μ˜€μ—Όμ„ λ°©μ§€ν•˜μ‹­μ‹œμ˜€.
null
class ListUtility { private static void addToList(List list, Object obj) { list.add(obj); // Unchecked warning } public static void main(String[] args) { List<String> list = new ArrayList<String> (); addToList(list, 42); System.out.println(list.get(0)); // Throws ClassCastException } }
class ListUtility { private static void addToList(List<String> list, String str) { list.add(str); // No warning generated } public static void main(String[] args) { List<String> list = new ArrayList<String> (); addToList(list, "42"); System.out.println(list.get(0)); } }
JAVA
객체 μ§€ν–₯ (OBJ)
νž™ μ˜€μ—Όμ„ λ°©μ§€ν•˜μ‹­μ‹œμ˜€.
null
class ListUtility { private static void addToList(List list, Object obj) { list.add(obj); // Unchecked warning } public static void main(String[] args) { List<String> list = new ArrayList<String> (); addToList(list, 42); System.out.println(list.get(1)); // Throws ClassCastException } }
class ListUtility { private static void addToList(List list, Object obj) { list.add(obj); // Unchecked warning, also throws ClassCastException } public static void main(String[] args) { List<String> list = new ArrayList<String> (); List<String> checkedList = Collections.checkedList(list, String.class); addToList(checkedList, 42); System.out.println(list.get(0)); } }
JAVA
객체 μ§€ν–₯ (OBJ)
νž™ μ˜€μ—Όμ„ λ°©μ§€ν•˜μ‹­μ‹œμ˜€.
null
class ListAdder { @SuppressWarnings("unchecked") private static void addToList(List list, Object obj) { list.add(obj); // Unchecked warning suppressed } private static <T> void printNum(T type) { if (!(type instanceof Integer || type instanceof Double)) { System.out.println("Cannot print in the supplied type"); } List<T> list = new ArrayList<T>(); addToList(list, 42); System.out.println(list.get(0)); } public static void main(String[] args) { double d = 42; int i = 42; System.out.println(d); ListAdder.printNum(d); System.out.println(i); ListAdder.printNum(i); } }
class ListAdder { private static <T> void addToList(List<T> list, T t) { list.add(t); // No warning generated } private static <T> void printNum(T type) { if (type instanceof Integer) { List<Integer> list = new ArrayList<Integer>(); addToList(list, 42); System.out.println(list.get(0)); } else if (type instanceof Double) { List<Double> list = new ArrayList<Double>(); addToList(list, 42.0); // Will not compile with 42 instead of 42.0 System.out.println(list.get(0)); } else { System.out.println("Cannot print in the supplied type"); } } public static void main(String[] args) { double d = 42; int i = 42; System.out.println(d); ListAdder.printNum(d); System.out.println(i); ListAdder.printNum(i); } }
JAVA
객체 μ§€ν–₯ (OBJ)
νž™ μ˜€μ—Όμ„ λ°©μ§€ν•˜μ‹­μ‹œμ˜€.
null
class ListModifierExample { public static void modify(List<String>... list) { Object[] objectArray = list; objectArray[1] = Arrays.asList(42); // Pollutes list, no warning for (List<String> ls : list) { for (String string : ls) { // ClassCastException on 42 System.out.println(string); } } } public static void main(String[] args) { List<String> s = Arrays.asList("foo", "bar"); List<String> s2 = Arrays.asList("baz", "quux"); modify( s, s2); // Unchecked varargs warning } }
class ListModifierExample { public static void modify(List<List<String>> list) { list.set( 1, Arrays.asList("forty-two")); // No warning for (List<String> ls : list) { for (String string : ls) { // ClassCastException on 42 System.out.println(string); } } } public static void main(String[] args) { List<String> s = Arrays.asList("foo", "bar"); List<String> s2 = Arrays.asList("baz", "quux"); List<List<String>> list = new ArrayList<List<String>>(); list.add(s); list.add(s2); modify(list); } }
JAVA
객체 μ§€ν–₯ (OBJ)
νž™ μ˜€μ—Όμ„ λ°©μ§€ν•˜μ‹­μ‹œμ˜€.
null
class ListModifierExample { public static void modify(List<String>[] list) { Object[] objectArray = list; // Valid objectArray[1] = Arrays.asList(42); // Pollutes list, no warning for (List<String> ls : list) { for (String string : ls) { // ClassCastException on 42 System.out.println(string); } } } public static void main(String[] args) { List<String> s = Arrays.asList("foo", "bar"); List<String> s2 = Arrays.asList("baz", "quux"); List list[] = {s, s2}; modify(list); // Unchecked conversion warning } }
class ListModifierExample { public static void modify(List<List<String>> list) { list.set( 1, Arrays.asList("forty-two")); // No warning for (List<String> ls : list) { for (String string : ls) { // ClassCastException on 42 System.out.println(string); } } } public static void main(String[] args) { List<String> s = Arrays.asList("foo", "bar"); List<String> s2 = Arrays.asList("baz", "quux"); List<List<String>> list = new ArrayList<List<String>>(); list.add(s); list.add(s3); modify(list); } }
JAVA
객체 μ§€ν–₯ (OBJ)
μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ— μΈμŠ€ν„΄μŠ€λ₯Ό μ•ˆμ „ν•˜κ²Œ 전달할 수 μžˆλ„λ‘ 볡사 κΈ°λŠ₯을 κ°–μΆ˜ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀λ₯Ό μ œκ³΅ν•˜μ‹­μ‹œμ˜€.
null
public final class MutableClass { private Date date; public MutableClass(Date d) { this.date = d; } public void setDate(Date d) { this.date = d; } public Date getDate() { return date; } }
public final class MutableClass { // Copy constructor private final Date date; public MutableClass(MutableClass mc) { this.date = new Date(mc.date.getTime()); } public MutableClass(Date d) { this.date = new Date(d.getTime()); // Make defensive copy } public Date getDate() { return (Date) date.clone(); // Copy and return } }
JAVA
객체 μ§€ν–₯ (OBJ)
μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ— μΈμŠ€ν„΄μŠ€λ₯Ό μ•ˆμ „ν•˜κ²Œ 전달할 수 μžˆλ„λ‘ 볡사 κΈ°λŠ₯을 κ°–μΆ˜ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀λ₯Ό μ œκ³΅ν•˜μ‹­μ‹œμ˜€.
null
public final class MutableClass { private Date date; public MutableClass(Date d) { this.date = d; } public void setDate(Date d) { this.date = d; } public Date getDate() { return date; } }
class MutableClass { private final Date date; private MutableClass(Date d) { // Noninstantiable and nonsubclassable this.date = new Date(d.getTime()); // Make defensive copy } public Date getDate() { return (Date) date.clone(); // Copy and return } public static MutableClass getInstance(MutableClass mc) { return new MutableClass(mc.getDate()); } }
JAVA
객체 μ§€ν–₯ (OBJ)
μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ— μΈμŠ€ν„΄μŠ€λ₯Ό μ•ˆμ „ν•˜κ²Œ 전달할 수 μžˆλ„λ‘ 볡사 κΈ°λŠ₯을 κ°–μΆ˜ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀λ₯Ό μ œκ³΅ν•˜μ‹­μ‹œμ˜€.
null
public final class MutableClass { private Date date; public MutableClass(Date d) { this.date = d; } public void setDate(Date d) { this.date = d; } public Date getDate() { return date; } }
public final class MutableClass implements Cloneable { private Date date; public MutableClass(Date d) { this.date = new Date(d.getTime()); } public Date getDate() { return (Date) date.clone(); } public void setDate(Date d) { this.date = (Date) d.clone(); } public Object clone() throws CloneNotSupportedException { final MutableClass cloned = (MutableClass) super.clone(); cloned.date = (Date) date.clone(); // Manually copy mutable Date object return cloned; } }
JAVA
객체 μ§€ν–₯ (OBJ)
μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ— μΈμŠ€ν„΄μŠ€λ₯Ό μ•ˆμ „ν•˜κ²Œ 전달할 수 μžˆλ„λ‘ 볡사 κΈ°λŠ₯을 κ°–μΆ˜ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀λ₯Ό μ œκ³΅ν•˜μ‹­μ‹œμ˜€.
null
public final class MutableClass { private Date date; public MutableClass(Date d) { this.date = d; } public void setDate(Date d) { this.date = d; } public Date getDate() { return date; } }
public final class MutableClass implements Cloneable { private final Date date; // final field public MutableClass(Date d) { this.date = new Date(d.getTime()); // Copy in } public Date getDate() { return (Date) date.clone(); // Copy and return } public Object clone() { Date d = (Date) date.clone(); MutableClass cloned = new MutableClass(d); return cloned; } }
JAVA
객체 μ§€ν–₯ (OBJ)
μ‹ λ’°ν•  수 μ—†λŠ” μ½”λ“œμ— μΈμŠ€ν„΄μŠ€λ₯Ό μ•ˆμ „ν•˜κ²Œ 전달할 수 μžˆλ„λ‘ 볡사 κΈ°λŠ₯을 κ°–μΆ˜ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀λ₯Ό μ œκ³΅ν•˜μ‹­μ‹œμ˜€.
null
public final class MutableClass { private Date date; public MutableClass(Date d) { this.date = d; } public void setDate(Date d) { this.date = d; } public Date getDate() { return date; } }
class UnmodifiableDateView extends Date { private Date date; public UnmodifiableDateView(Date date) { this.date = date; } public void setTime(long date) { throw new UnsupportedOperationException(); } // Override all other mutator methods to throw UnsupportedOperationException } public final class MutableClass { private Date date; public MutableClass(Date d) { this.date = d; } public void setDate(Date d) { this.date = (Date) d.clone(); } public UnmodifiableDateView getDate() { return new UnmodifiableDateView(date); } }
JAVA
객체 μ§€ν–₯ (OBJ)
privateν•œ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀 멀버에 λŒ€ν•œ μ°Έμ‘°λ₯Ό λ°˜ν™˜ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
class MutableClass { private Date d; public MutableClass() { d = new Date(); } public Date getDate() { return d; } }
public Date getDate() { return (Date)d.clone(); }
JAVA
객체 μ§€ν–₯ (OBJ)
privateν•œ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀 멀버에 λŒ€ν•œ μ°Έμ‘°λ₯Ό λ°˜ν™˜ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
class MutableClass { private Date[] date; public MutableClass() { date = new Date[20]; for (int i = 0; i < date.length; i++) { date[i] = new Date(); } } public Date[] getDate() { return date; // Or return date.clone() } }
class MutableClass { private Date[] date; public MutableClass() { date = new Date[20]; for(int i = 0; i < date.length; i++) { date[i] = new Date(); } } public Date[] getDate() { Date[] dates = new Date[date.length]; for (int i = 0; i < date.length; i++) { dates[i] = (Date) date[i].clone(); } return dates; } }
JAVA
객체 μ§€ν–₯ (OBJ)
privateν•œ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀 멀버에 λŒ€ν•œ μ°Έμ‘°λ₯Ό λ°˜ν™˜ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
class ReturnRef { // Internal state, may contain sensitive data private Hashtable<Integer,String> ht = new Hashtable<Integer,String>(); private ReturnRef() { ht.put(1, "123-45-6666"); } public Hashtable<Integer,String> getValues(){ return ht; } public static void main(String[] args) { ReturnRef rr = new ReturnRef(); Hashtable<Integer, String> ht1 = rr.getValues(); // Prints sensitive data 123-45-6666 ht1.remove(1); // Untrusted caller can remove entries Hashtable<Integer, String> ht2 = rr.getValues(); // Now prints null; original entry is removed } }
class ReturnRef { // ... private Hashtable<Integer,String> getValues(){ return (Hashtable<Integer, String>) ht.clone(); // Shallow copy } public static void main(String[] args) { ReturnRef rr = new ReturnRef(); // Prints nonsensitive data Hashtable<Integer,String> ht1 = rr.getValues(); // Untrusted caller can only modify copy ht1.remove(1); // Prints nonsensitive data Hashtable<Integer,String> ht2 = rr.getValues(); } }
JAVA
객체 μ§€ν–₯ (OBJ)
privateν•œ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀 멀버에 λŒ€ν•œ μ°Έμ‘°λ₯Ό λ°˜ν™˜ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
class MutableClass { private Date d; public MutableClass() { d = new Date(); } public Date getDate() { return d; } }
public Date getDate() { return (Date)d.clone(); }
JAVA
객체 μ§€ν–₯ (OBJ)
privateν•œ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀 멀버에 λŒ€ν•œ μ°Έμ‘°λ₯Ό λ°˜ν™˜ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
class MutableClass { private Date[] date; public MutableClass() { date = new Date[20]; for (int i = 0; i < date.length; i++) { date[i] = new Date(); } } public Date[] getDate() { return date; // Or return date.clone() } }
class MutableClass { private Date[] date; public MutableClass() { date = new Date[20]; for(int i = 0; i < date.length; i++) { date[i] = new Date(); } } public Date[] getDate() { Date[] dates = new Date[date.length]; for (int i = 0; i < date.length; i++) { dates[i] = (Date) date[i].clone(); } return dates; } }
JAVA
객체 μ§€ν–₯ (OBJ)
privateν•œ λ³€κ²½ κ°€λŠ₯ν•œ 클래슀 멀버에 λŒ€ν•œ μ°Έμ‘°λ₯Ό λ°˜ν™˜ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
class ReturnRef { // Internal state, may contain sensitive data private Hashtable<Integer,String> ht = new Hashtable<Integer,String>(); private ReturnRef() { ht.put(1, "123-45-6666"); } public Hashtable<Integer,String> getValues(){ return ht; } public static void main(String[] args) { ReturnRef rr = new ReturnRef(); Hashtable<Integer, String> ht1 = rr.getValues(); // Prints sensitive data 123-45-6666 ht1.remove(1); // Untrusted caller can remove entries Hashtable<Integer, String> ht2 = rr.getValues(); // Now prints null; original entry is removed } }
class ReturnRef { // ... private Hashtable<Integer,String> getValues(){ return (Hashtable<Integer, String>) ht.clone(); // Shallow copy } public static void main(String[] args) { ReturnRef rr = new ReturnRef(); // Prints nonsensitive data Hashtable<Integer,String> ht1 = rr.getValues(); // Untrusted caller can only modify copy ht1.remove(1); // Prints nonsensitive data Hashtable<Integer,String> ht2 = rr.getValues(); } }
JAVA
객체 μ§€ν–₯ (OBJ)
λ³€κ²½ κ°€λŠ₯ν•œ μž…λ ₯κ³Ό λ³€κ²½ κ°€λŠ₯ν•œ λ‚΄λΆ€ ꡬ성 μš”μ†Œλ₯Ό λ°©μ–΄μ μœΌλ‘œ λ³΅μ‚¬ν•˜μ‹­μ‹œμ˜€.
null
public final class MutableDemo { // java.net.HttpCookie is mutable public void useMutableInput(HttpCookie cookie) { if (cookie == null) { throw new NullPointerException(); } // Check whether cookie has expired if (cookie.hasExpired()) { // Cookie is no longer valid; handle condition by throwing an exception } // Cookie may have expired since time of check doLogic(cookie); } }
public final class MutableDemo { // java.net.HttpCookie is mutable public void useMutableInput(HttpCookie cookie) { if (cookie == null) { throw new NullPointerException(); } // Create copy cookie = (HttpCookie)cookie.clone(); // Check whether cookie has expired if (cookie.hasExpired()) { // Cookie is no longer valid; handle condition by throwing an exception } doLogic(cookie); } }
JAVA
객체 μ§€ν–₯ (OBJ)
λ³€κ²½ κ°€λŠ₯ν•œ μž…λ ₯κ³Ό λ³€κ²½ κ°€λŠ₯ν•œ λ‚΄λΆ€ ꡬ성 μš”μ†Œλ₯Ό λ°©μ–΄μ μœΌλ‘œ λ³΅μ‚¬ν•˜μ‹­μ‹œμ˜€.
null
public final class MutableDemo { // java.net.HttpCookie is mutable public void useMutableInput(HttpCookie cookie) { if (cookie == null) { throw new NullPointerException(); } // Check whether cookie has expired if (cookie.hasExpired()) { // Cookie is no longer valid; handle condition by throwing an exception } // Cookie may have expired since time of check doLogic(cookie); } }
public void deepCopy(int[] ints, HttpCookie[] cookies) { if (ints == null || cookies == null) { throw new NullPointerException(); } // Shallow copy int[] intsCopy = ints.clone(); // Deep copy HttpCookie[] cookiesCopy = new HttpCookie[cookies.length]; for (int i = 0; i < cookies.length; i++) { // Manually create copy of each element in array cookiesCopy[i] = (HttpCookie)cookies[i].clone(); } doLogic(intsCopy, cookiesCopy); }
JAVA
객체 μ§€ν–₯ (OBJ)
λ³€κ²½ κ°€λŠ₯ν•œ μž…λ ₯κ³Ό λ³€κ²½ κ°€λŠ₯ν•œ λ‚΄λΆ€ ꡬ성 μš”μ†Œλ₯Ό λ°©μ–΄μ μœΌλ‘œ λ³΅μ‚¬ν•˜μ‹­μ‹œμ˜€.
null
// java.util.Collection is an interface public void copyInterfaceInput(Collection<String> collection) { doLogic(collection.clone()); }
public void copyInterfaceInput(Collection<String> collection) { // Convert input to trusted implementation collection = new ArrayList(collection); doLogic(collection); }
JAVA
객체 μ§€ν–₯ (OBJ)
λ―Όκ°ν•œ ν΄λž˜μŠ€λŠ” 슀슀둜 λ³΅μ‚¬λ˜λ„λ‘ ν—ˆμš©ν•΄μ„œλŠ” μ•ˆ λ©λ‹ˆλ‹€.
null
class SensitiveClass { private char[] filename; private Boolean shared = false; SensitiveClass(String filename) { this.filename = filename.toCharArray(); } final void replace() { if (!shared) { for(int i = 0; i < filename.length; i++) { filename[i]= 'x' ;} } } final String get() { if (!shared) { shared = true; return String.valueOf(filename); } else { throw new IllegalStateException("Failed to get instance"); } } final void printFilename() { System.out.println(String.valueOf(filename)); } }
class SensitiveClass { // ... public final SensitiveClass clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } }
JAVA
객체 μ§€ν–₯ (OBJ)
쀑첩 ν΄λž˜μŠ€μ—μ„œ μ™ΈλΆ€ 클래슀의 λΉ„κ³΅κ°œ 멀버λ₯Ό λ…ΈμΆœν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
class Coordinates { private int x; private int y; public class Point { public void getPoint() { System.out.println("(" + x + "," + y + ")"); } } } class AnotherClass { public static void main(String[] args) { Coordinates c = new Coordinates(); Coordinates.Point p = c.new Point(); p.getPoint(); } }
class Coordinates { private int x; private int y; private class Point { private void getPoint() { System.out.println("(" + x + "," + y + ")"); } } } class AnotherClass { public static void main(String[] args) { Coordinates c = new Coordinates(); Coordinates.Point p = c.new Point(); // Fails to compile p.getPoint(); } }
JAVA
객체 μ§€ν–₯ (OBJ)
클래슀 이름이 μ•„λ‹Œ 클래슀λ₯Ό λΉ„κ΅ν•˜μ‹­μ‹œμ˜€.
null
// Determine whether object auth has required/expected class object if (auth.getClass().getName().equals( "com.application.auth.DefaultAuthenticationHandler")) { // ... }
// Determine whether object auth has required/expected class name if (auth.getClass() == com.application.auth.DefaultAuthenticationHandler.class) { // ... }
JAVA
객체 μ§€ν–₯ (OBJ)
클래슀 이름이 μ•„λ‹Œ 클래슀λ₯Ό λΉ„κ΅ν•˜μ‹­μ‹œμ˜€.
null
// Determine whether objects x and y have the same class name if (x.getClass().getName().equals(y.getClass().getName())) { // Objects have the same class }
// Determine whether objects x and y have the same class if (x.getClass() == y.getClass()) { // Objects have the same class }
JAVA
객체 μ§€ν–₯ (OBJ)
public static final이 μ•„λ‹Œ ν•„λ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
package org.apache.xpath.compiler; public class FunctionTable { public static FuncLoader m_functions; }
public static final FuncLoader m_functions; // Initialize m_functions in a static initialization block
JAVA
객체 μ§€ν–₯ (OBJ)
public static final이 μ•„λ‹Œ ν•„λ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
class DataSerializer implements Serializable { public static long serialVersionUID = 1973473122623778747L; // ... }
class DataSerializer implements Serializable { private static final long serialVersionUID = 1973473122623778747L; }
JAVA
객체 μ§€ν–₯ (OBJ)
μƒμ„±μžκ°€ μ˜ˆμ™Έλ₯Ό λ˜μ§€λ„λ‘ ν—ˆμš©ν•˜λŠ” 것에 μœ μ˜ν•˜μ‹­μ‹œμ˜€.
null
public class BankOperations { public BankOperations() { if (!performSSNVerification()) { throw new SecurityException("Access Denied!"); } } private boolean performSSNVerification() { return false; // Returns true if data entered is valid, else false // Assume that the attacker always enters an invalid SSN } public void greet() { System.out.println("Welcome user! You may now use all the features."); } } public class Storage { private static BankOperations bop; public static void store(BankOperations bo) { // Store only if it is initialized if (bop == null) { if (bo == null) { System.out.println("Invalid object!"); System.exit(1); } bop = bo; } } } public class UserApp { public static void main(String[] args) { BankOperations bo; try { bo = new BankOperations(); } catch (SecurityException ex) { bo = null; } Storage.store(bo); System.out.println("Proceed with normal logic"); } }
public final class BankOperations { // ... } λ˜λŠ” public class BankOperations { public final void finalize() { // Do nothing } } μ½”λ“œλ‘œ finalizer 곡격을 λ°©μ§€ν•  수 μžˆλ‹€.
JAVA
객체 μ§€ν–₯ (OBJ)
μƒμ„±μžκ°€ μ˜ˆμ™Έλ₯Ό λ˜μ§€λ„λ‘ ν—ˆμš©ν•˜λŠ” 것에 μœ μ˜ν•˜μ‹­μ‹œμ˜€.
null
public class Interceptor extends BankOperations { private static Interceptor stealInstance = null; public static Interceptor get() { try { new Interceptor(); } catch (Exception ex) {/* Ignore exception */} try { synchronized (Interceptor.class) { while (stealInstance == null) { System.gc(); Interceptor.class.wait(10); } } } catch (InterruptedException ex) { return null; } return stealInstance; } public void finalize() { synchronized (Interceptor.class) { stealInstance = this; Interceptor.class.notify(); } System.out.println("Stole the instance in finalize of " + this); } } public class AttackerApp { // Invoke class and gain access // to the restrictive features public static void main(String[] args) { Interceptor i = Interceptor.get(); // Stolen instance // Can store the stolen object even though this should have printed // "Invalid Object!" Storage.store(i); // Now invoke any instance method of BankOperations class i.greet(); UserApp.main(args); // Invoke the original UserApp } }
public final class BankOperations { // ... } λ˜λŠ” public class BankOperations { public final void finalize() { // Do nothing } } μ½”λ“œλ‘œ finalizer 곡격을 λ°©μ§€ν•  수 μžˆλ‹€.
JAVA
객체 μ§€ν–₯ (OBJ)
μƒμ„±μžκ°€ μ˜ˆμ™Έλ₯Ό λ˜μ§€λ„λ‘ ν—ˆμš©ν•˜λŠ” 것에 μœ μ˜ν•˜μ‹­μ‹œμ˜€.
null
public class BankOperations { public BankOperations() { if (!performSSNVerification()) { throw new SecurityException("Access Denied!"); } } private boolean performSSNVerification() { return false; // Returns true if data entered is valid, else false // Assume that the attacker always enters an invalid SSN } public void greet() { System.out.println("Welcome user! You may now use all the features."); } } public class Storage { private static BankOperations bop; public static void store(BankOperations bo) { // Store only if it is initialized if (bop == null) { if (bo == null) { System.out.println("Invalid object!"); System.exit(1); } bop = bo; } } } public class UserApp { public static void main(String[] args) { BankOperations bo; try { bo = new BankOperations(); } catch (SecurityException ex) { bo = null; } Storage.store(bo); System.out.println("Proceed with normal logic"); } }
public class BankOperations { public BankOperations() { this(performSSNVerification()); } private BankOperations(boolean secure) { // secure is always true // Constructor without any security checks } private static boolean performSSNVerification() { // Returns true if data entered is valid, else throws a SecurityException // Assume that the attacker just enters invalid SSN, so this method always throws the exception throw new SecurityException("Invalid SSN!"); } // ...remainder of BankOperations class definition }
JAVA
객체 μ§€ν–₯ (OBJ)
μƒμ„±μžκ°€ μ˜ˆμ™Έλ₯Ό λ˜μ§€λ„λ‘ ν—ˆμš©ν•˜λŠ” 것에 μœ μ˜ν•˜μ‹­μ‹œμ˜€.
null
public class BankOperations { public BankOperations() { if (!performSSNVerification()) { throw new SecurityException("Access Denied!"); } } private boolean performSSNVerification() { return false; // Returns true if data entered is valid, else false // Assume that the attacker always enters an invalid SSN } public void greet() { System.out.println("Welcome user! You may now use all the features."); } } public class Storage { private static BankOperations bop; public static void store(BankOperations bo) { // Store only if it is initialized if (bop == null) { if (bo == null) { System.out.println("Invalid object!"); System.exit(2); } bop = bo; } } } public class UserApp { public static void main(String[] args) { BankOperations bo; try { bo = new BankOperations(); } catch (SecurityException ex) { bo = null; } Storage.store(bo); System.out.println("Proceed with normal logic"); } }
class BankOperations { private volatile boolean initialized = false; public BankOperations() { if (!performSSNVerification()) { return; // object construction failed } this.initialized = true; // Object construction successful } private boolean performSSNVerification() { return false; } public void greet() { if (!this.initialized) { throw new SecurityException("Invalid SSN!"); } System.out.println( "Welcome user! You may now use all the features."); } }
JAVA
객체 μ§€ν–₯ (OBJ)
μƒμ„±μžκ°€ μ˜ˆμ™Έλ₯Ό λ˜μ§€λ„λ‘ ν—ˆμš©ν•˜λŠ” 것에 μœ μ˜ν•˜μ‹­μ‹œμ˜€.
null
class Trade { private static Stock s; static { try { s = new Stock(); } catch (IOException e) { /* Does not initialize s to a safe state */ } } // ... }
private static final Stock s;
JAVA
객체 μ§€ν–₯ (OBJ)
λ³€κ²½ κ°€λŠ₯ν•œ 객체에 λŒ€ν•œ μ°Έμ‘°κ°€ λ…ΈμΆœλ˜μ§€ μ•Šλ„λ‘ ν•˜μ‹­μ‹œμ˜€.
null
public static final SomeType [] SOMETHINGS = { ... };
private static final SomeType [] SOMETHINGS = { ... }; public static final SomeType [] somethings() { return SOMETHINGS.clone(); }
JAVA
객체 μ§€ν–₯ (OBJ)
λ³€κ²½ κ°€λŠ₯ν•œ 객체에 λŒ€ν•œ μ°Έμ‘°κ°€ λ…ΈμΆœλ˜μ§€ μ•Šλ„λ‘ ν•˜μ‹­μ‹œμ˜€.
null
private static final SomeType [] SOMETHINGS = { ... }; public static final getSomethings() {return SOMETHINGS;}
private static final SomeType [] THE_THINGS = { ... }; public static final List<SomeType> SOMETHINGS = Collections.unmodifiableList(Arrays.asList(THE_THINGS));
JAVA
Methods (MET), λ©”μ„œλ“œ
λ©”μ„œλ“œμ˜ 인수λ₯Ό κ²€μ¦ν•˜μ‹­μ‹œμ˜€.
null
private Object myState = null; // Sets some internal state in the library void setState(Object state) { myState = state; } // Performs some action using the state passed earlier void useState() { // Perform some action here }
private Object myState = null; // Sets some internal state in the library void setState(Object state) { if (state == null) { // Handle null state } // Defensive copy here when state is mutable if (isInvalidState(state)) { // Handle invalid state } myState = state; } // Performs some action using the state passed earlier void useState() { if (myState == null) { // Handle no state (e.g., null) condition } // ... }
JAVA
Methods (MET), λ©”μ„œλ“œ
λ©”μ„œλ“œμ˜ 인수λ₯Ό κ²€μ¦ν•˜κΈ° μœ„ν•΄ μ–΄μ„€μ…˜μ„ μ ˆλŒ€ μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-617, Reachable Assertion
public static int getAbsAdd(int x, int y) { return Math.abs(x) + Math.abs(y); } getAbsAdd(Integer.MIN_VALUE, 1);
public static int getAbsAdd(int x, int y) { if (x == Integer.MIN_VALUE || y == Integer.MIN_VALUE) { throw new IllegalArgumentException(); } int absX = Math.abs(x); int absY = Math.abs(y); if (absX > Integer.MAX_VALUE - absY) { throw new IllegalArgumentException(); } return absX + absY; }
JAVA
Methods (MET), λ©”μ„œλ“œ
λ©”μ„œλ“œμ˜ 인수λ₯Ό κ²€μ¦ν•˜κΈ° μœ„ν•΄ μ–΄μ„€μ…˜μ„ μ ˆλŒ€ μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
CWE-617, Reachable Assertion
public static int getAbsAdd(int x, int y) { assert x != Integer.MIN_VALUE; assert y != Integer.MIN_VALUE; int absX = Math.abs(x); int absY = Math.abs(y); assert (absX <= Integer.MAX_VALUE - absY); return absX + absY; }
public static int getAbsAdd(int x, int y) { if (x == Integer.MIN_VALUE || y == Integer.MIN_VALUE) { throw new IllegalArgumentException(); } int absX = Math.abs(x); int absY = Math.abs(y); if (absX > Integer.MAX_VALUE - absY) { throw new IllegalArgumentException(); } return absX + absY; }
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.lang.Character.isJavaLetter()
java.lang.Character.isJavaIdentifierStart()
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.lang.Character.isJavaLetterOrDigit()
java.lang.Character.isJavaIdentifierPart()
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.lang.Character.isSpace()
java.lang.Character.isWhitespace()
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.lang.Class.newInstance()
java.lang.reflect.Constructor.newInstance()
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.util.Date (many methods)
java.util.Calendar
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.util.Dictionary<K,V>
java.util.Map<K,V>
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.util.Properties.save()
java.util.Properties.store()
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.lang.Thread.run()
java.lang.Thread.start()
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.lang.Thread.stop()
java.lang.Thread.interrupt()
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.lang.ThreadGroup (many methods)
java.util.concurrent.Executor
JAVA
Methods (MET), λ©”μ„œλ“œ
더 이상 μ‚¬μš©λ˜μ§€ μ•Šκ±°λ‚˜ 폐기된 ν΄λž˜μŠ€λ‚˜ λ©”μ„œλ“œλ₯Ό μ‚¬μš©ν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
java.util.Date
java.time (since Java 8)
JAVA
Methods (MET), λ©”μ„œλ“œ
λ³΄μ•ˆ 검사λ₯Ό μˆ˜ν–‰ν•˜λŠ” λ©”μ„œλ“œλŠ” private λ˜λŠ” final둜 μ„ μ–Έλ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€.
null
public void readSensitiveFile() { try { SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Check for permission to read file sm.checkRead("/temp/tempFile"); } // Access the file } catch (SecurityException se) { // Log exception } }
public final void readSensitiveFile() { try { SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Check for permission to read file sm.checkRead("/temp/tempFile"); } // Access the file } catch (SecurityException se) { // Log exception } }
JAVA
Methods (MET), λ©”μ„œλ“œ
λ³΄μ•ˆ 검사λ₯Ό μˆ˜ν–‰ν•˜λŠ” λ©”μ„œλ“œλŠ” private λ˜λŠ” final둜 μ„ μ–Έλ˜μ–΄μ•Ό ν•©λ‹ˆλ‹€.
null
public void readSensitiveFile() { try { SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Check for permission to read file sm.checkRead("/temp/tempFile"); } // Access the file } catch (SecurityException se) { // Log exception } }
private void readSensitiveFile() { try { SecurityManager sm = System.getSecurityManager(); if (sm != null) { // Check for permission to read file sm.checkRead("/temp/tempFile"); } // Access the file } catch (SecurityException se) { // Log exception } }
JAVA
Methods (MET), λ©”μ„œλ“œ
μ˜€λ²„λΌμ΄λ“œ λ˜λŠ” μˆ¨κ²¨μ§„ λ©”μ„œλ“œμ˜ 접근성을 높이지 λ§ˆμ‹­μ‹œμ˜€.
CWE-487
class Super { protected void doLogic() { System.out.println("Super invoked"); } } public class Sub extends Super { public void doLogic() { System.out.println("Sub invoked"); // Do sensitive operations } }
class Super { protected final void doLogic() { // Declare as final System.out.println("Super invoked"); // Do sensitive operations } }
JAVA
Methods (MET), λ©”μ„œλ“œ
μƒμ„±μžκ°€ μž¬μ •μ˜ κ°€λŠ₯ν•œ λ©”μ„œλ“œλ₯Ό ν˜ΈμΆœν•˜μ§€ μ•Šλ„λ‘ ν•˜μ‹­μ‹œμ˜€.
null
class SuperClass { public SuperClass () { doLogic(); } public void doLogic() { System.out.println("This is superclass!"); } } class SubClass extends SuperClass { private String color = "red"; public void doLogic() { System.out.println("This is subclass! The color is :" + color); // ... } } public class Overridable { public static void main(String[] args) { SuperClass bc = new SuperClass(); // Prints "This is superclass!" SuperClass sc = new SubClass(); // Prints "This is subclass! The color is :null" } }
class SuperClass { public SuperClass() { doLogic(); } public final void doLogic() { System.out.println("This is superclass!"); } }
JAVA
Methods (MET), λ©”μ„œλ“œ
clone()μ—μ„œ μ˜€λ²„λΌμ΄λ“œ κ°€λŠ₯ν•œ λ©”μ„œλ“œλ₯Ό ν˜ΈμΆœν•˜μ§€ λ§ˆμ„Έμš”.
null
class CloneExample implements Cloneable { HttpCookie[] cookies; CloneExample(HttpCookie[] c) { cookies = c; } public Object clone() throws CloneNotSupportedException { final CloneExample clone = (CloneExample) super.clone(); clone.doSomething(); // Invokes overridable method clone.cookies = clone.deepCopy(); return clone; } void doSomething() { // Overridable for (int i = 0; i < cookies.length; i++) { cookies[i].setValue("" + i); } } HttpCookie[] deepCopy() { if (cookies == null) { throw new NullPointerException(); } // Deep copy HttpCookie[] cookiesCopy = new HttpCookie[cookies.length]; for (int i = 0; i < cookies.length; i++) { // Manually create a copy of each element in array cookiesCopy[i] = (HttpCookie) cookies[i].clone(); } return cookiesCopy; } } class Sub extends CloneExample { Sub(HttpCookie[] c) { super(c); } public Object clone() throws CloneNotSupportedException { final Sub clone = (Sub) super.clone(); clone.doSomething(); return clone; } void doSomething() { // Erroneously executed for (int i = 0;i < cookies.length; i++) { cookies[i].setDomain(i + ".foo.com"); } } public static void main(String[] args) throws CloneNotSupportedException { HttpCookie[] hc = new HttpCookie[20]; for (int i = 0 ; i < hc.length; i++){ hc[i] = new HttpCookie("cookie" + i,"" + i); } CloneExample bc = new Sub(hc); bc.clone(); } }
class CloneExample implements Cloneable { final void doSomething() { // ... } final HttpCookie[] deepCopy() { // ... } // ... }
JAVA
Methods (MET), λ©”μ„œλ“œ
μŠˆνΌν΄λž˜μŠ€λ‚˜ μŠˆνΌμΈν„°νŽ˜μ΄μŠ€μ— μ„ μ–Έλœ λ©”μ„œλ“œλ₯Ό μˆ¨κΈ°λŠ” 클래슀 λ©”μ„œλ“œλ₯Ό μ„ μ–Έν•˜μ§€ λ§ˆμ‹­μ‹œμ˜€.
null
class GrantAccess { public static void displayAccountStatus() { System.out.println("Account details for admin: XX"); } } class GrantUserAccess extends GrantAccess { public static void displayAccountStatus() { System.out.println("Account details for user: XX"); } } public class StatMethod { public static void choose(String username) { GrantAccess admin = new GrantAccess(); GrantAccess user = new GrantUserAccess(); if (username.equals("admin")) { admin.displayAccountStatus(); } else { user.displayAccountStatus(); } } public static void main(String[] args) { choose("user"); } }
class GrantAccess { public void displayAccountStatus() { System.out.print("Account details for admin: XX"); } } class GrantUserAccess extends GrantAccess { @Override public void displayAccountStatus() { System.out.print("Account details for user: XX"); } } public class StatMethod { public static void choose(String username) { GrantAccess admin = new GrantAccess(); GrantAccess user = new GrantUserAccess(); if (username.equals("admin")) { admin.displayAccountStatus(); } else { user.displayAccountStatus(); } } public static void main(String[] args) { choose("user"); } }
JAVA
Methods (MET), λ©”μ„œλ“œ
equals() λ©”μ„œλ“œλ₯Ό μ˜€λ²„λΌμ΄λ“œν•  λ•Œ 동등성 계약을 μœ μ§€ν•˜μ‹­μ‹œμ˜€.
CWE-697, 잘λͺ»λœ 비ꡐ
public final class CaseInsensitiveString { private String s; public CaseInsensitiveString(String s) { if (s == null) { throw new NullPointerException(); } this.s = s; } // This method violates symmetry public boolean equals(Object o) { if (o instanceof CaseInsensitiveString) { return s.equalsIgnoreCase(((CaseInsensitiveString)o).s); } if (o instanceof String) { return s.equalsIgnoreCase((String)o); } return false; } // Comply with MET09-J public int hashCode() {/* ... */} public static void main(String[] args) { CaseInsensitiveString cis = new CaseInsensitiveString("Java"); String s = "java"; System.out.println(cis.equals(s)); // Returns true System.out.println(s.equals(cis)); // Returns false } }
public final class CaseInsensitiveString { private String s; public CaseInsensitiveString(String s) { if (s == null) { throw new NullPointerException(); } this.s = s; } public boolean equals(Object o) { return o instanceof CaseInsensitiveString && ((CaseInsensitiveString)o).s.equalsIgnoreCase(s); } public int hashCode() {/* ... */} public static void main(String[] args) { CaseInsensitiveString cis = new CaseInsensitiveString("Java"); String s = "java"; System.out.println(cis.equals(s)); // Returns false now System.out.println(s.equals(cis)); // Returns false now } }
JAVA
Methods (MET), λ©”μ„œλ“œ
equals() λ©”μ„œλ“œλ₯Ό μ˜€λ²„λΌμ΄λ“œν•  λ•Œ 동등성 계약을 μœ μ§€ν•˜μ‹­μ‹œμ˜€.
CWE-697, 잘λͺ»λœ 비ꡐ
public class Card { private final int number; public Card(int number) { this.number = number; } public boolean equals(Object o) { if (!(o instanceof Card)) { return false; } Card c = (Card)o; return c.number == number; } public int hashCode() {/* ... */} } class XCard extends Card { private String type; public XCard(int number, String type) { super(number); this.type = type; } public boolean equals(Object o) { if (!(o instanceof Card)) { return false; } // Normal Card, do not compare type if (!(o instanceof XCard)) { return o.equals(this); } // It is an XCard, compare type as well XCard xc = (XCard)o; return super.equals(o) && xc.type == type; } public int hashCode() {/* ... */} public static void main(String[] args) { XCard p1 = new XCard(1, "type1"); Card p2 = new Card(1); XCard p3 = new XCard(1, "type2"); System.out.println(p1.equals(p2)); // Returns true System.out.println(p2.equals(p3)); // Returns true System.out.println(p1.equals(p3)); // Returns false // violating transitivity } }
class XCard { private String type; private Card card; // Composition public XCard(int number, String type) { card = new Card(number); this.type = type; } public Card viewCard() { return card; } public boolean equals(Object o) { if (!(o instanceof XCard)) { return false; } XCard cp = (XCard)o; return cp.card.equals(card) && cp.type.equals(type); } public int hashCode() {/* ... */} public static void main(String[] args) { XCard p1 = new XCard(1, "type1"); Card p2 = new Card(1); XCard p3 = new XCard(1, "type2"); XCard p4 = new XCard(1, "type1"); System.out.println(p1.equals(p2)); // Prints false System.out.println(p2.equals(p3)); // Prints false System.out.println(p1.equals(p3)); // Prints false System.out.println(p1.equals(p4)); // Prints true } }
JAVA
Methods (MET), λ©”μ„œλ“œ
equals() λ©”μ„œλ“œλ₯Ό μ˜€λ²„λΌμ΄λ“œν•  λ•Œ 동등성 계약을 μœ μ§€ν•˜μ‹­μ‹œμ˜€.
CWE-697, 잘λͺ»λœ 비ꡐ
public class Card { private final int number; public Card(int number) { this.number = number; } public boolean equals(Object o) { if (!(o instanceof Card)) { return false; } Card c = (Card)o; return c.number == number; } public int hashCode() {/* ... */} } class XCard extends Card { private String type; public XCard(int number, String type) { super(number); this.type = type; } public boolean equals(Object o) { if (!(o instanceof Card)) { return false; } // Normal Card, do not compare type if (!(o instanceof XCard)) { return o.equals(this); } // It is an XCard, compare type as well XCard xc = (XCard)o; return super.equals(o) && xc.type == type; } public int hashCode() {/* ... */} public static void main(String[] args) { XCard p1 = new XCard(1, "type1"); Card p2 = new Card(1); XCard p3 = new XCard(1, "type2"); System.out.println(p1.equals(p2)); // Returns true System.out.println(p2.equals(p3)); // Returns true System.out.println(p1.equals(p4)); // Returns false // violating transitivity } }
public class Card { private final int number; public Card(int number) { this.number = number; } public boolean equals(Object o) { if (!(o.getClass() == this.getClass())) { return false; } Card c = (Card)o; return c.number == number; } public int hashCode() {/* ... */} }
JAVA
Methods (MET), λ©”μ„œλ“œ
equals() λ©”μ„œλ“œλ₯Ό μ˜€λ²„λΌμ΄λ“œν•  λ•Œ 동등성 계약을 μœ μ§€ν•˜μ‹­μ‹œμ˜€.
CWE-697, 잘λͺ»λœ 비ꡐ
public class Filter { public static void main(String[] args) throws MalformedURLException { final URL allowed = new URL("http://mailwebsite.com"); if (!allowed.equals(new URL(args[0]))) { throw new SecurityException("Access Denied"); } // Else proceed } }
public class Filter { public static void main(String[] args) throws MalformedURLException { final URL allowed = new URL("http://mailwebsite.com"); if (!allowed.toString().equals(new URL(args[0]).toString())) { throw new SecurityException("Access Denied"); } // Else proceed } }
JAVA
Methods (MET), λ©”μ„œλ“œ
equals() λ©”μ„œλ“œλ₯Ό μ˜€λ²„λΌμ΄λ“œν•  λ•Œ 동등성 계약을 μœ μ§€ν•˜μ‹­μ‹œμ˜€.
CWE-697, 잘λͺ»λœ 비ꡐ
public class Filter { public static void main(String[] args) throws MalformedURLException { final URL allowed = new URL("http://mailwebsite.com"); if (!allowed.equals(new URL(args[1]))) { throw new SecurityException("Access Denied"); } // Else proceed } }
public class Filter { public static void main(String[] args) throws MalformedURLException, URISyntaxException { final URI allowed = new URI("http://mailwebsite.com"); if (!allowed.equals(new URI(args[0]))) { throw new SecurityException("Access Denied"); } // Else proceed } }
JAVA
Methods (MET), λ©”μ„œλ“œ
equals() λ©”μ„œλ“œλ₯Ό μ˜€λ²„λΌμ΄λ“œν•  λ•Œ 동등성 계약을 μœ μ§€ν•˜μ‹­μ‹œμ˜€.
CWE-697, 잘λͺ»λœ 비ꡐ
private static boolean keysEqual(Key key1, Key key2) { if (key1.equals(key2)) { return true; } return false; }
private static boolean keysEqual(Key key1, Key key2) { if (key1.equals(key2)) { return true; } if (Arrays.equals(key1.getEncoded(), key2.getEncoded())) { return true; } // More code for different types of keys here. // For example, the following code can check if // an RSAPrivateKey and an RSAPrivateCrtKey are equal: if ((key1 instanceof RSAPrivateKey) && (key2 instanceof RSAPrivateKey)) { if ((((RSAKey)key1).getModulus().equals( ((RSAKey)key2).getModulus())) && (((RSAPrivateKey) key1).getPrivateExponent().equals( ((RSAPrivateKey) key2).getPrivateExponent()))) { return true; } } return false; }
JAVA
Methods (MET), λ©”μ„œλ“œ
equals() λ©”μ„œλ“œλ₯Ό μ •μ˜ν•˜λŠ” ν΄λž˜μŠ€λŠ” hashCode() λ©”μ„œλ“œλ„ μ •μ˜ν•΄μ•Ό ν•©λ‹ˆλ‹€.
CWE-581
public final class CreditCard { private final int number; public CreditCard(int number) { this.number = number; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof CreditCard)) { return false; } CreditCard cc = (CreditCard)o; return cc.number == number; } public static void main(String[] args) { Map<CreditCard, String> m = new HashMap<CreditCard, String>(); m.put(new CreditCard(100), "4111111111111111"); System.out.println(m.get(new CreditCard(100))); } }
public final class CreditCard { private final int number; public CreditCard(int number) { this.number = number; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof CreditCard)) { return false; } CreditCard cc = (CreditCard)o; return cc.number == number; } public int hashCode() { int result = 17; result = 31 * result + number; return result; } public static void main(String[] args) { Map<CreditCard, String> m = new HashMap<CreditCard, String>(); m.put(new CreditCard(100), "4111111111111111"); System.out.println(m.get(new CreditCard(100))); } }