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 | Serialization (SER) | ์ง๋ ฌํ ๋ฐฉ๋ฒ์ ์ ์ ํ ์๋ช
์์ ๋ฒ์ด๋์ง ๋ง์ญ์์ค. | CWE-502 ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ์ญ์ง๋ ฌํ | public class NonCompliantClass implements Serializable {
private static final long serialVersionUID = 1L;
// ์๋ชป๋ ์ ๊ทผ ์ ํ์: public
public void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
// ์๋ชป๋ ์ ๊ทผ ์ ํ์: public
public void readObject(ObjectInputStrea... | public class CompliantClass implements Serializable {
private static final long serialVersionUID = 1L;
// ์ฌ๋ฐ๋ฅธ ์ ๊ทผ ์ ํ์: private
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
}
// ์ฌ๋ฐ๋ฅธ ์ ๊ทผ ์ ํ์: private
private void readObject(ObjectInputStre... |
JAVA | Serialization (SER) | ์ง๋ ฌํ ๋ฐฉ๋ฒ์ ์ ์ ํ ์๋ช
์์ ๋ฒ์ด๋์ง ๋ง์ญ์์ค. | CWE-502 ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ์ญ์ง๋ ฌํ | public class NonCompliantClass implements Serializable {
private static final long serialVersionUID = 1L;
// ์๋ชป๋ ์๊ทธ๋์ฒ: private
private Object readResolve() {
// ...
return this;
}
// ์๋ชป๋ ์๊ทธ๋์ฒ: private
private Object writeReplace() {
// ...
return this;
}
} | public class CompliantClass implements Serializable {
private static final long serialVersionUID = 1L;
// ์ฌ๋ฐ๋ฅธ ์๊ทธ๋์ฒ: protected
protected Object readResolve() {
// ...
return this;
}
// ์ฌ๋ฐ๋ฅธ ์๊ทธ๋์ฒ: protected
protected Object writeReplace() {
// ...
return this;
... |
JAVA | Serialization (SER) | ๊ฐ์ฒด๋ฅผ ํธ๋ฌ์คํธ ๊ฒฝ๊ณ ๋ฐ์ผ๋ก ๋ณด๋ด๊ธฐ ์ ์ ์๋ช
ํ๊ณ ๋ด์ธํ๊ธฐ | CWE-319 ๋ฏผ๊ฐํ ์ ๋ณด์ ํ๋ฌธ ์ ์ก | public class MapSerializer {
public static void main(String[] args) throws IOException, ClassNotFoundException {
// ๋งต ์์ฑ
SerializableMap<String, Integer> map = buildMap();
// ๋งต ์ง๋ ฌํ
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("map.ser"))) {
o... | public class MapSerializer {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
private static final String SIGNATURE_ALGORITHM = "SHA256withRSA";
public static void main(String[] args) throws Exception {
// ํค ๋ฐ ์๋ช
๊ฐ์ฒด ์ด๊ธฐํ
... |
JAVA | Serialization (SER) | ์ํธํ๋์ง ์์ ๋ฏผ๊ฐํ ๋ฐ์ดํฐ๋ฅผ ์ง๋ ฌํํ์ง ๋ง์ญ์์ค. | CWE-499 ๋ฏผ๊ฐํ ๋ฐ์ดํฐ๋ฅผ ํฌํจํ ์ง๋ ฌํ ๊ฐ๋ฅํ ํด๋์ค, CWE-502 ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ์ญ์ง๋ ฌํ | public class Point implements Serializable {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point() {
// No-argument constructor
}
}
public class Coordinates extends Point {
public static void main(String[] args) {
FileOutputSt... | public class Point implements Serializable {
private transient double x; // Declared transient
private transient double y; // Declared transient
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public Point() {
// No-argument constructor
}
}
public class Coordinates extends Point {
publ... |
JAVA | Serialization (SER) | ์ํธํ๋์ง ์์ ๋ฏผ๊ฐํ ๋ฐ์ดํฐ๋ฅผ ์ง๋ ฌํํ์ง ๋ง์ญ์์ค. | CWE-499 ๋ฏผ๊ฐํ ๋ฐ์ดํฐ๋ฅผ ํฌํจํ ์ง๋ ฌํ ๊ฐ๋ฅํ ํด๋์ค, CWE-502 ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ์ญ์ง๋ ฌํ | public class SensitiveClass extends Number {
// ... Implement abstract methods, such as Number.doubleValue()รขยยฆ
private static final SensitiveClass INSTANCE = new SensitiveClass();
public static SensitiveClass getInstance() {
return INSTANCE;
}
private SensitiveClass() {
// Perform security checks... | class SensitiveClass extends Number {
// ...
private final Object writeObject(java.io.ObjectOutputStream out) throws NotSerializableException {
throw new NotSerializableException();
}
private final Object readObject(java.io.ObjectInputStream in) throws NotSerializableException {
throw new NotSerializa... |
JAVA | Serialization (SER) | ์ง๋ ฌํ์ ์ญ์ง๋ ฌํ๊ฐ ๋ณด์ ๊ด๋ฆฌ์๋ฅผ ์ฐํํ์ง ์๋๋ก ํ์ญ์์ค. | null | public final class Hometown implements Serializable {
// Private internal state
private String town;
private static final String UNKNOWN = "UNKNOWN";
void performSecurityManagerCheck() throws AccessDeniedException {
// ...
}
void validateInput(String newCC) throws InvalidInputException {
// ...
... | public final class Hometown implements Serializable {
// ... All methods the same except the following:
// writeObject() correctly enforces checks during serialization
private void writeObject(ObjectOutputStream out) throws IOException {
performSecurityManagerCheck();
out.writeObject(town);
}
// r... |
JAVA | Serialization (SER) | ๋ด๋ถ ํด๋์ค์ ์ธ์คํด์ค๋ฅผ ์ง๋ ฌํํ์ง ๋ง์ญ์์ค. | CWE-499 ๋ฏผ๊ฐํ ๋ฐ์ดํฐ๋ฅผ ํฌํจํ ์ง๋ ฌํ ๊ฐ๋ฅํ ํด๋์ค | public class OuterSer implements Serializable {
private int rank;
class InnerSer implements Serializable {
protected String name;
// ...
}
} | public class OuterSer implements Serializable {
private int rank;
class InnerSer {
protected String name;
// ...
}
} |
JAVA | Serialization (SER) | ๋ด๋ถ ํด๋์ค์ ์ธ์คํด์ค๋ฅผ ์ง๋ ฌํํ์ง ๋ง์ญ์์ค. | CWE-499 ๋ฏผ๊ฐํ ๋ฐ์ดํฐ๋ฅผ ํฌํจํ ์ง๋ ฌํ ๊ฐ๋ฅํ ํด๋์ค | public class OuterSer implements Serializable {
private int rank;
class InnerSer implements Serializable {
protected String name;
// ...
}
} | public class OuterSer implements Serializable {
private int rank;
static class InnerSer implements Serializable {
protected String name;
// ...
}
} |
JAVA | Serialization (SER) | ์ญ์ง๋ ฌํ ์ private ๋ณ๊ฒฝ ๊ฐ๋ฅํ ๊ตฌ์ฑ ์์๋ฅผ ๋ฐฉ์ด์ ์ผ๋ก ๋ณต์ฌํ์ญ์์ค. | CWE-502 ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ์ญ์ง๋ ฌํ | class MutableSer implements Serializable {
private static final Date epoch = new Date(0);
private Date date = null; // Mutable component
public MutableSer(Date d){
date = new Date(d.getTime()); // Constructor performs defensive copying
}
private void readObject(ObjectInputStream ois) throws IOExcept... | private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = ois.readFields();
Date inDate = (Date) fields.get("date", epoch);
// Defensively copy the mutable component
date = new Date(inDate.getTime());
// Perform validation if necessary
} |
JAVA | Serialization (SER) | ๊ตฌํ์ ์ ์๋ ๋ถ๋ณ ์กฐ๊ฑด์ ๊ฐ์ง ํด๋์ค์ ๋ํด ๊ธฐ๋ณธ ์ง๋ ฌํ ํ์์ ์ฌ์ฉํ์ง ๋ง์ญ์์ค. | null | public class NumberData extends Number {
// ... Implement abstract Number methods, like Number.doubleValue()...
private static final NumberData INSTANCE = new NumberData ();
public static NumberData getInstance() {
return INSTANCE;
}
private NumberData() {
// Perform security checks and parameter ... | public class NumberData extends Number {
// ...
protected final Object readResolve() throws NotSerializableException {
return INSTANCE;
}
} |
JAVA | Serialization (SER) | ๊ตฌํ์ ์ ์๋ ๋ถ๋ณ ์กฐ๊ฑด์ ๊ฐ์ง ํด๋์ค์ ๋ํด ๊ธฐ๋ณธ ์ง๋ ฌํ ํ์์ ์ฌ์ฉํ์ง ๋ง์ญ์์ค. | null | public class Lottery implements Serializable {
private int ticket = 1;
private SecureRandom draw = new SecureRandom();
public Lottery(int ticket) {
this.ticket = (int) (Math.abs(ticket % 20000) + 1);
}
public int getTicket() {
return this.ticket;
}
public int roll() {
this.ticket = (int... | public final class Lottery implements Serializable {
// ...
private synchronized void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = s.readFields();
int ticket = fields.get("ticket", 0);
if (ticket > 20000 |... |
JAVA | Serialization (SER) | ๊ตฌํ์ ์ ์๋ ๋ถ๋ณ ์กฐ๊ฑด์ ๊ฐ์ง ํด๋์ค์ ๋ํด ๊ธฐ๋ณธ ์ง๋ ฌํ ํ์์ ์ฌ์ฉํ์ง ๋ง์ญ์์ค. | CWE-502 ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ์ญ์ง๋ ฌํ | public class AtomicReferenceArray<E> implements java.io.Serializable {
private static final long serialVersionUID = -6209656149925076980L;
// Rest of class...
// No readObject() method, relies on default readObject
} | public class AtomicReferenceArray<E> implements java.io.Serializable {
private static final long serialVersionUID = -6209656149925076980L;
// Rest of class...
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
* @param s the stream
*/
private void readObject(java.io.ObjectIn... |
JAVA | Serialization (SER) | ๊ถํ์ด ์๋ ์ปจํ
์คํธ์์ ์ญ์ง๋ ฌํํ๊ธฐ ์ ์ ๊ถํ์ ์ต์ํํ์ญ์์ค. | CWE-250 ๋ถํ์ํ ๊ถํ์ผ๋ก ์คํ | import java.io.*;
import java.security.*;
public class NonCompliantExample {
public static void main(String[] args) throws Exception {
// ๊ถํ์ด ๋ถ์ฌ๋ ์ปจํ
์คํธ์์ ์ญ์ง๋ ฌํ ์ํ
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
try (ObjectInputStream ois = new ObjectInputStream(new... | import java.io.*;
import java.security.*;
public class CompliantExample {
public static void main(String[] args) throws Exception {
// ์ต์ ๊ถํ์ผ๋ก ์ญ์ง๋ ฌํ ์ํ
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
// ํ์ํ ์ต์ ๊ถํ ์ค์
PermissionCollection minimalPermissi... |
JAVA | Serialization (SER) | readObject() ๋ฉ์๋์์ ์ฌ์ ์ ๊ฐ๋ฅํ ๋ฉ์๋๋ฅผ ํธ์ถํ์ง ๋ง์ญ์์ค. | null | private void readObject(final ObjectInputStream stream)
throws IOException, ClassNotFoundException {
overridableMethod();
stream.defaultReadObject();
}
public void overridableMethod() {
// ...
} | private void readObject(final ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
} |
JAVA | Serialization (SER) | ์ง๋ ฌํ ๊ณผ์ ์์ ๋ฉ๋ชจ๋ฆฌ ๋ฐ ์์ ๋์๋ฅผ ๋ฐฉ์งํ์ญ์์ค. | CWE-400 ํต์ ๋์ง ์์ ์์ ์๋น (์ผ๋ช
"์์ ๊ณ ๊ฐ"), CWE-770 ์ ํ ๋๋ ์กฐ์ ์์ด ์์ ํ ๋น | class SensorData implements Serializable {
// 1 MB of data per instance!
...
public static SensorData readSensorData() {...}
public static boolean isAvailable() {...}
}
class SerializeSensorData {
public static void main(String[] args) throws IOException {
ObjectOutputStream out = null;
try {
... | class SerializeSensorData {
public static void main(String[] args) throws IOException {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream("ser.dat")));
while (SensorData.isAvailable()) {
// Note that each SensorData o... |
JAVA | Serialization (SER) | ์ธ๋ถํ ๊ฐ๋ฅํ ๊ฐ์ฒด๊ฐ ๋ฎ์ด์ฐ์ด์ง ์๋๋ก ๋ฐฉ์งํ์ญ์์ค. | null | public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// Read instance fields
this.name = (String) in.readObject();
this.UID = in.readInt();
// ...
} | private final Object lock = new Object();
private boolean initialized = false;
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
synchronized (lock) {
if (!initialized) {
// Read instance fields
this.name = (String) in.readObject();
... |
JAVA | Serialization (SER) | ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ์ญ์ง๋ ฌํ๋ฅผ ๋ฐฉ์งํ์ญ์์ค. | CWE-502 ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ์ญ์ง๋ ฌํ | import java.io.*;
class DeserializeExample {
public static Object deserialize(byte[] buffer) throws IOException, ClassNotFoundException {
Object ret = null;
try (ByteArrayInputStream bais = new ByteArrayInputStream(buffer)) {
try (ObjectInputStream ois = new ObjectInputStream(bais)) {
ret = oi... | import java.io.*;
import java.util.*;
class WhitelistedObjectInputStream extends ObjectInputStream {
public Set whitelist;
public WhitelistedObjectInputStream(InputStream inputStream, Set wl) throws IOException {
super(inputStream);
whitelist = wl;
}
@Override
protected Class<?> resolveClass(Ob... |
JAVA | Platform Security (SEC) | ๊ถํ์ด ๋ถ์ฌ๋ ๋ธ๋ก์ด ์ ๋ขฐ ๊ฒฝ๊ณ๋ฅผ ๋์ด ๋ฏผ๊ฐํ ์ ๋ณด๋ฅผ ๋์ถํ์ง ์๋๋ก ํ์ญ์์ค. | CWE-266 ๋ถ์ ์ ํ ๊ถํ ํ ๋น, CWE-272 ์ต์ ๊ถํ ์๋ฐ | public class PasswordManager {
public static void changePassword() throws FileNotFoundException {
FileInputStream fin = openPasswordFile();
// ๊ธฐ์กด ๋น๋ฐ๋ฒํธ ํ์ธ ๋ฐ ๋ณ๊ฒฝ ๋ก์ง
}
public static FileInputStream openPasswordFile() throws FileNotFoundException {
final String passwordFile = "password"... | public class PasswordManager {
public static void changePassword() throws FileNotFoundException {
// ๋น๋ฐ๋ฒํธ ๋ณ๊ฒฝ ๋ก์ง
try (FileInputStream fin = openPasswordFile()) {
// ๊ธฐ์กด ๋น๋ฐ๋ฒํธ ํ์ธ ๋ฐ ๋ณ๊ฒฝ ๋ก์ง
} catch (IOException e) {
// ์์ธ ์ฒ๋ฆฌ
}
}
private static FileInputStre... |
JAVA | Platform Security (SEC) | ๊ถํ ๋ธ๋ก์์ ์ค์ผ๋ ๋ณ์๋ฅผ ํ์ฉํ์ง ์์ต๋๋ค. | CWE-266 ๋ถ์ ์ ํ ๊ถํ ํ ๋น, CWE-272 ์ต์ ๊ถํ ์๋ฐ, CWE-732 ์ค์ํ ๋ฆฌ์์ค์ ๋ํ ๋ถ์ ์ ํ ๊ถํ ํ ๋น | private void privilegedMethod(final String filename) throws FileNotFoundException {
try {
FileInputStream fis = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoundException {
return... | private void privilegedMethod(final String filename) throws FileNotFoundException {
final String cleanFilename;
try {
cleanFilename = cleanAFilenameAndPath(filename);
} catch (Exception e) {
// cleanAFilenameAndPath ๋ฉ์๋์ ์ฌ์์ ๋ฐ๋ฅธ ์์ธ ์ฒ๋ฆฌ
return;
}
try {
FileInputStream fi... |
JAVA | Platform Security (SEC) | ๊ถํ ๋ธ๋ก์์ ์ค์ผ๋ ๋ณ์๋ฅผ ํ์ฉํ์ง ์์ต๋๋ค. | CWE-266 ๋ถ์ ์ ํ ๊ถํ ํ ๋น, CWE-272 ์ต์ ๊ถํ ์๋ฐ, CWE-732 ์ค์ํ ๋ฆฌ์์ค์ ๋ํ ๋ถ์ ์ ํ ๊ถํ ํ ๋น | private void privilegedMethod(final String filename) throws FileNotFoundException {
try {
FileInputStream fis = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoundException {
return... | private void privilegedMethod() throws FileNotFoundException {
final String trustedFilename = "/path/to/trusted/file";
try {
FileInputStream fis = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoun... |
JAVA | Platform Security (SEC) | ์ ๋ขฐํ ์ ์๋ ์ฝ๋๊ฐ ์์์ ํด๋์ค๋ฅผ ๋ก๋ํ๋๋ก ํ์ฉํ ํ ์ ๋ขฐํ ์ ์๋ ํด๋์ค๋ฅผ ๋ก๋ํ์ง ๋ง์ญ์์ค. | null | public class NonCompliantExample {
public static void main(String[] args) {
// ์ ๋ขฐํ ์ ์๋ ์ฝ๋๊ฐ ์์์ ํด๋์ค๋ฅผ ๋ก๋ํ๋๋ก ํ์ฉ
UntrustedClassLoader untrustedLoader = new UntrustedClassLoader();
untrustedLoader.loadClass("com.example.TrustedClass");
// ์ดํ์ ์ ๋ขฐํ ์ ์๋ ํด๋์ค ๋ก๋
Class.forName("com.e... | public class CompliantExample {
public static void main(String[] args) {
// ์ ๋ขฐํ ์ ์๋ ํด๋์ค ๋จผ์ ๋ก๋
Class.forName("com.example.TrustedClass");
// ์ดํ์ ์ ๋ขฐํ ์ ์๋ ์ฝ๋๊ฐ ์์์ ํด๋์ค๋ฅผ ๋ก๋ํ๋๋ก ํ์ฉ
UntrustedClassLoader untrustedLoader = new UntrustedClassLoader();
untrustedLoader.loadClass("com.e... |
JAVA | Platform Security (SEC) | ๋ฆฌํ๋ ์
์ ์ฌ์ฉํ์ฌ ํด๋์ค, ๋ฉ์๋ ๋๋ ํ๋์ ์ ๊ทผ์ฑ์ ๋์ด์ง ๋ง๋ผ | null | import java.lang.reflect.Field;
public class FieldExample {
private int i = 3;
private int j = 4;
public void zeroField(String fieldName) {
try {
Field field = this.getClass().getDeclaredField(fieldName);
field.setAccessible(true); // ์ ๊ทผ์ฑ ์ฆ๊ฐ
field.setInt(this, 0... | public class FieldExample {
private int i = 3;
private int j = 4;
public void zeroI() {
this.i = 0;
}
public void zeroJ() {
this.j = 0;
}
@Override
public String toString() {
return "FieldExample: i=" + i + ", j=" + j;
}
public static void main(String[... |
JAVA | Platform Security (SEC) | ์ ๋ขฐํ ์ ์๋ ์์ค๋ฅผ ๊ธฐ๋ฐ์ผ๋ก ๋ณด์ ๊ฒ์ฌ๋ฅผ ์ํํ์ง ๋ง์ธ์. | CWE-302 ๊ฐ์ ๋ ๋ถ๋ณ ๋ฐ์ดํฐ๋ฅผ ํตํ ์ธ์ฆ ์ฐํ, CWE-470 ์ธ๋ถ์์ ์ ์ด๋๋ ์
๋ ฅ์ ์ฌ์ฉํ์ฌ ํด๋์ค๋ ์ฝ๋๋ฅผ ์ ํ ("์์ ํ์ง ์์ ๋ฆฌํ๋ ์
") | public RandomAccessFile openFile(final java.io.File f) {
askUserPermission(f.getPath());
// ...
return (RandomAccessFile) AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return new RandomAccessFile(f, f.getPath());
}
});
} | public RandomAccessFile openFile(java.io.File f) {
final java.io.File copy = new java.io.File(f.getPath());
askUserPermission(copy.getPath());
// ...
return (RandomAccessFile) AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
return new RandomAccessFile(copy, copy.ge... |
JAVA | Platform Security (SEC) | ๋ณด์ ๊ด๋ฆฌ์ ์ ๊ฒ์ผ๋ก ๋ฏผ๊ฐํ ์์
๋ณดํธ | null | class SensitiveHash {
private Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
public void removeEntry(Object key) {
ht.remove(key);
}
} | class SensitiveHash {
private Hashtable<Integer,String> ht = new Hashtable<Integer,String>();
public void removeEntry(Object key) {
check("removeKeyPermission");
ht.remove(key);
}
private void check(String directive) {
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
... |
JAVA | Platform Security (SEC) | ๋ณด์ ๊ด๋ฆฌ์ ์ ๊ฒ์ผ๋ก ๋ฏผ๊ฐํ ์์
๋ณดํธ | null | SecurityManager sm = System.getSecurityManager();
if (sm != null) { // Check whether file may be read
sm.checkRead("/local/schema.dtd");
} | SecurityManager sm = System.getSecurityManager();
if (sm != null) { // Check whether file may be read
DTDPermission perm = new DTDPermission("/local/", "readDTD");
sm.checkPermission(perm);
} |
JAVA | Platform Security (SEC) | ๋ณด์ ๊ด๋ฆฌ์ ์ ๊ฒ์ผ๋ก ๋ฏผ๊ฐํ ์์
๋ณดํธ | null | SecurityManager sm = System.getSecurityManager();
if (sm != null) { // Check whether file may be read
sm.checkRead("/local/schema.dtd");
} | // Take the snapshot of the required context, store in acc, and pass it to another context
AccessControlContext acc = AccessController.getContext();
// Accept acc in another context and invoke checkPermission() on it
acc.checkPermission(perm); |
JAVA | Platform Security (SEC) | URLClassLoader์ java.util.jar์์ ์ ๊ณตํ๋ ๊ธฐ๋ณธ ์๋ ์๋ช
๊ฒ์ฆ์ ์์กดํ์ง ๋ง๋ผ | CWE-300 ๋น์ข
๋จ์ ์ ์ํด ์ ๊ทผ ๊ฐ๋ฅํ ์ฑ๋ (์ผ๋ช
"์ค๊ฐ์ ๊ณต๊ฒฉ, Man-in-the-Middle"), CWE-319 ๋ฏผ๊ฐํ ์ ๋ณด์ ํ๋ฌธ ์ ์ก, CWE-347 ์ํธํ ์๋ช
์ ๋ถ์ ์ ํ ๊ฒ์ฆ, CWE-494 ๋ฌด๊ฒฐ์ฑ ํ์ธ ์์ด ์ฝ๋ ๋ค์ด๋ก๋ | import java.net.URL;
import java.net.URLClassLoader;
public class JarRunner {
public static void main(String[] args) throws Exception {
URL url = new URL(args[0]);
URLClassLoader loader = new URLClassLoader(new URL[]{url});
String className = args[1];
Class<?> cls = loader.loadClass... | import java.io.File;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
public class SecureJarLoader {
public static voi... |
JAVA | Platform Security (SEC) | ์ฌ์ฉ์ ์ ์ ํด๋์ค ๋ก๋๋ฅผ ์์ฑํ ๋ ์ํผํด๋์ค์ getPermissions() ๋ฉ์๋๋ฅผ ํธ์ถํฉ๋๋ค. | null | protected PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = new Permissions();
// Allow exit from the VM anytime
pc.add(new RuntimePermission("exitVM"));
return pc;
} | protected PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = super.getPermissions(cs);
// Allow exit from the VM anytime
pc.add(new RuntimePermission("exitVM"));
return pc;
} |
JAVA | Runtime Environment (ENV) | ๋ชจ๋ ๋ณด์์ ๋ฏผ๊ฐํ ์ฝ๋๋ฅผ ํ๋์ JAR์ ๋ฃ๊ณ ์๋ช
๋ฐ ๋ด์ธํ์ธ์. | CWE-349 ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ํจ๊ป ๋ถํ์ํ ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ๋ฅผ ์์ฉ | package trusted;
import untrusted.RetValue;
public class MixMatch {
private void privilegedMethod() throws IOException {
try {
AccessController.doPrivileged(
new PrivilegedExceptionAction<Void>() {
public Void run() throws IOException, FileNotFoundException {
final FileInputS... | package trusted;
public class MixMatch {
// ...
}
// In the same signed & sealed JAR file:
package trusted;
class RetValue {
int getValue() {
return 1;
}
} |
JAVA | Runtime Environment (ENV) | ๋ชจ๋ ๋ณด์์ ๋ฏผ๊ฐํ ์ฝ๋๋ฅผ ํ๋์ JAR์ ๋ฃ๊ณ ์๋ช
๋ฐ ๋ด์ธํ์ธ์. | CWE-349 ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ํจ๊ป ๋ถํ์ํ ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ๋ฅผ ์์ฉ | package trusted;
import untrusted.RetValue;
public class MixMatch {
private void privilegedMethod() throws IOException {
try {
final FileInputStream fis = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoundExc... | package trusted;
public class MixMatch {
// ...
}
// In the same signed & sealed JAR file:
package trusted;
class RetValue {
int getValue() {
return 1;
}
} |
JAVA | Runtime Environment (ENV) | ํ๊ฒฝ ๋ณ์์ ๊ฐ์ ์ ๋ขฐํ์ง ๋ง๋ผ | null | String username = System.getenv("USER"); | String username = System.getProperty("user.name"); |
JAVA | Runtime Environment (ENV) | ์ํํ ๊ถํ ์กฐํฉ์ ๋ถ์ฌํ์ง ๋ง๋ผ | CWE-732 ์ค์ํ ๋ฆฌ์์ค์ ๋ํ ๋ถ์ ์ ํ ๊ถํ ํ ๋น | // ๋ณด์ ์ ์ฑ
ํ์ผ์ ๋ด์ฉ
grant codeBase "file:${klib.home}/j2se/home/klib.jar" {
permission java.security.AllPermission;
}; | // ๋ณด์ ์ ์ฑ
ํ์ผ์ ๋ด์ฉ
grant codeBase "file:${klib.home}/j2se/home/klib.jar", signedBy "Admin" {
permission java.io.FilePermission "/tmp/*", "read";
permission java.net.SocketPermission "*", "connect";
}; |
JAVA | Runtime Environment (ENV) | ๋ฐ์ดํธ์ฝ๋ ํ์ธ์ ๋นํ์ฑํํ์ง ๋ง์ธ์. | null | java -Xverify:none ApplicationName | java -Xverify:all ApplicationName |
JAVA | Runtime Environment (ENV) | ์๊ฒฉ์ผ๋ก ๋ชจ๋ํฐ๋งํ ์ ์๋ ์ ํ๋ฆฌ์ผ์ด์
์ ๋ฐฐํฌํ์ง ๋ง๋ผ | null | // JVM ์ต์
์ ์๊ฒฉ ๋ชจ๋ํฐ๋ง์ ํ์ฑํํ๋ ์ค์
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=12345
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false | // ์๊ฒฉ ๋ชจ๋ํฐ๋ง์ ๋นํ์ฑํํ JVM ์ต์
// (ํน๋ณํ ์ค์ ์ด ์์ผ๋ฉด ์๊ฒฉ ๋ชจ๋ํฐ๋ง์ ๊ธฐ๋ณธ์ ์ผ๋ก ๋นํ์ฑํ๋์ด ์์ต๋๋ค.) |
JAVA | Runtime Environment (ENV) | ํ๋ก๋์
์ฝ๋์๋ ๋๋ฒ๊น
์ง์
์ ์ ํฌํจํ์ง ๋ง๋ผ | null | class Stuff {
private static final boolean DEBUG = false;
// ๊ธฐํ ํ๋์ ๋ฉ์๋
public static void main(String[] args) {
Stuff.DEBUG = true;
Stuff stuff = new Stuff();
// ํ
์คํธ ์ฝ๋
}
} | class Stuff {
// ๊ธฐํ ํ๋์ ๋ฉ์๋
} |
JAVA | Java Native Interface (JNI) | ๋ค์ดํฐ๋ธ ๋ฉ์๋์ ๋ํผ ์ ์ | CWE-111 ์์ ํ์ง ์์ JNI์ ์ง์ ์ฌ์ฉ | public final class NativeMethod {
// Public native method
public native void nativeOperation(byte[] data, int offset, int len);
// Wrapper method that lacks security checks and input validation
public void doOperation(byte[] data, int offset, int len) {
nativeOperation(data, offset, len);
}
stat... | public final class NativeMethodWrapper {
// Private native method
private native void nativeOperation(byte[] data, int offset, int len);
// Wrapper method performs SecurityManager and input validation checks
public void doOperation(byte[] data, int offset, int len) {
// Permission needed to invoke nativ... |
JAVA | Java Native Interface (JNI) | ์ฆ์ ํธ์ถ์์ ํด๋์ค ๋ก๋ ์ธ์คํด์ค๋ฅผ ์ฌ์ฉํ์ฌ ์์
์ ์ํํ๋ ํ์ค API(loadLibrary)๋ฅผ ์์ ํ๊ฒ ํธ์ถํ์ญ์์ค. | CWE-111 ์์ ํ์ง ์์ JNI์ ์ง์ ์ฌ์ฉ | // Trusted.java
import java.security.*;
public class Trusted {
public static void loadLibrary(final String library){
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
System.loadLibrary(library);
return null;
}
});
}
}
... | // Trusted.java
import java.security.*;
public class Trusted {
// load native libraries
static{
System.loadLibrary("NativeMethodLib1");
System.loadLibrary("NativeMethodLib2");
...
}
// private native methods
private native void nativeOperation1(byte[] data, int offset, int len);... |
JAVA | ๊ธฐํ | ๋ณด์ ๋ฐ์ดํฐ ๊ตํ์ ์ํด Socket ๋์ SSLSocket์ ์ฌ์ฉํ์ญ์์ค. | CWE-311 ๋ฏผ๊ฐํ ๋ฐ์ดํฐ ์ํธํ ์คํจ | // Exception handling has been omitted for the sake of brevity
class EchoServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(9999);
Socket socket = serverSocket.accept();
PrintWriter out = new PrintWrite... | // Exception handling has been omitted for the sake of brevity
class EchoServer {
public static void main(String[] args) throws IOException {
SSLServerSocket sslServerSocket = null;
try {
SSLServerSocketFactory sslServerSocketFactory =
(SSLServerSocketFactory) SSLServerSocketFactory.getDefault... |
JAVA | ๊ธฐํ | ๋น(๊ณต๋ฐฑ) ๋ฌดํ ๋ฃจํ๋ฅผ ์ฌ์ฉํ์ง ๋ง์ญ์์ค. | null | public int nop() {
while (true) {}
} | public final int DURATION=10000; // In milliseconds
public void nop() throws InterruptedException {
while (true) {
// Useful operations
Thread.sleep(DURATION);
}
} |
JAVA | ๊ธฐํ | ๋น(๊ณต๋ฐฑ) ๋ฌดํ ๋ฃจํ๋ฅผ ์ฌ์ฉํ์ง ๋ง์ญ์์ค. | null | public int nop() {
while (true) {}
} | public void nop() {
while (true) {
Thread.yield();
}
} |
JAVA | ๊ธฐํ | ๊ฐ๋ ฅํ ๋์๋ฅผ ์์ฑํ๋ผ | CWE-327 ์์๋์๊ฑฐ๋ ์ํํ ์ํธํ ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉ
CWE-330 ์ถฉ๋ถํ ๋๋คํ์ง ์์ ๊ฐ์ ์ฌ์ฉ
CWE-332 PRNG์์์ ๋ถ์ถฉ๋ถํ ์ํธ๋กํผ
CWE-336 PRNG์์ ๋์ผํ ์๋ ์ฌ์ฉ
CWE-337 ์์ธก ๊ฐ๋ฅํ ์๋์ ์ฌ์ฉ in PRNG | import java.util.Random;
public class WeakRandomExample {
public static void main(String[] args) {
Random random = new Random(123L); // ๊ณ ์ ๋ ์๋ ๊ฐ ์ฌ์ฉ
for (int i = 0; i < 20; i++) {
int n = random.nextInt(21); // 0๋ถํฐ 20๊น์ง์ ์ ์ ์์ฑ
System.out.println(n);
}
}
} | import java.security.SecureRandom;
public class StrongRandomExample {
public static void main(String[] args) {
SecureRandom secureRandom = new SecureRandom();
for (int i = 0; i < 20; i++) {
int n = secureRandom.nextInt(21); // 0๋ถํฐ 20๊น์ง์ ์ ์ ์์ฑ
System.out.println(n);
}... |
JAVA | ๊ธฐํ | ๊ฐ๋ ฅํ ๋์๋ฅผ ์์ฑํ๋ผ | CWE-327 ์์๋์๊ฑฐ๋ ์ํํ ์ํธํ ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉ
CWE-330 ์ถฉ๋ถํ ๋๋คํ์ง ์์ ๊ฐ์ ์ฌ์ฉ
CWE-332 PRNG์์์ ๋ถ์ถฉ๋ถํ ์ํธ๋กํผ
CWE-336 PRNG์์ ๋์ผํ ์๋ ์ฌ์ฉ
CWE-337 ์์ธก ๊ฐ๋ฅํ ์๋์ ์ฌ์ฉ in PRNG | import java.util.Random;
public class WeakRandomExample {
public static void main(String[] args) {
Random random = new Random(123L); // ๊ณ ์ ๋ ์๋ ๊ฐ ์ฌ์ฉ
for (int i = 0; i < 20; i++) {
int n = random.nextInt(21); // 0๋ถํฐ 20๊น์ง์ ์ ์ ์์ฑ
System.out.println(n);
}
}
} | // Java 8 ์ด์์์์ ์ค์ ์ฝ๋ ์์
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class StrongRandomExample {
public static void main(String[] args) {
try {
SecureRandom secureRandom = SecureRandom.getInstanceStrong();
for (int i = 0; i < 20; i++) {
... |
JAVA | ๊ธฐํ | ๋ฏผ๊ฐํ ์ ๋ณด๋ฅผ ํ๋์ฝ๋ฉํ์ง ๋ง๋ผ | CWE-259 ํ๋์ฝ๋๋ ๋น๋ฐ๋ฒํธ ์ฌ์ฉ
CWE-798 ํ๋์ฝ๋๋ ์๊ฒฉ ์ฆ๋ช
์ฌ์ฉ | class DatabaseConfig {
private static final String DB_USERNAME = "admin";
private static final String DB_PASSWORD = "password123";
// ๊ธฐํ ์ฝ๋
} | import java.io.Console;
class DatabaseConfig {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
throw new IllegalStateException("์ฝ์์ ์ฌ์ฉํ ์ ์์ต๋๋ค.");
}
String username = console.readLine("์ฌ์ฉ์ ์ด๋ฆ: ");
char[] passwor... |
JAVA | ๊ธฐํ | ๋ฉ๋ชจ๋ฆฌ ๋์ ๋ฐฉ์ง | CWE-401 ๋ง์ง๋ง ์ฐธ์กฐ๋ฅผ ์ ๊ฑฐํ๊ธฐ ์ ์ ๋ฉ๋ชจ๋ฆฌ๋ฅผ ๋ถ์ ์ ํ๊ฒ ํด์ ("๋ฉ๋ชจ๋ฆฌ ๋์") | public class Leak {
static Vector<String> vector = new Vector<>();
public void useVector(int count) {
for (int n = 0; n < count; n++) {
vector.add(Integer.toString(n));
}
// ...
for (int n = count - 1; n > 0; n--) { // ๋ฉ๋ชจ๋ฆฌ ํด์
vector.removeElementAt(n);
... | public class Leak {
static Vector<String> vector = new Vector<>();
public void useVector(int count) {
int n = 0;
try {
for (; n < count; n++) {
vector.add(Integer.toString(n));
}
// ...
} finally {
for (n = n - 1; n >= 0; n... |
JAVA | ๊ธฐํ | ํ ๊ณต๊ฐ์ ์์งํ์ง ๋ง์ญ์์ค. | CWE-400 ํต์ ๋์ง ์์ ์์ ์๋น (์ผ๋ช
"์์ ๊ณ ๊ฐ"), CWE-770 ์ ํ ๋๋ ์กฐ์ ์์ด ์์ ํ ๋น | class ReadNames {
private Vector<String> names = new Vector<String>();
private final InputStreamReader input;
private final BufferedReader reader;
public ReadNames(String filename) throws IOException {
this.input = new FileReader(filename);
this.reader = new BufferedReader(input);
}
public void ... | class ReadNames {
// ... Other methods and variables
public static final int fileSizeLimit = 1000000;
public ReadNames(String filename) throws IOException {
long size = Files.size( Paths.get( filename));
if (size > fileSizeLimit) {
throw new IOException("File too large");
} else if (size == ... |
JAVA | ๊ธฐํ | ํ ๊ณต๊ฐ์ ์์งํ์ง ๋ง์ญ์์ค. | CWE-400 ํต์ ๋์ง ์์ ์์ ์๋น (์ผ๋ช
"์์ ๊ณ ๊ฐ"), CWE-770 ์ ํ ๋๋ ์กฐ์ ์์ด ์์ ํ ๋น | class ReadNames {
private Vector<String> names = new Vector<String>();
private final InputStreamReader input;
private final BufferedReader reader;
public ReadNames(String filename) throws IOException {
this.input = new FileReader(filename);
this.reader = new BufferedReader(input);
}
public void ... | class ReadNames {
// ... Other methods and variables
public static String readLimitedLine(Reader reader, int limit)
throws IOException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < limit; i++) {
int c = reader.read();
if (c == -1) {
... |
JAVA | ๊ธฐํ | ํ ๊ณต๊ฐ์ ์์งํ์ง ๋ง์ญ์์ค. | CWE-400 ํต์ ๋์ง ์์ ์์ ์๋น (์ผ๋ช
"์์ ๊ณ ๊ฐ"), CWE-770 ์ ํ ๋๋ ์กฐ์ ์์ด ์์ ํ ๋น | /* Assuming the heap size as 512 MB
* (calculated as 1/4 of 2GB RAM = 512MB)
* Considering long values being entered (64 bits each,
* the max number of elements would be 512MB/64 bits =
* 67108864)
*/
public class ReadNames {
// Accepts unknown number of records
Vector<Long> names = new Vector<Long>();
long ... | // ...
int count = 10000000;
// โฆ |
JAVA | ๊ธฐํ | ๋ฐ๋ณต์ด ์งํ ์ค์ผ ๋๋ ๊ธฐ๋ณธ ์ปฌ๋ ์
์ ์์ ํ์ง ๋ง์ธ์. | null | class BadIterate {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
Iterator iter = list.iterator();
while (iter.hasNext()) {
String s = (String)iter.next();
if (s.equals("one")) {
list.remove(s);
... | // ...
if (s.equals("one")) {
iter.remove();
}
// โฆ |
JAVA | ๊ธฐํ | ๋ฐ๋ณต์ด ์งํ ์ค์ผ ๋๋ ๊ธฐ๋ณธ ์ปฌ๋ ์
์ ์์ ํ์ง ๋ง์ธ์. | null | List<Widget> widgetList = new ArrayList<Widget>();
public void widgetOperation() {
// May throw ConcurrentModificationException
for (Widget w : widgetList) {
doSomething(w);
}
} | List<Widget> widgetList =
Collections.synchronizedList(new ArrayList<Widget>());
public void widgetOperation() {
synchronized (widgetList) { // Client-side locking
for (Widget w : widgetList) {
doSomething(w);
}
}
} |
JAVA | ๊ธฐํ | ๋ฐ๋ณต์ด ์งํ ์ค์ผ ๋๋ ๊ธฐ๋ณธ ์ปฌ๋ ์
์ ์์ ํ์ง ๋ง์ธ์. | null | List<Widget> widgetList = new ArrayList<Widget>();
public void widgetOperation() {
// May throw ConcurrentModificationException
for (Widget w : widgetList) {
doSomething(w);
}
} | List<Widget> widgetList = new ArrayList<Widget>();
public void widgetOperation() {
List<Widget> deepCopy = new ArrayList<Widget>();
synchronized (widgetList) { // Client-side locking
for (Object obj : widgetList) {
deepCopy.add(obj.clone());
}
}
for (Widget w : deepCopy) {
doSomething(w);
... |
JAVA | ๊ธฐํ | ๋ฐ๋ณต์ด ์งํ ์ค์ผ ๋๋ ๊ธฐ๋ณธ ์ปฌ๋ ์
์ ์์ ํ์ง ๋ง์ธ์. | null | List<Widget> widgetList = new ArrayList<Widget>();
public void widgetOperation() {
// May throw ConcurrentModificationException
for (Widget w : widgetList) {
doSomething(w);
}
} | List<Widget> widgetList = new CopyOnWriteArrayList<Widget>();
public void widgetOperation() {
for (Widget w : widgetList) {
doSomething(w);
}
} |
JAVA | ๊ธฐํ | ์ฑ๊ธํค ๊ฐ์ฒด์ ๋ค์ค ์ธ์คํด์คํ ๋ฐฉ์ง | CWE-543, ๋ฉํฐ์ค๋ ๋ ์ปจํ
์คํธ์์ ๋๊ธฐํ ์์ด ์ฑ๊ธํค ํจํด ์ฌ์ฉ | class MySingleton {
private static MySingleton instance;
protected MySingleton() {
instance = new MySingleton();
}
public static MySingleton getInstance() {
return instance;
}
} | class MySingleton {
private static final MySingleton instance = new MySingleton();
private MySingleton() {
// Private constructor prevents instantiation by untrusted callers
}
public static MySingleton getInstance() {
return instance;
}
} |
JAVA | ๊ธฐํ | ์ฑ๊ธํค ๊ฐ์ฒด์ ๋ค์ค ์ธ์คํด์คํ ๋ฐฉ์ง | CWE-543, ๋ฉํฐ์ค๋ ๋ ์ปจํ
์คํธ์์ ๋๊ธฐํ ์์ด ์ฑ๊ธํค ํจํด ์ฌ์ฉ | public static MySingleton getInstance() {
if (instance == null) {
synchronized (MySingleton.class) {
instance = new MySingleton();
}
}
return instance;
} | class MySingleton {
private static MySingleton instance;
private MySingleton() {
// Private constructor prevents instantiation by untrusted callers
}
// Lazy initialization
public static synchronized MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
... |
JAVA | ๊ธฐํ | ์ฑ๊ธํค ๊ฐ์ฒด์ ๋ค์ค ์ธ์คํด์คํ ๋ฐฉ์ง | CWE-543, ๋ฉํฐ์ค๋ ๋ ์ปจํ
์คํธ์์ ๋๊ธฐํ ์์ด ์ฑ๊ธํค ํจํด ์ฌ์ฉ | class MySingleton implements Cloneable {
private static MySingleton instance;
private MySingleton() {
// Private constructor prevents
// instantiation by untrusted callers
}
// Lazy initialization
public static synchronized MySingleton getInstance() {
if (instance == null) {
instance = n... | class MySingleton implements Cloneable {
private static MySingleton instance;
private MySingleton() {
// Private constructor prevents instantiation by untrusted callers
}
// Lazy initialization
public static synchronized MySingleton getInstance() {
if (instance == null) {
instance = new MySi... |
JAVA | ๊ธฐํ | ์ฑ๊ธํค ๊ฐ์ฒด์ ๋ค์ค ์ธ์คํด์คํ ๋ฐฉ์ง | CWE-543, ๋ฉํฐ์ค๋ ๋ ์ปจํ
์คํธ์์ ๋๊ธฐํ ์์ด ์ฑ๊ธํค ํจํด ์ฌ์ฉ | {
ClassLoader cl1 = new MyClassLoader();
Class class1 = cl1.loadClass(MySingleton.class.getName());
Method classMethod =
class1.getDeclaredMethod("getInstance", new Class[] { });
Object singleton = classMethod.invoke(null, new Object[] { });
System.out.println(singleton.hashCode());
}
ClassLoader cl1 ... | {
ClassLoader cl1 = new MyClassLoader();
Class class1 = cl1.loadClass(MySingleton.class.getName());
Method classMethod =
class1.getDeclaredMethod("getInstance", new Class[] { });
Object singleton = classMethod.invoke(null, new Object[] { });
ObjectPreserver.preserveObject(singleton); // Preserve the obj... |
JAVA | ๊ธฐํ | ์๋ธ๋ฆฟ ๋ด์์ ์ธ์
์ ๋ณด๊ฐ ์ ์ถ๋์ง ์๋๋ก ํ๊ธฐ | CWE-543, ๋ฉํฐ์ค๋ ๋ ์ปจํ
์คํธ์์ ๋๊ธฐํ ์์ด ์ฑ๊ธํค ํจํด ์ฌ์ฉ | public class SampleServlet extends HttpServlet {
private String lastAddr = "nobody@nowhere.com";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.pr... | public class SampleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
String emailAddr = request.ge... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-134, ์ธ๋ถ์์ ์ ์ด๋๋ Format String ์ฌ์ฉ | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
import sys
# Simulating a global include of sensitive information:
ENCRYPTION_KEY = "FL4G1"
# Simulating a include per language:
MESSAGE = "Contract '{0.instance_name}' created for "
class MicroS... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
import sys
from string import Template
# Simulating a global include of sensitive information:
ENCRYPTION_KEY = "FL4G1"
# Simulating a include per language for international support:
MESSAGE = Template... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-197, Numeric Truncation Error | """ Non-compliant Code Example """
counter = 0.0
while counter <= 1.0:
if counter == 0.8:
print("we reached 0.8")
break # never going to reach this
counter += 0.1 | """ Compliant Code Example """
counter = 0
while counter <= 10:
value = counter/10
if value == 0.8:
print("we reached 0.8")
break
counter += 1 |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-197, Numeric Truncation Error | """ Non-compliant Code Example """
counter = 1.0 + 1e-16
target = 1.0 + 1e-15
while counter <= target: # never ends
print(f"counter={counter / 10**16 :.20f}")
print(f" target={target / 10**16:.20f}")
counter += 1e-16 | """ Compliant Code Example """
counter = 1
target = 10
while counter <= target:
print(f"counter={counter / 10**16 :.20f}")
print(f" target={target / 10**16:.20f}")
counter += 1 |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-400, ํต์ ๋์ง ์์ ์์ ์๋น (์ผ๋ช
"์์ ๊ณ ๊ฐ") | """ Non-compliant Code Example """
import time
from concurrent.futures import ThreadPoolExecutor
def take_time(x):
print(f"Started Task: {x}")
# Simulate work
for i in range(10):
time.sleep(1)
print(f"Completed Task: {x}")
def run_thread(_executor, var):
future = _executor.submit(take_ti... | """ Compliant Code Example """
import time
from concurrent.futures import ThreadPoolExecutor
from threading import Event
def take_time(x, _event):
print(f"Started Task: {x}")
# Simulate work
for _ in range(10):
if _event.is_set():
print(f"Interrupted Task: {x}")
# Save part... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-409, ๊ณ ์์ถ ๋ฐ์ดํฐ์ ๋ถ์ ์ ํ ์ฒ๋ฆฌ(๋ฐ์ดํฐ ์ฆํญ) | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
import zipfile
with zipfile.ZipFile("zip_attack_test.zip", mode="r") as archive:
archive.extractall() | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
import zipfile
from pathlib import Path
MAXSIZE = 100 * 1024 * 1024 # limit is in bytes
MAXAMT = 5 # max amount of files, includes directories in the archive
class ZipExtractException(Exception):
... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-409, ๊ณ ์์ถ ๋ฐ์ดํฐ์ ๋ถ์ ์ ํ ์ฒ๋ฆฌ(๋ฐ์ดํฐ ์ฆํญ) | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
import zipfile
MAXSIZE = 100 * 1024 * 1024 # limit is in bytes
with zipfile.ZipFile("zip_attack_test.zip", mode="r") as archive:
for member in archive.infolist():
if member.file_size >=... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
import zipfile
from pathlib import Path
MAXSIZE = 100 * 1024 * 1024 # limit is in bytes
MAXAMT = 5 # max amount of files, includes directories in the archive
class ZipExtractException(Exception):
... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-410, ์์ ํ ๋ถ์กฑ | """ Non-compliant Code Example """
import logging
import threading
import time
logging.basicConfig(level=logging.INFO)
def process_message(message: str, processed_messages: list):
""" Method simulating mediation layer i/o heavy work"""
logging.debug("process_message: started message %s working %is", messag... | """ Compliant Code Example """
import logging
import time
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import wait
logging.basicConfig(level=logging.INFO)
def process_message(message: str):
""" Method simulating mediation layer i/o heavy work"""
logging.debug("process_message: st... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-410, ์์ ํ ๋ถ์กฑ | """ Non-compliant Code Example """
import logging
import time
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import wait
logging.basicConfig(level=logging.INFO)
def process_message(message: str):
""" Method simulating mediation layer i/o heavy work"""
logging.debug("process_message... | """ Compliant Code Example """
import logging
import time
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import wait
logging.basicConfig(level=logging.INFO)
def process_message(message: str):
""" Method simulating mediation layer i/o heavy work"""
logging.debug("process_message: st... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-426, ์ ๋ขฐํ ์ ์๋ ๊ฒ์ ๊ฒฝ๋ก | # Non-compliant Code Example
python3 -m http.server -b 127.0.0.42 8080 | # Compliant Code Example
python3 -I --check-hash-based-pycs always -m http.server -b 127.0.0.42 8080 |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-502, ์ ๋ขฐํ ์ ์๋ ๋ฐ์ดํฐ์ ์ญ์ง๋ ฌํ | """ Non-Compliant Code Example """
import platform
import pickle
class Message(object):
"""Sample Message Object"""
sender_id = 42
text = "Some text"
def printout(self):
"""prints content to stdout to demonstrate active content"""
print(f"Message:sender_id={self.sender_id} text={self.... | """ Compliant Code Example """
import platform
import json
class Message(object):
"""Sample Message Object"""
sender_id = int()
text = str()
def __init__(self):
self.sender_id = 42
self.text = "Some text"
def printout(self):
print(f"sender_id: {self.sender_id}\ntext: ... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-532, ๋ก๊ทธ ํ์ผ์ ํตํ ์ ๋ณด ๋
ธ์ถ | """ Non-compliant Code Example """
import logging
def login_user(username, password, security_question):
"""Function to login user with username password, and security question"""
logging.info(
"User %s login attempt: password=%s, security answer=%s",
username, password, security_question
... | """ Compliant Code Example """
import logging
def login_user(username, password, security_question):
"""Function to login user with username password, and security question"""
logging.info("User %s login attempt", username)
# Continue to other login functionality
def main():
"""Main function... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-532, ๋ก๊ทธ ํ์ผ์ ํตํ ์ ๋ณด ๋
ธ์ถ | """ Non-compliant Code Example """
import logging
def process_order(address):
"""Function for processing some online order"""
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s',
level=logging.DEBUG)
logger = logging.getLogger(__name__)
logger.info("Initial l... | """ Compliant Code Example """
import logging
def process_order(address):
logging.basicConfig(
format="%(asctime)s %(levelname)s:%(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
logger.info("Initial logging level: %s", logger.getEffectiveLevel())
logger.debug... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-665, ๋ถ์ ์ ํ ์ด๊ธฐํ | """ Non-compliant Code Example """
from time import sleep
from enum import Enum
from threading import local, current_thread
from concurrent.futures import ThreadPoolExecutor, wait
class User(Enum):
GUEST = 1
ADMIN = 2
class Session(object):
def __init__(self):
self.user = local()
self.se... | """ Compliant Code Example """
from time import sleep
from enum import Enum
from threading import local, current_thread
from concurrent.futures import ThreadPoolExecutor, wait
class User(Enum):
GUEST = 1
ADMIN = 2
class Session(object):
def __init__(self):
self.user = local()
self.set_us... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-665, ๋ถ์ ์ ํ ์ด๊ธฐํ | """ Non-compliant Code Example """
from time import sleep
from enum import Enum
from threading import local, current_thread
from concurrent.futures import ThreadPoolExecutor, wait
class User(Enum):
GUEST = 1
ADMIN = 2
class Session(object):
def __init__(self):
self.user = local()
self.se... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
from time import sleep
from enum import Enum
from threading import local, current_thread
from concurrent.futures import ThreadPoolExecutor, wait
class User(Enum):
GUEST = 1
ADMIN = 2
class Se... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-681, ์ซ์ ์ ํ ๊ฐ์ ์๋ชป๋ ๋ณํ | """ Non-compliant Code Example """
s = str(4 / 2)
print(f"s: {s}")
# s is "2.0", a string
if s == "2":
print("s equals 2")
# <no output> | """ Compliant Code Example """
from decimal import Decimal
t = Decimal(str(4 / 2))
print(f"t: {t}")
# t still prints "2.0", but now it's a Decimal
if Decimal("2").compare(t) == 0:
print("t equals 2")
# prints "t equals 2" |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-833, Deadlock | """ Non-compliant Code Example """
from concurrent.futures import ThreadPoolExecutor
from typing import List
class ReportTableGenerator(object):
def __init__(self):
self.executor = ThreadPoolExecutor()
def generate_string_table(self, inputs: List[str]) -> str:
futures = []
aggregated... | """ Compliant Code Example """
from concurrent.futures import ThreadPoolExecutor
from typing import List
class ReportTableGenerator(object):
def __init__(self):
self.executor = ThreadPoolExecutor()
def generate_string_table(self, inputs: List[str]) -> str:
futures = []
aggregated = "... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-833, Deadlock | """ Non-compliant Code Example """
from concurrent.futures import ThreadPoolExecutor, wait
from threading import Lock
from typing import Callable
class BankingService(object):
def __init__(self, n: int):
self.executor = ThreadPoolExecutor()
self.number_of_times = n
self.count = 0
... | """ Compliant Code Example """
from concurrent.futures import ThreadPoolExecutor, wait
from threading import Lock
from typing import Callable
class BankingService(object):
def __init__(self, n: int):
self.executor = ThreadPoolExecutor()
self.number_of_times = n
self.count = 0
self... |
Python | CWE-664, ๋ฆฌ์์ค์ ์๋ช
๊ธฐ๊ฐ ๋์ ๋ถ์ ์ ํ ์ ์ด | null | CWE-843, ํธํ๋์ง ์๋ ์ ํ์ ์ฌ์ฉํ ๋ฆฌ์์ค ์ก์ธ์ค('์ ํ ํผ๋') | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
def shopping_bag(price: int, qty: str) -> int:
return price * qty
####################
# attempting to exploit #above code example
#####################
print(shopping_bag(100, "3")) | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
def shopping_bag(price: int, qty: str) -> int:
return int(price) * int(qty)
####################
# attempting to exploit #above code example
#####################
print(shopping_bag(100, "3")) |
Python | CWE-682, ์๋ชป๋ ๊ณ์ฐ | null | CWE-1335, ๋นํธ ๋จ์ ์ฐ์ฐ ๋์ ์ฐ์ ์ฐ์ฐ์ผ๋ก ์ํ์ ์ฝ๋๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ๋
์ฑ ๋ฐ ํธํ์ฑ ํฅ์ | """ Non-compliant Code Example """
print(8 << 2 + 10) | """ Compliant Code Example """
print(8 * 4 + 10) |
Python | CWE-682, ์๋ชป๋ ๊ณ์ฐ | null | CWE-1335, ๋นํธ ๋จ์ ์ฐ์ฐ ๋์ ์ฐ์ ์ฐ์ฐ์ผ๋ก ์ํ์ ์ฝ๋๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ๋
์ฑ ๋ฐ ํธํ์ฑ ํฅ์ | """ Non-compliant Code Example """
foo: int
foo = -50
foo >>= 2
print(foo) | """ Compliant Code Example """
foo: int = -50
bar: float = foo / 4
print(bar) |
Python | CWE-682, ์๋ชป๋ ๊ณ์ฐ | null | CWE-1339, ์ค์์ ๋ถ์ ์ ํ ์ ๋ฐ๋ ๋๋ ์ ํ๋ | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
balance = 3.00
item_cost = 0.33
item_count = 5
#####################
# exploiting above code example
#####################
print(
f"{str(item_count)} items bought, ${item_cost} each. "
f"Current account balance: ${str(balance... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
balance = 300
item_cost = 33
item_count = 5
#####################
# exploiting above code example
#####################
print(
f"{str(item_count)} items bought, ${item_cost / 100} each. "
f"Current account balance: ${str((bal... |
Python | CWE-682, ์๋ชป๋ ๊ณ์ฐ | null | CWE-1339, ์ค์์ ๋ถ์ ์ ํ ์ ๋ฐ๋ ๋๋ ์ ํ๋ | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
balance = 3.00
item_cost = 0.33
item_count = 5
#####################
# exploiting above code example
#####################
print(
f"{str(item_count)} items bought, ${item_cost} each. "
f"Current account balance: ${str(balance... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
from decimal import Decimal
balance = Decimal("3.00")
item_cost = Decimal("0.33")
item_count = 5
#####################
# exploiting above code example
#####################
print(
f"{str(item_count)} items bought, ${item_cost} e... |
Python | CWE-682, ์๋ชป๋ ๊ณ์ฐ | null | CWE-191, ์ ์ ์ธ๋ํ๋ก(๋ฉ ๋๋ ๋ฉ์ด๋ผ์ด๋) | """ Non-compliant Code Example """
import numpy
a = numpy.int64(numpy.iinfo(numpy.int64).max)
print(a + 1) # RuntimeWarning and continues
print()
b = numpy.int64(numpy.iinfo(numpy.int64).max + 1) # OverflowError and stops
print(b) # we will never reach this | """ Compliant Code Example """
import warnings
import numpy
warnings.filterwarnings("error")
a = numpy.int64(numpy.iinfo(numpy.int64).max)
with warnings.catch_warnings():
try:
print(a + 1)
except Warning as _:
print("Failed to increment " + str(a) + " due to overflow error")
# RuntimeWarni... |
Python | CWE-682, ์๋ชป๋ ๊ณ์ฐ | null | CWE-191, ์ ์ ์ธ๋ํ๋ก(๋ฉ ๋๋ ๋ฉ์ด๋ผ์ด๋) | """ Non-compliant Code Example """
import time
def get_time_in_future(hours_in_future):
"""Gets the time n hours in the future"""
currtime = [tm for tm in time.localtime()]
currtime[3] = currtime[3] + hours_in_future
if currtime[3] + hours_in_future > 24:
currtime[3] = currtime[3] - 24
... | """ Compliant Code Example """
import time
def get_time_in_future(hours_in_future):
"""Gets the time n hours in the future"""
try:
currtime = list(time.localtime())
currtime[3] = currtime[3] + hours_in_future
if currtime[3] + hours_in_future > 24:
currtime[3] = currtime[3]... |
Python | CWE-682, ์๋ชป๋ ๊ณ์ฐ | null | CWE-191, ์ ์ ์ธ๋ํ๋ก(๋ฉ ๋๋ ๋ฉ์ด๋ผ์ด๋) | """ Non-compliant Code Example """
import math
def calculate_exponential_value(number):
"""Return 'E' raised to the power of different numbers:"""
return math.exp(number)
#####################
# attempting to exploit above code example
#####################
print(calculate_exponential_value(1000)) | """ Compliant Code Example """
import math
def calculate_exponential_value(number):
"""Return 'E' raised to the power of different numbers:"""
try:
return math.exp(number)
except OverflowError as _:
return "Number " + str(number) + " caused an integer overflow"
#####################
# at... |
Python | CWE-691, ๋ถ์ถฉ๋ถํ ์ ์ด ํ๋ฆ ๊ด๋ฆฌ | null | CWE-617, Reachable Assertion | """ Non-compliant Code Example """
import math
def my_exp(x):
assert x in range(
1, 710
), f"Argument {x} is not valid" # range(1, 709) produces 1-708
return math.exp(x)
#####################
# exploiting above code example
#####################
try:
print(my_exp(1))
except (AssertionError... | """ Compliant Code Example """
import math
def my_exp(x):
if x not in range(1, 710): # range(1, 709) produces 1-708
raise ValueError(f"Argument {x} is not valid")
return math.exp(x)
#####################
# exploiting above code example
#####################
try:
print(my_exp(1))
except (Assert... |
Python | CWE-693, ๋ณดํธ ๋ฉ์ปค๋์ฆ ์คํจ | null | CWE-184, ํ์ฉ๋์ง ์๋ ์
๋ ฅ์ ๋ถ์์ ํ ๋ชฉ๋ก | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
import re
import unicodedata
import sys
sys.stdout.reconfigure(encoding="UTF-8")
class TagFilter:
"""Input validation for human language"""
def filter_string(self, input_string: str) -> s... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
import re
import unicodedata
import sys
sys.stdout.reconfigure(encoding="UTF-8")
class TagFilter:
"""Input validation for human language"""
def filter_string(self, input_string: str) -> str:
... |
Python | CWE-693, ๋ณดํธ ๋ฉ์ปค๋์ฆ ์คํจ | null | CWE-330, ์ถฉ๋ถํ ๋๋คํ์ง ์์ ๊ฐ์ ์ฌ์ฉ | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
import random
def generate_web_token():
"""Poor random number generator"""
return random.randrange(int("1" + "0" * 31), int("9" * 32), 1)
#####################
# attempting to exploit abo... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
import secrets
def generate_web_token():
"""Better cryptographic number generator"""
return secrets.token_urlsafe()
#####################
# attempting to exploit above code example
##########... |
Python | CWE-693, ๋ณดํธ ๋ฉ์ปค๋์ฆ ์คํจ | null | CWE-778, ๋ถ์ถฉ๋ถํ ๋ก๊น
| # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Error occurred:", e)
#Continues to execute | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
import logging
try:
result = 10 / 0
except ZeroDivisionError as e:
logging.critical("Error occurred: Division by zero")
#Continues to execute |
Python | CWE-693, ๋ณดํธ ๋ฉ์ปค๋์ฆ ์คํจ | null | CWE-798, ํ๋์ฝ๋ฉ๋ ์๊ฒฉ ์ฆ๋ช
์ฌ์ฉ | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
databaseIPAddress = "192.168.0.1"
print(databaseIPAddress) | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
import os
print(os.environ["databaseIPAddress"]) |
Python | CWE-697, ์๋ชป๋ ๋น๊ต | null | CWE-595, ๊ฐ์ฒด ๋ด์ฉ ๋์ ๊ฐ์ฒด ์ฐธ์กฐ ๋น๊ต | """ Non-compliant Code Example """
class Integer:
def __init__(self, value):
self.value = value
#####################
# exploiting above code example
#####################
print(Integer(12) == Integer(12))
# Prints False, as == operator compares id(self) == id(other) when __eq__ isn't implemented
# As a ... | """ Compliant Code Example """
class Integer:
def __init__(self, value):
self.value = value
def __eq__(self, other):
if isinstance(other, type(self)):
return self.value == other.value
if isinstance(other, int):
return self.value == other
return False... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-230, ๋๋ฝ๋ ๊ฐ์ ๋ถ์ ์ ํ ์ฒ๋ฆฌ | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
def balance_is_positive(value: str) -> bool:
"""Returns True if there is still enough value for a transaction"""
_value = float(value)
if _value == float("NaN") or _value is float("NaN"... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
from decimal import ROUND_DOWN, Decimal
def balance_is_positive(value: str) -> bool:
"""Returns True if there is still enough value for a transaction"""
# TODO: additional input sanitation... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-390, ์กฐ์น ์์ด ์ค๋ฅ ์ํ ๊ฐ์ง | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
from time import sleep
def exception_example():
"""Non-compliant Code Example using bare except"""
while True:
try:
sleep(1)
_ = 1 / 0
except:
... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
from time import sleep
def exception_example():
"""Compliant Code Example catching a specific exception"""
while True:
sleep(1)
try:
_ = 1 / 0
except ZeroDiv... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-390, ์กฐ์น ์์ด ์ค๋ฅ ์ํ ๊ฐ์ง | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
import logging
from pathlib import Path
def exception_example(args: list):
"""Non-compliant Code Example missing handling"""
file_path = Path(Path.home(), args[0])
try:
file_ha... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
from pathlib import Path
def exception_example(args: list):
"""Compliant code demonstrating a simplistic handling.
input validation or architectural are not demonstrated.
"""
file_exis... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-392, ์ค๋ฅ ์ํ ๋ณด๊ณ ๋๋ฝ | """ Non-compliant Code Example """
import math
from concurrent.futures import ThreadPoolExecutor
def get_sqrt(a):
return math.sqrt(a)
def run_thread(var):
with ThreadPoolExecutor() as executor:
return executor.submit(get_sqrt, var)
#####################
# exploiting above code example
#############... | """ Compliant Code Example """
import math
from concurrent.futures import ThreadPoolExecutor
def get_sqrt(a):
return math.sqrt(a)
def run_thread(var):
with ThreadPoolExecutor() as executor:
future = executor.submit(get_sqrt, var)
if future.exception() is not None:
# handle except... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-392, ์ค๋ฅ ์ํ ๋ณด๊ณ ๋๋ฝ | """ Non-compliant Code Example """
import math
from concurrent.futures import ThreadPoolExecutor
def get_sqrt(a):
return math.sqrt(a)
def run_thread(var):
with ThreadPoolExecutor() as executor:
return executor.submit(get_sqrt, var)
#####################
# exploiting above code example
#############... | """ Compliant Code Example """
import math
from concurrent.futures import ThreadPoolExecutor
def get_sqrt(a):
return math.sqrt(a)
def run_thread(var):
with ThreadPoolExecutor() as executor:
future = executor.submit(get_sqrt, var)
try:
res = future.result()
return res
... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-392, ์ค๋ฅ ์ํ ๋ณด๊ณ ๋๋ฝ | """ Non-compliant Code Example """
import math
from concurrent.futures import ThreadPoolExecutor
def get_sqrt(a):
return math.sqrt(a)
def map_threads(x):
with ThreadPoolExecutor() as executor:
return executor.map(get_sqrt, x)
#####################
# exploiting above code example
#################... | """ Compliant Code Example """
import math
from concurrent.futures import ThreadPoolExecutor
def get_sqrt(a):
return math.sqrt(a)
def map_threads(x):
with ThreadPoolExecutor() as executor:
result_gen = executor.map(get_sqrt, x)
ret = list()
invalid_arg = 0
try:
f... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-392, ์ค๋ฅ ์ํ ๋ณด๊ณ ๋๋ฝ | """ Non-compliant Code Example """
import math
from concurrent.futures import ThreadPoolExecutor
def get_sqrt(a):
return math.sqrt(a)
def map_threads(x):
with ThreadPoolExecutor() as executor:
return executor.map(get_sqrt, x)
#####################
# exploiting above code example
#################... | """ Compliant Code Example """
import math
from concurrent.futures import ThreadPoolExecutor
def get_sqrt(a):
try:
return math.sqrt(a)
except ValueError as e:
print(f"Invalid argument: {a}")
return None
def map_threads(x):
with ThreadPoolExecutor() as executor:
return ex... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-754, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
import sys
class Package:
def __init__(self):
self.package_weight = float(1.0)
def put_in_the_package(self, object_weight):
value = float(object_weight)
print(f"Add... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
import sys
from math import isinf, isnan
class Package:
def __init__(self):
self.package_weight = float(1.0)
def put_in_the_package(self, user_input):
try:
value = ... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-755, ์์ธ ์กฐ๊ฑด์ ๋ถ์ ์ ํ ์ฒ๋ฆฌ | """ Non-compliant Code Example """
import os
import uuid
def read_file(file):
"""Function for opening a file and reading it's content."""
fd = os.open(file, os.O_RDONLY)
content = os.read(fd)
return content.decode()
#####################
# exploiting above code example
#####################
# ... | """ Compliant Code Example """
import os
import uuid
def read_file(file):
"""Function for opening a file and reading its content."""
try:
fd = os.open(file, os.O_RDONLY)
try:
content = os.read(fd, 1024)
finally:
os.close(fd)
return content.decode(... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-755, ์์ธ ์กฐ๊ฑด์ ๋ถ์ ์ ํ ์ฒ๋ฆฌ | """ Non-compliant Code Example """
import uuid
from pathlib import Path
def read_file(file):
"""Function for opening a file and reading its content."""
path = Path(file)
content = path.read_text(encoding="utf-8")
return content
#####################
# exploiting above code example
############... | """ Non-compliant Code Example """
import uuid
from pathlib import Path
def read_file(file):
"""Function for opening a file and reading its content."""
path = Path(file)
try:
content = path.read_text(encoding="utf-8")
return content
except OSError as e:
if path.is_dir():
... |
Python | CWE-703, ๋น์ ์์ ์ด๊ฑฐ๋ ์์ธ์ ์ธ ์กฐ๊ฑด์ ๋ํ ๋ถ์ ์ ํ ๊ฒ์ฌ ๋๋ ์ฒ๋ฆฌ ํ์ธ ๋๋ ์ฒ๋ฆฌ | null | CWE-755, ์์ธ ์กฐ๊ฑด์ ๋ถ์ ์ ํ ์ฒ๋ฆฌ | """ Non-compliant Code Example """
import pathlib
import uuid
def delete_temporary_file(file):
"""Function for deleting a temporary file from a certain location"""
resource_path = pathlib.Path(file)
resource_path.unlink(missing_ok=True)
#####################
# exploiting above code example
#######... | """ Non-compliant Code Example """
import uuid
from pathlib import Path
def read_file(file):
"""Function for opening a file and reading its content."""
path = Path(file)
try:
content = path.read_text(encoding="utf-8")
return content
except OSError as e:
if path.is_dir():
... |
Python | CWE-707, ๋ถ์ ์ ํ ์ค๋ฆฝํ ์ฒ๋ฆฌ | null | CWE-117, ๋ก๊ทธ์ ๋ํ ๋ถ์ ์ ํ ์ถ๋ ฅ ์ค๋ฆฝํ | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Non-compliant Code Example """
import logging
def log_authentication_failed(user):
"""Simplified audit logging missing RFC 5424 details"""
logging.warning("User login failed for: '%s'", user)
#####################
# at... | # SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
import logging
import re
def allowed_chars(user):
"""Verify only allowed characters are used"""
if bool(re.compile(r"\w+").fullmatch(user)):
return True
return False
def log_authe... |
Python | CWE-707, ๋ถ์ ์ ํ ์ค๋ฆฝํ ์ฒ๋ฆฌ | null | CWE-175, ํผํฉ ์ธ์ฝ๋ฉ์ ๋ถ์ ์ ํ ์ฒ๋ฆฌ | """ Non-compliant Code Example """
import datetime
import locale
dt = datetime.datetime(2022, 3, 9, 12, 55, 35, 000000)
def get_date(date):
# Return year month day tuple e.g. 2022, March, 09
return date.strftime("%Y"), date.strftime("%B"), date.strftime("%d")
#####################
# Trying to exploit above ... | """ Compliant Code Example """
import datetime
import locale
dt = datetime.datetime(2022, 3, 9, 12, 55, 35, 000000)
CURRENT_LOCALE = 'en_IE.utf8'
OTHER_LOCALE = 'uk_UA.utf8'
#####################
# Trying to exploit above code example
#####################
locale.setlocale(locale.LC_ALL, CURRENT_LOCALE)
# Month is ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.