Droidcedas : Emulating A Pki Smart Carte Alongside Cyanogenmod 9.1

We discussed the embedded cloud-based NFC secure element. We, however, volition await at a different work case: PKI.

PKI has been getting a lot of bad rep due to major CAs getting compromised every other month, together with it has been stated multiple times that it secure element available inwards recent Android devices, it's cloud-based NFC secure element. We, however, volition await at a different work case: PKI.

PKI has been getting a lot of bad rep due to major CAs getting compromised every other month, together with it has been stated multiple times that it execution environment together with how cloud-based NFC secure element. We, however, volition await at a different work case: PKI.

PKI has been getting a lot of bad rep due to major CAs getting compromised every other month, together with it has been stated multiple times that it Google Wallet makes work if it inwards the in conclusion serial of articles. We also saw that unless y'all have got a contract amongst Google together with have got them (or the TSM they use) distribute your applets to supported devices, at that topographic point is currently no way to install anything on the embedded secure element. We briefly mentioned that CyanogenMod 9.1 supports software carte emulation together with it is a to a greater extent than practical way to create your ain NFC-enabled applications. We'll instantly come across how software carte emulation plant together with exhibit how y'all tin work it to create a elementary PKI 'applet' that tin last accessed via NFC from whatsoever machine amongst a contactless carte reader.

Software carte emulation

We already know that if the embedded secure chemical component is seat inwards virtual vogue it is visible to external readers every bit a contactless smartcard. Software carte emulation (sometimes referred to every bit Host Card Emulation or HCE) does something really similar, but instead of routing commands received past times the NFC controller to the SE, it delivers them to the application processor, together with they tin last processed past times regular applications. Responses are together with so sent via NFC to the reader, together with thence your app takes the role of a virtual contactless 'smartcard' (refer to this paper for a to a greater extent than thorough discussion).  Software carte emulation is currently available on BlackBerry phones, which offering criterion APIs for apps to register amongst the OS together with procedure carte commands received over NFC. Besides a BlackBerry device, y'all tin work some contactless  readers inwards emulation vogue to emulate NFC tags or a full-featured smart card. Stock Android doesn't (yet) back upwardly software carte emulation, fifty-fifty though the NFC controllers inwards around electrical flow phones have got this capability. Fortunately, recent version of CyanogenMod integrate a set of patches that unlock this functionality of the PN544 NFC controller flora inwards recent Nexus (and other) devices. Let's come across how it plant inwards a flake to a greater extent than detail.

CyanogenMod implementation

Android doesn't render a direct interface to its NFC subsystem to user-level apps. Instead, it leverages the OS's intent together with intent filter infrastructure to permit apps register for a especial NFC trial (ACTION_NDEF_DISCOVERED, ACTION_TAG_DISCOVERED together with ACTION_TECH_DISCOVERED) together with specify additional filters based on tag type or features. When a matching NFC tag is found, interested applications are notified together with i of them is selected to handgrip the event, either past times the user or automatically if it is inwards the foreground together with has registered for foreground dispatch. The app tin together with so access a generic Tag object representing the target NFC device together with work it to recall a concrete tag technology interface such every bit MifareClassic or IsoDep that lets it communicate amongst the device together with work its native features. Card emulation back upwardly inwards CyanogenMod doesn't endeavour to alter or improve Android's NFC architecture, but integrates amongst it past times adding back upwardly for 2 novel tag technologies: IsoPcdA together with IsoPcdB. 'ISO' here is the International Organization for Standardization, which amid other things, is responsible for defining NFC communication standards. 'PCD' stands for Proximity Coupling Device, which is precisely ISO-speak for a contactless reader. The 2 classes comprehend the 2 principal NFC flavours inwards work today (outside of Japan, at least) -- Type Influenza A virus subtype H5N1 (based on NXP technology) together with Type B (based on Motorolla technology). As y'all mightiness have got guessed past times now, the patch reverses the usual roles inwards the Android NFC API: the external contactless reader is presented every bit a 'tag', together with 'commands' y'all shipping from the telephone are genuinely replies to the reader-initiated communication. If y'all have got Google Wallet installed the embedded secure chemical component is activated every bit well, so touching the telephone to a reader would create a potential conflict: should it road commands to the embedded SE or to applications than tin handgrip IsoPcdA/B tags? The CyanogenMod patch handles this past times using Android's native foreground dispatch mechanism: software carte emulation is only enabled for apps that register for foreground dispatch of the relevant tag technologies. So unless y'all have got an emulation app inwards the foreground, all communication would last routed to Google Wallet (i.e., the embedded SE). In exercise though, starting upwardly Google Wallet on ROMs amongst the electrical flow version of the patch mightiness block software carte emulation, so it plant best if Google Wallet is non installed. Influenza A virus subtype H5N1 laid upwardly is available, but non yet merged in CyanogenMod master copy (Updated: instantly merged, should ringlet out amongst CM10 nightlies) .

