|
| 1 | +package test.cwe327.semmle.tests; |
| 2 | + |
| 3 | +import java.util.Properties; |
| 4 | +import java.io.FileInputStream; |
| 5 | +import java.io.IOException; |
| 6 | +import java.security.MessageDigest; |
| 7 | +import java.security.NoSuchAlgorithmException; |
| 8 | + |
| 9 | +public class WeakHashing { |
| 10 | + void hashing() throws NoSuchAlgorithmException, IOException { |
| 11 | + java.util.Properties props = new java.util.Properties(); |
| 12 | + props.load(new FileInputStream("example.properties")); |
| 13 | + |
| 14 | + // BAD: Using a weak hashing algorithm even with a secure default |
| 15 | + MessageDigest bad = MessageDigest.getInstance(props.getProperty("hashAlg1")); |
| 16 | + |
| 17 | + // BAD: Using a weak hashing algorithm even with a secure default |
| 18 | + MessageDigest bad2 = MessageDigest.getInstance(props.getProperty("hashAlg1", "SHA-256")); |
| 19 | + |
| 20 | + // BAD: Using a strong hashing algorithm but with a weak default |
| 21 | + MessageDigest bad3 = MessageDigest.getInstance(props.getProperty("hashAlg2", "MD5")); |
| 22 | + |
| 23 | + // BAD: Property does not exist and default (used value) is unknown |
| 24 | + MessageDigest bad4 = MessageDigest.getInstance(props.getProperty("non-existent_property", "non-existent_default")); |
| 25 | + |
| 26 | + // GOOD: Using a strong hashing algorithm |
| 27 | + MessageDigest ok = MessageDigest.getInstance(props.getProperty("hashAlg2")); |
| 28 | + |
| 29 | + // BAD?: Property does not exist (considered unknown) and but default is secure |
| 30 | + MessageDigest ok2 = MessageDigest.getInstance(props.getProperty("non-existent-property", "SHA-256")); |
| 31 | + |
| 32 | + // GOOD: Using a strong hashing algorithm |
| 33 | + MessageDigest ok3 = MessageDigest.getInstance("SHA3-512"); |
| 34 | + |
| 35 | + // GOOD: Using a strong hashing algorithm |
| 36 | + MessageDigest ok4 = MessageDigest.getInstance("SHA384"); |
| 37 | + |
| 38 | + props.load(new FileInputStream("unobserved-file.properties")); |
| 39 | + |
| 40 | + // BAD: "hashalg1" is not visible since the file isn't known, this is an 'unknown' hash |
| 41 | + // False positive/negative |
| 42 | + MessageDigest bad5 = MessageDigest.getInstance(props.getProperty("hashAlg1", "SHA-256")); |
| 43 | + } |
| 44 | +} |
0 commit comments