50+ ways to secure iOS applications

Let’s analysis/investigate different aspects for improving security of iOS application :-

  1. SSL Pinning/MITM
  2. HTTPS
  3. Secure local data
  4. API Chaining
  5. Generic response/status code
  6. Prevent screenshot/screen recording
  7. Hide password while typing
  8. Integrating Biometric
  9. Auto logout
  10. Access control — Private/Fileprivate/Final/Open/Internal
  11. Avoid using third party library
  12. Logs decoding
  13. OTP based login
  14. 3 step verification
  15. Encryption public keys
  16. Place third parties keys in secure place
  17. Jailbroken detection
  18. Human check / warning / robot
  19. Secure server logs
  20. Encrypt/Decrypt critical information in API’s
  21. Encrypt file before saving to disk / Core data
  22. Obfuscation code
  23. CI/CD security
  24. SSO security
  25. Security testing
  26. Push notification payload
  27. 30 sec Timer on payment / Critical page
  28. Disallow same API call multiple time within 0.0001 sec
  29. Block user if there is any suspicious activity.
  30. GET/PUT/POST request type
  31. Use AI to track user
  32. Memory leak
  33. Hide account number in application
  34. 3 step verification while setting/updating password
  35. Renew password frequently
  36. Secure password — 10 digits/special characters
  37. Do not share IPA/Build to unknown team/software
  38. Do not store critical data in shared place
  39. Keychain storage
  40. Update software
  41. Don’t miss update on security patch
  42. Reduce intercommunication between other services
  43. Disable sharing option for password/Card number/info
  44. App crash
  45. Stop user from login if there is any server deployment
  46. Auto-disable user
  47. Frequent app release
  48. Use inbuilt services/API
  49. Secure prod DB
  50. Encrypted data / secure login in prod DB
  51. Private network while testing
  52. Don't share keys via mail, slack, message
  53. API name should be random
  54. Prevent Cross site scripting
  55. Prevent SQL injection
  56. Do not send critical logs to third party Analytics
  57. Hide critical screen while moving to background/Inactive state
  58. Payment Security
  59. Enable location
  60. Charles proxy
  61. Disallow Copy/Paste

Let’s visit above points one by one to analysis impact on security :-

1. SSL Pinning — MITM

SSL Secure Sockets Layer (SSL) is a standard security technology for establishing an encrypted link between a server and a client .

MITM is a cyberattack where the attacker secretly relays and possibly alters the communications between two parties who believe that they are directly communicating with each other, as the attacker has inserted themselves between the two parties

  • Perpetrator intercepts/capture data from User. That’s why it is called Man in the middle attack.
  • You can use Charles Debugging tool to intercepts data. You can easily see raw data.

SSL Pinning

  • SSL certificate pinning is a technique designed to prevent dangerous and complex security attacks. This security measure pins the identity of trustworthy certificates on mobile apps and blocks unknown documents from the suspicious servers.
  • SSL Pinning which is a protocol for creating an encrypted connection between client and server
  • SSL encrypts the data being transmitted so that a third party or any “Man-in-the-Middle” cannot “listen” on the transmission and view the databeing transmitted. Only the client and the secure server are able to recognize and understand the data. This means that anyone who tries to intercept this data will only see a garbled mix of characters that’s nearly impossible to decrypt.
  • This initiates an authentication process called a handshake between two communicating devices to ensure that both devices are really who they claim to be. SSL also digitally signs data in order to provide data integrity, verifying that the data is not tampered with before reaching its intended recipient.

**

It’s all about trust. “How end user will trust server” and “How server trust end user”. We are just solving Trust issue in SSL Pinning

**

Certificate:- It’s like your identity. Like you have DNA Identity which cannot be changed. Similarly certificate is a file that consist Subject(Owner name), Serial number(Unique ID),Issuer(name),Valid From,Valid To, Public key(used by end user),Algorithm id, digital signature,timestamp

SSL Handshake:- Client talk to server and request identify itself. Server send identify certificate which include public key. Client check if the certificate is valid. If certificate is valid then client creates session key, encrypt with public key, then sends back to server. Server decrypt encrypted by private key and send acknowledgement to client. An then session starts.

