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
Empty file added languages/rust/custom/.gitkeep
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Cleartext logging of cryptographic key material
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.

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 `KeyInit::generate_key` 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 `rust/cleartext-logging` query relies on variable names to recognize sensitive data, and does not recognize names such as `key_bytes`.


## Recommendation
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.


## Example
In the following example, a freshly generated AES-256-GCM key is hex-encoded and printed:


```rust
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()
}

```
In the following corrected example, only the key length is printed:


```rust
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()
}

```

## Known limitations

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.

Helpers are recognized only when the filled buffer flows locally to a return value, including explicit `return` 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.

## References
* MITRE: [CWE-532: Insertion of Sensitive Information into Log File](https://cwe.mitre.org/data/definitions/532.html).
* OWASP: [Logging Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html).
* Common Weakness Enumeration: [CWE-312](https://cwe.mitre.org/data/definitions/312.html).
* Common Weakness Enumeration: [CWE-532](https://cwe.mitre.org/data/definitions/532.html).
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<!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>
</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>
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
/**
* @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 rust/cleartext-logging-key-material
* @tags security
* 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"
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()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Hard-coded cryptographic key or passphrase
A cryptographic key or passphrase that is embedded in source code can be recovered by anyone with access to the source code or to the compiled binary. An attacker who recovers the key can decrypt data that it protects, or forge ciphertexts and authentication tags that the application will accept as genuine.

This query finds constant values (literals, constant arrays, and repeated-value arrays) that flow to the key or passphrase argument of a cryptographic API. It complements the standard `rust/hard-coded-cryptographic-value` query by recognizing additional APIs from the `age`, `orion` and `ring` crates, and keys that are wrapped with `GenericArray::from` or `secrecy::Secret::new` before use. Results that the standard query already reports are not repeated.


## Recommendation
Do not embed keys or passphrases in source code. Generate keys with a cryptographically secure random number generator, or load them at runtime from a protected secret store such as a key management service, and rotate any key that has been committed to source control.


## Example
In the following example, an AES key is a fixed array of zero bytes:


```rust
use aes::cipher::{generic_array::GenericArray, BlockEncrypt, KeyInit};
use aes::Aes128;

fn encrypt(block: &mut [u8; 16]) {
let key = GenericArray::from([0u8; 16]); // BAD: the key is hard-coded
let cipher = Aes128::new(&key);
cipher.encrypt_block(GenericArray::from_mut_slice(block));
}

```
In the following corrected example, the key is supplied at runtime from a protected secret store:


```rust
use aes::cipher::{generic_array::GenericArray, BlockEncrypt, KeyInit};
use aes::Aes128;

fn encrypt(block: &mut [u8; 16], key_bytes: [u8; 16]) {
// GOOD: the key is loaded at runtime from a protected secret store
let key = GenericArray::from(key_bytes);
let cipher = Aes128::new(&key);
cipher.encrypt_block(GenericArray::from_mut_slice(block));
}

```

## References
* MITRE: [CWE-321: Use of Hard-coded Cryptographic Key](https://cwe.mitre.org/data/definitions/321.html).
* OWASP: [Key Management Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Key_Management_Cheat_Sheet.html).
* Common Weakness Enumeration: [CWE-321](https://cwe.mitre.org/data/definitions/321.html).
* Common Weakness Enumeration: [CWE-798](https://cwe.mitre.org/data/definitions/798.html).
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

<overview>
<p>
A cryptographic key or passphrase that is embedded in source code can be recovered
by anyone with access to the source code or to the compiled binary. An attacker who
recovers the key can decrypt data that it protects, or forge ciphertexts and
authentication tags that the application will accept as genuine.
</p>
<p>
This query finds constant values (literals, constant arrays, and repeated-value
arrays) that flow to the key or passphrase argument of a cryptographic API. It
complements the standard <code>rust/hard-coded-cryptographic-value</code> query by
recognizing additional APIs from the <code>age</code>, <code>orion</code> and
<code>ring</code> crates, and keys that are wrapped with
<code>GenericArray::from</code> or <code>secrecy::Secret::new</code> before use.
Results that the standard query already reports are not repeated.
</p>
</overview>

<recommendation>
<p>
Do not embed keys or passphrases in source code. Generate keys with a
cryptographically secure random number generator, or load them at runtime from a
protected secret store such as a key management service, and rotate any key that
has been committed to source control.
</p>
</recommendation>

<example>
<p>
In the following example, an AES key is a fixed array of zero bytes:
</p>
<sample src="HardcodedCryptographicKeyBad.rs" />
<p>
In the following corrected example, the key is supplied at runtime from a protected
secret store:
</p>
<sample src="HardcodedCryptographicKeyGood.rs" />
</example>

<references>
<li>
MITRE: <a href="https://cwe.mitre.org/data/definitions/321.html">CWE-321: Use of Hard-coded Cryptographic Key</a>.
</li>
<li>
OWASP: <a href="https://cheatsheetseries.owasp.org/cheatsheets/Key_Management_Cheat_Sheet.html">Key Management Cheat Sheet</a>.
</li>
</references>

</qhelp>
Loading
Loading