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
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"]
}
78 changes: 78 additions & 0 deletions rust/src/security/CWE-312/CleartextLoggingOfKeyMaterial.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<!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 only when the filled buffer flows locally to a return
value, including explicit <code>return</code> expressions. Each call to such a
helper is a separate source unless its result is itself locally returned by
another wrapper. Those shared inner-call sources are suppressed to avoid
correlating independent outer calls. Nested returning 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 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>
131 changes: 131 additions & 0 deletions rust/src/security/CWE-312/CleartextLoggingOfKeyMaterial.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/**
* @name Cleartext logging of cryptographic key material
* @description Writing a generated cryptographic key to a log or to the console
* exposes it to anyone who can read the output, allowing them to
* decrypt or forge the data it protects.
* @kind path-problem
* @problem.severity warning
* @security-severity 5.5
* @precision medium
* @id githubsecuritylab/rust/cleartext-logging-of-key-material
* @tags security
* experimental
* external/cwe/cwe-312
* external/cwe/cwe-532
*/

import rust
import codeql.rust.dataflow.DataFlow
import codeql.rust.dataflow.TaintTracking
import codeql.rust.security.CleartextLoggingExtensions
import common.CryptoKeyMaterial

/**
* A buffer that has just been filled with random bytes.
*/
private class RandomlyFilledBuffer extends DataFlow::PostUpdateNode {
RandomlyFilledBuffer() {
exists(Expr buffer, Expr filled |
randomFillCall(_, buffer) and
(if buffer instanceof RefExpr then filled = buffer.(RefExpr).getExpr() else filled = buffer) and
this.getPreUpdateNode().asExpr() = filled
)
}
}

/** Holds if `node` flows locally to a return value of `wrapper`. */
private predicate isReturnedBy(DataFlow::Node node, Callable wrapper) {
exists(DataFlow::Node returned |
returned.asExpr() = wrapper.getBody()
or
exists(ReturnExpr ret |
ret.getEnclosingCfgScope() = wrapper and returned.asExpr() = ret.getExpr()
)
|
DataFlow::localFlow(node, returned)
)
}

/** A key returned by an API that specifically generates cryptographic keys. */
private class GeneratedCryptographicKey extends DataFlow::Node {
GeneratedCryptographicKey() {
this.asExpr().(Call).getStaticTarget().getCanonicalPath() =
["<crypto_common::KeyInit>::generate_key", "<crypto_common::KeyIvInit>::generate_key"]
}
}

/**
* Generated material, with returned random buffers sourced at each wrapper call
* rather than conflating independent generated values at the fill in the helper.
*/
class GeneratedKeyMaterial extends DataFlow::Node {
GeneratedKeyMaterial() {
this instanceof GeneratedCryptographicKey
or
exists(RandomlyFilledBuffer buffer |
this = buffer and not isReturnedBy(buffer, _)
or
isReturnedBy(buffer, this.asExpr().(Call).getStaticTarget()) and
// Do not retain a shared inner-call source in unsupported nested wrappers.
not isReturnedBy(this, _)
)
}
}

/**
* A taint-tracking configuration for generated key material that flows to a
* cryptographic key sink and to a logging sink.
*/
module CleartextLoggingOfKeyMaterialConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node source) { source instanceof GeneratedKeyMaterial }

predicate isSink(DataFlow::Node sink) {
sink instanceof CleartextLogging::Sink
or
sink.(CryptographicKeySink).getKind() = ["key", "password"]
}

predicate isBarrier(DataFlow::Node barrier) {
barrier instanceof CleartextLogging::Barrier
or
isNonRevealingProperty(barrier.asExpr())
}

predicate isAdditionalFlowStep(DataFlow::Node node1, DataFlow::Node node2) {
// flow from `a` to `&a`
node2.asExpr().(RefExpr).getExpr() = node1.asExpr()
or
keyMaterialConversionStep(node1, node2)
or
keyMaterialEncodingStep(node1, node2)
}

predicate allowImplicitRead(DataFlow::Node node, DataFlow::ContentSet c) {
// flow out from tuple content at logging sinks
node instanceof CleartextLogging::Sink and
c.getAReadContent() instanceof DataFlow::TuplePositionContent
}
}

module CleartextLoggingOfKeyMaterialFlow =
TaintTracking::Global<CleartextLoggingOfKeyMaterialConfig>;

import CleartextLoggingOfKeyMaterialFlow::PathGraph

from
CleartextLoggingOfKeyMaterialFlow::PathNode source,
CleartextLoggingOfKeyMaterialFlow::PathNode sink
where
CleartextLoggingOfKeyMaterialFlow::flowPath(source, sink) and
sink.getNode() instanceof CleartextLogging::Sink and
(
// Key-generation APIs already establish that the value is a key.
source.getNode() instanceof GeneratedCryptographicKey
or
// Generic random buffers, including wrapper results, still require key use.
exists(CryptographicKeySink keySink | keySink.getKind() = ["key", "password"] |
CleartextLoggingOfKeyMaterialFlow::flow(source.getNode(), keySink)
)
)
select sink.getNode(), source, sink, "This operation writes $@ to a log.", source,
"generated cryptographic key material"
9 changes: 9 additions & 0 deletions rust/src/security/CWE-312/CleartextLoggingOfKeyMaterialBad.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use ring::aead::{UnboundKey, AES_256_GCM};
use ring::rand::{SecureRandom, SystemRandom};

fn make_key() -> UnboundKey {
let mut key_bytes = vec![0; AES_256_GCM.key_len()];
SystemRandom::new().fill(&mut key_bytes).unwrap();
println!("key_bytes = {}", hex::encode(&key_bytes)); // BAD: the key is written to stdout
UnboundKey::new(&AES_256_GCM, &key_bytes).unwrap()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
use ring::aead::{UnboundKey, AES_256_GCM};
use ring::rand::{SecureRandom, SystemRandom};

fn make_key() -> UnboundKey {
let mut key_bytes = vec![0; AES_256_GCM.key_len()];
SystemRandom::new().fill(&mut key_bytes).unwrap();
println!("generated a {}-byte key", key_bytes.len()); // GOOD: only the key length is written
UnboundKey::new(&AES_256_GCM, &key_bytes).unwrap()
}
Loading
Loading