Skip to content

Commit 62a1992

Browse files
felickzCopilot
andauthored
[New Queries - githubsecuritylab/rust/hardcoded-cryptographic-key, githubsecuritylab/rust/cleartext-logging-of-key-material] - detect hard-coded and logged cryptographic keys in Rust (#259)
* Rust: add hard-coded key and logged key material queries Add githubsecuritylab/rust/hardcoded-cryptographic-key (CWE-321, CWE-798), which extends the standard rust/hard-coded-cryptographic-value query with the key and passphrase arguments of the age, orion and ring crates, and githubsecuritylab/rust/cleartext-logging-of-key-material (CWE-312, CWE-532), which reports a generated key that is written to a log or to the console. The two queries share common/CryptoKeyMaterial.qll. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust key material: match digits in orion module paths, document the fill barrier The orion sink patterns used a module path class without digits, so orion::hazardous::stream::chacha20::SecretKey::from_slice and similar constructors were not recognized. Allow digits and add a regression. State in the query help that the in-place fill check ignores the order of the statements and the content that is written. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * CI: run the Rust tests in a single slice The Test Queries step splits the tests of a language into four slices and starts one codeql test run per slice. The slices are made by test directory, so a pull request with two Rust test directories extracts them at the same time on a fresh runner. The Rust extractor installs the toolchain that it needs with rustup on demand. Both slices download it into the same ~/.rustup, and one of them fails at extraction with "could not rename 'downloaded' file", which fails Validate test results. Running the job again is unlikely to help, because every runner starts without the toolchain. Run Rust as a single slice, so that its test directories are extracted one after the other. The other languages keep four slices. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust key material: give a helper that fills a parameter a source at each call A helper that fills a mutable parameter with random bytes, such as fn fill_random(out: &mut [u8]), kept one source at the fill in its body, shared by every call. A key and a logged request id that were filled by separate calls shared it, so the request id was reported as key material. Use the buffer that each call passes as the source instead, as is done for a helper that returns the bytes, and drop the shared source in the helper. A call that passes on a parameter of its own function is not a source, like a nested returning wrapper. Add regressions for independent calls that fill a key and a logged request id, for a key that is filled by the helper and logged, and for a helper that wraps the filling helper. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 * Rust key material: test the ring HKDF key sink Both queries treat the key that is passed to ring::hkdf::Prk::new_less_safe as a key sink, but no test used it. Add a hard-coded HKDF key and a safe counterpart to the hard-coded key test, and a generated key that is used for HKDF and logged to the logging test. No query change: the sink was already recognized. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752 --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Copilot-Session: 4124a708-0b20-41df-a2e2-c945fbf86752
1 parent 4b2295d commit 62a1992

29 files changed

Lines changed: 3374 additions & 2 deletions

‎.github/workflows/ci.yml‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,11 @@ jobs:
155155
slices = [(1, 1, [str(p) for p in targeted_qlrefs])]
156156
else:
157157
print(f"Executing tests found (recursively) in the directory '{test_root}'")
158-
# Runners have 4 cores, so split the tests into 4 "slices", and run one per thread
159-
num_slices = 4
158+
# Runners have 4 cores, so split the tests into 4 "slices", and run one per thread. The Rust extractor
159+
# installs the toolchain that it needs with rustup on demand, so slices that start together download it
160+
# into the same ~/.rustup at once and one of them fails at extraction. Rust runs a single slice, which
161+
# extracts its test directories one after the other.
162+
num_slices = 1 if language == "rust" else 4
160163
slices = [(n, num_slices, [f"--slice={n}/{num_slices}", str(test_root)]) for n in range(1, num_slices+1)]
161164
162165
procs = []
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
/**
2+
* Provides classes and predicates for recognizing cryptographic key material in
3+
* Rust code, complementing the models in `codeql/rust-all` for crates such as
4+
* `age`, `orion`, `ring` and `generic-array`.
5+
*/
6+
7+
import rust
8+
private import codeql.rust.dataflow.DataFlow
9+
private import codeql.rust.security.HardcodedCryptographicValueExtensions
10+
11+
/**
12+
* Holds if `call` targets a function whose canonical path matches `pathRegex`.
13+
*/
14+
bindingset[pathRegex]
15+
private predicate callTo(Call call, string pathRegex) {
16+
call.getStaticTarget().getCanonicalPath().regexpMatch(pathRegex)
17+
}
18+
19+
/**
20+
* An argument to a cryptographic API that is interpreted as secret key material
21+
* (a key or passphrase), and that is not already modeled by `codeql/rust-all`.
22+
*/
23+
class AdditionalCryptographicKeySink extends DataFlow::Node {
24+
CryptographicValueKind kind;
25+
26+
AdditionalCryptographicKeySink() {
27+
exists(Call call, int i | this.asExpr() = call.getPositionalArgument(i) |
28+
// age: passphrase-based encryption and decryption
29+
callTo(call,
30+
[
31+
"<age::protocol::Encryptor>::with_user_passphrase",
32+
"<age::protocol::decryptor::PassphraseDecryptor>::decrypt"
33+
]) and
34+
i = 0 and
35+
kind = "password"
36+
or
37+
// orion: secret keys and passwords constructed from raw bytes
38+
callTo(call, "<orion::[a-z0-9_:]+::SecretKey>::from_slice") and
39+
i = 0 and
40+
kind = "key"
41+
or
42+
callTo(call, "<orion::[a-z0-9_:]+::Password>::from_slice") and
43+
i = 0 and
44+
kind = "password"
45+
or
46+
// ring: AEAD, HMAC and HKDF keys constructed from raw bytes
47+
callTo(call,
48+
[
49+
"<ring::aead::unbound_key::UnboundKey>::new", "<ring::hmac::Key>::new",
50+
"<ring::hkdf::Prk>::new_less_safe"
51+
]) and
52+
i = 1 and
53+
kind = "key"
54+
)
55+
}
56+
57+
/** Gets the kind of cryptographic value this sink is interpreted as. */
58+
CryptographicValueKind getKind() { result = kind }
59+
}
60+
61+
/**
62+
* A value that is used as a cryptographic key or passphrase, either by an API
63+
* modeled in `codeql/rust-all` or by an `AdditionalCryptographicKeySink`.
64+
*/
65+
class CryptographicKeySink extends DataFlow::Node {
66+
CryptographicValueKind kind;
67+
68+
CryptographicKeySink() {
69+
kind = this.(AdditionalCryptographicKeySink).getKind()
70+
or
71+
kind = this.(HardcodedCryptographicValue::Sink).getKind()
72+
}
73+
74+
/** Gets the kind of cryptographic value this sink is interpreted as. */
75+
CryptographicValueKind getKind() { result = kind }
76+
}
77+
78+
/**
79+
* Holds if `call` is a call to a random number generator API that fills
80+
* `buffer` with random bytes.
81+
*/
82+
predicate randomFillCall(Call call, Expr buffer) {
83+
callTo(call,
84+
[
85+
"<_ as ring::rand::SecureRandom>::fill", "<[^>]+ as rand_core::RngCore>::fill_bytes",
86+
"<[^>]+ as rand_core::RngCore>::try_fill_bytes", "<_ as rand::rng::Rng>::fill",
87+
"<_ as rand::rng::Rng>::try_fill", "getrandom::fill", "getrandom::getrandom"
88+
]) and
89+
buffer = call.getPositionalArgument(0)
90+
}
91+
92+
/**
93+
* Holds if `e` is the buffer argument of a call that fills it with random
94+
* bytes, or is nested inside such an argument (for example `key` in
95+
* `&mut key`).
96+
*/
97+
predicate isRandomlyFilledBuffer(Expr e) {
98+
exists(Expr buffer | randomFillCall(_, buffer) | e.getParentNode*() = buffer)
99+
}
100+
101+
/**
102+
* Holds if there is a conversion from `node1` to `node2` that preserves key
103+
* material and that is not otherwise modeled, such as
104+
* `GenericArray::from([0u8; 16])` (whose `From` implementation is often not
105+
* resolved) or `secrecy::Secret::new(s)`.
106+
*/
107+
predicate keyMaterialConversionStep(DataFlow::Node node1, DataFlow::Node node2) {
108+
exists(Call call |
109+
node1.asExpr() = call.getPositionalArgument(0) and
110+
node2.asExpr() = call
111+
|
112+
// `T::from(x)` where the `From` implementation is not resolved
113+
exists(Path path | path = call.(CallExpr).getFunction().(PathExpr).getPath() |
114+
path.getSegment().getIdentifier().getText() = "from" and
115+
exists(path.getQualifier()) and
116+
not exists(call.getStaticTarget())
117+
)
118+
or
119+
// secret wrappers from the `secrecy` crate
120+
callTo(call,
121+
[
122+
"<secrecy::Secret>::new", "<secrecy::SecretBox>::new",
123+
"<secrecy::SecretString as core::convert::From>::from"
124+
])
125+
)
126+
}
127+
128+
/**
129+
* Holds if `node2` is an encoding (such as a hex string) of the key material
130+
* in `node1`.
131+
*/
132+
predicate keyMaterialEncodingStep(DataFlow::Node node1, DataFlow::Node node2) {
133+
exists(Call call |
134+
callTo(call, ["hex::encode", "hex::encode_upper"]) and
135+
node1.asExpr() = call.getPositionalArgument(0) and
136+
node2.asExpr() = call
137+
)
138+
}
139+
140+
/**
141+
* Holds if `e` computes a property of a value, such as its length, that does
142+
* not reveal the value itself.
143+
*/
144+
predicate isNonRevealingProperty(Expr e) {
145+
e.(MethodCallExpr).getIdentifier().getText() = ["len", "is_empty", "capacity"]
146+
}
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
6+
<overview>
7+
<p>
8+
Output written to the console or to a log is commonly retained in shared log
9+
storage, and is readable by operators, log aggregation services, and anyone else
10+
with access to those logs. If a cryptographic key is written to such output, an
11+
attacker who can read the logs can recover the key and use it to decrypt or forge
12+
the data that it protects.
13+
</p>
14+
<p>
15+
This query finds generated key material that is written to a log or to standard
16+
output or standard error, possibly after hex encoding. Results from key-generation
17+
APIs such as <code>KeyInit::generate_key</code> are already known to be keys, even
18+
when returned without being passed to a constructor. Generic randomly filled
19+
buffers, including results of helpers returning such buffers, must also flow to a
20+
cryptographic key API. The standard
21+
<code>rust/cleartext-logging</code> query relies on variable names to recognize
22+
sensitive data, and does not recognize names such as <code>key_bytes</code>.
23+
</p>
24+
</overview>
25+
26+
<recommendation>
27+
<p>
28+
Do not write cryptographic keys to logs or to the console, even in encoded form. If
29+
you need to identify a key in diagnostic output, log a non-secret identifier for
30+
the key instead.
31+
</p>
32+
<p>
33+
A tool whose purpose is to generate a key and print it for the user is reported as well. Dismiss
34+
the alert in that case.
35+
</p>
36+
</recommendation>
37+
38+
<example>
39+
<p>
40+
In the following example, a freshly generated AES-256-GCM key is hex-encoded and
41+
printed:
42+
</p>
43+
<sample src="CleartextLoggingOfKeyMaterialBad.rs" />
44+
<p>
45+
In the following corrected example, only the key length is printed:
46+
</p>
47+
<sample src="CleartextLoggingOfKeyMaterialGood.rs" />
48+
</example>
49+
50+
<section title="Known limitations">
51+
<p>
52+
For generic random buffers, both key-use and logging flows must be available from
53+
the same source in the global data-flow graph. Data-flow state and operation order
54+
can prevent some combinations from being correlated. The query does not infer this
55+
relationship from variable names or use of the same helper.
56+
</p>
57+
<p>
58+
Helpers are recognized when the filled buffer flows locally to a return value, including
59+
explicit <code>return</code> expressions, or when the helper fills one of its parameters in
60+
place, as in <code>fn fill_random(out: &amp;mut [u8])</code>. A fill of only a part of a parameter, such
61+
as <code>&amp;mut out[..16]</code>, keeps its source in the helper. Each call to such a helper is a
62+
separate source, unless its result is itself locally returned by another wrapper, or the call
63+
passes on a parameter of the function that contains it. Those shared inner-call sources are
64+
suppressed to avoid correlating independent outer calls. Nested wrappers are not promoted to
65+
sources, so even logging and key use of the same outer-call result can be missed. Logging inside
66+
a helper that returns the filled buffer or fills a parameter is also not covered by this
67+
call-site model.
68+
</p>
69+
</section>
70+
71+
<references>
72+
<li>
73+
MITRE: <a href="https://cwe.mitre.org/data/definitions/532.html">CWE-532: Insertion of Sensitive Information into Log File</a>.
74+
</li>
75+
<li>
76+
OWASP: <a href="https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html">Logging Cheat Sheet</a>.
77+
</li>
78+
</references>
79+
80+
</qhelp>

0 commit comments

Comments
 (0)