Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
category: minorAnalysis
---
* Added C++ random number generator models for the C standard library, POSIX/BSD, Windows, OpenSSL, and C++ engines. The models identify the output and its cryptographic security and are also available through the quantum library. Data extensions can register additional generators with `randomNumberGeneratorModel`.
1 change: 1 addition & 0 deletions cpp/ql/lib/experimental/quantum/Language.qll
Original file line number Diff line number Diff line change
Expand Up @@ -110,3 +110,4 @@ private class ConstantDataSource extends Crypto::GenericConstantSourceInstance i
}

import OpenSSL.OpenSSL
import Standard.Random
18 changes: 5 additions & 13 deletions cpp/ql/lib/experimental/quantum/OpenSSL/Random.qll
Original file line number Diff line number Diff line change
@@ -1,17 +1,9 @@
import cpp
private import experimental.quantum.Language
private import LibraryDetector
private import semmle.code.cpp.dataflow.new.DataFlow
private import cpp
private import experimental.quantum.Standard.Random

class OpenSslRandomNumberGeneratorInstance extends Crypto::RandomNumberGenerationInstance instanceof Call
{
/** A call to an OpenSSL random byte generator. */
class OpenSslRandomNumberGeneratorInstance extends ModeledRandomNumberGeneratorInstance {
OpenSslRandomNumberGeneratorInstance() {
this.(Call).getTarget().getName() in ["RAND_bytes", "RAND_pseudo_bytes"]
this.(Call).getTarget().hasGlobalName(["RAND_bytes", "RAND_priv_bytes", "RAND_pseudo_bytes"])
}

override Crypto::DataFlowNode getOutputNode() {
result.asDefiningArgument() = this.(Call).getArgument(0)
}

override string getGeneratorName() { result = this.(Call).getTarget().getName() }
}
19 changes: 19 additions & 0 deletions cpp/ql/lib/experimental/quantum/Standard/Random.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/** Exposes the C++ random number generator models as cryptographic artifacts. */

private import experimental.quantum.Language
private import semmle.code.cpp.security.RandomNumberGeneration as Random

class ModeledRandomNumberGeneratorInstance extends Crypto::RandomNumberGenerationInstance instanceof Random::RandomNumberGeneration
{
override Crypto::DataFlowNode getOutputNode() {
result = this.(Random::RandomNumberGeneration).getOutputNode()
}

override string getGeneratorName() {
result = this.(Random::RandomNumberGeneration).getGeneratorName()
}

override predicate isCryptographicallySecure() {
this.(Random::RandomNumberGeneration).isCryptographicallySecure()
}
}
37 changes: 37 additions & 0 deletions cpp/ql/lib/ext/random.model.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
extensions:
- addsTo:
pack: codeql/cpp-all
extensible: randomNumberGeneratorModel
# namespace, type, name, output, secure
data:
# C standard library / POSIX / BSD generators returning the value (insecure).
- ["", "", "rand", "", false]
- ["", "", "random", "", false]
- ["", "", "drand48", "", false]
- ["", "", "erand48", "", false]
- ["", "", "lrand48", "", false]
- ["", "", "nrand48", "", false]
- ["", "", "mrand48", "", false]
- ["", "", "jrand48", "", false]
- ["", "", "rand_r", "", false]
# POSIX/BSD generators returning the value (secure).
- ["", "", "arc4random", "", true]
- ["", "", "arc4random_uniform", "", true]
# Generators writing to a buffer argument (secure).
- ["", "", "arc4random_buf", "0", true]
- ["", "", "getentropy", "0", true]
- ["", "", "RtlGenRandom", "0", true]
- ["", "", "BCryptGenRandom", "1", true]
- ["", "", "CryptGenRandom", "2", true]
# OpenSSL byte generators.
- ["", "", "RAND_bytes", "0", true]
- ["", "", "RAND_priv_bytes", "0", true]
- ["", "", "RAND_pseudo_bytes", "0", false]
# C++ <random> engines (insecure) and std::random_device (secure).
- ["std", "mersenne_twister_engine", "operator()", "", false]
- ["std", "linear_congruential_engine", "operator()", "", false]
- ["std", "subtract_with_carry_engine", "operator()", "", false]
- ["std", "discard_block_engine", "operator()", "", false]
- ["std", "shuffle_order_engine", "operator()", "", false]
- ["std", "independent_bits_engine", "operator()", "", false]
- ["std", "random_device", "operator()", "", true]
57 changes: 57 additions & 0 deletions cpp/ql/lib/semmle/code/cpp/security/RandomNumberGeneration.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/** Provides models of random number generator calls and their outputs. */

private import cpp
private import semmle.code.cpp.ir.dataflow.DataFlow

/**
* Models a generator named `name` in `namespace` and declaring class `type`.
* An empty namespace matches the global or std namespace. An empty type selects free functions.
* An empty `output` selects the return value, otherwise it identifies the output buffer argument.
* `secure` holds for cryptographically secure generators.
*/
extensible predicate randomNumberGeneratorModel(
string namespace, string type, string name, string output, boolean secure
);

private predicate generator(Call call, string generatorName, string output, boolean secure) {
exists(string ns, string type, string name, string base |
randomNumberGeneratorModel(ns, type, name, output, secure) and
(
call.getTarget().hasQualifiedName(ns, type, name)
or
ns = "" and call.getTarget().hasQualifiedName("std", type, name)
) and
(if type = "" then base = name else base = type) and
(if ns = "" then generatorName = base else generatorName = ns + "::" + base)
)
or
call.getTarget().hasGlobalName("getrandom") and
generatorName = "getrandom" and
output = "0" and
// Linux UAPI defines GRND_INSECURE as 0x0004. Unknown flags do not establish security.
exists(int flags | flags = call.getArgument(2).getValue().toInt() |
if flags.bitAnd(4) = 0 then secure = true else secure = false
)
}

/** A call producing random output with a known security classification. */
class RandomNumberGeneration extends Call {
string generatorName;
string output;
boolean secure;

RandomNumberGeneration() { generator(this, generatorName, output, secure) }

/** Gets the name of the generator. */
string getGeneratorName() { result = generatorName }

/** Gets the generated value, or the contents of the buffer immediately after the call. */
DataFlow::Node getOutputNode() {
output = "" and result.asExpr() = this
or
result.asDefiningArgument(1) = this.getArgument(output.toInt())
}

/** Holds if this generator produces cryptographically secure output. */
predicate isCryptographicallySecure() { secure = true }
}
19 changes: 19 additions & 0 deletions cpp/ql/src/Security/CWE/CWE-330/InsecureRandomness.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <stdlib.h>

void encrypt(EVP_CIPHER_CTX *ctx, unsigned char *iv) {
unsigned char key[16];

// BAD: the key is derived from a cryptographically weak generator, so an
// attacker may be able to predict it.
for (int i = 0; i < 16; i++) {
key[i] = (unsigned char)rand();
}
EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), 0, key, iv);

