Centro Polit´ ecnico Superior Universidad de Zaragoza Securing Multi-Application Smart Cards by Security-by-Contract Ingenier ´ ıa en Inform´ atica Proyecto Fin de Carrera Realizado en: Technical University of Denmark Eduardo Lostal Lanza Septiembre 2010 Director: Nicola Dragoni Department of Informatics and Mathematical Modelling Technical University of Denmark Ponente: Francisco Javier Fabra Caro Departamento de Inform´atica e Ingenier´ıa de Sistemas C.P.S, Universidad de Zaragoza
Securing Multi-Application Smart Cards by Security-by-Contract Resumen La tecnolog´ıa de Java Card ha evolucionado hasta el punto de permitir la ejecuci´on de servidores y clientes Web en una tarjeta inteligente. Sin embargo, desarrollos concretos de tarjetas inteligentes multiaplicaci´on no son a´un muy corrientes dado el modelo de negocio de descarga as´ıncrona y actualizaci´on de aplicaciones por diferentes partes que requiere que el control de las interacciones entre las aplicaciones sea hecho despu´es de la expedici´on de la tarjeta. Los modelos y t´ecnicas de seguridad actuales no soportan dicho tipo de evoluci´on en la tartjeta. Un enfoque prometedor para resolver este problema parece ser la idea de Seguridad-mediante- Contrato (S×C). S×Ces un entorno en el que se hace obligatorio que cualquier modificaci´on de una aplicaci´on tras la expedici´on de la tarjeta traiga consigo una especificaci´on de su comportamiento en lo que concierne a seguridad, llamado contrato. Este se debe ajustar a la pol´ıtica de seguridad de la tarjeta multiaplicaci´on. A causa de los recursos limitados de estos dispositivos, el enfoque de S×Cpuede ser aplicado a diferentes niveles de abstracci´on, seg´un un jerarqu´ıa de modelos la cual proporciona beneficios en t´erminos de complejidad computacional o expresividad del lenguaje. El nivel de m´as detalle (mayor expresividad) requiere algoritmos demasiado complejos para ser ejecutados en la tarjeta, por lo que es necesario enviar datos de forma privada a una tercera parte de confianza que ser´a la responsable de realizar la comparaci´on del contrato y la pol´ıtica de la tarjeta (proceso llamado Comparaci´on Contrato-Pol´ıtica) con objeto de decidir si la modificaci´on se ajusta a la pol´ıtica de seguridad o no; es decir, si el cambio es aceptable seg´un el comportamiento esperado por la tarjeta y expresado en su pol´ıtica. El prop´osito del proyecto es desarrollar un sistema el cual resuelva el problema de externalizar el proceso de Comparaci´on Contrato-Pol´ıtica a una entidad externa para tarjetas inteligentes multiaplicaci´on de Java. Este sistema debe garantizar una comunicaci´on segura entre la tarjeta y alguna tercera parte de confianza sobre un medio inseguro. La comunicaci´on tiene que ser segura en t´erminos de autenticaci´on, integridad y confidencialidad. Lograr este objetivo requiere resolver problemas tales como la gesti´on de identidades y claves y el uso de funciones criptogr´aficas para hacer segura la comunicaci´on de datos privados almacenados en la tarjeta inteligente. Es por ello que los objetivos del proyecto son: Dise˜nar un sistema que resuelva el problema Implementar un prototipo que demuestre la validez del sistema Validar el prototipo y valorar su idoneidad en cuesti´on de espacio i
Agradecimientos El presente PFC supone la finalizaci´on de mi estudios en Ingenier´ıa en inform´atica. A pesar de las miles de horas en la biblioteca de filolog´ıa con su techo cay´endose a pedazos (literalmente), estos a˜nos han sido incre´ıbles. En primer lugar, me gustar´ıa dar las gracias a mi familia. Siempre me apoy´ais en lo que necesito. Sin vosotros no ser´ıa la persona que soy. A pesar de nuestras diferencias, no sab´eis lo agradecido que os estoy. Peque˜na t´u tambi´en eres parte de la familia. Gracias por apoyarme y hacerme sonreir. Otra de las personas a las que estoy profundamente agradecido es Nicola. Gracias por la oportunidad de trabajar contigo y toda la confianza que pusiste en mi. El proyecto ha sido muy fruct´ıfero en todos los sentidos y eres bastante responsable de ello. Gracias Javi por tu apoyo y tener siempre un momento para hablar por Skype. Gracias Davide pro tu ayuda, discusiones y sugerencias, ¡disfruta Firenze! Gracias Lawrie y Olaf por vuestra disponibilidad para tratar el proyecto. Gracias a al foro de Java Card y todos los autores de los papers incluidos en las referencias (y los que no que tambi´en consulte). Gracias a la gente de Tinbjerg (y adoptados). No tengo palabras para describir lo incre´ıble que ha sido este a˜no. Gracias a mis amigos que siempre os tengo en mente, a la AMZ y similares. Si lees esto es porque consideras interesante mi trabajo, as´ı que, ¡gracias! iii
´ Indice general Resumen I ´ Indice general VII ´ Indice de figuras X ´ Indice de tablas XI ´ Indice de c´odigos fuente XIII 1. Introducci´on 1 1.1. Tarjetasinteligentes .................................... 1 1.2. Multiaplicaci´on y Seguridad-mediante-Contrato . . . . . . . . . . . . . . . . . . . . . 3 1.3. Contextodelproblema................................... 3 1.4. An´alisisdelasoluci´on ................................... 3 1.5. Objetivosyresultados ................................... 4 1.6. Estructuradelamemoria ................................. 4 2. An´alisis del problema 7 2.1. Seguridad-mediante-Contrato . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 3. Dise˜no de la soluci´on 11 3.1. ConfidencialidadyNonce ................................. 11 3.2. Arquitecturadelsistema.................................. 12 4. Implementaci´on 21 4.1. Herramientas ........................................ 21 4.2. Certificados......................................... 22 4.3. Funcionescriptogr´aficas .................................. 24 v
5. Evaluaci´on 25 5.1. Casodeuso......................................... 25 5.2. Evaluaci´on de los resultados . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 6. Conclusi´on y trabajo futuro 27 6.1. Conclusi´on ......................................... 27 6.2. Limitaciones y problemas encontrados . . . . . . . . . . . . . . . . . . . . . . . . . . 28 6.3. Trabajofuturo ....................................... 29 6.4. Valoraci´onpersonal..................................... 31 A. Gesti´on del tiempo y esfuerzo 33 A.1.Gruposdetareas...................................... 33 A.2.Tareasrealizadas...................................... 34 A.3.Diagramas.......................................... 36 B. Metodolog´ıa de desarrollo 39 C. Smart Card Technology 41 C.1.Types ............................................ 42 C.2. Different Types of Smart Card Communication Interfaces . . . . . . . . . . . . . . . 42 C.3.Hardware .......................................... 44 C.4. Smart Card’s Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 C.5.SecurityinSmartCards.................................. 47 D. Multi-Application Smart Cards 51 D.1.MainStandards....................................... 52 D.2. Open Multi-Application Smart Cards . . . . . . . . . . . . . . . . . . . . . . . . . . 56 E. Security-By-Contract for Multi-Application Smart Cards 59 E.1.MobileCodeSecurity ................................... 59 E.2.Security-by-Contract.................................... 60 F. Extending SxC for Off-card Contract-Policy Matching 65 F.1. Confidentiality and NONCE Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 F.2. Architecture of the System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 G. Implementation of the Prototype 77 vi
G.1.ProgrammingLanguages.................................. 77 G.2. Limitations of the Prototype: Use of Eclipse, CREF and JCWDE . . . . . . . . . . . 80 G.3. Communication and Involved Parts’ Structure . . . . . . . . . . . . . . . . . . . . . . 81 G.4.Certificates ......................................... 82 G.5.CryptographicFunctions.................................. 90 G.6. Some Other Implementation Details . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 H. Case Study 93 H.1.MemoryAnalysis...................................... 98 I. ASN.1 Specifications 103 I.1. Certification Signing Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 I.2. X.509Certificate ......................................104 I.3. Signature ..........................................105 J. Source Code of the Prototype 107 J.1. SmartCard .........................................107 J.2. TrustedReader .......................................107 J.3. TrustedThirdParty.....................................107 J.4. ApplicationIssuer......................................108 K. Source Code for a Real Implementation 109 K.1.SmartCard .........................................109 K.2.TrustedReader .......................................109 K.3.TrustedThirdParty.....................................110 K.4.ApplicationIssuer......................................110 L. Memory Analysis Figures 111 M.Securing Off-Card Contract-Policy Matching in Security-By-Contract for Multi- Application Smart Cards 115 N. Glosario de Acr´onimos 121 N.1.Acr´onimosencastellano..................................121 N.2.Acr´onimoseningl´es ....................................122 Bibliograf´ıa 127 vii
Cap´ıtulo 1 Introducci´on La gran explosi´on de la comunicaci´on digital ha producido en los ´ultimos a˜nos que haya cambiado la forma de interaccionar entre la gente. De ah´ı que muchas organizaciones se esten moviendo hac´ıa formas de comunicaci´on en red debido a los requerimientos de que su informaci´on este disponible y segura al mismo tiempo. Muchas de ellas se han dado cuenta de la ventaja y beneficios que las tarjetas inteligentes ofrecen. Una tarjeta inteligente es un dispositivo capaz de almacenar datos, llevar a cabo funciones por s´ı misma e interactuar de forma inteligente con un lector externo mediante un microprocesador empotrado en un tarjeta de pl´astico. Se ha expandido ampliamente gracias a su facilidad de uso, portabilidad y precio [27]. Son resistentes a la manipulaci´on y proporcionan caracter´ısticas de seguridad que les hace ser considerados dispositivos seguros y de confianza. Esto hace que sean usadas en aplicaciones donde se necesita alta seguridad y apropiadas para sistemas criptogr´aficos y operaciones como autenticaci´on. Son especialmente interesantes las tarjetas inteligentes multiaplicaci´on. No est´an muy extendidas debido al problema del control de las interacciones entres sus aplicaciones, especialmente cuando estas son a˜nadidas despu´es de la emisi´on de la tarjeta. Lo que falta es una forma r´apida de realizar modificaciones sobre aplicaciones de manera as´ıncrona una vez que la tarjeta ha sido emitida. De esta forma, los emisores de las aplicaciones pueden confiar en que su aplicaci´on no ser´a accedida o modificada de forma inesperada. El esquema de Seguridad-mediante-Contrato (S×C) soluciona este problema mediante la comparaci´on de un contrato que acompa˜na la aplicaci´on con la pol´ıtica de la tarjeta. Pero dado que la tarjeta tiene recursos computacionales limitados, puede ser necesario llevar a cabo dicha comparaci´on fuera de la tarjeta, en una tercera parte de confianza. Para ello, es necesario securizar la comunicaci´on entre la tarjeta y esa parte. Esa es la base del problema a resolver. Este proyecto se desarrolla en el marco de una Master Thesis de 30 ECTS en el departamento DTU Informatiks de la Technical University of Denmark (DTU), Lyngby (Copenhagen). Dicho proyecto, previamente a su dep´osito en el Centro Polit´ecnico Superior (C.P.S.) de Zaragoza, ha sido entregado, presentado y evaluado en la DTU obteniendo la nota de 10. 1.1. Tarjetas inteligentes Estos dispositivos est´an ampliamente extendidos por las caracter´ısticas de seguridad que ofrecen a sus usuarios junto a la sencillez de su uso. Su hardware, tipos, aplicaciones, caracter´ısticas f´ısicas y de seguridad son descritas de forma m´as extensa en el Ap´endice C. A continuaci´on se destaca lo m´as importante. Respecto al interfaz de comuniaci´on que utilizan, pueden diferenciarse dos tipos de tarjetas. Los 1
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza ataques que pueden ser llevados a cabo dependen de esta caracter´ıstica. Tarjetas inteligentes de contacto. Para encederse necesitan ser insertadas en un Disposito de Aceptaci´on de Tarjetas (CAD, por sus siglas en ingl´es), que es el interfaz situado entre el host y la tarjeta. El ´area de contacto son ocho celdas que estan en contacto f´ısico con el lector. Una desventaja de estas tarjetas es que pueden empezar a fallar como consecuencia del desgaste de sus celdas. Tarjetas inteligentes sin contacto. La comunicaci´on, as´ı como el suministro de energ´ıa, se lleva a cabo mediante el aire gracias a una antena situada dentro del cuerpo de pl´astico de la tarjeta. Utilizan un interfaz de radio frecuencia [27]. Dado que el chip est´a dentro del pl´astico, est´a m´as protegido y no sufre por el desgaste de sus contactos, luego tienen una vida m´as larga. Son tarjetas m´as fiables, pero m´as caras que las anteriores. En lo concerniente al hardware, una tarjeta inteligente contiene: Microprocesador Normalmente no construidos exclusivamente para tarjetas inteligentes por razones de dinero y seguridad. Los actuales estan basados en arquitecturas de 32-bit Reduced Instruction Set Computer (RISC) [27]. Memoria Dividida en tres partes: de acceso aleatorio (RAM), de solo lectura programable y borrable el´ectricamente (EEPROM) y de solo lectura (ROM). Debido a que cada una de ellas ocupa una cantidad distinta de espacio por bit, se a˜naden siguiendo esta limitaci´on: ROM donde sea posible, despu´es EEPROM y finalmente RAM. Coprocesadores Se trata de hardware suplementario para ayudar al microprocesador en tareas particulares. Los fabricantes son los que deciden cuales incluir debido a que incrementan el precio del chip considerablemente [27]. Los m´as importantes y normalmente a˜nadidos son para algoritmos criptogr´aficos y generaci´on de n´umeros aleatorios. Las principales aplicaciones se muestran a continuaci´on [44][17], m´as informaci´on en Ap´endice C. Telecomunicaci´on Las m´as conocidas son las tarjetas Subscriber Identity Model (SIM). Merece la pena tambi´en mencionar las casi extintas tarjetas prepago para llamar. Banca Tarjetas de cr´edito, d´ebito, etc. Transporte Gran cantidad de tarjetas sin contacto han sido expedidas como las Oyster Card en Londres. Control de acceso Se usan para restringir el acceso f´ısico tanto a lugares como recursos. Identificaci´on Por ejemplo pasaportes electr´onicos. Otras aplicaciones Asistencia sanitaria, autenticaci´on, tarjetas de fidelizaci´on, industria audiovisual, dinero para juegos, e-servicios, mallas de computaci´on, etc. Informaci´on sobre seguridad en tarjetas inteligentes se puede encontrar en el Ap´endice C, secci´on 5. 2
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza 1.2. Multiaplicaci´on y Seguridad-mediante-Contrato En lo que respecta a tarjetas inteligentes, las que despiertan mayor inter´es son las multiaplicaci´on, y especialmente las tarjetas inteligentes multiaplicaci´on abiertas. Su caracter´ıstica m´as importante es la oportunidad de permitir una carga din´amica de aplicaciones. Esto significa tener la posibilidad de a˜nadir, actualizar o eliminar cualquier aplicaci´on en la tarjeta en cualquier momento despu´es de su emisi´on. Las tarjetas m´as conocidas de este tipo son MULTOS y Java Card. Asimismo, merece la pena destacar el est´andar Global Platform. Todo esto se amplia en el Ap´endice D. El problema de este tipo de tarjetas es el control de las interacciones entre las aplicaciones almacenadas en ellas. Estas interacciones pueden llevar a comportamientos indeseados entre las aplicaciones. Por ejemplo, que una aplicaci´on malintencionada consiga datos secretos de otra aplicaci´on relacionada con temas bancarios. Aunque se han desarrollado herramientas como el cortafuegos y el interfaz de compartici´on de objetos (SIO, por sus siglas en ingl´es) de Java Card que intentan corregir estos problemas, ninguna lo hace de forma correcta ya que por ejemplo una aplicaci´on puede utilizar el SIO para sus propios prop´ositos [34]. En definitiva, se pueden llegar a dar intercambios de informaci´on inesperados. La idea de Seguridad-mediante-Contrato (Security-by-Contract,S×C) se ha desarrollado con objeto de resolver este problema. Este enfoque consiste en que cualquier aplicaci´on debe venir acompa˜nada de un contrato que especifique su comportamiento. Este contrato ser´a comparado con la pol´ıtica de seguridad de la tarjeta; si cumple con lo esperado ser´a aceptado y la aplicaci´on instalada, en otro caso ser´a rechazado. De esta forma, s´olo se instalan aplicaciones que cumplan con el comportamiento deseado por la tarjeta. 1.3. Contexto del problema Sin embargo, las tarjetas inteligentes son dispositivos limitados en recursos mientras que el algoritmo que realice la comparaci´on anterior puede llegar a ser considerablemente complejo. Por ello, el esquema de S×Cproporciona una jerarqu´ıa de modelos para la definici´on de contratos y pol´ıticas. Conforme aumenta el nivel de la escala, aumenta la complejidad de la definici´on por lo que se hace necesario mayor esfuerzo computacional. Se espera que en el nivel m´as alto, la tarjeta no pueda llevar a cabo la comparaci´on por lo que sea necesario externalizar esa comparaci´on a un dispositivo externo con mayor potencia computacional. Dado que la informaci´on que se envia en la comunicaci´on es la fundamental (contrato, pol´ıtica y resultado) del esquema propuesto, se debe asegurar dicha comunicaci´on con objeto de que no pueda ser manipulada. Si pudiera llegar a ser modificada, el esquema completo ser´ıa inservible ya que la tarjeta no podr´ıa confiar en lo que el dispositivo externo le manda. El proyecto que cubre este documento se enmarca en la construcci´on de un sistema que resuelva el problema anterior: asegurar la comunicaci´on entre la tarjeta y un dispositivo externo para que la externalizaci´on del proceso de comparaci´on entre el contrato y la pol´ıtica sea confiable. 1.4. An´alisis de la soluci´on La soluci´on al problema anterior se basa en la creaci´on de un sistema criptogr´afico que asegure la comunicaci´on proporcionando mutua autenticaci´on, confidencialidad e integridad. Las identidades se manejan a trav´es de certificados, lo que hace necesario el uso de un analizador sint´actico en la tarjeta para permitir que ella misma pueda verificar dichos certificados. Precisamente el uso de 3
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza certificados junto con el almacentamiento de la pol´ıtica inicial de seguridad de la tarjeta provocan que sea necesario una fase de inicializaci´on de la misma, durante la cual se generan sus certificados y se almacenan junto con la pol´ıtica. Esta fase debe llevarse a cabo de forma previa a la utilizaci´on de la tarjeta, ya que hasta ese momento su uso no es seguro. En esta soluci´on, participan varias entidades con distintos roles: la tarjeta inteligente, un tercera parte de confianza sobre un entorno seguro que se encarga de realizar la inicializaci´on de la tarjeta, otra tercera parte de confianza que realiza la comparaci´on entre contrato y pol´ıtica y finalmente el emisor de la aplicaci´on a a˜nadir que debe almacenar el contrato en la tarjeta para poder llevarse a cabo la comparaci´on previa. Cada entidad realiza comunicaciones de distinto tipo con la tarjeta con diferentes necesidades de seguridad. El proyecto aporta el dise˜no presentado para resolver el problema de la externalizaci´on de la comparaci´on entre contrato y pol´ıtica. Aunque dise˜nos similares se han desarrollado para resolver problemas criptogr´aficos, la contribuci´on del proyecto es el dise˜no e implementaci´on de la soluci´on al problema en un dispositivo de recursos limitados con todo lo que ello implica: comunicaci´on mediante Application Protocol Data Unit (APDU), restricciones de memoria, API limitada, requerimiento de un analizador l´exico a construir en la tarjeta, etc. Particularmente, no solo proporciona dicho dise˜no para tarjetas inteligentes sino que se centra en resolver el problema para el esquema de S×C. 1.5. Objetivos y resultados Los principales objetivos del proyecto, descritos de forma sintetizada, son los mostrados a continuaci´on: Dise˜no del sistema que resuelva el problema previamente explicado Implementaci´on de un prototipo Validaci´on del prototipo Establecido esto, lo que se espera obtener del proyecto es el dise˜no de un sistema que proporcione una comunicaci´on segura para poder confiar en la externalizaci´on de la comparaci´on entre contrato y pol´ıtica para tarjetas multiaplicaci´on. El sistema debe proporcionar mutua autenticaci´on, confidencialidad e integridad. Todo ello se logra mediante una infraestructura de clave p´ublica (PKI, por sus siglas en ingl´es). Dicho dise˜no deber´ıa ir acompa˜nado de un prototipo construido que sirva como prueba de concepto para demostrar la validez del sistema previamente dise˜nado. Estas dos cosas, el dise˜no y el prototipo, son los resultado esperados del proyecto. Por ´ultimo, la validaci´on del prototipo debe ser realizada para asegurar la correcci´on de lo anterior. Asimismo, dado que las tarjetas inteligentes son dispositivos limitados en recursos especialmente de memoria, se espera que se realice alg´un tipo de memoria que permita analizar la idoneidad y viabilidad o no del sistema desarrollado en t´erminos del espacio necesario en la tarjeta para llevar a cabo la idea de S×C. A este sentido, cabe destacar que del prototipo lo que se espera es obtener una implementaci´on funcional y que signifique una acotaci´on superior de sus necesidades de memoria. En otras palabras, no se espera obtener una versi´on optimizada de dicho prototipo. 1.6. Estructura de la memoria La parte principal de esta memoria, excluyendo los ap´endices, se estructura en cinco cap´ıtulos que siguen el siguiente orden: 4
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza 1. An´alisis del problema. Detalla el problema a resolver partiendo de un resumen del trabajo relacionado y el marco sobre el que se situa. 2. Dise˜no de la soluci´on. Describe la arquitectura del sistema propuesto como soluci´on al problema a resolver. 3. Implementaci´on. En esta secci´on se aportan detalles de la implementaci´on de la soluci´on, incluyendo cambios necesarios en el dise˜no para la construcci´on del prototipo. 4. Evaluaci´on. Presenta un ejemplo de utilizaci´on del sistema en forma de gu´ıa de usuario, as´ı como un an´alisis de la memoria empleada por el sistema. 5. Conclusion. Contiene la conlusi´on, limitaciones y problemas encontrados, sugerencias de trabajo futuro y una valoraci´on personal de lo que ha supuesto el desarrollo del proyecto. Adicionalmente, con objeto de detallar el trabajo llevado a cabo se incluyen dos ap´endices que contienen la gesti´on del tiempo y esfuerzo (Ap´endice A) y la metodolog´ıa de desarrollo (Ap´endice B). Mediante la inclusi´on de ambos ap´endices, se pretende que el lector tenga una idea m´as clara de las tareas realizadas, el esfuerzo invertido y la forma de llevarlas a cabo. La memoria resultante del proyecto desarrollado en la Technical University of Denmark (DTU) ha sido a˜nadida en forma de ap´endices correspondiendo cada uno de ellos con los diferentes cap´ıtulos de dicho documento. As´ı pues, los anexos que van desde el Ap´endice C hasta el H, contienen los cap´ıtulos de la memoria, mientras que los ap´endices desde el I hasta el L contienen sus anexos. Todos estos anexos que corresponden a la memoria desarrollada y presentada en DTU, se encuentran en ingl´es. Dado que la memoria completa desarrollada para la universidad danesa es m´as detallada, en la presente, de menor longitud, se har´an constantes referencias a los ap´endices que contienen la primera con objeto de completar la informaci´on sobre el trabajo desarrollado. Resultados preliminares del proyecto fueron aceptados y ser´an presentados en forma de publicaci´on el pr´oximo octubre en ”The Fourth International Conference on Mobile Ubiquitous Computing, Systems, Services and Technologies (Ubicomm) 2010”. Dicha publicaci´on, cuya referencia se muestra a continuaci´on, se puede encontrar en el Ap´endice M. [M] Nicola Dragoni, Eduardo Lostal, Davide Papini, and Javier Fabra. Securing Off-Card Contract- Policy Matching in Security-By-Contract for Multi-Application Smart Cards. Ubicomm: The Fourth International Conference on Mobile Ubiquitous Computing, Systems, Services and Technologies, 2010. Accepted for publication. Por ´ultimo, cabe destacar que a lo largo del presente documento (tanto en los cap´ıtulos como especialmente en los ap´endices) se hace continuo uso de acr´onimos, por lo que se aconseja al lector la lectura del correspondiente glosario (Ap´endice N), tanto de su secci´on de castellano como de ingl´es. 5
Cap´ıtulo 2 An´alisis del problema Las tarjetas inteligentes multiaplicaci´on permiten a los consumidores hacer una gesti´on (descarga y eliminaci´on) din´amica de las aplicaciones durante el ciclo de vida de la tarjeta. La raz´on por la que ejemplos de estas tarjetas a´un son raros es por la falta de soluci´on al control de las interacciones entre las aplicaciones. De hecho el modelo de negocio de descarga y actualizaci´on as´ıncrona de aplicaciones por diferentes partes requiere el control de las interacciones entre las posibles aplicaciones tr´as la emisi´on de la tarjeta. La clave es asegurar a los emisores de las aplicaciones que estas no ser´an accedidas por otras indeseadas a˜nadidas tras ellas, o al menos que sus aplicaciones s´olo interaccionar´an con otras de algunos socios de negocio. El estado del arte de este problema se puede encontrar en el Ap´endice E. 2.1. Seguridad-mediante-Contrato Seguridad-mediante-Contrato es el esquema propuesto para prevenir el intercambio ilegal de informaci´on entre diversas aplicaciones, comprobando las interacciones en el momento de carga de la aplicaci´on en la tarjeta. S×Cresuelve tambi´en el problema de los cambios despu´es de la emisi´on de la tarjeta, es decir carga, eliminaci´on o actualizaci´on din´amica de aplicaciones durante el ciclo de vida de la tarjeta. En otras palabras, la evoluci´on din´amica del contenido de la tarjeta inteligente. El enfoque de S×Cse construye sobre la idea de C´odigo Conteniendo el Modelo (MCC por sus siglas inglesas) y ha sido apropiadamente desarrollado para entornos de c´odigo m´ovil ([33]), intentando adaptarse a la tecnolog´ıa de tarjetas inteligentes. En t´erminos generales, consiste en la idea de contrato que especifica el comportamiento de la aplicaci´on, de pol´ıtica que especifica la pol´ıtica de seguridad de la tarjeta y el algoritmo de comparaci´on que comprueba si el contrato se ajusta a la pol´ıtica. El objetivo es hacer esta comprobaci´on cuando se carga la aplicaci´on en la tarjeta ahorrando costosas monitarizaciones en tiempo de ejecuci´on. Los problemas que este esquema pretende resolver se pueden resumir como lo hace [35] en: 1. Una nueva aplicaci´on no deber´ıa interaccionar con aplicaciones prohibidas ya almacenadas 2. Un cambio din´amico no deber´ıa afectar al funcionamiento correcto de applicaciones ya almacenadas. Estos cambios pueden ser: Adici´on de una nueva aplicaci´on Actualizaci´on de una aplicaci´on Cambios en la pol´ıtica de la tarjeta Eliminaci´on de una aplicaci´on 7
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Un contrato es una especificaci´on completa, correcta y formal del comportamiento de una aplicaci´on en lo que respecta a acciones de seguridad relevantes y particularmente con problemas de intercambio de datos sensibles. No solo almacena el comportamiento de la aplicaci´on sino el deseable para otras aplicaciones en relaci´on a communicaciones directas o indirectas con ellas [34]. El objetivo es que una nueva aplicaci´on sea capaz de expresar su deseo de interactuar con otras a´un no presentes en la tarjeta, por ejemplo. El contrato es proporcionado por el emisor de la aplicaci´on quien es el responsable de adjuntarlo a la aplicaci´on a ser instalada. Una pol´ıtica es una especificaci´on formal y completa del comportamiento aceptable para las aplicaciones que esperan ser ejecutadas en la tarjeta en lo que respecta a sus acciones relevantes de seguridad (ambas definiciones obtenidas de [33]). La pol´ıtica inicial debe ser creada por el emisor de la tarjeta. Es el responsable de preparar los requerimientos de la tarjeta. 2.1.1. Esquema de trabajo de la Seguridad-mediante-Contrato En lo que respecta a S×Cpara c´odigo m´ovil, la plataforma objetivo (i.e., tarjetas inteligentes) sigue un esquema similar al mostrado en la Figura E.1 en tiempo de carga de la aplicaci´on. Primero, comprueba que la evidencia es correcta. Tal evidencia puede ser una firma digital. Como alternativa a la evidencia puede usarse cualquier tipo de prueba confirmando que el c´odigo satisface el contrato (i.e., [15] para tarjetas inteligentes). Una vez que se tiene la evidencia de que el contrato es digno de confianza, la plataforma comprueba que este se ajusta a la pol´ıtica de la plataforma objetivo. Este proceso es la Comparaci´on Contrato-Pol´ıtica. Si se ajusta, la aplicaci´on se puede lanzar. La comparaci´on garantiza que las interacciones resultantes son correctas. Esto resulta en un ahorro considerable sobre el uso de monitores de referencia en ejecuci´on [32]. Volviendo a las tarjetas inteligentes, el algoritmo de comparaci´on deber´ıa dar un resultado positivo s´olo en el caso que cada petici´on del contrato sea conforme a todos los requerimientos de seguridad que la tarjeta requiere. Particularmente, ambos deber´ıa coincidir si no dan lugar a ninguna fuga o intercambio ilegal de informaci´on entre la nueva aplicaci´on y otra existente en la tarjeta. 2.1.2. Jerarqu´ıa de modelos de contrato/pol´ıtica Se considera m´as seguro realizar la comprobaci´on previa en la misma tarjeta, ya que supone no tener que confiar en entidades externas. Su caracter´ıstica de resistencia a la manipulaci´on de los contenidos hace que las operaciones en la tarjeta sean m´as confiables. Sin embargo, dados sus recursos limitados puede llegar a ser neceario que algunas operaciones se lleven a cabo fuera de la tarjeta [25]. Es precisamente por dichas limitaciones computacionales por las que S×Cpropone una jerarqu´ıa de modelos para contratos y pol´ıticas. ´ Estos tienen diferentes caracter´ısticas en cada nivel de la jerarqu´ıa especificando el comportamiento de la aplicaci´on con diferente profundidad en funci´on de la capacidad computacional esperada para ese nivel. En otras palabras, cada nivel trabaja sobre diferentes capacidades computacionales y tiene diferentes limitaciones de expresividad acorde a ellas. Por ejemplo, el nivel m´as bajo tiene los mayores beneficios en t´erminos computacionales, pero sus contenidos pierden en expresividad; es decir, son menos concretos. Por otra parte, el nivel m´as alto necesita de muchos recursos del procesador, pero permite una completa especificaci´on de contratos y pol´ıticas. Los niveles propuestos son [34]: 8
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza L0: Aplicaci´on como servicio. En este nivel las aplicaciones son definidas como una lista de servicios disponibles y requeridos, similares a la configuraci´on de Global Platform. Este es el nivel que necesita menos esfuerzo computacional y presumiblemente puede ser llevado a cabo en la propia tarjeta. L1: Flujo de control permitido. Este nivel construye un grafo representando la aplicaci´on donde los v´ertices son los estados de esta y las aristas la invocaci´on de diferentes servicios. Permite realizar un control de la informaci´on m´as detallado. Los niveles m´as abstractos se basan en ´el, a˜nadiendo otras caracter´ısticas. L2: Flujo de control deseado y permitido. A˜nade estados correctos y de error al grafo previo. El objetivo es proporcionar una forma de comprobar que cualquier cambio en la pol´ıtica o la eliminaci´on de una aplicaci´on no evite el correcto funcionamiento del resto. L3: Flujo completo de informaci´on. En este nivel, el grafo es mejorado a˜nadiendo el flujo de informaci´on entre las variables. Requiere el esfuerzo computacional m´as alto. 2.1.2.1. Limitaci´on del nivel 0 El problema del nivel 0 es que s´olo captura el posible intercambio de informaci´on entre las aplicaciones en lugar del real; lo que significa que no puede especificar el comportamiento de una aplicaci´on. Como [35] refleja, no es posible distinguir entre servicios que una aplicaci´on puede necesitar de los que realmente requiere. Por ejemplo, supongamos que una aplicaci´on A en la tarjeta, la cual se quiere eliminar, proporciona un m´etodo que otra aplicaci´on B puede requierir. Lo que el nivel 0 no puede comprobar es si la aplicaci´on B seguir´a trabajando apropiadamente tras quitar la aplicaci´on A. Para hacerlo necesita otro nivel de abstracci´on. Tampoco puede capturar las comunicaciones indirectas entre las aplicaciones. Esa es la raz´on por la que para un nivel de seguridad m´as alto es apropiado usar alg´un otro nivel. El problema radica en la capacidad computacional limitada para realizar la Comparaci´on Contrato-Pol´ıtica en la tarjeta para niveles m´as altos. Por ello, cuando dicha tarea requiere un gran esfuerzo es posible externalizar esa fase a una Tercera Parte de Confianza (TPC). Esto se llama Externalizaci´on de la Comparaci´on Contrato-Pol´ıtica. 2.1.3. Problema: Securizando la externalizaci´on de la Comparaci´on Contrato-Pol´ıtica La idea de la externalizaci´on de la Comparaci´on Contrato-Pol´ıtica se muestra en la Figura E.2. Se lleva a cabo cuando la fase de comparaci´on es demasiado pesada (computacionalmente hablando) para realizarla en la tarjeta. En ese caso, es necesario hacer uso de una TPC que proporcione sus capacidades computacionales para correr el algoritmo de comparaci´on. La TPC puede proporcionar una prueba de la conformidad a la tarjeta inteligente, la cual debe verificarla. La pol´ıtica de la tarjeta inteligente (TI) se actualiza seg´un el resultado de la comparaci´on recibida de TPC: si la comprobaci´on ha sido exitosa, la pol´ıtica se actualiza con el nuevo contrato y la aplicaci´on puede ser ejecutada. De otra forma, la aplicaci´on se rechaza. En caso de que TPC incluya una prueba de la comparaci´on en la respuesta, ´esta debe ser verificada como se muestra en la Figura E.2. Dado que la comunicaci´on entre TI y TPC se lleva a cabo sobre un entorno inseguro, tiene que ser securizada. El sistema debe asegurar autenticaci´on, confidencialidad e integridad de los datos enviados durante toda la comunicaci´on. Para garantizar la autenticaci´on e integridad, las dos partes (TI y TPC) tienen que cifrar y firmar sus mensajes por medio de sus parejas de claves. Deber´ıan mantener su clave privada secreta y enviar sus claves p´ublicas a la otra entidad. Por tanto, es necesario alg´un tipo de intercambio de claves al inicio. 9
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza aplicaciones de la tarjeta, ya sea adici´on, actualizaci´on, eliminaci´on de aplicaciones o cambios en la pol´ıtica. Esta fase se ejecuta posteriormente a la de almacenamiento del contrato. La fase de Comparaci´on Contrato-Pol´ıtica tiene tres etapas: 1. Intercambio de certificados 2. Env´ıo de contrato y pol´ıtica 3. Env´ıo del resultado de la comparaci´on El proceso entero se puede observar en la Figura 3.4. Tercera Parte de Confianza (TPC) Tarjeta Inteligente (TI) TPCCertCifr Verificación del certificado de TPC Verificación del certificado de TI Verificación del certificado de TPC TICertFirm Generación: CSes, N_ti Cifrado: C_CSes(M), C_TPCCPuCif(CSes), C_TPCCPuCif(N_ti) Firma digital: F_TICPrFir(HMAC(M,N_ti)) [C_TPCCPuCif(CSes), C_TPCCPuCif(N_ti), C_CSes(M), F_TICPrFir(HMAC(M,N_ti))] Orden contrato y política Firma digital: F_TPCCPrFir( HMAC(R,N_ti +1)) Descifrado, verificación y obtención del resultado Descifrado y verificación Correr algoritmo TPCCertFirm TICertCifr Intercambio de certificados Envío de contrato y política Envío del resultado de la comparación Cifrado: C_CSes(R) [C_CSes(R), F_TPCCPrFir(HMAC(R,N_ti+1))] Verificación del certificado de TI Confirmación Figura 3.4: Diagrama de la fase de Comparaci´on Contrato-Pol´ıtica 3.2.4.1. Intercambio de certificados El intercambio de los certificados entre la tarjeta y el TPC se lleva a cabo por medio de mensajes que incluyen los correspondientes certificados. Cada parte tiene que intercambiar dos certificados con la otra parte: una para cifrar y otro para firmar. Lo que significa que cuatro mensajes son necesarios para completar el intercambio donde dos son de TPC y otros dos de TI. TPC comienza la comunicaci´on enviando su certificado en un Comando. El analizador en TI deber´ıa verificar el certificado con el de la AC almacenado. El analizador tambi´en obtiene la clave p´ublica de TPC para cifrar. Si la verificaci´on es positiva (el certificado es v´alido), TI responde con una Respuesta incluyendo su certificado para cifrar. TPC verifica este certificado y obtiene la clave 16
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza p´ublica correspondiente. Este proceso se repite para intercambiar los certificados para firmar. Se puede observar en la Figura 3.4. Los datos enviados durante esta etapa son: Comando 1: TPCCertCifr, certificado de TPC para cifrar Respuesta: TICertCifr Comando 2: TTPCertFirm, certificado de TPC para firmar Respuesta 2: TICertFirm 3.2.4.2. Env´ıo de contrato y pol´ıtica Cuando el intercambio de certificados ha terminado, TPC tiene que pedir el contrato y la pol´ıtica que se encuentran en la tarjeta. As´ı pues, env´ıa un Comando sin datos para realizar la petici´on. Tanto el contrato como la pol´ıtica se env´ıan dentro del mismo mensaje con objeto de reducir la cantidad de mensajes a intercambiar, esto es: TIContratoPol´ıtica (las siglas TI se a˜naden para diferenciar los datos entre los enviados y los recuperados en la verificaci´on TPCContratoPol´ıtica, que se utilizar´a m´as adelante). Contrato y pol´ıtica tienen que estar cifrados y firmados por la tarjeta antes de ser enviados para asegurar los requerimientos del sistema (autenticaci´on, confidencialidad e integridad). El cifrado se realiza a trav´es de criptograf´ıa sim´etrica en bloque. La raz´on de usar este tipo de cifrado en lugar de criptograf´ıa asim´etrica (basada en PKI) es que la segunda es m´as lenta cuando se realiza sobre una cantidad considerable de datos, mientras que el cifrado sim´etrico proporciona una velocidad de cifra m´as alta (tambi´en de descifrado ya que es la misma operaci´on). Adem´as, la criptograf´ıa sim´etrica proveer´a alta seguridad debido a su falta de linealidad (clave aleatoria y diferente en cada sesi´on) y que normalmente s´olo ataques de fuerza bruta suelen funcionar (aunque depende del algoritmo ya que por ejemplo DES puede ser roto por criptoan´alisis [8]). En definitiva, un cifrador en bloque es apropidado para ser usado sobre una cantidad de datos grande. Usar criptograf´ıa sim´etrica implica que ambas partes deben conocer la clave. As´ı que la tarjeta, que es la genera la clave, tiene que enviar la clave compartida a TPC. Pero dicha clave no puede enviarse en texto plano ya que un intruso podr´ıa interceptar el mensaje y descifrar su contenido (no tiene sentido enviar el mensaje cifrado junto con la clave en plano con la que descifrar el mensaje). Es por eso que se cifra esta clave por medio de la clave p´ublica de TPC, asegurando que ´este ser´a el ´unico capaz de descifrarla. El cifrado se hace esta vez por medio de criptrogaf´ıa asim´etrica ya que se trata s´olo de unos pocos cientos de bits como m´aximo. La clave para criptograf´ıa sim´etrica cambiar´a en cada sesi´on para asegurar un nivel m´as alto de seguridad asegurando su frescura y aleatoriedad. La secuencia de acciones a realizar por la tarjeta para securizar la Respuesta a TPC conteniendo el contrato y la pol´ıtica es la siguiente: 1. Generar una clave de sesi´on que ser´a usada para criptograf´ıa sim´etrica: Cses 2. Generar el Nonce: NT I 3. Cifrar la clave de sesi´on a trav´es de la clave p´ublica de TPC para cifrar: CifT P CCP uCif (Cses) 4. Cifrar el Nonce a trav´es de la clave p´ublica de TPC para cifrar: CifT P CCP uCif (NT I ) 17
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza 5. Cifrar el mensaje con la clave de sesi´on: CifCses (TIContratoPol´ıtica) 6. Calcular el HMAC (un hash mezclado con un salt) del contenido: HMAC(TIContratoPol´ıtica, NT I ) 7. Firmar el HMAC anterior con la clave para firmar: FirT ICP rF ir(HMAC(TIContratoPol´ıtica, NT I )) Se usa una funci´on Hash-based Message Authentication Code (HMAC)para crear la firma en lugar de una funci´on de Hash normal como Secure Hash Algorithm (SHA), ya que HMAC a˜nade una clave compartida (llamada salt) que asegura la frescura del resumen: cada HMAC construido con difererente salt dar´a lugar un resumen diferente. Adem´as, garantiza que s´olo las partes de la comunicaci´on que conozcan esta clave compartida podr´an generar el resumen y comprobar por tanto su integridad. Para construir este tipo de resumen, es necesario un n´umero aleatorio renovado en cada sesi´on. Dado que el Nonce se ajusta perfectamente a estas caracter´ısticas, es el usado. Finalmente, la Respuesta segura construida para contestar a la petici´on del TPC es la siguiente: Respuesta: [CifT P CCP uCif (Cses), CifT P CCP uCif (NT I ), CifCses (TIContratoPol´ıtica), FirT ICP rF ir(HMAC(TIContratoPol´ıtica, NT I ))], que contiene: •Clave de sesi´on cifrada: CifT P CCP uCif (Cses) •Nonce cifrado: CifT P CCP uCif (NT I ) •Contrato y pol´ıtica cifrados: CifCses (TIContratoPol´ıtica) •Firma: FirT ICP rF ir(HMAC(TIContratoPol´ıtica, NT I )) TPC recibe la Respuesta, la cual tiene que descifrar y verificar. Para comprobar la integridad y autenticidad construye un HMAC del contenido que acaba de descifrar y lo compara con el HMAC que ha obtenido del descifrado de la firma. Si ambos HMAC coinciden, la autenticidad ha sido probada ya que s´olo la tarjeta puede firmar con su clave privada. La integridad por su parte, tambi´en habr´a sido comprobada ya que si ambos HMAC coinciden significa que los datos sobre los que el HMAC se ha realizado, coinciden con los descifrados, es decir, que nadie ha podido modificar el contenido. Obviamente, dado que dichos datos estaban cifrados, la confidencialidad tambi´en se ha cumplido. La secuencia de acciones necesarias para llevar a cabo la verificaci´on son las siguientes: 1. Descifrar la clave de sesi´on: DesT P CCP rCif (CifT P CCP uCif (Cses)) = Cses 2. Descifrar el Nonce: DesT P CCP rCif (CifT P CCP uCif (NT I )) = NT I 3. Obtener el contrato y pol´ıtica descifrando con la clave de sesi´on: DesCses (CifCses (TPCContratoPol´ıtica)) = TPCContratoPol´ıtica 4. Calcular el HMAC del contrato y la pol´ıtica descifrados: HMAC(TPCContratoPol´ıtica, NT I ) 18
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza 5. Descifrar la firma a trav´es de la clave p´ublica para firmar de la tarjeta: DesT ICP uF ir(FirT ICP rF ir(HMAC(TIContratoPol´ıtica, NT I ))) = HMAC(TIContratoPol´ıtica, NT I ) 6. Si el HMAC calculado en el TPC a trav´es del contenido descifrado del mensaje coincide con el HMAC obtenido de la firma del mensaje, los requerimientos de autenticidad, confidencialidad e integridad han sido cumplidos; de otra forma, no. Esto es: If (HMAC(TIContratoPol´ıtica, NT I ) == HMAC(TPCContratoPol´ıtica, NT I )) →Mensaje OK else →Requerimientos no cumplidos Si la verificaci´on es correcta, TPC ha obtenido el contrato y la pol´ıtica de una forma segura. 3.2.4.3. Env´ıo del resultado de la comparaci´on Una vez el contrato y la pol´ıtica estan en posesi´on de TPC, ´este puede ejecutar el algoritmo de comparaci´on obteniendo el resultado correspondiente. Tras esto, tiene que construir un Comando seguro que lo contenga para ser enviado a la tarjeta de una forma similar ha como ha sido realizado antes el env´ıo del contrato y la pol´ıtica. La clave usada para cifrar es la misma clave recibida antes y usada para descifrar previamente el mensaje (contrato y pol´ıtica). As´ı que en primer lugar se cifra el resultado con esta clave. La firma se realiza como antes con la diferencia que el HMAC usa como salt en este caso el valor NT I+1 en lugar del anterior. Este cambio se hace para asegurar que TPC ha podido leer, almacenar y modificar el Nonce. Adem´as, supone una medida contra ataques dado que incrementa la aleatoriedad de la clave. Gracias a ello, la funci´on HMAC cambia ya que la clave usada para la operaci´on de cifrado es diferente; por tanto, incrementa el esfuerzo de un atacante que intente falsificar el HMAC. La secuencia de acciones que tiene que seguir TPC para construir el Comando a la tarjeta es la siguiente: 1. Cifrar el resultado del algoritmo con la clave de sesi´on: CifCses (TPCResultado) 2. Calcular el HMAC del contenido: HMAC(TPCResultado, NT I+1) 3. Firmar el HMAC anterior con la clave para firmar: FirT P CCP rF ir(HMAC(TPCResultado, NT I+1)) Finalmente, el Comando construido para enviar a la tarjeta conteniendo el resultado es: Comando: [CifCses (TPCResultado), FirT P CCP rF ir(HMAC(TPCResultado, NT I+1))], que contiene: •Resultado cifrado: CifCses (TPCResultado) •Firma: FirT P CCP rF ir(HMAC(TPCResultado, NT I+1)) De la misma forma que TPC ha verificado el mensaje anterior, la tarjeta tiene que hacerlo en este momento. La secuencia de acciones a llevar a cabo es la siguiente: 19
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza 1. Obtener el resultado descifrando con la clave de sesi´on: DesCses (CifCses (TIResultado)) = TIResultado 2. Calcular el HMAC del resultado descifrado: HMAC(TIResultado, NT I+1) 3. Descifrar la firma a trav´es de la clave p´ublica para firmar de TPC: DesT P CCP uF ir(FirT P CCP rF ir(HMAC(TPCResultado, NT I+1))) = HMAC(TPCResultado, NT I+1) 4. Si el HMAC calculado en TI a trav´es del contenido descifrado del mensaje coincide con el HMAC obtenido de la firma incluida en el mensaje, entonces los requerimientos de autenticaci´on, confidencialidad e integridad han sido cumplidos; de otra forma no. Esto es: If (HMAC(TPCResultado, NT I+1) == HMAC(TIResultado, NT I+1)) →Mensaje OK else →Requerimientos no cumplidos Si el Comando es correcto, la tarjeta puede obtener el resultado y enviar una confirmaci´on a TTP en una Respuesta. Con el resultado, la tarjeta puede decidir si la aplicaci´on deber´ıa ser instalada en la tarjeta o no. 20
Cap´ıtulo 4 Implementaci´on Con el objetivo de validar el dise˜no previo del sistema para resolver el problema de la externalizaci´on de la Comparaci´on Contrato-Pol´ıtica se construy´o un prototipo. Este prototipo debe interpretarse como una prueba de concepto en el sentido que lo que se pretende con su construcci´on es obtener una prueba funcional que demuestre que el sistema dise˜nado es viable. Esto significa que no es necesario su funcionamiento en una tarjeta real, ni se espera obtener una versi´on optimizada de su c´odigo. Con estas premisas, se construye el prototipo para ser usado sobre un simulador cuyas limitaciones provocan la necesidad de realizar diversos cambios sobre el dise˜no previo. Cabe destacar que las especificaciones de los dominios de seguridad de Global Platform no han sido tenidos en cuenta por limitaciones de tiempo. Esta es una de las mejoras propuestas como trabajo futuro. Durante el cap´ıtulo se tratar´an las herramientas utilizadas durante esta fase, as´ı como todo lo relacionado con certificados y funciones criptogr´aficas. Algunos comentarios que no encajan en ninguna de estas secciones se pueden encontrar en la ´ultima parte del Ap´endice G. De hecho, este cap´ıtulo se halla considerablemente m´as detallado en el citado ap´endice. 4.1. Herramientas En esta secci´on se detallan las herramientas utilizadas en la etapa de implementaci´on; es decir, lenguajes de programaci´on, entorno, simuladores, etc. Los lenguajes de programaci´on utilizados han sido dos dependiendo de la plataforma de cada entidad. As´ı pues, para EA, LS y TPC se ha utilizado Java con la versi´on del Java Development Kit (JDK) 1.6.0.18. Cabe destacar que se ha hecho uso de los paquetes sun.*; que no pertenecen a la API de Java, pero s´ı est´an disponibles dentro del Software Development Kit (SDK) incorporado en el JDK. No es recomendable su uso dado que al no ser parte de la API, Sun no se compromete a mantenerlos en las diferentes versiones del JDK. Es por ello, que se puede garantizar que el prototipo funciona para el JDK especificado, pero no en otro diferente. Este tema se trata en profundidad en el Ap´endice G y el reemplazo de dichos paquetes se propone como trabajo futuro. Por su parte para TI se ha utilizado Java Card en su versi´on 2.2.2. Por qu´e no se ha utilizado la versi´on 3 de este lenguaje se explica en la correspondiente secci´on del Ap´endice G. Las razones por las que se usan y m´as caracter´ısticas de estos lenguajes se explican en el apartado “Programming Languages” de dicho ap´endice. El entorno de programaci´on utilizado ha sido Eclipse SK 3.5.2. Sobre ´el se lanzaban las entidades externas a la tarjeta. Mientras que para simular la tarjeta esta se lanzaba directamente por l´ınea de comandos sobre el simulador. Los simuladores que se han utilizado han sido dos, dependiendo de la etapa de la implementaci´on: 21
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Java Card platform Workstation Development Environment tool (JCWDE) para la primera parte que no almacenaba el estado de la tarjeta C-language Java Card Runtime Environment (CREF) para la segunda cuando era necesario que la tarjeta recordara su estado de una simulaci´on a otra As´ı pues, JCWDE se utiliz´o para la primera parte de la implementaci´on cuando se trabaj´o en la generaci´on y almacenamiento de certificados, ya que la tarjeta no necesitaba recordar su estado tras la ´ultima simulaci´on. CREF fue utilizado en el resto del desarrollo cuando era necesario hacer uso de memoria persistente. Este simulador crea una imagen de la memoria de la tarjeta que permite recuperar su estado cuando se vuelve a realizar una simulaci´on. Ambos simuladores tienen el mismo problema y es que no soportan todas las clases de la API de Java Card 2.2.2. Esto ha provocado que el prototipo sea construido con limitaciones en las longitudes de clave y, dada la falta de algunos algoritmos necesarios para la implementaci´on realizada, con cambios en el dise˜no del sistema para poder obtener el prototipo trabajando. Estos cambios son asumibles dado el objetivo del prototipo, pero no lo ser´ıan para una implementaci´on en una tarjeta real. Es por ello, que durante esta etapa se construyeron dos c´odigos fuente distintos que son el del prototipo y una implementaci´on preparada para su uso en una tarjeta real que soporte los algoritmos necesarios. Dichas implementaciones se pueden encontrar en los ap´endices J (prototipo) y K (real). Se ofrece una explicaci´on m´as detallada de entorno de programaci´on, simuladores y sus limitaciones en el Ap´endice G. 4.2. Certificados En esta secci´on se examina todo lo referente a los certificados: generaci´on, gesti´on, an´alisis, etc. Se han utilizado los tipos de certificados X.509. Para familiarizarse y trabajar con ellos, es necesario tener conocimientos sobre Abstract Syntax Notation One (ASN.1) y las codificaciones Basic Encoding Rules (BER) y Distinguished Encoding Rules (DER). En el Ap´endice G, se detallan las referencias donde poder buscar informaci´on de estas especificaciones y codificaciones. Asimismo, las especificaciones de ASN.1 para los CSRs y los certificados se encuentran en el Ap´endice I. 4.2.1. CSRs y generaci´on de certificados La implementaci´on de la generaci´on de certificados se ha realizado por medio de OpenSSL. Primero se genero un certificado autofirmado para la AC. Con ´el, OpenSSL era capaz de construir los certificados a partir de los CSRs y firmarlos con esta AC. La construcci´on de los CSRs se realiza en el LS por medio de clases incluidas en paquetes sun.*, cuya conveniencia se ha comentado anteriormente. Estos paquetes facilitan clases para trabajar tanto con DER como con Base64, lo cual es necesario para la generaci´on de los CSRs. El proceso m´as complicado fue la generaci´on de la firma del certificado, la cual debe ser enviada a TI para ser firmada. Es decir, se prepara la estructura a firmar en el LS y se env´ıa a TI, el cual la devuelve firmada. Dicha estructura tiene la siguiente forma: 00 || 01 || PS || 00 || T, donde: T es la codificaci´on DER de la estructura digestInfo (consultar especificaci´on de ASN.1 en C´odigo I.6) PS es una cadena de octetos de longitud k-3-||T|| con valor FF. Su longitud debe ser de al menos 8 octetos k es el tama˜no de m´odulo del algoritmo de Rivest, Shamir and Adleman (RSA) 22
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Esto debe ser enviado a la tarjeta para ser cifrado con la clave privada de TI. Pero surge un problema y es que dado que la estructura previa se construye seg´un el esquema de PKCS#1 v1.5 (Public- Key Cryptography Standard), el relleno (padding) ya ha sido a˜nadido, por lo que es necesario una implementaci´on de RSA que no a˜nada ning´un relleno al realizar el cifrado (i.e., ALG NO PAD). Pero el simulador no soporta esta implementaci´on, por lo que la decisi´on tomada fue modificar el dise˜no, enviando la clave privada de la tarjeta para que fuera LS el que cifrara la estructura consiguiendo la firma. Esto se muestra en la Figura 4.1. Este cambio s´olo es aceptable dado el objetivo del prototipo, pero no para una tarjeta real. M´as detalle en la correspondiente secci´on del Ap´endice G. Lector Seguro (LS) Tarjeta Inteligente (TI) Petición CPu de TI CSRTI Firmar y almacenar CSR CPrTI CPuTI Petición CPr de TI Figura 4.1: Construcci´on de los CSRs en el prototipo 4.2.2. Certificados en las entidades externas Sus certificados se almacenan en ficheros de extension Privacy-Enhanced Electronic Mail (PEM) y codificados en Base64. Cuando esas entidades se ejecutan los certificados se almacenan en estructuras de datos de tipo X509Certificate. M´as informaci´on en la secci´on “Off-Card Certificates”del Ap´endice G. 4.2.3. Certificados en la tarjeta Los certificados en la tarjeta se almacenan en vectores de bytes y codificados con DER. Cabe destacar la diferencia entre los certificados de TI y AC que se conservan desde la inicializaci´on durante el resto de tiempo de vida de la aplicaci´on, de los certificados de TPC los cuales se almacenan moment´aneamente mientras son analizados y se extrae la clave. M´as detalle en la secci´on “On-Card Certificates”del Ap´endice G. 4.2.4. Analizador sint´actico en la tarjeta Dadas las caracter´ısticas de las tarjetas inteligentes, no es posible comprobar todos los contenidos del certificado, por lo que el analizador construido lo que se encarga es de comprobar lo siguiente: Conformidad del certificado con codificaci´on DER y especificaci´on ASN.1 Algoritmos de clave y firma esperados, as´ı como la longitud de clave Validez de la firma De la misma forma que con la firma del CSR, al intentar descifrarla es necesario usar la implementaci´on del algoritmo de RSA sin relleno. Dado que no est´a disponible, la soluci´on elegida fue 23
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza que cuando el analizador llegue a la firma, se devuelva ´esta a la entidad externa con la que se esta comunicando. La entidad externa descifrar´a la firma y le enviar´a la estructura descifrada para que la tarjeta pueda realizar la comprobaci´on de la validez de la firma. Esto se muestra en la Figura 4.2. El analizador con mayor detalle se describe en la secci´on “Parser On-Card”del Ap´endice G. Entidad externa Tarjeta Inteligente (TI) Certificado Analizar certificado Desencriptar firma con ALG_NO_PAD Comparar Digest Info structures TI certificado (si TPC) Firma Firma encriptada Obtener la firma encriptada Obtener la clave pública Figura 4.2: Verificaci´on de la firma de los certificados en el prototipo 4.3. Funciones criptogr´aficas Esta secci´on describe la implementaci´on de las funciones criptogr´aficas de la segunda parte de la fase de Comparaci´on Contrato-Pol´ıtica, tras el intercambio de certificados. En esta parte, se puede distinguir entre criptograf´ıa sim´etrica y asim´etrica, pero es de forma conjunta como el sistema tiene sentido. El algoritmo de criptograf´ıa en bloque sim´etrica utilizado ha sido AES con una longitud de clave de 128 bits (la ´unica proporcionada por el simulador) con un tama˜no de bloque de 16 bits y con el modo Cipher Block Chaining (CBC). Como vector de inicializaci´on (necesario para el modo CBC) se ha utilizado el Nonce por ser aleatorio y renovado en cada nueva sesi´on. El por qu´e del uso de este algoritmo en lugar de otros (p.ej., DES) as´ı como el uso del modo u otras posibilidades para el vector de inicializaci´on se detallan en la secci´on “Cryptographic Functions” del Ap´endice G. Por otra parte, el cifrado por RSA se ha llevado a cabo a trav´es de una longitud de clave de 512 bits, ya que era la ´unica longitud proporcionada por el simulador. Para el proceso de Comparaci´on Contrato-Pol´ıtica no hay problema con el simulador ya que no importa cual sea la implementaci´on de RSA utilizada, mientras se use la misma en las dos partes de la comunicaci´on. As´ı pues se usa la ´unica implementaci´on proporcionada por el simulador: un cifrador RSA acorde con el esquema de PKCS#1 (v1.5). Un problema relevante de seguridad es el uso del algoritmo de generaci´on pseudo aleatoria de n´umeros para la implementaci´on del prototipo. De nuevo, se ha tenido que implementar as´ı por la limitaci´on del simulador. Se deber´ıa usar el generador seguro de n´umeros aleatorios, dado que ´este m´etodo esta preparado para tratar con requerimientos criptogr´aficos como [49] especifica. M´as detalle sobre este problema en “Cryptographic Functions” del Ap´endice G. Como comentario final de esta secci´on, cabe destacar que en la implementaci´on para una tarjeta real se recomienda incrementar la longitud de las claves de RSA. Se espera que se usen durante un largo tiempo, pero su longitud es muy corta. As´ı que se sugiere aumentarla hasta 2048 bits para la implementaci´on real. Los cambios entre ambas implementaciones se especifican en el Ap´endice K. 24
Cap´ıtulo 5 Evaluaci´on Durante este cap´ıtulo se muestra en primer lugar un caso de uso de forma que adem´as sirva de gu´ıa de usuario para que el lector se familiarize con el uso del prototipo desarrollado. Tras esto, se realiza un an´alisis de dicho prototipo respecto a sus prestaciones en t´erminos de memoria, dada los recursos limitados en este sentido de las tarjetas inteligentes. En este momento cabe destacar la metodolog´ıa de pruebas seguida. Se ha probado toda la casu´ıstica posible, conforme las distintas partes del sistema se iban implementando. Dicha casu´ıstica se basa en la posibilidad de errores en la firma, cifrado, longitud inesperada del mensaje, certificado incorrecto en cuanto a formato, firma del certificado no v´alida, etc. Toda esta casu´ıstica, se ha probado en el momento de la implementaci´on de la parte encargada de trabajar con la posibilidad de fallo. Es decir, se realiz´o una separaci´on modular del sistema para llevar a cabo las pruebas. Por ejemplo, en el caso de certificados, tras la implementaci´on de la parte que verificaba la firma se ha probado que suced´ıa si se cambiaba un byte de la firma recibida (evidentemente fallaba). 5.1. Caso de uso Dada la limitaci´on de espacio del presente documento, esta parte se encuentra perfectamente desarrollada en la primera parte del Ap´endice H. 5.2. Evaluaci´on de los resultados La importancia del siguiente an´alisis radica en las limitaciones de memoria de las tarjetas inteligentes, ya que si la idea te´orica del esquema de S×Cnecesita gran parte de la memoria disponible para llevarse a cabo, se puede concluir que no es la apropiada. El an´alisis se ha llevado a cabo mediante una opci´on del simulador CREF, para m´as informaci´on de su funcionamiento consultar el cap´ıtulo 10 de [2]. En el Ap´endice L, se pueden observar las capturas de pantallas con toda la informaci´on suministrada por el simulador, correspondiendo cada imagen con una de las fases del sistema. La informaci´on importante se muestra en bytes resumida en la Tabla 5.1. En dicha tabla se muestran solo resultados de la EEPROM. La raz´on es que es la ´unica interesante para el desarrollador de tarjetas inteligentes. Se trata de la memoria persistente donde se almacenan las aplicaciones. Adem´as, tambi´en se encuentran los datos que deben ser almacenados cuando la fuente de energ´ıa cesa de suministrar a la tarjeta; p.ej., cuando la tarjeta se retira del lector. Los resultados tanto de la ROM como de la RAM, son triviales en este sentido, ya que la primera es inicializada por el fabricante y no se puede modificar; mientras que la segunda es la memoria vol´atil que se borra cada vez que la tarjeta deja de recibir energ´ıa. La estructura de la memoria persistente se puede observar en la Figura H.12 del Ap´endice H. CREF proporciona una memoria de 64 KB (i.e., 65536 bytes), aunque las tarjetas reales suelen 25
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza especial inter´es en lo que se refiere a la organizaci´on, ya que la documentaci´on generada, as´ı como la bibliograf´ıa era bastante considerable. Asimismo, la duraci´on del proyecto hace que se tenga que tener cuidado con los detalles e intentar dejar todo lo m´as claro posible, ya que sino se hace d´ıficil retomar trabajo hecho dos semanas antes. Dicha duraci´on tambi´en implica el desarrollo de una constancia en el trabajo y ser responsable con ´el, puesto que se prolonga por un tiempo considerable. En definitiva, el proyecto me ha aportado muchas conocimientos tanto a nivel t´ecnico como personal, as´ı como me ha hecho desarrollar valores que ser´an importantes en mi futura profesi´on. Por otra parte, el trabajo llevado a cabo servir´a como un punto de partida firme sobre el que se podr´an establecer futuros desarrollos. 32
Ap´endice A Gesti´on del tiempo y esfuerzo En este ap´endice se da una idea de la gesti´on del tiempo realizada, as´ı como del esfuerzo invertido en la realizaci´on del proyecto. Para ello, se ha separado el trabajo en grupos de tareas a realizar cuyo significado se explica en la primera parte del ap´endice. En la segunda, se procede dividir dichas tareas en otras m´as peque˜nas detallando de forma estimativa las horas invertidas en ellas. Al final del ap´endice se pueden encontrar tanto un diagrama de Gantt como uno de sectores circulares, ambos construidos a partir de los datos anteriores. A.1. Grupos de tareas Los grupos de tareas que se han construido de forma general han sido los siguientes: Estudio previo Este grupo engloba toda la consulta, lectura y b´usqueda de bibliograf´ıa sobre criptograf´ıa, tarjetas inteligentes, su seguridad, informaci´on sobre Java Card, estado del arte sobre el problema, Seguridad-mediante-Contrato y est´andares y especificaciones de los certificados y sus peticiones. Dise˜no Esto incluye el dise˜no de la arquitectura del sistema, definiendo las diferentes etapas y entidades que participan en ella, adem´as del estudio de los ataques que pod´ıan ser llevados a cabo. Como resultado de esta parte, el tiempo de estas tareas incluye el de la documentaci´on que generan. Familiarizaci´on con el entorno Este grupo de tareas fue el llevado a cabo de forma previa al inicio de la implementaci´on cuando la plataforma, entorno y simuladores eran desconocidos. Incluye la prueba, uso y posterior decisi´on sobre el IDE y simuladores a utilizar. Asimismo, incluye el desarrollo de aplicaciones sencillas y seguimiento de tutoriales para conseguir la conexi´on entre la tarjeta y un dispositivo externo. Implementaci´on Este grupo de tareas se divide en el esfuerzo de implementaci´on por separado de cada uno de los hitos del sistema. Evaluaci´on Incluye las pruebas realizadas sobre el prototipo para validar su funcionamiento y el an´alisis de memoria realizado a dicho prototipo. Documentaci´on Engloba la generaci´on de documentaci´on del proyecto en todas sus fases (excepto dise˜no): diagramas, memorias tanto para Dinamarca como Espa˜na y la publicaci´on. Copias de seguridad Este grupo de tareas tiene en cuenta el sistema de copias de seguridad seguido, diferenciando las tareas seg´un los disintos tipos de copia. 33
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Reuniones Esta tarea ´unica tiene en cuenta las reuniones con el tutor, el ponente (v´ıa Skype) y discusiones con expertos sobre el sistema. A.2. Tareas realizadas En esta secci´on se realiza la divisi´on de tareas dentro de los grupos previamente descritos con la estimaci´on del tiempo empleado. A.2.1. Estudio previo Para resumir solo se muestra el tema sobre el que trata la consulta, lectura y b´usqueda de bibliograf´ıa. Criptograf´ıa: 30 h Tarjetas inteligentes: 40 h Seguridad en tarjetas inteligentes: 30 h Java Card (incluyendo consulta de su API): 60 h Estado del arte: 10 h Seguridad-mediante-Contrato: 30 h Est´andares y especificaciones de certificados y sus peticiones: 50 h Estimaci´on total de horas de estudio previo: 250 h A.2.2. Dise˜no Dise˜no de la fase de inicializaci´on: 20 h Dise˜no de la fase de almacenamiento del contrato: 2 h Dise˜no de la fase de comparaci´on entre contrato y pol´ıtica: 60 h Estudio de los ataques que se pueden llevar a cabo: 30 h Estimaci´on total de horas de dise˜no: 112 h A.2.3. Familiarizaci´on con el entorno Instalaci´on, tutoriales y pruebas con NetBeans y lo necesario para Java Card: 40 h Instalaci´on, tutoriales y pruebas con Eclipse y lo necesario para Java Card: 10 h Instalaci´on y pruebas con OpenSSL: 5 h Familiarizaci´on, pruebas y consulta de bibliograf´ıa de L A T EX: 10 h Estimaci´on total de horas de familiarizaci´on con el entorno: 65 h 34
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza A.2.4. Implementaci´on En lugar de estimar el tiempo de las partes por separado, se han detallado los hitos de la implementaci´on del proyecto. Esto se ha hecho as´ı ya que no tendr´ıa sentido describir el tiempo necesario para construir las entidades puesto que en cada una de las fases participan distintas entidades. Por ello, la estimaci´on es m´as precisa si lo que se tiene en cuenta es lo que cada parte del sistema ha necesitado. Estructura b´asica de los c´odigos fuentes de las entidades y comunicaci´on: 30 h Env´ıos y recepciones por APDU (tambi´en longitud extendida): 25 h Generaci´on de las peticiones y posteriores certificados: 60 h Funciones criptogr´aficas: 50 h Analizador sint´actico en la tarjeta: 65 h Almacenamiento del contrato: 5 h Estimaci´on total de horas de implementaci´on: 235 h A.2.5. Evaluaci´on Pruebas realizadas durante la implementaci´on: 20 h An´alisis de las prestaciones: 5 h Estimaci´on total de horas de evaluaci´on: 25 h A.2.6. Documentaci´on Documentos de/para reuniones y organizaci´on: 10 h Diagramas: 10 h Memoria para Dinamarca: 180 h Memoria para Espa˜na: 80 h Redacci´on de la publicaci´on (Ap´endice M): 35 h Estimaci´on total de horas de documentaci´on: 315 h A.2.7. Copias de seguridad Para asegurar la ausencia de p´erdida de informaci´on, se estableci´on una pol´ıtica de copias de seguridad que se basa en cuatro sistemas de copias con diferente periodicidad. Diariamente, se realizaban dos copias de seguridad al terminar de trabajar: una a un USB Pen Drive que consist´ıa en la copia integra del directorio del proyecto incluyendo bibliograf´ıa, documentos de dise˜no, proyectos de la implementaci´on, memoria, etc.; y otra enviada al correo electr´onico que conten´ıa comprimidos los proyectos de la implementaci´on y el directorio que conten´ıa el proyecto de L A T EXde la memoria. Semanalmente se realizaba una copia del directorio del proyecto a un disco duro externo. El repositorio de Subversion (SVN) fue utilizado para almacenar el estado del proyecto en los hitos de la implementaci´on. 35
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Copia diaria del directorio a USB Pen Drive: 15 h Copia diaria de memoria e implementaci´on al correo: 7 h Copia de seguridad semanal a disco duro externo: 3 h Copias de seguridad mediante un repositorio de SVN: 1h Estimaci´on total de horas de copias de seguridad: 26 h A.2.8. Reuniones La estimaci´on total de horas de reuniones es: 20 h A.3. Diagramas A continuaci´on se encuentran dos diagramas obtenidos a partir de los datos anteriores. Con ellos se pretende que presentar de forma gr´afica la distribuci´on de los esfuerzos. Se han eligido un diagrama de Gantt (Figura A.1) y una gr´afica de sectores circulares (Figura A.2). Figura A.1: Diagrama de Gantt con la distribuci´on del esfuerzo en el tiempo El diagrama de Gantt muestra como se ha distribuido el esfuerzo en el tiempo, pero en este caso, no es muy esclarecedor dado que los diversos grupos de tareas se superponen entre ellos. De esta forma, no se puede apreciar un avance claro entre las distintas etapas del proyecto. Realmente este diagrama no implica que esas tareas se lleven a cabo ininterrumpidamente durante toda su duraci´on, sino que empiezan y terminan en el espacio de tiempo que muestra. Por ejemplo, la documentaci´on se ha hecho por partes. En dicho diagrama se han omitido las barras temporales correspondientes a las reuniones y copias de seguridad, ya que son tareas que se alargan durante toda la duraci´on del proyecto. El diagrama de sectores por su parte, muestra la cantidad de esfuerzo invertido en cada una de los grupos de tareas. La estimaci´on aproximada del n´umero total de horas invertidas en el proyecto es alrededor de 1048. La mayor parte del esfuerzo se dedic´o a la documentaci´on, aspecto que parece normal ya que esa documentaci´on (de por s´ı tarea costosa en tiempo) ha generado dos memorias distintas y una publicaci´on. La otra parte que necesit´o m´as tiempo fue el estudio previo, dado que se part´ıa de un conocimiento nulo sobre la tecnolog´ıa y que los problemas encontrados en la generaci´on de las peticiones de certificados provocaron un estudio exhaustivo de especificaciones y formatos. La implementaci´on necesit´o tambi´en de una buena parte del tiempo. De hecho, su principio no fue f´acil al tratarse de una tecnolog´ıa nueva con errores en la tarjeta no f´acilmente identificables a priori. El resto de tareas han necesitado de menos tiempo al tratarse de cosas m´as puntuales o de duraci´on m´as corta. 36
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura A.2: Diagrama de sectores circulares con la distribuci´on del esfuerzo 37
Ap´endice B Metodolog´ıa de desarrollo La metodolog´ıa de desarrollo seguida para la construcci´on del prototipo ha sido en cascada, pero con una peque˜na variaci´on, y es que la retroalimentaci´on no se reduce s´olo desde la ´ultima etapa a las anteriores, sino tambi´en desde la etapa de implementaci´on hasta la de dise˜no. Esto se puede observar en la Figura B.1. Ingeniería y análisis del sistema Diseño Implementación Pruebas Validación Figura B.1: Diagrama que muestra la metodolog´ıa de desarrollo utilizada La raz´on para este cambio fue el desconocimiento previo de la plataforma y simuladores utilizados para la implementaci´on. Dada las limitaciones de estos, la etapa de implementaci´on provoc´o cambios sobre el dise˜no para que el prototipo fuera funcional. Asimismo dado que no hay posibilidad de manutenci´on del software ya que a la finalizaci´on del proyecto, se entregan los deliverables y no tiene continuidad en un futuro pr´oximo, no es necesario que exista una fase de mantenimiento. En su lugar, aparece la fase de validaci´on la cual supone la finalizaci´on del proyecto y no tiene ning´un tipo de realimentaci´on. As´ı pues, la metodolog´ıa est´a compuesta de las siguientes partes: Ingenier´ıa y an´alisis del sistema Esta es la etapa donde se estudian las necesidades para preparar los requisitos del sistema. Dise˜no Se prepara el dise˜no del sistema como soluci´on al problema y satisfaciendo los requisitos obtenidos en la etapa anterior. Como resultado se obtiene la arquitectura del sistema, 39
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza normalmente en forma de diagramas que detallan su funcionamiento. Implementaci´on En esta etapa se deciden las herramientas a utilizar en cuanto a entorno de programaci´on, lenguajes, simuladores. Una vez que dichas herramientas son conocidas se llevan a cabo la codificaci´on del dise˜no, es decir la construcci´on del c´odigo fuente del prototipo. Pruebas El objetivo de esta parte es comprobar la validez e idoneidad de la implementaci´on. Es decir, que las pruebas pueden estar orientadas a buscar errores en la implementaci´on o validar ´esta en cuestiones de rendimiento o uso de recursos. Validaci´on Finalmente, iteraciones de las etapas anteriores dan lugar al sistema final el cual se valida en esta fase, considerandose finalizado. El proyecto comenz´o con la fase de an´alisis del sistema, donde tras un estudio del problema a resolver se procedi´o a definir las necesidades del sistema para solucionar el problema. Una vez que esas necesidades estaban claras, se pas´o a la etapa de dise˜no donde se prepara la arquitectura del sistema. Como resultado de esta etapa, surgen los distintos diagramas que rigen el funcionamiento del sistema. Tras el refinamiento de estos diagramas, se llega a la etapa de implementaci´on. Durante esta etapa se produce la primera realimentaci´on. Las limitaciones del simulador provocan que cambios en el dise˜no sean necesarios. Dichos cambios se han detallado en el cap´ıtulo de implementaci´on. Una vez superados estos cambios, en la fase de pruebas durante el an´alisis de memoria se observan las estad´ısticas sobre el espacio necesario en memoria de la aplicaci´on. Su an´alisis da lugar a un refinamiento y optimizaci´on de algunas de las partes del c´odigo fuente de la tarjeta inteligente. En lo que respecta a las pruebas de validaci´on del sistema, se realiz´o una separaci´on modular de forma que en lugar de hacer las pruebas sobre todo el sistema como se espera en la metodolog´ıa en cascada; dichas pruebas se hicieron sobre cada una de las partes del sistema conforme se desarrollaban. La validaci´on de todas las partes por separado, es lo que permite la validaci´on total del sistema. Para confirmar esto ´ultimo, se realizaron algunas pruebas m´as sobre el prototipo ya terminado para comprobar su correcto funcionamiento. 40
Ap´endice C Smart Card Technology The big explosion of the digital communication produced in the last years has done that the way to interact among the people had changed. That is why organizations are moving towards network communications ways because of the requirements for their information was available and secure at the same time. Many of them have realized of the advantages and benefits that smart cards are offering. A smart card is a device able to store data, carry out functions on itself and interact in an intelligent way with an external reader by means of a microprocessor embedded in the plastic card. It is a widespread device thanks to its easiness of use, portability and cheap price [27]. Smart cards are tamper-resistant and provide security features what makes them to be considered as a secure and trusted device. These features allow smart card to be used in fields where high-security is needed and suitable to cryptographic systems and operations like authentication and authorization. Its origins are dated back to plastic cards which were started to deploy in US in the early 1950s for payment applications. At the beginning, they were made of paper moving later to PVC to get a longer lifetime. VISA and Mastercard appeared at this moment. Magnetic stripe cards were introduced afterwards, mainly because of the fraud. They were able to store digital data. Nevertheless, magnetic stripes had an important weakness: everyone with the right equipment could read, modify or delete the data, or even make a copy of the card bit by bit (technique called Card Skimming). Thus, sensitive data could not be stored on the card. To check them consisted in accessing online to a server or host with confidential data. This is as smart cards appeared. Two German invertors applied for its patent in 1968, a Japanese in 1970 and a French in 1974. In 1984 in France, telephone cards were distributed as a trial and the first bank card, which incorporated safety cryptographic keys and algorithms, was introduced [39]. Some authors argue that development of smart cards was slow at the beginning because of all information about smart cards was tried to keep withheld to avoid becoming an unsecure device [17]. At the beginning, development process was very long and complex. After choosing the chip (first step), code was written. This code was a mix between C and assembly in order to optimize. Developers had to manage for themselves memory pages. Once compiled, binary code was added to Operating System (OS) binary code and test on an emulator. In fact, OS was a few low level primitives used to managed the chip. Next step was to send it to Integrated Circuit Chip (ICC) manufacturer. After that, no change or update could be done, due to it was considered a possible weakness to attack. Masking process built Read-Only-Memory (ROM) on the wafer. Since process was very slow, manufacturers proposed generic soft masks which included a limited OS with some functionalities. Developer left OS issue aside and used Application Programming Interfaces (APIs). That made the process easier and faster: application was compiled and its binary was added to the soft mask to be sent to ICC manufacturer. BasicCard apparition was the key point for the 41
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza and mainly at [23] and [52]. C.5.1.1. Invasive Attacks Executing these attacks means to get physical access to the microprocessor, or in other words remove it from the smart card, in order to inspect and try to tamper it. The whole process requires expensive equipment to remove the microprocessor and work within it, a high ability and long time to reach results. That is the reason why they are not very common except among the manufacturers companies, laboratories and perhaps some researchers. These attacks are focused in attacks to bus lines, EEPROM, RAM and ROM and reverse engineering. It is possible to place a probe on bus lines between blocks of a chip and by means of an oscilloscope seeing the values sent on aforesaid lines. To avoid buses being through probed, they are usually placed in the lower layers of the device and scrambled in a specific way. Either scrambling non-volatile memory cells is a way to prevent similar attacks against EEPROM. By hardware, is easy, efficient in space and very hard to break by an attacker. By software, it is harder to program but it can be made chip-specific and dynamic [27]. In what RAM´s concerned, its content can be held in the memory if their cells are cooled to a temperature of -60 ◦C or if the content is not changed for a long time. Hence, on one hand, secret keys should not be kept in the memory for more than the elapsed time. On the other hand, RAM can be protected with a metal layer, which elimination leads to useless memory cells. On one hand, EEPROM and RAM data are encrypted in real-time (even by using memory address, that is, cipher text is distinct for the same plaintext and different address) in order to be protected. This feature is available in newest microcontroller. On the other hand, smart card manufacturers use ion-implanted ROM to prevent this memory from being read bit by bit using an optical microscope. One of the most important invasive attacks is the reverse engineering. The goal is get to know how a chip works in order to be able to copy the design with the corresponding losses to the owner. Also weaknesses on the chip can be found. These attacks are usually carrying out by people inside to the smart card industry who can access the necessary equipment to make the attack and are the most interested in getting information about the competitors to have competitive advantage. Consequently, several countermeasures are usually implemented on the chips. The most important are glue logic, obfuscated logic and adding another metal layer. One known example of reverse engineering which got their goal was MIFARE. The proprietary cryptographic algorithm was broken by reverse engineering compromising the MIFARE chips which used this algorithm [24]. Figura C.5: Physical view for two chips; both insecure (left) and secure (rigth) 48
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza As it can be seen at Figure C.5 (got from [27]), a secure chip looks like the right one. It implements several of the countermeasures aforementioned to prevent the physical attacks against the chip. Some of them are glue logic and a new metal layer which makes access to the chip difficult. C.5.1.2. Side-Channel Attacks They work observing the changes in a smart card when it processes different information and deals with unexpected effects. The main techniques are timing, power and electromagnetic analysis and fault induction attacks. Timing analysis, as its name suggests, consists in checking the time of operations to get conclusions and make inferences from it. To avoid attacks over: PIN code, the whole bytes are compared Cryptographic keys, current cards use noise-free cryptographic algorithms Power analysis is the technique which observes the power consumption over the time (for instance adding a resistor in series with card and checking the voltage change) and gives information about which operation is carrying out the microprocessor. There is two ways to do it: Simple (SPA) and Differential (DPA). Simple looks for several patterns in the consumption. For example, the rounds in AES cipher or square and multiply algorithms in RSA. If power consumption can change because of the value of the keys used, an attacker might get these keys [22]. DPA analyzes statically the samples. It is one of the most important attacks due to carrying it out is relatively cheap and the consumption is yet dependent to the data and the microprocessor. Some countermeasures include either to add a voltage regulator or artificial noise generator, use random delays or an on-chip random generator which varies the frequency of the clock. It is also possible to use machine instructions with similar consumption or have prepared different algorithms to solve the same problem. Patented countermeasures can be read at Cryptography Research, Inc. [42]. An electromagnetic analysis can be carried out by means of the electromagnetic radiation of the chip. It is hard to get success with it because it is necessary chip has to be close enough to get a properly signal. To prevent chips from this attack, a metal shields can be added or some layers stacked on top of it. Because of this attack is related to power analysis attack, their countermeasures help to protect against this one also. Fault induction attacks try to produce some effect, which attackers can take advantage from, after injecting a fault. Some of them are focused in the movement of the silicon atoms which might provoke resetting data, data randomization or modification of operation codes. Shielding and scrambling wires on the chip help to make difficult to access the important parts. C.5.2. Security of Contactless Smart Cards Any possible attack to a contact smart card, it is possible to be carried out in a contactless smart card, and therefore, the attacks and their countermeasures explained in the previous sections are valid for these kind of cards too. One contactless smart card drawback is that as they communicate over the air, everyone who wants to carry out an attack, only needs a radio device (ready to work at a short range) to try it against a card placed some meters far from the device. Some attacks are the following. Due to communication is over the air, it is easy to try an eavesdropping attack without the cardholder realized that someone is accessing to its card. It is difficult to get private data, but all 49
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza the communications should make encrypted to avoid problems. In fact, in order to avoid a man-in- the-middle attack which would be able to altering the data transmitted, data should not be only encrypted, but with certain randomness. That assures data integrity [27]. Denial of service is one of the hardest attacks to fight against because any countermeasure works properly for contactless smart card. Finally, other important attack is radio frequency analysis, which is made up of a power and electromagnetic analysis. It is not necessary to have physical access because data is taken from radio field emitted. This attack is easier to carry out and harder to detect. It may prevent by means of a current stabilizer and message and exponents randomization. C.5.3. Anomaly Monitors Some parts of the smart card might be affected by changes in their environment when they do the conditions go too extreme [27]. That is the reason why some anomaly monitors are added. They expect the card works in a range of acceptable conditions. When these conditions change and go to an unacceptable value, they (monitors) notice it and the chip stops running up to conditions come back to be suitable. They need space on the chip, so usually not all of the following monitors are implemented on the same card; it depends on what is the task for. Voltage monitor is used in the most of current cards because it can avoid some attacks to get information as secret keys by Differential Fault Analysis (to know more [9]). When it detects that the voltage is working over the upper or down the lower limit, it informs the smart card in order to stop running. To avoid monitor from being disabled by an attacker, they are protected in such a way that its manipulation stops the card. Another monitor always placed on the chip is a power on detector which leads the chip to an initial state when it detects a power on condition. The clock signal is provided by an external clock (because of the lack of power supply). The frequency does not depend on the card then, but on the supplier. Hence, a frequency monitoring may be added. It orders the card to stop when under or over frequency values appear. As far as temperature concerns it is a controversial topic because; on one hand, it may change out of the specifications without being an attack. On the other hand, an attack modifying the temperature can lead to manipulate the random-number generator ([27]). That is why temperature sensors are discussed by the experts, and also, because of deactivating the chip when it is working in a temperature out of the specifications can increase failure rate. C.5.4. Software Attacks In addition to the normal bugs which can be found in any software development, it is worth mentioning the following aspects. To do the verification of the bytecode is a task too expensive to run on the card, so it is not possible to perform it over the microprocessor of chip. Therefore, malicious applications built over illegal bytecode instructions is a problem to be solved. Otherwise, these kind of constructions can allow an attacker to get the total control of the card in the worst case. It should be taken into account the parties which participate in the communication between the smart card and the host. Moreover the smart card, either the link layer or the host can be attacked. That is why the design of the system and a correct use of the cryptography are necessary to develop a trusted system. An example of how the communication may be compromised by a man-in-the-middle attack could be read at [6]. More information about software attacks in [12]. 50
Ap´endice D Multi-Application Smart Cards As its name suggest, a multi-application smart card is a smart card which can host several applications. After the huge development in 90’s, a lot of companies chose to use smart cards as a security solution and normal people used to go with several of these cards everyday. The idea is to be able to use the same card for the whole needs of the user instead of one card for each need; that is, ro reduce the number of cards in the user’s wallet. Nevertheless, the most important reason to work in that topic is the needs of the issuer card companies of being able to offer more services in the same card. The best example is a SIM card which currently has been improved up to provide to end-user new services. It was necessary to improve the cards to get the flexibility and the security to make the market’s needs possible. The most interesting issue in multi-application is the chance to allow the dynamic application load. That means to be able to add new, update or remove the already loaded applications on the card whenever the user wanted. For instance, if a customer wishes to change their bank account from one bank to other, the customer would be able to remove the application of the old bank and install application from the newer. All process may be done quickly, instead of canceling the old credit card and ordering a new one to the current bank. Another example about update operation is the following. Let’s suppose a worker who uses a smart card as an access control card in his job. Some day, he is promoted, and then, has access to a new laboratory with a stronger security measures. Application in the smart card needs to update itself to adapt to the new algorithm to check the identity and permissions or update the previous content. The architecture of a multi-application smart card is shown at Figure D.1. As it can be seen, applications run over the OS which interprets the instructions to do them irrespective from the hardware. This independence is achieved through a virtual machine, for instance Java Card uses Java Card Virtual Machine (the acronym JVCM will be used in the remain) which is similar to the Java Virtual Machine. Figura D.1: Architecture for multi-application smart cards 51
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza D.1. Main Standards The two main standards are MULTOS and Java Card which are explained below. Some more are Smartcard.NET (to support .Net framework, freedom for the developer to choose the language to work), Multiapplication BasicCard (evolution from BasicCard, file system similar to File Allocation Table (FAT) by means of the data is sharing) or Windows for Smart Cards (WfSC, authentication oriented, real FAT file system). A brief summary of all of them can be read at [44]. In the following, Java Card will be described deeper than MULTOS for two reasons: it is the most important standard for multi-application smart cards and it is which will be used in the implementation. Also, Global Platform will be slightly presented. D.1.1. MULTOS This operating system is considered the main competitor to Java Card. It was created emphasizing on interoperability and security. Its architecture is made up of a virtual machine and a security scheme from Secure Trusted Environment Provisioning (STEP) technology to protect smart card, application code and data [30]. It is possible to program for MULTOS in several highlevel languages, thanks to the amount of available compilers, like Modula-2, Basic, etc. although the most common are Java and C. It is also possible to program in low-level assembly language. Applications are compiled into MEL bytecodes. MEL is an optimized language which is based on Pascal P-codes. Then they are executed by the virtual machine which checks every bytecode and the address accessed. Data sharing is not allowed among applications, thus any application can access to the data of the others [30]. The main drawback from MULTOS respect Java is that manufacturers of the first one are not allowed to add their own API, so to be able to use the functions everywhere they have to be replicated. D.1.2. Java Card Java Card is a technology which allows developer to build applications using Java Card programming language to run them in smart cards. It defines a subset of the Java Programming language and a Java Card API. As it happens with Java, it provides object oriented programming, a secure programming platform, interoperability and hardware independence (portability). Although its speed is limited because of the card’s hardware and the byte code run-time’s interpretation, Java Cards are not slower thanks to the usage of crypto-coprocessors which help them to make cryptographic operations much faster. However, the key point of this technology is the chance to develop multi-application smart cards and manage (addition, removal and update) them dynamically, that is, post-issuance card application management. Since this dynamism may generate several security problems; a context isolation mechanism was added to the Java Card Runtime Environment (JCRE). It provides isolation among applications at context level, as explain [50], what means that applets (applications on-card) cannot access applets from other context. This granularity is appreciated at Figure D.2 (from [17]), where ”Package¨ıs used instead of ¸context”. Context isolation is enforced by an application firewall which checks every access; and if someone is not allowed, it throws an exception. But, some applets may need to call methods from others. This is possible by means of Shared Interface Objects (SIO). It is an interface which stores the accessible methods. Thus, an applet accesses to data or methods from some distinct applet accessing SIO mechanisms through the firewall. 52
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura D.2: Firewall containment D.1.2.1. Previous Versions to Java Card 3.0 In previous versions to Java Card 3, the card always works as a server; it gets a request, processes it and sends response back to the client, but it never takes the initiative. Communications are made by Application Protocol Data Unit (APDU) commands, specified at ISO 7816 standard. Garbage collection works on demand, that is, developer is the responsible for the memory management. If it is neglected, execution might run out the memory resources of the card, and consequently, make it useless. The most representative of these versions is the split virtual machine architecture, which it shows at Figure D.3 (got from [17]). Owing to the constrained resources of traditional smart cards; it is not possible to do bytecode generation on-card. That is why it is carrying out on the PC. Thereby, loading, linking, optimization and bytecode verification are done off-card by a tool, the converter, whose output is a Converted Applet (CAP) file. This file is loaded on the card and ready to be interpreted by the JCVM [50]. To sum up, bytecode execution and security enforcement are done on-card and previous work off-card. Figura D.3: Split Java Card Virtual Machine D.1.2.2. Java Card 3.0 Java Card 3.0 provides two editions, both of them backward compatible: Classic is an evolution from the version 2.2.2, oriented to constrained resource cards, using the split-virtual machine and working as a server. Connected is network oriented to high-end cards with improved connectivity; that is why HTTP(s) is added as communication protocol using high speed interfaces like USB [3]. Card can work as a client and a Web server is incorporated giving rise to a new kind of applets: servlets. 53
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza A relevant feature of this edition is the on-card bytecode verification which supposes the change in the architecture: JCVM is not split but it is completely integrated on the card. Necessaries protocols and layers are shown in Figure D.4. The protocols which are bordered by the black line are exclusive from Connected Edition, whilst the rest are available for Classic Edition too. New logical protocols were developed to replace APDU because it spent too much time with ISO (APDU) command. Connections were not enough fast and a high-speed protocol was needed for new applications [10]; p.ej., for mobile applications. Figura D.4: Physical and logical layers of Java Card 3 Connected Edition D.1.2.3. Application Protocol Data Unit APDU is the protocol used by Java Card to establish communication. As it has been described previously, the card always (Classic Edition and previous versions) works as a server following a master-slave model between the card and the CAD, which is the responsible for supplying power to the card. Communication consists of two types of messages: Command APDU, which are the messages sent from the CAD to the card Response APDU, which are the messages sent from the card to the CAD Every response is sent as a reply to a command and every command receives a response. Both types of messages are transmitted by Transmission Protocol Data Units [20]. The most common protocols are: byte-oriented, block-oriented and contactless. A command APDU is merely made up of two parts: Header (mandatory) and Body (optional). Body consists of three optional parts which give rise to four possible command structures according to its presence (see Figure D.5 from [38]). The whole parts are described at the the following: CLA (1 byte): Identify an application class of instructions; in other words, identifies the applet among the stored on-card INS (1 byte): Specifies the instruction among the available in the CLA set P1, P2 (1 byte each one): Parameters 1 and 2, they are used to qualify the INS field or for input data Lc (variable): Length of the data included in the command 54
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Data (variable): Data included in the command Le (variable): Maximum length of the expected response Figura D.5: Possible command APDU structures Response APDU is made up of the following fields. Its format can be seen at Figure D.6 from [38]. Data (variable): Data included in the response Status Word (2 bytes): SW specifies which was the result of the execution on-card (if no error 0x9000) Figura D.6: Response APDU At [14] it is further described the standard for ISO 7816-4. This document is particularly interesting to start to develop Java Card applications because valid CLA, INS and SW values are described. CLA and the necessaries INS have to be defined by the developer. When smart card starts to receive power, it sends a message to the host called Answer To Reset which contains some parameters for the transmission like the protocol supported. Once this message has been received by the host, the communication can start. First command to be sent should be a select in order to choose the applet with which will be worked. Since the card saves its state, it is also possible to work with the applet selected before the card was powered off. But the CLA in the command has to meet with the CLA of the applet already selected. Any command with a different CLA, whose instruction was different to select, will be ignored. D.1.3. GlobalPlatform They are a set of specifications whose goal was to create a standard for cards management irrespectively of hardware, manufacturers or applications. Specifications are related to cards, card terminals and global management of systems using smart cards. That means they can be implemented over any multi-application technology. 55
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Some of the most interesting parts are Security Domains (SD), which ensuring a total separation (complete isolation) of cryptographic keys between Card Issuer and other Security domains. They support the most of the cryptographic services like encryption, key handling, etc. Every time one of the keys is required, application accesses to the corresponding SD through GlobalPlatform API which provides the service [44]. D.2. Open Multi-Application Smart Cards Multi-Application technologies were strongly pushed few years ago because of the needs of service providers which required a flexible, open and secure platform which allows them to load dynamically applications on cards after their issuance, that is, dynamic load post-issuance. It led to the differentiation of multi-application smart-cards depending on their flexibility to allow dynamic application load. In other words, their content management. They are distinguished among [44]: Open policy which allows anybody to load, update or remove any application on the card Closed policy which limits load, update or remove applications to the card issuer and some trusted partners There is an intermediate policy, called mid-open, which allows modifications to ”less”trusted parties. That means a partner in contact with a partner of the card issuer could also load its application, for instance. The risk of every policy is obvious. Open policy is more prone to be attacked or infected by malware than closed policy, because anyone can load its application, whilst in closed policy the issuer is the only one who can. That is why the chance to a malicious application was load on the card is as bigger as opened is the policy. Nevertheless, it does not mean that the open policy is the only one which can be attacked. Some of the main attacks possible against open multi-application cards are the following [44]: Collect information about services on-card in order to identify them Attack the OS Be familiarized with the card in order to select the best attack Denial of service An important risk of open multi-application perspective is that the software to be installed might not be trustworthy; and that is an issue to solve. It should be taken in account that up to date, it was difficult to load new applications in a deployed card, and consequently, it was hard to exploit bugs in the software. But using open multi-application smart cards, new applications loaded in deployed cards might allow attackers to exploit software bugs which may be important (also because they might combine physical and logical attacks). In other words, a problem of the open multi-application cards is that it is possible to load a malicious application in order to carry out internal attacks. These attacks might identify available services on the card, collect information in order to try to deduce the possible behavior of an application or attack the JCVM and the firewall. It is longer explained at [43]. D.2.1. Security Challenge The main problem with these cards is the interactions among the applications stored on it. In order to avoid them some tools have been developed and the security level of multi-application 56
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza developments has been enhanced. For example, Java Card added its firewall and SIO. Firewall mechanism isolates applets from the rests within of its own space (context). But it is not enough, because applications can interact through the sharing methods. Let’s suppose that a class used to bank account management implements its interface for the SIO, due to it wishes that other application on the card related to bank issues could make use of its methods. The problem is that an application can make use of the shareable interfaces for its own purposes [34]. Any other application on the card will be also able to access its methods on the SIO carrying out malicious tasks. Of course, any application will not be able to access the context of the whole applications on-card (but only the presents on the SIO), but some unexpected behaviors may be carried out like illegal information exchange. Some companies have already implemented some solutions but they are still only an improvement of Global Platform specifications. These improvements do not deal neither with the compliance of the new applications with the stored on the card nor with how the changes can interfere in the work of the applications already stored on the card. The problem is that the semantic of the modification (either addition, removal or update) is not checked. It should be verified what the application intends to do on the card, its behavior; in order to make sure that it is not in conflict with the already stored on the card. In such a way, any application can do nothing unexpected or forbidden; because if the change is accepted is because its behavior is compliant with the expected on the card. That is the idea of Security-By-Contract. 57
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura E.2: Off-Card S×CContract-Policy Matching rest of the parts of the system realizing of that. This problem is solved using certificates which have been signed previously by a Certification Authority (CA) in which both parts rely on. Certificates identify its owner unmistakably and they cannot be forged because they are signed with CA’s private key. But SC’s certificates cannot be sent through an insecure environment to be stored on the card. They must be stored through a secure and trusted environment and only once during the card initialization. That is why an initialization phase is necessary. It is carried out in a trusted environment by means of a trusted reader which works as an installer and is placed between the card and the CA. It is the responsible for sending the certification signing requests to the CA and gives them back signed to the card. The card cannot be used until initialization has properly finished with the storage. Otherwise, security requirements are not accomplished, security verifications cannot be carried out. Any change over any application on the card should be rejected until the end of the initialization. Once everything been stored, the card is ready to work as it is expected. To summarize, the thesis is focused on solving the problem of securing the communication between SC and TTP during the Off-Card Contract-Policy Matching Phase. Specifically this is done by making the communication over an untrusted environment secure and trustworthy by satisfying the requirements of mutual authentication, integrity and confidentiality. To achieve this it makes use of a PKI scheme which needs certificates to handle identities. 64
Ap´endice F Extending SxC for Off-card Contract-Policy Matching Contract-Policy Matching is a key step in the S×Cframework. When the limited resources of the device do not allow the card to run this algorithm, it has to be done off-card. A TTP which has enough computational capabilities will run the matching algorithm. To do that it is necessary to send the contract, policy and subsequently the results, over an untrusted environment. Therefore the communication has to be secured. The current chapter introduces the design of the system’s architecture designed to solve the problem of securing the communication for outsourcing the matching algorithm. The user will be able to securely rely on system decisions about matchingalgorithm output to decide advisability or not of the change (addition, removal or update). In order to fulfil the requirements of mutual authentication, integrity and confidentiality, the system is based on a PKI where keys and identities are handled through certificates that are exchanged between both parties at the beginning of each communication. For this reason, the card requires an initialization phase where certificates are stored in the SC along with the initial security policy of the card. Notice the difference between this phase and the installation which adds the system to the card and creates the instances necessaries to its proper work. Since TTP is the responsible for running the matching algorithm, it is expected to be a trusted and secure device. The security of the system relies on this assumption, therefore the communication is what needs to be secured. Each part of the PKI architecture involved in the matching algorithm (SC and TTP) has two key pairs. One of these key pairs is used for encryption, while the other one is used for signing. Although it is perfectly possible to use only one key pair for both encryption and signature, it is safer to use two different key pairs. Since both of them are distinct cryptographic functions, in the unlikely case of one of them being compromised the other will not. Hence, the common recommendation is to use two different key pairs. Therefore, every principal part of PKI architecture has two certificates, one for each key pair. To sum up, the use of two key pairs (and consequently two certificates) is optional, and it has been pointed out in the figures belonging to Initialization Phase; however it makes the system more secure. It is worth mentioning that the card works always as a server. That means it never starts a communication, but it merely receives a command from off-card clients, processes it, sends the reply back and holds waiting next command as Figure F.1 (modified from [38]) shows. This is important to understand the subsequent design. Throughout this chapter the term Command will be used to refer to the messages sent from any off-card entity to the card, whilst the term Response will refer the messages from the card to any entity. 65
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura F.1: Smart card’s communication by APDU F.1. Confidentiality and NONCE Issue In the previous section it has been stated that the requirements of the system are authentication, integrity and confidentiality, but someone might wonder why the last one is necessary in the system. Since during the communication what is sent are the contract and policy and the result of the matching algorithm, all of that might be public, it might seem that this is unnecessary. What is really important it is to keep the integrity and authenticity of the message safe because it guarantees that the message has been sent from the card to the TTP and viceversa without being modified. That is: the card is sure that the result which it receives is the one generated by the TTP by means of the contract and policy that it has sent. However, let’s consider the following scenario. At the beginning, a trustworthy application wants to be installed on the card. Its contract is stored on the card, and those sends this contract and its policy to a TTP in order to run the contract-policy matching algorithm. The result is positive, and TTP gives back a message to the card telling it that the application is trustworthy. Now an attacker is able to intercept and save this message. The attacker wants to install its untrustworthy application on the card. Thereby, it sends the contract of its application to the card, which forwards the contract together the policy to a TTP to run the matching algorithm. The result is negative, the application should not be installed on the card. TTP sends this result to the card, but the message is intercepted again by the attacker, which substitutes it for the previous message containing a positive result. In such a way, the attacker gets to install the malicious application on the card (this kind of attack is known as Replay Attack). The solution to that problem is to add a number used only once (NONCE, in this case a Cryptographic NONCE). It should be random in order to insure the freshness. This number is used as a kind of time-stamp which prevents the card to accept previous messages. The NONCE has to be sent encrypted in order to avoid malicious entities to know it, and consequently, forge some messages. Concerning the confidentiality of the message (contract, policy and result), it is used to avoid some kind of spoofing attack against the content. Moreover, an attacker could get information about the behavior of applications on the card and use it in a bad way. That is why some application issuers, whose applications needed a high-security level like bank’s applications, may demand the use of confidentiality, refusing the card if it does not provide it. As a final comment, it might be considered to restructure the system for really constrained resource devices which cannot afford message encryption, but it is strongly advised because of the benefits are much bigger than the 66
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza disadvantages. F.2. Architecture of the System The system has several parties involved during its different phases; Initialization, Contract Storage and Contract-Policy Matching. These phases can also be separated in other smaller parts. All of them are addressed in the remainder of this section according to the order in which they have to be run. Note that Installation Phase has to be performed first. F.2.1. Installation Phase Applications in any smart card have to be installed in order to be used. First of all, the application is deployed on the card, and the Installation is done afterwards. The keys are usually generated and stored at this phase. Keys generation can be done in the ways proposed at the following: TR produce the the keys and gets the certificate after sending the CSR to the CA CA is the responsible for generating the keys and the certificates The card creates the keys and by means of the TR which sends the CSR to the CA gets its certificates The first two ways have a particularly significant drawback. They have to send the keys, or rather the private key, to the card in a secure manner. If this key was compromised the card would be useless. Also, they should remove physically all the information related to the generation and the own keys. Even physical security measures shall be used to ensure that the off-card entity and operations are free from tampering [1]. That is why is much more secure to generate the keys inside the own card. Indeed it is one of the security highlights of the system which makes it particularly secure. The reason is that the private keys do not leave never the card simply because there is no reason to do that. Therefore, no one apart from the card can either get or use the private keys. F.2.2. Initialization Phase This phase is the responsible for creating and storing SC certificates, CA certificate (needed to verify correctness of TTP certificates) and the policy of the card. The whole process is made up of three stages: Certificate Signing Requests (CSR) building, certificates issuing, and finally certificates and policy storage. The off-card entity involved in this part is a Trusted Reader (TR). It is carried out in an environment considered trusted, as well as the communication between both parties. Notice that TR is the responsible for storing the certificates and the policy; hence, the security of the card depends on its proper work. If the storage were compromised and what the TR stored on the card were infected, the whole system would be compromised. It is expected to be carried out by the card issuer who is trusted. It is worth mentioning that it is only possible to run this phase only once, or rather, every storage can be done only once. Therefore it is avoided the case where everyone could store whatever (certificates or policy) they need on the card. Notice that the card is only a server which replies requests without being able to identify the requester. This issue is further discussed in the Future Work section. 67
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza F.2.2.1. Certificate Signing Requests Building In this stage the CSRs are built and stored on the TR in order to be sent to the CA. A certification request consists of a distinguished name, a public key, and optionally a set of attributes. Everything is signed by the entity which is requesting the certificate. A CA receives the CSR and if it is correct (information and signature), CA creates a public-key certificate containing the information of the CSR. The signature is used to prevent any entity from being able to request a certificate including the public key from another entity. Usually, certification authorities might require other non-electronic ways of request or reply in order to assure the information given by the requester; but that is beyond of the scope of the project. TR has to create the two CSR, one for each key pair. CSR for encryption is created before, whilst CSR for signature is created later. In order to do that, it needs the public keys stored on the card. That is why to build the CSR, the first Command, which TR sends to the card, orders the public key for encryption (PuKSCEnc) and does not contain any data. SC receives the query and replies it with a Response whose data is PuKSCEnc. TR by means of PuKSCEnc creates the CSR for encryption (SCEncCSR) adding the pertinent information. However the card has to sign the CSR since it is the owner of the private key. That is why at this moment TR has to sent SCEncCSR to the card and be signed there with the private key for encryption (PrKSCEnc). In such a way, CA will be able to verify that the signature is right, and consequently, that the public key matches with the private key of the requester. In other words, signature is what CA needs to be sure that PuKSCEnc belongs to whom is sending SCEncCSR, because it is the only one who can sign with the private key corresponding to the public key in the CSR. Once it is signed, the card sends a Response containing the signed SCEncCSR (SigP rKSCEnc(SCEncCSR)) attached in the data. This process is shown at Figure F.2. Figura F.2: Initialization Phase: CSR’s building diagram As notation, it is worth mentioning that in the Figure F.2 and subsequent, the messages typed in blue means that they do not contain data, whilst the black messages do. To sum up the flow of messages for the first CSR’s building is: 1. Command 1: No data, it is ordering PuKSCEnc 68
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza 2. Response 1: PuKSCEnc 3. Command 2: SCEncCSR 4. Response 2: Signed CSR, that is SigP rKSCEnc(SCEncCSR) TR stores SigP rKSCEnc(SCEncCSR) and builds afterwards the CSR for signature (SCSigCSR) in the same way: orders the public key for signature to the card (PuKSCSig), builds SCSigCSR and sends it to the card in order to be signed with the private key for signature (PrKSCSig). Hence, the messages for the second CSR’s building will contain, in the following order: 1. Command 1: No data, it is ordering PuKSCSig 2. Response 1: PuKSCSig 3. Command 2: SCSigCSR 4. Response 2: Signed CSR, that is SigP rKSCSig(SCSigCSR) F.2.2.2. Certificates Issuing Once both CSRs have been built and signed, TR has to send them to a CA in order to get the corresponding certificates. This process is shown in the Figure F.3. TR is called TR-Certificates Manager in this figure because it depends on the actual implementation of the TR which is not within the purpose of this project. The messages’ content exchanged between the TR-Certificates Manager and the CA are the following: 1. Command 1: SigP rKSCEnc(SCEncCSR) 2. Response 1: SCCertEncr, that is the SC’s certificate to encrypt 3. Command 2: SigP rKSCSig(SCSigCSR) 4. Response 2: SCCertSign, that is the SC’s certificate to sign Each certificate contains (among other) information about the owner of the key, the public key and the signature. For instance, previous certificates may contain each one: Information which identifies the owner: IDSC Public key which intends to be authenticated by the certificate: SCPuKEnc/SCPuKSig Certificate’s signature: SP rKCA (SCEncInfo/SCSigInfo) Once the certificates have been issued by the CA, sent and received, TR stores them in order to be available to be sent and stored to the card. 69
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura F.3: Initialization Phase: Certificates issuing diagram F.2.2.3. Certificates and Policy Storage The last stage during the Initialization Phase is the storage of all the necessary on the card. TR has to send both SC’s and CA certificates and the security policy. On one hand, each one of this things is sent in a different Command by the TR. On the other hand, the card always replies with an acknowledgement without any data. The stage is detailed at the Figure F.4. As it has been pointed out previously, these messages can only be sent once, that is, any object can be stored on the card once. The data sent within the commands from TR are the following (the order is not relevant): Command 1: CA’s Certificate Command 2: SCCertEncr Command 3: SCCertSign Command 4: Card Security Policy After the SC had been initialized, it is ready to be used to run securely any activity related to the contract-policy matching algorithm. At that time, the card is able to verify the identity of the TTP (validate its certificates), authenticate and authorize its requests. F.2.3. Contract Storage Phase At this phase, the contract of the application wished to be installed on the card has to be sent and stored there. It has to be carried out previously to any Contract-Policy Matching Phase since it needs that the contract had already been stored on the card. After every phase which runs the matching algorithm, the contract is removed from the card, that is why other contract should be stored on the card in order to perform the matching algorithm again. The process is very simple. An off-card entity, called Application Issuer (AI), sends a request to store the contract to the card, attaching aforementioned contract. The card stores the contract and replies the entity with an acknowledgement. The process is shown at Figure F.5. The entity responsible for storing the contract is the application issuer because it should be the same entity that develops the same which enclose to it the contract with its behavior, as it is proposed in the S×Cframework. 70
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura F.4: Initialization Phase Application Issuer (AI) Smart Card (SC) Contract Store Contract Acknowledgement Figura F.5: Contract Storage Phase F.2.4. Contract-Policy Matching Phase Contract-Policy Matching is the key phase of the S×Cframework. It has to run the matching algorithm by means of the data provided through the secure communication between a TTP and the card. With more detail, contract and policy, stored on the card, are sent encrypted from the card to some TTP which runs the matching algorithm giving the result back to the card. While Initialization Phase is expected to be executed only once, this one is supposed to be executed commonly. In fact, always that a change was necessary in any application on the card; either addition, update or removal. As it has been pointed out in the previous section, Contract-Policy Matching is always performed afterwards Contract Storage Phase. As far as this phase (contract-policy validation) is concerned, it has three stages: 1. Certificates’ exchange 2. Contract and policy sending 3. Matching result sending The whole process can be observed at Figure F.6. 71
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura F.6: Contract-Policy Matching Phase F.2.4.1. Certificates’ Exchange The exchange of the certificates between the card and the TTP is carried out by means of messages which encloses the corresponding certificates. Each party has to exchange two certificates to each other: one for encryption and one for signature. That means four messages are necessary to complete the exchange where two are from TTP and two from the card. At the beginning, certificates for encryption are exchanged. TTP starts the communication sending its certificate to encrypt to the card enclosed within a Command. A parser is implemented by means of which the smart card is able to verify the certificate against CA certificate stored during Initialization Phase. Parser also takes the TTP’s public key from the certificate allowing the card to get it. If the verification is positive (the certificate is right), it replies the message with aResponse attaching its certificate for encryption. TTP verifies the certificate got from the card and gets also smart card’s public key to encrypt. This process is repeated to exchange certificates to signature between both parties. It can be observed at Figure F.6. The data which contain the messages sent during this stage are: Command 1: TTPCertEncr, that is TTP’s certificate to encrypt Response: SCCertEncr Command 2: TTPCertSign, that is TTP’s certificate to sign Response: SCCertSign 72
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza F.2.4.2. Contract and Policy Sending When certificates’ exchange has finished, TTP has to order the contract and policy which are stored on the card. That is why it sends a Command without any data to make the query. Both contract and policy will be enclosed together within the same message in order to reduce the amount of messages to exchange, that is: SCContractPolicy (SC acronym has added in front to differentiate from the contract and policy which will be used during the verification of the message which will be TTPContractPolicy). Contract and policy have to be encrypted and signed by the card before being sent in order to assure the requirements of the system (authenticity, confidentiality and integrity). The encryption will be done through block symmetric ciphering (for instance AES or DES). The reason to use symmetric cryptography instead of asymmetric (based on PKI) is that asymmetric encryption is very slow when it is carried out over a considerable amount of data, whilst symmetric encryption provides higher speed (decryption is the same process; hence, it is also very fast). In addition, symmetric cryptography provides high security due to their no linearity and it depends on the algorithm (i.e., DES can be broken by cryptanalysis [8]) but usually only brute force can work. That is why a Block cipher is suitable to used over these data which may be relatively long. To use symmetric cryptography implies to both parties have to know the key. Thereby, the card that is which generates the key has to send the shared key to the TTP; but it cannot be sent in plain text because if someone could intercept the message, it could decrypt the content. That is why the key is encrypted and enclosed later to the message. The encryption at this moment is done by means of PKI because the key is not expected to be too long, but a few hundreds bits as maximum. It also guarantees that TTP is the only one which can decrypt the session key. The key for symmetric cryptography will change every session, that is, every time when it has to run a new Contract-Policy Matching Phase in order to assure freshness and randomness and get a higher security level. Keeping in mind this kind of ciphering and taking in account also the NONCE previously explained, the sequence of actions, which the card has to follow aiming to secure the message containing the requested information (contract and policy) by the TTP, is: 1. Generate a session key that will be used for symmetric cryptography: Ksess 2. Generate a NONCE (Number used Once): Nsc 3. Encrypt the session key through TTP’s public key to encrypt: EncP uKT T P Enc(Ksess) 4. Encrypt the NONCE through TTP’s public key to encrypt: EncP uKT T P Enc(Nsc) 5. Encrypt the message with the session key: EncKsess (SCContractPolicy) 6. Compute the HMAC (a hash mixed with a salt) of the content: HMAC(SCContractPolicy, Nsc) 7. Sign the HMAC previously built through the key to sign: SigP rKSCSig(HMAC(SCContractPolicy, Nsc)) 73
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza supposed to be backward compatible; hence, in the event of moving to version 3 the changes should be small. G.2. Limitations of the Prototype: Use of Eclipse, CREF and JCWDE Eclipse is a multi-language software development environment which includes an Integrated Development Environment (IDE). It provides a comfortable way to develop software at the same time that it may be tested. For the goal of the current project, it exists a plugin to work over Java Card. Eclipse is a free and open source software. The version used has been Eclipse SDK 3.5.2. The main reason to use Eclipse instead of Netbeans (which was used at the beginning, as above mentioned), was the problems to get a communication between the card and an off-card part in the latter. In contrast, by means of the manual in [11], the basic communication between both parts was straightforward in the Eclipse environment. In addition, Netbeans only provided a plugin for the last version of Java Card, that is JC3; therefore Eclipse was the logical and natural choice. Moreover this is a prototype, a proof of concept, a way to demonstrate the correctness of the system designed; therefore the choice of Eclipse and simulators to carry out the implementation is more than appropriate. During the implementation phase, two simulators have been used, allowing both to communicate the card (emulated card) with a CAD via socket interface. They are: Java Card platform Workstation Development Environment tool (JCWDE) for the first part of this phase C-language Java Card Runtime Environment (CREF) for the second part On one hand, JCWDE is a tool which allows running an applet simulating that applet is masked at a ROM of a Java Card; that is, the applet run as if it were stored on a card. To do that, it makes use of the Java virtual machine to emulate the JCRE. In other words, it uses a subset of the Java virtual machine to emulate a JCVM. That is why some of the features of the actual JCRE are not supported like package installation, persistent card state, firewall and transactions. Its main advantage is that as the applet has not to be stored on the card (because it does not save the card state), it is faster to test with it. That is the reason why it was used for the first part of the implementation stage where the structure of the system and communication were implemented and for the whole initialization phase. At this part, the card state was not stored (from one running to the next), only while the applet is running. To learn more about JCWDE, read chapter 4 from [2]. On the other hand, CREF is a similar simulator written in the C programming language which allows testing applets in a emulated environment in a very accurate way. The main difference is that it may be built with a ROM mask which allows it to simulate the persistent card memory (EEPROM), like a real card which saves its state. That means applets can be installed on the card. The main and obvious advantage over JCWDE is that it can save the card’s state; but also, it supports some features that JCWDE does not, like transactions. To learn more about CREF, read chapter 10 from [2]. This simulator was used for the second part of the implementation stage when the initialization phase was already finished. Then, it was necessary its use because contract-policy matching phase needed to work with a card which has already stored the certificates, contract, etc. and which was able to use its cryptographic keys. Both simulators have a problem which limits seriously their performance. They are designed with the goal to be useful for the people who is starting to work with Java Card. By means of 80
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Entity Project Source code SC SmartCard VerifyPolicyAndClaimApplet TR TrustedReader InitializationClass TTP TrustedThirdParty TerminalClass AI ApplicationIssuer ContractDelivery Tabla G.1: Equivalence among entities, projects and source codes them, they can create and test their own applets. That is why they do not support the whole of cryptographic classes and methods which Java Card 2.2.2 really provides. They only provide a basic security and cryptographic classes that [2] details at chapter 13. It restricts key lengths, available cryptographic algorithms, etc. Indeed, the restrictions caused the system design was modified for the prototype. It may lead to an error: theoretical system design has to be separated from the prototype’s implementation. The system design presented at the previous chapter is the correct and which should be used in a real implementation. But, due to these simulators are the only available and what it was expected to build was a prototype as a proof of concept, it was decided to modify as less as possible the necessary parts to get the prototype working on that simulators. The main part which had to be modified was the CSR’s generation and the verification of the certificates’ signature, because of the lack of support for the RSA cipher implementation without padding. Also random number generation and key lengths have been affected. Every part which was changed will be properly explained at its corresponding section. Consequently, two different source codes are provided in the appendixes. Source code in Appendix J belongs to the code for the prototype, whilst source code in Appendix K belongs to the code for a real implementation. G.3. Communication and Involved Parts’ Structure The communication among involved parts is the basis over the whole system is built; hence, their structure and the interaction among them was the first stage in the implementation. Card works as a server, that is the reason why its process method is limited to assure that the request was replied calling the corresponding method. To select the correct method to be called, process method makes use of a case statement by means of received INS. To work with CLA, INS and SW, there are a lot of necessary constants at the beginning of the applet’s code. These constants are also duplicated within off-card applications which make use of them. After the constants, necessary attributes are placed. Among them, it is worth mentioning the bytes array to store contract and policy and the booleans which store whether the certificates, contract and policy have been stored or not. They are used to carry out verification to check if everything is properly stored to run the matching algorithm. Before process method, Constructor, Deselect, Install, and Select are included. Constructor creates instances of algorithms and AES keys and generates RSA keys. Install calls constructor and registers the applet on the card. Deselect and select make cleaning operations. The rest of the code of the applet, is divided among some useful methods for utilities like converts between data types (p.ej., short to byte array), cryptographic methods and APDU management for extended length. The equivalence among entities of the system design and the implementation projects and source codes files is shown in the Table G.1. 81
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza The InitializationClass’s main method, responsible for the initialization phase, is presented as a menu. According to the option chosen, corresponding method is called. The APDU communication is carried out by means of methods which work on it. They try to abstract the details of APDU management and make it more general and easy to use. Thereby, to send an APDU command without data it is only necessary to call two methods: prepareAPDU and exchangeAPDUs, omitting low-level details about the values of the octets of CLA, INS, etc. Result can also be checked by means of checkAPDUStatus method. These methods are also available at TerminalClass and ContractDelivery code. To complete InitializationClass’s code structure, cryptographic and some useful methods are included. TerminalClass and ContractDelivery main methods are built in a sequential way. They run their operations and if any error occurs they finished properly. They rest of their structure is similar to InitializationClass. G.4. Certificates The main issues addressed in this section are the certification request and certificate generation, verification and storage, both on and off-card sides. In order to be able to understand that properly, it is necessary to be familiar with formats, Abstract Syntax Notation One (ASN.1) specification and encoding rules and formats of CSRs and X.509 certificates. ASN.1 is a notation used to describe both abstract types and values defined by Open Systems Interconnection (OSI). Every ASN.1 object has a tag which is made up of a class and a tag number. Only tag number identifies unequivocally a type. OSI also defined a set of rules which are used to convert the abstract objects in strings of ones and zeros. This set of rules is called Basic Encoding Rules (BER). BER provides an encoding for the object which consists on three parts: Identifier, length and content. Both ASN.1 and BER are explained wider at [18]. Finally, DER are a subset of BER which apply some restrictions getting a unique possible encoding for every object, in spite of BER which allows several encodings (this is not suitable for instance to check digital signatures on certificates). To know more about DER [21]. On one hand, CSR’s ASN.1 specification can be studied at Listing I.1 and I.3 and is described at [29]. On the other hand, ASN.1 specification for X.509 certificates can be observed at Listing I.4 and I.5. X.509 are detailed at [7] and [40]. X.509, although it can be large in size, is the most widely used certificate format. The remainder of the section is organized in the following way. It first deals with the implementation of both certification request and certificates generation. Once the generation has been detailed, certificate’s storage and management are described on and off-card sides. Finally, the verification of the certificates on-card is explained through the parser implemented. G.4.1. CSRs and Certificates Generation This section examines the implementation of the CSR and Certificate generation. These tasks are carried out by means of the TR. As it has been described at previous chapter, CSR is supposed to be built in TR and signed on-card. After that, card issuer should send the CSR to a CA in order to get the expected certificate. CSRs to encrypt and sign are built in the same way. First, TR orders public key to the card. Once it is received, CSR structure is built and prepared to be signed with the private key on-card. Main options to create the CSR are to make use of: 82
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Bouncy Castle Java sun.* packages Bouncy Castle is, roughly speaking, a collection of lightweight cryptography APIs for Java. It provides a way to create CSR, but it is necessary to have the private key of the entity to be certified in order to sign it. That means it does not allow building a CSR structure to be sent to the card and signed there. Hence; the only way to create the CSR by means of Bouncy Castle is exporting the private key from the card, which is a significant security risk. Java sun.* packages allows developer to create the handmade CSR thanks their classes to work with DER and Base64 Encoding. Once CSR structure has been created, DER encoded digest info structure has to be sent to the card in order to be signed. This one, called Encoded Message (EM), is built as follows ([26]): EM = 00 || 01 || PS || 00 || T, where T is the DER encoding of digestInfo structure (ASN.1 specification is at Listing I.6) PS is an octet string of length k-3-||T|| with value FF. The length of PS must be at least 8 octets k is the RSA modulus size EM is what has to be sent to the card. At this time a problem with the simulator appears. EM has been built according to PKCS#1 v1.5 (Public-Key Cryptography Standard) scheme, that means padding has been already added. That is why it should be encrypted on-card with the RSA implementation which does not add any padding; that is: ALG NO PAD. But the simulator does not provide this implementation (although JC 2.2.2 does), as it may be checked at chapter 13 of [2]. For this reason, the design of this part was modified to adapt to what simulator supports. Change consists in export the private key to the TR in order to sign by means of the needed algorithm off-card. It is shown at Figure G.1. The source code which contains this implementation for the prototype can be observed at Appendix J. Trusted Reader (TR) Smart Card (SC) SC’s public key order SCCSR Sign and store CSR PrKSC PuKSC SC’s private key order Figura G.1: CSR’s building process on the prototype It is worth mentioning that in the case of a real card implementation, Java Card 2.2.2 provides the necessary method; thus, it would not have to make this risky change. In other words, the change is only acceptable for the building of the prototype with the simulator; the private key never has to leave the card. 83
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Once CSR is built and sent, CA authenticates the requesting entity and verifies its signature. If the request is valid, CA constructs a X.509 certificate. Certificate is built by means of the distinguished name and public key got from the CSR, and adding the issuer name, corresponding serial number, validity period, and signature algorithm from the CA. If any PKCS#9 attribute is included in the CSR, CA may also use these attributes to construct X.509 certificate extensions [29]. Two are the main tools to carry out the creation of the certificate from the CSR, due to Java does not have any support for this operation: Keytool and OpenSSL. Both are tools which can be used to generate and display X.509 certificates. On one hand, Keytool, developed by Sun, is a tool to manage keys and certificates; usually used as a database to store keys and their certificates which authenticate them. On the other hand, OpenSSL is a wider goal tool which provides a toolkit to work with secure communication protocols and cryptographic library. The reason to choose OpenSSL was that it was closer to what it would be the real world. The behavior of this tool is exactly what it was necessary: it receives the CSR and by means of the CA’s key pair, it generates the certificate. After that, it finishes its work with certificate, CSR and keys. In contrast, with Keytool, certificate and keys are held in its database. Generating the certificates with OpenSSL consists in moving the CSRs to the OpenSSL’s folder, run by command line the commands shown at Listing H.4. When the command finishes, the certificate is ready. CA certificate used to do that is a self-signed certificate, because it was suitable for the developed prototype (free and quick to get). This is the task of the TR-Certificate Manager aforementioned above. G.4.2. On-Card Certificates They are stored as byte arrays because Java Card does not provide any other data structure to work with them. During the lifetime of the smart card, several certificates are sent to the card for different purposes. On one hand, SC certificates (to encryption and signature) are sent and stored on the card for the whole smart card’s lifetime. Also, CA certificate. On the other hand, in every Contract-Policy Matching session two TTP certificates are sent to the card. These are not stored definitely, but temporary, during the necessary time to parse the certificate. Difference is that while CA’s and SC’s certificates are stored as attributes because they will be used during the whole smart card lifetime, TTP’s certificates are stored in a ’temporary’ byte array (it is only one attribute because they are not sent at the same time, but sequentially). Temporary is between quotation marks because the variable where current TTP certificate is stored is a global, what means that it is alive during the whole smart card’s lifetime. However, certificate is stored only while it is being verified for the parser; because the variable is cleaned (the whole components of the variable are put to zero) once parser has finished. Verification is over, that is why it is not necessary to save the certificate longer. Auxiliary byte array which stores TTP certificates while they are parsed is currentCertificate. Reason, to be global (i.e., attribute) instead of a local (temporary) variable inside the method which receives the certificate, is to save space on the JCVM stack. JCVM has a stack-oriented architecture. That means every applet has its own stack ([51]) which stores frames (i.e., pieces of each method called which stores environ, local variables, etc.). Every frame stores its parameter taking up space from the stack. If the certificate is stored as a local variable, this one has to be passed as a parameter to the methods which work with it. The usage of nested methods may get that the certificate was stored several times in the same stack wasting space and time what is not suitable for a constraint resources device. As bigger was the nesting level and the certificate size, bigger was the wasted. To avoid that, a global variable is 84
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza created and every nested method calls it, saving the time of pass the certificate as a parameter (to copy and delete from the stack) and the space in the stack. Something similar is what concerns to parserOffset attribute which stores the current offset used to parse the current certificate. G.4.2.1. Encoding for On-Card Certificates Possible ideas for the format to store on-card certificates might be: As a certificate data structure sent from the off-card reader to the card As a string Base64 encoded (how the CA gives it back) DER encoded First and second option are ruled out because of the lack of support in Java Card. Base64 is not a good idea at all, mainly for two reasons. First one is that although the Base64 encoding were decoded, the certificate would not be usable yet, because it would follow DER encoded, that is why it would be better send it DER encoded directly. Let’s think the steps to send certificate Base64 encoded: Two tiresome steps are added if certificate is sent Base64 encoded. 1. TTP DER encodes certificate contained in its data structure 2. TTP Base64 encodes 3. Certificate is sent 4. Certificate is Base64 decoded 5. Certificate is parsed while is DER decoded The second important reason in order not to send the certificate Base64 encoded is that there is not any support in Java Card to work with it; that is why a new Base64 class to decode should be implemented to work on-card. In contrast, Java Card provides a class to work with BER-TLV (Tag, Length, Value). As it has been explained previously, BER is more generic than DER, and consequently, any tool to work with BER, it will do with DER. To sum up, certificates are stored DER encoded (as byte array) because there is class which provides support to work with it and it allows to save time avoiding some steps. Classes to work with BER are BER-TLV and BERTag. For instance, BERTag provides a useful method to get the tag number from the tag structure byte, whilst BER-TLV provides another to verify whether the certificate is properly encoded. G.4.3. Off-Card Certificates This section includes certificates on TR and on TTP. Also it addresses TTP’s private keys issue since they are stored in a similar way than certificates. Certificates of TTP and TR are stored in files permanently. To retrieve certificates from their respective files, a Byte Array Input Stream is used. Thanks to the classes provided by Java to generate it, a new instance of a X.509 is created containing the certificate, which is Base64 encoded 85
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza within the file. This file is stored in the device where TTP or TR is running with Privacy-enhanced Electronic Mail (PEM) extension. PEM is a format which can store private and public keys (both RSA and DSA) and X.509 certificates. It stores the certificate Base64 encoded after applying DER format and wrapped between two headers (BEGIN and END CERTIFICATE). All this encoding is suitable to transmit it among systems. But all the previous information about how to work in Java with certificates does not fit with TTP private keys. TTP keys are created by means of OpenSSL and stored in their respective files: TTPCertEnc,TTPCertEncPrivate,TTPCertSig and TTPCertSigPrivate, all with PEM extension. While the public keys’ files are certificates which contain them, private keys are Base64 encoded. But Java does not provide any class to work with Base64 encoding in its API (sun.* packages provide, but with the aforementioned problem). To solve that, by means of the last command of OpenSSL from Listing G.1; Base64 encoding is removed allowing to work only with DER encoding, which is comprehensive by a PKCS#8 class provided by Java API. Therefore, private keys are stored with DER extension. Listing G.1 shows the commands necessaries to build a key pair which can be used by the system. At this example the key pair and public certificate for TTP to encrypt are created. The first command create the key pair, while the second command by means of the CA key pair gets a certificate signed by a CA. Finally, the last command makes the conversion from PEM to DER. openssl req −newkey rsa :512 −subj "/OU=Cryptography/CN=TTPEncrypt" −keyout TTPCertEncPrivate . pem −out TTPCertEncAux . pem openssl x509 −CA CA publicKey . pem −CAkey CA privateKey . pem −req −in TTPCertEncAux . pem −days 3650 −sha1 −CAcreateserial −out TTPCertEnc . pem −e x t f i l e c on f ig . txt openssl pkcs8 −topk8 −inform PEM −in TTPCertEncPrivate . pem −outform DER −nocrypt −out TTPCertEncPrivate . der Listing G.1: OpenSSL commands to create a key pair usable by the system Certificates on TR Its use is simple because it is limited to verify CA and SC certificates before sending them to the card. TR only has to get the certificates from their respective files, creating a certificate data structure. By means of that structures, certificates can be verified easily and converted in a DER encoded byte array to send to the card. Certificates on TTP In the same way that TTP certificates on-card, SC certificates are not stored permanently in TTP. They are only present while TTP verifies them and get their public keys. Once, it finishes with them, local variable which stores them disappears. Only SC public keys are stored during the rest of TTP’s lifetime. The rest of the content of the certificate is ignored, after verified. It is worth mentioning that TTP gets from its certificates its public keys. G.4.4. Parser On-Card Parser on-card is the responsible for verifying the correctness of the certificates which are received. In order to carry out this verification, it has to check: Certificate is compliant with DER encoding Certificate is compliant with ASN.1 Key algorithm is the expected 86
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Signature algorithm is the expected Key length is the expected Signature is valid If this verification could not be done on-card, SC would not be able to trust in any TTP since it would not be sure about its identity. In other words, what parser allows is to make in a trusted way the initial key exchange. Card knows then whether the certificate is trustworthy. It is worth mentioning that it was considered it is not necessary to parse SC’s certificates when they are stored because they come from TR (which is trusted environment). G.4.4.1. What to Parse On-Card A common certificate comes with quite information about the owner of the public key and issuer CA. All this information which is useful in Web developments, it is not in smart cards because of the limitations of these devices to check information’s truthfulness. What parser needs from the certificate to check or store is: Signature algorithm: Both from TBSCertificate and Certificate (according to ASN.1 specification of X.509 certificate) structure. It has been checked that both algorithms match. Issuer Public Key Algorithm Public key Signature C e r t i f i c a t e : Data : Version : 3 (0 x2 ) S e r i a l Number : 94:1 b : 9 2 : b0 : e1 : 1 0 : a9 : 9 d Signature Algorithm : sha1WithRSAEncryption I s s u e r : C=DK, ST=Lingby , L=Lingby , O=DTU, OU=IMM.DTU, CN=Secbycontract , emailAddress=s091011@student . dtu . dk Validity Not Before : Jun 2 1 1:56: 1 5 2010 GMT Not After : May 30 1 1:56: 1 5 2020 GMT Subject : ST=Copenhagen , C=DK, O=SCIssuer , OU=Cryptography , CN=SCEncrypt Subject Public Key I nf o : Public Key Algorithm : rsaEncryption RSA Public Key : (512 b it ) Modulus (512 bi t ) : 00: b4 : 0 5 : c4 : 0 e : [ . . ] Exponent : 65537 (0 x10001 ) X509v3 ex te nsion s : X509v3 Basic Constraints : c r i t i c a l CA:FALSE Signature Algorithm : sha1WithRSAEncryption 5 f : 8 9 : b7 :3 e : aa : [ . . ] Listing G.2: Example of X.509 certificate contents (Certificate used by smart card to encrypt) 87
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza As it may be observed in Listing G.2 (one of the SC certificates), certificate provides some fields with information useless to the smart card for not being interesting or for the lack of tools to verify them. These fields are Version, Serial Number, Subject (unless the certificate was the CA certificate, case when the offset of this field is stored to be checked against the Issuer field from the rest of certificates) or the most of the extensions (if any, except CA extension). About extensions, anyone of them is checked on-card. That is why only CA extension would be interesting: It assures that a certificate expected to be a CA certificate, it is really a CA certificate. It may be observed in Listing G.2 that in the extensions part shows up a field CA marked as false because certificate belongs to the SC. This verification is done in the initialization phase in the InitializationClass. It checks the certificate before sending it to the card. A function gets the value of BasicConstraints extension which stores whether certificate’s subject is a CA or not. As [48] indicates, only returns minus one when the latter option. At this point, it is worth mentioning that two important issues related to certificates were left aside: Validity and Revocation. [37] deals with both of them proposing some solutions, but it has not them into account in its prototype. A solution is proposed in the future work section, but they are ignored during the implementation. G.4.4.2. Parser’s Implementation Details This section will focus on providing some details of the parser’s implementation. Verification process of a certificate, which the parser carries out, can be separated in two parts: the actual parser of the certificate and the verification of the signature. First one checks whether the format and the encoding of the certificate is correct and gets the data elements to be verified. The second one, when the first part has finished and has given back the signature, checks its correctness. Parser takes some ideas from [37], but adapts them to its needs. The certificate is scanned once, but it is not necessary to save the offset of the fields because their contents will be got during the parser process and the only one which is necessary to store is the public key, but it is stored directly instead of saving its offset and be stored later. Therefore, in contrast to the parser implemented in [37], the content’s offsets are not stored, because they will be checked only once. The only exception is CA certificate which is stored permanently on-card. In order to verify that TTP’s certificate has been issued by CA, issuer field has to be checked against CA’s name field. Thereby, the offset of this field from CA’s certificate is stored in a global variable. In such a way, it is easy and fast to take the CA’s name to make the comparison. Every certificate BER format is verified by means of a method provided by BERTLV Java Card class. It is checked that every expected field is present. As it has been described previously, only a few fields’ contents are really parsed. Issuer field has already detailed. The public key (not from CA) is got according to the expected BER encoding and stored in its corresponding variable: TTPPublicKeyRSAEnc or TTPPublicKeyRSASig. It is worth mentioning that when the key is retrieved, its length may vary. The reason is that to avoid modulus and exponent from being understood as negative because of its first byte, a zero is added before. Java Card classes does not work in the same way, thus it is necessary to remove the first component in that cases or the system will fail on-card. The fields which are left out are signature and public key algorithm, both are algorithm identifiers according to ASN.1 specification. Both contains wrapped in a SEQUENCE statement an Object Identifier (OID) which identifies theirs respective methods. How to DER encode an OID is explained in a revision of the document [21]. But to make it easier, it was implemented several 88
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza lines of Java code (at Listing G.3) by means of which the OID is DER encoded. That encoding was wrapped in a byte array which is only compared against the OID got from the certificate, both to check signature and public key algorithms. Oid aoid = null ; aoid = new Oid ( "1.2.840.113549.1.1.5") ; byte [ ] oid = null ; oid = aoid . getDER ( ) ; System . out . p r i n t l n ( byteArrayToHexString ( o id ) ) ; Listing G.3: Code to OID generation (sha1WithRSAEncryption example) The verification of the signature can be made in two ways. After decrypting with the public key of the corresponding CA, an EM is got. Either hash code is retrieved from that Digest Info structure and compared against the hash code built or a Digest Info structure is built through the hash code of the TBSCertificate part (ASN.1 specification) of the certificate and compared against to the Digest Info structure got decrypting the signature. The latter was chosen for the current implementation. While parser is scanning the certificate gets the offset and length of TBSCertificate part and make a hash code which is stored in order to be used to build the Digest Info structure. That one is checked against to the decrypted one. The problem is coming when the signature has to be decrypted, like it happened with CSRs and certificates generation. To decrypt the signature is necessary to make use of an RSA algorithm implementation with no padding which is not available on the simulators used. It can be observed at Appendix K, which corresponds to the real implementation source code where this algorithm is available, that it is enough with decrypting and following the aforementioned process to compare Digest Info structures. Since the algorithm is not available, it is necessary to modify the system design again for the prototype. There are three methods which have to parse distinct certificates: Method which receives TTP certificate to encrypt Method which receives TTP certificate to sign Method which receives CA certificate Owing to the previous limitation, this methods were split in two methods each one. Thereby, for instance in the source code of the prototype, there are the methods: processStoreCACertificate and processStoreCACertificate2. The structure of these two methods for the rest of certificates (TTP certificates) is the same. The first method receives the certificate, parses it, gets the public key (if TTP certificate) and gets the signature encrypted. It gives that signature back to the offcard side which decrypts the signature by means of the CA’s public key and an RSA algorithm implementation with no padding. Once decrypted, it sends the Digest Info structure to the card, being processed by the second method. It checks if the Digest Info received matches with the built. If it was not a CA certificate, the card replies with its corresponding certificate. The whole process is shown at Figure G.2. The result is that is necessary to send one APDU command and response more which make the system more complex. The source code which contains this implementation for the prototype can be observed at Appendix J. 89
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza generation by command line. openssl x509 −CA CA publicKey . pem −CAkey CA privateKey . pem −req −in EncCertReq . pem −days 3650 −sha1 −CAcreateserial −out SCEncCert . pem −e x t f i l e c on f ig . txt openssl x509 −CA CA publicKey . pem −CAkey CA privateKey . pem −req −in SigCertReq . pem −days 3650 −sha1 −CAcreateserial −out SCSigCert . pem −e x t f i l e c on f ig . txt Listing H.4: Commands to get certificates from CSRs Figura H.5: Certificate generation with OpenSSL As a result of the previous generation, two certificates should have been created in the folder: SCEncCert.pem and SCSigCert.pem. The content of the folder is expected to be similar to the shown at Figure H.6. To sum up, it should contain at least both CSRs and certificates, CA certificate and its private key. When both certificates have been generated, card issuer must to drag them to TrustedReader folder, and then, option 2 of the Initialization Phase menu can be launched. It will store CA and SC certificates on the card. A screenshot of its storage can be observed at Figure H.7. At this moment both CSRs and certificates should be removed from OpenSSL and TrustedReader respective folders. Finally, Card Issuer must store CardPolicy choosing option 3. Once everything aforementioned has been done, what supposes CA and SC certificates and Policy have been stored, Card Issuer can finish with the initialization phase choosing option 4. Notice that the TrustedReader can be called only once in the sense that, since the moment when certificates and policy are stored on the card, they cannot be stored again. Certificate’s renewal will be discuss in the future work section. At the end of the initialization phase, the card can be used as many times as required to check the compliance of any change of the applications on the card. To do that, before running the Contract-Policy Matching algorithm, it is necessary to load ApplicationContract. That is carried out by Application Issuer who is the responsible for sending the contract to the card. Hence, ContractDelivery class has to be run on Eclipse before TerminalClass. Otherwise, the error shown at Figure H.8 appears. This error also appears if some of the elements expected to be on-card when the algorithm is run (like certificates) are not already stored. Every error which can be captured on-card, it is shown with the same error modal window than the previous one. To run ContractDelivery class, it has to be run OldCard.bat script. After that, right clicking over 96
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura H.6: OpenSSL\bin folder after certificates generation Figura H.7: Certificates storage on-card Figura H.8: Message when ApplicationContract has not been stored the corresponding class and choosing Run as, Java Application, like to run the TrustedReader, ApplicationContract is stored on the card. The APDUs involved at this process can be observed at 97
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figure H.9. Figura H.9: Contract storage process The last part is the Contract-Policy Matching. In order to avoid a message like the shown at Figure H.8; certificates, contract and policy have to be already stored on the card. Notice that when a matching algorithm finishes, contract is removed; hence, any contract has to be stored again before running the algorithm again. Like the other clients, to run TrustedThirdParty, it is necessary to run the OldCard.bat script and from Eclipse, right click on the source code, Run as, Java Application. The communication will start and at the end a modal info window communicate which has been the result of the algorithm, as it can be seen at Figure H.10. Figura H.10: Message with the matching result Together the window with the result, the APDUs which have been sent during the communication between TTP and SC can be observed. They are shown separated according to the parts of the communication, as Figure H.11 illustrates. H.1. Memory Analysis Smart Cards are devices with constraint resources particularly in terms of memory. There lies the importance of this analysis, because if the theoretical idea needed to take advantage of more than the half of the available memory, it would not be the suitable solution. The analysis has been done by means of the data provided by a command line option of CREF. This option prints resource consumption statistics of memory usage at the startup and the shutdown of the card, giving an idea of the needed resources for installing and executing the applet as it is explained at Chapter 10 of [2]. Every time that CREF is launched with this option the statics related to the following resources appear (once at startup and once at shutdown): EEPROM 98
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura H.11: Contract storage process Transaction buffer Stack usage Clear-on-reset RAM Clear-on-deselect RAM Also some statics about the ROM are shown at the beginning of the statics. At Appendix D, screenshots corresponding to the memory statics of each stage of the applet lifetime can be observed. To sum up, the results of these statics are shown at Table H.1. There only results related to EEPROM are included. The reason why only these statics are shown is because are the most interesting for a smart card developer. On one hand, ROM is the memory which stores binary codes of the OS and the JCVM among others. This memory is created and initialized by the smart card manufacturer and it is not able to be modified later. That is why it is lacking in interest for a developer who cannot alter it. On the other hand, RAM is the memory which stores the whole application which is running at every moment and its data. This is very important due to if an applet needs for its running more memory than RAM provides and uses it up, an error appear because of RAM memory resources of the card are exhausted. However, that is a problem which every developer has to keep in mind when it is working on smart cards; but it is not interesting from the point of view of the project. That is because the RAM is always the same and the developer should know with which size it can work and to adapt its development to that. Also RAM is cleared at every shutdown and cleaned by the garbage collector over demand; hence, it changes every cardtearing. That is why the statics are referred to EEPROM memory which stores the applications and data which are dynamically loaded to the card; load which is tried to be properly managed by the S×Cframework. The key point of checking the memory statics is to know whether it is worth adding the system developed to the card or in change, it takes too many memory resources reducing 99
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza excessively the space on-card and making multi-application framework useless. A structure of the non-volatile memory can be observed at Figure H.12 from [38], which shows the common content of the ROM at the bottom (OS, JCVM, etc.) and of the EEPROM (the applets) at the top. Figura H.12: EEPROM and ROM content The statics of the Table H.1 are shown in bytes. They have been taken from the prototype developed by means of CREF. This simulator provides an EEPROM memory with a size of 64 KB (i.e., 65536 bytes). The common size for Java Card 2.2.2 real implementations ranges between 32 (old and constrained) and 128 KB, although it is starting to use greater. The stages chosen to appear on the table are compliant with the highlights in the applet lifetime. They cause the main changes over the EEPROM. These stages are the following: Deployment: It consists in download the applet to the card; store the bytecode there Installation: It is done calling the applet’s static install method which install the applet on the card invoking somewhere register method Initialization: This stage corresponds with the Initialization Phase detailed in previous sections Running: That is the Contract-Policy Matching Phase The last static (Running) is taken after several runnings in order to see the statics when the memory is established. About the tags used for the columns they are referred to the moment previous and next to the stage was run. For example, C¸ onsumed beforerefers to the bytes which were used from the EEPROM before the corresponding stage started. As it can be seen at the table, the card reserves almost 7 KB for itself before storing something what seems to be some space for the OS or some card’s needs. Downloading the applet to the card takes almost 6 KB, whilst its installation more than 1 KB. It is worth mentioning that during the installation is when the most of necessary data create their instance, reserving space on the card. That is what happened with keys and algorithms, for instance. The initialization decreases the available memory in 3 KB. At this stage certificates (both SC and CA) and Policy have been 100
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Stage Figure Consumed before Consumed after Available before Available after Deployment L.1 6994 12837 58510 52667 Installation L.2 12837 14322 52667 51182 Initialization L.3 14322 17919 51182 47585 Running L.4 18298 18135 47206 47369 Tabla H.1: Memory Analysis statics in bytes stored. As an example of initial Policy for the card, a file of 518 bytes was used. Obviously, this value will change according to security needs of the card, installed applications, etc. Finally, the EEPROM’s consumption of the matching algorithm only makes memory vary a few hundred bytes. To sum up, the system developed needs a rough memory space in the EEPROM of 11 KB. Previous result has to be taken as an upper-limit for the necessary space on the memory of the developed system since an optimal implementation was not a goal during its implementation. That is why the result of the analysis is positive. There are also several points to take in account. If the statics are looked through, what takes more bytes is the applet’s download because of the extensive source code. That is because the applet has to deal with several cryptographic problems, even including a parser on-card. The common applets are not as large as it what means that a high number of applets are still possible to be stored. For instance, let’s suppose that every application takes between 4 and 5 KB of memory space as average; still more than eleven applets could be stored on-card. If the size is smaller (commonly) the approach is better since much more applets could be stored. The heaviest issue is the bytecode download. Notice that the analysis has been done over the prototype which contains some methods necessaries because of the limitations of the simulator, but which there were not in a real implementation. Therefore this performance is expected to be better there. It should keep in mind than the smart card like the rest of the current hardware is continually evolving what carries out to think that the available memory will be greater in short time, whilst the necessary space for the system developed will be the same. As it is pointed out in Future work section, the priority while the implementation stage was to get a clear and easy to understand source code. Thereby, an optimization is able (and recommended) to be made over the code, reducing its weight. Although an optimization should be done over the code, it is considered that the system is suitable and could fit properly in a multi-application smart card. It takes more space than a usual applet since it has to carry out more operations than them, but it does not reduce the available memory considerably allowing to store a large number of applications in a secure way. 101
Ap´endice I ASN.1 Specifications The current appendix contains the ASN.1 specifications of the Certification Signing Request and X.509 certificates. These specifications could be found also in [29] for Certification Signing Request’s and in [1], [7] and [40] for X.509 certificate’s specification. I.1. Certification Signing Request I.1.1. Certification Request Ce rt i fi c at i on Req ues t ::= SEQUENCE { c e r t i f i c a t i o n R e q u e s t I n f o Ce rt ifi ca tio nRe qu est Inf o , si gn atur eAlg orit hm A l g o r i t h m I d e n t i f i e r {{ SignatureAlgorithms }} , sig natur e BIT STRING } A l g o r i t h m I d e n t i f i e r ::= SEQUENCE { al gorithm OBJECT IDENTIFIER , parameters ANY DEFINED BY algorithm OPTIONAL } Listing I.1: ASN.1 specification for Certification Signing Request I.1.2. Alternative Certification Request Ce rt i fi c at i on Req ues t ::= SIGNED {EncodedCertificationRequestInfo } (CONSTRAINED BY { −− Ver ify or sign encoded −− CertificationRequestInfo −− }) EncodedCertificationRequestInfo ::= TYPE−IDENTIFIER.&Type( CertificationRequestInfo) SIGNED {ToBeSigned }::= SEQUENCE { toBeSigned ToBeSigned , al gor ithm A l g o r i t h m I d e n t i f i e r { { SignatureAlgorithms} } , sig natur e BIT STRING } Listing I.2: Alternative ASN.1 specification for Certification Signing Request I.1.3. Certification Request Info C e r t i f i c a t i o n R e q u e s t I n f o ::= SEQUENCE { ver sion INTEGER {v1 (0) }( v1 , . . . ) , sub ject Name, subjectPKInfo SubjectPublicKeyInfo {{ PKInfoAlgorithms }} , a t t r i b u t e s [ 0 ] A ttributes {{ CRIAttributes }} 103
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza } SubjectPublicKeyInfo {ALGORITHM : IOSet}::= SEQUENCE { al gor ithm A l g o r i t h m I d e n t i f i e r {{IOSet}} , subjectPublicKey BIT STRING } PKInfoAlgorithms ALGORITHM ::= { . . . −− add any l o c a l l y defined algorithms here −− } Attributes {ATTRIBUTE: IOSet }::= SET OF Attribute {{ IOSet }} CRIAttributes ATTRIBUTE ::= { . . . −− add any l o c a l l y d efined a t t r i b u t e s here −− } Attribute {ATTRIBUTE: IOSet }::= SEQUENCE { type ATTRIBUTE.& id ({IOSet}) , values SET SIZE ( 1 . .MAX) OF ATTRIBUTE.&Type ({IOSet}{@type}) } Listing I.3: ASN.1 specification for Certification Request Info I.2. X.509 Certificate I.2.1. Certificate C e r t i f i c a t e ::= SEQUENCE { t b s C e r t i f i c a t e TBSCertificate , signatureAlgorithm Alg o rith m Iden t ifie r , signatureValue BIT STRING } A l g o r i t h m I d e n t i f i e r ::= SEQUENCE { al gorithm OBJECT IDENTIFIER , parameters ANY DEFINED BY algorithm OPTIONAL } Listing I.4: ASN.1 specification for Certificate I.2.2. TBS Certificate TBSCertificate ::= SEQUENCE { ver sion [ 0 ] EXPLICIT Version DEFAULT v1 (0) , serialNumber CertificateSerialNumber , signature AlgorithmIdentifier , i s s u e r Name, v a l i d i t y Validity , sub ject Name, subjectPublicKeyInfo SubjectPublicKeyInfo , issuer UniqueID [ 1 ] IMPLICIT U n i q u e I d e n t i f i e r OPTIONAL, −− I f present , ver s ion MUST be v2 or v3 subjectUniqueID [ 2 ] IMPLICIT U n i q u e I d e n t i f i e r OPTIONAL, −− I f present , ver s ion MUST be v2 or v3 ext e nsion s [ 3 ] EXPLICIT Extensions OPTIONAL −− I f are present , v e rsion MUST be v3 } 104
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Version ::= INTEGER {v1 (0) , v2 (1) , v3 ( 2) } Certif i c at eS e ri al N um be r ::= INTEGER Name ::= CHOICE {RDNSequence} RDNSequence ::= SEQUENCE OF RelativeDistinguishedName RelativeDistinguishedName ::= SET OF AttributeTypeAndValue AttributeTypeAndValue ::= SEQUENCE { type AttributeType , value AttributeValue } AttributeType ::= OBJECT IDENTIFIER AttributeValue ::= ANY DEFINED BY AttributeType Val i dity ::= SEQUENCE { notBefore Time , notAfter Time } Time ::= CHOICE { utcTime UTCTime, generalTime GeneralizedTime } U n i q u e I d e n t i f i e r ::= BIT STRING SubjectPublicKeyInfo ::= SEQUENCE { algorithm AlgorithmIdentifier , subjectPublicKey BIT STRING } Extensions ::= SEQUENCE SIZE ( 1 . .MAX) OF Extension Extension ::= SEQUENCE { extnId OBJECT IDENTIFIER , c r i t i c a l BOOLEAN DEFAULT FALSE, extnValue OCTET STRING } Listing I.5: ASN.1 specification for Certificate Info part I.3. Signature d i g e s t I n f o ::= SEQUENCE { digestAlgorithm A l gori t hmId e ntif i er , d i g e s t OCTET STRING } Listing I.6: ASN.1 specification for digestInfo structure 105
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura L.2: Analysis before and after of the installation Figura L.3: Analysis before and after of the initialization 112
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza Figura L.4: Analysis before and after of running the matching algorithm 113
Ap´endice M Securing Off-Card Contract-Policy Matching in Security-By-Contract for Multi-Application Smart Cards Aceptado para publicaci´on en Ubicomm 2010: Cuarta conferencia internacional en computaci´on m´ovil obicua, sistemas, servicios y tecnolog´ıas. Del 25 al 30 de octubre, 2010. Florencia, Italia. Accepted for publication in Ubicomm 2010: The Fourth International Conference on Mobile Ubiquitous Computing, Systems, Services and Technologies. October 25 - 30, 2010. Florence, Italy. 115
Securing Off-Card Contract-Policy Matching in Security-By-Contract for Multi-Application Smart Cards Nicola Dragoni, Eduardo Lostal, Davide Papini DTU Informatics Technical University of Denmark {ndra,dpap}@imm.dtu.dk eduar[email protected] Javier Fabra Department of Computer Science and Systems Engineering University of Zaragoza
[email protected] Abstract—The Security-by-Contract (S×C) framework has recently been proposed to support applications evolution in multi-application smart cards. The key idea is based on the notion of contract, a specification of the security behavior of an application that must be compliant with the security policy of a smart card. In this paper we address one of the key features needed to apply the S×Cidea to a resource limited device such as a smart card, namely the outsourcing of the contract-policy matching to a Trusted Third Party. The design of the overall system as well as a first implemented prototype are presented. Keywords- Multi-Application Smart Cards; Security; Contract Matching. I. INTRODUCTION Java card technology has progressed at the point of allowing several Web applications to run on a smart card and to dynamically load and remove applications during the card’s active life1. With the advent of these new Web enabled multi-application smart cards the industry potential is huge. However, concrete deployment of multi-application smart cards have remained extremely rare. One reason is the lack of solutions to an old problem: the control of interactions among applications. Indeed, the business model of the asynchronous download and update of applications by different parties requires the control of interactions among possible applications after the card has been fielded. In other words, what is missing is a quick way to deploy new applications on the smart card once it is in the field, so that applications are owned and asynchronously controlled by different stakeholders. In particular, owners of different applications (banks, airline companies, etc.) would like to make sure their applications cannot be accessed by new (bad) applications added after theirs, or that their applications will interact only with the ones of some business partners. To date, current security models and techniques for smart cards (namely, permissions and firewall) do not support any type of applications’ evolution. Smart card developers have to prove that all the changes that are possible to apply to the card are security-free, so that their formal proof of compliance with Common Criteria is still valid and they do 1http://java.sun.com/javacard/specs.html not need to obtain a new certificate. The result is that there are essentially no multi-application smart cards, though the technology already supports them (Java Card and Global Platform specifications). The Security-by-Contract (S×C) framework has recently been proposed to address this challenge [1]. The approach was built upon the notion of Model Carrying Code (MCC) [2] and successfully developed for mobile code ([3], [4] to mention only a few). The overall idea is based on the notion of contract, that is a specification of the security behavior of an application that must be compliant with the security policy of the hosting platform (i.e., the smart card). This compliance can be checked at load time and in this way avoid the need for costly run-time monitoring. The effectiveness of S×Chas been discussed in [1], [5], where the authors show how the approach can be used to prevent illegal information exchange among several applications on a single smart card, and how to deal with dynamic changes in both contracts and platform policy. However, in those papers the authors assume that the key S×Cphase, namely contract-policy matching, is done on the card, which is a resource limited device. What they leave open is the issue of outsourcing the contract-matching phase to a Trusted Third Party, in case this phase requires a too expensive computational effort for the card. In this paper we explicitly address this issue, discussing the design and a first prototype of this key functionality of the S×Cframework. The paper is organized as follows. In Section II we introduce the S×Cframework and the problem we tackle. Then the discussion of the design and implementation details of the proposed system are depicted in Section III and IV, respectively. Section V concludes the paper summarizing its contribution. II. SECURITY-BY-CONTRACT (S×C)... IN A NUTSHELL In the S×Capproach, mobile code carries with a claim on its security behavior (an application’s contract) that could be matched against a mobile platform’s policy before downloading the code. In this setting, a digital signature does not only certify the origin of the code but also binds together
the code with a contract with the main goal to provide a semantics for digital signatures on mobile code. At load time, the target platform follows a workflow similar to the one depicted in Fig. 1 (see also [6]). First, it checks that the evidence is correct. Such evidence can be a trusted signature as in standard mobile applications [7]. An alternative evidence can be a proof that the code satisfies the contract (and then one can use PCC techniques to check it [8] or specific techniques for smart-cards such as [9]). Figure 1. S×CWorkflow Once we have evidence that the contract is trustworthy, the platform checks that the claimed policy is compliant with the policy that our platform wants to enforce. This is a key phase called contract-policy matching in the S×Cjargon. If it is, then the application can be run without further ado. At run-time, a firewall (such as the one provided by the Java Card Runtime Environment) can just check that only the declared API in the contract can be called. The matching step guarantees that the resulting interactions are correct. This is a significant saving over full in-line reference monitors. A. Off-Card Contract-Policy Matching A key issue in the S×Cframework concerns who is responsible for executing the contract-policy matching. Due to the computational limitations of a resource limited environment such as a smart card (SC), running a full matching process on the card might be too expensive. In the S×C setting, the choice between “on-card” and “off-card” matching relies on the level of contract/policy abstraction [1], [5]. Indeed, the framework is based on a hierarchy of contracts/policies models for smart cards, so that each level of the hierarchy can be used to specify contracts/policies with different computational efforts and expressivity limitations. This paper focuses on the situation where contract-policy matching is too expensive to be performed on the card. The idea, depicted in Fig. 2, is that a Trusted Third Party (TTP), for instance the card issuer, provides its computational capabilities to perform the contract-policy compliance check. The TTP could supply a proof of contract-policy compliance to be checked on the smart card. The SC’s policy is then updated according to the results received by the TTP: if the compliance check was successful, then the SC’s policy is updated with the new contract and the application can be executed. Otherwise, the application is rejected or the policy enforced off-card (for example, by means of a service provided by the TTP in addition to contract-policy matching). In case the TTP includes a proof of compliance in the reply, then a further check is needed to verify the proof, as shown in Fig. 2. Figure 2. Off-Card S×CContract-Policy Matching In this scenario, the communication between SC and TTP must be secured in order to deal with an untrusted environment. Both contract and policy must be encrypted and signed by SC before they are sent to the TTP to ensure authentication, integrity and confidentiality. Analogously, the results of the compliance check should be encrypted and signed by TTP before they are sent back to SC. III. SECURING OFF-CARD MATCHING To secure the system we use Public Key Infrastructure (PKI), where keys and identities are handled through certificates (namely, X.509 certificates [10]) that are exchanged between parties during communication. For this reason, the SC must engage an initialization phase, where certificates are stored in the SC along with security policies. The security of the system relies on the assumption that the environment in this phase is completely trusted and secure. As above mentioned all messages between SC-TTP will be signed and encrypted. We have decided to use two certificates (i.e. two different key-pairs), one for the signature and one for the encryption, so that in the unlikely event of one being compromised the other is not. The use of two certificates is optional, but it makes the system more secure. In this Section we first show the design of the initialization phase and then pass over the contract-policy matching one. Since the system is based on Java card 2.2.2, the SC acts as a server which responds only to Application Protocol Data Unit (APDU) commands by
means of APDU-response messages. Initialization Phase. This phase is divided into three different steps: Certificate Signing Request (CSR) building [11], certificates issuing, and finally certificates and policy storage. As shown in Fig. 3 the first step consists in building the CSR for the two certificates to be sent to the Certification Authority (CA). The Trusted Reader (TR) queries the SC for its public key, then TR builds the CSR and sends it back to SC that signs it. Message #4 SPrKSCEnc(SCEncCSR) means that the CSR for encryption is signed (S) with private key (PrK) of SC for encryption (Enc). Messages throughout all figures are likewise. Figure 3. CSRs Building In the second step (Fig. 4) the TR - Certificates Manager (TRCM) sends to CA the CSRs previously built, CA issues the certificates and then sends them back to the TRCM. Figure 4. Certificates Issuing The final step, shown in Fig. 5, completes the initialization phase by storing in the SC the two certificates, the security policy and the CA digital certificate (this is needed by the SC to verify certificates of TTP). After the SC has been initialized it is ready to securely engage in any activity that involves the contract and policy matching. Specifically the card will be able to verify the identity of the TTP, authenticate and authorize its requests. Figure 5. Storage of Keys and Certificates on Smart Card Contract-Policy Matching Phase. During this phase the contract and the security policy, stored in the card, are sent from SC to some TTP which runs the matching algorithm and then sends the result back to SC. Our goal is to secure communication between TTP and SC in terms of mutual authentication, integrity and confidentiality. The solution we propose is shown in Fig. 6. It is divided into three parts: certificates exchange,contract and policy sending,matching result sending. Figure 6. Protocol for Off-Card Contract-Policy Matching In the first part TTP and SC exchange their own pair of certificates (one for encryption and one for the signature) and then respectively check the validity of those. Particularly, the SC checks them against CA certificate stored during Initialization phase. If the certificates are valid then the TTP asks SC for the contract and policy. At this point the SC engages in a sequence of actions aiming to secure the message Mcontaining requested information that needs to
be sent back to TTP. Specifically: 1) It generates a session key and a NONCE (Number used Once) that will be used for this communication. 2) It encrypts the session key and the NONCE with TTP Public Key, and then message Mwith the session key. 3) It computes the HMAC (a hash mixed with a salt, i.e. the NONCE (Nsc )) and it signs it. Then the message is sent to TTP which verifies the message and extracts the needed information. In the last part TTP runs the matching algorithm against contract and policy, and builds a secure message containing the algorithm result Rto be sent to SC. The key used for encryption is still the session key generated previously by SC. The signature is done as before except that the HMAC uses as salt the value Nsc +1. At this point SC decrypts and verifies the result and sends an acknowledgement to TTP. IV. PROTOTYPE IMPLEMENTATION A first prototype of the proposed framework has been implemented, representing almost a fully-functional implementation. Java version 1.6 has been used to implement the TTP and the TR, and Java Card 2.2.2 was used for the SC. This version was used instead of Java Card 3 due to the lack of mature in version 3 (actually, there are no cards supporting its real implementation). An APDU extended length capability has been implemented in order to allow sending up to 32KB data messages instead of the by-default maximum 255 bytes size. All message exchange protocols have been implemented and authentication, integrity and confidentiality are ensured by means of X.509 certificates in communications between the TTP and the card. These certificates are managed by means of the CA, which generates self-signed certificates using OpenSSL 0.9.8n. The implementation of the initialization phase is almost finished. All required data is stored and sent to the installer and also sent back to the card. On the other hand, some work must be done in the contract and policy matching phase. Certificate exchange is working properly, but verification is only carried out in the TTP and not on the card yet. RSA keys are used to achieve PKI encryption, but digital signatures and block ciphering must be developed too. To test the prototype, two different simulation environments have been used. At first stages, the Java Card platform Workstation Development Environment tool (Java Card WDE) was used. However, saving the status of the card and all the session data is currently being addressed, so the environment has been changed to the C-language Java Card RE (CREF), which eases this feature. V. CONCLUSION In this paper we have addressed the issue of outsourcing the S×Ccontract-policy matching service to a Trusted Third Party. The design of the overall system as well as a first implemented prototype have been presented. The solution provides confidentiality, integrity and mutual authentication altogether. In particular, the following mechanisms have been implemented to strengthen the security of the system: (i) The use of two different certificates for signature and encryption. (ii) A NONCE created for each session to ensure freshness of the messages. (iii) Both the session key and the NONCE are generated within the SC, and then sent encrypted to TTP. The fact that TTP uses them to correctly compose the message Ris a proof that TTP is the one that decrypted the message in the same session (due to the freshness of NONCE) and no one else did (the only way would be to get the Private Key of TTP but Public Key Cryptosystems are considered secure and unbreakable). (iv) The HMAC sent within the response is salted with Nsc + 1. The change in the value of the salt introduces variability in the hash making it more unlikely to forge. REFERENCES [1] N. Dragoni, O. Gadyatskaya, and F. Massacci, “Supporting applications’ evolution in multi-application smart cards by security-by-contract,” in Proc. of WISTP, 2010, pp. 221–228. [2] R. Sekar, V. Venkatakrishnan, S. Basu, S. Bhatkar, and D. DuVarney, “Model-carrying code: a practical approach for safe execution of untrusted applications,” in Proc. of SOSP- 03. ACM, 2003, pp. 15–28. [3] N. Dragoni, F. Massacci, K. Naliuka, and I. Siahaan, “Security-by-contract: Toward a semantics for digital signatures on mobile code,” in Proc. of EUROPKI. Springer- Verlag, 2007, pp. 297–312. [4] L. Desmet, W. Joosen, F. Massacci, P. Philippaerts, F. Piessens, I. Siahaan, and D. Vanoverberghe, “Security-by- Contract on the .NET platform,” Information Security Tech. Rep., vol. 13, no. 1, pp. 25 – 32, 2008. [5] N. Dragoni, O. Gadyatskaya, and F. Massacci, “Security-by- contract for applications evolution in multi-application smart cards,” in Proc. of NODES, DTU Technical Report, 2010. [6] D. Vanoverberghe, P. Philippaerts, L. Desmet, W. Joosen, F. Piessens, K. Naliuka, and F. Massacci, “A flexible security architecture to support third-party applications on mobile devices,” in Proc. of ACM Comp. Sec. Arch. Workshop, 2007. [7] B. Yee, “A sanctuary for mobile agents,” in Secure Internet Programming, J. Vitek and C. Jensen, Eds. Springer-Verlag, 1999, pp. 261–273. [8] G. Necula, “Proof-carrying code,” in Proc. of the 24th ACM SIGPLAN-SIGACT Symp. on Princ. of Prog. Lang. ACM Press, 1997, pp. 106–119. [9] D. Ghindici and I. Simplot-Ryl, “On practical information flow policies for java-enabled multiapplication smart cards,” in Proc. of CARDIS, 2008. [10] ITU-T, “ITU-T Rec. X.509,” 2005. [11] M. Nystrom and B. S. Kaliski, “PKCS #10: Certification Request Syntax Specification version 1.7,” RFC 2986, 2000.
Ap´endice N Glosario de Acr´onimos N.1. Acr´onimos en castellano AC Autoridad de Certificaci´on CifA(B) Cifrado de B mediante A (en las figuras: C A(B)) CPuA Clave P´ublica de A CPrA Clave Privada de A CSes Clave de sesi´on para criptograf´ıa sim´etrica CSRTI Petici´on de certificaci´on de la tarjeta inteligente EA Emisor de la Aplicaci´on FirA(B) Firma B mediante A (en las figuras: F A(B)) LS Lector Seguro SServidor (en el trabajo futuro) SxC Seguridad-mediante-Contrato TI Tarjeta Inteligente TICertCifr Certificado de TI para cifrar TICertFirm Certificado de TI para firmar TICifCSR Petici´on de certificado de TI para cifrar TICPrCif Clave Privada de TI para cifrar TICPrFir Clave Privada de TI para firmar TICPuCif Clave P´ublica de TI para cifrar TICPuFir Clave P´ublica de TI para firmar TIFirCSR Petici´on de certificado de TI para firmar TPC Tercera Parte de Confianza 121
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza [15] D. Ghindici and I. Simplot-Ryl. On practical information flow policies for java-enabled multiapplication smart cards. In CARDIS ’08: Proceedings of the 8th IFIP WG 8.8/11.2 international conference on Smart Card Research and Advanced Applications, pages 32–47. Springer-Verlag, 2008. [16] P. Girard. Which security policy for multiapplication smart cards? In USENIX Workshop on Smartcard Technology. USENIX Association, 1999. [17] S. Hans. Java Card Platform Overview. Technical report, Sun Microsystems, Inc., 2008. [18] Open Systems Interconnection. Blue Book, volume Fascicle VIII.4, chapter Specification of Basic Encoding Rules for Abstract Syntax Notation One (ASN.1). Telecommunication Standardization Sector of ITU (International Telecommunication Union), 1988. UIT-T Recommendation X.209. [19] H. McGilton J. Gosling. The Java Language Environment: Contents. Sun Microsystems, Inc., white paper edition, May 1996. [20] M. Siev¨anen J. Leiwo. Smart Card Application Development, 2003. [21] Burton S. Kaliski Jr. A Layman’s Guide to a Subset of ASN.1, BER, and DER. RSA Data Security, Inc., Redwood City, CA, Jun 1991. Also revision of the document from 1993 has been looked up. [22] G. Hancke I. Askoxylakis K. Mayes K. Markantonakis, M. Tunstall. Attacking smart card systems: Theory and practice. Information Security Technical Report 14, Elsevier, Aug 2009. [23] K. Markantonakis K. Mayes. Smart Cards, Tokens, Security and Applications. Springer US, 2008. [24] S. Starbug H. Pl¨otz K. Nohl, D. Evans. Reverse-engineering a cryptographic RFID tag. In 17th USENIX security symposium, pages 185–193. USENIX Association, 2008. [25] Q. Zhang W. G. Sirett K. Mayes K. Papapanagiotou, K. Markantonakis. Security and Privacy in the Age of Ubiquitous Computing, volume 181/2005 of IFIP Advances in Information and Communication Technology, chapter On the performance of Certificate Revocation Protocols Based on a Java Card Certificate Client implementation, pages 551–563. Springer Boston, Royal Holloway, University of London, Jun 2005. [26] RSA Laboratories. PKCS #1 v2.1: RSA Cryptography Standard. RSA Security Inc. Public-Key Cryptography Standards (PKCS), Jun 2002. [27] X. Leng. Smart card applications and security. Information Security Technical Report 14, Elsevier, August 2009. [28] C. Sprenger M. Huisman, D. Gurov and G. Chugunov. Checking absence of illicit applet interactions: a case study. pages 84–98. [29] B. Kaliski M. Nystrom. PKCS #10: Certification Request Syntax Specification Version 1.7. RSA Security, Nov 2000. rfc2986. [30] MULTOS. MULTOS Technology. [31] N. Coffey. Java Cryptography. Javamex, 2009. 128
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza [32] D. Papini N. Dragoni, E. Lostal and J. Fabra. Securing off-card contract-policy matching in security-by-contract for multi-application smart cards. In Proc. of the The Fourth International Conference on Mobile Ubiquitous Computing, Systems, Services and Technologies, 2010. [33] K. Naliuka N. Dragoni, F. Massacci and I. Siahaan. Security-by-contract: Toward a semantics for digital signatures on mobile code. In Proc. of EUROPKI, pages 297–312. Springer-Verlag, 2007. [34] O. Gadyatskaya N. Dragoni and F. Massacci. Can we support applications’ evolution in multi-application smart cards by security-by-contract? In Information Security Theory and Practices. Security and Privacy of Pervasive Systems and Smart Devices, volume 6033/2010 of Lecture Notes in Computer Science, pages 221–228. Springer Berlin / Heidelberg, 2010. [35] O. Gadyatskaya N. Dragoni and F. Massacci. Supporting applications’ evolution in multiapplication smart cards by security-by-contract. In 4th Workshop in Information Security Theory and Practices (WISTP 2010), 2010. [36] G. C. Necula. Proof-carrying code. In Proc. of the 24th ACM SIGPLAN-SIGACT Symp. on Princ. of Prog. Lang., pages 106–119. ACM Press, 1997. [37] D. Scheuermann B. Struif O. Henninger, K. Lafou. Verifying X.509 Certificates on Smart Cards. In World Academy of Science, Engineering and Technology, volume 22, pages 25–28, Aug 2006. [38] C. E. Ortiz. An introduction to Java Card Technology. Technical report, Sun Developer Network (SDN), May 2003. [39] S. Petri. An introduction to Smart Cards. Technical report, Secure Service Provider (SSP), October 1999. [40] P.Gutmann. X.509 Style Guide. Technical report, University of Auckland, Oct 2000. [41] S. Basu S. Bhatkar R. Sekar, V. N. Venkatakrishnan and D. C. DuVarney. Model-carrying code: a practical approach for safe execution of untrusted applications. In Proc. of the 19th ACM Symp. on Operating Syst. Princ., pages 15–28. ACM Press, 2003. [42] Cryptography Research. DPA countermeasures. [43] D. Sauveron S. Chaumette. Some security problems raised by open multiapplication smart cards. In 10th Nordic Workshop on Secure IT-systems: NordSec 2005, 2005. [44] D. Sauveron. Multiapplication smart card: Towars an open smart card? Information Security Technical Report 14, Elsevier, Aug 2009. [45] Inc. Smart Card Integrators. s-Choice Smart Card Casino System. [46] W. Stallings. Cryptography and Network Security: Principles and Practice. Pearson Education, 2002. [47] Inc Sun Microsystems. Why Developers Should Not Write Programs That Call ’sun’ Packages, 1996. [48] Inc Sun Microsystems. Java 2 Platform, Standard Edition, v 1.4.2 API Specification, 2003. 129
Securing Multi-Application Smart Cards by Security-by-Contract Eduardo Lostal Lanza [49] Inc Sun Microsystems. Java Card v2.2.2 API Specification, 2005. [50] Sun Microsystems, Inc. The Java Card 3 Platform, white paper edition, Aug 2008. [51] F. Yellin T. Lindholm. The Java Virtual Machine Specification, chapter Chapter 3: The Structure of the Java Virtual Machine. Sun Microsystems, Inc, second edition edition, 1999. [52] W. Effing W. Rankl. Smart Card Handbook. Willey, 2003. [53] R. Di Giorgio Z. Chen. Understanding Java Card 2.0. JavaWorld.com, 1998. 130