diff --git a/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashing.qhelp b/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashing.qhelp index d6806b2ddcc..cda0a74671c 100755 --- a/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashing.qhelp +++ b/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashing.qhelp @@ -51,18 +51,25 @@ +

+ 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. +

+

- The following examples show a function for checking whether the hash - of a certificate matches a known value -- to prevent tampering. + The following examples show a function for fetching data from a + URL along with a hash of the data, perhaps to check the data has + not been tampered with. +

+

In the first case the MD5 hashing algorithm is used that is known to be vulnerable to collision attacks.

-

+

Here is the same function using SHA-512, which is a strong cryptographic hashing function.

diff --git a/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashingBad.swift b/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashingBad.swift index a39dd47edce..5153c852342 100755 --- a/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashingBad.swift +++ b/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashingBad.swift @@ -1,5 +1,10 @@ -typealias Hasher = Crypto.Insecure.MD5 +func getContentsAndHash(url: URL) -> (Data, String)? { + guard let data = try? Data(contentsOf: url) else { + return nil + } -func checkCertificate(cert: Array[UInt8], hash: Array[UInt8]) -> Bool - return Hasher.hash(data: cert) == hash // BAD -} + let digest = Insecure.MD5.hash(data: data) + let hash = digest.map { String(format: "%02hhx", $0) }.joined() + + return (data, hash) +} \ No newline at end of file diff --git a/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashingGood.swift b/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashingGood.swift index 7345b2ea49c..4b9e0ec6af3 100755 --- a/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashingGood.swift +++ b/swift/ql/src/queries/Security/CWE-328/WeakSensitiveDataHashingGood.swift @@ -1,4 +1,10 @@ -typealias Hasher = Crypto.SHA512 +func getContentsAndHash(url: URL) -> (Data, String)? { + guard let data = try? Data(contentsOf: url) else { + return nil + } -func checkCertificate(cert: Array[UInt8], hash: Array[UInt8]) -> Bool - return Hasher.hash(data: cert) == hash // GOOD + let digest = SHA512.hash(data: data) + let hash = digest.map { String(format: "%02hhx", $0) }.joined() + + return (data, hash) +} \ No newline at end of file