Droidcedas : Using The Sim Carte Du Jour Every Mo A Secure Chemical Part Inward Android

Our last post introduced 1 of Android 4.3's to a greater extent than notable safety features -- improved credential storage, too spell at that topographic point are a few other previously, mobile devices tin include some cast of a Secure Element (SE), but a smart card based UICC (usually called only 'SIM card') is almost universally present. Virtually all SIM cards inward utilization today are programmable too thus tin live used every bit a SE. Continuing the subject of hardware-backed security, nosotros volition at nowadays aspect into how SIMs tin live programmed too used to heighten the safety of Android applications.

SIM cards

First, a few words about terminology: while the right term for modern mobile devices is UICC (Universal Integrated Circuit Card), since the destination of this post service is non to verbalize over the differences betwixt mobile networks, nosotros volition commonly telephone telephone it a 'SIM card' too only brand the distinction when necessary. 

So what is a SIM card? 'SIM' stands for Subscriber Identity Module too refers to a smart card that securely stores the subscriber identifier too the associated primal used to position too authenticate to a mobile network. It was originally used on GSM networks too standards were subsequently extended to back upwardly 3G too LTE. Since SIMs are smart cards, they arrange to ISO-7816 standards regarding physical characteristics too electrical interface. Originally they were the same size every bit 'regular' smart cards (Full-size, FF), but past times far the most pop sizes nowadays are Mini-SIM (2FF) and Micro-SIM (3FF), with Nano-SIM (4FF) introduced inward 2012. 

Of course, non every smart that fits inward the SIM slot tin live used inward a mobile device, so the side past times side inquiry is: what makes a smart card a SIM card? Technically, it's conformance to mobile communication standards such 3GPP TS 11.11 and certification past times the SIMalliance. In exercise it is the might to run an application that allows it to communicate amongst the telephone (referred to every bit 'Mobile Equipment', ME, or 'Mobile Station', MS inward related standards) too connect to a mobile network. While the original GSM criterion did non brand a  distinction betwixt the physical smart card too the software required to connect to the mobile network, amongst the introduction of 3G standards, a clear distinction has been made. The physical smart card is referred to every bit Universal Integrated Circuit Card (UICC) too dissimilar mobile network applications than run on it conduct hold been defined: GSM, CSIM, USIM, ISIM, etc. Influenza A virus subtype H5N1 UICC tin host too run to a greater extent than than 1 network application (hence 'universal'), too thus tin live used to connect to dissimilar networks. While network application functionality depends on the specific mobile network, their inwardness features are quite similar: store network parameters securely too position to the network, every bit good every bit authenticate the user (optionally) too store user data. 

SIM card applications

Let's conduct hold GSM/3G every bit an instance too briefly review how a network application works. For GSM the primary network parameters are network identity (International Mobile Subscriber Identity, IMSI; tied to the SIM), telephone number  (MSISDN, used for routing calls too changeable) too a shared network authentication primal Ki. To connect to the network the MS needs to authenticate itself too negotiate a session key. Both authentication too session primal derivation brand utilization of Ki, which is also known to the network too looked upwardly past times IMSI. The MS sends a connector asking too includes its IMSI, which the network uses to honor the corresponding Ki. The network so uses the Ki to generate a challenge (RAND), expected challenge reply (SRES) too session primal Kc too sends RAND to the MS. Here's where the GSM application running on the SIM card comes into play: the MS passes the RAND to the SIM card, which inward plough generates its ain SRES too Kc. The SRES is sent to the network too if it matches the expected value, encrypted communication is established using the session primal Kc. As you lot tin see, the safety of this protocol hinges solely on the secrecy of the Ki. Since all operations involving the Ki are implemented within the SIM too it never comes amongst direct contact amongst neither the MS or the network, the scheme is kept reasonably secure. Of course, safety depends on the encryption algorithms used every bit well, too major weaknesses that allow intercepted GSM calls to live decrypted using off-the shelf hardware were found inward the original versions of the A3/A5 algorithms (which were initially secret). Jumping dorsum to Android for a moment, all of this is implemented past times the baseband software (more on this later) too network authentication is never direct visible to the primary OS.

