Skip to content

[NEW QUERY] Rust: hard-coded cryptographic keys (CWE-321) and logging of generated key material (CWE-532) - #322

Draft
felickz with Copilot wants to merge 6 commits into
mainfrom
copilot/rust-query-create-credential-and-data-exposure
Draft

felickz with Copilot wants to merge 6 commits into
mainfrom
copilot/rust-query-create-credential-and-data-exposure

Conversation

Copilot AI commented Oct 31, 2026 •

Copy link
Copy Markdown

📝 Query Information

  • Language: rust
  • Query IDs: rust/hardcoded-cryptographic-key, rust/cleartext-logging-key-material
  • Category: security
  • Severity: warning (security-severity 6.5 / 5.5), precision medium
  • CWE: CWE-321, CWE-798 / CWE-312, CWE-532

🎯 Description

The issue reported 8 medium-severity findings in synthetic Rust apps that default setup missed. I reproduced each one in a qltest database. Rust already has a hard-coded key query, so the premise "no query exists" is only partly right:

Finding rust/hard-coded-cryptographic-value / rust/cleartext-logging Why it was missed
Aes192::new_from_slice(&[0,1,..]) ✅ found n/a
AES and Camellia keys built with GenericArray::from([..]) ❌ The From impl isn't resolved, so taint stops at from
age passphrase, orion SecretKey::from_slice, ring UnboundKey::new / hmac::Key::new ❌ No sink models for these crates
ring key filled by SystemRandom and printed with hex::encode ❌ SensitiveData uses variable names and doesn't treat key_bytes as secret

New pack: languages/rust/custom/{src,test}

Rust had no custom pack yet. I followed the layout of the other languages. The test .gitignore excludes the generated Cargo.toml, lib.rs and target/. Cargo.lock is committed so dependency versions are reproducible.

common/CryptoKeyMaterial.qll

  • AdditionalCryptographicKeySink: sinks for age (with_user_passphrase, PassphraseDecryptor::decrypt), orion (SecretKey/Password::from_slice) and ring (UnboundKey::new, hmac::Key::new, hkdf::Prk::new_less_safe).
  • CryptographicKeySink: the sinks above plus the stdlib HardcodedCryptographicValue::Sink.
  • keyMaterialConversionStep: flows through T::from(x) calls whose target isn't resolved, and through the secrecy wrappers.
  • randomFillCall / isRandomlyFilledBuffer: recognises calls that overwrite a buffer with random bytes.
  • keyMaterialEncodingStep: hex::encode and hex::encode_upper.
  • isNonRevealingProperty: len, is_empty and capacity.

rust/hardcoded-cryptographic-key

  • Uses the stdlib constant sources and barriers, plus the sinks and steps above.
  • A buffer overwritten by an RNG is treated as safe, so vec![0; n] followed by rand.fill(..) isn't reported.
  • Dedupe: a copy of the stdlib config runs alongside it, and results that rust/hard-coded-cryptographic-value already reports are dropped.

rust/cleartext-logging-key-material

  • Source: generated key material, meaning an RNG-filled buffer (post-update node) or a generate_key result.
  • Reported when: the same source reaches both a key or password sink and a CleartextLogging::Sink. Logging sinks include println!, eprintln! and the log macros.
  • Printed nonces, ciphertext, random IDs never used as keys, and key.len() aren't reported.

Example vulnerable code

let key = GenericArray::from([0u8; 16]);            // rust/hardcoded-cryptographic-key
let cipher = Aes128::new(&key);

let mut key_bytes = vec![0; AES_256_GCM.key_len()];
rng.fill(&mut key_bytes)?;
println!("{}", hex::encode(&key_bytes));             // rust/cleartext-logging-key-material
let k = UnboundKey::new(&AES_256_GCM, &key_bytes)?;

Example safe code

let mut key_bytes = vec![0; AES_256_GCM.key_len()];
rng.fill(&mut key_bytes)?;                           // overwritten with random bytes
println!("key length = {}", key_bytes.len());
let k = UnboundKey::new(&AES_256_GCM, &key_bytes)?;

