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
8 changes: 4 additions & 4 deletions unified/ql/lib/ext/legacy-swift.model.json
Original file line number Diff line number Diff line change
Expand Up @@ -261,10 +261,10 @@
["", "SHA384.Type", true, "hash(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA384", "manual"],
["", "SHA384", true, "update(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA384", "manual"],
["", "SHA384", true, "update(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA384", "manual"],
["", "SHA3", true, "callAsFunction(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA2", "manual"],
["", "SHA3", true, "calculate(for:)", "", "", "Argument[for:]", "weak-password-hash-input-SHA2", "manual"],
["", "SHA3", true, "process(block:currentHash:)", "", "", "Argument[block:]", "weak-password-hash-input-SHA2", "manual"],
["", "SHA3", true, "update(withBytes:isLast?:)", "", "", "Argument[withBytes:]", "weak-password-hash-input-SHA2", "manual"],
["", "SHA3", true, "callAsFunction(_:)", "", "", "Argument[0]", "weak-password-hash-input-SHA3", "manual"],
["", "SHA3", true, "calculate(for:)", "", "", "Argument[for:]", "weak-password-hash-input-SHA3", "manual"],
["", "SHA3", true, "process(block:currentHash:)", "", "", "Argument[block:]", "weak-password-hash-input-SHA3", "manual"],
["", "SHA3", true, "update(withBytes:isLast?:)", "", "", "Argument[withBytes:]", "weak-password-hash-input-SHA3", "manual"],
["", "SHA512.Type", true, "hash(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA512", "manual"],
["", "SHA512.Type", true, "hash(data:)", "", "", "Argument[data:]", "weak-password-hash-input-SHA512", "manual"],
["", "SHA512", true, "update(bufferPointer:)", "", "", "Argument[bufferPointer:]", "weak-password-hash-input-SHA512", "manual"],
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
Hash functions that are not sufficiently computationally hard can leave data vulnerable. You should not use such functions for password hashing.
</p>

<p>
A strong cryptographic hash function should be resistant to:
</p>
<ul>
<li>
<strong>Pre-image attacks</strong>. If you know a hash value <code>h(x)</code>,
you should not be able to easily find the input <code>x</code>.
</li>
<li>
<strong>Collision attacks</strong>. If you know a hash value <code>h(x)</code>,
you should not be able to easily find a different input
<code>y</code>
with the same hash value <code>h(x) = h(y)</code>.
</li>
<li>
<strong>Brute force</strong>. If you know a hash value <code>h(x)</code>,
you should not be able to find an input <code>y</code> that computes to that hash value
using brute force attacks without significant computational effort.
</li>
</ul>

<p>
All of MD5, SHA-1, SHA-2 and SHA-3 are weak against offline brute forcing, since they are not sufficiently computationally hard. This includes SHA-224, SHA-256, SHA-384 and SHA-512, which are in the SHA-2 family.
</p>

<p>
Password hashing algorithms should be slow and/or memory intensive to compute, to make brute force attacks more difficult.
</p>

</overview>
<recommendation>

<p>
For password storage, you should use a sufficiently computationally hard cryptographic hash function, such as one of the following:
</p>

<ul>
<li>
Argon2
</li>
<li>
scrypt
</li>
<li>
bcrypt
</li>
<li>
PBKDF2
</li>
</ul>

</recommendation>
<example>

<p>
The following examples show two versions of the same function. In both cases, a password is hashed using a cryptographic hashing algorithm.

In the first case, the SHA-512 hashing algorithm is used. It is vulnerable to offline brute force attacks:
</p>
<sample src="WeakPasswordHashingBad.swift"/>
<p>

Here is the same function using Argon2, which is suitable for password hashing:
</p>
<sample src="WeakPasswordHashingGood.swift"/>

</example>
<references>
<li>
OWASP:
<a href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html">Password Storage
Cheat Sheet
</a>
</li>
<li>
GitHub: <a href="https://github.com/krzyzanowskim/CryptoSwift/blob/main/README.md#password-based-key-derivation-function">CryptoSwift README - Password-Based Key Derivation Function</a>
</li>
<li>
libsodium: <a href="https://doc.libsodium.org/bindings_for_other_languages#bindings-for-programming-languages">libsodium bindings for other languages</a>
</li>
<li>
GitHub: <a href="https://github.com/tmthecoder/Argon2Swift">Argon2Swift</a>
</li>
</references>