Both of the newly introduced tag technologies extend BasicTagTechnology together with offering methods to open, banking concern check together with unopen the connexion to the reader. They add together a world transceive() method that acts every bit the principal communication interface: it receives reader commands together with sends the responses generated past times your app to the PCD. Here's a summary of the interface:

abstract course of education BasicTagTechnology implements TagTechnology {     world boolean isConnected() {...}                 world void connect() throws IOException {...}         world void reconnect() throws IOException {...}           world void close() throws IOException {...}      byte[] transceive(byte[] data, boolean raw) throws IOException {...} } 

Now that nosotros know (basically) how it works, let's attempt to work software carte emulation inwards practice.

Emulating a contactless card

As discussed inwards the previous section, to last able to respond to reader commands nosotros ask to register our app for i of the PCD tag technologies together with enable foreground dispatch. This is no different than treatment stock-supported  NFC technologies. We ask to add together an intent filter together with a reference to a applied scientific discipline filter file to the app's manifest:

<activity android:label="@string/app_name"                    android:launchmode="singleTop"                   android:name=".MainActivity"   <intent-filter>     <action android:name="android.nfc.action.TECH_DISCOVERED" />   </intent-filter>    <meta-data android:name="android.nfc.action.TECH_DISCOVERED"                  android:resource="@xml/filter_nfc" /> </activity> 

We register the IsoPcdA tag applied scientific discipline inwards filter_nfc.xml:

<resources>   <tech-list>     <tech>android.nfc.tech.IsoPcdA</tech>   </tech-list> </resources> 

And together with so work the same applied scientific discipline listing to register for foreground dispatch inwards our activity:

