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(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
} | 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(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
} |
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"))) {
out.writeObject(map);
}
// ๋งต ์ญ์ง๋ ฌํ
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("map.ser"))) {
SerializableMap<String, Integer> deserializedMap = (SerializableMap<String, Integer>) in.readObject();
inspectMap(deserializedMap);
}
}
} | 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 {
// ํค ๋ฐ ์๋ช
๊ฐ์ฒด ์ด๊ธฐํ
KeyGenerator keyGen = KeyGenerator.getInstance(ALGORITHM);
keyGen.init(256);
SecretKey secretKey = keyGen.generateKey();
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048);
KeyPair keyPair = keyPairGen.generateKeyPair();
// ๋งต ์์ฑ
SerializableMap<String, Integer> map = buildMap();
// ๋งต ์ง๋ ฌํ ๋ฐ ์ํธํ
byte[] serializedData;
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos)) {
out.writeObject(map);
serializedData = bos.toByteArray();
}
// ๋ฐ์ดํฐ ์๋ช
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.initSign(keyPair.getPrivate());
signature.update(serializedData);
byte[] digitalSignature = signature.sign();
// ๋ฐ์ดํฐ ์ํธํ
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] iv = cipher.getIV();
byte[] encryptedData = cipher.doFinal(serializedData);
// ์ํธํ๋ ๋ฐ์ดํฐ์ ์๋ช
์ ์ฅ
try (FileOutputStream fos = new FileOutputStream("map.enc");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
oos.writeObject(iv);
oos.writeObject(encryptedData);
oos.writeObject(digitalSignature);
oos.writeObject(keyPair.getPublic());
}
// ์ํธํ๋ ๋ฐ์ดํฐ์ ์๋ช
์ฝ๊ธฐ
byte[] readIv;
byte[] readEncryptedData;
byte[] readDigitalSignature;
PublicKey publicKey;
try (FileInputStream fis = new FileInputStream("map.enc");
ObjectInputStream ois = new ObjectInputStream(fis)) {
readIv = (byte[]) ois.readObject();
readEncryptedData = (byte[]) ois.readObject();
readDigitalSignature = (byte[]) ois.readObject();
publicKey = (PublicKey) ois.readObject();
}
// ๋ฐ์ดํฐ ๋ณตํธํ
Cipher decipher = Cipher.getInstance(TRANSFORMATION);
IvParameterSpec ivSpec = new IvParameterSpec(readIv);
decipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
byte[] decryptedData = decipher.doFinal(readEncryptedData);
// ์๋ช
๊ฒ์ฆ
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(decryptedData);
if (!sig.verify(readDigitalSignature)) {
throw new SecurityException("๋ฐ์ดํฐ ๋ฌด๊ฒฐ์ฑ ๊ฒ์ฆ ์คํจ");
}
// ๋งต ์ญ์ง๋ ฌํ
try (ByteArrayInputStream bis = new ByteArrayInputStream(decryptedData);
ObjectInputStream in = new ObjectInputStream(bis)) {
SerializableMap<String, Integer> deserializedMap = (SerializableMap<String, Integer>) in.readObject();
inspectMap(deserializedMap);
}
}
} |
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) {
FileOutputStream fout = null;
try {
Point p = new Point(5, 2);
fout = new FileOutputStream("point.ser");
ObjectOutputStream oout = new ObjectOutputStream(fout);
oout.writeObject(p);
} catch (Throwable t) {
// Forward to handler
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException x) {
// Handle error
}
}
}
}
} | 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 {
public static void main(String[] args) {
FileOutputStream fout = null;
try {
Point p = new Point(5,2);
fout = new FileOutputStream("point.ser");
ObjectOutputStream oout = new ObjectOutputStream(fout);
oout.writeObject(p);
oout.close();
} catch (Exception e) {
// Forward to handler
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException x) {
// Handle error
}
}
}
}
} |
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 and parameter validation
}
private int balance = 1000;
protected int getBalance() {
return balance;
}
}
class Malicious {
public static void main(String[] args) {
SensitiveClass sc =
(SensitiveClass) deepCopy(SensitiveClass.getInstance());
// Prints false; indicates new instance
System.out.println(sc == SensitiveClass.getInstance());
System.out.println("Balance = " + sc.getBalance());
}
// This method should not be used in production code
static public Object deepCopy(Object obj) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
new ObjectOutputStream(bos).writeObject(obj);
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray());
return new ObjectInputStream(bin).readObject();
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
} | 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 NotSerializableException();
}
private final Object readObjectNoData(java.io.ObjectInputStream in) throws NotSerializableException {
throw new NotSerializableException();
}
} |
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 Hometown() {
performSecurityManagerCheck();
// Initialize town to default value
town = UNKNOWN;
}
// Allows callers to retrieve internal state
String getValue() {
performSecurityManagerCheck();
return town;
}
// Allows callers to modify (private) internal state
public void changeTown(String newTown) {
if (town.equals(newTown)) {
// No change
return;
} else {
performSecurityManagerCheck();
validateInput(newTown);
town = newTown;
}
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(town);
}
private void readObject(ObjectInputStream in) throws IOException {
in.defaultReadObject();
// If the deserialized name does not match the default value normally
// created at construction time, duplicate the checks
if (!UNKNOWN.equals(town)) {
validateInput(town);
}
}
} | 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);
}
// readObject() correctly enforces checks during deserialization
private void readObject(ObjectInputStream in) throws IOException {
in.defaultReadObject();
// If the deserialized name does not match the default value normally
// created at construction time, duplicate the checks
if (!UNKNOWN.equals(town)) {
performSecurityManagerCheck();
validateInput(town);
}
}
} |
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 IOException, ClassNotFoundException {
ois.defaultReadObject();
// Perform validation if necessary
}
} | 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 validation
}
protected int printData() {
int data = 1000;
// Print data
return data;
}
}
class Malicious {
public static void main(String[] args) {
NumberData sc = (NumberData) deepCopy(NumberData.getInstance());
// Prints false; indicates new instance
System.out.println(sc == NumberData.getInstance());
System.out.println("Balance = " + sc.printData());
}
// This method should not be used in production code
public static Object deepCopy(Object obj) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
new ObjectOutputStream(bos).writeObject(obj);
ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray());
return new ObjectInputStream(bin).readObject();
} catch (Exception e) {
throw new IllegalArgumentException(e);
}
}
} | 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) ((Math.abs(draw.nextInt()) % 20000) + 1);
return this.ticket;
}
public static void main(String[] args) {
Lottery l = new Lottery(2);
for (int i = 0; i < 10; i++) {
l.roll();
System.out.println(l.getTicket());
}
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
}
} | 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 || ticket <= 0) {
throw new InvalidObjectException("Not in range!");
}
// Validate draw
this.ticket = ticket;
}
} |
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.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Note: This must be changed if any additional fields are defined
Object a = s.readFields().get("array", null);
if (a == null || !a.getClass().isArray())
throw new java.io.InvalidObjectException("Not array type");
if (a.getClass() != Object[].class)
a = Arrays.copyOf((Object[])a, Array.getLength(a), Object[].class);
unsafe.putObjectVolatile(this, arrayFieldOffset, a);
}
} |
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 FileInputStream("object.dat"))) {
Object obj = ois.readObject();
// ์ญ์ง๋ ฌํ๋ ๊ฐ์ฒด ์ฌ์ฉ
}
return null;
});
}
} | import java.io.*;
import java.security.*;
public class CompliantExample {
public static void main(String[] args) throws Exception {
// ์ต์ ๊ถํ์ผ๋ก ์ญ์ง๋ ฌํ ์ํ
AccessController.doPrivileged((PrivilegedExceptionAction<Void>) () -> {
// ํ์ํ ์ต์ ๊ถํ ์ค์
PermissionCollection minimalPermissions = new Permissions();
minimalPermissions.add(new File |
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 {
out = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream("ser.dat")));
while (SensorData.isAvailable()) {
// Note that each SensorData object is 1 MB in size
SensorData sd = SensorData.readSensorData();
out.writeObject(sd);
}
} finally {
if (out != null) {
out.close();
}
}
}
} | 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 object is 1 MB in size
SensorData sd = SensorData.readSensorData();
out.writeObject(sd);
out.reset(); // Reset the stream
}
} finally {
if (out != null) {
out.close();
}
}
}
} |
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();
this.UID = in.readInt();
// ...
initialized = true;
} else {
throw new IllegalStateException();
}
}
} |
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 = ois.readObject();
}
}
return ret;
}
} | 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(ObjectStreamClass cls) throws IOException, ClassNotFoundException {
if (!whitelist.contains(cls.getName())) {
throw new InvalidClassException("Unexpected serialized class", cls.getName());
}
return super.resolveClass(cls);
}
}
class DeserializeExample {
private static Object deserialize(byte[] buffer) throws IOException, ClassNotFoundException {
Object ret = null;
Set whitelist = new HashSet<String>(Arrays.asList(new String[]{"GoodClass1","GoodClass2"}));
try (ByteArrayInputStream bais = new ByteArrayInputStream(buffer)) {
try (WhitelistedObjectInputStream ois = new WhitelistedObjectInputStream(bais, whitelist)) {
ret = ois.readObject();
}
}
return ret;
}
} |
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";
FileInputStream fin = null;
try {
fin = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoundException {
// ๋ฏผ๊ฐํ ํ์ผ์ ์ ๊ทผ
return new FileInputStream(passwordFile);
}
}
);
} catch (PrivilegedActionException e) {
throw (FileNotFoundException) e.getException();
}
return fin;
}
} | public class PasswordManager {
public static void changePassword() throws FileNotFoundException {
// ๋น๋ฐ๋ฒํธ ๋ณ๊ฒฝ ๋ก์ง
try (FileInputStream fin = openPasswordFile()) {
// ๊ธฐ์กด ๋น๋ฐ๋ฒํธ ํ์ธ ๋ฐ ๋ณ๊ฒฝ ๋ก์ง
} catch (IOException e) {
// ์์ธ ์ฒ๋ฆฌ
}
}
private static FileInputStream openPasswordFile() throws FileNotFoundException {
final String passwordFile = "password";
try {
return AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoundException {
// ๋ฏผ๊ฐํ ํ์ผ์ ์ ๊ทผ
return new FileInputStream(passwordFile);
}
}
);
} catch (PrivilegedActionException e) {
throw (FileNotFoundException) e.getException();
}
}
} |
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 new FileInputStream(filename);
}
}
);
// ํ์ผ์ ์ฌ์ฉํ ํ ๋ซ๊ธฐ
} catch (PrivilegedActionException e) {
// ์์ธ ์ฒ๋ฆฌ
}
} | private void privilegedMethod(final String filename) throws FileNotFoundException {
final String cleanFilename;
try {
cleanFilename = cleanAFilenameAndPath(filename);
} catch (Exception e) {
// cleanAFilenameAndPath ๋ฉ์๋์ ์ฌ์์ ๋ฐ๋ฅธ ์์ธ ์ฒ๋ฆฌ
return;
}
try {
FileInputStream fis = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream(cleanFilename);
}
}
);
// ํ์ผ์ ์ฌ์ฉํ ํ ๋ซ๊ธฐ
} catch (PrivilegedActionException e) {
// ์์ธ ์ฒ๋ฆฌ
}
} |
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 new FileInputStream(filename);
}
}
);
// ํ์ผ์ ์ฌ์ฉํ ํ ๋ซ๊ธฐ
} catch (PrivilegedActionException e) {
// ์์ธ ์ฒ๋ฆฌ
}
} | private void privilegedMethod() throws FileNotFoundException {
final String trustedFilename = "/path/to/trusted/file";
try {
FileInputStream fis = AccessController.doPrivileged(
new PrivilegedExceptionAction<FileInputStream>() {
public FileInputStream run() throws FileNotFoundException {
return new FileInputStream(trustedFilename);
}
}
);
// ํ์ผ์ ์ฌ์ฉํ ํ ๋ซ๊ธฐ
} catch (PrivilegedActionException e) {
// ์์ธ ์ฒ๋ฆฌ
}
} |
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.example.TrustedClass");
}
} | public class CompliantExample {
public static void main(String[] args) {
// ์ ๋ขฐํ ์ ์๋ ํด๋์ค ๋จผ์ ๋ก๋
Class.forName("com.example.TrustedClass");
// ์ดํ์ ์ ๋ขฐํ ์ ์๋ ์ฝ๋๊ฐ ์์์ ํด๋์ค๋ฅผ ๋ก๋ํ๋๋ก ํ์ฉ
UntrustedClassLoader untrustedLoader = new UntrustedClassLoader();
untrustedLoader.loadClass("com.example.UntrustedClass");
}
} |
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);
} catch (NoSuchFieldException | IllegalAccessException e) {
// ์์ธ ์ฒ๋ฆฌ
}
}
@Override
public String toString() {
return "FieldExample: i=" + i + ", j=" + j;
}
public static void main(String[] args) {
FieldExample fe = new FieldExample();
System.out.println(fe);
fe.zeroField("i");
System.out.println(fe);
}
} | 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[] args) {
FieldExample fe = new FieldExample();
System.out.println(fe);
fe.zeroI();
System.out.println(fe);
}
} |
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.getPath());
}
});
} |
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) {
sm.checkSecurityAccess(directive);
}
}
} |
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(className);
cls.getMethod("main", String[].class).invoke(null, (Object) new String[]{});
}
} | 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 void main(String[] args) throws Exception {
String jarPath = args[0];
String certPath = args[1];
// ์ ๋ขฐํ ์ ์๋ ์ธ์ฆ์ ๋ก๋
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate trustedCert;
try (FileInputStream fis = new FileInputStream(certPath)) {
trustedCert = cf.generateCertificate(fis);
}
// JAR ํ์ผ์ ์๋ช
๊ฒ์ฆ
try (JarFile jarFile = new JarFile(jarPath, true)) {
jarFile.stream().forEach(entry -> {
try {
if (entry.isDirectory()) return;
Certificate[] certs = getCertificates(jarFile, entry);
if (certs != null) {
for (Certificate cert : certs) {
if (cert.equals(trustedCert)) {
// ์ ๋ขฐํ ์ ์๋ ์ธ์ฆ์๋ก ์๋ช
๋ ํญ๋ชฉ
return;
}
}
}
throw new SecurityException("์๋ช
๊ฒ์ฆ ์คํจ: " + entry.getName());
} catch (Exception e) {
throw new RuntimeException(e);
}
});
}
// ์๋ช
๊ฒ์ฆ์ด ์๋ฃ๋ JAR ํ์ผ ๋ก๋ ๋ฐ ์คํ
URL url = new File(jarPath).toURI().toURL();
try (URLClassLoader loader = new URLClassLoader(new URL[]{url})) {
String className = args[2];
Class<?> cls = loader.loadClass(className);
cls.getMethod("main", String[].class).invoke(null, (Object) new String[]{});
}
}
private static Certificate[] getCertificates(JarFile jarFile, JarEntry entry) throws Exception {
try (JarInputStream jis = new JarInputStream(jarFile.getInputStream(entry))) {
while (jis.getNextEntry() != null) {
// ๋ชจ๋ ํญ๋ชฉ์ ์ฝ์ด์ผ ์๋ช
๊ฒ์ฆ์ด ์๋ฃ๋จ
}
return entry.getCertificates();
}
}
} |
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 FileInputStream fis = new FileInputStream("file.txt");
try {
RetValue rt = new RetValue();
if (rt.getValue() == 1) {
// Do something with sensitive file
}
} finally {
fis.close();
}
return null; // Nothing to return
}
}
);
} catch (PrivilegedActionException e) {
// Forward to handler and log
}
}
public static void main(String[] args) throws IOException {
MixMatch mm = new MixMatch();
mm.privilegedMethod();
}
}
// In another JAR file:
package untrusted;
class RetValue {
public int getValue() {
return 1;
}
} | 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 FileNotFoundException {
return new FileInputStream("file.txt");
}
}
);
try {
RetValue rt = new RetValue();
if (rt.getValue() == 1) {
// Do something with sensitive file
}
} finally {
fis.close();
}
} catch (PrivilegedActionException e) {
// Forward to handler and log
}
}
public static void main(String[] args) throws IOException {
MixMatch mm = new MixMatch();
mm.privilegedMethod();
}
}
// In another JAR file:
package untrusted;
class RetValue {
public int getValue() {
return 1;
}
} | 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);
}
static {
// Load native library in static initializer of class
System.loadLibrary("NativeMethodLib");
}
} | 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 native method
securityManagerCheck();
if (data == null) {
throw new NullPointerException();
}
// Copy mutable input
data = data.clone();
// Validate input
if ((offset < 0) || (len < 0) || (offset > (data.length - len))) {
throw new IllegalArgumentException();
}
nativeOperation(data, offset, len);
}
static {
// Load native library in static initializer of class
System.loadLibrary("NativeMethodLib");
}
} |
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;
}
});
}
}
---------------------------------------------------------------------------------
// Untrusted.java
public class Untrusted {
private native void nativeOperation();
public static void main(String[] args) {
String library = new String("NativeMethodLib");
Trusted.loadLibrary(library);
new Untrusted.nativeOperation(); // invoke the native method
}
} | // 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);
private native void nativeOperation2(...)
...
// wrapper methods perform SecurityManager and input validation checks
public void doOperation1(byte[] data, int offset, int len) {
// permission needed to invoke native method
securityManagerCheck();
if (data == null) {
throw new NullPointerException();
}
// copy mutable input
data = data.clone();
// validate input
if ((offset < 0) || (len < 0) || (offset > (data.length - len))) {
throw new IllegalArgumentException();
}
nativeOperation1(data, offset, len);
}
public void doOperation2(...){
...
}
} |
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 PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
out.println(inputLine);
}
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException x) {
// Handle error
}
}
}
}
}
class EchoClient {
public static void main(String[] args)
throws UnknownHostException, IOException {
Socket socket = null;
try {
socket = new Socket("localhost", 9999);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println(in.readLine());
}
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException x) {
// Handle error
}
}
}
}
} | // 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();
sslServerSocket = (SSLServerSocket) sslServerSocketFactory.
createServerSocket(9999);
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
PrintWriter out = new PrintWriter(sslSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(
new InputStreamReader(sslSocket.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
out.println(inputLine);
}
} finally {
if (sslServerSocket != null) {
try {
sslServerSocket.close();
} catch (IOException x) {
// Handle error
}
}
}
}
}
class EchoClient {
public static void main(String[] args) throws IOException {
SSLSocket sslSocket = null;
try {
SSLSocketFactory sslSocketFactory =
(SSLSocketFactory) SSLSocketFactory.getDefault();
sslSocket =
(SSLSocket) sslSocketFactory.createSocket("localhost", 9999);
PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(sslSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println(in.readLine());
}
} finally {
if (sslSocket != null) {
try {
sslSocket.close();
} catch (IOException x) {
// Handle error
}
}
}
}
} |
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++) {
int n = secureRandom.nextInt(21); // 0๋ถํฐ 20๊น์ง์ ์ ์ ์์ฑ
System.out.println(n);
}
} catch (NoSuchAlgorithmException e) {
// ์์ธ ์ฒ๋ฆฌ ๋ก์ง
}
}
} |
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[] password = console.readPassword("๋น๋ฐ๋ฒํธ: ");
// ์
๋ ฅ๋ฐ์ ์ฌ์ฉ์ ์ด๋ฆ๊ณผ ๋น๋ฐ๋ฒํธ๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐ์ดํฐ๋ฒ ์ด์ค ์ฐ๊ฒฐ
}
} |
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 static void main(String[] args) {
Leak le = new Leak();
int i = 1;
while (true) {
System.out.println("Iteration: " + i);
le.useVector(1);
i++;
}
}
} | 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--) {
vector.removeElementAt(n);
}
}
}
public static void main(String[] args) {
Leak le = new Leak();
int i = 1;
while (true) {
System.out.println("Iteration: " + i);
le.useVector(1);
i++;
}
}
} |
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 addNames() throws IOException {
try {
String newName;
while (((newName = reader.readLine()) != null) &&
!(newName.equalsIgnoreCase("quit"))) {
names.addElement(newName);
System.out.println("adding " + newName);
}
} finally {
input.close();
}
}
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("Arguments: [filename]");
return;
}
ReadNames demo = new ReadNames(args[0]);
demo.addNames();
}
} | 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 == 0L) {
throw new IOException("File size cannot be determined, possibly too large");
}
this.input = new FileReader(filename);
this.reader = new BufferedReader(input);
}
} |
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 addNames() throws IOException {
try {
String newName;
while (((newName = reader.readLine()) != null) &&
!(newName.equalsIgnoreCase("quit"))) {
names.addElement(newName);
System.out.println("adding " + newName);
}
} finally {
input.close();
}
}
public static void main(String[] args) throws IOException {
if (args.length != 1) {
System.out.println("Arguments: [filename]");
return;
}
ReadNames demo = new ReadNames(args[0]);
demo.addNames();
}
} | 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) {
return ((sb.length() > 0) ? sb.toString() : null);
}
if (((char) c == '\n') || ((char) c == '\r')) {
break;
}
sb.append((char) c);
}
return sb.toString();
}
public static final int lineLengthLimit = 1024;
public static final int lineCountLimit = 1000000;
public void addNames() throws IOException {
try {
String newName;
for (int i = 0; i < lineCountLimit; i++) {
newName = readLimitedLine(reader, lineLengthLimit);
if (newName == null || newName.equalsIgnoreCase("quit")) {
break;
}
names.addElement(newName);
System.out.println("adding " + newName);
}
} finally {
input.close();
}
}
} |
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 newID = 0L;
int count = 67108865;
int i = 0;
InputStreamReader input = new InputStreamReader(System.in);
Scanner reader = new Scanner(input);
public void addNames() {
try {
do {
// Adding unknown number of records to a list
// The user can enter more IDs than the heap can support and,
// as a result, exhaust the heap. Assume that the record ID
// is a 64-bit long value
System.out.print("Enter recordID (To quit, enter -1): ");
newID = reader.nextLong();
names.addElement(newID);
i++;
} while (i < count || newID != -1);
} finally {
input.close();
}
}
public static void main(String[] args) {
ReadNames demo = new ReadNames();
demo.addNames();
}
} | // ...
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();
}
return instance;
}
} |
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 = new MySingleton();
}
return instance;
}
} | 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 MySingleton();
}
return instance;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
} |
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 = 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 = 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 object
System.out.println(singleton.hashCode());
}
ClassLoader cl1 = new MyClassLoader();
Class class1 = cl1.loadClass(MySingleton.class.getName());
Method classMethod =
class1.getDeclaredMethod("getInstance", new Class[] { });
// Retrieve the preserved object
Object singleton = ObjectPreserver.getObject();
System.out.println(singleton.hashCode()); |
JAVA | ๊ธฐํ | ์๋ธ๋ฆฟ ๋ด์์ ์ธ์
์ ๋ณด๊ฐ ์ ์ถ๋์ง ์๋๋ก ํ๊ธฐ | CWE-543, ๋ฉํฐ์ค๋ ๋ ์ปจํ
์คํธ์์ ๋๊ธฐํ ์์ด ์ฑ๊ธํค ํจํด ์ฌ์ฉ | public class SampleServlet extends HttpServlet {
private String lastAddr = "[email protected]";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
String emailAddr = request.getParameter("emailAddr");
if (emailAddr != null) {
out.println("Email Address:");
out.println(sanitize(emailAddr));
out.println("<br>Previous Address:");
out.println(sanitize(lastAddr));
};
out.println("<p>");
out.print("<form action=\"");
out.print("SampleServlet\" ");
out.println("method=POST>");
out.println("Parameter:");
out.println("<input type=text size=20 name=emailAddr>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");
lastAddr = emailAddr;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
// Filter the specified message string for characters
// that are sensitive in HTML.
public static String sanitize(String message) {
// ...
}
} | 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.getParameter("emailAddr");
HttpSession session = request.getSession();
Object attr = session.getAttribute("lastAddr");
String lastAddr = (attr == null) ? "null" : attr.toString();
if (emailAddr != null) {
out.println("Email Address::");
out.println(sanitize(emailAddr));
out.println("<br>Previous Email Address::");
out.println(sanitize(lastAddr));
};
out.println("<p>");
out.print("<form action=\"");
out.print("SampleServlet\" ");
out.println("method=POST>");
out.println("Parameter:");
out.println("<input type=text size=20 name=emailAddr>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");
session.setAttribute("lastAddr", emailAddr);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
doGet(request, response);
}
// Filter the specified message string for characters
// that are sensitive in HTML.
public static String sanitize(String message) {
// ...
}
} |
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 MicroService:
"""Fancy MicroService"""
def __init__(self, instance_name):
self.instance_name = instance_name
def front_end(customer):
"""Display service instance"""
message_format = MESSAGE + customer
mc = MicroService("big time microservice")
print(message_format.format(mc))
#####################
# exploiting above code example
#####################
if __name__ == "__main__":
if len(sys.argv) > 1: # running from command line
# you can print the global encryption key by using '{0.__init__.__globals__[ENCRYPTION_KEY]}' as
# argument.
front_end(sys.argv[1])
else:
# running in your IDE, simulating command line:
# Printing the ENCRYPTION_KEY via the global accessible object
front_end("{0.__init__.__globals__[ENCRYPTION_KEY]}") | # 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("Contract '$instance_name' created for '$customer'")
class MicroService:
"""Fancy MicroService"""
def __init__(self, instance_name):
self.instance_name = instance_name
def get_instance_name(self) -> str:
"""return instance_name as string"""
return self.instance_name
def front_end(customer):
"""Display service instance"""
mc = MicroService("big time microservice")
print(MESSAGE.substitute(instance_name=mc.get_instance_name(),
customer=customer))
#####################
# exploiting above code example
#####################
if __name__ == "__main__":
if len(sys.argv) > 1: # running from command line
# you can print the global encryption key by using '{0.__init__.__globals__[ENCRYPTION_KEY]}' as
# argument.
front_end(sys.argv[1])
else:
# running in your IDE, simulating command line:
# Printing the ENCRYPTION_KEY via the global accessible object
front_end("{0.__init__.__globals__[ENCRYPTION_KEY]}") |
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_time, var)
return future
def interrupt(future):
print(future.cancel())
print(f"Interrupted: {future}")
#####################
# Exploiting above code example
#####################
with ThreadPoolExecutor() as executor:
task = run_thread(executor, "A")
interrupt(task) | """ 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 partial results
return
time.sleep(1)
print(f"Completed Task: {x}")
def run_thread(_executor, var):
e = Event()
future = _executor.submit(take_time, var, e)
return future, e
def interrupt(future, e):
"""Cancel the task, just in case it is not yet running, and set the Event flag"""
future.cancel()
e.set()
#####################
# Exploiting above code example
#####################
with ThreadPoolExecutor() as executor:
task, event = run_thread(executor, "A")
interrupt(task, event) |
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):
"""Custom Exception"""
def path_validation(input_path, base_path, permit_subdirs=True):
"""Ensure to have only allowed path names"""
test_path = (Path(base_path) / input_path).resolve()
if permit_subdirs:
if not Path(base_path).resolve() in test_path.resolve().parents:
raise ZipExtractException(f"Filename {test_path} not in {Path(base_path)} directory")
else:
if test_path.parent != Path(base_path).resolve():
raise ZipExtractException(f"Filename {test_path} not in {Path(base_path)} directory")
def extract_files(file, base_path):
"""Unpack zip file into base_path"""
with zipfile.ZipFile(file, mode="r") as archive:
dirs = []
# Validation:
if len(archive.infolist()) > MAXAMT:
raise ZipExtractException(f"Metadata check: too many files, limit is {MAXAMT}")
for zm in archive.infolist():
if zm.file_size > MAXSIZE:
raise ZipExtractException(f"Metadata check: {zm.filename} is too big, limit is {MAXSIZE}")
path_validation(zm.filename, base_path)
with archive.open(zm.filename, mode='r') as mte:
read_data = mte.read(MAXSIZE + 1)
if len(read_data) > MAXSIZE:
raise ZipExtractException(f"File {zm.filename} bigger than {MAXSIZE}")
if not Path(base_path).resolve().exists():
Path(base_path).resolve().mkdir(exist_ok=True)
for zm in archive.infolist():
# Extraction - create directories
if zm.is_dir():
dirs.append(Path(base_path).resolve().joinpath(zm.filename))
for directory in dirs:
Path.mkdir(directory)
for zm in archive.infolist():
with archive.open(zm.filename, mode='r') as mte:
xpath = Path(base_path).joinpath(mte.name).resolve()
print(f"Writing file {xpath}")
# Skip if directory
if xpath not in dirs: # check if file is a directory
with open(xpath, mode="wb") as filehandle:
filehandle.write(read_data)
extract_files("zip_attack_test.zip", "ziptemp") |
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 >= MAXSIZE:
print(f"Unable to extract {member.filename}, exceeds size {MAXSIZE}")
else:
print(f"Extracting {member.filename}")
archive.extract(member.filename) | # 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):
"""Custom Exception"""
def path_validation(input_path, base_path, permit_subdirs=True):
"""Ensure to have only allowed path names"""
test_path = (Path(base_path) / input_path).resolve()
if permit_subdirs:
if not Path(base_path).resolve() in test_path.resolve().parents:
raise ZipExtractException(f"Filename {test_path} not in {Path(base_path)} directory")
else:
if test_path.parent != Path(base_path).resolve():
raise ZipExtractException(f"Filename {test_path} not in {Path(base_path)} directory")
def extract_files(file, base_path):
"""Unpack zip file into base_path"""
with zipfile.ZipFile(file, mode="r") as archive:
dirs = []
# Validation:
if len(archive.infolist()) > MAXAMT:
raise ZipExtractException(f"Metadata check: too many files, limit is {MAXAMT}")
for zm in archive.infolist():
if zm.file_size > MAXSIZE:
raise ZipExtractException(f"Metadata check: {zm.filename} is too big, limit is {MAXSIZE}")
path_validation(zm.filename, base_path)
with archive.open(zm.filename, mode='r') as mte:
read_data = mte.read(MAXSIZE + 1)
if len(read_data) > MAXSIZE:
raise ZipExtractException(f"File {zm.filename} bigger than {MAXSIZE}")
if not Path(base_path).resolve().exists():
Path(base_path).resolve().mkdir(exist_ok=True)
for zm in archive.infolist():
# Extraction - create directories
if zm.is_dir():
dirs.append(Path(base_path).resolve().joinpath(zm.filename))
for directory in dirs:
Path.mkdir(directory)
for zm in archive.infolist():
with archive.open(zm.filename, mode='r') as mte:
xpath = Path(base_path).joinpath(mte.name).resolve()
print(f"Writing file {xpath}")
# Skip if directory
if xpath not in dirs: # check if file is a directory
with open(xpath, mode="wb") as filehandle:
filehandle.write(read_data)
extract_files("zip_attack_test.zip", "ziptemp") |
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", message, int(message) / 10)
for _ in range(int(message)):
time.sleep(0.01)
logging.debug("process_message: completed message %s", message)
processed_messages.append(f"processed {message}")
class MessageAPI(object):
"""Class simulating the front end facing API"""
def add_messages(self, messages: list) -> list:
""" Receives a list of messages to work on """
logging.info("add_messages: got %i messages to process", len(messages))
processed_messages = []
threads = []
for message in messages:
threads.append(
threading.Thread(target=process_message, args=[message, processed_messages]))
threads[-1].start()
logging.debug("add_messages: submitted %i messages", len(messages))
for thread in threads:
thread.join()
logging.info("add_messages: messages_done=%i", len(processed_messages))
return processed_messages
#####################
# exploiting above code example
#####################
mapi = MessageAPI()
attacker_messages = [str(msg) for msg in range(1000)]
print("ATTACKER: start sending messages")
result_list = mapi.add_messages(attacker_messages)
print(
f"ATTACKER: done sending {len(attacker_messages)} messages, got {len(result_list)} messages "
f"back")
print(f"ATTACKER: result_list = {result_list}") | """ 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: started message %s working %is", message, int(message) / 10)
for _ in range(int(message)):
time.sleep(0.01)
logging.debug("process_message: completed message %s", message)
return f"processed {message}"
class MessageAPI(object):
"""Class simulating the front end facing API"""
# TODO: Prevent the attacker from creating multiple MessageAPI objects
def __init__(self):
# TODO: set or handle timeout as it is provided by the mediation layer
self.timeout = 1
self.executor = ThreadPoolExecutor()
def add_messages(self, messages: list) -> list:
""" Receives a list of messages to work on """
# TODO: limit on max messages from the mediation layer.
# TODO: input sanitation.
futures = []
# with self.executor:
for message in messages:
futures.append(self.executor.submit(process_message, message))
logging.debug("add_messages: submitted %i messages, waiting for %is to complete.", len(messages), self.timeout)
messages_done, messages_not_done = wait(futures, timeout=self.timeout)
for future in messages_not_done:
future.cancel()
logging.info("add_messages: messages_done=%i messages_not_done=%i", len(messages_done), len(messages_not_done))
process_messages = []
for future in messages_done:
process_messages.append(future.result())
return process_messages
#####################
# exploiting above code example
#####################
mapi = MessageAPI()
result_list = []
attacker_messages = [str(msg) for msg in range(100)]
print("ATTACKER: start sending messages")
result_list = mapi.add_messages(attacker_messages)
print(f"ATTACKER: done sending {len(attacker_messages)} messages, got {len(result_list)} messages back")
print(f"ATTACKER: result_list = {result_list}") |
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: started message %s working %is", message, int(message) / 10)
for _ in range(int(message)):
time.sleep(0.01)
logging.debug("process_message: completed message %s", message)
return f"processed {message}"
class MessageAPI(object):
"""Class simulating the front end facing API"""
def __init__(self):
self.executor = ThreadPoolExecutor()
self.timeout = 1
def add_messages(self, messages: list) -> list:
""" Receives a list of messages to work on """
futures = []
for message in messages:
futures.append(self.executor.submit(process_message, message))
logging.debug("add_messages: submitted %i messages, waiting for %is to complete.",
len(messages), self.timeout)
messages_done, messages_not_done = wait(futures, timeout=self.timeout)
logging.info("add_messages: messages_done=%i messages_not_done=%i", len(messages_done),
len(messages_not_done))
process_messages = []
for future in messages_done:
process_messages.append(future.result())
return process_messages
#####################
# exploiting above code example
#####################
mapi = MessageAPI()
result_list = []
attacker_messages = [str(msg) for msg in range(1000)]
print("ATTACKER: start sending messages")
result_list = mapi.add_messages(attacker_messages)
print(
f"ATTACKER: done sending {len(attacker_messages)} messages, got {len(result_list)} messages "
f"back")
print(f"ATTACKER: result_list = {result_list}") | """ 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: started message %s working %is", message, int(message) / 10)
for _ in range(int(message)):
time.sleep(0.01)
logging.debug("process_message: completed message %s", message)
return f"processed {message}"
class MessageAPI(object):
"""Class simulating the front end facing API"""
# TODO: Prevent the attacker from creating multiple MessageAPI objects
def __init__(self):
# TODO: set or handle timeout as it is provided by the mediation layer
self.timeout = 1
self.executor = ThreadPoolExecutor()
def add_messages(self, messages: list) -> list:
""" Receives a list of messages to work on """
# TODO: limit on max messages from the mediation layer.
# TODO: input sanitation.
futures = []
# with self.executor:
for message in messages:
futures.append(self.executor.submit(process_message, message))
logging.debug("add_messages: submitted %i messages, waiting for %is to complete.",
len(messages), self.timeout)
messages_done, messages_not_done = wait(futures, timeout=self.timeout)
logging.info("add_messages: messages_done=%i messages_not_done=%i", len(messages_done),
len(messages_not_done))
if len(messages_not_done) > 0:
# TODO: be graceful, warn a trusted client
logging.warning("add_messages: %i messages taking longer than %is, %i more to process",
len(messages), self.timeout, len(messages_not_done))
messages_done, messages_not_done = wait(futures, timeout=self.timeout)
logging.info("add_messages: messages_done=%i messages_not_done=%i", len(messages_done),
len(messages_not_done))
for future in messages_not_done:
future.cancel()
logging.info("add_messages: messages_done=%i messages_not_done=%i", len(messages_done),
len(messages_not_done))
process_messages = []
for future in messages_done:
process_messages.append(future.result())
return process_messages
#####################
# exploiting above code example
#####################
mapi = MessageAPI()
result_list = []
attacker_messages = [str(msg) for msg in range(100)]
print("ATTACKER: start sending messages")
result_list = mapi.add_messages(attacker_messages)
print(
f"ATTACKER: done sending {len(attacker_messages)} messages, got {len(result_list)} messages "
f"back")
print(f"ATTACKER: result_list = {result_list}") |
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.text}")
class Preserver(object):
"""Demonstrating deserialisation"""
def can(self, _message: Message) -> bytes:
"""Serializes a Message object.
Parameters:
_message (Message): Message object
Returns:
_jar (bytes): pickled jar as string
"""
return pickle.dumps(_message)
def uncan(self, _jar) -> Message:
"""De-serializes a Message object.
Parameters:
_jar (String): Pickled jar
Returns:
(Message): Message object
"""
return pickle.loads(_jar)
# serialization of a normal package
p1 = Preserver()
message = Message()
message.printout()
jar = p1.can(message)
# sending or storing would happen here
p2 = Preserver()
message = None
message = p2.uncan(jar)
message.printout()
#####################
# exploiting above code example
#####################
print("-" * 10)
print("Attacker trying to read the message")
message = pickle.loads(jar)
message.printout()
print("-" * 10)
if platform.system() == "Windows":
PAYLOAD = b"""cos
system
(S'calc.exe'
tR."""
else:
PAYLOAD = b"""cos
system
(S'whoami;uptime;uname -a;ls -la /etc/shadow'
tR."""
print("Attacker trying to inject PAYLOAD")
p3 = Preserver()
message = None
message = p3.uncan(PAYLOAD) | """ 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: {self.text}")
class Preserver(object):
"""Demonstrating deserialisation"""
def can(self, _message: Message) -> str:
"""Serializes a Message object.
Parameters:
_message (Message): Message object
Returns:
_jar (bytes): jar as string
"""
return json.dumps(vars(_message))
def uncan(self, _jar) -> Message:
"""Verifies and de-serializes a Message object.
Parameters:
_jar (String): Pickled jar
Returns:
(Message): Message object
"""
j = json.loads(_jar)
_message = Message()
_message.sender_id = int(j["sender_id"])
_message.text = str(j["text"])
return _message
# serialization of a normal package
p1 = Preserver()
message = Message()
jar = p1.can(message)
print(jar)
print(type(json.loads(jar)))
# sending or storing would happen here
p2 = Preserver()
message = None
message = p2.uncan(jar)
message.printout()
print(message.sender_id)
#####################
# exploiting above code example
#####################
print("-" * 10)
print("Attacker trying to read the message")
print(jar)
message.printout()
print("-" * 10)
if platform.system() == "Windows":
PAYLOAD = b"""cos
system
(S'calc.exe'
tR."""
else:
PAYLOAD = b"""cos
system
(S'whoami;uptime;uname -a;ls -la /etc/shadow'
tR."""
print("Attacker trying to inject PAYLOAD")
p3 = Preserver()
message = None
message = p3.uncan(PAYLOAD) |
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
)
# Continue to other login functionality
def main():
"""Main function showing login functionality"""
logger = logging.getLogger()
logger.setLevel(logging.INFO)
username = input("Enter your username: ")
password = input("Enter your password: ")
security_question = input("What is the name of your favorite pet?: ")
login_user(username, password, security_question)
main() | """ 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 showing login functionality"""
logger = logging.getLogger()
logger.setLevel(logging.INFO)
username = input("Enter your username: ")
password = input("Enter your password: ")
security_question = input("What is the name of your favorite pet?: ")
login_user(username, password, security_question)
main() |
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 logging level: %s",
logging.getLevelName(logger.getEffectiveLevel()))
logger.debug("Processing order for address: %s", address)
# Continue to process the order.
process_order("10 Grafton Street") | """ 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("Processing order for address: %s", address)
# Continue to process the order.
process_order("10 Grafton Street") |
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.set_user_as_guest()
def set_user_as_guest(self):
self.user.value = User.GUEST
def set_user(self, user):
self.user.value = user
def work_thread(self):
""" Perform a task for the user in its own thread """
thread = current_thread()
print(f"{thread.name}: Working concurrently as {self.user.value}")
sleep(1) # To allow for worker threads to be reused
class SessionPool(object):
def __init__(self):
self.num_of_threads = 2
self.session = Session()
self.executor = ThreadPoolExecutor(initializer=self.initializer,
max_workers=self.num_of_threads
)
def initializer(self):
thread = current_thread()
print(f"+++ {thread.name} initializer +++")
self.session.set_user_as_guest()
def work_as_admin(self):
self.session.set_user(User.ADMIN)
self.session.work_thread()
def work_as_guest(self):
"""Uses the default user (GUEST) to perform a task"""
self.session.work_thread()
def execute_task(self, task):
return self.executor.submit(task)
#####################
# exploiting above code example
#####################
sp = SessionPool()
futures = [
sp.execute_task(sp.work_as_admin), # Thread 1, works as ADMIN
sp.execute_task(sp.work_as_guest), # Thread 2, should work as GUEST
sp.execute_task(sp.work_as_guest), # Thread 3, should work as GUEST
]
# To prevent the main thread from stopping before worker threads finish
wait(futures)
for future in futures:
future.result() | """ 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_user_as_guest()
def set_user_as_guest(self):
self.user.value = User.GUEST
def set_user(self, user):
self.user.value = user
def work_thread(self):
""" Perform a task for the user in its own thread """
thread = current_thread()
print(f"{thread.name}: Working concurrently as {self.user.value}")
sleep(1) # To allow for worker threads to be reused
class SessionPool(object):
def __init__(self):
self.num_of_threads = 2
self.session = Session()
self.executor = ThreadPoolExecutor(initializer=self.initializer,
max_workers=self.num_of_threads
)
def initializer(self):
thread = current_thread()
print(f"+++ {thread.name} initializer +++")
self.session.set_user_as_guest()
def work_as_admin(self):
try:
self.session.set_user(User.ADMIN)
self.session.work_thread()
finally:
self.session.set_user_as_guest()
def work_as_guest(self):
"""Uses the default user (GUEST) to perform a task"""
self.session.work_thread()
def execute_task(self, task):
return self.executor.submit(task)
#####################
# exploiting above code example
#####################
sp = SessionPool()
futures = [
sp.execute_task(sp.work_as_admin), # Thread 1, works as ADMIN
sp.execute_task(sp.work_as_guest), # Thread 2, should work as GUEST
sp.execute_task(sp.work_as_guest), # Thread 3, should work as GUEST
]
# To prevent the main thread from stopping before worker threads finish
wait(futures)
for future in futures:
future.result() |
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.set_user_as_guest()
def set_user_as_guest(self):
self.user.value = User.GUEST
def set_user(self, user):
self.user.value = user
def work_thread(self):
""" Perform a task for the user in its own thread """
thread = current_thread()
print(f"{thread.name}: Working concurrently as {self.user.value}")
sleep(1) # To allow for worker threads to be reused
class SessionPool(object):
def __init__(self):
self.num_of_threads = 3
self.session = Session()
self.executor = ThreadPoolExecutor(initializer=self.initializer,
max_workers=self.num_of_threads
)
def initializer(self):
thread = current_thread()
print(f"+++ {thread.name} initializer +++")
self.session.set_user_as_guest()
def work_as_admin(self):
self.session.set_user(User.ADMIN)
self.session.work_thread()
def work_as_guest(self):
"""Uses the default user (GUEST) to perform a task"""
self.session.work_thread()
def execute_task(self, task):
return self.executor.submit(task)
#####################
# exploiting above code example
#####################
sp = SessionPool()
futures = [
sp.execute_task(sp.work_as_admin), # Thread 1, works as ADMIN
sp.execute_task(sp.work_as_guest), # Thread 2, should work as GUEST
sp.execute_task(sp.work_as_guest), # Thread 3, should work as GUEST
]
# To prevent the main thread from stopping before worker threads finish
wait(futures)
for future in futures:
future.result() | # 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 Session(object):
def __init__(self):
self.user = local()
self.set_user_as_guest()
def set_user_as_guest(self):
self.user.value = User.GUEST
def set_user(self, user):
self.user.value = user
def work_thread(self):
""" Perform a task for the user in its own thread """
thread = current_thread()
print(f"{thread.name}: Working concurrently as {self.user.value}")
sleep(1) # To allow for worker threads to be reused
class SessionPool(object):
def __init__(self):
self.num_of_threads = 2
self.session = Session()
self.executor = ThreadPoolExecutor(initializer=self.initializer,
max_workers=self.num_of_threads
)
def initializer(self):
thread = current_thread()
print(f"+++ {thread.name} initializer +++")
self.session.set_user_as_guest()
def work_as_admin(self):
self.session.set_user(User.ADMIN)
self.session.work_thread()
def work_as_guest(self):
"""Uses the default user (GUEST) to perform a task"""
self.session.set_user_as_guest()
self.session.work_thread()
def execute_task(self, task):
return self.executor.submit(task)
#####################
# exploiting above code example
#####################
sp = SessionPool()
futures = [
sp.execute_task(sp.work_as_admin), # Thread 1, works as ADMIN
sp.execute_task(sp.work_as_guest), # Thread 2, should work as GUEST
sp.execute_task(sp.work_as_admin), # Thread 1, works as ADMIN
sp.execute_task(sp.work_as_guest), # Thread 3, should work as GUEST
sp.execute_task(sp.work_as_guest), # Thread 2, should work as GUEST
sp.execute_task(sp.work_as_guest), # Thread 3, should work as GUEST
]
# To prevent the main thread from stopping before worker threads finish
wait(futures)
for future in futures:
future.result() |
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 = "|Data|Length|\n"
for i in inputs:
futures.append(self.executor.submit(self._create_table_row, i))
for future in futures:
aggregated += future.result()
return aggregated
def _create_table_row(self, row: str) -> str:
print(f"Creating a row out of: {row}")
future = self.executor.submit(self._reformat_string, row)
return f"|{future.result()}|{len(row)}|\n"
def _reformat_string(self, row: str) -> str:
print(f"Reformatting {row}")
row_reformated = row.capitalize()
return row_reformated
#####################
# exploiting above code example
#####################
report_table_generator = ReportTableGenerator()
attacker_messages = [str(msg) for msg in range(1000)]
print("ATTACKER: start sending messages")
result = report_table_generator.generate_string_table(attacker_messages)
print(
f"ATTACKER: done sending {len(attacker_messages)} messages, got {len(result)} messages "
f"back")
print(f"ATTACKER: result = {result}") | """ 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 = "|Data|Length|\n"
for i in inputs:
futures.append(self.executor.submit(self._create_table_row, i))
for future in futures:
aggregated += future.result()
return aggregated
def _create_table_row(self, row: str) -> str:
print(f"Creating a row out of: {row}")
return f"|{self._reformat_string(row)}|{len(row)}|\n"
def _reformat_string(self, row: str) -> str:
print(f"Reformatting {row}")
row_reformated = row.capitalize()
return row_reformated
#####################
# exploiting above code example
#####################
report_table_generator = ReportTableGenerator()
attacker_messages = [str(msg) for msg in range(1000)]
print("ATTACKER: start sending messages")
result = report_table_generator.generate_string_table(attacker_messages)
print(
f"ATTACKER: done sending {len(attacker_messages)} messages, got {len(result)} messages "
f"back")
print(f"ATTACKER: result = {result}") |
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
self.lock = Lock()
def for_each_client(self):
print("For each client")
self.invoke_method(self.for_each_account)
def for_each_account(self):
print("For each account")
self.invoke_method(self.for_each_card)
def for_each_card(self):
print("For each card")
self.invoke_method(self.check_card_validity)
def check_card_validity(self):
with self.lock:
self.count += 1
print(f"Number of checked cards: {self.count}")
def invoke_method(self, method: Callable):
futures = []
for _ in range(self.number_of_times):
futures.append(self.executor.submit(method))
wait(futures)
#####################
# exploiting above code example
#####################
browser_manager = BankingService(5)
browser_manager.for_each_client() | """ 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.all_tasks = []
self.lock = Lock()
def for_each_client(self):
print("Per client")
self.invoke_method(self.for_each_account)
def for_each_account(self):
print("Per account")
self.invoke_method(self.for_each_card)
def for_each_card(self):
print("Per card")
self.invoke_method(self.check_card_validity)
def check_card_validity(self):
with self.lock:
self.count += 1
print(f"Number of checked cards: {self.count}")
def invoke_method(self, method: Callable):
futures = []
for _ in range(self.number_of_times):
if self.can_fit_in_executor():
self.lock.acquire()
future = self.executor.submit(method)
self.all_tasks.append(future)
self.lock.release()
futures.append(future)
else:
# Execute the method in the thread that invokes it
method()
wait(futures)
def can_fit_in_executor(self):
running = 0
for future in self.all_tasks:
if future.running():
running += 1
print(f"Max workers: {self.executor._max_workers}, Used workers: {running}")
# Depending on the order of submitted subtasks, the script can sometimes deadlock
# if we don't leave a spare worker.
return self.executor._max_workers > running + 1
#####################
# exploiting above code example
#####################
browser_manager = BankingService(5)
browser_manager.for_each_client() |
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 - item_count * item_cost)}"
) | # 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((balance - item_count * item_cost) / 100)}"
) |
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 - item_count * item_cost)}"
) | # 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} each. "
f"Current account balance: ${str(balance - item_count * item_cost)}"
) |
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")
# RuntimeWarning and continues
try:
b = numpy.int64(numpy.iinfo(numpy.int64).max + 1) # OverflowError and stops
except OverflowError as e:
print("Failed to assign value to B due to overflow error") |
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
return time.asctime(tuple(currtime)).split(" ")[3]
#####################
# exploiting above code example
#####################
print(get_time_in_future(23**74)) | """ 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] - 24
return time.asctime(tuple(currtime)).split(" ")[3]
except OverflowError as _:
return "Number too large to set time in future " + str(hours_in_future)
#####################
# attempting to exploit above code example
#####################
print(get_time_in_future(23**74)) |
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"
#####################
# attempting to exploit above code example
#####################
print(calculate_exponential_value(710)) |
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, OverflowError, TypeError, ValueError) as e:
print(e)
try:
print(my_exp(709))
except (AssertionError, OverflowError, TypeError, ValueError) as e:
print(e)
try:
print(my_exp(710))
except (AssertionError, OverflowError, TypeError, ValueError) as e:
print(e)
try:
print(my_exp(0))
except (AssertionError, OverflowError, TypeError, ValueError) as e:
print(e)
try:
print(my_exp("b"))
except (AssertionError, OverflowError, TypeError, ValueError) as e:
print(e)
# output
# $ python3.9 noncompliant01.py
# 2.718281828459045
# 8.218407461554972e+307
# Argument 710 is not valid
# Argument 0 is not valid
# Argument b is not valid
# $ python3.9 -O noncompliant01.py
# 2.718281828459045
# 8.218407461554972e+307
# math range error
# 1.0
# must be real number, not str | """ 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 (AssertionError, OverflowError, TypeError, ValueError) as e:
print(e)
try:
print(my_exp(709))
except (AssertionError, OverflowError, TypeError, ValueError) as e:
print(e)
try:
print(my_exp(710))
except (AssertionError, OverflowError, TypeError, ValueError) as e:
print(e)
try:
print(my_exp(0))
except (AssertionError, OverflowError, TypeError, ValueError) as e:
print(e)
try:
print(my_exp("b"))
except (AssertionError, OverflowError, TypeError, ValueError) as e:
print(e)
# output
# $ python3.9 compliant01.py
# 2.718281828459045
# 8.218407461554972e+307
# Argument 710 is not valid
# Argument 0 is not valid
# Argument b is not valid
# $ python3.9 -O compliant01.py
# 2.718281828459045
# 8.218407461554972e+307
# Argument 710 is not valid
# Argument 0 is not valid
# Argument b is not valid
|
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) -> str:
"""Normalize and validate untrusted string
Parameters:
input_string(string): String to validate
"""
# normalize
_str = unicodedata.normalize("NFKC", input_string)
# validate, exclude dangerous tags
for tag in re.findall("<[^>]*>", _str):
if tag in ["<script>", "<img", "<a href"]:
raise ValueError("Invalid input tag")
# modify, keep only trusted human words
# _filtered_str = "".join(re.findall(r'([\//\w<>\s_-]+)', _str))
_filtered_str = "".join(re.findall(r"[/\w<>\s-]+", _str))
if len(_str) - len(_filtered_str) != 0:
raise ValueError("Invalid input string")
return _filtered_str
#####################
# attempting to exploit above code example
#####################
names = [
"YES ๆฏๆณฝไธๅ
็",
"YES Marรญa Quiรฑones Marquรฉs",
"YES ะะพัะธั ะะธะบะพะปะฐะตะฒะธั ะะปััะธะฝ",
"YES Bjรถrk Guรฐmundsdรณttir",
"YES 0123456789",
"YES <b>",
"YES <p>foo</p>",
"YES underscore_",
"YES dash-",
"NOK semicolon;",
"NOK noprint " + "\uFDD0",
"NOK noprint " + "\uFDEF",
"NOK <script" + "\uFDEF" + ">",
"NOK <script็>",
"NOK and &",
]
for name in names:
print(name, end=" ")
try:
TagFilter().filter_string(name)
except ValueError as e:
print(" Error: " + str(e))
else:
print(" OK") | # 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:
"""Normalize and validate untrusted string
Parameters:
input_string(string): String to validate
"""
# normalize
_str = unicodedata.normalize("NFKC", input_string)
# modify, keep only trusted human words
_filtered_str = "".join(re.findall(r"[/\w<>\s-]+", _str))
if len(_str) - len(_filtered_str) != 0:
raise ValueError("Invalid input string")
# validate, only allow harmless tags
for tag in re.findall("<[^>]*>", _str):
if tag not in ["<b>", "<p>", "</p>"]:
raise ValueError("Invalid input tag")
return _str
#####################
# attempting to exploit above code example
#####################
names = [
"YES ๆฏๆณฝไธๅ
็",
"YES Marรญa Quiรฑones Marquรฉs",
"YES ะะพัะธั ะะธะบะพะปะฐะตะฒะธั ะะปััะธะฝ",
"YES Bjรถrk Guรฐmundsdรณttir",
"YES 0123456789",
"YES <b>",
"YES <p>foo</p>",
"YES underscore_",
"YES dash-",
"NOK semicolon;",
"NOK noprint " + "\uFDD0",
"NOK noprint " + "\uFDEF",
"NOK <script" + "\uFDEF" + ">",
"NOK <script็>",
"NOK and &",
]
for name in names:
print(f"{name}", end=" ")
try:
TagFilter().filter_string(name)
except ValueError as e:
print(" Error: " + str(e))
else:
print(" OK") |
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 above code example
#####################
TOKEN = generate_web_token()
print(f"Your insecure token is: {TOKEN}") | # 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
#####################
TOKEN = generate_web_token()
print(f"Your secure tokens is: {TOKEN}") |
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 result, the same will be true for comparing lists as they delegate comparison to the objects.
print([Integer(12)] == [Integer(12)])
# And this is equally this will always be False as well
print(Integer(12) in [Integer(10), Integer(12)]) | """ 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
#####################
# exploiting above code example
#####################
# All these senarios will now show True
print(Integer(12) == Integer(12))
print([Integer(12)] == [Integer(12)])
print(Integer(12) in [Integer(10), Integer(12)])
# By adding the handling for int we also support
print(Integer(12) == 12) |
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") or _value is None:
raise ValueError("Expected a float")
if _value <= 0:
return False
else:
return True
#####################
# attempting to exploit above code example
#####################
print(balance_is_positive("0.01"))
print(balance_is_positive("0.001"))
print(balance_is_positive("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 for expected type
_value = Decimal(value)
# TODO: exception handling
return _value.quantize(Decimal(".01"), rounding=ROUND_DOWN) > Decimal("0.00")
#####################
# attempting to exploit above code example
#####################
print(balance_is_positive("0.01"))
print(balance_is_positive("0.001"))
print(balance_is_positive("NaN")) |
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:
print("Don't care")
#####################
# exploiting above code example
#####################
exception_example() | # 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 ZeroDivisionError:
print("How is it now?")
#####################
# exploiting above code example
#####################
exception_example() |
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_handle = open(file_path, "r", encoding="utf-8")
_ = file_handle.readlines()
except Exception as exception:
logging.exception(exception)
#####################
# exploiting above code example
#####################
exception_example(["goblegoblegoble"]) | # 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_exists = False
path = Path(Path.home(), args[0])
while not file_exists:
try:
file_handle = open(path, "r", encoding="utf-8")
file_exists = True
print(file_handle.readlines())
except FileNotFoundError:
print(f"Unable to find file '{path.name}'")
filename = input("Please provide a valid filename: ")
path = Path(Path.home(), filename)
#####################
# exploiting above code example
#####################
exception_example(["goblegoblegoble"]) |
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
#####################
# get_sqrt will raise ValueError that will be suppressed by the ThreadPoolExecutor
arg = -1
result = run_thread(arg) # The outcome of the task is unknown | """ 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 exception...
raise ValueError(f"Invalid argument: {var}")
return future
#####################
# exploiting above code example
#####################
arg = -1
result = run_thread(arg) # Now code execution will be interrupted by ValueError |
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
#####################
# get_sqrt will raise ValueError that will be suppressed by the ThreadPoolExecutor
arg = -1
result = run_thread(arg) # The outcome of the task is unknown | """ 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
except ValueError as e:
# handle exception...
raise ValueError(f"Invalid argument: {var}") from None
#####################
# exploiting above code example
#####################
arg = -1
result = run_thread(arg) # Now code execution will be interrupted by ValueError |
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
#####################
# get_sqrt will raise ValueError that will be suppressed by the ThreadPoolExecutor
args = [2, -1, 4]
results = map_threads(args)
for result in results:
print(result) # Unhandled ValueError will be raised before all results are read | """ 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:
for res in result_gen:
ret.append(res)
invalid_arg += 1
return res
except ValueError as e:
# handle exception...
raise ValueError(
f"Invalid argument: {x[invalid_arg]} at list index {invalid_arg}"
) from None
#####################
# exploiting above code example
#####################
args = [2, -1, 4]
results = map_threads(args)
for result in results:
print(
result
) # The exception is handled, but the rest of the results are still unavailable |
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
#####################
# get_sqrt will raise ValueError that will be suppressed by the ThreadPoolExecutor
args = [2, -1, 4]
results = map_threads(args)
for result in results:
print(result) # Unhandled ValueError will be raised before all results are read | """ 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 executor.map(get_sqrt, x)
#####################
# exploiting above code example
#####################
args = [2, -1, 4]
results = map_threads(args)
for result in results:
print(result) # Now no exception is raised and we can read all of the results |
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"Adding an object that weighs {value} units")
self.package_weight += value
def get_package_weight(self):
return self.package_weight
#####################
# exploiting above code example
#####################
package = Package()
print(f"\nOriginal package's weight is {package.get_package_weight():.2f} units\n")
for item in [sys.float_info.max, "infinity", "-infinity", "nan"]:
try:
package.put_in_the_package(item)
print(f"Current package weight = {package.get_package_weight():.2f}\n")
except Exception as e:
print(e) | # 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 = float(user_input)
except ValueError:
raise ValueError(f"{user_input} - Input is not a number!")
print(f"value is {value}")
if isnan(value) or isinf(value):
raise ValueError(f"{user_input} - Input is not a real number!")
if value < 0:
raise ValueError(
f"{user_input} - Packed object weight cannot be negative!"
)
if value >= sys.float_info.max - self.package_weight:
raise ValueError(f"{user_input} - Input exceeds acceptable range!")
self.package_weight += value
def get_package_weight(self):
return self.package_weight
#####################
# exploiting above code example
#####################
package = Package()
print(f"\nOriginal package's weight is {package.get_package_weight():.2f} units\n")
for item in [sys.float_info.max, "infinity", "-infinity", "nan"]:
try:
package.put_in_the_package(item)
print(f"Current package weight = {package.get_package_weight():.2f}\n")
except Exception as e:
print(e) |
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
#####################
# Attempting to read a random non-existent file
read_file(f"{uuid.uuid4()}.txt") | """ 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()
except OSError as e:
if not os.path.exists(file):
print(f"File not found: {file}")
elif os.path.isdir(file):
print(f"Is a directory: {file}")
else:
print(f"An error occurred: {e}")
#####################
# exploiting above code example
#####################
# Attempting to read a random non-existent file
read_file(f"{uuid.uuid4()}.txt") |
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
#####################
# Attempting to read a random non-existent file
read_file(f"{uuid.uuid4()}.txt") | """ 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():
print(f"Is a directory: {file}")
elif not path.exists():
print(f"File not found: {file}")
else:
print(f"An error occurred: {e}")
return None
#####################
# exploiting above code example
#####################
# Attempting to read a random non-existent file
read_file(f"{uuid.uuid4()}.txt") |
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
#####################
# Attempting to remove a random non-existent file
delete_temporary_file(f"{uuid.uuid4()}.txt") | """ 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():
print(f"Is a directory: {file}")
elif not path.exists():
print(f"File not found: {file}")
else:
print(f"An error occurred: {e}")
return None
#####################
# exploiting above code example
#####################
# Attempting to read a random non-existent file
read_file(f"{uuid.uuid4()}.txt") |
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)
#####################
# attempting to exploit above code example
#####################
log_authentication_failed("""foo
WARNING:root:User login failed for: administrator""") | # 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_authentication_failed(user):
"""Simplified audit logging missing RFC 5424 details"""
if not allowed_chars(user):
logging.critical("Login attempt with non-allowed characters in user name: '%s'", user)
logging.warning("User login failed for: '%s'", user)
#####################
# attempting to exploit above code example
#####################
log_authentication_failed("""foo
WARNING:root:User login failed for: administrator""") |
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 code example
#####################
CURRENT_LOCALE = 'en_IE.utf8'
OTHER_LOCALE = 'uk_UA.utf8'
locale.setlocale(locale.LC_ALL, CURRENT_LOCALE)
# Month is 'March'
curryear, currmonth, currdate = get_date(dt)
locale.setlocale(locale.LC_ALL, OTHER_LOCALE)
# Month is 'ะฑะตัะตะทะตะฝั', i.e. berezenโ
otheryear, othermonth, otherdate = get_date(dt)
if currmonth == othermonth:
print("Locale-dependent months are equal")
else:
print("Locale-dependent months are not equal") | """ 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 'March'
currmonth = dt.month
locale.setlocale(locale.LC_ALL, OTHER_LOCALE)
# Month is 'ะฑะตัะตะทะตะฝั', i.e. berezenโ
othermonth = dt.month
if currmonth == othermonth:
print("Locale-independent months are equal")
else:
print("Locale-independent months are not equal") |