🧪 Testing

  • Positive test cases included (all 8 linked findings, plus ring HMAC, orion pwhash and aes-gcm generate_key)
  • Negative test cases included (env::var, getrandom, ring fill, orion SecretKey::default, nonce, ciphertext, len())
  • Edge cases covered (rand/rand_core fills aren't covered yet, see below)
  • All tests pass

Tests use inline expectations and qltest_dependencies (they need network access to crates.io). With CLI 2.27.2 the lock files must pin codeql/rust-all 0.2.23. 0.2.24's dbscheme fails codeql test run, and the lock files are gitignored, so anyone running the tests needs the same pin.

📋 Checklist

  • Query compiles without errors
  • Documentation complete (.md and .qhelp)
  • Metadata properly set (@name, @id, @kind, etc.)
  • Tests validate query behavior
  • No false positives in test cases

⚠️ Known gap (open)

The rand and rand_core patterns in randomFillCall use canonical paths of the form <_ as …>. That form only appears for methods defined in blanket impls, so OsRng.fill_bytes(..) and rng.fill(..) never match. As a result:

  • Keys generated this way and then logged aren't reported.
  • A zero-initialised buffer filled this way and passed to a ring or orion key function can be falsely reported as hard-coded.

Planned fix: change the patterns to <([^>]+ as )?rand_core::RngCore>::(try_)?fill_bytes and <([^>]+ as )?rand::rng::Rng>::(try_)?fill, and add rand test cases.

🔗 References

Copilot AI and others added 2 commits October 31, 2026 05:38
… tests

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Copilot AI changed the title [WIP] Add new query for credential and sensitive data exposure [NEW QUERY] Rust: hard-coded cryptographic keys (CWE-321) and logging of generated key material (CWE-532) Oct 31, 2026
Copilot AI requested a review from felickz October 31, 2026 05:56
@felickz
felickz requested a balanced review from Copilot November 2, 2026 18:37
Copilot stopped reviewing on behalf of felickz due to an error November 2, 2026 18:57

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

RNG and key-flow handling can cause missed findings and false alerts, while dependency and installer configuration issues prevent reliable pack setup.

6 open issues
What changed in this PR

Adds the repository’s first custom Rust query pack to address the cryptographic-key exposure gaps described in #272, complementing existing CodeQL queries.

Changes:

  • Adds queries for hard-coded keys and passphrases, and logging of generated key material.
  • Introduces shared models for cryptographic APIs, conversions, random fills, and hex encoding.
  • Adds regression fixtures, expected results, dependency locks, and documentation with safe and unsafe examples.
File Description
languages/​rust/​example/​.gitkeep Rust example directory placeholder.
languages/​rust/​custom/​test/​qlpack.yml Defines the Rust test pack.
languages/​rust/​custom/​test/​HardcodedCryptographicKey/​test_ring.rs Tests ring keys and random initialization.
languages/​rust/​custom/​test/​HardcodedCryptographicKey/​test_orion.rs Tests Orion keys and passwords.
languages/​rust/​custom/​test/​HardcodedCryptographicKey/​test_camellia.rs Tests a constant Camellia key.
languages/​rust/​custom/​test/​HardcodedCryptographicKey/​test_age.rs Tests literal and runtime age passphrases.
languages/​rust/​custom/​test/​HardcodedCryptographicKey/​test_aes.rs Tests AES conversions and standard-query deduplication.
languages/​rust/​custom/​test/​HardcodedCryptographicKey/​options.yml Configures extraction and test dependencies.
languages/​rust/​custom/​test/​HardcodedCryptographicKey/​HardcodedCryptographicKey.qlref Connects fixtures to the hard-coded-key query.
languages/​rust/​custom/​test/​HardcodedCryptographicKey/​HardcodedCryptographicKey.expected Records expected alerts and paths.
languages/​rust/​custom/​test/​HardcodedCryptographicKey/​Cargo.lock Locks hard-coded-key test dependencies.
languages/​rust/​custom/​test/​CleartextLoggingOfKeyMaterial/​test_ring.rs Tests key logging and non-secret output.
languages/​rust/​custom/​test/​CleartextLoggingOfKeyMaterial/​test_aes.rs Tests debug and hex-encoded key logging.
languages/​rust/​custom/​test/​CleartextLoggingOfKeyMaterial/​test_aes_gcm.rs Tests generated keys, nonces, and ciphertext.
languages/​rust/​custom/​test/​CleartextLoggingOfKeyMaterial/​options.yml Configures extraction and logging-test dependencies.
languages/​rust/​custom/​test/​CleartextLoggingOfKeyMaterial/​CleartextLoggingOfKeyMaterial.qlref Connects fixtures to the logging query.
languages/​rust/​custom/​test/​CleartextLoggingOfKeyMaterial/​CleartextLoggingOfKeyMaterial.expected Records expected logging alerts and paths.
languages/​rust/​custom/​test/​CleartextLoggingOfKeyMaterial/​Cargo.lock Locks logging-test dependencies.
languages/​rust/​custom/​test/​.gitignore Excludes generated Rust test artifacts.
languages/​rust/​custom/​src/​qlpack.yml Defines the custom Rust query pack.
languages/​rust/​custom/​src/​HardcodedCryptographicKey/​HardcodedCryptographicKeyGood.rs Demonstrates runtime-supplied key material.
languages/​rust/​custom/​src/​HardcodedCryptographicKey/​HardcodedCryptographicKeyBad.rs Demonstrates a hard-coded AES key.
languages/​rust/​custom/​src/​HardcodedCryptographicKey/​HardcodedCryptographicKey.ql Detects additional constant-key flows and deduplicates standard results.
languages/​rust/​custom/​src/​HardcodedCryptographicKey/​HardcodedCryptographicKey.qhelp Provides query help and remediation guidance.
languages/​rust/​custom/​src/​HardcodedCryptographicKey/​HardcodedCryptographicKey.md Documents hard-coded-key detection and examples.
languages/​rust/​custom/​src/​common/​CryptoKeyMaterial.qll Shares crypto sinks and key-material flow models.
languages/​rust/​custom/​src/​CleartextLoggingOfKeyMaterial/​CleartextLoggingOfKeyMaterialGood.rs Demonstrates logging only key length.
languages/​rust/​custom/​src/​CleartextLoggingOfKeyMaterial/​CleartextLoggingOfKeyMaterialBad.rs Demonstrates logging a generated key.
languages/​rust/​custom/​src/​CleartextLoggingOfKeyMaterial/​CleartextLoggingOfKeyMaterial.ql Detects generated material reaching key and logging sinks.
languages/​rust/​custom/​src/​CleartextLoggingOfKeyMaterial/​CleartextLoggingOfKeyMaterial.qhelp Provides logging-query help and remediation.
languages/​rust/​custom/​src/​CleartextLoggingOfKeyMaterial/​CleartextLoggingOfKeyMaterial.md Documents key-logging detection and examples.
languages/​rust/​custom/​.gitkeep Rust custom directory placeholder.

Review effort: Balanced

Comment thread languages/rust/custom/src/qlpack.yml Resolved
Comment thread languages/rust/custom/src/qlpack.yml Resolved
Copilot AI and others added 3 commits November 2, 2026 20:27
Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Query Create]: CWE-321, CWE-532 MEDIUM - Rust: new query for credential and sensitive data exposure

3 participants