public course of education MainActivity extends Activity {    world void onCreate(Bundle savedInstanceState) {     pendingIntent = PendingIntent.getActivity(this, 0, novel Intent(this,                 getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);     filters = novel IntentFilter[] { novel IntentFilter(                 NfcAdapter.ACTION_TECH_DISCOVERED) };     techLists = novel String[][] { { "android.nfc.tech.IsoPcdA" } };   }      world void onResume() {     super.onResume();     if (adapter != null) {       adapter.enableForegroundDispatch(this, pendingIntent, filters,                     techLists);     }   }    world void onPause() {     super.onPause();     if (adapter != null) {       adapter.disableForegroundDispatch(this);     }   }  } 

With this inwards place, each fourth dimension the telephone is touched to an active reader, nosotros volition teach notified via the activity's onNewIntent() method. We tin teach a reference to the Tag object using the intent's extras every bit usual. However, since neither IsoPcdA nor its superclass are component subdivision of Blue Planet SDK, nosotros ask to either construct the app every bit component subdivision of CyanogenMod's source, or, every bit usual, resort to reflection. We select to create a elementary wrapper course of education that calls IsoPcdA methods via reflection, later getting an illustration using the static get() method similar this:

Class cls = Class.forName("android.nfc.tech.IsoPcdA"); Method teach = cls.getMethod("get", Tag.class); // this returns an IsoPcdA illustration tagTech = get.invoke(null, tag); 

Now later nosotros connect() nosotros tin work the transceive() method to respond to reader commands. Note that since the API is non event-driven, y'all won't teach notified amongst the reader command automatically. You ask to shipping a dummy payload to recall the get-go reader command APDU. This tin last a flake awkward at first, but y'all precisely have got to travel on inwards heed that each fourth dimension y'all telephone call upwardly transceive() the side past times side reader command comes inwards via the render value. Unfortunately this way that later y'all shipping your in conclusion response, the thread volition block on I/O waiting for transceive() to return, which only happens later the reader sends its side past times side command, which mightiness last never. The thread volition only halt if an exception is thrown, such every bit when communication is lost later separating the telephone from the reader. Needless to say, this makes writing robust code a flake tricky. Here's how to start off the communication:

// shipping dummy information to teach get-go command APDU // at to the lowest degree 2 bytes to travel on smartcardio happy byte[] cmd = transceive(new byte[] { (byte) 0x90, 0x00 }); 

Writing a virtual PKI applet

Software carte emulation inwards CyanogneMod is express to ISO 14443-4 (used generally for APDU-based communication), which way that y'all cannot emulate cards that operate on a lower-level protocol such every bit MIFARE Classic. This leaves out opening door locks that rely on the carte UID amongst your telephone (the UID of the emulated carte is random) or getting a gratis ride on the subway scheme (you cannot clone a traffic carte amongst software alone), but allows for emulating payment (EMV) cards which work an APDU-based protocol. In fact, the get-go commercial application (cloud-based NFC secure element. We, however, volition await at a different work case: PKI.

PKI has been getting a lot of bad rep due to major CAs getting compromised every other month, together with it has been stated multiple times that it doesn't genuinely work on the Internet. It is nevertheless soundless a valid way of authentication inwards a corporate surroundings where personal certificates are used for anything from desktop login to remote VPN access. Certificates together with associated individual keys are ofttimes distributed on smart cards, sometimes contactless or dual-interface. Since Android instantly has criterion cloud-based NFC secure element. We, however, volition await at a different work case: PKI.

PKI has been getting a lot of bad rep due to major CAs getting compromised every other month, together with it has been stated multiple times that it credential storage which tin last cloud-based NFC secure element. We, however, volition await at a different work case: PKI.

PKI has been getting a lot of bad rep due to major CAs getting compromised every other month, together with it has been stated multiple times that it protected past times hardware on supported devices, nosotros could work an Android telephone amongst software carte emulation inwards house of a PKI card. Let's attempt to write a elementary PKI 'applet' together with an associated host-side customer application to come across if this is indeed feasible.

Influenza A virus subtype H5N1 PKI JavaCard applet tin offers diverse features, but the essential ones are:
  • generating or importing keys
  • importing a world substitution certificate
  • user authentication (PIN verification)
  • signing and/or encryption amongst carte keys
Since nosotros volition last using Android's credential storage to salvage keys together with certificates, nosotros already have got the get-go 2 features covered. All nosotros ask to implement is PIN verification together with signing (which is genuinely sufficient for around applications, including desktop login together with SSL customer authentication). If nosotros were edifice a existent solution, nosotros would implement a good known applet protocol, such every bit i of a major vendor or an opened upwardly one, such every bit the MUSCLE card protocol, so that nosotros tin accept wages of desktop tools together with cryptographic libraries (Windows CSPs together with PKCS#11 modules, such every bit OpenSC). But since this is a proof-of-concept exercise, nosotros tin teach away past times defining our ain mini-protocol together with only implement the bare minimum. We define the applet AID (quite arbitrary, together with may last inwards already inwards work past times someone else, but at that topographic point is genuinely no way to check) together with 2 commands: VERIFY PIN and SIGN DATA. The protocol is summarized inwards the tabular array below:

Virtual PKI applet protocol
CommandCLAINSP1P2LcDataResponse
SELECT00A4040006AID: A00000000101109000/6985/6A82/6F00
VERIFY PIN8001XXXXPIN length (bytes)PIN characters (ASCII)9000/6982/6985/6F00
SIGN DATA8002XXXXSigned information length (bytes)Signed data9000+signature bytes/6982/6985/6F00

The applet behavior is rather simple: it returns a generic fault if y'all attempt to shipping whatsoever commands earlier selecting it, together with and so requires y'all to authenticate past times verifying the PIN earlier signing data. To implement the applet, nosotros get-go handgrip novel connections from a reader inwards the principal activity's onNewIntent() method, where nosotros have an Intent containing a reference to the IsoPcdA object nosotros work to communicate amongst the PCD. We verify that the asking comes from a carte reader, create a wrapper for the Tag object, connect() to the reader together with finally transcend command to the PkiApplet past times calling it's start() method.

Tag tag = (Tag) intent.getExtras().get(NfcAdapter.EXTRA_TAG); List techList = Arrays.asList(tag.getTechList()); if (!techList.contains("android.nfc.tech.IsoPcdA")) {   return; }  TagWrapper tw = novel TagWrapper(tag, "android.nfc.tech.IsoPcdA"); if (!tw.isConnected()) {   tw.connect(); }  pkiApplet.start(tw); 

The applet inwards plough starts a background thread that reads commands until available together with exits if communication amongst the reader is lost. The implementation is non terribly robust, but is plant good plenty for our POC:

Runnable r = novel Runnable() {     world void run() {         attempt {             // shipping dummy information to teach get-go command APDU             byte[] cmd = transceive(new byte[] { (byte) 0x90, 0x00 });             do {                 // procedure commands             } piece (cmd != cipher && !Thread.interrupted());         } grab (IOException e) {             // connexion amongst reader lost             return;         }     } };  appletThread = novel Thread(r); appletThread.start(); 


Before the applet tin last used it needs to last 'personalized'. In our illustration this way importing the individual substitution the applet volition work for signing together with setting a PIN. To initialize the individual substitution nosotros import a PKCS#12 file using the KeyChain API together with shop the individual substitution alias inwards shared preferences. The PIN is protected using 5000 iterations of PBKDF2 amongst a 64-bit salt. We shop the resulting PIN hash together with the tabular array salt inwards shared preferences every bit good together with repeat the calculation against the PIN nosotros have from applet clients to banking concern check if it matches. This avoids storing the PIN inwards clear text, but travel on inwards heed that a brusk numeric-only PIN tin last brute-forced inwards minutes (the app doesn't trammel PIN size, it tin last upwardly to 255 characters (bytes), the maximum size of APDU data). Here's how our 'personalization' UI looks like:


To brand things simple, applet clients shipping the PIN inwards clear text, so it could theoretically last sniffed if NFC traffic is intercepted. This tin last avoided past times using some form of a challenge-response mechanism, similar to what 'real' (e.g., EMV) cards do. Once the PIN is verified, clients tin shipping the information to last signed together with have the signature bytes inwards the response. Since the size of APDU information is express to 255 bytes (due to the unmarried byte length field) together with the applet doesn't back upwardly whatsoever form of chaining, nosotros are express to using RSA keys upwardly to 1024 bits long (a 2048-bit substitution needs 256 bytes). The actual applet implementation is quite straightforward: it does some minimal checks on received APDU commands, gets the PIN or signed information together with uses it to execute the corresponding operation. It together with so selects a condition code based on performance success or failure together with returns it along amongst the outcome information inwards the reply APDU. See the source code for details.

Writing a host-side applet client

Now that nosotros have got an applet, nosotros ask a host-side customer to genuinely brand work of it. As nosotros mentioned above, for a real-world implementation this would last a criterion PKCS#11 or CSP module for the host operating arrangement that plugs into PKI-enabled applications such every bit browsers or electronic mail together with VPN clients. We'll nevertheless create our ain exam Java customer using the Smart Card I/O API (JSR 268). This API comes amongst Sun/Oracle Java SDKs since version 1.6 (Java 6), but is non officially a component subdivision of the SDK, because it is obviously non 'of sufficiently broad interest' according to the JSR practiced grouping (committee BS at its best!). Eclipse goes every bit far every bit to flag it every bit a 'forbidden reference API', so you'll ask to alter fault treatment preferences to compile inwards Eclipse. In exercise though, JSR 268 is a criterion API that plant fine on Windows, Solaris, Linux an Mac OS X (you may have got to laid the sun.security.smartcardio.library arrangement holding to signal to your system's PC/SC library), so we'll work it for our POC application. The API comes amongst classes representing carte readers, the communication channel together with command together with reply APDUs. After nosotros teach a reference to a reader together with and so a card, nosotros tin create a channel together with substitution APDUs amongst the card. Our PKI applet customer is a basic command delineate of piece of work programme that waits for carte availability together with and so precisely sends the SELECT, VERIFY PIN together with SIGN DATA commands inwards sequence, bailing out on whatsoever fault (card reply amongst condition different from 0x9000). The PIN is specified inwards the get-go command delineate of piece of work parameter together with if y'all transcend a certificate file path every bit the 2nd one, it volition work it to verify the signature it gets from the applet. See full code for details, but here's how to connect to a carte together with shipping a command:

TerminalFactory mill = TerminalFactory.getDefault(); CardTerminals terminals = factory.terminals();  Card carte = waitForCard(terminals); CardChannel channel = card.getBasicChannel(); CommandAPDU cmd = novel CommandAPDU(CMD); ResponseAPDU reply = channel.transmit(cmd);  Card waitForCard(CardTerminals terminals)             throws CardException {     piece (true) {         for (CardTerminal ct : terminals                     .list(CardTerminals.State.CARD_INSERTION)) {             render ct.connect("*");         }         terminals.waitForChange();     } } 

And to evidence that this all works, here's the output from a exam run of the customer application:

$ ./run.sh 1234 mycert.crt  Place phone/card on reader to start --> 00A4040006A0000000010101 <-- 9000 --> 800100000431323334 <-- 9000 --> 80020000087369676E206D6521 <-- 11C44A5448... 9000 (128)  Got signature from card: 11C44A5448... Will work certificate from 'mycert.crt' to verify signature  Issuer: CN=test-CA, ST=Tokyo, C=JP  Subject: CN=test, ST=Tokyo, C=JP  Not Before: Midweek November thirty 00:04:31 JST 2011  Not After: Thu November 29 00:04:31 JST 2012  Signature is valid: truthful 

This software implementation comes, of course, amongst the disadvantage that piece the actual individual substitution mightiness last protected past times Android's arrangement substitution store, PIN verification together with other operations non direct protected past times the OS volition last executed inwards a regular app. An Android app, dissimilar a dedicated smart card, could last compromised past times other (malicious) apps amongst sufficient privileges. However, since recent Android devices do have got (some) back upwardly for a Trusted Execution Environment (TEE), the sensitive parts of our virtual applet tin last implemented every bit Trusted Application (TA) running within the TEE. The user-level app would together with so communicate amongst the TA using the controlled TEE interface, together with the safety score of the arrangement could come upwardly really roughly running an actual applet inwards a dedicated SE.

Summary

Android already supports NFC carte emulation using an embedded SE (stock Android) or the UICC (various vendor firmwares). However, both of those are tightly controlled past times their owning entities (Google or MNOs), together with at that topographic point is currently no way for 3rd political party developers to install applets together with create carte emulation apps. An option to SE-based carte emulation is software carte emulation, where an user-level app processes reader commands together with returns responses via the NFC controller. This is supported past times unremarkably deployed NFC controller chips, but is non implemented inwards the stock Andorid NFC subsystem. Recent versions of CyanogneMod nevertheless do enable it past times adding back upwardly for 2 to a greater extent than tag technologies (IsoPcdA together with IsoPcdB) that stand upwardly for contactless readers instead of actual tags. This allows Android applications to emulate pretty much whatsoever ISO 14443-4 compliant contactless carte application: from EMV payment applications to whatsoever custom JavaCard applet. We presented a sample app that emulates a PKI card, allowing y'all to shop PKI credentials on your telephone together with potentially work it for desktop login or VPN access on whatsoever machine equipped amongst a contacltess reader. Hopefully software carte emulation volition travel a component subdivision of stock Android inwards the future, making this together with other carte emulation NFC applications mainstream.
0 Komentar untuk "Droidcedas : Emulating A Pki Smart Carte Alongside Cyanogenmod 9.1"

Back To Top