How SSL Pinning works:- - SSL Certificate help to create trust to establish a secure connection. - SSL Certificate have Public & Private key. - These keys makes connection secure. As these keys will be used by respective parties. - Client consists Public key - Client save certificate with app bundle

How we can achieve SSL Pinning ?

1 Certificate Pinning

2 Public key pinning

3 Hash pinning

  1. Certificate Pinning:-

  • Easiest way to achieve, Store certificate in application and when the certificate expires, application need to be updated.
  • At runtime- We excess server certificate in the callback. Within the callback, we compared the retrieve certificate with embedded certificate.
  • Downside of certificate pinning , whenever server change certificate, expired, then application need to be updated

2. Public Key Pinning:

  • Extract public key from certificate. In this approach, we generate keypair. Private key is in server and Public key in our app.
  • Retrieve public key of the certificate in the code as a string.
  • We check extracted public key with embedded copy of public key.
  • Public key pinning, we can avoid frequent application updates as the public key can remain same for longer periods.
  • Downsides:- Harder with keys, Key is static. Violet rotation policy.

3. Hash Pinning

Pin hash of public key of our server certificate, match with hash of the hash certificate public key received during network request.

How to implement SSL Pinning in iOS Swift ?

  1. URLSession

URLSession:didReceiveChallenge:completionHandler:delegate.
public override func urlSession(_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if let serverTrust = challenge.protectionSpace.serverTrust {
/* do pinning validation (your pinning logic should come here. As discussed above you can either
 * Pin the Certificate / * Pin the public keys) */

if pinningSucceeded {
      completionHandler(.useCredential, URLCredential(trust:serverTrust))
} else {
/* The entire request will be canceled; the credential parameter is ignored. */
     completionHandler(.cancelAuthenticationChallenge, nil)
}
return 
}
// Pinning failed
completionHandler(.cancelAuthenticationChallenge, nil)

}
        

2. Almofire


let pathToCert = Bundle.main.path(forResource: "certificatename", ofType: "cer")
let localCertificate: NSData = NSData(contentsOfFile: pathToCert!)!

let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
    certificates: [SecCertificateCreateWithData(nil, localCertificate)!],
    validateCertificateChain: true,
    validateHost: true
)

let serverTrustPolicies = [
    "server.com": serverTrustPolicy
]

let sessionManager = SessionManager(
    serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
)        

Challenges in Certificate:-

  • Maintain the old certificate for a time, until we make sure all users have downloaded new version already.
  • A special flow to download new certificate. But what if this flow is attacked

2. HTTPS vs HTTP protocol

  • HTTP requests and responses are sent in plaintext, which means that anyone can read them.
  • HTTP operates at the Application Layer, whereas HTTPS operates at Transport Layer.
  • HTTPS corrects this problem by using TLS/SSL encryption.
  • TTPS uses TLS (SSL) to encrypt normal HTTP requests and responses, and to digitally sign those requests and responses
  • When a client opens a connection with a server, the two devices use the public and private key to agree on new keys, called session keys, to encrypt further communications between them.
  • All HTTP requests and responses are then encrypted with these session keys, so that anyone who intercepts communications can only see a random string of characters, not the plaintext.
  • HTTPS protocol can’t stop stealing confidential information from the pages cached on the device.
  • HTTPS = HTTP + SSL


GET /hello.txt HTTP/1.1
User-Agent: curl/7.63.0 libcurl/7.63.0 OpenSSL/1.1.l zlib/1.2.11
Host: www.example.com
Accept-Language: en



//HTTPS
GET /hello.txt HTTP/1.1
User-Agent: curl/7.63.0 libcurl/7.63.0 OpenSSL/1.1.l zlib/1.2.11
Host: www.example.com
Accept-Language: en
The attacker sees something like:


t8Fw6T8UV81pQfyhDkhebbz7+oiwldr1j2gHBB3L3RFTRsQCpaSnSBZ78Vme+DpDVJPvZdZUZHpzbbcqmSW1+3        

Difference between SSL Pinning & HTTPS ?

SSL pinning means the client has the server’s certificate “built-in” and doesn’t use your computer’s trusted store. This means that even if your IT dept installs their own root cert, it won’t be used.

3. Secure local data

How to store data securely ?

  • Do not store any sensitive data on the device like Credit card info, password
  • Even if your Manager want to breach the security threat then you can use Keychain to securely store data.