</qhelp>
79 changes: 79 additions & 0 deletions unified/ql/src/queries/security/CWE-328/WeakPasswordHashing.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
/**
* @name Use of an inappropriate cryptographic hashing algorithm on passwords
* @description Using inappropriate cryptographic hashing algorithms with passwords can compromise security.
* @kind path-problem
* @problem.severity warning
* @security-severity 7.5
* @precision high
* @id unified/swift/weak-password-hashing
* @tags security
* external/cwe/cwe-327
* external/cwe/cwe-328
* external/cwe/cwe-916
*/

import unified
import codeql.unified.security.SensitiveData

/**
* Holds if `node` is a sink for weak password hashing using `algorithm`.
*/
private predicate isWeakPasswordHashingSink(DataFlow::Node node, string algorithm) {
exists(string kind | Models::isSink(node, kind) |
// match the following sinks:
// - `weak-hash-input-<algorithm>` (sinks that apply to both this query and `unified/swift/weak-sensitive-data-hashing`)
// - `weak-password-hash-input-<algorithm>` (sinks that apply to just this query)
algorithm = kind.regexpCapture("weak-(?:password-)?hash-input-(.+)", 1)
)
}

/**
* A taint tracking configuration from password expressions to inappropriate
* hashing sinks.
*/
module WeakPasswordHashingConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node node) {
node.(SensitiveData).getClassification() = SensitiveDataClassification::password()
}

predicate isSink(DataFlow::Node node) { isWeakPasswordHashingSink(node, _) }

predicate isBarrier(DataFlow::Node node) {
// A barrier for weak password hashing, when it occurs inside of
// certain cryptographic algorithms as part of their design.
exists(ClassLikeDeclaration cls, string name |
node.asExpr().getParent+() = cls and
(
name = cls.resolve().getName()
or
name = cls.getExtensionTarget().(Identifier).getValue()
) and
name = ["HMAC", "PBKDF1", "PBKDF2"]
)
}

predicate isBarrierIn(DataFlow::Node node) {
// make sources barriers so that we only report the closest instance
isSource(node)
}

predicate isBarrierOut(DataFlow::Node node) {
// make sinks barriers so that we only report the closest instance
isSink(node)
}

predicate observeDiffInformedIncrementalMode() { any() }
}

module WeakPasswordHashingFlow = TaintTracking::Global<WeakPasswordHashingConfig>;

import WeakPasswordHashingFlow::PathGraph

from
WeakPasswordHashingFlow::PathNode source, WeakPasswordHashingFlow::PathNode sink, string algorithm
where
WeakPasswordHashingFlow::flowPath(source, sink) and
isWeakPasswordHashingSink(sink.getNode(), algorithm)
select sink.getNode(), source, sink,
"Insecure hashing algorithm (" + algorithm + ") depends on $@.", source.getNode(),
"password (" + source.getNode().toString() + ")"
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
let passwordData = Data(passwordString.utf8)
let passwordHash = Crypto.SHA512.hash(data: passwordData) // BAD: SHA-512 is not suitable for password hashing.

// ...