We've shown that SIM cards demand to run applications, let's at nowadays say a few words well-nigh how those applications are implemented too installed. Initial smart cards were based on a file organization model, where files (elementary files, EF) too directories (dedicated files, DF) were named amongst a two-byte identifier. Thus developing 'an application' consisted to a greater extent than oftentimes than non of selecting an ID for the DF that hosts its files (called ADF), too specifying the formats too names of EFs that store data. For example, the GSM application is nether the '7F20' ADF, too the USIM ADF hosts the EF_imsi, EF_keys, EF_sms, etc. files. Practically all SIMs used today are based on Java Card engineering scientific discipline too implement GlobalPlatform card specifications. Thus all network applications are implemented every bit Java Card applets too emulate the legacy file-based construction for backward compatibility. Applets are installed according to GlobalPlatform specifications past times authenticating to the Issuer Security Domain (Card Manager) too issuing LOAD too INSTALL commands.

One application management characteristic specific to SIM cards is back upwardly for OTA (Over-The-Air) updates via binary SMS. This functionality is non used past times all carries, but it allows them to remotely install applets on SIM cards they conduct hold issued. OTA is implemented past times wrapping card commands (APDUs) inward SMS T-PDUs, which the ME forwards to the SIM (ETSI TS 102 226). In most SIMs this is genuinely the only way to charge applets on the card, fifty-fifty during initial personalization. That is why most of the mutual GlobalPlatform-compliant tools cannot live used every bit is for managing SIMs. One needs to either utilization a tool that supports SIM OTA, such every bit the SIMalliance Loader, or implement APDU wrapping/unwrapping, including whatever necessary encryption too integrity algorithms (ETSI TS 102 225). Incidentally, problems amongst the implementation of those secured packets on some SIMs that utilization DES every bit the encryption too integrity algorithm conduct hold been used to crack OTA update keys. The major utilization of the OTA functionality is to install too hold SIM Toolkit (STK) applications which tin interact amongst the handset via criterion 'proactive' (in reality implemented via polling) commands too display menus or fifty-fifty opened upwardly Web pages too send SMS. While STK applications are almost unheard of inward the U.S. too Asia, they are even so heavily used inward some parts of Europe too Africa for anything from mobile banking to citizen authentication. Android also supports STK amongst a dedicated STK organization app, which is automatically disabled if the SIM card has non STK applets installed.

Accessing the SIM card

As mentioned above, network related functionality is implemented past times the baseband software too what tin live done from Android is exclusively theme on what features the baseband exposes. Android supports STK applications, so it does conduct hold internal back upwardly for communicating to the SIM, but the OS security overview explicitly states that 'low grade access to the SIM card is non available to third-party apps'. So how tin nosotros utilization it every bit an SE then? Some Android builds from major vendors, most notably Samsung, furnish an implementation of the SIMalliance Open Mobile API on some handsets too an opened upwardly source implementation (for compatible devices) is available from the SEEK for Android project. The Open Mobile API aims to furnish a unified interface for accessing SEs on Android, including the SIM. To sympathize how the Open Mobile API industrial plant too the movement of its limitations, let's outset review how access to the SIM card is implemented inward Android.

On Android devices all mobile network functionality (dialing, sending SMS, etc.) is provided past times the baseband processor (also referred to every bit 'modem' or 'radio'). Android applications too organization services communicate to the baseband only indirectly via the Radio Interface Layer (RIL) daemon (rild). It inward plough talks to the actual hardware past times using a manufacturer-provided RIL HAL library, which wraps the proprietary interface the baseband provides. The SIM card is typically connected only to baseband processor (sometimes also to the NFC controller via SWP), too thus all communication needs to become through the RIL. While the proprietary RIL implementation tin ever access the SIM inward gild to perform network identification too authentication, every bit good every bit read/write contacts too access STK applications, back upwardly for transparent APDU central is non ever available. The criterion way to furnish this characteristic is to utilization extended AT commands such AT+CSIM (Generic SIM access) too AT+CGLA (Generic UICC Logical Channel Access), every bit defined inward 3GPP TS 27.007, but some vendors implement it using proprietary extensions, so back upwardly for the necessary AT commands does non automatically furnish SIM access.