// GOOD: the key is filled from a cryptographically secure generator.
if (RAND_bytes(key, sizeof(key)) != 1)
return;
EVP_EncryptInit_ex(ctx, EVP_aes_128_cbc(), 0, key, iv);
}
52 changes: 52 additions & 0 deletions cpp/ql/src/Security/CWE/CWE-330/InsecureRandomness.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
Using a cryptographically weak pseudo-random number generator to produce a security-sensitive value,
such as an encryption key, an initialization vector, a nonce, or a session token, may allow an attacker
to predict the value.
</p>

<p>
A pseudo-random number generator produces a sequence of numbers that only approximates the properties of
random numbers. The sequence is completely determined by a relatively small seed value. Generators such as
<code>rand</code>, the <code>drand48</code> family, and the C++ <code>&lt;random&gt;</code> engines
(for example <code>std::mt19937</code>) are not designed to resist prediction, so an attacker who observes
some output, or who can reconstruct the seed, may be able to predict future values.
</p>
</overview>

<recommendation>
<p>
Use a cryptographically secure random number generator when the output is used in a security-sensitive
context. Suitable choices include <code>getrandom</code> without <code>GRND_INSECURE</code>, <code>getentropy</code>, the
<code>arc4random</code> family, OpenSSL's <code>RAND_bytes</code>, the Windows
<code>BCryptGenRandom</code> function, and C++'s <code>std::random_device</code> (where it is backed by a
secure source).
</p>
</recommendation>

<example>
<p>
The following example seeds an AES key with <code>rand</code>. Because <code>rand</code> is not
cryptographically secure, an attacker may be able to predict the key.
</p>

<sample src="InsecureRandomness.c" />

<p>
Instead, fill the key from a cryptographically secure generator such as <code>RAND_bytes</code>.
</p>
</example>

<references>
<li>Wikipedia:
<a href="https://en.wikipedia.org/wiki/Pseudorandom_number_generator">Pseudorandom number generator</a>.</li>
<li>Common Weakness Enumeration:
<a href="https://cwe.mitre.org/data/definitions/330.html">CWE-330: Use of Insufficiently Random Values</a>.</li>
<li>Common Weakness Enumeration:
<a href="https://cwe.mitre.org/data/definitions/338.html">CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)</a>.</li>
</references>
</qhelp>
82 changes: 82 additions & 0 deletions cpp/ql/src/Security/CWE/CWE-330/InsecureRandomness.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/**
* @name Insecure randomness
* @description Using a cryptographically insecure pseudo-random number generator to generate a
* security-sensitive value may allow an attacker to predict what value will
* be generated.
* @kind path-problem
* @problem.severity warning
* @security-severity 7.8
* @precision medium
* @id cpp/insecure-randomness
* @tags security
* external/cwe/cwe-330
* external/cwe/cwe-338
*/

