Skip to content

Rust: new query rust/hardcoded-crytographic-value #18943

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 39 commits into from
Jul 22, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
9a35feb
Rust: Query framework and basic tests.
geoffw0 Mar 3, 2025
bd75f01
Rust: More test cases.
geoffw0 Mar 5, 2025
9fb00da
Rust: Implement the query (with one source, one sink model).
geoffw0 Mar 3, 2025
a6e106e
Rust: Model more sinks + flows.
geoffw0 Mar 4, 2025
aacbfc0
Rust: Improve alert messages.
geoffw0 Mar 5, 2025
055baf2
Rust: Improve results on arrays (less duplication).
geoffw0 Mar 6, 2025
ac94ac6
Rust: Model even more sinks + flows.
geoffw0 Mar 6, 2025
b4a6063
Rust: Add std::mem::zeroed as a source.
geoffw0 Mar 6, 2025
95be12e
Rust: Add qhelp and examples.
geoffw0 Mar 6, 2025
e564c41
Rust: Compute security-severity tag.
geoffw0 Mar 6, 2025
952e417
Rust: Tweak some wording.
geoffw0 Mar 6, 2025
9af2d02
Rust: Add the new sinks to stats.
geoffw0 Mar 6, 2025
42e7d1e
Rust: Fix typo.
geoffw0 Mar 6, 2025
b6c9be2
Merge branch 'main' into constcrypto
geoffw0 Mar 7, 2025
19416a9
Rust: Correct test results.
geoffw0 Mar 7, 2025
c63c1be
Rust: Accept integration test .expected changes.
geoffw0 Mar 7, 2025
3dc35f1
Rust: Accept more test changes.
geoffw0 Mar 7, 2025
fdb4362
Merge remote-tracking branch 'upstream/main' into constcrypto
geoffw0 Mar 7, 2025
b4e710f
Rust: Add missing models (for some platforms???).
geoffw0 Mar 7, 2025
e84a98b
Apply suggestions from code review
geoffw0 Mar 10, 2025
a34f9be
Rust: Add a test case for getrandom.
geoffw0 Mar 10, 2025
9e54d53
Rust: Add barrier.
geoffw0 Mar 10, 2025
1ca5c59
Rust: Replace imports of internal.DataFlowImpl where possible.
geoffw0 Mar 10, 2025
e3beacb
Rust: Print models (temporary, to see how this differs on CI).
geoffw0 Mar 10, 2025
a0f4fa2
Rust: hardcoded -> hard-coded.
geoffw0 Mar 11, 2025
704b385
Rust: Fix a mistake in the test.
geoffw0 Mar 17, 2025
81edb47
Merge branch 'main' into constcrypto
geoffw0 Mar 17, 2025
f5daec9
Rust: Fix after merge.
geoffw0 Mar 17, 2025
07011f7
Rust: Fix more after merge.
geoffw0 Mar 17, 2025
898c569
Rust: Change note.
geoffw0 Jun 24, 2025
c2ddf25
Merge branch 'main' into constcrypto
geoffw0 Jul 17, 2025
0ec10e5
Rust: Corrections after the merge.
geoffw0 Jul 17, 2025
fc8a662
Rust: Update the models.
geoffw0 Jul 17, 2025
796cb19
Rust: Accept test regressions with new format MaD.
geoffw0 Jul 21, 2025
ec3ad85
Rust: Add another test case for barriers (that still functions).
geoffw0 Jul 21, 2025
d53dada
Rust: Update barrier logic to use getCanonicalPath.
geoffw0 Jul 21, 2025
43ac82f
Rust: Update consistency check .expected files.
geoffw0 Jul 21, 2025
1945fb8
Rust: Accept changes to query suites.
geoffw0 Jul 21, 2025
f7d822b
Rust: Remove empty file.
geoffw0 Jul 22, 2025
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
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ ql/rust/ql/src/queries/security/CWE-312/CleartextLogging.ql
ql/rust/ql/src/queries/security/CWE-327/BrokenCryptoAlgorithm.ql
ql/rust/ql/src/queries/security/CWE-328/WeakSensitiveDataHashing.ql
ql/rust/ql/src/queries/security/CWE-770/UncontrolledAllocationSize.ql
ql/rust/ql/src/queries/security/CWE-798/HardcodedCryptographicValue.ql
ql/rust/ql/src/queries/security/CWE-825/AccessInvalidPointer.ql
ql/rust/ql/src/queries/summary/LinesOfCode.ql
ql/rust/ql/src/queries/summary/LinesOfUserCode.ql
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ ql/rust/ql/src/queries/security/CWE-327/BrokenCryptoAlgorithm.ql
ql/rust/ql/src/queries/security/CWE-328/WeakSensitiveDataHashing.ql
ql/rust/ql/src/queries/security/CWE-696/BadCtorInitialization.ql
ql/rust/ql/src/queries/security/CWE-770/UncontrolledAllocationSize.ql
ql/rust/ql/src/queries/security/CWE-798/HardcodedCryptographicValue.ql
ql/rust/ql/src/queries/security/CWE-825/AccessAfterLifetime.ql
ql/rust/ql/src/queries/security/CWE-825/AccessInvalidPointer.ql
ql/rust/ql/src/queries/summary/LinesOfCode.ql
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ ql/rust/ql/src/queries/security/CWE-312/CleartextLogging.ql
ql/rust/ql/src/queries/security/CWE-327/BrokenCryptoAlgorithm.ql
ql/rust/ql/src/queries/security/CWE-328/WeakSensitiveDataHashing.ql
ql/rust/ql/src/queries/security/CWE-770/UncontrolledAllocationSize.ql
ql/rust/ql/src/queries/security/CWE-798/HardcodedCryptographicValue.ql
ql/rust/ql/src/queries/security/CWE-825/AccessAfterLifetime.ql
ql/rust/ql/src/queries/security/CWE-825/AccessInvalidPointer.ql
ql/rust/ql/src/queries/summary/LinesOfCode.ql
Expand Down
9 changes: 9 additions & 0 deletions rust/ql/lib/codeql/rust/frameworks/genericarray.model.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
extensions:
- addsTo:
pack: codeql/rust-all
extensible: summaryModel
data:
- ["<generic_array::GenericArray>::from_slice", "Argument[0].Reference", "ReturnValue.Reference", "value", "manual"]
- ["<generic_array::GenericArray>::from_mut_slice", "Argument[0].Reference", "ReturnValue.Reference", "value", "manual"]
- ["<generic_array::GenericArray>::try_from_slice", "Argument[0].Reference", "ReturnValue.Field[crate::result::Result::Ok(0)].Reference", "value", "manual"]
- ["<generic_array::GenericArray>::try_from_mut_slice", "Argument[0].Reference", "ReturnValue.Field[crate::result::Result::Ok(0)].Reference", "value", "manual"]
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,28 @@ extensions:
- ["<_ as digest::digest::Digest>::chain_update", "Argument[0]", "hasher-input", "manual"]
- ["<_ as digest::digest::Digest>::digest", "Argument[0]", "hasher-input", "manual"]
- ["md5::compute", "Argument[0]", "hasher-input", "manual"]
- ["<_ as crypto_common::KeyInit>::new", "Argument[0]", "credentials-key", "manual"]
- ["<_ as crypto_common::KeyInit>::new", "Argument[1]", "credentials-iv", "manual"]
- ["<_ as crypto_common::KeyInit>::new_from_slice", "Argument[0]", "credentials-key", "manual"]
- ["<_ as crypto_common::KeyInit>::new_from_slice", "Argument[1]", "credentials-iv", "manual"]
- ["<_ as crypto_common::KeyIvInit>::new", "Argument[0]", "credentials-key", "manual"]
- ["<_ as crypto_common::KeyIvInit>::new", "Argument[1]", "credentials-iv", "manual"]
- ["<_ as crypto_common::KeyIvInit>::new_from_slice", "Argument[0]", "credentials-key", "manual"]
- ["<_ as crypto_common::KeyIvInit>::new_from_slice", "Argument[1]", "credentials-iv", "manual"]
- ["<cipher::stream_wrapper::StreamCipherCoreWrapper as crypto_common::KeyInit>::new", "Argument[0]", "credentials-key", "manual"]
- ["<cipher::stream_wrapper::StreamCipherCoreWrapper as crypto_common::KeyInit>::new", "Argument[1]", "credentials-iv", "manual"]
- ["<cipher::stream_wrapper::StreamCipherCoreWrapper as crypto_common::KeyInit>::new_from_slice", "Argument[0]", "credentials-key", "manual"]
- ["<cipher::stream_wrapper::StreamCipherCoreWrapper as crypto_common::KeyInit>::new_from_slice", "Argument[1]", "credentials-iv", "manual"]
- ["<cipher::stream_wrapper::StreamCipherCoreWrapper as crypto_common::KeyIvInit>::new", "Argument[0]", "credentials-key", "manual"]
- ["<cipher::stream_wrapper::StreamCipherCoreWrapper as crypto_common::KeyIvInit>::new", "Argument[1]", "credentials-iv", "manual"]
- ["<cipher::stream_wrapper::StreamCipherCoreWrapper as crypto_common::KeyIvInit>::new_from_slice", "Argument[0]", "credentials-key", "manual"]
- ["<cipher::stream_wrapper::StreamCipherCoreWrapper as crypto_common::KeyIvInit>::new_from_slice", "Argument[1]", "credentials-iv", "manual"]
- ["<digest::core_api::wrapper::CoreWrapper as crypto_common::KeyInit>::new", "Argument[0]", "credentials-key", "manual"]
- ["<digest::core_api::wrapper::CoreWrapper as crypto_common::KeyInit>::new", "Argument[1]", "credentials-iv", "manual"]
- ["<digest::core_api::wrapper::CoreWrapper as crypto_common::KeyInit>::new_from_slice", "Argument[0]", "credentials-key", "manual"]
- ["<digest::core_api::wrapper::CoreWrapper as crypto_common::KeyInit>::new_from_slice", "Argument[1]", "credentials-iv", "manual"]
- ["<digest::core_api::wrapper::CoreWrapper as crypto_common::KeyIvInit>::new", "Argument[0]", "credentials-key", "manual"]
- ["<digest::core_api::wrapper::CoreWrapper as crypto_common::KeyIvInit>::new", "Argument[1]", "credentials-iv", "manual"]
- ["<digest::core_api::wrapper::CoreWrapper as crypto_common::KeyIvInit>::new_from_slice", "Argument[0]", "credentials-key", "manual"]
- ["<digest::core_api::wrapper::CoreWrapper as crypto_common::KeyIvInit>::new_from_slice", "Argument[1]", "credentials-iv", "manual"]
- ["<_ as aead::Aead>::encrypt", "Argument[0]", "credentials-nonce", "manual"]
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@ extensions:
pack: codeql/rust-all
extensible: summaryModel
data:
# Conversions
- ["<core::alloc::layout::Layout>::align_to", "Argument[self].Element", "ReturnValue.Field[0,1,2].Reference.Element", "taint", "manual"]
- ["<_ as core::convert::Into>::into", "Argument[self].Element", "ReturnValue.Element", "taint", "manual"]
- ["<_ as core::convert::Into>::into", "Argument[self].Reference.Element", "ReturnValue.Element", "taint", "manual"]
- ["<alloc::string::String as core::convert::Into>::into", "Argument[self].Element", "ReturnValue.Element", "taint", "manual"]
- ["<alloc::string::String as core::convert::Into>::into", "Argument[self].Reference.Element", "ReturnValue.Element", "taint", "manual"]
# Iterator
- ["<core::result::Result>::iter", "Argument[self].Element", "ReturnValue.Element", "value", "manual"]
- ["<alloc::vec::Vec as value_trait::array::Array>::iter", "Argument[self].Element", "ReturnValue.Element", "value", "manual"]
Expand Down Expand Up @@ -59,6 +65,8 @@ extensions:
pack: codeql/rust-all
extensible: sourceModel
data:
# Mem
- ["core::mem::zeroed", "ReturnValue.Element", "constant-source", "manual"]
# Ptr
- ["core::ptr::drop_in_place", "Argument[0]", "pointer-invalidate", "manual"]
- ["core::ptr::dangling", "ReturnValue", "pointer-invalidate", "manual"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import rust
private import codeql.rust.dataflow.DataFlow
private import codeql.rust.dataflow.internal.DataFlowImpl
private import codeql.rust.dataflow.FlowSink
private import codeql.rust.security.SensitiveData
private import codeql.rust.Concepts

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
/**
* Provides classes and predicates for reasoning about hard-coded cryptographic value
* vulnerabilities.
*/

import rust
private import codeql.rust.dataflow.DataFlow
private import codeql.rust.dataflow.FlowSource
private import codeql.rust.dataflow.FlowSink
private import codeql.rust.Concepts
private import codeql.rust.security.SensitiveData

/**
* A kind of cryptographic value.
*/
class CryptographicValueKind extends string {
CryptographicValueKind() { this = ["password", "key", "iv", "nonce", "salt"] }

/**
* Gets a description of this value kind for user-facing messages.
*/
string getDescription() {
this = "password" and result = "a password"
or
this = "key" and result = "a key"
or
this = "iv" and result = "an initialization vector"
or
this = "nonce" and result = "a nonce"
or
this = "salt" and result = "a salt"
}
}

/**
* Provides default sources, sinks and barriers for detecting hard-coded cryptographic
* value vulnerabilities, as well as extension points for adding your own.
*/
module HardcodedCryptographicValue {
/**
* A data flow source for hard-coded cryptographic value vulnerabilities.
*/
abstract class Source extends DataFlow::Node { }

/**
* A data flow sink for hard-coded cryptographic value vulnerabilities.
*/
abstract class Sink extends QuerySink::Range {
override string getSinkType() { result = "HardcodedCryptographicValue" }

/**
* Gets the kind of credential this sink is interpreted as.
*/
abstract CryptographicValueKind getKind();
}

/**
* A barrier for hard-coded cryptographic value vulnerabilities.
*/
abstract class Barrier extends DataFlow::Node { }

/**
* A literal, considered as a flow source.
*/
private class LiteralSource extends Source {
LiteralSource() { this.asExpr().getExpr() instanceof LiteralExpr }
}

/**
* An array initialized from a list of literals, considered as a single flow source. For example:
* ```
* `[0, 0, 0, 0]`
* ```
*/
private class ArrayListSource extends Source {
ArrayListSource() { this.asExpr().getExpr().(ArrayListExpr).getExpr(_) instanceof LiteralExpr }
}

/**
* An externally modeled source for constant values.
*/
private class ModeledSource extends Source {
ModeledSource() { sourceNode(this, "constant-source") }
}

/**
* An externally modeled sink for hard-coded cryptographic value vulnerabilities.
*/
private class ModelsAsDataSinks extends Sink {
CryptographicValueKind kind;

ModelsAsDataSinks() { sinkNode(this, "credentials-" + kind) }

override CryptographicValueKind getKind() { result = kind }
}

/**
* A call to `getrandom` that is a barrier.
*/
private class GetRandomBarrier extends Barrier {
GetRandomBarrier() {
exists(CallExprBase ce |
ce.getStaticTarget().(Addressable).getCanonicalPath() =
["getrandom::fill", "getrandom::getrandom"] and
this.asExpr().getExpr().getParentNode*() = ce.getArgList().getArg(0)
)
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

import rust
private import codeql.rust.dataflow.DataFlow
private import codeql.rust.dataflow.internal.DataFlowImpl
private import codeql.rust.dataflow.FlowSink
private import codeql.rust.Concepts
private import codeql.util.Unit

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
category: newQuery
---
* Added a new query, `rust/hardcoded-crytographic-value`, for detecting use of hardcoded keys, passwords, salts and initialization vectors.
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

<overview>
<p>
Hard-coded passwords, keys, initialization vectors, and salts should not be used for cryptographic operations.
</p>
<ul>
<li>
Attackers can easily recover hard-coded values if they have access to the source code or compiled executable.
</li>
<li>
Some hard-coded values are easily guessable.
</li>
<li>
Use of hard-coded values may leave cryptographic operations vulnerable to dictionary attacks, rainbow tables, and other forms of cryptanalysis.
</li>
</ul>

</overview>
<recommendation>

<p>
Use randomly generated key material, initialization vectors, and salts. Use strong passwords that are not hard-coded.
</p>

</recommendation>
<example>

<p>
The following example shows instantiating a cipher with hard-coded key material, making the encrypted data vulnerable to recovery.
</p>

<sample src="HardcodedCryptographicValueBad.rs" />

<p>
In the fixed code below, the key material is randomly generated and not hard-coded, which protects the encrypted data against recovery. A real application would also need a strategy for secure key management after the key has been generated.
</p>

<sample src="HardcodedCryptographicValueGood.rs" />

</example>
<references>

<li>
OWASP: <a href="https://www.owasp.org/index.php/Use_of_hard-coded_password">Use of hard-coded password</a>.
</li>
<li>
OWASP: <a href="https://cheatsheetseries.owasp.org/cheatsheets/Key_Management_Cheat_Sheet.html">Key Management Cheat Sheet</a>.
</li>
<li>
O'Reilly: <a href="https://www.oreilly.com/library/view/secure-programming-cookbook/0596003943/ch04s09.html">Using Salts, Nonces, and Initialization Vectors</a>.
</li>

</references>
</qhelp>
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* @name Hard-coded cryptographic value
* @description Using hard-coded keys, passwords, salts or initialization
* vectors is not secure.
* @kind path-problem
* @problem.severity warning
* @security-severity 9.8
* @precision high
* @id rust/hard-coded-cryptographic-value
* @tags security
* external/cwe/cwe-259
* external/cwe/cwe-321
* external/cwe/cwe-798
* external/cwe/cwe-1204
*/

import rust
import codeql.rust.security.HardcodedCryptographicValueExtensions
import codeql.rust.dataflow.DataFlow
import codeql.rust.dataflow.TaintTracking
import codeql.rust.dataflow.internal.DataFlowImpl
import codeql.rust.dataflow.internal.Content

/**
* A taint-tracking configuration for hard-coded cryptographic value vulnerabilities.
*/
module HardcodedCryptographicValueConfig implements DataFlow::ConfigSig {
import HardcodedCryptographicValue

predicate isSource(DataFlow::Node source) { source instanceof Source }

predicate isSink(DataFlow::Node sink) { sink instanceof Sink }

predicate isBarrier(DataFlow::Node barrier) { barrier instanceof Barrier }

predicate isBarrierIn(DataFlow::Node node) {
// make sources barriers so that we only report the closest instance
// (this combined with sources for `ArrayListExpr` means we only get one source in
// case like `[0, 0, 0, 0]`)
isSource(node)
}

predicate allowImplicitRead(DataFlow::Node node, DataFlow::ContentSet c) {
// flow out from reference content at sinks.
isSink(node) and
c.getAReadContent() instanceof ReferenceContent
}
}

module HardcodedCryptographicValueFlow = TaintTracking::Global<HardcodedCryptographicValueConfig>;

import HardcodedCryptographicValueFlow::PathGraph

from
HardcodedCryptographicValueFlow::PathNode source, HardcodedCryptographicValueFlow::PathNode sink
where HardcodedCryptographicValueFlow::flowPath(source, sink)
select source.getNode(), source, sink, "This hard-coded value is used as $@.", sink,
sink.getNode().(HardcodedCryptographicValueConfig::Sink).getKind().getDescription()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
let key: [u8;32] = [0;32]; // BAD: Using hard-coded keys for encryption
let cipher = Aes256Gcm::new(&key.into());
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
let key = Aes256Gcm::generate_key(aes_gcm::aead::OsRng); // GOOD: Using randomly generated keys for encryption
let cipher = Aes256Gcm::new(&key);
1 change: 1 addition & 0 deletions rust/ql/src/queries/summary/Stats.qll
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ private import codeql.rust.security.SqlInjectionExtensions
private import codeql.rust.security.TaintedPathExtensions
private import codeql.rust.security.UncontrolledAllocationSizeExtensions
private import codeql.rust.security.WeakSensitiveDataHashingExtensions
private import codeql.rust.security.HardcodedCryptographicValueExtensions

/**
* Gets a count of the total number of lines of code in the database.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
multipleCallTargets
| test_cipher.rs:15:30:15:77 | ...::new(...) |
| test_cipher.rs:19:30:19:80 | ...::new(...) |
| test_cipher.rs:22:30:22:98 | ...::new(...) |
| test_cipher.rs:26:30:26:101 | ...::new(...) |
| test_cipher.rs:30:30:30:102 | ...::new(...) |
| test_cipher.rs:38:30:38:81 | ...::new(...) |
| test_cipher.rs:42:30:42:80 | ...::new(...) |
| test_cipher.rs:47:30:47:85 | ...::new(...) |
| test_cipher.rs:51:31:51:83 | ...::new(...) |
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy