Full text
Centro Polit´ ecnico Superior Universidad de Zaragoza Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Ingenier ´ ıa en Inform´ atica Proyecto Fin de Carrera Realizado en: Technical University of Denmark Rub´en Romart´ınez Alonso Noviembre 2010 Director: Nicola Dragoni Department of Informatics and Mathematical Modelling Technical University of Denmark Ponente: ´ Alvaro Alesanco Iglesias Departamento de Inform´atica e Ingenier´ıa de Sistemas C.P.S, Universidad de Zaragoza
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Resumen La tecnolog´ıa de Java Card ha evolucionado hasta el punto de permitir correr tanto servidores como clientes Web dentro de una tarjeta inteligente. Adem´as, las tarjetas inteligentes actuales permiten tener instaladas en si mismas m´ultiples aplicaciones, las cuales pueden ser descargadas y actualizadas a lo largo de la vida de la tarjeta. Esta nueva caracter´ıstica de las tarjetas inteligentes las hace muy atractivas para ambos usuarios y desarrolladores de tarjetas inteligentes debido a las nuevas posibilidades que estas proveen. El uso de estas tarjetas inteligentes no supone ning´un problema cuando las aplicaciones han sido instaladas antes de que la tarjeta haya sido sellada porque las interacciones entre las aplicaciones instaladas han sido comprobadas a priori con sus respectivas pol´ıticas. El problema surge cuando las aplicaciones pueden ser descargadas din´amicamente y la seguridad de la informaci´on intercambiada entre estas aplicaciones no puede ser asegurada. Por ello, el uso de las tarjetas inteligentes como tarjetas multi-aplicaci´on es todav´ıa extremadamente raro debido a que las aplicaciones en ellas instaladas, las cuales contienen informaci´on sensible, provienen de diferentes proveedores. Debido a esto es necesario un m´etodo que controle las posibles interacciones entre las aplicaciones instaladas. Dado que los actuales modelos y t´ecnicas de seguridad para tarjetas inteligentes no soportan este tipo de evoluci´on, es necesario un nuevo m´etodo donde el comportamiento referente a la seguridad se ajuste con la pol´ıtica de seguridad de la tarjeta anfitriona en caso de nuevas descargas o actualizaciones. La conformidad entre el comportamiento de la tarjeta y la pol´ıtica de la tarjeta debe ser comprobada durante la petici´on de instalaci´on o de actualizaci´on evitando la necesidad de los costosos m´etodos de monitorizaci´on en tiempo de ejecuci´on. Adem´as deber´a asegurarse que no existir´an fugas de informaci´on en su intercambio entre las aplicaciones. Este nuevo modelo propuesto, que ser´a llamado seguridad por contrato (SxC usando las siglas en ingl´es) tratar´a con los posibles cambios tanto en los contratos de las aplicaciones como en los de la pol´ıtica de la plataforma din´amicamente. En el presente PFC se presenta y desarrolla un modelo de pol´ıticas y contratos as´ı como los algoritmos que se encargar´an de asegurar la certificaci´on de las aplicaciones. Tambi´en, debido a la limitaci´on de memoria en las tarjetas inteligentes el sistema ser´a testeado con un ejemplo real. i
Agradecimientos I would like to thank to my supervisor Nicola Dragoni for give me the opportunity of developing this project which has allowed me to dive into the world of smart cards. What is collected in this thesis is information that I found in articles or in books. A special thanks to the authors listed in the bibliography page. Without them, this thesis would have taken years off my life (and I don’t have many to spare). Thanks also to all the people who have shared with me this amazing year in Denmark; I’m never going to forget you. A´ Alvaro Alesanco por la ayuda aportada en el desarrollo del proyecto y por aconsejarme que es mejor hacer las cosas de un modo correcto aunque haya que sacrificar algo que realizarlas aprisa y peor cuando las consecuencias pueden acarrear peores problemas. Last but not least I would like to thank my parents their support during these months abroad. They guide me when I was lost in a foreigner country and best of all they gave me the unique chance to be a scientist for the science, with the only objective of knowledge, which probably won’t be the same never again. iii
´ Indice 1. Introducci´on 1 1.1. TarjetasInteligentes .................................... 1 1.2. ContextodelProblema................................... 2 1.3. Soluci´onAportada ..................................... 2 1.4. Dise˜noyresultados..................................... 3 1.5. Descripci´on del Contenido . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 2. An´alisis del Problema 5 2.1. Introducci´on......................................... 5 2.2. SeguridadporContrato .................................. 5 2.3. EsquemadeSxC ...................................... 6 2.4. Jerarqu´ıa de Modelos Pol´ıtica/Contrato . . . . . . . . . . . . . . . . . . . . . . . . . 7 2.5. LimitacionesdelEntorno ................................. 7 3. Dise˜no de la Soluci´on 9 3.1. MarcodeSxC........................................ 9 3.2. Soportando la Evoluci´on de las Aplicaciones con SxC . . . . . . . . . . . . . . . . . . 9 4. Implementaci´on del Nivel 0 de SxC 17 4.1. Tecnolog´ıaAdoptada.................................... 17 4.2. Implementaci´on....................................... 17 4.3. Rendimiento ........................................ 20 5. Conclusiones y Trabajo Futuro 27 5.1. Resultados.......................................... 27 5.2. Conclusiones ........................................ 27 5.3. TrabajoFuturo....................................... 28 5.4. ProblemasEncontrados .................................. 28 5.5. Incidencias ......................................... 29 5.6. Gesti´on del Tiempo y del Esfuerzo . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 A. Smart Card Technology 31 A.1.Background......................................... 31 A.2.Architecture......................................... 32 A.3. Multi-application Smart Cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 B. Security of Smart Cards 43 B.1.HardwareSecurity ..................................... 43 B.2.SoftwareSecurity...................................... 44 v
C. Supporting Applications’ Evolution in Multi-application Smart Cards 47 C.1. Multi-application Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 C.2.State-of-the-Art....................................... 49 D. Security by Contract 51 D.1.SxCFramework....................................... 51 D.2. Supporting Applications’ Evolution by SxC . . . . . . . . . . . . . . . . . . . . . . . 53 E. Implementation of SxC Level 0 61 E.1.Technologyadopted .................................... 61 E.2.Implementation....................................... 62 E.3.Performance......................................... 72 F. Conclusion 81 G. Battery tests 83 G.1. Check of compliance of new application . . . . . . . . . . . . . . . . . . . . . . . . . 83 G.2. Check of removal an application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88 G.3. Check of compliance of AppPolicy update . . . . . . . . . . . . . . . . . . . . . . . . 90 G.4. Check of new contract compliance with the policy . . . . . . . . . . . . . . . . . . . 93 vi
Lista de Figuras 2.1. EsquemadetrabajoSxC.................................. 6 5.1. Distribuci´ondetiempos .................................. 30 A.1. Contacts of a typical contact smart card . . . . . . . . . . . . . . . . . . . . . . . . . 31 A.2. Inside a contactless smart card . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 A.3.Smartcardchip....................................... 33 A.4. Global Platform card architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36 A.5. Multiapplication card architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 A.6.APDUexchange ...................................... 39 A.7. Objects in volatile memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39 A.8. Objects in non-volatil memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 A.9.Splitvirtualmachine.................................... 40 vii
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso 5. Anexos donde se incluye la memoria en ingl´es realizada para la presentaci´on de la misma en Dinamarca la cual incluye la bater´ıa de pruebas realizadas para el dise˜no del sistema. 4
Cap´ıtulo 2 An´alisis del Problema 2.1. Introducci´on Actualmente han surgido una gran cantidad de entornos donde las aplicaciones cooperan y comparten informaci´on y donde, adem´as, estas aplicaciones pueden ser instaladas o modificadas a˜nadiendo o eliminando algunas funcionalidades durante la vida del sistema. Esto es posible dado que en estos ambientes o la seguridad de la informaci´on instalada y compartida no es muy importante o se dispone de la suficiente potencia computacional para poder ejecutar herramientas que controlen la seguridad de la informaci´on compartida y almacenada en tiempo real. El problema surge cuando la informaci´on almacenada es la parte m´as importante del sistema y adem´as no se dispone de suficiente potencia para usar una de esas herramientas, as´ı que la seguridad de la informaci´on no se puede asegurar. Este es el problema de las tarjetas inteligentes, los ordenadores m´as extendidos en la actualidad y que son usados en multitud de sistemas como tarjetas de transporte, tarjetas bancarias, tarjetas de acceso, etc. Como estas tarjetas inteligentes no soportan los costosos m´etodos que funcionan en tiempo real, la soluci´on escogida para este sistema pasa por el desarrollo de est´andares que ayuden a resolver los problemas de las tarjetas inteligentes multi-aplicaci´on. Los est´andares m´as comunes son Java Card, GlobalPlatform y MULTOS. Aunque estos est´andares fueron desarrollados para que diferentes proveedores pudieran cooperar en la misma tarjeta, en la actualidad en la mayor´ıa de las tarjetas usadas como tarjetas multi-aplicaci´on las aplicaciones provienen del mismo proveedor pues el problema sigue siendo la informaci´on compartida. Como las aplicaciones pueden ser a˜nadidas, modificadas o eliminadas en tiempo real, es necesario poder asegurar a los emisores de las aplicaciones que los requisitos que se cumplir´an cuando su aplicaci´on fue a˜nadida seguir´an cumpli´endose a lo largo de la vida de su aplicaci´on. Esta informaci´on est´a ampliada en el Ap´endice C con ejemplos y con el estado del arte explicados en detalle. 2.2. Seguridad por Contrato La idea de Seguridad por Contrato (SxC) surge como soluci´on al problema de intercambio ilegal de informaci´on entre aplicaciones, tanto en el momento de carga de las aplicaciones en la tarjeta como en las posibles modificaciones despu´es de la emisi´on de esta. El modelo de SxC surge la propuesta development-by-contract y de la idea Model Carrying Code (MCC) propuesto por Sekar et al. [26] dise˜nada y probada sistemas de c´odigo m´ovil y adaptada para tarjetas inteligentes. En este modelo, la aplicaci´on llega a la plataforma con un contrato, que 5
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso es una descripci´on del comportamiento de la aplicaci´on. La tarjeta inteligente dispone de la pol´ıtica de la plataforma, la cual describe el comportamiento de seguridad de la tarjeta, que es comparada con el contrato de la aplicaci´on para ver si ambos encajan. En caso de ser as´ı, la instalaci´on o actualizaci´on de la aplicaci´on es aceptada. Gracias a este m´etodo que comprueba que el contrato encaja con la pol´ıtica de la tarjeta, se evita el uso de los costosos m´etodos de monitorizaci´on en tiempo real que tendr´ıan que realizarse en un sistema externo a la tarjeta. Los problemas que se desean resolver son ([24]): 1. (Seguridad Estable) Una aplicaci´on no puede interactuar con aplicaciones prohibidas que ya est´an instaladas en la tarjeta inteligente 2. (Funcionalidad Estable) Un cambio din´amico no debe afectar a la ejecuci´on correcta de una aplicaci´on en la tarjeta inteligente. En particular, una aplicaci´on debe poder funcionar despu´es de uno de estos cambios en la tarjeta. Adici´on de una nueva aplicaci´on a la tarjeta. Actualizaci´on de una aplicaci´on ya existente. Cambios en la pol´ıtica de seguridad de la plataforma de la tarjeta. Eliminaci´on de una aplicaci´on existente en la tarjeta. 2.3. Esquema de SxC El esquema de trabajo que sigue el model de SxC es el representado en la figura 2.1. Como se puede observar, primero se comprueba que la evidencia es correcta, lo que puede hacerse mediante una firma digital de confianza o, para el caso de las tarjetas inteligentes como una prueba de que el c´odigo satisface el contrato. Una vez comprobado que esta evidencia es fidedigna, la plataforma comprueba que este se ajusta a la pol´ıtica que la tarjeta quiere hacer cumplir. En casi afirmativo, la aplicaci´on puede ser ejecutada asegurando que durante su ejecuci´on solamente las interacciones declaradas ser´an permitidas. Figura 2.1: Esquema de trabajo SxC 6
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso 2.4. Jerarqu´ıa de Modelos Pol´ıtica/Contrato Debido a la existencia de diferentes sistemas en los que este modelo puede ser aplicado se definen tanto la pol´ıtica como los contratos utilizando diferentes niveles de expresi´on teniendo en cuenta la potencia computacional requerida para la ejecuci´on del modelo como las limitaciones de expresividad dadas por el entorno. De este modo, en los niveles m´as bajos se obtienen beneficios computacionales pero perdiendo expresividad en la definici´on de contratos y pol´ıticas. L0: Aplicaciones como servicios. Este nivel modela aplicaciones como una lista de servicios requeridos y provistos. L1: Flujo de control permitido. Este nivel provee un grafo G1(A) de la aplicaci´on, donde los v´ertices son los estados de la aplicaci´on y los arcos representan la invocaci´on de diferentes servicios. Con este modelo se puede conseguir un control de acceso basado en el historial y un control del intercambio de informaci´on m´as fino. L2: Flujo de control permitido y deseado. Este nivel a˜nade al anterior las nociones de estados correctos e incorrectos. Puede ser necesario si se quiere comprobar si la eliminaci´on de una aplicaci´on (o un cambio en la pol´ıtica) no interfiere en funcionamiento de otras aplicaciones. L3: Flujo completo de informaci´on. Este nivel extiende el anterior considerando tambi´en el intercambio de informaci´on entre las variables. Moverse de un nivel a otro superior supone a˜nadir m´as detalle en la especificaci´on del contra- to/pol´ıtica, modelar de forma m´as precisa el comportamiento de las aplicaciones corriendo en la tarjeta. 2.5. Limitaciones del Entorno Debido a las limitaciones computacionales presentadas por las tarjetas inteligentes, en los niveles L1, L2 y L3 la comparaci´on contrato/pol´ıtica debe realizarse en el exterior de la tarjeta recayendo en la necesidad de securizar la comunicaci´on mediante m´etodos criptogr´aficos as´ı como buscar una tercera parte de confianza donde se ejecute esta comprobaci´on. Por ello, el nivel 0 es el seleccionado para la implementaci´on de este modelo en la tarjetas inteligentes. Debido a que las actuales definiciones del nivel 0 no especifican el comportamiento real de las aplicaciones si no s´olo el intercambio de informaci´on entre las aplicaciones, ser´a necesario otra definici´on que solucione este problema. 7
Cap´ıtulo 3 Dise˜no de la Soluci´on Como se ha nombrado en el cap´ıtulo anterior, la actual definici´on del nivel cero dada por Dragoni et al en [24] no da una representaci´on real del comportamiento de las aplicaciones de la tarjeta, por lo que es necesario la modificaci´on de este modelo con el fin de obtener un modelo donde la seguridad de la informaci´on entre las aplicaciones pueda ser asegurado. 3.1. Marco de SxC Como se explica en el cap´ıtulo anterior, el modelo de SxC se basa en comprobar la correcta correspondencia entre las distintas aplicaciones y la pol´ıtica de la tarjeta. Un contrato es definido como la descripci´on formal completa del comportamiento de una aplicaci´on en lo que respecta a acciones de seguridad. En este contrato se almacena tanto el comportamiento de esta aplicaci´on con respecto a las dem´as como el comportamiento deseado de las dem´as hacia ella misma. El contrato de una aplicaci´on es proporcionado por el emisor de la aplicaci´on. As´ı mismo, se define pol´ıtica de seguridad como una especificaci´on formal completa del comportamiento de las aplicaciones que van a ser ejecutadas en la plataforma y el cual se refiere a acciones que conciernen a la seguridad. La pol´ıtica inicial de la tarjeta es definida por el emisor de la tarjeta y actualizada con la informaci´on proveniente de todos los emisores de aplicaciones de la tarjeta. Una vez definidos los t´erminos contrato y pol´ıtica de las tarjetas, se define la correspondencia contrato-pol´ıtica como: Definici´on (Correspondencia contrato-pol´ıtica):el contrato de una aplicaci´on encaja con la pol´ıtica de la plataforma si no hay intercambio ilegal entre la aplicaci´on a instalar y las aplicaciones ya instaladas en la tarjeta. 3.2. Soportando la Evoluci´on de las Aplicaciones con SxC Debido a la falta de expresividad de la definici´on actual del nivel 0, es necesario realizar una nueva definici´on tanto del contrato como de la pol´ıtica de la tarjeta para resolver este problema y poder asegurar que la informaci´on almacenada e intercambiada en la tarjeta no va a ser comprometida. 3.2.1. Contrato de las Aplicaciones Como se puede ver en la Figura 2.1, el contrato provisto por el emisor de la aplicaci´on es comparado con el c´odigo de la aplicaci´on para comprobar su correspondencia, por lo que es l´ogico pensar que este contrato pueda ser extra´ıdo directamente del c´odigo de la aplicaci´on. De este modo, las ´unicas restricciones existentes para la invocaci´on de alguno de los servicios que esta aplicaci´on provee son las impuestas por el c´odigo. Puesto que es normal que los due˜nos de las aplicaciones apliquen restricciones sobre qui´en puede usar los servicios que sus aplicaciones proveen y es l´ogico que esta informaci´on se encuentre en el contrato, la informaci´on del contrato es dividida en dos 9
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso partes: el claim y la pol´ıtica de la aplicaci´on. El claim describe el comportamiento de la aplicaci´on con el resto de aplicaciones de la tarjeta, mientras que la pol´ıtica de la aplicaci´on se refiere a c´omo las otras aplicaciones que comparten servicios dentro de la tarjeta deben interactuar con ella. Este ´ultimo es establecido por los proveedores de la aplicaci´on, los due˜nos de los dominios seguros o las autoridades controladoras. Para cada aplicaci´on en la tarjeta, el claim es un par (servicios invocados, servicios provistos). Los servicios invocados representan los servicios que el c´odigo de estas aplicaciones van a usar durante su ejecuci´on en la tarjeta. Por otra parte, los servicios provistos forman un subset de los servicios que la aplicaci´on ha implementado y suministra a la plataforma por lo que otras aplicaciones pueden usar. La pol´ıtica de la aplicaci´on tambi´en es definida como un par (servicios permitidos, servicios necesitados). En este caso los servicios necesitados son un subset de los servicios invocados por la aplicaci´on. Estos servicios ser´an necesarios durante la invocaci´on de la aplicaci´on. Por otra parte, los servicios permitidos es un set de pares, donde uno de los elementos es un servicio del set de prove´ıdos y el otro el identificador de la aplicaci´on a la que se le permite el uso. Esta aplicaci´on puede estar o no instalada en la tarjeta. Con esta clasificaci´on, un contrato queda representado como: Aplicaci´on Claim Pol´ıtica Provistos Invocados Necesarios Permitidos Medicina@Farmacia lista medicinas - - (lista medicinas, ap1@Farmacia) (lista medicinas, ap2@Hospital) Tabla 3.1: Ejemplo de Contrato Tras estas definiciones, el intercambio de informaci´on entre aplicaciones puede ser explicado usando los set concretos de servicios. Existe intercambio de informaci´on entre dos aplicaciones cuando el servicio provisto por una de ellas es invocado por la otra. Imaginemos dos aplicaciones A y B, existir´a un intercambio de informaci´on entre ellas si existe una entrada en la lista de servicios provistos de la aplicaci´on A llamada servicioA y una entrada en la lista de servicios invocados de la aplicaci´on B llamada servicioA. Pero aunque exista un intercambio de informaci´on entre estas aplicaciones, no significa que este intercambio sea legal. Un intercambio legal se define como: Definici´on (Intercambio legal):Un intercambio de informaci´on es legal cuando la aplicaci´on que provee el servicio permite a las aplicaciones que lo invocan usarlo. Con esto se puede concluir que la definici´on del Contrato puede ayudarnos a tratar con ambos: fallos funcionales (P2) y fallos de seguridad (P1) en la plataforma. Los posibles cambios junto con los posibles fallos derivados de estos son: Cambios en el Claim: •A˜nadir un servicio a la lista de servicios invocados puede provocar un fallo de seguridad debido a que puede ser que esa aplicaci´on no tenga permiso para usar el servicio. •Eliminar un servicio de la lista de servicios invocados no puede provocar ning´un fallo de seguridad. •A˜nadir un servicio a la lista de servicios provistos puede provocar un fallo funcional porque este puede ser invocado por una aplicaci´on instalada en la plataforma pero no tener permitido su uso. •Eliminar un servicio de la lista de servicios provistos puede provocar un fallo funcional debido a que es posible que alguna aplicaci´on necesite el servicio provisto. 10
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Cambios en la pol´ıtica de la aplicaci´on: •A˜nadir un servicio a la lista de servicios necesarios puede provocar un fallo funcional si el servicio a˜nadido no es provisto por las aplicaciones de la plataforma. •Eliminar un servicio de la lista de servicios necesario no puede provocar un fallo funcional. •A˜nadir un par (servicio, aplicaci´on) a la lista de servicios permitidos no puede provocar un fallo funcional. •Eliminar un par (servicio, aplicaci´on) de la lista de servicios permitidos puede provocar un fallo de seguridad si la aplicaci´on referenciada en el par usa el servicio referenciado. 3.2.2. Pol´ıtica de Seguridad de la Tarjeta Como se ha dicho con anterioridad, la pol´ıtica de seguridad inicial de la tarjeta es provista por el emisor de la tarjeta. Debido a la capacidad de evoluci´on de las tarjetas despu´es de la emisi´on es necesaria la definici´on de una pol´ıtica general para tarjetas inteligentes. Esta pol´ıtica debe estar formada y provista por todos los participantes en la tarjeta (proveedores de aplicaciones, due˜nos de dominios seguros y autoridades controladoras). Cuando un nuevo participante llega a la tarjeta, primero ser´a necesario comprobar que su pol´ıtica encaja con el resto de pol´ıticas de sus compa˜neros y, segundo, deber´a proveer sus propios requerimientos para las aplicaciones de otros participantes e incluir estos en la pol´ıtica de la tarjeta. Adem´as, ser´a posible la actualizaci´on de la pol´ıtica de la tarjeta por parte de los participantes modificando sus propias pol´ıticas, siempre y cuando esta modificaci´on siga ajust´andose a la pol´ıtica anterior. Por lo tanto, se define pol´ıtica de la tarjeta como la combinaci´on de las pol´ıticas de las aplicaciones almacenadas en la tarjeta. Esta informaci´on puede ser reordenada en dos sets, PolNeeds y PolAllows, dependiendo en el objetivo de los requerimientos de seguridad. El set PolNeeds se representa como {Dependientes1,..., Dependientesn}donde cada elemento es una lista de las aplicaciones que necesitan alguno de los servicios que la Aplicacioniprovee. Para el caso del set PolAllows, este es representado como {Permitidos1,..., Permitidosn}donde cada elemento es la lista de servicios permitidos de la correspondiente aplicaci´on. 3.2.3. Algoritmos para la Evoluci´on a Tarjetas Inteligentes Multi-aplicaci´on Una vez que el problema ha sido expuesto, los algoritmos desarrollados para poder resolver el problema van a ser explicados. Estos algoritmos est´an divididos en dos clases, los algoritmos que actualizan la pol´ıtica y los algoritmos que comprueban la conformidad entre la actual pol´ıtica y los posibles cambios a realizar (actualizaci´on del contrato de una aplicaci´on, instalaci´on y eliminaci´on de aplicaciones). Los algoritmos del primer grupo son: Actualizaci´on de la pol´ıtica al a˜nadir una aplicaci´on nueva Actualizaci´on de la pol´ıtica al eliminar una aplicaci´on de la plataforma Actualizaci´on de la pol´ıtica al ocurrir un cambio en la pol´ıtica de una aplicaci´on Y en el segundo grupo: Comprobar la conformidad al a˜nadir una nueva aplicaci´on. Comprobar la conformidad al eliminar una aplicaci´on. 11
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Comprobar la conformidad al modificar la pol´ıtica de la aplicaci´on. Comprobar la conformidad al modificar el contrato de una aplicaci´on. El pseudoc´odigo de estos algoritmos est´a presentado en el Ap´endice D. 3.2.3.1. Comprobaci´on de Correspondencia de una Nueva Aplicaci´on/ Check of Compliance of New Application Cuando una nueva aplicaci´on quiere ser instalada en la tarjeta inteligente es necesario comprobar si el contrato de la aplicaci´on encaja con la actual pol´ıtica de la plataforma. Para realizar esto, el Algoritmo 1 realiza tres comprobaciones para asegurar que el nuevo contrato no puede provocar ning´un fallo. La primera parte comprueba, por cada servicio que la nueva aplicaci´on tiene en la lista de servicios invocados, si existe alguna aplicaci´on en la plataforma que lo provee y que le permite usarlo. Si ninguna aplicaci´on en la plataforma provee este servicio, su uso no puede producir ning´un fallo y se comprueba el siguiente servicio. Si la aplicaci´on que provee el servicio que la aplicaci´on necesita no le deja usarlo (no hay una entrada en la lista de permitidos con el servicio y el identificador de la aplicaci´on), la aplicaci´on no cumple las condiciones de conformidad con la pol´ıtica y se rechaza la instalaci´on. Por otra parte, si el servicio es provisto y la aplicaci´on que lo provee tambi´en le permite usarlo, se comprueba el siguiente servicio hasta terminar con todos y seguir con el siguiente paso. En la segunda parte se comprueban los servicios de la lista de servicios necesitados. Para esta comprobaci´on s´olo es necesario mirar si todos los servicios de esta lista est´an provistos por una de las aplicaciones en la plataforma. Si todos lo est´an, se comprueba el siguiente paso y, si no, se cancela la instalaci´on. Finalmente, para la tercera parte, los servicios provistos por la aplicaci´on son comprobados. Si los servicios provistos no son invocados por ninguna aplicaci´on en la plataforma, la aplicaci´on es instalada. Pero si alg´un servicio es invocado, la aplicaci´on que lo invoca debe tener permiso para ello. Si lo posee, se contin´ua con la siguiente, en caso contrario la instalaci´on se cancela. Algorithm 1 Check of Compliance of New Application Require: ContractA, Policy. Ensure: True if the application is compliance, false otherwise. 1: for sAservice in CallsAdo 2: for Ajin Λ do 3: for sjin ProvidesAjdo 4: if sA=sjAND (sA, A) 6∈ AllowsAjthen 5: return false 6: for sAservice in NeedsAdo 7: for Ajin Λ do 8: if sA∈ProvidesBAND B6∈ Λthen 9: return false 10: for sAservice in ProvidesAdo 11: for Ajin Λ do 12: if sA∈CallsAjAND (sA, Aj)6∈ AllowsAjthen 13: return false 14: return true 12
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso 3.2.3.2. Comprobaci´on de la Eliminaci´on de una Aplicaci´on/ Check of Removal of Application El Algoritmo 2 es el responsable de comprobar que no hay aplicaciones en la plataforma que dependa de la aplicaci´on que va a ser eliminada. Para conseguir esto s´olo se necesita comprobar que la lista Dependientes de esta aplicaci´on est´a vac´ıa. Si esta lista esta vac´ıa porque ninguna aplicaci´on necesita los servicios que ella provee, la aplicaci´on ser´a eliminada de la plataforma. En caso contrario se cancela su eliminaci´on para evitar fallos funcionales. Algorithm 2 Check of Removal of Application Require: Application A, Policy. Ensure: True if it is possible to remove the application, false otherwise. 1: for e element in PolNeeds do 2: if e.ID = A.ID then 3: if e.Application list = ∅then 4: return true 5: else 6: return false 7: return true 3.2.3.3. Comprobaci´on de Correspondencia de la Actualizaci´on de la Pol´ıtica de una Aplicaci´on/ Check of Compliance of AppPolicy Update Cuando un proveedor de aplicaciones quiere modificar la pol´ıtica de una de sus aplicaciones a˜nadiendo o eliminando servicios, ser´a necesario comprobar mediante el Algoritmo 3 que esta pol´ıtica est´a conforme con la pol´ıtica de la tarjeta. Para ello se tendr´an que comprobar los casos explicados con anterioridad sobre que cambios en la pol´ıtica de las aplicaciones puede provocar errores en el funcionamiento. Primero se comprueban los nuevos servicios a˜nadidos a la lista de servicios necesarios. Es necesario realizar esta comprobaci´on porque cada servicio de esta lista debe ser provisto por una aplicaci´on en la plataforma. Para ello, se extraer´an las diferencias entre la antigua lista de servicios y la nueva y se comprobar´a si para cada uno de estos servicios hay una aplicaci´on que los provee. Si no es as´ı, la actualizaci´on es cancelada. A continuaci´on se comprueban los pares eliminados de la lista de permisos. Si alguno de los servicios de los pares de esta lista est´a todav´ıa siendo invocado por alguna aplicaci´on en la plataforma, la aplicaci´on no puede ser eliminada y se cancela la acci´on. En cambio, si ninguno de los servicios de los pares eliminados es usado, la actualizaci´on puede ser realizada. 3.2.3.4. Comprobaci´on de Correspondencia de un Nuevo Contrato con la Pol´ıtica/ Check of New Contract Compliance with the Policy Si, en vez de modificar s´olo la pol´ıtica de la aplicaci´on se modifica todo el contrato, a parte de las comprobaciones anteriores es necesario comprobar las modificaciones correspondientes al Claim (Algoritmo 4). En cuanto a los cambios en el Claim, primero se compraban las modificaciones en la lista de servicios invocados. Para cada servicio a˜nadido a esta lista es necesario confirmar si este es proporcionado por alguna aplicaci´on en la plataforma. Si no es proporcionado no hay que comprobar nada m´as y se sigue con el siguiente servicio, pero si es proporcionado hay que comprobar tambi´en que la aplicaci´on que lo provee le permite usarlo. En caso de no ser as´ı se cancela la actualizaci´on. Por ´ultimo, se tienen que comprobar las diferencias en la lista de servicios provistos. En este caso hay que comprobar ambos, los nuevos servicios a˜nadidos y los antiguos eliminados. En el primero 13
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso 2. manage policy update remove app esta funci´on ´unicamente extrae el identificador de la aplicaci´on a eliminar de la tarjeta e invoca a la funci´on correspondiente. Si ninguna aplicaci´on depende de ella la aplicaci´on ser´a eliminada de la tarjeta. En caso de no existir la aplicaci´on, se devuelve un error al sistema externo de la tarjeta. Este applet tambi´en almacena la informaci´on que en el sistema real se almacena en la tarjeta: la pol´ıtica de la plataforma. Tambi´en tiene la referencia a la clase que implementa las funciones del protocolo desarrollado. 4.2.3.1. Problemas Los principales problemas surgidos durante la implementaci´on del sistema son debido a las limitaciones de Java Card en el uso de las funciones que proporciona. En el caso de la clase Vector, algunas funciones que podr´ıan haber facilitado la implementaci´on del sistema no est´an presentes. Por ejemplo, de haber existido la funci´on clone(), los constructores de las estructuras que poseen estos habr´ıan sido m´as sencillos. Solamente asignando a las variables de la clase los datos de entrada con la funci´on clone, no ser´ıa necesario la implementaci´on de los bucles. Otro de los problemas es que, al disponer de algunas estructuras dobles dentro de los vectores como por ejemplo con Permitidos, no es posible el uso de las funciones suministradas por la clase Vector. 4.2.4. Bater´ıa de Tests Para cada algoritmo implementado se han realizado una serie de tests en los cuales se suministran distintos tipos de entradas (correctas e incorrectas) para comprobar si los algoritmos funcionan como han sido definidos siguiendo la especificaci´on realizada de SxC. En la Tabla 4.1 se muestran los resultados de dichas pruebas. Adem´as, dichas pruebas pueden ser encontrados en el Ap´endice G donde se muestran los comandos APDU de entrada y se explican en detalle los resultados obtenidos. 4.3. Rendimiento Dado que uno de los principales problemas en las tarjetas inteligentes es el espacio disponible para almacenar la informaci´on, esta debe ser tenida en cuenta a la hora de asegurar que lo implementado en el simulador encajar´a en un entorno real. Para comprobar el espacio usado por el applet desarrollado se han implementado varios algoritmos que comprobar´an el espacio de cada estructura y del sistema completo. El comprobador de memoria ha sido implementado en la clase MemoryTestBench, la cual se compone de dos algoritmos. El primero de ellos se llama calculate- MemoryUsage y es el encargado de calcular la memoria usada por la clase recibida como par´ametro. Para ello, se inicializa tanto la variable sobre la que va a crear el objeto a testear y las variables que van a almacenar el espacio ocupado antes de crear el objeto y despu´es. Una vez inicializadas, se llama al recolector de basura para que elimine de la memoria toda la informaci´on que no esta siendo usada y se mide el espacio ocupado. Despu´es de esto se crea el objeto a medir, se vuelve a llamar al recolector de basura y se vuelve a medir el espacio ocupado. Restando estos dos valores se obtiene el espacio que ocupa el objeto a medir, el cual es devuelto al algoritmo principal que mostrar´a los resultados. Para poder comprobar las diferentes estructuras instanciadas en el programa, se crea una interfaz publica llamada Object test, la cual tiene una funci´on abstracta llamada makeObject y que se encarga de devolver la instancia del objeto a medir. Para cada una de las estructuras implementadas se crea una nueva interfaz que extiende Object test donde se implementa la clase a medir. Por ´ultimo, la clase Main es la que crea la instancia de la clase memoryTestBench y la que invoca a cada una de las clases mostrando por pantalla el espacio ocupado por cada una de ellas. 20
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Tabla 4.1: Resultado Pruebas Nombre Parte Tipo de Prueba Resultado Servicios Invocados Los servicios invocados no est´an presentes en la tarjeta Aplicaci´on Instalada Los servicios invocados est´an presentes y pueden ser usados Aplicaci´on Instalada Los servicios invocados est´an presentes pero no pueden ser usados Aplicaci´on Rechazada Check of compliance Servicios Necesarios Los servicios necesarios est´an provistos por la tarjeta Aplicaci´on Instalada of new application Los servicios necesarios no est´an provistos por la tarjeta Aplicaci´on Rechazada Servicios Provistos Los servicios provistos no son invocados Aplicaci´on Instalada Los servicios provistos son invocados por una aplicaci´on sin permiso Aplicaci´on Rechazada Los servicios provistos son invocados por una aplicaci´on con permiso Aplicaci´on Instalada Check of removal Tiene dependencias La aplicaci´on a eliminar tiene servicios que otras aplicaciones necesitan Aplicaci´on No Eliminada an application No tiene dependencias La aplicaci´on a eliminar no tiene otras aplicaciones que la invoquen Aplicaci´on Eliminada A˜nadir servicios necesarios Los servicios a˜nadidos est´an provistos por la tarjeta Actualizaci´on Aceptada Check of compliance Los servicios a˜nadidos no est´an provistos por la tarjeta Actualizaci´on Rechazada of AppPolicy update Eliminar permisos La aplicaci´on a la que se le quitan los permisos no est´a en la tarjeta Actualizaci´on Aceptada La aplicaci´on existe pero no usa el servicio del permiso Actualizaci´on Aceptada La aplicaci´on existe y usa ese servicio Actualizaci´on Rechazada A˜nadir invocaciones El servicio a˜nadido no est´a provisto por la tarjeta Actualizaci´on Aceptada El servicio a˜nadido est´a provisto y tiene permisos para usarse Actualizaci´on Aceptada El servicio a˜nadido est´a provisto pero no tiene permisos Actualizaci´on Rechazada Check of new Contract Servicio eliminado El servicio es necesario por otra aplicaci´on Actualizaci´on Rechazada compliance with de Policy El servicio no es necesario para ninguna aplicaci´on Actualizaci´on Aceptada Servicio a˜nadido El servicio a˜nadido no es invocado Actualizaci´on Aceptada El servicio a˜nadido es invocado pero no tienen permisos Actualizaci´on Rechazada El servicio a˜nadido es invocado y tienen permisos Actualizaci´on Aceptada 21
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso 4.3.1. Resultados En esta secci´on se realiza un estudio sobre las necesidades del espacio necesario de cada estructura de datos implementada en el sistema. Estos datos son introducidos en varias tablas correspondientes a cada una de las estructuras las cuales pueden encontrarse en el Ap´endice E. Tras esto, se realiza un estudio del espacio necesario de un sistema real. 4.3.1.1. Cadenas Aunque las cadenas son internalizadas por Java, lo que significa que s´olo una de las instancias de la misma cadena es guardada en memoria, es necesario saber el espacio que ocupar´ıa cada una de ellas en el peor caso para poder maximizar el espacio requerido. Una cadena almacena: 8 Bytes para la clase 16 Bytes para la cadena de caracteres 4 Bytes para el Offset 4 Bytes para la longitud de la cadena 4 Bytes para el c´omputo 4 Bytes para el Hash 2 Bytes para cada car´acter en la cadena Por lo tanto, una cadena de 6 caracteres ocupar´a 40 bytes para almacenar la informaci´on de la cadena y 12 bytes para la informaci´on en si. Para la medida de espacio de cada estructura las cadenas no han sido tenidas en cuenta hasta el c´alculo final del sistema. 4.3.1.2. Permitidos Permitidos es una estructura que almacena dos cadenas de caracteres. Los resultados pueden ser vistos en la Tabla E.1 y muestran que se necesitan 8 bytes para la clase y 8 bytes m´as para los punteros a las cadenas. 4.3.1.3. Claim Claim es una estructura que almacena dos vectores de cadenas. Como se muestra en la Tabla E.2, el objeto usa 8 bytes para la instancia de la clase, 8 bytes m´as para los punteros de los vectores y: 40 bytes para el vector vac´ıo inicializado con una posici´on vac´ıa. 8 bytes m´as para cada dos elementos a˜nadidos debido al padding. 4.3.1.4. Pol´ıtica de la Aplicaci´on Esta estructura est´a compuesta por una cadena y dos vectores, uno de cadenas y otro con Permitidos. Como en las clases anteriores, se necesitan 8 bytes para la clase y 4 m´as para el puntero de cada objeto con un total de 16 bytes debido al padding. Los vectores ocupan 40 bytes 22
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso vac´ıos y crecen de la siguiente manera: el vector de cadenas como en el Claim, 8 bytes cada dos elementos, y el vector de Permitidos crece 16 bytes por cada elemento a˜nadido y 8 bytes cada dos elementos para los punteros. 4.3.1.5. Contrato Como el contrato es b´asicamente una estructura que almacena las dos clases anteriores, su tama˜no es la suma del tama˜no de estas a˜nadi´endole: 8 bytes para la clase, 16 bytes para los punteros de las clases y la cadena y el tama˜no de la Pol´ıtica y el Claim (Tabla E.4). 4.3.1.6. Aplicaciones Aunque esto no es una clase, es donde se almacena los contratos de las aplicaciones de la tarjeta. El espacio necesario para almacenarlo es, como en los vectores anteriores: 40 bytes para el vector vac´ıo, 8 bytes por cada dos elementos a˜nadidos y el tama˜no de los contratos almacenados en el vector. En la Tabla E.5, la primera columna corresponde con el tama˜no de los elementos a˜nadidos al vector en orden. La segunda columna representa el numero de elementos en el vector, la tercera el tama˜no del vector sin el tama˜no de los elementos y la ultima el tama˜no total. 4.3.1.7. PolAllows Esta clase almacena ´unicamente un vector de Permitidos m´as las constantes de la clase. Estas son: 8 bytes para la clase, 8 bytes para el puntero y el padding y 40 bytes para el vector vac´ıo. Por cada elemento a˜nadido al vector el tama˜no se incrementa en 16 bytes y ocho bytes m´as por cada dos elementos. 4.3.1.8. Dependientes Este estructura s´olo amacena un vector de cadenas por lo que el tama˜no de la clase s´olo depende del n´umero de datos en su interior. Si el vector est´a vac´ıo necesitar´a 8 bytes para la clase, 8 bytes para el puntero y padding y 40 bytes para el vector. Por cada dos elementos a˜nadidos al vector, el espacio necesario crecer´a en 8 bytes. 4.3.1.9. Pol´ıtica Esta estructura consiste en dos vectores, uno de Dependientes y otro de PolAllows, lo que significa que el tama˜no total ser´a la suma del tama˜no de los datos de estos m´as las constantes. Esto es: 8 bytes para la clase, 8 bytes para los punteros de los vectores y 40 bytes para los vectores vac´ıos. Para entender un poco mejor c´omo crece el tama˜no de estos vectores, se han separado tres casos. En el primero (Tabla E.8), el n´umero de elementos en los vectores es constante e igual a uno, y lo que cambia el tama˜no de estos elementos dependiendo del numero de servicios que almacenan. En el segundo (Tabla E.9), el n´umero de elementos en los dos vectores cambian, pero el tama˜no de los objetos a˜nadidos es siempre el mismo e igual a 56 y 72 bytes respectivamente. El ´ultimo caso (Tabla E.10) es una mezcla de los dos anteriores donde ambos el numero de elementos y el tama˜no de cada uno varia. 4.3.2. Caso de Estudio Una vez que cada clase a sido medida separadamente, es el momento de medir cu´anto puede ocupar un sistema completo de la vida real. El sistema completo est´a compuesto por tres elementos: la pol´ıtica de la plataforma, las aplicaciones en la tarjeta y las constantes necesarias en el programa 23
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Application Policy PolNeeds PolAllows EMV@BANK ePurse@BANK (transaction, ePurse@BANK) (fill purse, ePurse@BANK) ePurse@BANK jTicket@Transport (payment, jTicket@Transport) jTicket@Transport (account balance, jTicket@Transport) eTicket@SAS jTicket@Transport - - weather@Sky - (weather info, travel@Sky) (weather RSS, travel@Sky) eTicket@SAS - - Tabla 4.3: Pol´ıtica principal. Este sistema est´a compuesto por cinco aplicaciones con distintas relaciones entre ellas como ser´ıa en un sistema real. En la tabla 4.2 se muestra las cinco aplicaciones integradas ya en el sistema e insertadas en el orden de aparici´on en la tabla. Durante esta inserci´on, la pol´ıtica ha sido creada y queda como se muestra en la Tabla 4.3. Application Claim Policy Provides Calls Needs Allows EMV@BANK transaction - - (transaction, ePurse@BANK) fill purse (fill purse, ePurse@BANK) ePurse@BANK payment fill purse fill purse (payment, jTicket@Transport) account balance transaction (account balance, jTicket@Transport) jTickect@Transport buy ticket payment payment - payment payment Weather@Sky weather info - - (weather info, travel@Sky) weather RSS (weather RSS, travel@Sky) eTicket@SASTravel - - fill purse - payment Tabla 4.2: Contrato Con esta informaci´on, los datos son insertados en las diferentes tablas para obtener el tama˜no total del sistema. Los resultados pueden verse en la Tabla 4.4 sin tener en cuenta las constantes necesarias para la ejecuci´on del sistema, que ocupan unos 70 bytes. Con estos valores se obtiene que el espacio necesario para almacenar la informaci´on del sistema presentado anteriormente es de, aproximadamente, 3 kilobytes. A estos valores es necesario a˜nadirles el espacio ocupado por las cadenas. Por ello, asumiendo que cada cadena es almacenada independientemente en memoria, el tama˜no total necesario ser´ıa de unos 4,5 Kilobytes. Este valor es muy grande comparado con el espacio necesario para almacenar el resto del sistema, pero aun con este valor, el espacio total necesario es de unos 7 kilobytes. Este valor, comparado con el espacio que tiene una tarjeta inteligente que puede ser de 128 kilobytes, es una peque˜na parte de lo que se puede almacenar, lo que indica que las tarjetas inteligentes actuales disponen de suficiente espacio de memoria no vol´atil para llevar el sistema desarrollado a un ambiente real. Adem´as, esto contempla el caso en el que el espacio que ocupa cada cadena se mide de manera independiente. Si se mide tomando solo una copia por cada una de ellas el espacio necesario se reduce a 700 bytes para las cadenas y a 4 24
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso kilobytes para el sistema completo. Claim AppPolicy Contract PolAllows PolNeeds System EMV@BANK 104 144 272 96 64 ePurse@BANK 112 144 280 96 64 jTicket@Transport 104 122 240 56 56 weather@Sky 104 144 272 96 56 eTicket@SAS 96 112 232 56 56 Total 1352 780 2140 Tabla 4.4: Resultado del Sistema Completo Una vez calculado el resultado te´orico del test se lleva este al sistema desarrollado en el simulador con una tarjeta de 128 kilobytes, donde se introducen las distintas aplicaciones y se comprueba tanto obteniendo los datos del simulador como del sistema con los sistemas de test que el espacio calculado por las aplicaciones es el calculado anteriormente. 25
Cap´ıtulo 5 Conclusiones y Trabajo Futuro 5.1. Resultados Los resultados obtenidos del desarrollo de este proyecto fin de carrera son: El desarrollo de un protocolo seguro que permite la instalaci´on, modificaci´on y eliminaci´on de aplicaciones dentro de una tarjeta inteligente multi-aplicaci´on permitiendo la compartici´on de informaci´on entre las aplicaciones y evitando la fuga de informaci´on y el posible mal funcionamiento de las aplicaciones en la tarjeta. La implementaci´on de un sistema que simula el funcionamiento de una tarjeta inteligente con el protocolo definido implementado en ´el. Una bater´ıa de pruebas que comprueban el funcionamiento del sistema para diversas entradas. Medici´on del espacio de memoria requerido por el sistema desarrollado y que demuestra que el sistema desarrollado encaja en las limitaciones de las tarjetas inteligentes. 5.2. Conclusiones A lo largo de este proyecto fin de carrera se ha presentado la tecnolog´ıa Java Card centr´andose en las caracter´ısticas de seguridad de las mismas. Tras esto ha sido presentado el actual problema con las tarjetas inteligentes multi-aplicaci´on. Para la resoluci´on de este problema se ha presentado el marco de SxC, describi´endolo en detalle y se ha aportado una implementaci´on tanto te´orica como pr´actica para solucionar los problemas de seguridad en las tarjetas inteligentes multi-aplicaci´on. En este sistema, seg´un la aproximaci´on definida en ´el, cada aplicaci´on que quiere ser instalada en la tarjeta va acompa˜nada de la especificaci´on de su comportamiento seguro, el cual debe ajustarse a la pol´ıtica de seguridad impuesta por la plataforma de la tarjeta anfitriona. En particular, se ha mostrado como la aproximaci´on del SxC puede ser usada para resolver diferentes problemas de la seguridad de las tarjetas inteligentes, como los problemas del intercambio ilegal de informaci´on entre las aplicaciones de una misma tarjeta o el problema de preservar el estado seguro de la tarjeta despu´es de haberse realizado cambios din´amicos en las aplicaciones o sus pol´ıticas. El marco ha sido definido en el primer nivel de la jerarqu´ıa llamada nivel 0 del modelo para tarjetas inteligentes. Con esta aproximaci´on se ha realizado la implementaci´on del sistema que simula la tarjeta inteligente y del marco del SxC. La implementaci´on del sistema ha sido testeada ejecutando diferentes test en el sistema usando el simulador del entorno de Java Card. Estos test muestran que el sistema implementado siguiendo la aproximaci´on propuesta es v´alida y funcional y soluciona los problemas de la aproximaci´on de primer nivel en sistemas reales. 27
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Tambi´en las medidas de espacio del sistema demuestran no s´olo que el sistema implementado se puede almacenar en una tarjeta inteligente, si no que puede almacenar la informaci´on de varias aplicaciones sin llegar a preocuparse por el uso que la pol´ıtica y el contrato almacenados lleguen a necesitar usando la tecnolog´ıa actual del mercado. Cogiendo estos resultados juntos, se observa que el sistema implementado esta en disposici´on de ser exportado a sistemas reales. Esto ser´a un gran paso en las tarjetas inteligentes multi-aplicaci´on las cuales todav´ıa no est´an siendo usadas como tal, integrando este marco desarrollado en las Java Cards. 5.3. Trabajo Futuro Como posibilidades de continuaci´on con este trabajo, las opciones consistir´ıan en la extensi´on de los contratos actuales con interacciones indirectas entre aplicaciones y con la ordenaci´on de el ´arbol de invocaciones de servicios. Esta extensi´on requerir´a modelos m´as complejos de representaci´on de los contratos de las aplicaciones, como por ejemplos grafos de flujo. La parte problem´atica de esta nueva representaci´on ser´ıa el encontrar un punto medio entre la posibilidad de ejecutar esta nueva representaci´on de los modelos en la tarjeta con la expresividad de estos modelos. Otra soluci´on ser´ıa proveer recursos computacionales externos para la resoluci´on de la correspondencia entre la pol´ıtica y los contratos con este nuevo modelo, pero extendiendo el modelo actual flujo de trabajo y marco con m´etodos de cifrado y descifrado para asegurar que los resultados de la verificaci´on externa permanecen intactos. 5.4. Problemas Encontrados El primero de los problemas encontrados fue la b´usqueda de informaci´on tanto sobre la base del proyecto (tarjetas inteligentes) como del marco del problema (tarjetas multi-aplicaci´on) y sobre la nueva infraestructura a usar. En cuanto a la b´usqueda de informaci´on de lo primero, el problema fue bastante grande porque se dispone de mucha informaci´on, sobre todo de tarjetas inteligentes, de la cual mucha de ella est´a anticuada o incluso mucha de la informaci´on disponible era contradictoria entre diferentes fuentes, teniendo que clasificarla y contrastarla para poder discernir cual de ellos ten´ıa raz´on. En el segundo caso el problema fue justo el contrario ya que casi no existe informaci´on sobre tarjetas inteligentes multi-aplicaci´on. Por ´ultimo, el buscar informaci´on sobre las posibles infraestructuras para elegir la opci´on correcta y m´as tarde llegar a familiarizarse con esta. Aunque la elecci´on fuera Java Card para su implementaci´on, fue necesario el familiarizarse con ella pues est´a bastante limitada en cuanto a funciones con lo que estaba acostumbrado normalmente con Java adem´as de ser necesario trabajar con estructuras de bajo nivel a las que no estaba acostumbrado. Aunque el desarrollo del protocolo parec´ıa en un principio bastante complicado, el trabajo en el que se basaba estaba bien fundamentado y la informaci´on recibida tanto por el supervisor como con los colaboradores me ayudo mucho. Adem´as las constantes correcciones recibidas por parte de estos ayudaron a que, en caso de desviarme del camino correcto, no tardar mucho en darme cuenta. El siguiente problema encontrado fue encontrar el simulador para Java Card. Seg´un la informaci´on obtenida de los foros y p´aginas web, la mejor opci´on era usar Eclipse con IDE, pero este simulador solo permit´ıa usar la versi´on 2.2.2 de Java Card. Como el uso de esta versi´on supon´ıa el no poder crear estructuras de datos complejas, lo cual era una de las principales necesidades para la implementaci´on del sistema. Por ello se eligi´o NetBeans como simulador, aunque este simulador no dispon´ıa de ninguna herramienta que permitiera la simulaci´on del sistema externo de la tarjeta por lo que toda la informaci´on enviada a la tarjeta se ten´ıa que hacer mediante scripts realizados a mano con el consiguiente consumo de tiempo. 28
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso 5.5. Incidencias La experiencia de la elaboraci´on de este proyecto ha sido muy gratificante tanto debido a las condiciones de trabajo en las que se ha desarrollado como los conocimientos aportados tanto en punto de vista t´ecnico como en el modo de llevar a cabo el trabajo (entrevistas con el tutor, b´usqueda de informaci´on en solitario, colaboraci´on con otras personas, etc.). Primero el tener que familiarizarse con una tecnolog´ıa de la que no sab´ıa pr´acticamente nada como son las tarjetas inteligentes, adem´as de la b´usqueda de un simulador que permitiera el desarrollo de los objetivos que al principio todav´ıa no estaban del todo claro en la fase de dise˜no fue bastante dif´ıcil. Adem´as de las limitaciones de Java Card respecto a las capacidades que ofrece este sistema a las que no estaba acostumbrado me llev´o al principio muchos problemas, aunque al final llegar´a a controlarla. Adem´as, el haber realizado esta clase de proyecto en un pa´ıs extranjero ha hecho m´as dif´ıcil la realizaci´on de todo lo mencionado, lo que requer´ıa mucho m´as esfuerzo por mi parte as´ı como la escritura de esta clase de proyectos en ingl´es, que requiere un gran dominio de vocabulario t´ecnico como el desarrollo de estructuras complejas. Por ´ultimo, el realizar una presentaci´on en otro idioma durante treinta minutos, cuando ya es dif´ıcil realizarla espa˜nol me parece una experiencia incre´ıble. Por ´ultimo, la necesidad de organizaci´on, constancia, ser riguroso a la hora de obtener un buen resultado de lo buscado han sido necesarios para llevar este proyecto a buen puerto, m´as teniendo en cuenta que estando de Erasmus es muy f´acil abstraerse y darse a otras tareas. Como resumen, la realizaci´on de este proyecto podr´ıa ser la base para el desarrollo de futuros proyectos puesto que, desde el principio, se ten´ıan que tener en cuenta detalles como tiempo necesario para realizar las tareas, posibles incidencias, etc. y que a la hora de llevar esto a la vida laboral ser´an muy positivas. 5.6. Gesti´on del Tiempo y del Esfuerzo Esta secci´on da una idea de la manera en que el tiempo ha sido gestionado en el desarrollo del proyecto, as´ı como del esfuerzo empleado en el mismo en las distintas fases. Para ello se han separado las diferentes fases de realizaci´on del proyecto y se ha detallado el tiempo necesario para la realizaci´on de dichas tareas. De estos resultados se obtiene el diagrama de Gant mostrado al final de esta secci´on. 5.6.1. Divisi´on de tareas La divisi´on de tareas se ha realizado de la siguiente manera: Estudio previo donde se engloba toda la consulta, lectura y b´usqueda de bibliograf´ıa durante las distintas fases del proyecto. Dise˜no donde se incluye la definici´on del protocolo tanto en solitario como conjuntamente con el tutor as´ı como el dise˜no en pseudoc´odigo de los algoritmos que forman parte del protocolo. Familiarizaci´on con el entorno donde se incluye tanto la b´usqueda, prueba y posterior elecci´on del simulador e IDE a utilizar as´ı como el dise˜no de peque˜nas aplicaciones y seguimiento de tutoriales para un aprendizaje b´asico. Implementaci´on del sistema dise˜nado. 29
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Figura A.4: Global Platform card architecture RunTime Environment (RTE): this is, as it has been aforementioned, a neutral API which provides, besides secure storage to the code and the data, a separated space (called context) where the application can execute its own code and services to have secure communication among the application and the entities off-card. Trusted Framework: it is the one which provide communication services among the applications in the card. Global Platform Environment (OPEN): it is the responsible to provide all the services of the RTE when it hadn’t implemented or when the RTE had implemented it but not as the standard says. Additionally, when a new application wants to be installed in the card, OPEN is the manager of download the code and the installation of the application, assuring that the security principles imposed by the issuer are performed. Global Platform API: it is the one which provides services, like cardholder verification, and Card Content management services to applications. Card Manager: it is the central administrator of the card and it is represented by three entities: 1. OPEN. 2. Cardholder Verification Methods services. 3. Issuer Security Domains. A.3.2.2. Security Architecture The goal of this architecture is to provide several secure mechanisms like data integrity, confidentiality, and authentication, which allows assuring the integrity and the security of all the 36
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso components to protect the card operation inside the system. The responsible to carry out with this security measures are [7]: Card Issuer: generating keys, enforcing standards and policies and so on. Application Providers: generating keys, providing applications, obtaining authorization to install new applications... Controlling Authorities: generating keys, controlling the applications to carry out with the standards and so on. On-card components as RTE, trusted framework, OPEN, etc. Back-end systems. A.3.2.3. Cryptographic Support The card must provide algorithms which allow: signature generation, symmetric cryptographic algorithms like DES and optionally asymmetric cryptographic algorithms like RSA which can assure data integrity, providers and other external entities authentication and secure messaging [7]. Secure card content management: adds a new value to messages to verify the source and the message integrity. Secure communication: offers services with the aim that interchanged data between off-card and on-card is neither modified nor replaced for a third party. Provide three different services: 1. Entity authentication: where the sender prove his identity to the receiver through a message interchange. 2. Integrity and authentication: which allow the receiver to know if the message received is correct and if the message comes from the correct sender. 3. Confidentiality: to assure that an external entity cannot understand (decrypt) the message. A.3.3. Java Cards A.3.3.1. Overview Java card technology was invented in 1996 to allow applications written on Java language work in smart cards. Thanks to this technology, smart cards could incorporate the Java language advantages like Object Oriented programming, even though the most important advantage is to store and manage several applications in the same card (Figure A.5), including download, installation and so on. 37
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Figura A.5: Multiapplication card architecture Java Card technology works via applets, which are applications written in Java language that you can download and run. Applets communicate among the off-card clients via the Application Protocol Data Unit (hereafter APDU). Moreover, this new technology adds new security measures which do not exist before as on-card checker or a mechanism (firewall) which isolate the applications (data and keys) in their own context. Though the firewall isolates applications, it allows secure communication among applications through a public API. As aforementioned, adding Java Card language to smart cards supply smart cards with new features as: Object-oriented programming Programming secure platform Operating System independent Multi-application support Secure applet loading Open standards As well as another security features: Isolated applications through firewall Secure sharing and communication among applications Cryptographic support A.3.3.2. General Features Java Card worked as a passive server until the new version 3.0 connected edition was developed. With this new version, applications can connect with off-card servers, losing the passive function. With this new version Java Card can also admit several communication protocols (both secure and no-secure). As aforementioned, Java Card uses APDU commands to communicate with the off-card system. The APDU [6] is a communication format based on question/response messages and 38
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso used between on-card and off-card applications (Figure A.6) following ISO-7816-3 ([1]) specification. APDU is defined as an entry point object in the Java Card, so every applet context can access to it. APDU commands were long restricted, so if the data sent is longer than this limited size, the information is written in portions and sent separately. After version 2.2.2 [16], the specification ISO 7816-4 defines an extended format, which is able to send until 65536 Bytes, but due to the use of shorts in the field which denotes the length of the messages LC and LE, the maximum data length to send is 32,768 [2]. Figura A.6: APDU exchange Two heaps: volatile and no-volatile. All the objects in a Java card are created in the volatile memory. To make these objects persistent (be part of the no-volatile memory), they should be referenced by an object which is in the no-volatile memory. All the objects of the volatile memory are garbage collected (this function is automatic in Java Card 3.0.2 ([5] [3])). By way of illustration, the Figure A.7 shown the volatile and the non-volatile heaps. The non-volatile contains several objects and in the volatile is shown an object called ”v”which point to two others: ”s1.and ”s2”. In the next image (Figure A.8) ”v”has been referenced by the blue object of the non-volatile memory. This means that both the object ”v.and the objects referenced by has been promoted and stored in the non-volatile memory, while their old copies are garbage collected. Figura A.7: Objects in volatile memory 39
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Figura A.8: Objects in non-volatil memory Firewall among applications: the firewall avoids applications to access to other applications objects unless these applications communicate through shared interfaces and they have access permission. Split Virtual Machine (VM): the VM (as it can be shown in the Figure A.9) is divided in two parts due to Java card technology features limitations. So, the off-card part (converter) receives the files .class, which contains the applications code, and does the following tasks: load, link and name resolution as well as bytecode verification, optimization and conversion, obtaining the .cap file, which is sent to the on-card part (interpreter). There, the interpreter manages the bytecode execution and the security enforcement. Figura A.9: Split virtual machine Transactions: owing to the card can be disconnected in any moment, Java card add the concept of transactions: all the operations done by an application should be atomic and consistence. If a transaction doesn’t finish, all the things which happened will be ruled out to assure the integrity and consistency of both data and code [10]. A.3.3.3. New Features With the new two versions (3.0 classic and connected edition) some of the old features have been upgraded and others have been added. The connected edition has the upgrades of the classic edition adding some more [3]: Applets: •A Java application can have several packages instead one. 40
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso •More facilities and libraries •Concurrently execution over different I/O interfaces •Extended applets (similar to the old ones but using the new API features) Multithreading: With this new version, the web and the classic applets support multithreading. Since of the threads are no persistent, this editions add a new feature which saves the execution tasks to recover they automatically after a reset. Persistence: both machine code and applications are stored in the persistent memory, instead the objects should be referenced by a persistent object if you want to keep it. To make it and due to the objects are created automatically in the volatile memory, Java card use a strategy which consist on reference this object by a persistent object to be promoted. When an object in the no-volatile memory is no referenced anymore, this object and all the objects it references are garbage collected [10]. Transactions •Multiple concurrent transactions •Nested transitions •Better control and programming of the transactions duration. Communication between applications: to improve and make easier the communication among applications the new version adds two new features: 1. Publish a service that the other applications can use. They can be published by applications or be a predefined service. 2. Informing other applications that something has happened through an event, achieving an asynchronous communication model. As with the services, predefined events are already defined. Network communication: with the new versions, applications are allowed to connect directly with off-card servers. This involve smart cards can work not only as passive servers. Besides, Java cards support several communication protocols both secure and no secure. File access: each application has its own storage space where the application is the only one which has access. A.3.4. Applications Uses Since the appearance of multi-application smart cards, multiples industries have developed application which could be in smart cards together with others. These industries can be classified into: Payment and banking Loyalty Insurance Governmental E-security 41
Ap´endice B Security of Smart Cards In this chapter it is informally introduced the issue of security of smart cards, distinguishing between hardware and software security. This chapter describes both: How the attackers try to break in the smart card information and how it is prevented How the smart card prevents to be broken in and how the attackers try to skip these methods B.1. Hardware Security Smart card hardware security consists in avoiding visualizing how the smart card works and the data it has and controlling the environment and the inputs which could be dangerous. These hardware security issues try to prevent the attacker from obtain important information about how the card works or the data it has. There are different methods to protect smart cards depending on the attacks are going to be realized. B.1.1. Anomaly Monitors These monitors are the responsible for switch off the smart card when the environment conditions become extremes or the voltage or clock values become anomalous. There are different kinds of monitoring [19]: Voltage monitoring: when the voltage supplied to the card is lower or upper than an established limit, the smart card switch off automatically to prevent from possible attacks. Due to attackers try to deactivate the monitor before doing the attack, the monitor is especially protected. Frequency monitoring: similar to the voltage monitoring, if the value of the clock frequency supplied by the external entity is lower or upper than the limits established by the manufacturer, the monitor orders the card to switch off in order to avoid the microcontroller to be analyzed. Temperature monitoring B.1.2. Reverse Engineering Since the chip and its components could be observed in order to learn how the chip works and, with this information, try to find weaknesses on it, smart cards includes methods as putting the components randomly to make more difficult to understand how them works. The chips include also methods as obfuscated logic and buried buses to prevent reverse engineering. 43
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso B.1.3. Scrambling This method consists in scrambling the buses and the EEPROM to avoid knowing the addresses of the memory or the function the bus realizes [19]. B.1.4. Ion Implanted ROM The manufacturers use a kind of ROM where the data cannot be visualized using a microscope within visible or ultraviolet light spectrum [19]. B.1.5. Silicon Features Adding metal shields prevent from exterior access to the components. B.1.6. Side-channel Countermeasures Side-channel attacks are a no-invasive attack which involve observing the supply consume, electromagnetic radiation, the time that need a task to execute and so on. The more normal methods to prevent from these attacks are: To execute always the instructions in the same order regardless of the data. To include random delays between instructions. To put shields to avoid the electromagnetic emissions. B.1.7. Redundancy This method consists in repeat parts of the algorithms which are too easy to attack in order to avoid an input specially manipulated to discover how the card works using fault analysis methods [18]. B.2. Software Security Smart cards offer a lot of methods to protect both privacy and security of the data stored [9]. The methods are: Authentication: smart cards provide mechanisms to prove the identity of the user, the applications and the off-card entities. Secure data storage: the data stored in the card could only be accessed by the application which belongs to or by other applications through the API, but only if the application has the firewall authorization. Encryption: smart cards have several encryption methods to keep the system safely. Secure communication: smart cards have secure communication protocols which provide confidentiality, integrity and authentication. Biometrics: smart cards allow storing biometric templates to the systems which allow these methods. 44
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Certifications: smart cards have been certificated as carry out with the standards after strict tests. Besides, contactless smart cards have more security features related to them [9]: Mutual authentication: not only the card should identify itself besides the reader should do before starting. Authenticated and authorized information access: the smart cards could recognize the authority of the requestor and it will give him only the requested information, not access for all the information stored. In the other hand, smart cards data can be attacked using different methods [19]: Bug exploits: although in all the software are bugs, in the smart cards is very difficult to use it because they are very difficult to find and they should be loaded before exploit it. Usually, these bugs are used with physical attacks to be successful. Illegal bytecode: these attacks are very difficult to find in the smart cards because verify all the bytecode require a lot of CPU power which the cards don’t have. If this attack reaches its objective, the attacker obtains the control of the card. Besides these attacks, which affect to both contact and contactless smart cards, the contactless smart cards even have more attacks [19], which are: Altering data transmitted: an external attacker could do a man-in-the-middle attack, obtaining important information. Denial of service: an attacker could, with a strong radio tool, realize a lot of requests to the reader making impossible to the other cards to use it. Eavesdropping of the data transmitted: due to the information in a contactless communication goes through the air, this information could be stolen by a non-authorized user compromising the information sent. B.2.1. Java Card Security 3.0 connected edition add new security mechanisms to the standards in smart cards [3]: Code isolation: the code of an application cannot interfere with other applications’ code since each application has its own space referenced to the loaded application. Even so, it is allowed using public interfaces and shared libraries to communicate with other applications’ objects. Package access control: prevents packages to be overwritten or extended once the package has been loaded. Context isolation: an object owned by an application in its own context cannot be acceded by applications in other contexts unless they access through the shareable interfaces. It is imposed by the firewall and it helps with application containment. 45
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Services the application provides Services the application calls Services the application needs Services the application allows and the application which is allowed to use it Due to this modification, each application should explicitly describe which application is allowed to use a service, not only the security domain. Definition(Security Policy) a security policy is a formal complete specification of the acceptable behavior of applications to be executed on the platform for what concerns relevant security actions. Continuing with the previous examples, a smart card policy example could be something like: Example 4.2: ”The service list medicines.Medicine@Pharmacy of the application Medicine@Pharmacy is allowed to be used only by other applications of Pharmacy and Hospital companies”. Knowing how a contract and a policy are defined, now the contract-policy matching could be defined as: Definition (Contract-Policy Matching) a contract of an application A matches a platform policy if there is no illegal information exchange between the application A and the applications already on the card. Due to this definition, a contract matches with a policy if does not exist an information leak between this contract and the policy (which is the contracts already added in the platform) following the workflow shown in (Figure 2.1). So, when a new application tries to be installed on the platform, it is only necessary to check that forbidden communication will not exist. After this is checked, if the policy and the contract are compliant (no forbidden communication exists) the action supposed to be done (i.e. update of an application) will be executed, otherwise the action will be rejected. Continuing with the examples: Example 4.3: (Successful match) Suppose the application Pharmacy is already installed on the card and the policy has been updated with its information. Now, a new application Manage@Hospital from the company Hospital which uses the service list medicines.Medicine@Pharmacy tries installing itself. Due to the policy has stored the contract of Medicine@Pharmacy and its contract allows the Hospital applications to use its services, hence no information leak exists and the application installation is accepted. Example 4.4: (Unsuccessful match) On the other hand, if another company (not Hospital neither Pharmacy) want to use the service list medicines.Medicine @Pharmacy, the platform will reject the installation caused by the illegal information exchange this new application wants. Once the policies and the contract has been explained, it is necessary to look for a way to develop this in a smart card where the computational power is not too much. Besides, process this information outside the card required secure communication methods and cryptography to make sure that the result has not been altered. In order to solve this limitations, in [24] a hieratical model has been presented where the higher level should be more expressive but more costly, and in the lower levels the opposite. 52
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso D.1.1. A Hierarchy of Contract/Policy Models The first challenge we have to address is to find an appropriate language for specifying contracts (policies) describing possible (allowed) information exchange among applications. To address computational limitations we propose a hierarchy of contracts/policies models for Global Platformbased smart cards. The rationale is that each level of the hierarchy can be used to specify contracts and policies, but with different computational efforts and expressivity limitations. For instance, using the lower level (L0) one can get computational benefits, but lose in contract/policy expressivity. L0: Application as Services. This level models applications as a list of required and available services. Essentially it is the current set-up of the GP. L1: Allowed Control Flow. This level provides a call graph G1(A) of the application, where vertices are the states of the application and edges represent the invocation of different services. Then we can do a bit of history based access control and more fine grained information exchange control. L2: Allowed and Desired Control Flow. This level adds to the previous one the notions of correct and error states. It can be necessary if we want to test that the removal of an application (or a change in a policy) does not break other applications. L3: Full Information Flow. This level extends the previous one considering also the information flow among variables. Practically speaking, moving from some level to a higher level (for instance, from L0 to L1) means to add more details in the contract/policy specifications, modeling more precisely the behavior of the applications running on the card. In this thesis, the level 0 is going to be used to implement the SxC framework. D.2. Supporting Applications’ Evolution by SxC In this section, the information extracted from the code and the platform policy, which should be represented in the same way to make possible to compare it and check if they are compliant, is explained. Also the algorithms and why they are used will be exposed. D.2.1. Information Structure First of all, to address the problem is necessary to specify the changes in the contract of the applications which are going to be dangerous to keep the platform in a secure state. These changes could be: Add a new application to the card Remove an old application from the card Modify an application already on the card adding or removing services To assure the secure state two properties have been defined in [22]. These properties describe how should be the state of the platform after occurs a change in order to keep the secure state of the platform. These are: P1 (Stable Security) After a change there should not be illegal information exchange between applications 53
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso P2 (Stable Functionality) After a change every application on the platform should be able to work correctly In order to keep these statements, the code is checked before an application modification. If both are compliant (the new application characteristics and the platform policy), then the change is allowed and the platform policy is updated with the new changes. Otherwise, the change is rejected. In both cases, the properties will be still kept. To achieve this problem, the representation of both the contract and the policy is made listing the services which the applications provides, the services which the application needs, the services the application calls and which of this services are allowed to others applications, in sets. These sets are directly extracted from the application using either proof-carrying-code techniques or other technique which allows extracting the contract directly from the application code as has been mentioned in [22]. With these techniques is possible to extract the application contract which has been divided in two parts, the claim and the application policy. This information is stored in the card to use it afterwards. The information extracted from the code has been divided in two parts because the four sets can be classified by two different criterions. The first one is called claim and is described as how an application is supposed to behave with the applications which are or will be on the smart card. On the other hand, the application policy is referred to how others applications, which are supposed to share services, should interact with it. The application providers, the security domain owner or the controlling authority will establish this behavior (see [24]). For each application on the card, the Claim is a pair (Calls, Provides). Both are subsets of services the applications which are or will be installed on the platform have. The Calls set represents the services this application code is going to call during its execution on the card. On the other hand, Provides is a subset of services this application has implemented and supplies to the platform so other applications can use. The application policy (hereafter AppPolicy) is also defined by a pair (Allows, Needs). In this case the Needs is a subset of the services which are called by this application and are included in its Calls set. They will be necessaries during the invocation of the application. In the other hand, the Allows is a set of pairs, where one of it has a service of the Provides set and the other element could be an installed or a non installed application ID. With this new classification the previous contract example will be represented as: Application Claim Policy Provides Calls Needs Allows Medicine@Pharmacy list medicines - - (list medicines, app1@Pharmacy) (list medicines, app2@Hospital) Tabla D.1: Contract example Once this has been explained, the information exchange can be defined using these concrete sets of services. A information exchange between two applications A and B exist when the service ”serviceA¨ıs provided by A and is invoked by B. That means that in the Provides set of the application A exists an entry called ”serviceA.and in the Calls set of the application B exists an entry called ”serviceA”. But, though an information exchange between the two applications exists, this does not mean that this exchange is legal. A legal information exchange is defined as: 54
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Definition(Legal Information Exchange)An information exchange is legal only if the application which provides the service allows the applications which calls the service to use it. Following with the examples, the information exchange between application A and B is legal if the pair (serviceA, B) exists in the Allows set of the application A. Besides this, it is also necessary to satisfy the application policy. To achieve this, all the services in the Needs list of an application should be provided for other applications in the platform. With this new data structure, the changes in the contract can be explained more in detail. These changes can also be separated in two different types depending in the problem they cause: functional or security. The functional is referred to the AppPolicy and the security failures to the Claim changes. The possible changes and the possible failures, which have been explained in [22], are: Changes in the Claim: •Add a service to Calls set could provoke a security failure due to this application is not allowed to use it. •Remove a service from Calls set cannot provoke any security failure. •Add a service to Provides set can provoke a security failure because this service could be called by an application already installed in the platform but not allowed to use it. •Remove a service from Provides set could provoke a security failure because it is possible that some application needs this provided service. Changes in the AppPolicy: •Add a service to Needs set can provoke a functionality failure because it is possible that the service requested is not provided. •Remove a service from Needs set cannot provoke any functionality failure. •Add a pair (service, application) to Allows set cannot provoke any functionality failure. •Remove a pair (service, application) from Allows set can provoke a functionality failure because the application in the pair could be still using the service allowed. In all these cases, the change could be accepted or rejected. The changes which cannot lead in any security or failure will be always accepted. But in the case the changes can lead in any failure, it is necessary to check the smart card issuer and the stakeholder to solve it. In this thesis, updates which can lead in security or functionality failures are always rejected. Finally the policy of the platform should be defined. Because the policy should satisfy all the requirements of the stakeholders, it is compositional and provided by them, and when a new stakeholder arrives to the car, her policy is checked to be compliance with the policy already in the card and. If this new policy is compliance, her new rules are added to the card policy. Therefore, the policy is defined as a set of the AppPolicy from all the applications stored in the platform. This is necessary because some authorities want to choose how the other applications on the card can interact with its application’s services. Due to that, some external rules control the interaction among the applications in the platform. Which is more, this policy could be updated without modify the working application. This has been defined before as AppPolicy, where each application authority set the relations allowed. The combination of all these application policies makes the platform security policy. Due to that, if a platform has ”n.applications, the Policy will be= {AppP olicy1,..., AppP olicyn}. An example with three applications could be as shown below: 55
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Application Policy Needs Allows Medicine@Pharmacy - (list medicines, app1@Pharmacy) (list medicines, app2@Hospital) app1@Pharmacy - - app2@Hospital - - Tabla D.2: Policy example But this information can also be reordered in two set of relations, PolNeeds and PolAllows, depending on the target of the security requirements. The PolNeeds set is represented as {Dependentes1,..., Dependentsn}where each element Dependents is a list of the applications which needs some of the services Application1provides. For the PolAllows set, it is represented as {Allows1,..., Allowsn} where each element is the Allows set of the corresponding application. Finally, the applications installed in the platform will be stored as the sum of the applications’ contracts and it will be represented by Λ. D.2.2. Algorithms for Applications’ Evolution Once the problem has been exposed, the algorithm necessaries to address the problem will be explained. These algorithms could be divided in two parts: one with the algorithms which check the compliance of the actual policy with the changes are try to do and the algorithms which update the policy if the change is compliance with the actual policy. In the first group, the algorithms are: Check of compliance of new application Check of removal of application Check of compliance of AppPolicy update Check of new Contract compliance with the Policy For the second group are: Policy update for approved new application Policy update for approved application removal Update of the Policy after approved AppPolicy change D.2.2.1. Check of Compliance of New Application When a new application wants to be installed in the smart card it is necessary to check if the application contract is compliance with the actual policy and the others applications contracts installed on the platform. To make sure this contract is compliance, the algorithm check three different parts of the Contract which may lead in any failure. The first part checks, for each service the new application has in its Calls set, if there is an application on the platform which provides this service and if this application allows new applications 56
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso to use it. If an application which provides this service doesn’t exist, this application cannot lead in a security failure. If some application provides this service but it does not allow to the incoming one to use it, then the new application is not compliant with the platform security policy and the installation is canceled. Otherwise, if the service is provided and the application which provides this service also allows the incoming application to use it, this step is passed and the algorithm continues checking the compliance. In the second part the Needs set is checked. In this case is enough checking if all the services the application needs are provided for one of the application on the platform. If they are not, the installation will be canceled. Finally, in the third case, the services which the application provides are checked. If the services provided are not called for any application on the platform, the application will be installed. On the other hand, if the services are called by some application on the platform, these applications should be also allowed to use it, otherwise the installation will be rejected. If the application contract passes all these three steps, then the algorithm will return true and the application will be installed on the platform. D.2.2.2. Check of Removal of Application This algorithm is the responsible checking if no applications relays in the application which is wanted to be removed. To achieve that it is only necessary to check the Dependents list of this application. If the Dependents list is empty because none applications needs its services, the application will be removed. Otherwise, the removal will be canceled. D.2.2.3. Check of Compliance of AppPolicy Update When any provider wants to modify its AppPolicy adding or removing some services, first it is necessary to check the compliance of the new AppPolicy with the platform security policy. To make sure of this it is necessary to check some special cases as it is shown in [22]: The first case deals with when a new service is added to the Needs list. This should be checked because this new service should be supplied by an application in the platform. To achieve this, first it is necessary to store the new services added to the Needs list and after, make sure that all of them are provided by the platform applications. Secondly, when a service is removed from the Allows list. Because maybe some application calls this service, this services which will be removed from the Allows list are stored in a new list and this list is checked. If none of the services in this list are called by any application on the platform, this step will be passed. Otherwise the update will be rejected. Finally, if the previous steps have been passed, the algorithm returns true and the update could be applied. D.2.2.4. Check of New Contract Compliance with the Policy Instead of modify only the AppPolicy, all the contract could be modified, so it is necessary a new algorithm which checks this modification. So, in this algorithm is not only necessary to check if the AppPolicy is correct as in the previous algorithm, but also if the Claim of the contract is. Because of this, there are some parts of the algorithm (the parts which check the Needs and the Allows differences) which will be similar to the previous one (Algorithms 3 parts 1 and 2) and which are shown below. 57
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso In the different ones, first is checked the Calls modifications. For each new service added to this list, it is necessary to confirm if the service is supplied for an application in the platform. In the case the service will be supplied, it is also necessary to check if the application is allowed to use it. Finally, for the Provides differences it is necessary to check both the added ones and the removed ones (Algorithm 4 part 3). In the first case (services removed from the list), the algorithm checks if the services which are going to be removed are needed for some application installed on the platform. If some service is still needed, the update will be rejected. Otherwise this step will be passed and the algorithm will continue with the checking. In the second case the services added to the Provide list are checked. Only if one of these services is called by some application in the platform but this application does not allow the callee to use it, the update will be rejected. D.2.2.5. Policy Update for Approved New Application Once the application compliance has been accepted, it is necessary to update the platform policy and to add the new application contract. To do that, the algorithm developed has three distinguished parts; the first one which modifies the data stored in the old policy, the second one which adds the new application contract to the application list and the third which modifies the policy adding the Dependents and Allows of the new application. First of all, the services needed by the new application are checked. Each element in the list is compared with the services provided in the platform. If this service is provided then the ID of the incoming application is added to the Dependents list of the application which supplies the service. Next, an empty vector is added to the PolNeeds list with the ID of the new application and the Allows list of the new application is stored in the policy list PolAllows. Finally, the application list is updated with the contract of the new application. D.2.2.6. Policy Update for Approved Application Removal Once the application removal compliance has confirmed, the application can be removed from the platform. To remove it from the platform will be necessary to update the policy of the platform and remove the application contract. As can be seen from the Algorithm 6, the Dependents and the Allows lists are removed from PolNeeds and PolAllows respectively. After that, any reference to the application is removed from the Dependents list and later, the application is removed from the applications list. D.2.2.7. Update of the Policy after Approved AppPolicy Change After the compliance of the modification of an application (either the application policy or the application contract) is accepted, the platform policy should be updated. Since policy only depends in the Needs and the Allows information, the algorithm only needs the new and the old AppPolicy of the modified application. Like in the algorithm which checks the compliance of a new contract, first the differences between the new and the old Needs list are extracted storing the new services added in a list. For each element in this list, the services provided by the applications on the platform are compared to them. If the service is provided, the ID of the application which is being modified is added to the Dependents list of the application which provides it. After that, the services which have been removed from the application Needs list are stored. In 58
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso this case, if some application has been providing this service, the ID of the application which needs this service is removed from the Dependents list of the application which provides the service. Finally it is necessary to store the new Allows list, so if the new and the old Allows list are different, the new one is stored in the policy. 59
Ap´endice E Implementation of SxC Level 0 This chapter will examine: The information about the technology used to develop the program which solves the problem How this program has been implemented which includes searching of information not only about the technology used either the way this information should be used to solve the problem. The problems which arose during the implementation of the system with both the technical and the theoretical problems. Also the implementation of the system will be explained in detail emphasizing the most important points as the algorithms which represent the framework itself. Also the test did to check the correction of the implementation will be explained. The last section assesses memory footprints, which measure the memory the system uses and references during the execution and when the card is switched off. E.1. Technology adopted To address the problem presented, Java Card Technology has been selected due to the fact it is the most important standard already in use and also the easiest, common and documented one. Nowadays, the most common and moderns version developed for Java Card are: Java Card v2.2.2 and Java Card v3.0.1 (connected and classis edition). Since it is true that the first version is the most used in the current systems, the new one (version 3.0.1) adds more features and it will be the one which will be used in a close future. Although it was possible to develop the system in both versions, the second one was chosen because it makes easier the development of the system with more modern facilities and libraries. E.1.1. Installation of the Environment For the installation of the system, the Development Kit User’s Guide [4] has been followed. As a summary, the steps necessaries to follow are, in order: 1. First it is necessary to download and install several programs before install the development kit. Each program should be installed following the instructions available in the his web page. The programs are: Apache ANT, necessary to run the samples. 61
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso v1 which don’t have the vector v2. To achieve this, a loop which goes through the vector v1 is implemented. Inside this loop, using the ¸contains”function, it is checked if the vector v2 doesn’t have the element selected in the loop and, if it has, the element will be added to an auxiliary vector. for(int i = 0; i <v1 . s i z e ( ) ; i++){ i f ( ! v2 . c ontains ( v1 . elementAt ( i ) ) ) vAux . addElement ( v1 . elementAt ( i ) ) ; } Listing E.9: Extract function Now, for the first part of the algorithm and using the function above explained the new services added to the Needs set are extracted. Once the new services have been added to the vector they should be checked. First, the vector filled before is scanned and ”belongs”, a boolean variable created at the beginning of the algorithm, is set to false inside the loop. Later, for each application in the platform, the service selected in the loop is searched in the Provides list of the application. If the service is provided, ”belongs¨ıs set to true and the loop continues with the next service. If all the services are provided, the algorithm continues with the next part of the algorithm, otherwise (some service is not provided) the algorithm returns false and the update is rejected. Once the Needs services modification has been checked and passed, it is the turn for the Allows list. As in the first part of the algorithm, the differences between the old and the new policy should be extracted. In this case, instead of the Needs set, the differences are extracted from the Allows set, and, instead of the services added, the selected services are the removed. Because the Allows structure is a register, it is impossible to use the function ¸contains”, so it is necessary to do in other way. To obtain that, it is necessary to make two nested loops: the outer one for the old services and the inner one for the news. Between both, the ”belongs”variable is set to false. In the body of the inner, the services selected from the lists by the indexes are compared and, if they are equals, ”belongs¨ıs set to true breaking the iteration and continuing with the other services. If the inner loop finish its data and ”belongs”value is still false, the service is added to an auxiliary vector. These iterations continue until all the services of the old Allows set have been checked. Vector<Allows>vAuxAllows = new Vector ( 1 , 1 ) ; for(int i = 0; i <a p p p o l i c y a o l d . allo ws . s i z e ( ) ; i ++){ belongs = false ; for(int j = 0; j <app policy a new . allows . s i z e ( ) ; j++){ i f ( app policy a new . allows . elementAt ( i ) . s e r v i c e . equals ( a p p p o l i c y a o l d . a llows . elementAt ( j ) . s e r v i c e )){ belongs = true ; break ; } } i f ( ! belongs ){ vAuxAllows . addElement (new Allows ( a p p p o l i c y a o l d . a llows . elementAt ( i ) . s e r v i ce , a p p p o l i c y a o l d . a llows . elementAt ( i ) . a p p l i c a t i o n i d ) ) ; } } Listing E.10: Extract function for allows structure Now it is time to check if the removed services stored in the auxiliary vector are called by any application on the platform, therefore all the services on the list are compared with the applications IDs of the applications in the platform. If these values are equals, it is necessary to check if the application which is allowed to use the called service really uses it. Using the ¸contains”function the 68
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso service is searched in the calls vector. If the vector contains a reference to this service the update is canceled. Otherwise, the next service is checked. When all the previous steps have been passed, the algorithm returns true and the update starts. E.2.2.4. Check of New Contract Compliance with the Policy Using the function to extract the differences between two vectors defined before (Listing E.9), the new services added to the Calls list are extracted. In the first part, the vector with the services before extracted is scanned. Later, each application on the platform is selected and the service is looked for in their Provides list. If the service is provided by some application, its Allows list is checked in order to know if the callee application is allowed to use it. If it is, a boolean variable called ”belongs¨ıs set to true and thanks to the escape sentences the next service is checked. Otherwise, the algorithm returns false and the update is canceled. The second part is identical to the Check of Compliance of AppPolicy (section E.2.2.3) update part one explained above. The third part extracts the old Provides’ services which are supposed to be removed using again the extraction method. Now, the applications list is gone through and if some of these applications still need one of the old services provided, the update is rejected. In the forth part the new added Provides’ services are checked. If the service is called by some application on the platform, it will be necessary to know if the application is allowed to use it in the new contract. If is allowed the algorithm continues until all the services has been checked. Otherwise, the new contract is not compliance and the update is refused. For the fifth part, the algorithm does the same as in the Check of Compliance of AppPolicy Update (section E.2.2.3) explained before. E.2.2.5. Policy Update for Approved New Application As in the previous algorithm, a boolean variable called .exist”will be necessary, so it is declared in the beginning of the algorithm. The first part, which adds the needed services to the Dependents lists, starts going through the Needs vector. Hereafter, .exist¨ıs set to false. For each application in the platform, the Provides vector is checked to know if it contains the service selected before. If this application contains it, the ID is stored in the PolNeeds vector. Once the application which provides this service is found, the .exist”variable is set to true in order to continue with the next services until finish with all the services. Next, the application is added to the platform adding its contract to the application list. In the final part a new empty vector is created which, together with the application ID, is added to the PolNeeds structure as the new Dependents information of the application. In the PolAllows case, the ID and the Allows vector of the application are stored. E.2.2.6. Policy Update for Approved Application Removal Before starting with the algorithm implementation, an integer variable called ¨ındex¨ıs created and initialized to zero for future uses. Now, first of all, the Dependents and the Allows lists of the application to be removed are erased 69
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso from the platform policy directly. This can be done because the position of this information has been stored previously in the check of removal of application algorithm (section E.2.2.2). After that, it is necessary to remove all the references the other applications have in their Dependents’ list. To achieve this, the PolNeeds vector is gone down. For each element in the vector, a loop which does not finish until the boolean variable ¨ındex¨ıs equal to minus one is implemented. In the body of the loop, ¨ındex¨ıs assigned with the value returned by the function ”vector.indexOf(element, index).of the vector class. This function returns the position of the element in the vector or minus one if this vector does not contain the element searched starting the search in the index position. In this case, the vector is the Dependents list in each PolNeeds element and the element searched is the ID of the application to be removed. The first search will start in zero, and the next ones in the position of the last element removed. When all the references have been removed from one application, the index is set to zero again and the loop continues with the next element. After all the references to the application have been removed, the application is removed from the platform. E.2.2.7. Update of the Policy after Approved AppPolicy Firstly, using the .extract function”(Listing E.9), the new services added to the Needs list are extracted and stored. Once the services have been extracted, the vector filled before is gone through. Then, for each application in the platform, the service selected in the loop is searched in its Provides list. If the service is provided, the ID of the application is added to the PolNeeds list in the position of the application which provides this service. Secondly, the old services removed from the list are extracted. Next, the vector filled before is gone down and, for each application in the platform, the service selected in the loop is searched in the Provides list of the application. If the service is provided, the ID of the application is removed from the PolNeeds list in the position of the application which provides this service. Finally, the Allows information should be actualized. To make this easy, the new one is always inserted in the same position replacing the old one. This is made in this way because is less costly to replace always the old information for the new one without check if this information has been modified. This is possible because both the applications and the policy are stored in the same position, so once one of them has been found, the other can be accessed directly. E.2.3. Implementation of the system Although the important part of the system is the algorithms and the data structures, it is necessary to test the correct functionally of these in a system inside of a Java Card simulator to make sure the system fits with it. The previous part of the system has been packed in two different classes: Data Structures and Multi Application Framework. The first has the data structures aforementioned and the framework algorithms and more algorithms necessaries to simulate the system which are: One which checks if the platform has an application comparing the incoming ID with the applications in the card. This function is necessary because when an update arrives to the system, it is necessary to check if this application is already in the system. Two functions more, which check the correct functionality of the system, have been developed. 70
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso These functions show the applications information stored in the platform and the policy. Finally, two functions which store the changes in the contracts after an approved update have been implemented. But the principal part of the system is the Input applet class, which receives the APDU commands from the off-card system, checks if the commands are correct and with the information received invokes the different framework functions. In the first part of the algorithm, the constants and the variables necessaries to the execution of the system are declared like ”policy”which will store the platform policy or ”SxC”which is a reference to the class Multi Application Framework. After that, the functions necessaries to manage the smart card and the APDU commands are implemented. Besides the normal functions in an applet for smart card as the constructor, the install function, which calls the constructor and register the applet in the card, and the process function, other functions have been developed. Besides, the process function, which receives the APDU command from the off-card system has been modified. This function receives the APDU command from the off-card system which is checked to assure the APDU command class byte (CLA) is correct. In this case could be: 0x20 to add a new application 0x30 to remove an application from the card 0x40 to modify the AppPolicy of an application on the card 0x50 to modify the Contract of an application on the card If the instruction is not correct, an error command is sent back to the off-card system. Otherwise the corresponding function is called. There are two different functions: 1. manage check of compliance is the function which manages when a new application is wanted to be added or when an installed one is going to be updated. These functionalities have been put together because the similarities in their code. First of all, the information received from the APDU command is extracted and stored in a buffer. Now, depending on which action is going to be executed the information will change. If the action is an AppPolicy update, the application policy is stored; otherwise the entire contract is stored (for a contract update and for a new application). Once this information is stored, the applications in the system are compared with the ID of the incoming application. In the case of a new application, if this ID already exists in the platform, the update will be rejected because each application ID in the platform should be unique. If it is not in the platform, first the compliance is checked with the actual policy in the platform, and if it is compliance, the application is added to the application list and the policy is updated. For the other cases (AppPolicy and Contract update), if the application ID doesn’t exist the update is rejected. If the application already exists, the compliance of the update will be compared with the old policy and, if it is still compliance, the policy and the application will be updated. 2. manage policy update remove app extracts the ID from the APDU buffer of the application is going to be deleted and, if the removal is accepted (no applications relay on this application) the update of the removal is executed. In this case is not necessary to check first if the application is already in the platform because if it’s not, the function returns false and nothing is removed. 71
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso E.2.3.1. Problems The main problems have arisen with the limitation of the Java Card in the use of the Vector structure, because the Vector class has a lot of useful functions which could have been used to make easier the implementation of the algorithms. The first problem is that the Vector class, in Java has a function called clone() which make a copy of the vector but the copy will contain a reference to a clone of the internal data array, not a reference to the original internal data array. If this function had been available in the Java Card, the constructors of the structures which use vectors would have been easier. With this function had not been necessary to copy each element from the input vector to the vector the structure. Only assigning to the class attribute the input vector using the clone function will simplify the entire loop which have been used to do that. Another problem is that, in the second version of the algorithms, sometimes is not possible to use the vector functions because the structures used for the Allows. Also if you want to look for a concrete application using the ID this function will help, but it is not possible to compare only the application ID. E.2.4. Battery Tests For each algorithm implemented, a battery test was performed in order to make sure the algorithm works as theoretically it should work following the SxC specification. In each test, the APDU commands necessaries to test the algorithm functionality are presented and the results are explained. These tests can been found in the Appendix G. E.3. Performance Due to one of the principal problems on the smart cards is the size the applications use to store the information, this should be taken in account to assure that the applications implemented in the simulator will fit with the real environment. To test the space the applet which has been developed uses, several algorithms has been implemented with the objective of see how much space each data structure and the entire system need. The memory tester has been implemented in the class MemoryTestBench which is composed of two algorithms. The first is called calculateMemoryUsage and it is the one which calculate the memory footprint. This algorithm starts constructing the object which is going to be tested and which is received as argument. Once the object has been created two variables called ”mem0.and ”mem1.are created and initialized and the object which points to the class to be measured is assigned to null. Next the garbage collector is called several times to free the memory which is not in use and the memory used is now calculated. After that, the object is created and the garbage collector invoked again. Now the memory used is counted again and subtracted from the previous value. The result is returned to the second algorithm, which will show the results obtained. To make possible testing the different objects instantiated in the framework, a public interface is created. This class is called Object test and has one abstract function called makeObject which returns the object is going to be measured. Starting from this class, new classes are created for each data structure used. Each class implements the Object test and the data structure to be measured. The abstract algorithm makeObject is implemented in these classes with the code where the data 72
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso structures are filled with different number of elements to known how the data increase its size when more information is added. Finally, this algorithm returns the object created. Lastly, the Main class, where the instance of the memoryTestBench is initialized, is created. With this instance, the function showMemoryUsage is called and all the instances of the different date structures used in the implementation of the system are presented. E.3.1. Results For each different data structure used in the implementation has been measured different sizes as showed and explained below. E.3.1.1. Strings Due to memory usage is crucial to the application, so is understanding the memory usage of strings. Although strings are actually ¨ınternalized”, which means that only one instance of the same string is kept, it is also necessary to know the size which all the strings will size in the worst case (each string is unique) to maximize the space required to store the smart card information. A String will have: 8 Bytes for the String class 16 Bytes for the character array 4 Bytes for the offset 4 Bytes for the String length 4 Bytes for the count 4 Bytes for the hash 2 Bytes for each character in the String So, an string with 6 characters will size 40 Bytes for the information plus 12 bytes for the data. For the performance of the structures no strings will be taken in account until the system performance. E.3.1.2. Allows Allows is a simple data structure which consists in two strings. The result of the test is shown in the Table E.1. Object Size Pointers Total Size 8 8 16 Tabla E.1: Measure in Bytes of Allows data structure In this result could be seen that an object needs 8 bytes to it instance and only 8 bytes to store the pointer to the strings. 73
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Object Size Pointers String Vector 1 String Vector 2 Total Size Elements Size Elements Size 8 8 0 40 0 40 96 8 8 1 40 1 40 96 8 8 0 40 1 40 96 8 8 2 48 0 40 104 8 8 2 48 2 48 112 8 8 2 48 3 48 112 8 8 3 48 3 48 112 8 8 4 56 3 48 120 8 8 4 56 4 56 128 8 8 4 56 5 56 128 8 8 5 56 5 56 128 8 8 5 56 6 64 136 8 8 6 64 6 64 144 8 8 6 64 7 64 144 8 8 7 64 7 64 144 Tabla E.2: Measure in Bytes of Claim data structure E.3.1.3. Claim Claim, as has been explained in the previous chapter is a structure with two string vectors. As can see in the Table E.2, the object uses 8 bytes to it instance, 8 bytes more for the two pointers to the vectors, and: In the first case 40 bytes for an empty vector, but initialized with an empty position. In the next cases, the size of the vector increases when a even data is added due to the padding. For example, in the fourth row of data could be seen that the first vector sizes 48 bytes with two elements, but the second vector sizes 40 bytes with one element. E.3.1.4. AppPolicy Here, the AppPolicy structure is measured. This structure is composed by one string and two vectors, one with Strings and other with Allows elements inside. As in the previous cases, the object instance sizes 8 bytes and the other sixteen bytes for the vectors’ and the String’s pointers (4 for the String and 4 more for padding). The vectors size forty bytes when they are empty and ground in the next way. The string vector increases the space eight bytes for each two strings added as in the Claim as it can be seen in the second and in the fourth lines. In the case of the Allows vector, for each element added the size increases sixteen bytes and eight bytes more in each even data added as in the normal vectors. For instance, when the first element is added (line 2 in Table E.3), the size of the Allows vector increases in sixteen bytes, but in the line 5 of (Table E.3), when the second element has been added, the size has increased in twenty four bytes. E.3.1.5. Contract For the contract, because this structure is made up of two previous structures (Claim and AppPolicy), the size it uses is directly calculated as the addition of the sizes of the elements which 74
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Object Size Vector String String Vector Allows Vector Total Size Pointer Pointer Elements Size Elements Size 8 8 8 0 40 0 40 104 8 8 8 1 40 1 56 120 8 8 8 0 40 1 56 120 8 8 8 2 48 1 56 128 8 8 8 2 48 2 80 152 8 8 8 2 48 3 96 168 8 8 8 3 48 3 96 168 8 8 8 4 56 3 96 176 8 8 8 4 56 4 120 200 8 8 8 4 56 5 136 216 8 8 8 5 56 5 136 216 8 8 8 5 56 6 160 240 8 8 8 6 64 6 160 248 8 8 8 6 64 7 176 264 8 8 8 7 64 7 176 264 Tabla E.3: Measure in Bytes of AppPolicy data structure made up the structure. This is: eight bytes of the object, eight bytes of the vectors pointers, eight bytes of the string pointer and the size of the AppPolicy and the Claim. In the Table E.4, the result of the previous tables has been used as the input data to calculate the examples of size of a Contract. E.3.1.6. Applications This is not exactly a data structure, but is the way which has been used to store the applications contracts in the application. This structure represents the size of all the applications stored in the smart cards. The size necessary is, as in all the previous vectors: forty when it is empty, forty plus the size of the elements in the other cases and eight bytes for each even element added. In the Table E.5, the first column corresponds with the size of the elements added to the vector in order: the first no elements, the second one element sized in two hundred and fifty six bytes, the third two elements, one with two hundred and fifty six (the previous one) and other with two hundred and eighty eight bytes, and so on. The second column represents the number the elements in the vector, the third is the size of the vector without the elements size and the last one is the total size of the applications in the platform. E.3.1.7. PolAllows This structure is which stores the PolAllows information, which make up the policy of the platform after the transformation depending on the security requirements. This structure has only an Allows vector, so the size it needs depends only the data stored in this vector and the constants. If the vector is empty, the size is 8 bytes for the object, 8 bytes for the pointer and forty for the empty vector. For each item added to the vector the size increases in 16 bytes and in 8 more if the item added is assigned to an even position in the vector. 75
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Object Size V. Pointer S. Pointer Claim AppPolicy Total Size 8 8 8 96 104 224 8 8 8 96 120 240 8 8 8 96 120 240 8 8 8 104 128 256 8 8 8 112 152 288 8 8 8 112 168 304 8 8 8 112 168 304 8 8 8 120 176 320 8 8 8 128 200 352 8 8 8 128 216 368 8 8 8 128 216 368 8 8 8 136 240 400 8 8 8 144 248 416 8 8 8 144 264 432 8 8 8 144 264 432 Tabla E.4: Measure in Bytes of Contract data structure New Element String Vector Total Size Size Elements Vector 0 0 40 40 256 1 40 296 288 2 48 592 304 3 48 896 320 4 56 1224 352 5 56 1576 368 6 64 1952 400 7 64 2352 416 8 72 2232 432 9 72 3208 Tabla E.5: Measure in Bytes of Applications data structure Object Size Pointers Allows Vector Total Size Elements Size 8 8 0 40 56 8 8 1 56 72 8 8 2 80 96 8 8 3 96 112 8 8 4 120 136 8 8 5 136 152 8 8 6 160 176 8 8 7 176 192 Tabla E.6: Measure in Bytes of PolAllows data structure 76
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Object Size Pointers String Vector Total Size Elements Size 8 8 0 40 56 8 8 1 40 56 8 8 2 48 64 8 8 3 48 64 8 8 4 56 72 8 8 5 56 72 8 8 6 64 80 8 8 7 64 80 Tabla E.7: Measure in Bytes of Dependents data structure E.3.1.8. Dependents In this structure is where the Dependents of PolNeeds is stored. This structure has only a String vector, so the size it needs depends only the data stored in this vector and the constants. If the vector is empty, the size is 8 bytes for the object, 8 bytes for the pointer and forty for the empty vector. For each two items added to the vector the size increases in 8 bytes starting in the second element added. E.3.1.9. Policy Finally, this structure of the Policy is measured. This structure consists in two vectors, one Dependents and one PolAllows, what means that the size will be the sum of the size of the two vectors plus the constants. This means 8 bytes for the object, 8 for the pointers and the sum of the vectors sizes. Due to exists different ways to increase the size of this structure, three different tables has been attached. In the first one (Table E.8), the number of elements in the two vectors is constant and equal to one, but not the size of this element, because the number of services varies. In the second table (Table E.9), the number of elements in the two vectors vary (Dependents and PolAllows), but the size of this elements is always the same and equal to fifty six and seventy two bytes respectively. The last case (Table E.10) is a mixture of the two previous examples, and both the size of the elements and the number of elements varies. E.3.2. Case of Study Once each structure has been measured separately, is the moment to measure an example of the complete system as it could be in the real life. The real system is composed by three elements, the platform policy, the applications in the card and the integers and constants. The system is made up of five applications with different relations among them as could be in a real system. In the table 4.2 could be seen the five applications which are in the system and which were inserted in the order which appears in the table. During the insertion of these applications in the platform, the policy was created and it can be shown in the Table 4.3. Now, the quantity of the data is inserted in the different tables to obtain the total size of the system. To this values obtained from the tables is necessary to add all the constants and integer 77
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso the APDU command. In this example the output is also correct because the service ”trans¸called by ePurse is provided by the application EMV already installed in the card. EMV@BANK: Provides = (trans) Calls = () Needs = () Allows = (trans, ePurse) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1B 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x06 .ePurse”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 ePurse@BANK: Provides = () Calls = (trans) Needs = () Allows = () Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x11 0x06 .ePurse”0x00 0x01 0x05 ”trans”0x00 0x00 0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 c) Finally, the case where the service called for the incoming application is not allowed is presented. In this case, the application ePurse wants to call the service ”trans”provided by the application EMV, but this application does not allow ePurse to use it and the installation is rejected (see APDU response = 00). EMV@BANK: Provides = (trans) Calls = () Needs = () Allows = (trans, LOA) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x18 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x03 ”LOA”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 ePurse@BANK: Provides = () Calls = (trans) Needs = () Allows = () Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x11 0x06 .ePurse”0x00 0x01 0x05 ”trans”0x00 0x00 0x7F; Response: Le: 02, 00, 00, SW1: 90, SW2: 00 2. The services needed by the incoming application are checked. Two cases are check for this case. 84
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso a) First, if the services needed are provided for the applications already installed in the card. First, two applications which provides services are added. After that, the tested application is sent using the APDU command. Because the services needed by the incoming application are provided by the applications installed in the card, the card responses that the contract matches with the policy. EMV@BANK: Provides = (trans) Calls = () Needs = () Allows = (trans, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 ePurse@BANK: Provides = (pay) Calls = () Needs = () Allows = (pay, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1B 0x06 .ePurse”0x01 0x03 ”pay”0x00 0x00 0x01 0x03 ”pay”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 jTicket@Transport: Provides = () Calls = (trans, pay) Needs = (trans, pay) Allows = () Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x20 0x07 ”jTicket”0x00 0x02 0x05 ”trans”0x03 ”pay”0x02 0x05 ”trans”0x03 ”pay”0x00 0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 b) Lastly, the case when one of the services is not provided is checked. First, two auxiliary applications are installed. After that, the application to test is sent to the card. Because the service .o ¨ıs not provided by the card, the installation is rejected. EMV@BANK: Provides = (trans) Calls = () Needs = () Allows = (trans, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; 85
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Response: Le: 02, 00, 01, SW1: 90, SW2: 00 ePurse@BANK: Provides = (pay) Calls = () Needs = () Allows = (pay, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1B 0x06 .ePurse”0x01 0x03 ”pay”0x00 0x00 0x01 0x03 ”pay”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 jTicket@Transport: Provides = () Calls = (trans, pay) Needs = (trans, pay, o) Allows = () Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x22 0x07 ”jTicket”0x00 0x02 0x05 ”trans”0x03 ”pay”0x03 0x05 ”trans”0x03 ”pay”0x01 .o”0x00 0x7F; Response: Le: 02, 00, 00, SW1: 90, SW2: 00 3. Finally, the services provided by the new application are checked. Three different cases are analyzed. a) First, when none of the services are called. Because none of the services provided by the incoming application are called by the applications already in the card, the installation is accepted. EMV@BANK: Provides = (trans) Calls = () Needs = () Allows = (trans, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 ePurse@BANK: Provides = (the) Calls = () Needs = () Allows = (the, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1B 0x06 .ePurse”0x01 0x03 ”the”0x00 0x00 0x01 0x03 ”pay”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 86
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso b) Secondly, the case when the incoming application provides a service which is called but the application that calls it is not allowed to use it is checked. In this case, because the application installed in the card called jTicket calls the service ”trans.and the incoming application provides this service but the jTicket is not allowed to use it, the installation is rejected. EMV@BANK: Provides = (trans) Calls = () Needs = () Allows = (trans, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 jTicket@Transport: Provides = () Calls = (trans, pay) Needs = (trans) Allows = () Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x07 ”jTicket”0x00 0x02 0x05 ”trans”0x03 ”pay”0x01 0x05 ”trans”0x00 0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 ePurse@BANK: Provides = (pay) Calls = () Needs = () Allows = (pay, other) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x19 0x06 .ePurse”0x01 0x03 ”pay”0x00 0x00 0x01 0x03 ”pay”0x07 .other”0x7F; Response: Le: 02, 00, 00, SW1: 90, SW2: 00 c) Finally, the case when all the services the incoming application provides are called and allowed. In this case, because all the services provided and called are allowed, the installation is accepted. EMV@BANK: Provides = (trans) Calls = () Needs = () Allows = (trans, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 jTicket@Transport: 87
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Provides = () Calls = (trans, pay) Needs = (trans) Allows = () Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x07 ”jTicket”0x00 0x02 0x05 ”trans”0x03 ”pay”0x01 0x05 ”trans”0x00 0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 ePurse@BANK: Provides = (pay) Calls = () Needs = () Allows = (pay, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1b 0x06 .ePurse”0x01 0x03 ”pay”0x00 0x00 0x01 0x03 ”pay”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 G.2. Check of removal an application 1. The first possibility is when an application is tried to be removed and the application Dependents list is not empty. In the example shown below two applications are installed in the card: EMV and ePurse. When the application EMV is tried to be removed from the card, its Dependent list is checked. Because jTicket needs ”trans”, the service EMV provides, the list is not empty and the removal is canceled. EMV@BANK: Provides = (trans) Calls = () Needs = () Allows = (trans, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 jTicket@Transport: Provides = () Calls = (trans, pay) Needs = (trans) Allows = () Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x07 ”jTicket”0x00 0x02 0x05 ”trans”0x03 ”pay”0x01 0x05 ”trans”0x00 0x7F; 88
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Response: Le: 02, 00, 01, SW1: 90, SW2: 00 Try to remove the application EMV: canceled Sent APDU command (Delete command): CLA: A0, INS: 30, P1: 00, P2: 00, Lc: 0x04 0x03 .EMV”0x7F; Response: Le: 02, 00, 00, SW1: 90, SW2: 00 2. The other possibility is when the Dependents list is empty. As it can be seen in the example listed below, the card installs first two applications. After that the EMV is tried to be removed but as it was explained in the previous example, it Dependent list is not empty and the removal is canceled. After this, the card receives the instruction to remove the application jTicket. Because its Dependent list is empty jTicket is removed from the card. After that, EMV is again tried to be removed. Because now its Dependent list is empty the application is removed from the card. EMV@BANK: Provides = (trans) Calls = () Needs = () Allows = (trans, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 jTicket@Transport: Provides = () Calls = (trans, pay) Needs = (trans) Allows = () Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x07 ”jTicket”0x00 0x02 0x05 ”trans”0x03 ”pay”0x01 0x05 ”trans”0x00 0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 Try to remove the application EMV: canceled Sent APDU command (Delete command): CLA: A0, INS: 30, P1: 00, P2: 00, Lc: 0x04 0x03 .EMV”0x7F; Response: Le: 02, 00, 00, SW1: 90, SW2: 00 Try to remove the application EMV: accepted Sent APDU command (Delete command): CLA: A0, INS: 30, P1: 00, P2: 00, Lc: 0x08 0x07 ”jTicket”0x7F; 89
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Response: Le: 02, 00, 01, SW1: 90, SW2: 00 Try to remove the application EMV: accepted Sent APDU command (Delete command): CLA: A0, INS: 30, P1: 00, P2: 00, Lc: 0x04 0x03 .EMV”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 G.3. Check of compliance of AppPolicy update In this algorithm, two possibilities are checked: when the Needs list is modified adding new services and when the Allows list is modified removing old services. 1. For the first case two possibilities are considered: First when the new services added to the list are provided. In this example two applications are added to the card. After that, the application ePurse is modified, adding to its Needs list a new service called ”trans”. Because the service is provided by the applications already installed in the card, the modification is accepted and performed. EMV@BANK: •Provides = (trans) •Calls = () •Needs = () •Allows = (trans, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 ePurse@Bank: •Provides = (pay) •Calls = () •Needs = () •Allows = (pay, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1b 0x06 .ePurse”0x01 0x03 ”pay”0x00 0x00 0x01 0x03 ”pay”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 Try to modify the application ePurse: accepted Sent APDU command (Update command): CLA: A0, INS: 40, P1: 00, P2: 00, Lc: 0x1B 0x06 .ePurse”0x01 0x05 ”trans”0x01 0x03 ”pay”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 The other case is when the modification adds a service to the Needs list but this service is not provided by the applications in the card. In the example, EMV adds the service .another”to its Needs list, which is not provided and the update is canceled. EMV@BANK: 90
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso •Provides = (trans) •Calls = () •Needs = () •Allows = (trans, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 Try to modify the application EMV: canceled Sent APDU command (Update command): CLA: A0, INS: 40, P1: 00, P2: 00, Lc: 00x1C 0x03 .EMV”0x01 0x07 .another”0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 00, SW1: 90, SW2: 00 2. For the second case three different cases are discussed: The first one describes the case when the application referenced by the permission removed from the Allows list is not in the application collection. In the example, the Allows pair (pay, jTicket) is removed from the ePurse Allows list. Because the application referenced is not in the card the modification is accepted. ePurse@Bank: •Provides = (pay) •Calls = () •Needs = () •Allows = (pay, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1b 0x06 .ePurse”0x01 0x03 ”pay”0x00 0x00 0x01 0x03 ”pay”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 Try to modify the application ePurse: accepted Sent APDU command (Update command): CLA: A0, INS: 40, P1: 00, P2: 00, Lc: 0x09 0x06 .ePurse”0x00 0x00 0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 The second example cover the case when the application referenced by the permission is in the application collection but the service is not called. In this example, the pair removed is (pay, jTicket) from the application ePurse. This pair makes reference to the application jTicket which is in the card, but the service ”pay¨ıs not in its Calls list, so the modification is accepted. jTicket@Transport: •Provides = () •Calls = (trans) •Needs = () •Allows = () 91
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 00x12 0x07 ”jTicket”0x00 0x01 0x05 ”trans”0x00 0x00 0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 ePurse@BANK: •Provides = (pay) •Calls = () •Needs = () •Allows = (pay, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1b 0x06 .ePurse”0x01 0x03 ”pay”0x00 0x00 0x01 0x03 ”pay”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 Try to modify the application ePurse: accepted Sent APDU command (Update command): CLA: A0, INS: 40, P1: 00, P2: 00, Lc: 0x09 0x06 .ePurse”0x00 0x00 0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 Finally, the case when the application referenced by the permission is in the application collection and the service is called. In this case, the application update is rejected due to the new contract does not match with the policy in the card. In the example shown below, the pair (trans, jTicket) is tried to be removed from the Allows list of EMV. Because the application jTicket is in the card and it calls ”trans”, the update cannot be accepted. EMV@BANK: •Provides = (trans) •Calls = () •Needs = () •Allows = (trans, jTicket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 jTicket@Transport: •Provides = () •Calls = (trans) •Needs = (trans) •Allows = () Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x18 0x07 ”jTicket”0x00 0x01 0x05 ”trans”0x01 0x05 ”trans”0x00 0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 Try to modify the application EMV: rejected Sent APDU command (Update command): CLA: A0, INS: 40, P1: 00, P2: 00, Lc: 0x06 0x03 .EMV”0x00 0x00 0x7F; 92
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso Response: Le: 02, 00, 00, SW1: 90, SW2: 00 G.4. Check of new contract compliance with the policy In this algorithm is necessary to check five different cases, depending the sets which have been modified. Because two of them test the same cases like in G.3, only the new ones will be explained. These are: 1. A new service is added to the Calls list of the application. Three different cases will be discussed: The first example explains when the service added is not provided in the smart card. As can be seen below, first the application is added to the smart card, and afterwards, the modification adds a new service to the Calls list called ”transp”. Because the service added is not provided the update is accepted and performed. ePurse@BANK: •Provides = (pay) •Calls = () •Needs = () •Allows = (pay, jTIcket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1b 0x06 .ePurse”0x01 0x03 ”pay”0x00 0x00 0x01 0x03 ”pay”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 Try to modify the application ePurse: accepted Sent APDU command (Update command): CLA: A0, INS: 50, P1: 00, P2: 00, Lc: 0x22 0x06 .ePurse”0x01 0x03 ”pay”0x01 0x06 ”transp”0x00 0x01 0x03 ”pay”0x07 ”jTick- et”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 The second example cover the case when the service added is both provided and allowed. In the example, one of the applications installed in the card called jTicket is going to be modified adding a new service to its Calls list named ”pay”. Due to this service is provided by the application ePurse and this application also allows jTicket to use it, the update is executed. EMV@BANK: •Provides = (trans) •Calls = () •Needs = () •Allows = (trans, jTIcket) Sent APDU command (Insert command): CLA: A0, INS: 20, P1: 00, P2: 00, Lc: 0x1C 0x03 .EMV”0x01 0x05 ”trans”0x00 0x00 0x01 0x05 ”trans”0x07 ”jTicket”0x7F; Response: Le: 02, 00, 01, SW1: 90, SW2: 00 jTicket@Transport: 93
Supporting Application’s Evolution in Multi-Application Smart Cards by Security by Contract Rub´en Romart´ınez Alonso [19] X. Leng. Smart card applications and security. ScienceDirect, Report 14:36–45, 2009. [20] C. Bernardeschi M. Avvenuti and N. De Francesco. Java bytecode verification for secure information flow. ACM SIGPLAN n.12, pages 20–27–28, 2003. [21] C. Sprenger M. Huisman, D. Gurov and G. Chugunov. Checking absence of illicit applet interactions: a case of study. LNCS, 2984:84–98, 2004. [22] F. Massacci and O. Gadyatskaya. Loading time policy certification for open multi-application smart cards. [23] M. Montgomery and K. Krishna. Secure object sharing in java card. USENIX Workshop on Smartcard Technology, 1999. [24] O. Gadyastskaya N. Dragoni and F. Massacci. Supporting applications’ evolution for smart cards by security-by-contract. [25] V. Wiles G. Zanon P. Girard P. Bieber, J. Cazin and J-L. Lanet. Checking secure interactions of smart card applets: Extended version. J. of Comp. Sec, 10:396–398, 2002. [26] S. Basu S. Bahatkar R. Sekar, V. N. Venkatakrishnan and D.C. DuVarney. Model-carrying code: a practical approach for safe execution of untrusted applications. ACM Press, pages 15–28, 2003. [27] D. Sauveron. Multiapplication smart card: Towards an open smart card? ScienceDirect, Report 14:70–78, 2009. 100