import cpp
import semmle.code.cpp.ir.dataflow.TaintTracking
import semmle.code.cpp.security.RandomNumberGeneration
import InsecureRandomnessFlow::PathGraph

/** Holds if argument `index` supplies a key or IV to an OpenSSL operation. */
private predicate keyOrIvArgument(Function f, int index) {
f.hasGlobalName(["EVP_EncryptInit_ex", "EVP_DecryptInit_ex", "EVP_CipherInit_ex"]) and
index = [3, 4]
or
f.hasGlobalName([
"EVP_EncryptInit", "EVP_DecryptInit", "EVP_CipherInit", "EVP_EncryptInit_ex2",
"EVP_DecryptInit_ex2", "EVP_CipherInit_ex2", "EVP_CipherInit_SKEY"
]) and
index = [2, 3]
or
f.hasGlobalName(["EVP_PKEY_new_mac_key", "DSA_do_sign"]) and index = 2
or
f.hasGlobalName(["EVP_PKEY_CTX_set_mac_key", "EVP_PKEY_CTX_new_from_pkey"]) and index = 1
or
f.hasGlobalName("EVP_PKEY_CTX_new") and index = 0
or
f.hasGlobalName(["EVP_DigestSignInit", "EVP_DigestVerifyInit"]) and index = 4
or
f.hasGlobalName(["EVP_DigestSignInit_ex", "EVP_DigestVerifyInit_ex", "RSA_sign", "RSA_verify"]) and
index = 5
or
f.hasGlobalName([
"EVP_SignFinal", "EVP_SignFinal_ex", "EVP_VerifyFinal", "EVP_VerifyFinal_ex", "DSA_do_verify"
]) and
index = 3
}

/**
* A taint-tracking configuration for flow from a cryptographically insecure
* random number generator to security-sensitive value such as a key, IV, or nonce.
*/
module InsecureRandomnessConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node source) {
exists(RandomNumberGeneration generator |
not generator.isCryptographicallySecure() and
source = generator.getOutputNode()
)
}

predicate isSink(DataFlow::Node sink) {
exists(FunctionCall call, int i |
keyOrIvArgument(call.getTarget(), i) and sink.asIndirectExpr(1) = call.getArgument(i)
)
}

predicate isBarrierIn(DataFlow::Node node) {
node = any(RandomNumberGeneration generator).getOutputNode()
}

predicate isBarrierOut(DataFlow::Node node) { isSink(node) }

predicate observeDiffInformedIncrementalMode() { any() }
}

module InsecureRandomnessFlow = TaintTracking::Global<InsecureRandomnessConfig>;