4. API Chaining

  • You can use chaining API’s technique.



Screen 1 ---> API1
Screen 2 ----> API2
Screen 3 ----> API3
Screen 4 ---> Payment page (API4)


API2 request ----> response token1
API2 request(token1) ---> response token2
API3 request(token2)-----> respinse token3

Screen 4 API4 Payment request(token3) ---> Success(200)

        

-> If hacker hacks API4, then he cannot send request as API4 depends on API3API3 depends on AP2 response…..

  • It’s extra layer on security on API level.

5. Generic response/status code

request :
  username: 'shrawan' // '[email protected]'
  password : 'encryptedPassword' == 'qwevrreteqdsfsdfsdfs'

response1: {invalid username}
   
response2: {invalid password}


Generic response : {Invalid username or password}
        

  • If hacker has list of email id’s. He want to find out list of emailid which has account in “XYZ” bank.

By generic response from server, hackers cannot decode it.

5. Hide password will typing


passwordTextField.isSecureTextEntry= true

// To toggle Hide/Unhide
passwordTextField.isSecureTextEntry.toggle()        

6. Prevent screenshot/screen recording

 let isCaptured = UIScreen.main.isCaptured

@objc func preventScreenRecording() {
    print("isCaptured: \(isCaptured)")
    if isCaptured {
        blurScreen()
    }
    else {
        removeBlurScreen()
    }
}

if isCaptured {
     blurScreen()
}else {
    removeBlurScreen()
}
        

7. Auto logout

  • If user is not using application for ‘x’ seconds, then there should be auto logout features
  • If device is stolen then thief must enter credential to start ‘x’ services like payment

8. Access control Private/Fileprivate/Open

  • If you are building library then your code shouldn’t be exposed to third party which is not required, for that you can use access control which hide implementation.
  • Most secure is Private which hide implementation details from other scope.
  • Open/Public least restrictive

9. Avoid using third party library

  • You might not know, third party library is using script/tool , memory leak that can lead to data breach

10 . Logs decoding

  • Important information like IP address, credential, APIrequest body should not be dumped in the Analytics.
  • Analytics server might be exposed to hacker and use these data for their benefits.

11 . OTP based login

  • For 2 step verification , OTP should be entered after login credential. Server should send notification to respective device and email id .

12. Jail broken detection

  • If device is jailbroken then there is changes in device core path, different kernel level command can be access in the application, new suspicious path is created.
  • Check jailbroken after launching the application or the screen which required secure connection like payment screen.


extension UIDevice {
    var isSimulator: Bool {
        return TARGET_OS_SIMULATOR != 0
    }
    
    var isJailBroken: Bool {
        get {
            if UIDevice.current.isSimulator { return false }
            if JailBrokenHelper.hasCydiaInstalled() { return true }
            if JailBrokenHelper.isContainsSuspiciousApps() { return true }
            if JailBrokenHelper.isSuspiciousSystemPathsExists() { return true }
            return JailBrokenHelper.canEditSystemFiles()
        }
    }
}
    
private struct JailBrokenHelper {
    static func hasCydiaInstalled() -> Bool {
        return UIApplication.shared.canOpenURL(URL(string: "cydia://")!)
    }
    
    static func isContainsSuspiciousApps() -> Bool {
        for path in suspiciousAppsPathToCheck {
            if FileManager.default.fileExists(atPath: path) {
                return true
            }
        }
        return false
    }
    
    static func isSuspiciousSystemPathsExists() -> Bool {
        for path in suspiciousSystemPathsToCheck {
            if FileManager.default.fileExists(atPath: path) {
                return true
            }
        }
        return false
    }
    
    static func canEditSystemFiles() -> Bool {
        let jailBreakText = "Developer Insider"
        do {
            try jailBreakText.write(toFile: jailBreakText, atomically: true, encoding: .utf8)
            return true
        } catch {
            return false
        }
    }
    
    /**
     Add more paths here to check for jail break
     */
    static var suspiciousAppsPathToCheck: [String] {
        return ["/Applications/Cydia.app",
                "/Applications/blackra1n.app",
                "/Applications/FakeCarrier.app",
                "/Applications/Icy.app",
                "/Applications/IntelliScreen.app",
                "/Applications/MxTube.app",
                "/Applications/RockApp.app",
                "/Applications/SBSettings.app",
                "/Applications/WinterBoard.app"
        ]
    }
    
