Modern Apps git

← xtool.git

Improve memory safety

Commit
5931a33682f5c6f9670255317ff3071bfa7e5ee4
Author
kabiroberai <[email protected]>
When
2020-08-15 20:14 UTC (6 years ago)
Parents
d69da95

Diff

Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift
diff --git a/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift b/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swiftindex 036e3df..6d22ba5 100644--- a/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift+++ b/Supersign/GrandSlam/Anisette/DeviceInfo+Fetching.swift@@ -14,11 +14,12 @@ extension DeviceInfo {     private static func fetchDeviceID() -> String? {         var waitTime = timespec(tv_sec: 0, tv_nsec: 0) // wait indefinitely         let bytes = [UInt8](unsafeUninitializedCapacity: MemoryLayout<uuid_t>.size) { buf, count in+            // force unwrapping is safe because uuid_t has a non-zero size             count = (gethostuuid(buf.baseAddress!, &waitTime) == 0) ? buf.count : 0         }         guard !bytes.isEmpty else { return nil }-        return bytes.withUnsafeBufferPointer { buf in-            UUID(uuid: UnsafeRawPointer(buf.baseAddress!).load(as: uuid_t.self)).uuidString+        return bytes.withUnsafeBufferPointer {+            UUID(uuid: UnsafeRawBufferPointer($0).load(as: uuid_t.self)).uuidString         }     } 
Supersign/GrandSlam/Crypto/AppTokens.swift
diff --git a/Supersign/GrandSlam/Crypto/AppTokens.swift b/Supersign/GrandSlam/Crypto/AppTokens.swiftindex 74fa7e9..25d02ec 100644--- a/Supersign/GrandSlam/Crypto/AppTokens.swift+++ b/Supersign/GrandSlam/Crypto/AppTokens.swift@@ -15,12 +15,13 @@ enum AppTokens {             let ptrArray = apps.map { strdup($0)! }             defer { ptrArray.forEach { free($0) } }             let immutablePtrArray = ptrArray.map { UnsafePointer($0) }-            return immutablePtrArray.withUnsafeBufferPointer { ptrBuf in-                var length = 0-                let bytes = app_tokens_create_checksum(-                    skBuf.baseAddress!, skBuf.count, adsid, ptrBuf.baseAddress!, ptrBuf.count, &length+            return Data {+                app_tokens_create_checksum(+                    skBuf.baseAddress, skBuf.count,+                    adsid,+                    immutablePtrArray, immutablePtrArray.count,+                    &$0                 )-                return Data(bytesNoCopy: bytes, count: length, deallocator: .free)             }         }     }@@ -28,12 +29,15 @@ enum AppTokens {     static func decrypt(gcm: Data, withSK sk: Data) -> Data? {         gcm.withUnsafeBytes { gcmBuf in             sk.withUnsafeBytes { skBuf in-                var length = 0-                return app_tokens_decrypt_gcm(-                    gcmBuf.baseAddress!, gcmBuf.count,-                    skBuf.baseAddress!, skBuf.count,-                    &length-                ).map { Data(bytesNoCopy: $0, count: length, deallocator: .free) }+                // the data must have a header so it shouldn't be empty+                guard let gcmBase = gcmBuf.baseAddress,+                    // the session key must have a length equal to that required by+                    // the cipher. It should be non-empty.+                    let skBase = skBuf.baseAddress+                    else { return nil }+                return Data {+                    app_tokens_decrypt_gcm(gcmBase, gcmBuf.count, skBase, skBuf.count, &$0)+                }             }         }     }
Supersign/GrandSlam/Crypto/SRPClient.swift
diff --git a/Supersign/GrandSlam/Crypto/SRPClient.swift b/Supersign/GrandSlam/Crypto/SRPClient.swiftindex 34c628b..452c9f3 100644--- a/Supersign/GrandSlam/Crypto/SRPClient.swift+++ b/Supersign/GrandSlam/Crypto/SRPClient.swift@@ -20,22 +20,20 @@ class SRPClient {     }      func add(data: Data) {-        data.withUnsafeBytes { srp_client_add_data(raw, $0.baseAddress!, $0.count) }+        data.withUnsafeBytes { srp_client_add_data(raw, $0.baseAddress, $0.count) }     }      func decrypt(cbc: Data) -> Data? {         cbc.withUnsafeBytes { buf in-            var length = 0-            return srp_client_decrypt_cbc(raw, buf.baseAddress!, buf.count, &length)-                .map { Data(bytesNoCopy: $0, count: length, deallocator: .free) }+            guard let base = buf.baseAddress else { return nil }+            return Data { srp_client_decrypt_cbc(raw, base, buf.count, &$0) }         }     }      // MARK: - SRP      func publicKey() -> Data {-        var length = 0-        return Data(bytesNoCopy: srp_client_copy_public_key(raw, &length), count: length, deallocator: .free)+        Data { srp_client_copy_public_key(raw, &$0) }     }      func processChallenge(@@ -48,27 +46,34 @@ class SRPClient {     ) -> Data? {         salt.withUnsafeBytes { saltBuf in             key.withUnsafeBytes { keyBuf in-                var length = 0-                return srp_client_process_challenge(-                    raw,-                    username, password,-                    saltBuf.baseAddress!, saltBuf.count,-                    .init(iterations),-                    keyBuf.baseAddress!,-                    keyBuf.count,-                    isS2K,-                    &length-                ).map { Data(bytesNoCopy: $0, count: length, deallocator: .free) }+                Data {+                    srp_client_process_challenge(+                        raw,+                        username, password,+                        saltBuf.baseAddress, saltBuf.count,+                        .init(iterations),+                        keyBuf.baseAddress, keyBuf.count,+                        isS2K,+                        &$0+                    )+                }             }         }     }      func verify(hamk: Data) -> Bool {-        hamk.withUnsafeBytes { srp_client_verify_session_HAMK(raw, $0.baseAddress!, $0.count) }+        hamk.withUnsafeBytes {+            // a hash has to be non-zero sized, so a nil baseAddress is invalid+            guard let base = $0.baseAddress else { return false }+            return srp_client_verify_session_HAMK(raw, base, $0.count)+        }     }      func verify(negProto: Data) -> Bool {-        negProto.withUnsafeBytes { srp_client_verify_neg_proto(raw, $0.baseAddress!, $0.count) }+        negProto.withUnsafeBytes {+            guard let base = $0.baseAddress else { return false }+            return srp_client_verify_neg_proto(raw, base, $0.count)+        }     }  }
Supersign/Model/Certificate/Certificate.swift
diff --git a/Supersign/Model/Certificate/Certificate.swift b/Supersign/Model/Certificate/Certificate.swiftindex da11f00..65ae309 100644--- a/Supersign/Model/Certificate/Certificate.swift+++ b/Supersign/Model/Certificate/Certificate.swift@@ -17,9 +17,9 @@ public class Certificate: Decodable {     let raw: certificate_t      private static func certificate(from data: Data) -> certificate_t? {-        data.withUnsafeBytes { bytes in-            let bound = bytes.bindMemory(to: Int8.self)-            return certificate_create_from_data(bound.baseAddress, bound.count)+        data.withUnsafeBytes {+            guard let base = $0.baseAddress else { return nil }+            return certificate_create_from_data(base, $0.count)         }     } @@ -31,9 +31,8 @@ public class Certificate: Decodable {     }      public init(contentsOf url: URL) throws {-        guard let certificate = url.withUnsafeFileSystemRepresentation(certificate_create_from_path) else {-            throw Error.invalidCertificate-        }+        guard let certificate = url.withUnsafeFileSystemRepresentation({ $0.flatMap(certificate_create_from_path) })+            else { throw Error.invalidCertificate }         self.raw = certificate     } @@ -58,17 +57,15 @@ public class Certificate: Decodable {     }      public func serialNumber() throws -> String {-        guard let serial = certificate_copy_serial_number(raw) else {-            throw Error.invalidCertificate-        }-        defer { free(serial) }-        return String(cString: serial)+        guard let serial = certificate_copy_serial_number(raw),+            let string = String(bytesNoCopy: serial, length: strlen(serial), encoding: .utf8, freeWhenDone: true)+            else { throw Error.invalidCertificate }+        return string     }      public func data() throws -> Data {-        guard let data = Data(cFunc: { certificate_generate_data(raw, $0) })-            else { throw Error.invalidCertificate }-        return data+        try Data { certificate_generate_data(raw, &$0) }+            .orThrow(Error.invalidCertificate)     }  }
Supersign/Model/Keypair/Keypair.swift
diff --git a/Supersign/Model/Keypair/Keypair.swift b/Supersign/Model/Keypair/Keypair.swiftindex fe2bbfb..977de3e 100644--- a/Supersign/Model/Keypair/Keypair.swift+++ b/Supersign/Model/Keypair/Keypair.swift@@ -52,27 +52,12 @@ public class Keypair {         keypair_free(raw)     } -    private func callKeypairDataFunc(-        fn: (keypair_t?, UnsafeMutablePointer<Int>?) -> UnsafeMutablePointer<Int8>?-    ) throws -> Data {-        var len = 0-        guard let bytes = fn(raw, &len) else {-            throw Error.invalidKeypair-        }-        defer { free(bytes) }-        return Data(bytes: UnsafeRawPointer(bytes), count: len)-    }-     public func privateKey() throws -> PrivateKey {-        guard let data = Data(cFunc: { keypair_copy_private_key(raw, $0) })-            else { throw Error.invalidKeypair }-        return PrivateKey(data: data)+        try PrivateKey(data: Data { keypair_copy_private_key(raw, &$0) }.orThrow(Error.invalidKeypair))     }      public func generateCSR() throws -> CSR {-        guard let data = Data(cFunc: { keypair_generate_csr(raw, $0) })-            else { throw Error.invalidKeypair }-        return CSR(data: data)+        try CSR(data: Data { keypair_generate_csr(raw, &$0) }.orThrow(Error.invalidKeypair))     }  }
Supersign/Model/Mobileprovision/Mobileprovision.swift
diff --git a/Supersign/Model/Mobileprovision/Mobileprovision.swift b/Supersign/Model/Mobileprovision/Mobileprovision.swiftindex dcf1932..e42b2b0 100644--- a/Supersign/Model/Mobileprovision/Mobileprovision.swift+++ b/Supersign/Model/Mobileprovision/Mobileprovision.swift@@ -39,9 +39,9 @@ public class Mobileprovision: Decodable {     let raw: mobileprovision_t      private static func mobileprovision(from data: Data) -> mobileprovision_t? {-        data.withUnsafeBytes { bytes in-            let bound = bytes.bindMemory(to: Int8.self)-            return mobileprovision_create_from_data(bound.baseAddress, bound.count)+        data.withUnsafeBytes {+            guard let base = $0.baseAddress else { return nil }+            return mobileprovision_create_from_data(base, $0.count)         }     } @@ -53,9 +53,8 @@ public class Mobileprovision: Decodable {     }      public init(contentsOf url: URL) throws {-        guard let profile = url.withUnsafeFileSystemRepresentation(mobileprovision_create_from_path) else {-            throw Error.invalidProfile-        }+        guard let profile = url.withUnsafeFileSystemRepresentation({ $0.flatMap(mobileprovision_create_from_path) })+            else { throw Error.invalidProfile }         self.raw = profile     } @@ -77,14 +76,12 @@ public class Mobileprovision: Decodable {         guard let ptr = mobileprovision_get_digest(raw, &len), len > 0 else {             throw Error.invalidProfile         }-        let data = Data(bytes: UnsafeRawPointer(ptr), count: len)+        let data = Data(bytes: ptr, count: len)         return try PropertyListDecoder().decode(Digest.self, from: data)     }      public func data() throws -> Data {-        guard let data = Data(cFunc: { mobileprovision_get_data(raw, $0) })-            else { throw Error.invalidProfile }-        return data+        try Data { mobileprovision_get_data(raw, &$0) }.orThrow(Error.invalidProfile)     }  }
Supersign/Model/Mobileprovision/mobileprovision.c
diff --git a/Supersign/Model/Mobileprovision/mobileprovision.c b/Supersign/Model/Mobileprovision/mobileprovision.cindex ba26830..14b3df3 100644--- a/Supersign/Model/Mobileprovision/mobileprovision.c+++ b/Supersign/Model/Mobileprovision/mobileprovision.c@@ -23,7 +23,7 @@ static mobileprovision_t mobileprovision_create(PKCS7 *raw) {     return profile; } -mobileprovision_t mobileprovision_create_from_data(const char *data, size_t len) {+mobileprovision_t mobileprovision_create_from_data(const void *data, size_t len) {     PKCS7 *raw = NULL;     d2i_PKCS7(&raw, (const unsigned char **)&data, len);     if (!raw) return NULL;@@ -48,15 +48,18 @@ void mobileprovision_free(mobileprovision_t profile) {     free(profile); } -char *mobileprovision_get_data(mobileprovision_t profile, size_t *len) {+void *mobileprovision_get_data(mobileprovision_t profile, size_t *len) {     unsigned char *data = NULL;     size_t data_len = i2d_PKCS7(profile->raw, &data);     if (data_len < 0) return NULL;     *len = data_len;-    return (char *)data;+    void *ret = malloc(data_len);+    memcpy(ret, data, data_len);+    OPENSSL_free(data);+    return ret; } -const char *mobileprovision_get_digest(mobileprovision_t profile, size_t *len) {+const void *mobileprovision_get_digest(mobileprovision_t profile, size_t *len) {     ASN1_OCTET_STRING *str = profile->raw->d.sign->contents->d.data;     if (len) *len = str->length;     return (char *)str->data;
Supersign/Model/Mobileprovision/mobileprovision.h
diff --git a/Supersign/Model/Mobileprovision/mobileprovision.h b/Supersign/Model/Mobileprovision/mobileprovision.hindex 1da31a6..4a60ce8 100644--- a/Supersign/Model/Mobileprovision/mobileprovision.h+++ b/Supersign/Model/Mobileprovision/mobileprovision.h@@ -11,23 +11,27 @@  #include <stdio.h> +#pragma clang assume_nonnull begin+ typedef struct mobileprovision *mobileprovision_t;  // MARK: - Lifecycle  /// create a profile from the given data-mobileprovision_t mobileprovision_create_from_data(const char *data, size_t len);+_Nullable mobileprovision_t mobileprovision_create_from_data(const void *data, size_t len);  /// create a profile from the given file path-mobileprovision_t mobileprovision_create_from_path(const char *path);+_Nullable mobileprovision_t mobileprovision_create_from_path(const char *path);  /// free `profile` void mobileprovision_free(mobileprovision_t profile);  // MARK: - Operations -char *mobileprovision_get_data(mobileprovision_t profile, size_t *len);+void * _Nullable mobileprovision_get_data(mobileprovision_t profile, size_t *len);++const void * _Nullable mobileprovision_get_digest(mobileprovision_t profile, size_t *len); -const char *mobileprovision_get_digest(mobileprovision_t profile, size_t *len);+#pragma clang assume_nonnull end  #endif /* mobileprovision_h */
Supersign/SignerImpl/SignerImpl.swift
diff --git a/Supersign/SignerImpl/SignerImpl.swift b/Supersign/SignerImpl/SignerImpl.swiftindex a2c0db4..ecb7f88 100644--- a/Supersign/SignerImpl/SignerImpl.swift+++ b/Supersign/SignerImpl/SignerImpl.swift@@ -74,35 +74,29 @@ public struct SignerImpl {             try url.withUnsafeFileSystemRepresentation { bundlePath in                 guard let bundlePath = bundlePath else { throw Error.badFilePath }                 return try encoder.encode(ents).withUnsafeBytes { bytes in-                    let bound = bytes.bindMemory(to: Int8.self)-                    return entitlements_data_t(-                        bundle_path: bundlePath, data: bound.baseAddress!, len: bound.count-                    )+                    // an XML plist should always be non-empty so force unwrapping baseAddress is safe+                    entitlements_data_t(bundle_path: bundlePath, data: bytes.baseAddress!, len: bytes.count)                 }             }         }-        try entsArray.withUnsafeBufferPointer { ents in-            try certificate.data().withUnsafeBytes { certBytes in-                try privateKey.data.withUnsafeBytes { privBytes in-                    let certBound = certBytes.bindMemory(to: Int8.self)-                    let privBound = privBytes.bindMemory(to: Int8.self)--                    var exception: UnsafeMutablePointer<Int8>?-                    defer { exception.map { free($0) } }--                    guard sign(-                        app.path,-                        certBound.baseAddress!,-                        certBound.count,-                        privBound.baseAddress!,-                        privBound.count,-                        ents.baseAddress!,-                        ents.count,-                        progress,-                        &exception-                    ) == 0 else {-                        throw Error.signer(exception.map { String(cString: $0) })-                    }+        try certificate.data().withUnsafeBytes { cert in+            try privateKey.data.withUnsafeBytes { priv in+                var exception: UnsafeMutablePointer<Int8>?+                defer { exception.map { free($0) } }++                guard let certBase = cert.baseAddress,+                    let privBase = priv.baseAddress+                    else { throw Error.signer(nil) }++                guard sign(+                    app.path,+                    certBase, cert.count,+                    privBase, priv.count,+                    entsArray, entsArray.count,+                    progress,+                    &exception+                ) == 0 else {+                    throw Error.signer(exception.map { String(cString: $0) })                 }             }         }@@ -134,14 +128,11 @@ public struct SignerImpl {      public func analyze(executable: URL) throws -> Data {         try executable.withUnsafeFileSystemRepresentation { (path: UnsafePointer<Int8>?) -> Data in+            guard let path = path else { throw Error.badFilePath }             var exception: UnsafeMutablePointer<Int8>?             defer { exception.map { free($0) } }-            var len = 0-            guard let out = analyze(path!, &len, &exception) else {-                throw Error.signer(exception.map { String(cString: $0) })-            }-            defer { free(out) }-            return Data(bytes: out, count: len)+            return try Data { analyze(path, &$0, &exception) }+                .orThrow(Error.signer(exception.map { String(cString: $0) }))         }     } 
Supersign/Utilities/CHelpers.swift
diff --git a/Supersign/Utilities/CHelpers.swift b/Supersign/Utilities/CHelpers.swiftindex ff34e1c..e6ac0f6 100644--- a/Supersign/Utilities/CHelpers.swift+++ b/Supersign/Utilities/CHelpers.swift@@ -9,10 +9,15 @@ import Foundation  extension Data {-    init?(cFunc: (UnsafeMutablePointer<Int>?) -> UnsafeMutablePointer<Int8>?) {-        var len = 0-        guard let bytes = cFunc(&len) else { return nil }-        defer { free(bytes) }-        self.init(bytes: UnsafeRawPointer(bytes), count: len)+    init?(deallocator: Deallocator = .free, acceptor: (inout Int) -> UnsafeMutableRawPointer?) {+        var count = 0+        guard let bytes = acceptor(&count) else { return nil }+        self.init(bytesNoCopy: bytes, count: count, deallocator: deallocator)+    }++    init(deallocator: Deallocator = .free, acceptor: (inout Int) -> UnsafeMutableRawPointer) {+        var count = 0+        let bytes = acceptor(&count)+        self.init(bytesNoCopy: bytes, count: count, deallocator: deallocator)     } }