Conf42 Mobile 2022 - Online

Secure coding in iOS

Video size:

Abstract

You are an iOS developer, but do you know how exactly your device protects the information of your users? Even more, do you know that you need to take control of certain behaviors or situations to make your code more secure? Are you using cryptography in your app? Where do you have to save the most sensitive information? Do you know that SwiftUI offers you a way to obfuscate data in less secure situations for your users?

In this talk, we will learn more about how iOS security works and how to improve your app making it more secure.

Summary

  • Darwin kernel is the kernel of all Apple operating systems. Was created in 2000 by Apple based on BSD and match with parts from OpenStep. This is the core of the iOS ten operating system. To understand the security of the iPhone, we are going to talk in a brief, secure history of the first iPhone.
  • The first iPhone model was far from the current ones. It was way less secure than the actual iPhones. When asked for apps, Apple's answer was web app. The iPhone was totally closed in system and kernel. For now they speak about to use web apps.
  • IPhone runs OS ten. That's the key. Why would we want to run such a sophisticated operating system on a mobile device? Well, because it's got everything we need. Apple think about third party software from the beginning.
  • First iPhone has a cryptographic coprocessor. It needs to validate the digital signature of the software. Only the password elements were encrypted, were encrypted. The other was open in plain text. If you make a brute force attack, you could extract the key.
  • Apple's Secure Enclave is a black box responsible for encrypting and decrypting any data. Only the chip finger is able to access the contents of the chip memory. Sand hackers and security investigators try to read this memory.
  • An entitlement allows the app to use certain functions or obtain specific permission to run some services or features on the system. For example, access to user information, extensions, services, or even iCloud is controlled by digital signed entitlements.
  • ATS ETS is a set of requirements for securing network communications. It force the exclusive use of your session and URL connection even for third party network APIs. All these things are mandatory standards since the end of 2016. We must know all these rules to ensure the security of our app.
  • Data encryption is free to use but with recommendations for Apple. For encryption you must use AesGCM or Chacha 20. NS file protection complete is the higher security code. IOS files are encrypted and inaccessible until the device is unlocked.
  • Swift is strictly typed, value oriented language. Data is self initialized to data types and isolates them by default. Code compiled in Swift is not readable, is not accessible. Also, obfuscation is when you change the name of the variables.
  • Any data recorded in flat persistent is visible by anyone. Sometimes they are very sensitive data that either should not go on the device. It's a best practice to make a transparent ledger between your database. With code data you must create a transparent layer for encryption and decryption.
  • IOS cryptographically secure random numbers are built in arrays of bytes in a data type and not with numbers. For example, when you have to store a password, you must store not in plain text but in hash. How can you validate a password?
  • Next step, we are trying to make encryption, okay. AES 2056 GCM encryption. It requires two keys, a cryptographic key as well as an encryption authentication data. GCM can take full advantage of parallel processing if we have many threads.
  • Next step, swiftui code security best practices. Try not to show any sensitive data when your app goes to background. Avoid backup copies of key files. Being responsible for security, data and good development practice will make our developments better and more efficient.

Transcript