    static var suspiciousSystemPathsToCheck: [String] {
        return ["/Library/MobileSubstrate/DynamicLibraries/LiveClock.plist",
                "/Library/MobileSubstrate/DynamicLibraries/Veency.plist",
                "/private/var/lib/apt",
                "/private/var/lib/apt/",
                "/private/var/lib/cydia",
                "/private/var/mobile/Library/SBSettings/Themes",
                "/private/var/stash",
                "/private/var/tmp/cydia.log",
                "/System/Library/LaunchDaemons/com.ikey.bbot.plist",
                "/System/Library/LaunchDaemons/com.saurik.Cydia.Startup.plist",
                "/usr/bin/sshd",
                "/usr/libexec/sftp-server",
                "/usr/sbin/sshd",
                "/etc/apt",
                "/bin/bash",
                "/Library/MobileSubstrate/MobileSubstrate.dylib"
        ]
    }
}        

13. Human check / warning / robot

  • To check application is simulated by robot or any script is run then you can ask basic question in device which help to know whether end user is human or bot.

14. Secure server logs

  • Server logs should be kept under secure hand

15. Encrypt/Decrypt critical information in API’s

  • Use encription/decryption technique if there is any critical information.
  • Credit card info should be encrypted by server and decrpted by client.

There are 2 types of encryption algorithms

1.Symmetric Encryption 2.Asymmetric Encryption

  1. Symmetric Encryption :- Secret key encryption, performed by same key to encrypt and decrypt data

DES , RC2 Cipher,AES, Blowfish

AES- Mostly used

It was developed in 2000 by two Belgian cryptographers using the Rijndael block cipher. The 128,192 and 256-bit key lengths are used for this encryption algorithm, which is more reliable than the DES. Data is used in the algorithm by dividing it into (4x4) matrixes called states. As AES encryption is completed, separate loop allocations are made for 128-bit, 192-bit and 256-bit key lengths. According to the DES algorithm, it is easy to apply and requires less memory, which is one of its powerful features.

2. Asymmetric Encryption

In asymmetric encryption, also known as public key encryption, there are 2 different keys, public and private keys, unlike the symmetric algorithm. The decryption and encryption key are not the same as in the symmetric encryption key. The key to the cipher is the public key and the decryptor is the private key. Text encrypted with a public key can only be decrypted with a key belonging to that user. This makes it a lot more effective than symmetric encryption.

RSA, DSA, Diffie-Helllman

Ref

16. Encrypt file before saving to disk

17. Obfuscation code before deploying

  • Obfuscation is the deliberate act of creating source or machine code that is difficult for humans to understand.
  • Code Obfuscation is the process of modifying an executable so that it is no longer useful to a hacker but remains fully functional.
  • Prevent anti reversing code
  • If you do have important knowledge to protect then obfuscation might be worthwhile. Obfuscation has its downsides: you can’t debug your obfuscated app any more. Crash reports will be useless.
  • It is difficult to maintain KVC with it, or deal with dynamic method dispatch (opening up lots of opportunities for Release-only crashes).
  • Obfuscation code might be bad idea for iPhone/iPad app, as executable of an app is already encrypted by Apple, and the executable code segment of the app sandbox isn’t writeable

18. Push notification payload

  • Payload must not contain critical information.

20. Disallow same API call multiple time within 0.0001/‘x’ sec

  • Bot might use different algorithm to hit same API again and again. Server should check frequency of single/multiple api and send appropriate warning to end user.

21. Block user if there is any suspicious activity.

22. Use GET/PUT/POST request method carefully

Put update existing resource on the server and POST methods creates or adds a resource on the server.

POST, PUT, and PATCH presumably have payloads containing information that end user might consider proprietary, the best practice is to put all payloads for those methods in the request body, and not in the URL parms, because it's very likely that somewhere, somehow, URL text is being logged by your web server and you don't want customer data getting splattered as plain text into your log filesystem.

23. Use AI to track user

Track any suspicious activity based on AI in backend

要查看或添加评论,请登录

Anuj Kumar的更多文章

社区洞察

其他会员也浏览了