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")