Skip to content

Commit 94a5aa4

Browse files
committed
Swift: Edit the weak sensitive data hashing examples and qhelp to encourage use of HMAC and key derivation algorithms where appropriate.
1 parent 51a0528 commit 94a5aa4

File tree

3 files changed

+25
-9
lines changed

3 files changed

+25
-9
lines changed

swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashing.qhelp

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,12 +51,17 @@
5151
</li>
5252
</ul>
5353

54+
<p>
55+
Note that special purpose algorithms exist for message authentication (ensuring that a message comes from a particular sender). These algorithms should be used when appropriate, as they address common vulnerabilities of simple hashing schemes in this context.
56+
</p>
57+
5458
</recommendation>
5559
<example>
5660

5761
<p>
58-
The following examples show a function for checking whether the hash
59-
of a certificate matches a known value -- to prevent tampering.
62+
The following examples show a function for fetching data from a
63+
URL along with a hash of the data, perhaps to check the data has
64+
not been tampered with.
6065

6166
In the first case the MD5 hashing algorithm is used that is known to be vulnerable to collision attacks.
6267
</p>
Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1-
typealias Hasher = Crypto.Insecure.MD5
1+
func getContentsAndHash(url: URL) -> (Data, String)? {
2+
guard let data = try? Data(contentsOf: url) else {
3+
return nil
4+
}
25

3-
func checkCertificate(cert: Array[UInt8], hash: Array[UInt8]) -> Bool
4-
return Hasher.hash(data: cert) == hash // BAD
5-
}
6+
let digest = Insecure.MD5.hash(data: data)
7+
let hash = digest.map { String(format: "%02hhx", $0) }.joined()
8+
9+
return (data, hash)
10+
}
Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
typealias Hasher = Crypto.SHA512
1+
func getContentsAndHash(url: URL) -> (Data, String)? {
2+
guard let data = try? Data(contentsOf: url) else {
3+
return nil
4+
}
25

3-
func checkCertificate(cert: Array[UInt8], hash: Array[UInt8]) -> Bool
4-
return Hasher.hash(data: cert) == hash // GOOD
6+
let digest = SHA512.hash(data: data)
7+
let hash = digest.map { String(format: "%02hhx", $0) }.joined()
8+
9+
return (data, hash)
10+
}

0 commit comments

Comments
 (0)