Skip to content
Merged
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
7 changes: 5 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,11 @@ jobs:
slices = [(1, 1, [str(p) for p in targeted_qlrefs])]
else:
print(f"Executing tests found (recursively) in the directory '{test_root}'")
# Runners have 4 cores, so split the tests into 4 "slices", and run one per thread
num_slices = 4
# Runners have 4 cores, so split the tests into 4 "slices", and run one per thread. The Rust extractor
# installs the toolchain that it needs with rustup on demand, so slices that start together download it
# into the same ~/.rustup at once and one of them fails at extraction. Rust runs a single slice, which
# extracts its test directories one after the other.
num_slices = 1 if language == "rust" else 4
slices = [(n, num_slices, [f"--slice={n}/{num_slices}", str(test_root)]) for n in range(1, num_slices+1)]

procs = []
Expand Down
146 changes: 146 additions & 0 deletions rust/src/common/CryptoKeyMaterial.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/**
* Provides classes and predicates for recognizing cryptographic key material in
* Rust code, complementing the models in `codeql/rust-all` for crates such as
* `age`, `orion`, `ring` and `generic-array`.
*/

import rust
private import codeql.rust.dataflow.DataFlow
private import codeql.rust.security.HardcodedCryptographicValueExtensions

/**
* Holds if `call` targets a function whose canonical path matches `pathRegex`.
*/
bindingset[pathRegex]
private predicate callTo(Call call, string pathRegex) {
call.getStaticTarget().getCanonicalPath().regexpMatch(pathRegex)
}

/**
* An argument to a cryptographic API that is interpreted as secret key material
* (a key or passphrase), and that is not already modeled by `codeql/rust-all`.
*/
class AdditionalCryptographicKeySink extends DataFlow::Node {
CryptographicValueKind kind;

AdditionalCryptographicKeySink() {
exists(Call call, int i | this.asExpr() = call.getPositionalArgument(i) |
// age: passphrase-based encryption and decryption
callTo(call,
[
"<age::protocol::Encryptor>::with_user_passphrase",
"<age::protocol::decryptor::PassphraseDecryptor>::decrypt"
]) and
i = 0 and
kind = "password"
or
// orion: secret keys and passwords constructed from raw bytes
callTo(call, "<orion::[a-z0-9_:]+::SecretKey>::from_slice") and
i = 0 and
kind = "key"
or
callTo(call, "<orion::[a-z0-9_:]+::Password>::from_slice") and
i = 0 and
kind = "password"
or
// ring: AEAD, HMAC and HKDF keys constructed from raw bytes
callTo(call,
[
"<ring::aead::unbound_key::UnboundKey>::new", "<ring::hmac::Key>::new",
"<ring::hkdf::Prk>::new_less_safe"
]) and
i = 1 and
kind = "key"
)
}

/** Gets the kind of cryptographic value this sink is interpreted as. */
CryptographicValueKind getKind() { result = kind }
}

/**
* A value that is used as a cryptographic key or passphrase, either by an API
* modeled in `codeql/rust-all` or by an `AdditionalCryptographicKeySink`.
*/
class CryptographicKeySink extends DataFlow::Node {
CryptographicValueKind kind;

CryptographicKeySink() {
kind = this.(AdditionalCryptographicKeySink).getKind()
or
kind = this.(HardcodedCryptographicValue::Sink).getKind()
}

/** Gets the kind of cryptographic value this sink is interpreted as. */
CryptographicValueKind getKind() { result = kind }
}

/**
* Holds if `call` is a call to a random number generator API that fills
* `buffer` with random bytes.
*/
predicate randomFillCall(Call call, Expr buffer) {
callTo(call,
[
"<_ as ring::rand::SecureRandom>::fill", "<[^>]+ as rand_core::RngCore>::fill_bytes",
"<[^>]+ as rand_core::RngCore>::try_fill_bytes", "<_ as rand::rng::Rng>::fill",
"<_ as rand::rng::Rng>::try_fill", "getrandom::fill", "getrandom::getrandom"
]) and
buffer = call.getPositionalArgument(0)
}

/**
* Holds if `e` is the buffer argument of a call that fills it with random
* bytes, or is nested inside such an argument (for example `key` in
* `&mut key`).
*/
predicate isRandomlyFilledBuffer(Expr e) {
exists(Expr buffer | randomFillCall(_, buffer) | e.getParentNode*() = buffer)
}

