Skip to content

Commit 39b45fa

Browse files
authored
Merge pull request github#13943 from geoffw0/weakhashexample
Swift: Update the weak sensitive data hashing examples and qhelp
2 parents f88428f + 125629a commit 39b45fa

File tree

3 files changed

+28
-10
lines changed

3 files changed

+28
-10
lines changed

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

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,18 +51,25 @@
5151
</li>
5252
</ul>
5353

54+
<p>
55+
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.
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.
65+
</p>
6066

67+
<p>
6168
In the first case the MD5 hashing algorithm is used that is known to be vulnerable to collision attacks.
6269
</p>
6370
<sample src="WeakSensitiveDataHashingBad.swift"/>
64-
<p>
6571

72+
<p>
6673
Here is the same function using SHA-512, which is a strong cryptographic hashing function.
6774
</p>
6875
<sample src="WeakSensitiveDataHashingGood.swift"/>
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)