SEEK for Android provides patches that implement a resources manager service (SmartCardService) that tin connect to whatever supported SE (embedded SE, ASSD or UICC) too extensions to the Android telephony framework that allow for transparent APDU central amongst the SIM. As mentioned above, access through the RIL is hardware too proprietary RIL library dependent, so you lot demand both a compatible device too a construct that includes the SmartCardService too related framework extensions. Thanks to some piece of work past times they u'smile project, UICC access on most variants of the pop Milky Way S2 too S3 handsets is available using a patched CyanogenMod build, so you lot tin brand utilization of the latest SEEK version. Even if you lot don't ain 1 of those devices, you lot tin utilization the SEEK emulator extension which lets you lot utilization a criterion PC/SC smart card reader to connect a SIM to the Android emulator. Note that only whatever regular Java card won't piece of work out of the box because the emulator volition aspect for the GSM application too grade the card every bit non usable if it doesn't honor one. You tin modify it to skip those steps, but a simple solution is to install a dummy GSM application that ever returns the expected responses.

Once you lot conduct hold managed to larn a device or the emulator to verbalize to the SIM, using the OpenMobile API to send commands is quite straightforward:

// connect to the SE service, asynchronous SEService seService = novel SEService(this, this); // listing readers  Reader[] readers = seService.getReaders(); // assume the outset 1 is SIM too opened upwardly session Session session = readers[0].openSession(); // opened upwardly logical (or basic) channel Channel channel = session.openLogicalChannel(aid); // send APDU too larn reply byte[] rapdu = channel.transmit(cmd); 

You volition demand to asking the org.simalliance.openmobileapi.SMARTCARD permission too add together the org.simalliance.openmobileapi extension library to your manifest for this to work. See the official wiki for to a greater extent than details.

<manifest ...>      <uses-permission android:name="org.simalliance.openmobileapi.SMARTCARD" />      <application ...>         <uses-library             android:name="org.simalliance.openmobileapi"             android:required="true" />      ...     </application> </manifest> 

SE-enabled Android applications

Now that nosotros tin connect to the SIM card from applications, what tin nosotros utilization it for? Just every bit regular smart cards, an SE tin live used to store information too keys securely too perform cryptographic operations without keys having to leave of absence the card. One of the commons applications of smart cards is to store RSA authentication keys too certificates that are used from anything from desktop logon to VPN or SSL authentication. This is typically implemented past times providing some form of middleware library, commonly a criterion cryptographic service provider (CSP) module that tin plug into the organization CSP or live loaded past times a compatible application. As the Android safety model does non allow organization extensions provided past times 3rd political party apps, inward gild to integrate amongst the organization primal management service, such middleware would demand to live implemented every bit a keymaster module for the organization credential store (keystore) too live bundled every bit a organization library. This tin live accomplished past times edifice a custom ROM which installs our custom keymaster module, but nosotros tin also conduct hold payoff of the SE without rebuilding the whole system. The most straightforward way to do this is to implement the safety critical portion of an app within the SE too conduct hold the app deed every bit a customer that only provides a user-facing GUI. One such application provided amongst the SEEK distribution is an SE-backed old password (OTP) Google Authenticator app. Since the critical portion of OTP generators is the seed (usually a symmetric cryptographic key), they tin easily live cloned 1 time the seed is obtained or extracted. Thus OTP apps that store the seed inward a regular file (like the official Google Authenticator app) furnish niggling protection if the device OS is compromised. The SEEK GoogleOtpAuthenticator app both stores the seed too performs OTP generation within the SE, making it impossible to recover the seed from the app information stored on the device.