/**
* Holds if there is a conversion from `node1` to `node2` that preserves key
* material and that is not otherwise modeled, such as
* `GenericArray::from([0u8; 16])` (whose `From` implementation is often not
* resolved) or `secrecy::Secret::new(s)`.
*/
predicate keyMaterialConversionStep(DataFlow::Node node1, DataFlow::Node node2) {
exists(Call call |
node1.asExpr() = call.getPositionalArgument(0) and
node2.asExpr() = call
|
// `T::from(x)` where the `From` implementation is not resolved
exists(Path path | path = call.(CallExpr).getFunction().(PathExpr).getPath() |
path.getSegment().getIdentifier().getText() = "from" and
exists(path.getQualifier()) and
not exists(call.getStaticTarget())
)
or
// secret wrappers from the `secrecy` crate
callTo(call,
[
"<secrecy::Secret>::new", "<secrecy::SecretBox>::new",
"<secrecy::SecretString as core::convert::From>::from"
])
)
}

/**
* Holds if `node2` is an encoding (such as a hex string) of the key material
* in `node1`.
*/
predicate keyMaterialEncodingStep(DataFlow::Node node1, DataFlow::Node node2) {
exists(Call call |
callTo(call, ["hex::encode", "hex::encode_upper"]) and
node1.asExpr() = call.getPositionalArgument(0) and
node2.asExpr() = call
)
}

/**
* Holds if `e` computes a property of a value, such as its length, that does
* not reveal the value itself.
*/
predicate isNonRevealingProperty(Expr e) {
e.(MethodCallExpr).getIdentifier().getText() = ["len", "is_empty", "capacity"]
}
80 changes: 80 additions & 0 deletions rust/src/security/CWE-312/CleartextLoggingOfKeyMaterial.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

<overview>
<p>
Output written to the console or to a log is commonly retained in shared log
storage, and is readable by operators, log aggregation services, and anyone else
with access to those logs. If a cryptographic key is written to such output, an
attacker who can read the logs can recover the key and use it to decrypt or forge
the data that it protects.
</p>
<p>
This query finds generated key material that is written to a log or to standard
output or standard error, possibly after hex encoding. Results from key-generation
APIs such as <code>KeyInit::generate_key</code> are already known to be keys, even
when returned without being passed to a constructor. Generic randomly filled
buffers, including results of helpers returning such buffers, must also flow to a
cryptographic key API. The standard
<code>rust/cleartext-logging</code> query relies on variable names to recognize
sensitive data, and does not recognize names such as <code>key_bytes</code>.
</p>
</overview>

<recommendation>
<p>
Do not write cryptographic keys to logs or to the console, even in encoded form. If
you need to identify a key in diagnostic output, log a non-secret identifier for
the key instead.
</p>
<p>
A tool whose purpose is to generate a key and print it for the user is reported as well. Dismiss
the alert in that case.
</p>
</recommendation>

<example>
<p>
In the following example, a freshly generated AES-256-GCM key is hex-encoded and
printed:
</p>
<sample src="CleartextLoggingOfKeyMaterialBad.rs" />
<p>
In the following corrected example, only the key length is printed:
</p>
<sample src="CleartextLoggingOfKeyMaterialGood.rs" />
</example>

<section title="Known limitations">
<p>
For generic random buffers, both key-use and logging flows must be available from
the same source in the global data-flow graph. Data-flow state and operation order
can prevent some combinations from being correlated. The query does not infer this
relationship from variable names or use of the same helper.
</p>
<p>
Helpers are recognized when the filled buffer flows locally to a return value, including
explicit <code>return</code> expressions, or when the helper fills one of its parameters in
place, as in <code>fn fill_random(out: &amp;mut [u8])</code>. A fill of only a part of a parameter, such
as <code>&amp;mut out[..16]</code>, keeps its source in the helper. Each call to such a helper is a
separate source, unless its result is itself locally returned by another wrapper, or the call
passes on a parameter of the function that contains it. Those shared inner-call sources are
suppressed to avoid correlating independent outer calls. Nested wrappers are not promoted to
sources, so even logging and key use of the same outer-call result can be missed. Logging inside
a helper that returns the filled buffer or fills a parameter is also not covered by this
call-site model.
</p>
</section>

<references>
<li>
MITRE: <a href="https://cwe.mitre.org/data/definitions/532.html">CWE-532: Insertion of Sensitive Information into Log File</a>.
</li>
<li>
OWASP: <a href="https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html">Logging Cheat Sheet</a>.
</li>
</references>

</qhelp>
Loading