if Crypto.SHA512.hash(data: Data(passwordString.utf8)) == passwordHash {
// ...
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Argon2Swift

let salt = Salt.newSalt()
let result = try! Argon2Swift.hashPasswordString(password: passwordString, salt: salt) // GOOD: Argon2 is suitable for password hashing.
let passwordHash = result.encodedString()

// ...

if try! Argon2Swift.verifyHashString(password: passwordString, hash: passwordHash) {
// ...
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
Using a broken or weak cryptographic hash function can leave data
vulnerable, and should not be used in security related code.
</p>

<p>
A strong cryptographic hash function should be resistant to:
</p>
<ul>
<li>
<b>Pre-image attacks</b>. If you know a hash value <code>h(x)</code>,
you should not be able to easily find the input <code>x</code>.
</li>
<li>
<b>Collision attacks</b>. If you know a hash value <code>h(x)</code>,
you should not be able to easily find a different input
<code>y</code>
with the same hash value <code>h(x) = h(y)</code>.
</li>
</ul>

<p>
As an example, both MD5 and SHA-1 are known to be vulnerable to collision attacks.
</p>

<p>
Since it's OK to use a weak cryptographic hash function in a non-security
context, this query only alerts when these are used to hash sensitive
data (such as usernames, identifying information and private data).
</p>

</overview>
<recommendation>

<p>
Ensure that you use a strong, modern cryptographic hash function, such as:
</p>

<ul>
<li>
Argon2, scrypt, bcrypt, or PBKDF2 for passwords and other data with limited input space where
a dictionary-like attack is feasible.
</li>
<li>
SHA-2, or SHA-3 in other cases.
</li>
</ul>

<p>
Note that special purpose algorithms, which are used to ensure that a message comes from a particular sender, exist for message authentication. These algorithms should be used when appropriate, as they address common vulnerabilities of simple hashing schemes in this context.
</p>

</recommendation>
<example>

<p>
The following examples show a function for fetching data from a
URL and computing a hash of the data, perhaps to check the data has
not been tampered with.
</p>

<p>
In the first case the MD5 hashing algorithm is used that is known to be vulnerable to collision attacks.
</p>
<sample src="WeakSensitiveDataHashingBad.swift"/>

<p>
Here is the same function using SHA-512, which is a strong cryptographic hashing function.
</p>
<sample src="WeakSensitiveDataHashingGood.swift"/>

</example>
<references>
<li>
OWASP:
<a href="https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html">Password Storage
Cheat Sheet
</a>
and
<a href="https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Security_Cheat_Sheet.html#use-strong-cryptographic-hashing-algorithms">
Transport Layer Security Cheat Sheet
</a>
</li>
</references>

</qhelp>
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* @name Use of a broken or weak cryptographic hashing algorithm on sensitive data
* @description Using broken or weak cryptographic hashing algorithms can compromise security.
* @kind path-problem
* @problem.severity warning
* @security-severity 7.5
* @precision high
* @id unified/swift/weak-sensitive-data-hashing
* @tags security
* external/cwe/cwe-327
* external/cwe/cwe-328
*/

import unified
import codeql.unified.security.SensitiveData

/**
* Holds if `node` is a sink for weak sensitive data hashing using `algorithm`.
*/
private predicate isWeakSensitiveDataHashingSink(DataFlow::Node node, string algorithm) {
exists(string kind | Models::isSink(node, kind) |
algorithm = kind.regexpCapture("weak-hash-input-(.+)", 1)
)
}

/**
* A taint tracking configuration from sensitive expressions to broken or weak
* hashing sinks.
*/
module WeakSensitiveDataHashingConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node node) {
node instanceof SensitiveData and
not node.(SensitiveData).getClassification() = SensitiveDataClassification::password() // responsibility of the weak password hashing query
}

predicate isSink(DataFlow::Node node) { isWeakSensitiveDataHashingSink(node, _) }

predicate isBarrierIn(DataFlow::Node node) {
// make sources barriers so that we only report the closest instance
isSource(node)
}

predicate isBarrierOut(DataFlow::Node node) {
// make sinks barriers so that we only report the closest instance
isSink(node)
}

predicate observeDiffInformedIncrementalMode() { any() }
}

module WeakSensitiveDataHashingFlow = TaintTracking::Global<WeakSensitiveDataHashingConfig>;

import WeakSensitiveDataHashingFlow::PathGraph

from
WeakSensitiveDataHashingFlow::PathNode source, WeakSensitiveDataHashingFlow::PathNode sink,
string algorithm, SensitiveData sensitiveData
where
WeakSensitiveDataHashingFlow::flowPath(source, sink) and
isWeakSensitiveDataHashingSink(sink.getNode(), algorithm) and
sensitiveData = source.getNode()
select sink.getNode(), source, sink,
"Insecure hashing algorithm (" + algorithm + ") depends on $@.", source.getNode(),
"sensitive data (" + sensitiveData.getClassification() + " " + sensitiveData.toString() + ")"
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
func getContentsAndHash(url: URL) -> (Data, String)? {
guard let data = try? Data(contentsOf: url) else {
return nil
}

let digest = Insecure.MD5.hash(data: data) // BAD: MD5 is not suitable for hashing sensitive data.
let hash = digest.map { String(format: "%02hhx", $0) }.joined()

return (data, hash)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
func getContentsAndHash(url: URL) -> (Data, String)? {
guard let data = try? Data(contentsOf: url) else {
return nil
}

let digest = SHA512.hash(data: data) // GOOD: SHA-512 is suitable for hashing sensitive data.
let hash = digest.map { String(format: "%02hhx", $0) }.joined()

return (data, hash)
}
Loading
Loading