|
| 1 | +/** |
| 2 | + * @name Use of a cryptographic algorithm with insufficient key size |
| 3 | + * @description Using cryptographic algorithms with too small a key size can |
| 4 | + * allow an attacker to compromise security. |
| 5 | + * @kind path-problem |
| 6 | + * @problem.severity error |
| 7 | + * @precision high |
| 8 | + * @id cpp/insufficient-key-size |
| 9 | + * @tags security |
| 10 | + * external/cwe/cwe-326 |
| 11 | + */ |
| 12 | + |
| 13 | +import cpp |
| 14 | +import semmle.code.cpp.ir.dataflow.DataFlow |
| 15 | +import semmle.code.cpp.ir.IR |
| 16 | +import DataFlow::PathGraph |
| 17 | + |
| 18 | +// Gets the recommended minimum key size (in bits) of `func`, the name of an encryption function that accepts a key size as parameter `paramIndex` |
| 19 | +int getMinimumKeyStrength(string func, int paramIndex) { |
| 20 | + func = |
| 21 | + [ |
| 22 | + "EVP_PKEY_CTX_set_dsa_paramgen_bits", "DSA_generate_parameters_ex", |
| 23 | + "EVP_PKEY_CTX_set_rsa_keygen_bits", "RSA_generate_key_ex", "RSA_generate_key_fips", |
| 24 | + "EVP_PKEY_CTX_set_dh_paramgen_prime_len", "DH_generate_parameters_ex" |
| 25 | + ] and |
| 26 | + paramIndex = 1 and |
| 27 | + result = 2048 |
| 28 | +} |
| 29 | + |
| 30 | +class KeyStrengthFlow extends DataFlow::Configuration { |
| 31 | + KeyStrengthFlow() { this = "KeyStrengthFlow" } |
| 32 | + |
| 33 | + override predicate isSource(DataFlow::Node node) { |
| 34 | + exists(int bits | |
| 35 | + node.asInstruction().(IntegerConstantInstruction).getValue().toInt() = bits and |
| 36 | + bits < getMinimumKeyStrength(_, _) and |
| 37 | + bits > 0 // exclude sentinel values |
| 38 | + ) |
| 39 | + } |
| 40 | + |
| 41 | + override predicate isSink(DataFlow::Node node) { |
| 42 | + exists(FunctionCall fc, string name, int param | |
| 43 | + node.asExpr() = fc.getArgument(param) and |
| 44 | + fc.getTarget().hasGlobalName(name) and |
| 45 | + exists(getMinimumKeyStrength(name, param)) |
| 46 | + ) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +from |
| 51 | + DataFlow::PathNode source, DataFlow::PathNode sink, KeyStrengthFlow conf, FunctionCall fc, |
| 52 | + int param, string name, int minimumBits, int bits |
| 53 | +where |
| 54 | + conf.hasFlowPath(source, sink) and |
| 55 | + sink.getNode().asExpr() = fc.getArgument(param) and |
| 56 | + fc.getTarget().hasGlobalName(name) and |
| 57 | + minimumBits = getMinimumKeyStrength(name, param) and |
| 58 | + bits = source.getNode().asInstruction().(ConstantValueInstruction).getValue().toInt() and |
| 59 | + bits < minimumBits and |
| 60 | + bits != 0 |
| 61 | +select fc, source, sink, |
| 62 | + "The key size $@ is less than the recommended key size of " + minimumBits.toString() + " bits.", |
| 63 | + source, bits.toString() |
0 commit comments