Another type of pop application that could do goodness from using an SE is a password manager. Password managers typically utilization a user-supplied passphrase to derive a symmetric key, which is inward plough used to encrypt stored passwords. This makes it hard to recover stored passwords without knowing the passphrase, but naturally safety grade is totally theme on its complexity. As usual, because typing a long string amongst rarely used characters on a mobile device is non a peculiarly pleasant experience, users tend to pick easier to type, low-entropy passphrases. If the primal is stored inward an SE, the passphrase tin live skipped or replaced amongst a simpler PIN, making the password manager app both to a greater extent than user-friendly too secure. Let's run into how such an SE-backed password manager tin live implemented using a Java Card applet too the Open Mobile API.

DIY SIM password manager

Ideally, all primal management too encryption logic should live implemented within the SE too the customer application would only furnish input (plain text passwords) too recollect opaque encrypted data. The SE applet should non only furnish encryption, but also guarantee the integrity of encrypted information either past times using an algorithm that provides authenticated encryption (which most smart card don't natively back upwardly currently) or past times calculating a MAC over the encrypted information using HMAC or some similar mechanism. Smart cards typically furnish some form of encryption support, starting amongst DES/3DES for low-end models too going upwardly to RSA too EC for top-of-the-line ones. Since world primal cryptography is typically non needed for mobile network authentication or secure OTA (which is based on symmetric algorithms), SIM cards rarely back upwardly RSA or EC. Influenza A virus subtype H5N1 reasonably secure symmetric too hash algorithm should live plenty to implement a simple password manager though, so inward theory nosotros should live able to utilization fifty-fifty a lower-end SIM.

As mentioned inward the previous section, all recent SIM cards are based on Java Card technology, too it is possible to develop too charge a custom applet, provided 1 has access to the Card Manager or OTA keys. Those are naturally non available for commercial MNO SIMs, so nosotros would demand to utilization a blank 'programmable' SIM that allows for loading applets without authentication or comes bundled amongst the required keys. Those are quite hard, but not impossible to come upwardly by, so let's run into how such a password manager applet could live implemented. We won't verbalize over the basics of Java Card programming, but outpouring straight to the implementation. Refer to the offical documentation, or a tutorial if you lot demand an introduction.

The Java Card API provides a subset of the JCA classes, amongst an interface optimized towards using pre-allocated, shared byte arrays, which is typical on a retention constrained platform such every bit a smart card. Influenza A virus subtype H5N1 basic encryption instance would aspect something similar this:

byte[] buff = apdu.getBuffer(); //.. DESKey deskey = (DESKey)KeyBuilder.buildKey(KeyBuilder.TYPE_DES_TRANSIENT_DESELECT,                KeyBuilder.LENGTH_DES3_2KEY, false); deskey.setKey(keyBytes, (short)0); Cipher zip = Cipher.getInstance(Cipher.ALG_DES_CBC_PKCS5, false); cipher.init(deskey, Cipher.MODE_ENCRYPT); cipher.doFinal(data, (short) 0, (short) data.length,                 buff, (short) 0); 

As you lot tin see, a dedicated primal object, that is automatically cleared when the applet is deselected, is outset created too so used to initialize a Cipher instance. Besides the unwieldy number of casts to short (necessary because 'classic' Java Card does non back upwardly int, but it is even so the default integer type) the code is real similar to what you lot would honor inward a Java SE or Android application. Hashing uses the MessageDigest cast too follows a similar routine. Using the system-provided Cipher too MessageDigest classes every bit edifice blocks it is fairly straightforward to implement CBC way encryption too HMAC for information integrity. However every bit it happens, our depression halt SIM card does non furnish usable implementations of those classes (even though the spec sail claims they do), so nosotros would demand to start from scratch. Fortunately, since Java cards tin execute arbitrary programs (as long every bit they fit inward memory), it is also possible to include our ain encryption algorithm implementation inward the applet. Even better, a Java Card optimized AES implementation is freely available. This implementation provides only the basic pieces of AES -- primal schedule generation too unmarried block encryption, so some additional piece of work is required to tally the Java Cipher cast functionality. The bigger downside is that past times using an algorithm implemented inward software nosotros cannot conduct hold payoff of the specialized crypto co-processor most smart cards have. With this implementation our SIM (8-bit CPU, 6KB RAM) card takes well-nigh 2 seconds to procedure a unmarried AES block amongst a 128-bit key. The performance tin live improved slightly past times reducing the number of AES circular to seven (10 are recommended for 128-bit keys), but that volition both lower the safety grade of the organization too upshot inward an non-standard cipher, making testing to a greater extent than difficult. Another disadvantage is that native primal objects are commonly stored inward a secured retention expanse that is improve protected from side channel attacks, but past times using our ain zip nosotros are forced to store keys inward regular byte arrays. With those caveats, this AES implementation should give us what nosotros demand for our demo application. Using the JavaCardAES cast every bit a edifice block, our AES CBC encryption routine would aspect something similar this:

aesCipher.RoundKeysSchedule(keyBytes, (short) 0, roundKeysBuff); brusk padSize = addPadding(cipherBuff, offset, len); brusk paddedLen = (short) (len + padSize); brusk blocks = (short) (paddedLen / AES_BLOCK_LEN);  for (short i = 0; i < blocks; i++) {   brusk cipherOffset = (short) (i * AES_BLOCK_LEN);   for (short j = 0; j < AES_BLOCK_LEN; j++) {     cbcV[j] ^= cipherBuff[(short) (cipherOffset + j)];   }   aesCipher.AESEncryptBlock(cbcV, OFFSET_ZERO, roundKeysBuff);   Util.arrayCopyNonAtomic(cbcV, OFFSET_ZERO, cipherBuff,                           cipherOffset, AES_BLOCK_LEN); } 

Not every bit concise every bit using the organization crypto classes, but gets the task done. Finally (not shown), the IV too zip text are copied to the APDU buffer too sent dorsum to the caller. Decryption follows a similar pattern. One affair that is evidently missing is the MAC, but every bit it turns out a hash algorithm implemented inward software is prohibitively tiresome on our SIM (mostly because it needs to access large tables stored inward the tiresome card EEPROM). While a MAC tin live also implemented using the AES primitive, nosotros conduct hold omitted it from the sample applet. In exercise tampering amongst the zip text of encrypted passwords would only upshot inward wrong passwords, but it is even so a proficient thought to utilization a MAC when implementing this on a fully functional Java Card.

Our applet tin at nowadays perform encryption too decryption, but 1 critical slice is even so missing -- a random number generator. The Java Card API has the RandomData cast which is typically used to generate primal cloth too IVs for cryptographic operations, but only every bit amongst the Cipher cast it is non available on our SIM. Therefore, unfortunately, nosotros demand to apply the DIY approach again. To continue things simple too amongst a (somewhat) reasonable reply time, nosotros implement a simple pseudo random number generator (PRNG) based on AES inward counter mode. As mentioned above, the largest integer type inward classic Java Card is short, so the counter volition wind every bit before long every bit it goes over 32767. While this tin live overcome fairly easily past times using a persistent byte array to simulate a long (or BigInteger if you lot are to a greater extent than ambitious), the bigger work is that at that topographic point is no suitable source of entropy on the smart card that nosotros tin utilization to seed the PRNG. Therefore the PRNG AES primal too nonce demand to live specified at applet install fourth dimension too live unique to each SIM. Our simplistic PRNG implementation based on the JavaCardAES cast is shown below (buff is the output buffer):

Util.arrayCopyNonAtomic(prngNonce, OFFSET_ZERO, cipherBuff,                              OFFSET_ZERO, (short) prngNonce.length); Util.setShort(cipherBuff, (short) (AES_BLOCK_LEN - 2), prngCounter);  aesCipher.RoundKeysSchedule(prngKey, (short) 0, roundKeysBuff); aeCipher.AESEncryptBlock(cipherBuff, OFFSET_ZERO, roundKeysBuff); prngCounter++;  Util.arrayCopyNonAtomic(cipherBuff, OFFSET_ZERO, buff, offset, len); 

The recent weak past times design too is used past times default inward pop crypto toolkits too finally the low-quality hardware RNG found inward FIPS certified smart cards conduct hold highlighted the critical send on a flawed PRNG tin conduct hold on whatever organization that uses cryptography. That is why a DIY PRNG is definitely non something you lot would similar to utilization inward a production system. Do honor a SIM that provides working crypto classes too do utilization RandomData.ALG_SECURE_RANDOM to initialize the PRNG (that won't assist much if the card's hardware RNG is flawed, of course).

With that nosotros conduct hold all the pieces needed to implement the password manager applet, too what is left is to define too expose a world interface. For Java Card this way defining the values of the CLA too INS bytes the applet tin process. Besides the evidently required encrypt too decrypt commands, nosotros also furnish commands to larn the electrical current state, initialize too clear the applet.

static concluding byte CLA = (byte) 0x80; static concluding byte INS_GET_STATUS = (byte) 0x1; static concluding byte INS_GEN_RANDOM = (byte) 0x2; static concluding byte INS_GEN_KEY = (byte) 0x03; static concluding byte INS_ENCRYPT = (byte) 0x4; static concluding byte INS_DECRYPT = (byte) 0x5; static concluding byte INS_CLEAR = (byte) 0x6; 

Once nosotros conduct hold a working applet, implementing the Android customer is fairly straightforward. We demand to connect to the SEService, opened upwardly a logical channel to our applet (AID: 73 69 6d seventy 61 73 73 6d 61 6e 01) too send the appropriate APDUs using the protocol outlined above. For example, sending a string to live encrypted requires the next code (assuming nosotros already conduct hold an opened upwardly Session to the SE). Here 0x9000 is the criterion ISO 7816-3/4 success condition give-and-take (SW):

Channel channel = session.openLogicalChannel(fromHex("73 69 6d seventy 61 73 73 6d 61 6e 01")); byte[] information = "password".getBytes("ASCII"); String cmdStr = "80 04 00 00 " + String.format("%02x", data.length)                 + toHex(data) + "00"; byte[] rapdu = channel.transmit(fromHex(cmdStr)); brusk sw = (short) ((rapdu [rapdu.length - 2] << 8) | (0xff & rapdu [rapdu.length - 1])); if (sw != (short)0x9000) {   // handgrip mistake } byte[] ciphertext = Arrays.copyOf(rapdu, rapdu.length - 2); String encrypted= Base64.encodeToString(ciphertext, Base64.NO_WRAP); 

Besides calling applet operations past times sending commands to the SE, the sample Android app also has a simple database to store encrypted passwords paired amongst a description, too displays currently managed passwords inward a listing view. Long pressing on the password call volition convey upwardly a contextual activeness that allows you lot to decrypt too temporarily display the password so you lot tin re-create it too glue it into the target application. The electrical current implementation does non require a PIN to decrypt passwords, but 1 tin easily past times provided using Java Card's OwnerPIN class, optionally disabling the applet 1 time a number of wrong tries is reached. While this app tin hardly compete amongst pop password managers, it has plenty functionality to both illustrate the concept of an SE-backed app too live practially useful. Passwords tin live added past times pressing the '+' activeness item too the delete item clears the encryption primal too PRNG counter, but non the PRNG seed too nonce. Influenza A virus subtype H5N1 screenshot of the award-winning UI is shown below. Full source code for both the applet too the Android app is available on Github.


Summary

The AOSP version of Android does non furnish a criterion API to utilization the SIM card every bit a SE, but many vendors do, too every bit long every bit the device baseband too RIL back upwardly APDU exchange, 1 tin live added past times using the SEEK for Android patches. This allows to improve the safety of Android apps past times using the SIM every bit a secure chemical component too both store sensitive information too implement critical functionality within it. Commercial SIM do non allow for installing arbitrary user applications, but applets tin live automatically loaded past times the carrier using the SIM OTA machinery too apps that conduct hold payoff of those applets tin live distributed through regular channels, such every bit the Play Store.

Thanks to Michael for developing the Milky Way S2/3 RIL patch too helping amongst getting it to piece of work on my somewhat exotic S2.
0 Komentar untuk "Droidcedas : Using The Sim Carte Du Jour Every Mo A Secure Chemical Part Inward Android"

Back To Top