from InsecureRandomnessFlow::PathNode source, InsecureRandomnessFlow::PathNode sink
where InsecureRandomnessFlow::flowPath(source, sink)
select sink.getNode(), source, sink,
"This security-sensitive value depends on $@, which is not cryptographically secure.",
source.getNode(), "a randomly generated number"
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
category: newQuery
---
* Added a new query, `cpp/insecure-randomness` ("Insecure randomness"), which flags cryptographically insecure random numbers (for example from `rand` or `std::mt19937`) that are used as security-sensitive values such as encryption keys, IVs, or nonces.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
| test.cpp:133:36:133:39 | call to rand | rand | test.cpp:133:21:133:41 | call to rand | false |
| test.cpp:141:36:141:44 | call to rand | rand | test.cpp:141:21:141:46 | call to rand | false |
| test.cpp:149:36:149:41 | call to random | random | test.cpp:149:21:149:43 | call to random | false |
| test.cpp:157:36:157:42 | call to drand48 | drand48 | test.cpp:157:21:157:44 | call to drand48 | false |
| test.cpp:166:36:166:42 | call to erand48 | erand48 | test.cpp:166:21:166:45 | call to erand48 | false |
| test.cpp:174:36:174:42 | call to lrand48 | lrand48 | test.cpp:174:21:174:44 | call to lrand48 | false |
| test.cpp:183:36:183:42 | call to nrand48 | nrand48 | test.cpp:183:21:183:45 | call to nrand48 | false |
| test.cpp:191:36:191:42 | call to mrand48 | mrand48 | test.cpp:191:21:191:44 | call to mrand48 | false |
| test.cpp:200:36:200:42 | call to jrand48 | jrand48 | test.cpp:200:21:200:45 | call to jrand48 | false |
| test.cpp:209:36:209:41 | call to rand_r | rand_r | test.cpp:209:21:209:48 | call to rand_r | false |
| test.cpp:221:37:221:40 | call to rand | rand | test.cpp:221:22:221:42 | call to rand | false |
| test.cpp:227:36:227:39 | call to rand | rand | test.cpp:227:21:227:41 | call to rand | false |
| test.cpp:239:39:239:39 | call to operator() | std::mersenne_twister_engine | test.cpp:239:21:239:40 | call to operator() | false |
| test.cpp:248:39:248:39 | call to operator() | std::linear_congruential_engine | test.cpp:248:21:248:40 | call to operator() | false |
| test.cpp:257:39:257:39 | call to operator() | std::discard_block_engine | test.cpp:257:21:257:40 | call to operator() | false |
| test.cpp:266:39:266:39 | call to operator() | std::shuffle_order_engine | test.cpp:266:21:266:40 | call to operator() | false |
| test.cpp:275:39:275:39 | call to operator() | std::independent_bits_engine | test.cpp:275:21:275:40 | call to operator() | false |
| test.cpp:284:39:284:39 | call to operator() | std::linear_congruential_engine | test.cpp:284:21:284:40 | call to operator() | false |
| test.cpp:297:3:297:19 | call to RAND_pseudo_bytes | RAND_pseudo_bytes | test.cpp:297:21:297:22 | RAND_pseudo_bytes output argument | false |
| test.cpp:306:3:306:12 | call to RAND_bytes | RAND_bytes | test.cpp:306:14:306:15 | RAND_bytes output argument | true |
| test.cpp:318:36:318:45 | call to arc4random | arc4random | test.cpp:318:21:318:47 | call to arc4random | true |
| test.cpp:326:36:326:53 | call to arc4random_uniform | arc4random_uniform | test.cpp:326:21:326:58 | call to arc4random_uniform | true |
| test.cpp:335:3:335:16 | call to arc4random_buf | arc4random_buf | test.cpp:335:18:335:19 | arc4random_buf output argument | true |
| test.cpp:344:3:344:11 | call to getrandom | getrandom | test.cpp:344:13:344:14 | getrandom output argument | true |
| test.cpp:353:3:353:12 | call to getentropy | getentropy | test.cpp:353:14:353:15 | getentropy output argument | true |
| test.cpp:362:3:362:14 | call to RtlGenRandom | RtlGenRandom | test.cpp:362:16:362:17 | RtlGenRandom output argument | true |
| test.cpp:371:3:371:16 | call to CryptGenRandom | CryptGenRandom | test.cpp:371:24:371:25 | CryptGenRandom output argument | true |
| test.cpp:380:3:380:17 | call to BCryptGenRandom | BCryptGenRandom | test.cpp:380:22:380:23 | BCryptGenRandom output argument | true |
| test.cpp:389:38:389:38 | call to operator() | std::random_device | test.cpp:389:21:389:39 | call to operator() | true |
| test.cpp:399:3:399:11 | call to getrandom | getrandom | test.cpp:399:13:399:15 | getrandom output argument | false |
| test.cpp:401:3:401:11 | call to getrandom | getrandom | test.cpp:401:13:401:15 | getrandom output argument | false |
| test.cpp:403:3:403:11 | call to getrandom | getrandom | test.cpp:403:13:403:15 | getrandom output argument | true |
| test.cpp:410:3:410:19 | call to RAND_pseudo_bytes | RAND_pseudo_bytes | test.cpp:410:21:410:23 | RAND_pseudo_bytes output argument | false |
| test.cpp:412:7:412:16 | call to RAND_bytes | RAND_bytes | test.cpp:412:18:412:20 | RAND_bytes output argument | true |
| test.cpp:414:7:414:21 | call to RAND_priv_bytes | RAND_priv_bytes | test.cpp:414:23:414:25 | RAND_priv_bytes output argument | true |
| test.cpp:432:10:432:19 | call to arc4random | arc4random | test.cpp:432:10:432:19 | call to arc4random | true |
| test.cpp:432:47:432:50 | call to rand | rand | test.cpp:432:25:432:53 | call to rand | false |
| test.cpp:437:7:437:16 | call to RAND_bytes | RAND_bytes | test.cpp:437:18:437:20 | RAND_bytes output argument | true |
| test.cpp:439:27:439:30 | call to rand | rand | test.cpp:439:12:439:32 | call to rand | false |
6 changes: 6 additions & 0 deletions cpp/ql/test/query-tests/Security/CWE/CWE-330/Generators.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import cpp
import semmle.code.cpp.security.RandomNumberGeneration

from RandomNumberGeneration generator, boolean secure
where if generator.isCryptographicallySecure() then secure = true else secure = false
select generator, generator.getGeneratorName(), generator.getOutputNode(), secure
Loading