This transcript was autogenerated. To make changes, submit a PR.
Okay, let's begin. First we are going to talk about the Darwin kernel. Darwin kernel is the kernel of all Apple operating systems. Was created in 2000 by Apple based on BSD and match with parts from OpenStep. You know that OpenStep was an open API created by Next and San microsystems based on the work that SteveJots made in next computer. Because next computer is not solvent in financial way, Steve Jobs thinks about to make an open API with open step with the possibility to work in Windows or even in Apple machines. And in this project, the result from this was open step. And this is the core of the iOS ten operating system. It supports all Apple OS, macOS, iOS, watchos and tvos. And maybe the next reality, iOS. It's an open source project and it iOS a kernel that supports the Appkit or Uikit development APIs. You know that Appkit is from macOS and Uikit is from iOS and the other mobile development, mobile systems like TBOS or watchOS, including the macOS interface. Aqua that. It's the interface, the API for the interface. IOS built in C and C. Okay? It's the kernel, it's the core of the operating system, and it's the same core for all the operating systems from Apple. We are going more deeper and for understand all the things about the security of the iPhone, we are going to talk in a brief, secure history of the first iPhone. Because I think it's very important to know the past, to understand the present and the future. And we are going to make this brief security, this brief, secure history of the iPhone. Okay? Today, there is no doubt that January 9, 2007, the wall changed with the introduction of the first iPhone. Okay. But the first iPhone model, however, was far from the current ones. In fact, it was way less secure than the actual iPhones. For example, the iPhone edge was a full feature smartphone, but it had no apps. It's a closer device. When asked for apps, Apple's answer was web app, not third party apps that runs naturally in the device. Apple defended to the hilt. It was not necessary to have third party software on the iPhone. And these closed functions were enough. The first idea about the iPhone is to make a device similar to an iPod with closed functions. Not the possibility to expand it, but with more functions, but all the functions that the mayor of the users needs to work needs for his device. But Apple and Steve Jobs was not sure about apps could bring something interesting to the users. And well, for now they speak about to use web apps. The iPhone was totally closed in system and kernel. It's like I said, a closed device. Otherwise, the initial scroll, the pinch, or the capacitive touch screen were some of its milestones. And let someone talk about this with software. Now, software on mobile phones is like baby software. It's not so powerful. And today we're going to show you a software breakthrough. Software that's at least five years ahead of what's on any other phone. Now, how do we do this? Well, we start with a strong foundation. IPhone runs OS ten. That's the key. Now, why would we want to run such a sophisticated operating system on a mobile device? Well, because it's got everything we need. Good question. It's got multitasking, it's got the best networking. It already knows how to power manage. We've been doing this on mobile computers for years. It's got awesome security and to write apps. It's got everything from Cocoa and the graphics, and it's got code animation built in, and it's got the audio and video that OS X is famous for. It's got all the stuff we want and it's built right into iPhone. And that has let us create desktop class applications and networking. That's the most important key about the iPhone because it runs os ten. And like Steve Job said, it's got awesome security. But the iPhone was software locked to what it has preinstalled, like I said before. And it used the Darwin kernel and the new Coco touch library on top of it. It's an extensive framework with Uikit and other framework, other APIs like your session or cocore animation, core audio and the other APIs that Stigob said in the keynote presentation. The kernel being based on BSD is the same kernel that we said before. The Darwin kernel that fits without any problem in its 128 megabytes of rAM that the iPhone has. Okay, but you know that native apps were programmed in object C. And Apple, this is the most important thing about security. Implemented digital signatures for code execution. And this is the way that we guarantee the security of the device. And for make this to ensure this security, app used this on certificate authority to disallow the execution of code that was not signed of them on the system. Because of this, as you know, if you try to execute any software on the iPhone, even if you could compile a program for this, it's not execute because it's not signing by app. But do you know that Apple think about third party software from the beginning? Yes. Let's read this. We define everything that is on the phone. You don't want your phone to be like a pc. The last thing you want is to have loaded three app on your phone and then you go to make a call and it doesn't work anymore. These are more like ipods than they are like computers. This is the first way that Apple see its device. But jobs add this. That doesn't mean there's not coding to be software to buy that you can load on them coming from us, it doesn't mean we have to write it all, but it means it has to be more of a controlled environment. Steve Job said this on January Twelveth, three days later from the iPhone keynote presentation on the New York Times. As you see, Apple was thinking about the possibility of the App Store. But first they want to know if the iPhone will be a success or not. Obviously. Okay, well, but we are going to talk about the security of this first iPhone, that it's way far from the actual security because of this. Okay. The first iPhone has a cryptographic coprocessor. Well it's so. Well, because it needs to validate the digital signature of the software. It has two AES keys engraved in the ship which cannot be extracted a Giid, a global key which is the same for all the devices and other that iOS unique for each device. The combination of these two keys makes the way for the cipher for the cryptography needs to encrypt or decrypt data or validate the detailed signature of the programs in the boot process. The did and the UID keys are used to create the keys to be used by the device and those limits its exposure. Okay, the passcode was recorded in the keychain with no hash. It's open even more. If you clean the record in the keychain for the passcode, you are open the iPhone and that was passcoded to anyone. Okay, well this is the security. It's so easy. It was so easy to clean a passcode in the first iPhone and obviously was increment version by version. The security of the device, the device keychain was and still iOS, an sqlite three database. But most important, only the password elements were encrypted, were encrypted. The other was open in plain text. The encrypted elements were encrypted with the device key and a random initialization vector. But it was only one key for the whole keychain because if you make a brute force attack, you could extract the key and access to all the keychain and all the items, not only the items in the keychain, also the future keys in the keychain could be extracted if you make this brute force attack to this only key, I repeat only for the password elements. The other are recorded in the keychain in plain text format. The iPhone Os one file system was not encrypted. Use a file system similar to the iPod and you can see all the folders with a special software. But any executable maybe the most important using about the security of this iPhone had to be signed by Apple to run on the iPhone. But maybe you are thinking about what is a digital signature. Okay, we are going to talk about it. The digital signature, it's a method to ensure that a certain file or data is not modified in the time since it was digital signature detail signed, okay. It is a method to ensure the integrity of a data and the fact that this was not modified, okay, works in this way. First we have a document and then we are coding to calculate a cryptographic hash of this document. A cryptographic hash that validates its content. Okay, we have this cryptographic hash. Then we used a private signing key from a certificate. The private key is used to encrypt and the public key is used to decrypt it. IOS like you have the rare or unrar or thief or antip, something like this, okay, you have two ways to make or extract, okay? With the private key you can encrypt something. You can encrypt this cryptographic hash, but with the public key that you can put in something or give to anyone. With this public key you can only do a decryption. You can't encrypt with this public. You only come to decrypt with this private signing key, you encrypt the hash. Then when you are encrypting the hash, then you are going to attach this hash to the document. And now we said that you have assigned document, okay, well, and then time goes by and later on we can check the signature and the integrity of a file, a file with its digital signature attached on it. Well, the next step is to calculate the cryptographic hash without the encrypted signature part. We are going to recalculate the cryptographic hash because we need to know what is this hash for the file. And then we used the public key to decrypt the signed cryptographic hash. When we have the cryptographic hash under the decrypted cryptographic hash for the digital signature, we are going to compare. If these two hashes are the same, it means that has not been altered and is validated and has been signed by the authority that encrypted the hash in the first steps. That's it. This is a digital signature. Well, let's talk about next step with the a seven code. The secure enclave chip. Apple evolves the encryption engine that has from the first iPhone to a multipurpose chips intended for all security and encryption functions on the systems, including the biometric features with a new security chip called Secure Enclave, a chip that iOS iOS property is a property of the kernel of the systems. As you can see, the keys never leave the chip to another context. The keys that the system uses or the biometric data for Touch ID or Face ID never leave the chip to another context. Secure Enclave is a black box. It's a black box responsible for encrypting and decrypting any data. But you put a data on secure enclave and secure enclave returns the data with the encryption or the data decrypted. But you never know how this chip works internally. Okay? This is the most important thing and we don't know how iOS or what is this mathematical way to storage. All the things about the geometry, the Touch ID and the Face ID and other thing that Apple makes is to encrypt each file with an independent and unique key for each file, not one key for all the file systems, okay? And again, all inside this secure enclave, only the chip finger is able to access the contents of the chip memory. Even if we read the memory, we will not be able to extract anything of it. Sand hackers and security investigators try to read this memory, but this memory is not able to track anything. The chip has an as 256 bitelectic curve, cryptographic key enzyme and four megabytes of ram in its first version. With this, we have this black box and ensure all the checks about encrypting data, signing data or biometric data, and all the things related to the security of the device. And obviously the system behaves in a very fluid way because there is no weight for these tax on the system. Okay, we are going to talk about additional layers of security that have been incorporated over time. For example, access to user information, extensions, services, or even iCloud is controlled by digital signed entitlements. But what is an entitlement? An entitlement allows the app to use certain functions or obtain specific permission to run some services or features on the system. If you want to use something that is not allowed for certain functionality, you can activate this entitlement. In fact, Apple could authorize you for certain entitlements after you ask the permission for certain features. Okay? And these entitlements allows you to use certain kind of APIs that in the first way it's forbidden for you. For example the diecloud or something else. Okay. Another thing that was implemented in the iPhone was ASLR or address space layer randomization that iOS incorporated in the system. This was a kind of security that iOS in each operating systems like Windows, Linux, et cetera. This function creates a table that ships important areas of the system such as the kernel, so that they are not always in the same place. And your process must have permission to ask about these tables to know what is the memory address of the kernel or other operating system important parts to access to them. Obviously you are not allowed to ask about this in your app, but the system have this security to guarantee the security and the integrity of all the system. About this iOS use Armxn or execute never. This is a way which marks memory pages as nonexecutable. If you put some code in the memory, you cannot execute this code. You are not allowed to execute code in any memory position in the device. Why? Because you need a valid entitlement of the associated app, but will be able to execute this code in memory. Each app has its own entitlement and if a code is not from this certain app is not allowed to execute this code in this place in the memory. Okay. This is the way that the system guarantees that you are not allowed to execute or to inject any code on the system to execute it. If this code is not from an autorespond app that it was a valid digital signature. Okay. Another thing iOS about network communications, we're going to talk about app transport security. ATS ETS is a set of requirements for securing network communications. It force the exclusive use of your session and URL connection even for third party network APIs. Because of this, all the third party network APIs are wrappers of Apple's native APIs. If you use Af networking or Alamo fire, you are using a wrapper of URL session. Okay? From iOS nine. This set of requirements are mandates for things like the users of TLS one two or even TLS one two three on all server certificates, 2048 arse encryption or 256 bits elliptic curve key signed with SHA 2056 using AC DHe with firewall secret this is a protocol to key agreement between two servers. You make a public key and send to another server and this server makes another public key and sent to you. And with this you can create a key agreement and create a private key that iOS shared between two sites from our server and the other server or from our device to a server and we have a private key that iOS different from each side but you can use it to decrypt the same data with this public key associated this is a key agreement protocol communication encryption. Okay, allow exceptions for this. If you don't want to use a secure connection through HTTPs or another protects, you can allow Apple allow the exception for for example multimedia content streams with AV foundation that can do it in HTTP or webview request or maybe local host usage when are working in debug code. Okay. All these things are mandatory standards since the end of 2016 which evolved year after year to comply with best practices in communications security. We must know all these rules to ensure the security of our app. Okay, well we are going to talk about data encryption. The use of data encryption is free to use but with recommendations for Apple. For example, Apple does not recommend the use of R C, four or three DES algorithms. Both are compromised and will be removed to avoid their use in future versions. For encryption you must use AesGCM or Chacha 20. That is two encryption algorithms that both support from Apple's cryptokit API that it's available for the system from iOS 13. Cryptokit is a swift native APIs API for encryption. Also if you work with SwiftuI in open source, you can use Swift crypto that is the same as cryptokid but using the coding SSL Google engine to make the same things with the same specification with the same interface. Because of this you can work in encryption in for example server side in vapor or in your app using Cocotach or Cocoa. With cryptokit these algorithms have the advantage of allowing not only encryption but also checking whether the data has been modified. We can validate the integrity of any data that it's encrypt of the crypt with these algorithms. Also all the files on the device are encrypted and we have several encryption modes to set for each file that we can use when users the metal safe from a data type. For example, we are going to talk about these four system code for encrypting data in storage. The first one iOS NS file protection known there is no encryption on the data. It remains open even when the device iOS locked. However, it requires the file system to be mounted because when your device is turned off the file system is not mounted. It needs that the file system is mounted and then anyone can access to these files. The next level is the NS file protection, complete until first user authentication. As you can see this name is from objective c. Obviously this option is the default for the system, it means that the file is encrypt and inaccessible inaccessible until the device is unlocked for the first time. When you put the first time your passcode or your password okay. It also locked after 20 or maybe 44 hours which requires real locking with passcode instead of touch id or face id. Do you know that between 24 hours or maybe later the device will ask you again for the passcode? And because the system rancrypt all the file system and needs you to put your passcode again. Like I said, this is the default code for all the files and it's a code that allows to access the files even when the device is locked. Okay, but you must put the first passcode at the beginning for processes that need continuous access to data, music, podcast, Bluetooth devices, your location, et cetera. Even if you have your device locked, your files are visible to the file system and the apps can access them while the device iOS not in mode. For asking you to put again the passcode, the next step is NS file protection complete unless open. In this kind of security, all the files are encrypted and can only be opened when the device is unlocked. When you locked the device, the file iOS encrypted and iOS not allowed to access to any app or any process in background. But there is one exception. Files are not locked or encrypted when the device is locked. If they're being used, they wait to encrypt when no threat is using it. Imagine you have a background process and you locked the device. Well if you lock the device and the file is using, the file is not encrypted unless it's closed. Unless complete. Unless open okay when the process is finished, then encrypt the file and the process or any other app cannot access to them. Okay recommended for the process when you have uploading or downloading data over network, which must be encrypted when the background process will finish. Okay, and the perfect method the method I use for most of my data is NS file protection complete. NS file protection complete is the higher security code. IOS files are encrypted and inaccessible until the device is unlocked. Okay, if you have your device unlocked, okay your device your files are ready to access, but if you locked the device, then all the files will be encrypted and it was impossible to access for any app or process. Okay, files are locked and any threats to them are cut off when the device is locked. Okay recommended for most update how can you use it? How can you use this? Well, using this code as you can see you have a try data write to URL and then you users options. And in these options you can put enumerations in an array. The first is atomic. Atomic. It's a mode that opens a temporary file to write all the data buffer, all the process to write the data buffer to this temporary file. And when all the data buffer is write to this temporary file, the temporary file is closed and then moved to the final location in the disk on the disk on the location of the app. Okay? This is a secure way to ensure that any other process cannot access to a writing process. In my application also you have complete file protection. Complete file protection iOS, the last mode that we are talk the code that encrypt the file in the moment that you locked your device. Okay? This is the way you can use this. With all these things in our hands, we have to ask you ourselves, are our iPhone secure? No. No system iOS secure. Even with all present of feature security features, no device iOS ever 100% secure. They never will be. Never. It's impossible. Okay, if someone says you something, someone says you that your iPhone or any other device is 100% secure, it lies to you. Okay? Every operating system and even hardware can have bugs in its design or iOS code that allow vulnerabilities to exploit it and do things that a system is supposed to be protected against. It's easy to understand what is a zero day because it's a software that tries you not to do something has a bag and this back that allows you to do it. That's it. And there's no system without this kind of errors. How can I protect against this? Okay, the only way to be protected is update our system as soon as patches are released for the bugs that are discovered. But part of our responsibility as developers is to take into account best development practice that improve security and make it more difficult for civil criminals to compromise our systems. Okay? If we do the right using to make our app more secure will be hard for these civil criminals to compromise our app and our users'data. Okay, that's it. We are going to talk about Swift Swift security because Swift has security as its core. Why? Okay, Swiftui, like many other languages, is made in c, in c language, okay, but Swift is strictly typed, value oriented language. But what does that mean? Okay. Means that data is self initialized to data types and isolates them by default. When you put a number one in your code, one is not a value, it's a type. It's a data type. That's because we are talking about value typed because the values are typed and converted automatically into data types because it's self initialized and there's no values in Swiftui, there's data types. Because of this. You can infer when you put let a equals one, a iOS integral type because one is not a value, one is an integral type. Self initialize it. Okay? This is value typed language, okay? And is strictly typed. Because of this, the different data types are not allowed to work between them. Also, swift runtime is static. It's not dynamic, so it does not allow runtime injection of any elements. Because of this, when you work with TDD, with test driven development, you have to create code, the injections or the mock objects, et cetera. You cannot use an API that injects dynamically like objectise or even other languages like Java because Swiftui has this static runtime and you cannot modify anything in the execution of your app collection types even is fully dynamic, so it avoids buffer overflows as its foundation. A string data, an array or dictionary has no initialization for the initial storage if all this kind of data are 100% dynamic. A string has a dynamic storage and creates more storage when it needs in real time. Okay? Because of this, it's impossible to do a buffer overflow when you code in impure swiftui. Okay, the use of uninitialized variables is prevented. As you know, we all know the optional values and iOS a compiler error for Swiftui forcing a defined initialization or the use of optional values. As you know, all the data in Swiftui must be initialized before we are going to users it. Okay? And if some data we don't know the data, we are going to storage them, we must users the optional values. Optional values are an uninitialized variables. No, because an optional value when you're defined it has an inferred initialization equals nil when you put bar something column int question mark and the compiler inferred equals nil. Because of this, all the data are initialized before we used. Okay. Also, code compiled in Swift is obfuscated by default. Any code compiled in Swift is not readable, is not accessible. You cannot read a compiled code in Swiftui because it's obfuscate. And obfuscation is when you change the name of the mail dots and the variables to something is not readable like randomized characters. Okay? You have a table for the corresponding names between the readable names and the non readable name that it's obfuscated. Okay, this table is the symbols. When you strip the symbols in Swiftui compilation. You're making this table and this table later you have to upload, for example to chrysalytics in Firebase to make the match between the obfuscated names and the names that the program used. Okay, this is the script symbols functionality, the feature let's go. And we are talking about insecure that data recording. We are going to talk about best practices with data. We have to know that any data recorded in flat persistent is visible by anyone such as using JSon, paylist or even core data or sqlite databases. It is wise to audit the sensitivity of the data before developing and decide how it will be persisted and where and if any data needs encryption or maybe any data have to be storage in certain locations, for example the keychain to avoid the access or read from anyone in the flat persistent, okay. Sometimes they are very sensitive data that either should not go on the device. For example, some data must be only in server side and if you work with this data only in your memory, this data iOS secure. But if you storage in your device with a JSoN, with a paylist, with a database, et cetera will be visible in, like I said before, persistent, flat persistent, okay. Because of this, the best way to work with certain data is not to a storage on the device works only with server size and with memory or have their own container in the system to be stored. The keychain health data or maybe honky data has its own container in the system and you have to use it. Okay, even more, the users of local databases should be properly encrypted. It's a best practice to make a transparent ledger between your database, for example with core data or even when you store directly in your application a JSON file. Maybe it's a good idea to make a transparent layer for encryption in these databases. Okay. If you users realm, for example realm has this feature, you can set an encryption key on realm and then all the data in this database will be encrypted and is not visible to anyone that try to read the database. Okay. But with code data you must create this transparent layer for encryption and decryption. It's not so hard because you can users extensions for the data types, okay, but well you must do it. This is your responsibility. If we persist, for example, an enumeration that is part of a sensitive data set, we should not duty its value as a string or sequential numbering, okay, if you users an enumeration and you are typing with string, it's more secure to put strings that is not equivalent to its value. Okay, because of this, when someone read your code, when someone read your data, they don't know the equivalent, the equivalent of these values. Okay, more now we are going to talk about data encryption and has calculation. Okay, maybe you are thinking, but to use encryption, okay, we are going to see it. The first things we want to know. IOS cryptographically secure random numbers okay, what is this? Okay, first of all, before playing with cryptography, it iOS necessary to be able to generate random numbers, but secure random numbers. Cryptographically secure random numbers, cryptographically strong random numbers which are built in arrays of bytes in a data type and not with numbers. Why we use them? Because these do not use any type of value from the device itself like other randomized algorithms. With this way we use algorithm, algorithmic formulas that guarantee that no pattern can be found that will discover them. It's a totally, absolutely randomized number with created without pattern, okay, it's a cryptographically strong random number, okay, how can we create it? Okay, it's so easy. We can use the sec random copy bytes method from the security of the keychain and all the things about the security framework in Swift. And then we can use something that is so good from swift five. The array of u int eight and signed integral of eight bits. An array of this swift native type is convertible, is directly convertible to data type with the constructor. Okay, as you know, you can convert a double number in int or int in double, okay, you can put an in number double parentheses in number parentheses, and then you have a direct creation, a direct transformation between types using the constructors, okay, an array of u int eight has direct transformation with data type. If you have an array of using eight, you can put this data in data constructor and you are making a new data type, a new row bytes data type. We are creating an array with empty values with zeros. Then we send to sec random copy bytes with the property ksec random default. Then the count bytes bytes we desire and then the reference with the ampersand of random bytes. Then sec random copy bytes returns in random bytes. The strong, the cryptoker, the cryptographically strong random number. Okay, it's so easy to make with this we can use data encryption. For example, when you have to store a password, you must store not in plain text, please, you must store in hash. With a password hashing, even the best way to do it is with hmac 256 algorithm, okay, hmac, what is hmac? It's an algorithm that uses a key to ensure that hashes are not repeated in their calculation. For the same data. One of the most important problems when you calculate a hash is the collision, okay? When you have a collision in a hash calculation, it means you have two different data that has the same hash, okay. And that it's a great problem to try to resolve this. HMac put a key when you calculate the hash. Because of this, if you don't have the key, you cannot check the data. You cannot create the same hash for the same data. Because for validate a hash, you must have the data and the equivalent and the key we use to create this hash. Okay, how can you do it? Okay, using cryptokit, this iOS the easiest way you received a key, a key that can be a cryptographically strong random number. We create in the path before, okay, we use this number and then we send us a key, okay, with this cryptokit creates with the data a symmetric key. And then with hMAC 256 dot authentication code, we obtain the hash for a string using the key, okay. And then because a code authentication code returns an array of using eight, then we are returning in the constructor of data, okay. Then this data can convert to, for example, a base 64 string. For example, how can you use this function, okay, in this way? It's so simple. Random key generator of 2048. Then H Mac 256 ck string and the key and then obtain the base 64 encoded string. Then this base 64 encoded string is the value you must to store. Okay, then how can you validate a password? Okay, the validation of a hash is to convert the plain text password, making the hash again with the sync key. And then you compared the encrypted hash with the new one. And if it's the same, it's the same password. Okay, why we use hash? Because hash is an algorithm that avoid to make the transformation, the decryption of the data. When you have the hash, it's impossible to know the data we are hashing. Okay, this is the security way to ensure this feature. Okay, when you want to validate an authentication code for hash, the only thing you need is to make HMAC SH 256 iOS validated authentication code. And then when you put in authenticating the plain text password that the user introduces with this, you are comparing the HK that is the hash with the value in plain text in Cadena, okay. And then using the key, the key for validate the hash. Okay, it's so easy. Next step, we are trying to make encryption, okay. AES 2056 GCM encryption. The AA. The AES GCM is a galua code code. It's a cipher mode that is one of the most widely used for its performance and efficiency and it's recommended by Apple. It requires two keys, a cryptographic key as well as an encryption authentication data. You need two values to make this encryption. If we do not have both values, we cannot decrypt the content. Okay. The operation is an authenticated encryption algorithm designed to provide both data authenticity, the integrity of the data and the confidentiality. Okay. Makes these things altogether. GCM can take full advantage of parallel processing if we have many threads. The algorithm use these many threads and implementing GCM can make efficient use of an instruction pipeline, of a hardware pipeline. For example, when you have many threads and have an encryption engine like an M one for example, okay, how can I do it? It's so easy. With cryptokit you have to create a sealed box. Okay, with try you are using AES GCM seal and in this seal you have to provide the data you want to encrypt, the key you are using and the authenticating data. Okay. With this you obtain a sealed box and when you access to combined property, you can extract an encrypted string. You can storage on base 64 for example. Okay, how can I decrypt this? Making the same. But in this time you are creating a celebrate box. Okay. With AasgCM you use the initialization initialize function sealed box with the combined data you are storage before. With this combined data you are creating a new sealed box and then you can open providing it the sealed box, the key and the authentication, and then it returns the data decrypted. This data you can convert with string, for example, string data with the data that returns this function. And in UTF eight, okay. And with this you can see the new data decrypted. Okay. It's so easy, it's not hard. Next step, swiftui code security best practices one of the things we are so important is to try not to show any sensitive data when your app goes to background. Because of this, the app makes a screenshot of the last screen it showed and then your application the screens when you buy from one application to another. In this screenshot you can see maybe any sensitive data. Well, this could result in an unintentional capture of sensitive data and we have to do some process to control it. What process? For example, if you use SwiftuI, you have a new modifier, privacy sensitive you can put in any view. If you put this modifier, when you put the app in background, this data will be blurred and the user cannot see. It's so simple. But when you use another framework or maybe if you use SwiftuI or even UI kit we can capture system notifications. Okay, you can capture the system notification UI application will resign active notification and did become active notification will resign iOS when the app goes to background and did become active is when the app is going foreground. Well with this you can use this code you make an observer to UI application will resign active notification in the main queue and then creates a black view controller and then put it on your present it in the root view controller. Okay? With this you can create a UIB control that puts in front of your screen at the moment you are entered to background. Your app will your app screenshot will see blank. Okay, how can you dismiss this blank interface? Okay, capturing another notification it become active notification. In this you make UI application shared Windows first root view controller dismiss and then the black view controller dismiss it. And then you can see the app when you enter infogram again. Okay, that's so easy. Another thing is to avoid backup copies of key files. An iTunes backup, for example, can allow access to files in a very simple way. Okay, since iOS eight three, Apple does not allow access to the sandboxing. But if you make or someone makes an unencrypted backup in itunes of your devices, they code to extract data, compromise your security or your privacy. We have to configure the resource of the URL file itself. In this way you prevent that a file will be included in iTunes backup. Okay. Or maybe iCloud. It's important to remember that except jailbreak, the only way to explore the file system on an iOS device is through an iTunes and encrypted backup. We should never trust any device that is not ours when it show us the alert to trust in this device. How can I do it? Okay, it's so easy. You have to modify the values of the URL type by adding a URL resource value object like this. If I want to write a data one TxT, you have to config URL resource value is excluded from backup. True. And then set resource value with this your data one TXT are not included in your iTunes backup or in your iCloud backup. Final conclusions as developers, okay, we are always behind the system. We have the responsibility with great power code, great responsibility. As you know, if it is vulnerable, so is our app. But doing our job well is a guarantee for our users. Okay? Everything we have said should be a lawyer. That is part of your day to day part of your development routine. Make your APIs, make your helper functions, make all the things you need to secure your application. Make a swift package, for example, and use it in all your apps to ensure you make the best secure coding in iOS or other Apple systems. Being responsible for security, data and good development practice will make our developments better and more efficient. And don't forget to update any third party libraries you use. But maybe it's better not to use it. Maybe a better option if you can iOS try to go completely native because many times and don't forget this, we don't know who is behind a third party library and we are relying on their good faith and good security practice blindly. That's not a good option. Remember, don't trust anyone, okay? And that's it. Thank you so much. I hope you like this talk and I hope you are now you know kung fu in security and then your code will be more secure. Thanks to conf 42 for the opportunity to make this talk and as I said, always in my podcast and live streams. Best regards and good apple coding.
...

Julio Cesar Fernandez Munoz

Swift Developer Evangelist & Podcaster @ Apple Coding Academy

Julio Cesar Fernandez Munoz's LinkedIn account Julio Cesar Fernandez Munoz's twitter account



Awesome tech events for

Priority access to all content

Video hallway track

Community chat

Exclusive promotions and giveaways