scieee AI-readable full text Open interactive document viewer

Repositorio Institucional de Documentos

Abstract

En los últimos años, la telefonía móvil ha redenido la forma de comunicación entre las personas. Los dispositivos electrónicos, a través de los cuales se establece dicha comunicaci ón, han evolucionado vertiginosamente en potencia, rendimiento y sobre todo en nuevas funcionalidades, pero siguen estando limitados por la autonomía que les proporciona la duración de la batería. Mientras la capacidad de procesamiento se incrementa en un 200% cada 18 meses siguiendo la Ley de Moore, el rendimiento de las baterías sólo se ha visto mejorado en un 80% en los últimos 10 años [Fit07]. Esta mejora del rendimiento y la llegada de Internet a estos dispositivos ha hecho posible la comunicación a través de diferentes canales, la búsqueda de información o la posibilidad de realizar compras, todo ello de una forma segura y condencial. Dichas conexiones seguras, bien utilizando conexiones cableadas o inalámbricas, se consiguen mediante la utilización de protocolos de seguridad, basados en algoritmos criptográcos. Estos algoritmos son seleccionados basándose en los objetivos de seguridad denidos en el protocolo de seguridad a utilizar. Entre ellos se incluyen algoritmos de encriptación simétricos y asimétricos, utilizados para proporcionar autenticación y encriptación de los datos, así como algoritmos basados en funciones hash, y, de esa manera, conseguir integridad en los mensajes intercambiados. En la actualidad, el consumo energético en dispositivos móviles es una de los principales preocupaciones de los fabricantes de dispositivos móviles. De la misma manera, la seguridad en las comunicaciones se posiciona como una área muy importante en materia de investigación y desarrollo. El uso de protocolos de seguridad no sólo afecta al rendimiento de las comunicaciones, sino que también representa un fuerte impacto en el consumo energético en estos dispositivos alimentados por baterías. De este modo, uno de los desaf íos más importantes es conseguir un balance entre rendimiento, seguridad y consumo energético, con el n de obtener un buen rendimiento y niveles de seguridad adaptados al usuario con la mínima cantidad de energía. En este contexto, Nokia corporation encargó un proyecto de investigación a la Aalto University School of Science and Technology (Helsinki, Finlandia), para analizar el consumo energético de diferentes protocolos de seguridad y algoritmos criptográcos en la plataforma móvil Symbian. Miranda Arto, Pedro; Siekkinen, Matti; Waris, Heikki

Full text

Proyecto Final de Carrera Ingeniería Informática Curso 2010-2011 Consumo energético de algoritmos criptográcosy protocolos de seguridad en dispositivos móviles Symbian Pedro Miranda Arto Director: Matti Siekkinen (Aalto University, Helsinki) Ponente: Sergio Ilarri Departamento de Informática e Ingeniería de Sistemas Centro Politécnico Superior Universidad de Zaragoza Diciembre de 2010 Agradecimientos A mi padres, Carmen y Pedro, este trabajo es gracias a ellos. A mi hermana Pilar, por saber siempre cómo incentivarme con nuevos retos. A todos mis amigos, gracias a ellos he aprendido muchas cosas, sobre todo cómo arreglar sus ordenadores. A mis compañeros de carrera, por hacer del CPS un lugar un poco menos duro. Y por último pero no menos importante a Sergio Ilarri, por su implicación y sus indicaciones. En Zaragoza, diciembre de 2010 Pedro Miranda ii Índice del documento 1 Introducción 1 1.1 Desarrollo del problema y objetivos . . . . . . . . . . . . . . . . . . . . . . 2 1.2 Organización de este documento . . . . . . . . . . . . . . . . . . . . . . . . 2 2 Contexto Tecnológico 5 2.1 Seguridad informática y sus objetivos . . . . . . . . . . . . . . . . . . . . . 5 2.2 Métodoscriptográcos ............................. 6 2.2.1 Criptografía simétrica . . . . . . . . . . . . . . . . . . . . . . . . . 6 2.2.2 Message Digest y Message Authentication Code (MAC) . . . . . . . 6 2.2.3 Criptografía asimétrica . . . . . . . . . . . . . . . . . . . . . . . . . 7 2.3 Secure Socket Layer (SSL) . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 2.4 Interfaces de red: 3G y WLAN . . . . . . . . . . . . . . . . . . . . . . . . 8 2.4.1 Interfaz3G ............................... 8 2.4.2 InterfazWLAN............................. 9 2.5 Seguridadyenergía............................... 10 2.5.1 Consumo energético de algoritmos criptográcos . . . . . . . . . . . 10 2.5.2 Consumo energético de 3G y WLAN . . . . . . . . . . . . . . . . . 11 3 Metodología 13 3.1 Tecnologías y herramientas utilizadas . . . . . . . . . . . . . . . . . . . . . 13 3.1.1 Symbian................................. 13 3.1.2 NokiaN95................................ 13 3.1.3 Carbide.C++IDE ........................... 14 3.1.4 OpenC/C++.............................. 14 3.1.5 OpenSSL ................................ 14 3.1.6 Nokia Energy Proler . . . . . . . . . . . . . . . . . . . . . . . . . . 15 iv Índice del documento 3.2 Entorno ..................................... 15 3.2.1 Suites criptográcas elegidas . . . . . . . . . . . . . . . . . . . . . . 15 3.2.2 Diseño de los diferentes escenarios . . . . . . . . . . . . . . . . . . . 16 3.3 Conguración experimental . . . . . . . . . . . . . . . . . . . . . . . . . . 19 3.3.1 Diseño de las aplicaciones . . . . . . . . . . . . . . . . . . . . . . . 21 3.3.2 Recolección de datos y muestras . . . . . . . . . . . . . . . . . . . . 22 3.4 Diagrama temporal y de esfuerzo . . . . . . . . . . . . . . . . . . . . . . . 22 4 Resultados Experimentales 27 4.1 Escenario:Casolocal.............................. 27 4.1.1 Datos intercambiados . . . . . . . . . . . . . . . . . . . . . . . . . . 27 4.1.2 Consumo energético . . . . . . . . . . . . . . . . . . . . . . . . . . 28 4.2 Escenario: Casos remotos . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 4.2.1 Estudio del perl de los servicios remotos . . . . . . . . . . . . . . . 29 4.2.2 Datos intercambiados . . . . . . . . . . . . . . . . . . . . . . . . . . 29 4.2.3 Consumo energético . . . . . . . . . . . . . . . . . . . . . . . . . . 29 4.2.4 Tiempos de ejecución paso a paso . . . . . . . . . . . . . . . . . . . 33 4.2.5 Comparando WLAN y 3G . . . . . . . . . . . . . . . . . . . . . . . 37 4.3 Rendimiento y coste adicional . . . . . . . . . . . . . . . . . . . . . . . . . 38 4.3.1 Datos adicionales en SSL . . . . . . . . . . . . . . . . . . . . . . . . 38 4.3.2 Rendimiento en SSL . . . . . . . . . . . . . . . . . . . . . . . . . . 39 4.3.3 Consumo energético adicional en SSL . . . . . . . . . . . . . . . . . 40 4.3.4 Consumo energético de cada uno de los componentes . . . . . . . . 41 5 Conclusiones 45 5.1 Conclusiones a nivel técnico . . . . . . . . . . . . . . . . . . . . . . . . . . 45 5.2 Conclusiones a nivel personal . . . . . . . . . . . . . . . . . . . . . . . . . 46 5.3 Trabajofuturo ................................. 46 Abreviaturas y acrónimos 49 Bibliografía 52 Anexos 54 A El protocolo de Handshake en SSL 55 v Índice del documento B Artículo: TLS and Energy Consumption On a Mobile Device: A Measurement Study 59 C Memoria en Inglés 67 D Evaluación 181 vi Índice de tablas 3.1 Suites criptográcas elegidas . . . . . . . . . . . . . . . . . . . . . . . . . . 16 3.2 Desglose de las horas totales empleadas en el proyecto . . . . . . . . . . . . 25 4.1 Información intercambiada en bytes durante la fase de handshake en el caso local ....................................... 28 4.2 Perl completo de los diferentes servicios remotos analizados . . . . . . . . 30 4.3 Información intercambiada en la fase de handshake para los casos remotos 31 4.4 Perl de los datos intercambiados entre el cliente y el servidor en una conexiónSSL .................................. 39 4.5 Rendimiento del protocolo SSL y un canal no seguro TCP . . . . . . . . . 40 4.6 Coste energético de diferentes operaciones criptográcas . . . . . . . . . . . 42 5.1 Equivalencias de seguridad (longitud de clave en bits) entre criptografía simétrica, de curva elíptica y de clave pública . . . . . . . . . . . . . . . . 47 A.1 Ejemplos de suites criptográcas . . . . . . . . . . . . . . . . . . . . . . . . 55 viii Capítulo 2. Contexto Tecnológico El objetivo de este capítulo es el de proporcionar una denición de lo que es la seguridad informática y los objetivos que hay detrás de esta, dando una denición de los diferentes algoritmos y protocolos utilizados en el campo de la criptografía. Estos incluyen encriptación simétrica y asimétrica, los cuales son usados para proporcionar autenticación y privacidad, así como algoritmos de message digest o funciones hash , utilizados para proporcionar integridad a los mensajes. Una vez explicados estos mecanismos, se da una introducción al protocolo Secure Sockets Layer (SSL), deniendo los diferentes protocolos involucrados y los pasos para establecer una comunicación segura. Además, se proporciona una introducción a los interfaces de red más importantes en los terminales móviles, WLAN y 3G, y sus características. Para nalizar, se incluye un estudio del impacto energético, tanto de la parte criptográca como de los interfaces de red. 2.1 Seguridad informática y sus objetivos El objetivo de la seguridad informática es idear y concebir formas de prevenir las debilidades de un sistema que pueden ser explotadas [PP06] a la vez que se permite que la información permanezca segura y accesible. Los objetivos de la seguridad informática están normalmente asociados a las funcionalidades de seguridad requeridas en un sistema o red para proteger datos sensibles o la identidad de los equipos/usuarios dentro de ese sistema. Existen 4 objetivos importantes, incluyendo: • Condencialidad asegura que los datos se mantienen en secreto ante personas no autorizadas y sólo pueden ser accesibles por usuarios autorizados. Este término es también conocido como privacidad . • Disponibilidad garantiza que la información es accesible por parte de usuarios autorizados cuando es necesaria. • Integridad protege los datos de ser modicados por usuarios no autorizados y sólo permite modicaciones de manera autorizada. • No rechazo es el concepto que prueba el origen de la información. Si este objetivo se consigue, se garantiza que la información es original y genuina. Uno de los desafíos en el desarrollo de un sistema seguro es encontrar un equilibrio correcto entre estos 4 objetivos, los cuales normalmente pueden ser independientes, pueden 5 Capítulo 2. Contexto Tecnológico 2.2. Métodos criptográcos solaparse e incluso pueden ser mutuamente exclusivos. Por ejemplo, asegurar una fuerte condencialidad puede afectar seriamente a la disponibilidad. 2.2 Métodos criptográcos En las siguientes secciones se trata de dar una introducción básica de los diferentes métodos criptográcos existentes y utilizados en este trabajo. Para un estudio más detallado de los fundamentos de la criptografía y de la nomenclatura, el lector puede encontrar mas información en el Capítulo 2 Security and energy background del Anexo C. 2.2.1 Criptografía simétrica La criptografía simétrica emplea el mismo proceso para encriptar y desencriptar, utilizando la misma clave secreta como entrada. Existen 2 tipos de encriptación simétrica: • Cifrado por bloques ( block cipher ) es un tipo de algoritmo de clave simétrica que transforma un bloque de texto de una longitud determinada en un bloque de texto cifrado de la misma longitud [Lab93]. La función de transformación depende de la clave proporcionada por el usuario, mientras que la longitud ja es conocida como el tamaño de bloque, normalmente 64 bits. El algoritmo más utilizado en el cifrado por bloques es AES [oST01]. • Cifrado por ujo ( stream cipher ) utiliza una función que genera un ujo de datos de 1 byte cada vez conocido como keystream . Este método utiliza una clave de encriptación como entrada, la cual controla exactamente cómo se genera dicho keystream . Uno de los algoritmos más utilizados en el cifrado por ujo es RC4 [Kau99]. Los algoritmos de cifrado por bloques son una solución más conservativa que los de cifrado por ujo, ya que estos han sido estudiados más en profundidad contra ataques criptoanalíticos. Sin embargo, estos últimos tienen un mejor rendimiento. Se puede encontrar más información detallada acerca de estos métodos y soluciones en la Sección 2.3 Symmetric Cryptography del Anexo C. 2.2.2 Message Digest y Message Authentication Code (MAC) Un algoritmo de resumen del mensaje o Message digest (también conocido como algoritmo hash ) es básicamente un procedimiento que toma una longitud arbitraria de datos como entrada y genera como salida una suma de vericación o checksum . Este método tiene una propiedad importante: la misma entrada siempre producirá la misma salida. De esta forma, un cambio accidental o intencionado producirá una cambio en dicho checksum . El uso principal de estos message digest es el de la creación de rmas digitales (ver rma digital en Sección 2.2.3). Los 2 más utilizados son Message Digest 5 (MD5) [Riv92] y Secure Hash Algorithm 1 (SHA-1 [EJ01]). 6 Capítulo 2. Contexto Tecnológico 2.3. Secure Socket Layer (SSL) Además de su uso como rma digital, estos algoritmos se utilizan como códigos de autenticación de mensaje o Message Authentication Code (MAC) , los cuales son un tipo de algoritmos de resumen pero incorporan una clave en su creación. Sus aplicaciones más populares son HMAC-SHA-1 o HMAC-MD5. Más información acerca de estos algoritmos y de sus diferentes usos está incluida en la Sección 2.4 Message Digest and Message Authentication Codes del Anexo C. 2.2.3 Criptografía asimétrica La criptografía asimétrica o de clave pública implica el uso de algoritmos asimétricos. Estos algoritmos se utilizan para crear un par de claves relacionadas: una clave privada secreta y otra pública. Un usuario puede usar la clave privada para codicar un mensaje, y ese mensaje puede ser decodicado únicamente con su correspondiente clave pública. Este tipo de criptografía es computacionalmente cara. La seguridad de estos algoritmos depende de la longitud de las claves utilizadas, las cuales normalmente son números muy largos. La criptografía de clave pública tiene 2 usos principales: • Protocolo de establecimiento de clave (Key extablishment protocolo) , en el cual cliente y servidor trabajan conjuntamente para establecer la clave de encriptación a utilizar. Dentro de este protocolo se incluyen 2 métodos para realizar dicha operación: Intercambio de clave (Key exchange) o Acuerdo de clave (Key agreement) . • Firma digital , utilizada para incluir una huella que sólo el emisor puede producir, pero que el receptor puede fácilmente reconocer y vericar que la información incluida es legitima. La rma se genera utilizando la clave privada del emisor, empleando el receptor su clave pública para vericar dicha rma. Las soluciones más populares son RSA [RSA78] y Die-Hellman [WH76]. Mas información sobre estás 2 últimas soluciones y la demostración puede encontrarse en la Sección 2.5 Public Key Cryptography del Anexo C . 2.3 Secure Socket Layer (SSL) Secure Socket Layer (SSL) [ 01 ] y su sucesor Transport Security Layer (TLS) [DA99] es un protocolo que permite establecer un canal seguro entre 2 pares conectados. Este protocolo fue diseñado para proteger datos en tránsito y para identicar los 2 pares involucrados en la comunicación. Los datos son cifrados entre dichos pares, pero la información que un par escribe es exactamente la misma que el otro par recibe. Dicho canal también ofrece transparencia, lo que signica que transmite la información sin cambio alguno. Esta propiedad permite que cualquier protocolo que utilice TCP pueda funcionar sobre SSL con un mínimo de modicaciones. El protocolo SSL se divide en 2 capas: 7 Capítulo 2. Contexto Tecnológico 2.4. Interfaces de red: 3G y WLAN 1. El protocolo de Handshake o apretón de manos permite al cliente y al servidor autenticarse uno al otro y negociar los algoritmos criptográcos a utilizar, así como las claves de encriptación necesarias para asegurar el canal. Se recomienda consultar más información acerca de este protocolo en el Anexo A para comprender los resultados de los experimentos realizados en el Capítulo 4. 2. El protocolo de record o de registro proporciona privacidad y abilidad a los datos intercambiados. Es el responsable de transferir la información y de interpretar los diferentes tipos de mensajes de los que el protocolo SSL está formado (ver Sección 3.3 The Record Protocol en el Anexo C). Este protocolo funciona de tal manera que divide los datos a transferir en fragmentos, cada uno de ellos independientemente protegido. Este comportamiento permite enviar los datos tan pronto como estén listos. Cabe mencionar que en este documento siempre se hace referencia a este protocolo como SSL, reriéndose indistintamente tanto a SSLv3 [Cor96] como a la versión estandarizada del protocolo TLS [DA99]. Más información acerca de este protocolo y de sus diferentes usos está incluida en el Capítulo 3 SSL and TLS del Anexo C. 2.4 Interfaces de red: 3G y WLAN Con la irrupción de Internet en los dispositivos móviles, los usuarios quieren estar en linea todo el tiempo. Esta tendencia genera un uso continuo e importante de la batería. Las interfaces de red, tales como GSM, 3G o WLAN, son las responsables de las diferentes comunicaciones utilizadas en un dispositivo móvil. En [Fit07] se menciona que estas interfaces son las causantes de aproximadamente el 50% del desgaste de la batería. Así pues, cualquier reducción en el uso de dichos interfaces signicará una mejora sustancial en la duración general de la batería. En este trabajo, solamente se estudian los interfaces 3G y WLAN, ya que estos son los más importantes y más utilizados para la transmisión de datos. Para analizar su consumo energético, es fundamental entender la naturaleza de los mismos. 2.4.1 Interfaz 3G 3G o Tercera generación es una familia de estándares para telecomunicaciones móviles que permite simultáneamente la transmisión de voz y datos con velocidades de transferencia de 14 Mbit/s de bajada y 5.8 Mbit/s de subida [XSK + ]. El interfaz 3G funciona en 3 modos diferentes de operación: • IDLE en ausencia de actividad en la red. • Dedicated Channel (DCH) asegura el máximo rendimiento con bajas latencias de transmisión, pero con un coste muy alto de energía. 8 Capítulo 2. Contexto Tecnológico 2.4. Interfaces de red: 3G y WLAN • Forward Access Channel (FACH) comparte el canal con otros dispositivos 3G y se usa cuando hay poco tráco a transmitir, utilizando alrededor de un 50% de la energía consumida en el estado DCH. Las transiciones desde DCH a FACH y desde FACH a IDLE son controladas por temporizadores de inactividad, los cuales normalmente se miden en segundos. Asimismo, el consumo energético de la interfaz de red 3G puede ser cuanticado atendiendo a estos 4 tipos de energía: 1. Energía de rampa necesaria para cambiar al estado DCH o de máximo rendimiento 2. Energía de transmisión utilizada en la transmisión de datos. 3. Energía de cola necesaria para mantener el estado DCH después de la nalización de la transmisión hasta la transición al estado FACH marcada por uno de los temporizadores de inactividad. 4. Energía de mantenimiento utilizada para mantener la interfaz de red 3G encendida. Cabe mencionar que la energía de cola puede ser de hasta un 60% del total de la energía utilizada para transmitir 50KB [BBV09]. 2.4.2 Interfaz WLAN La interfaz de red WLAN o Wireless Local Area Network se utiliza para conectar diferentes dispositivos sin la necesidad de la utilización de cables, permitiendo en la mayoría de los casos una conexión directa a Internet. Estos dispositivos se han vuelto muy populares debido a su creciente uso y las capacidades inalámbricas de portátiles y de smartphones . El estándar actual IEEE 802.11 dene diferentes bandas de frecuencia operacionales, tales como 2.4, 3.6 y 5 GHz. A su vez, existen diferentes protocolos, pero el más extendido es el 802.11g, establecido en una banda de frecuencias de 2.4GHz y operando a una velocidad máxima de 54 Mbit/s, con una rendimiento medio de 22 Mbit/s [XSK + ]. El consumo energético en esta interfaz WLAN puede ser cuanticado atendiendo a estos 3 factores: 1. Escaneo y asociación a una red : la energía utilizada en la búsqueda de las redes disponibles y la asociación a una de ellas. 2. Energía de transmisión : la energía requerida para la transmisión de los datos 3. Energía de mantenimiento : la energía necesaria para mantener el interfaz de red WLAN encendido. Al contrario que con el interfaz 3G, WLAN dispone de sistemas de ahorro de energía (como puede ser Power Saving Mode (PSM) ) que reducen enormemente el consumo cuando dicho interfaz no esta transmitiendo. 9 Capítulo 2. Contexto Tecnológico 2.5. Seguridad y energía 2.5 Seguridad y energía Los dispositivos de mano o handhelds como teléfonos móviles o PDAs , están fuertemente limitados por las baterías que incorporan. Componentes como el procesador, la pantalla y su iluminación, la cámara y sobre todo las interfaces de red, representan un impacto enorme en la descarga de la batería. Con todos estos componentes, la capacidad de los terminales para estar conectados durante largos periodos de tiempo se ve afectada dependiendo de su uso. En [Fit07] se nombra que en los últimos 10 años la capacidad de las baterías sólo se ha visto incrementada en un 80%, mientras que las capacidades de los microprocesadores se ven incrementadas un 200% cada 18 meses siguiendo la ley de Moore. Esta mejora en las capacidades de computación permite a los desarrolladores diseñar nuevas aplicaciones con nuevas funcionalidads que pueden tienen importantes costes energéticos dependiendo de las necesidades computacionales. 2.5.1 Consumo energético de algoritmos criptográcos Como se ha comentado previamente, la llegada de Internet a los dispositivos móviles ha hecho posible la comunicación a través del mismo, la búsqueda de información, la compra de artículos o compartir información de una forma segura y condencial. Esta privacidad se consigue gracias al uso de algoritmos criptográcos y de protocolos de seguridad, los cuales tienen un importante impacto en la duración de la batería, incrementando el número de cálculos y operaciones en el microprocesador y también aumentando la cantidad de datos intercambiados. Investigaciones previas [APS99] [PRRJ06] [SGM09], analizan el coste energético de diferentes algoritmos criptográcos así como el rendimiento del protocolo SSL en PDAs y en ordenadores personales. Estos estudios muestran diferentes observaciones, de las que se mencionan las más importantes a continuación: • La criptografía de clave pública tiene los costes energéticos más altos, mientras que los algoritmos hash tienen un impacto pequeño en la duración de la batería. • La elección del tamaño de clave afecta signicativamente al consumo energético en algoritmos asimétricos, pero no de igual manera en los simétricos. • El use de Die-Hellman como protocolo de acuerdo de clave durante la fase de negociación o handshake mejora la seguridad, pero a causa de incrementar signicativamente el coste energético y reduciendo el rendimiento si se compara con otros algoritmos de intercambio de clave como RSA. • El uso de SSL como protocolo de seguridad afecta signicativamente al rendimiento general de la conexión, pero esto puede ser suavizado eligiendo el algoritmo que más se adapte dependiendo de las necesidades de seguridad del usuario y de las capacidades hardware del equipo utilizado. 10 Capítulo 2. Contexto Tecnológico 2.5. Seguridad y energía 2.5.2 Consumo energético de 3G y WLAN En [BBV09] se estudia el consumo energético de estos interfaces de red utilizando un Nokia N95, el mismo empleado en este trabajo, con las siguiente conclusiones generales: • 3G consume signicativamente más energía en la descarga de datos que WLAN. Además de la diferente naturaleza de las comunicaciones, el menor ancho de banda comparado con WLAN requiere que la interfaz este operativa más tiempo y, por lo tanto, el consumo es mayor. • El uso de políticas de ahorro energético en WLAN tales como Power Saving Mode (PSM) reduce de forma signicativa el coste energético cuando el interfaz no se utiliza. • En 3G, cerca del 60% de la energía utilizada es energía de cola , consumida después de la nalización de una transmisión. Comparado con esto, la energía de rampa es sólo una pequeña cantidad y puede ser amortiguada con frecuentes y sucesivas transferencias, dentro del intervalo que marca el temporizador de inactividad. • La energía de transmisión es proporcional al tamaño de los datos transferidos y el nivel de la señal con que se ha transmitido. Esta energía utilizando WLAN es sustancialmente más pequeña que 3G, especialmente para transmisiones de datos grandes. A medida que se aumenta el tamaño de los datos, la eciencia crece. • WLAN es más eciente que 3G una vez que la interfaz de red se ha asociado al punto de acceso. • La energía para mantener cada uno de los interfaces de red es de 1-2 Julios/min en el caso de 3G mientras que es de 3-3.5 Julios/min en el caso de WLAN. Todas estas conclusiones, tanto de los sistemas criptográcos como del coste energético de WLAN y 3G, servirán para explicar mejor los resultados obtenidos en el Capítulo 4. 11 Capítulo 3. Metodología El objetivo principal de este capítulo es no sólo documentar las tecnologías, herramientas y componentes utilizados, sino también detallar los diferentes algoritmos y suites criptográcas utilizadas, justicando su elección. Además, también se incluye un estudio de los diferentes escenarios diseñados para la realización de los experimentos, así como la conguración experimental construida para tal n. 3.1 Tecnologías y herramientas utilizadas En la siguiente sección, se da una introducción a todas las tecnologías y herramientas utilizadas. Para una referencia mas detallada de cada una de ellas consultar la Sección 4.2 Hardware and Software used del Anexo C. 3.1.1 Symbian Symbian 1 es la plataforma mas utilizada y popular en los dispositivos móviles Nokia. El sistema Symbian es un sistema operativo multitarea de 32 bits capaz de ejecutar aplicaciones construidas con diferentes lenguajes de programación tales como Symbian C++, Open C/C++, Java, Adobe Flash o Qt. 3.1.2 Nokia N95 El teléfono Nokia N95 2 (ver Figura 3.1) fue lanzado al mercado en 2007 por Nokia. Está basado en Symbian 9.2, la tercera generación de dicho sistema operativo, y es el primer dispositivo de Nokia con conectividad HSDPA o 3.5G, la evolución del 3G. 1 http://www.symbian.org - Último acceso: 2 noviembre 2010 2 http://europe.nokia.com/support/product-support/nokia-n95 - Último acceso: 2 noviembre 2010 13 Capítulo 3. Metodología 3.3. Conguración experimental Figura 3.3: Conguración experimental entre el cliente y el servidor 20 Capítulo 3. Metodología 3.3. Conguración experimental 3.3.1 Diseño de las aplicaciones En esta sección se comentan los aspectos más importante de la implementación tanto del servidor como del cliente, así como los diferentes modos y opciones ofrecidos por los mismos. Se pueden obtener más detalles en la Sección 4.5.1 Design of the applications del Anexo C. Diseño del cliente El cliente SSL está desarrollado en lenguaje C con algunas funciones adicionales como la conexión interna con NEP creadas con C++. Para la codicación en estos lenguajes, es necesario el conjunto de librerías incorporadas en Open C/C++, que a su vez incluyen la implementación de OpenSSL necesaria para la implementación de los distintos métodos criptográcos y del protocolo SSL. Como el objetivo de este trabajo es medir el consumo energético de el uso del protocolo SSL y de otros métodos criptográcos, cualquier otro servicio o aplicación que esté en funcionamiento generará un coste energético extra. Con el n de ahorrar energía, memoria y ,a su vez, hacer la implementación más sencilla, no existe interfaz gráca, únicamente una consola de comandos para seleccionar las diferentes opciones para crear los diferentes escenarios a medir. En este tipo de conguraciones experimentales, la parte más importante corresponde con la implementación del motor criptográco y las mejores relacionadas con él, pero no en la interfaz gráca. Estas mejoras también incluyen la selección del interfaz de red a utilizar, que también se establece únicamente utilizando la consola de comandos. El proceso de handshake en SSL conlleva operaciones con tiempos de ejecución de un orden de magnitud de milisegundos. Para asegurar resultados precisos en los experimentos, es necesario la realización de varias repeticiones de los diferentes procesos y experimentos. Esto también es importante ya que el Nokia Energy Proler realiza muestras en las mediciones en intervalos de 0.25 ms. De este modo, en algunos casos (como pueden ser en el uso de la suite criptográca AES[128,256]-SHA1), el número de repeticiones es de hasta 300. Este número de repeticiones se selecciona dependiendo del tamaño de los datos incluido en las pruebas. Diseño del servidor El servidor SSL está implementado en lenguaje C y se ejecuta en un PC que virtualiza una distribución Linux Ubuntu 10 . El factor principal de la utilización de la virtualización es debido a que el IDE utilizado para el desarrollo de la aplicación cliente, Carbide.C++ sólo funciona en sistemas operativos Windows, por lo que para un correcta metodología de trabajo, en la que se incluyen experimentos y modicaciones en el código iteratívamente, era totalmente necesario. Además, el uso de Ubuntu es debido a que es un entorno Linux que proporciona aplicaciones como SSLDump 11 , que permiten la decodicación de todas las comunicaciones SSL conociendo la clave secreta. Este programa fue utilizado en 10 http://www.ubuntu.com/ - Último acceso: 2 noviembre 2010 11 http://www.rtfm.com/ssldump/ - Último acceso: 2 noviembre 2010 21 Capítulo 3. Metodología 3.4. Diagrama temporal y de esfuerzo una fase temprana de la investigación, pero como posteriormente se le incluyó al cliente también la mayoría de las opciones de SSLDump, ya no fue necesario. Se empleó una versión modicada de OpenSSL para la implementación del protocolo SSL en el desarrollo del servidor. SSLv3 y TLS ofrecen métodos de compresión opcionales para la transmisión de datos, pero no existe ninguno por defecto. OpenSSL utiliza por defecto compresión ZLIB 12 si es soportada por ambos pares. Con el n de realizar diferentes experimentos donde es necesario comparar la energía disipada utilizando un canal seguro SSL o un canal sin seguridad, fue necesario deshabilitar la compresión para intercambiar la misma cantidad de datos en los diferentes escenarios. 3.3.2 Recolección de datos y muestras Como se menciona en la Sección 3.1.6, se utiliza NEP para monitorizar y registrar el consumo energético del dispositivo móvil, el desgaste de la batería, las comunicaciones, la carga de la CPU y el voltaje a lo largo del tiempo. Con el n de ampliar las funcionalidades, NEP ofrece un componente externo y una API 13 para controlar las funcionalidades de la aplicación desde cualquier aplicación externa, en este caso el cliente móvil SSL, permitiendo iniciar y parar las mediciones en cualquier momento. Dicho componente habilita una clase CJuiceExternalAPI , que es la encargada de establecer la comunicación entre el cliente móvil y NEP. De este modo, se permiten realizar mediciones precisas en cualquier intervalo de tiempo deseado. La Figura 3.4 muestra cómo se inician tanto el cliente como el servidor y se preparan para establecer la comunicación SSL, junto con el protocolo de medición de los datos. Como se ha comentado en la Sección 2.5.2, diferentes estudios han demostrado que el mayor impacto energético en dispositivos móviles es debido al uso de interfaces de comunicación como pueden ser 3G, WLAN o Bluetooth , seguido por el consumo de pantallas y de la iluminación de las mismas. El proceso de medida del consumo se realiza de tal manera que únicamente el mínimo de servicios y aplicaciones necesarias para operar el móvil esté en funcionamiento, así como con la desconexión de la pantalla. De este modo, el cliente necesita esperar hasta que la pantalla pase a un estado donde dicha iluminación esté apagada. Esto supone un importante reducción del consumo energético y una mejora en la precisión de los experimentos. 3.4 Diagrama temporal y de esfuerzo En esta sección se pretende detallar, mediante la ayuda de un diagrama de Gantt (ver Figura 3.5), las diferentes etapas por las que el proyecto ha ido pasando hasta su nalización, intentando reejar de una manera aproximada el tiempo empleado en cada una de las diferentes tareas. 12 http://www.zlib.net/ - Último acceso: 2 noviembre 2010 13 http://www.forum.nokia.com/Tools_Docs_and_Code/Tools/Plug-ins/Extensions/Nokia_En- ergy_Proler_External_APIs/ - Último acceso: 2 noviembre 2010 22 Capítulo 3. Metodología 3.4. Diagrama temporal y de esfuerzo Figura 3.4: Visión general de la comunicación entre el cliente, el servidor y Nokia Energy Proler El proyecto se inició en Octubre de 2009, dándose por nalizado en Mayo de 2010. Tras la conclusión, se decidió continuar el trabajo con el n de publicar un articulo de investigación con los diferentes resultados obtenidos. Esta fase no está reejada en el diagrama, ya que se compaginó la escritura del articulo con un trabajo en una empresa externa a tiempo completo, por lo que el tiempo dedicado a esta tarea fue disperso. Una vez - nalizado el trabajo, a nales de Septiembre de 2010 se comienza con la adaptación de la memoria nal y su traducción, dando por nalizado el proyecto a nales de Octubre de 2010. El proyecto tuvo una duración aproximada de 440 horas, en las que no está incluido el tiempo invertido en el desarrollo del artículo de investigación. Estas tareas se pueden dividir en: • Estudio previo: Fase de estudio del problema y de recopilación de información.  Estudio de criptografía y seguridad.  Estudio del protocolo SSL. • Desarrollo: Fase de diseño, codicación y prueba de las aplicaciones de test. • Experimentación: Fase de experimentos y mediciones. • Documentación: Fase de escritura de la documentación y memoria nal.  Redacción de la memoria en Inglés. 23 Capítulo 3. Metodología 3.4. Diagrama temporal y de esfuerzo Figura 3.5: Diagrama de Gantt del proyecto 24 Capítulo 3. Metodología 3.4. Diagrama temporal y de esfuerzo Figura 3.6: Diagrama de tiempos invertidos  Adaptación y traducción de la memoria nal para su presentación en la universidad de Zaragoza. En la Tabla 3.2 se desglosa el número aproximado de horas dedicadas en cada una de las tareas individualmente, mostrando el porcentaje del total de horas, los cuales se muestran en la Figura 3.6. Concepto Horas Porcentajes Estudio previo Estudio de criptografía y seguridad 80 15,7 Estudio de SSL 50 9,8 Desarrollo Desarrollo de aplicaciones de test 120 23,5 Experimentación Experimentos y mediciones 110 21,6 Documentación Memoria 100 19,6 Adaptación y traducción de la memoria 50 9,8 Total 510 Tabla 3.2: Desglose de las horas totales empleadas en el proyecto 25 Capítulo 4. Resultados Experimentales En esta sección, se detalla un completo análisis del consumo energético del protocolo SSL y de los algoritmos asociados a él, utilizando la conguración experimental descrita en la Sección 3.3. 4.1 Escenario: Caso local La realización de experimentos en un ámbito local (latencias inferiores a 1 ms) reduce el tiempo empleado en establecer una conexión SSL debido a los diferentes mensajes intercambiados y los ACKs que ambos pares intercambian. Así pues, manteniendo las interfaces de red transmitiendo únicamente el tiempo necesario, se pueden obtener resultados mas precisos del coste energético total del establecimiento de dicha conexión. 4.1.1 Datos intercambiados Para entender bien cuánta información se intercambia en la fase de handshake , el cliente incluye una opción para medir el número de bytes intercambiados en la operación. Como en la fase de handshake únicamente se utilizan algoritmos criptográcos de clave pública (RSA) y mecanismos de intercambio de clave (RSA o Die-Hellman), los métodos de encriptación (AES) y los relacionados con integridad (HMAC-SHA1) no afectan y los resultados muestran este hecho: ya sea AES con longitud de clave 128 ó 256 bits, la única diferencia es debida el uso de RSA o DH. La Tabla 4.1 muestra los resultados en bytes divididos en 3 modos de operación: autenticación del cliente, sin autenticación del cliente y reanudación de la sesión. Para cada modo se analizaron las 4 suites criptográcas comentadas en la Sección 3.2.1. Las columnas marcadas con C→S y con C←S indican el ujo de la información, en bytes, de cliente a servidor y viceversa, respectivamente. Analizando la tabla anterior podemos concluir que el cliente siempre envía la misma cantidad de información, independientemente de la suite criptográca utilizada. Esta varía si se requiere autenticación del mismo y la variación dependerá de la longitud del certicado que proporcione el cliente. Además, el uso de la reanudación de la sesión reduce signicativamente la cantidad total de datos en un 50% en el lado del cliente y de más de un 90% en el lado del servidor. 27 Capítulo 4. Resultados Experimentales 4.1. Escenario: Caso local Operation Mode Cipher suite C→S S →C No Client AES128-SHA 249 2368 Authentication AES256-SHA 249 2368 DHE-RSA-AES128-SHA 249 2770 DHE-RSA-AES256-SHA 249 2770 Client AES128-SHA 1772 2348 Authentication AES256-SHA 1772 2348 DHE-RSA-AES128-SHA 1772 2752 DHE-RSA-AES256-SHA 1772 2752 Session Resumption NOT RELEVANT 142 168 Tabla 4.1: Información intercambiada en bytes durante la fase de handshake en el caso local 4.1.2 Consumo energético La Figura 4.1 muestra el consumo energético en milijulios (mJ) para las diferentes suites criptográcas en los diferentes modos antes señalados. Analizando dicha gura, la conclusión más importante que se obtiene es que el uso de Die-Hellman afecta críticamente al consumo energético por conexión comparado con RSA, siendo estos valores de 739 mJ y 99 mJ, respectivamente. El uso de autenticación por parte del cliente incrementa ligeramente el consumo, 842 mJ y 155 mJ, ya que es necesario más intercambio de datos. Además y como se ha comentado antes, el uso de la reanudación de sesión reduce enormemente el consumo energético a únicamente 64 mJ, independientemente del modo de operación elegido, ligeramente superior a los 25 mJ del coste total de una conexión TCP sin ningún tipo de seguridad adicional. Figura 4.1: Consumo energético en la fase de handshake para el caso local 28 Capítulo 4. Resultados Experimentales 4.2. Escenario: Casos remotos 4.2 Escenario: Casos remotos Mientras que en la sección anterior se describen experimentos realizados en un ámbito local con latencias menores a 1 ms, en los casos remotos, se estudian diferentes servicios remotos que dependen en gran medida de su localización geográca, el estado actual de la red y de el interfaz de red utilizado. 4.2.1 Estudio del perl de los servicios remotos Antes de empezar a explicar los experimentos y los resultados de los mismos, es necesario realizar un perl completo de los servicios remotos estudiados. Este estudio intenta analizar las propiedades más importantes de cada servicio incluyendo los protocolos SSL disponibles así como las diferentes implementaciones, la suite criptográca por defecto y la lista de las mismas disponibles, la longitud del certicado digital del servidor junto con la longitud de la clave pública y si incluye soporte o no para reanudar una sesión previamente establecida, así como si permite autenticación mediante el uso de Die-Hellman. Se puede encontrar más información en la Sección 5.2.1 Services prole study del Anexo C. La Tabla 4.2 recoge toda la información obtenida acerca de los servicios estudiados. Este estudio es necesario y ayudará a analizar y comprender mejor los diferentes resultados obtenidos en los siguientes experimentos. 4.2.2 Datos intercambiados Como ocurría con los experimentos realizados para el caso local, es importante medir la cantidad de información intercambiada para entender bien el consumo energético involucrado en la fase de handshake. La Tabla 4.3 muestra que el cliente siempre envía la misma cantidad de información, que únicamente se ve incrementada cuando el servidor utiliza una clave pública de longitud 2048 bits, como es el caso de ssl.Facebook y Verisign. Esta longitud de clave pública también coincide con una mayor longitud del certicado de los servidores, siendo Facebook, ssl.Facebook and Verisign los mayores. De nuevo, la posibilidad de reanudar una sesión SSL previa reduce la cantidad de información intercambiada desde los más de 5 KB a únicamente 179 bytes. 4.2.3 Consumo energético Una vez que se ha desarrollado un perl completo de los diferentes servicios y de la cantidad de información necesaria en cada uno de los handshakes , la Figura 4.2 muestra el consumo energético utilizando la interfaz de red WLAN. Como se ha comentado antes para el caso local, el uso de Die-Hellman afecta de manera drástica al coste energético total del establecimiento de la conexión, no sólo incrementando el tiempo de ejecución sino también los datos totales enviados por los pares durante todo la fase de handshake. Otro 29 Capítulo 4. Resultados Experimentales 4.2. Escenario: Casos remotos Figura 4.6: Tiempo de ejecución de los diferentes pasos de la fase de handshake utilizando RSA con 3G Figura 4.7: Tiempo de ejecución de los diferentes pasos de la fase de handshake utilizando DHE con 3G 36 Capítulo 4. Resultados Experimentales 4.2. Escenario: Casos remotos 4.2.5 Comparando WLAN y 3G Una vez se han presentado los resultados de los experimentos utilizando WLAN y 3G de forma separada, en esta sección se presentan las Figuras 4.8 y 4.9 para mostrar una comparativa con los valores medios de todos los consumos energéticos y de los tiempos de ejecución de los diferentes servicios estudiados, con el n de proporcionar una clara visión general de la diferencia de uso de las 2 interfaces de red. En el caso del uso de 3G, la media del consumo energético es un 300% mayor en el caso de la utilización de WLAN. Esto es debido en su mayor parte a las latencias mayores derivadas del uso de 3G, unido a su vez al ancho de banda inferior del mismo, lo que supone tiempos de transferencia mayores, manteniendo la interfaz de red en estado de consumo máximo más tiempo. Figura 4.8: Comparación del consumo energético entre WLAN y 3G Figura 4.9: Comparación de los tiempos de ejecución de la fase de handshake entre WLAN y 3G 37 Capítulo 4. Resultados Experimentales 4.3. Rendimiento y coste adicional 4.3 Rendimiento y coste adicional En las secciones anteriores, se ha tratado de medir el consumo energético, analizando en profundidad los pasos mas costosos y midiendo también la cantidad de información intercambiada entre el cliente y el servidor. Esta sección tiene por objetivo, utilizando datos obtenidos en algunos de los experimentos previos, estudiar el coste adicional real del protocolo SSL y su rendimiento. 4.3.1 Datos adicionales en SSL La Tabla 4.4 muestra la cantidad de información extra que se deriva del uso de SSL por el uso de RSA o DHE. La primera columna muestra el tamaño de los datos en bytes utilizados en cada experimento, desde 1KB a 5 MB. La siguiente muestra de qué manera se han enviado los datos, C->S signica de cliente a servidor y S->C , de servidor a cliente. La siguiente columna indica los datos intercambiados únicamente en el protocolo de handshake. Total RSA y Total DHE muestran los datos totales: Total _ Data =Handshake _ protocol +Record _ Protocol Es importante mencionar que en el protocolo de registro no sólo se incluye el tamaño de los datos de texto sin cifrar, sino que existen datos extra derivados del uso de SSL, como puede ser el hash HMAC-SHA1, y datos adicionales utilizados por el algoritmo de encriptación simétrico AES, los cuales incrementan ligeramente el tamaño de cada paquete. Las 2 siguientes, Overhead RSA (bytes) y Overhead DHE (bytes), muestran el verdadero coste adicional de SSL en bytes. SSL _ Overhead =Total _ Data −Transaction _ size Por último, Overhead RSA (%) y Overhead DHE (%) muestran el porcentaje del coste adicional comparado con el tamaño de los datos enviados. Overhead(%) = SSL _ Overhead(bytes) Transaction _ size(bytes)×100 Este coste adicional decrece a medida que el tamaño de datos se ve incrementado, pero hay que destacar que para tamaños pequeños de datos (1024 bytes), el coste adicional puede ser de alrededor de un 300% (utilizando DHE), ya que el certicado que envia el servidor es más de un 200% mayor. Sin embargo, para tamaños mayores de 100 KB dicho coste adicional se ve reducido a un 6%, siendo un 3% en el caso de 5MB. 38 Capítulo 4. Resultados Experimentales 4.3. Rendimiento y coste adicional Transaction Direction Handshake Total Total Overhead Overhead Overhead Overhead size(bytes) RSA(bytes) DHE(bytes) RSA(bytes) DHE(bytes) RSA(%) DHE(%) 1024 C->S 263 1361 1363 2721 3125 265,72 305,18 S->C 2384 2384 2786 10240 C->S 263 10910 10912 3054 3458 29,82 33,77 S->C 2384 2384 2786 51200 C->S 263 53350 53352 4534 4938 8,86 9,64 S->C 2384 2384 2786 102400 C->S 263 106400 106402 6384 6788 6,23 6,63 S->C 2384 2384 2786 512000 C->S 263 530800 530802 21184 21588 4,14 4,22 S->C 2384 2384 2786 1024000 C->S 263 1061300 1061302 39684 40088 3,88 3,91 S->C 2384 2384 2786 5120000 C->S 263 5305300 5305302 187684 188088 3,67 3,67 S->C 2384 2384 2786 Tabla 4.4: Perl de los datos intercambiados entre el cliente y el servidor en una conexión SSL 4.3.2 Rendimiento en SSL En esta sección se trata de analizar el rendimiento del protocolo SSL comparado con el uso de una conexión no segura utilizando TCP. La Tabla 4.5 muestra los resultados obtenidos en los diferentes experimentos. La primera columna indica el tamaño de los datos. La segunda muestra el número de conexiones realizadas para asegurar la precisión de los datos obtenidos. En el caso de tamaños de datos pequeños, el número de conexiones comienza en 300 y se va reduciendo a medida que dicho tamaño de datos se incrementa. Las razones de este proceso repetitivo han sido explicadas en la Sección 3.3.1. La tercera y cuarta columna indican el tiempo total de ejecución de los experimentos utilizando o no SSL. La quinta y sexta columna representan, en negrita, el rendimiento real del uso de SSL o no. Las 2 últimas columnas muestran el porcentaje medio de carga del procesador durante todo el proceso. Estos valores servirán para explicar algunos problemas encontrados en el uso de tamaños de datos grandes. El rendimiento se obtiene multiplicando el tamaño de los datos por el número de conexiones y dividiendo este resultado por el tiempo total de ejecución: Throughput(MB/s) = Transaction _ size ×Number _ of _ connections Total _ execution _ time ×106 Como el rendimiento se presenta en MB/s, este resultado tiene que dividirse por 106 , ya que el tamaño de datos está en bytes. La Figura 4.10 ayuda a interpretar mejor los resultados. A medida que el tamaño de datos incrementa, también lo hace el rendimiento. Esto es debido a que, a medida que los datos aumentan, el número de conexiones necesarias disminuye, y por tanto hay un menor tiempo total de ejecución. Como se ha comentado antes, para tamaños de datos mayores a 512KB, los resultados muestran que, cuando se utiliza SSL, el procesador está funcionando a carga máxima, alcanzando un 100% de uso y limitando la velocidad en la transmision. Este problema se debe al procesador incluido en el terminal móvil, un Dual ARM 11 a 332 MHz, el cual no 39 Capítulo 4. Resultados Experimentales 4.3. Rendimiento y coste adicional Transaction Number of Total execution time Total execution time Throughput Throughput % CPU % CPU size (bytes) connections with SSL(s) without SSL (s) with SSL (MB/s) without SSL (MB/s) with SSL without SSL 1024 300 20,95 5,38 0,015 0,057 85 90 10240 200 17,42 8,75 0,118 0,234 90 95 51200 150 28,66 18,08 0,268 0,425 96 98 102400 100 32,42 23,54 0,316 0,435 98 98 512000 30 48,55 31,71 0,348 0,484 100 98 1024000 10 26,48 14,74 0,387 0,695 100 96 5120000 5 63,38 39,74 0,404 0,644 100 97 Tabla 4.5: Rendimiento del protocolo SSL y un canal no seguro TCP Figura 4.10: Comparación del rendimiento utilizando SSL y un canal no seguro TCP es capaz de procesar las operaciones criptográcas a tiempo, creando un cuello de botella que limita el rendimiento general. 4.3.3 Consumo energético adicional en SSL Mientras que en la sección anterior se ha medido el rendimiento, en esta se pretende medir el consumo energético adicional derivado del uso de SSL, tanto utilizando WLAN como 3G. Las Figuras 4.11 y 4.12 representan grácamente los resultados obtenidos. En resultados anteriores, a medida que el tamaño de los datos incrementaba el coste adicional disminuía. Teóricamente, y tal como se ha visto en trabajos anteriores, el coste energético adicional del uso de SSL debería disminuir a medida que el tamaño de los datos se ve incrementado. Estos experimentos muestran que esta tendencia es correcta utilizando 3G pero muestran otros resultados con el uso del interfaz WLAN. Este hecho está relacionado con el factor limitante del procesador comentado en la sección anterior, en el cual el terminal no es capaz de completar todas las operaciones criptográcas a tiempo. Utilizando WLAN no existe latencia entre las operaciones y los ACKs del servidor llegan con retardo menor a 1 40 Capítulo 4. Resultados Experimentales 4.3. Rendimiento y coste adicional Figura 4.11: Coste energético adicional del uso de SSL utilizando WLAN ms. Sin embargo, utilizando 3G dichos retardos son de más de 100 ms, tiempo suciente para que el terminal complete las operaciones necesarias y mande el siguiente paquete. Figura 4.12: Coste energético adicional del uso de SSL utilizando 3G En la Sección 5.3.3 SSL Energy Consumption Overhead del Anexo C se puede encontrar más información acerca de estos experimentos, así como resultados y conclusiones adicionales comparando el coste energético total entre 3G y WLAN. 4.3.4 Consumo energético de cada uno de los componentes Utilizando las mediciones detalladas en experimentos previos, en conjunción con nuevas métricas (ver Appendix B Study of Symmetric and Hash algorithms del Anexo C), en esta sección se calcula el coste energético individual de cada uno de los componentes que 41 Capítulo 4. Resultados Experimentales 4.3. Rendimiento y coste adicional intervienen en la creación y uso de una sesión SSL. Estos componentes pueden dividirse en 4 clases principales: algoritmos simétricos, asimétricos, hashing e interfaces de red. En secciones anteriores se ha estudiado el coste energético de algunas de ellas, pero no el coste de el algoritmo de encriptación (AES) ni del algoritmo HMAC-SHA1. Para llevar a cabo dicho estudio, se realizaron pequeños experimentos para medir sus diferentes consumos, así como el impacto energético que tienen a su vez las operaciones de lectura/escritura en la memoria del teléfono, los cuales parece que no se tomaron en cuenta en estudios previos [PRRJ06]. Los resultados para cada una de estos se muestran en la Tabla 4.6. Mientras que los valores obtenidos se encuentran en órdenes de magnitud similares a los reportados anteriormente, lo más importante a destacar son los resultados energéticos de las operaciones de lectura/escritura. Estos sugieren que las operaciones de clave simétrica y de hashing son pequeñas si se comparan con estas últimas: la operación de encriptación utilizando AES-128 y hashing con SHA1 consume únicamente 0.7 µJ/B y 0.1 µJ/B , mientras que las operaciones de lectura/escritura del chero sobre el que se trabaja requieren 1.3 µJ/B , claramente superior. Esta energía se ve a su vez incrementada si se realizan operaciones sobre datos alojados en la tarjeta de memoria externa del móvil 2.9 µJ/B (en este caso microSD). Se puede encontrar mucha más información sobre estos experimentos y sus resultados en el Appendix B Study of Symmetric and Hash algorithms del Anexo C. Operation Energy ( µJ/B ) Encrypt with AES-256 (r/w phone memory) 2.0 Decrypt with AES-256 (r/w phone memory) 2.0 AES-256 vs. AES-128 0.3 Hash with SHA1 (read phone memory) 0.7 Read only (phone memory) 0.6 Read & write (phone memory) 1.3 Read only (memory card) 1.2 Read & write (memory card) 2.9 Tabla 4.6: Coste energético de diferentes operaciones criptográcas Una vez que ya se han estudiado todos los componentes involucrados por separado, las Figuras 4.13 y 4.14 muestran los resultados con el uso de RSA y de DHE, respectivamente. Es fácil darse cuenta de que para transmisiones pequeñas de datos el consumo energético corresponde casi en su totalidad a algoritmos de clave pública, principalmente en la fase de handshake. Sin embargo, a medida que el tamaño aumenta, las operaciones simétricas reemplazan a los algoritmos asimétricos como agentes dominantes del total de energía utilizada por procesamiento criptográco. Asimismo, la contribución energética derivada de los algoritmos de hashing también se incrementa con el tamaño de datos, aunque se mantiene como un factor mínimo. Cabe mencionar que estos valores han sido obtenidos utilizando la interfaz de red WLAN. Para el caso de 3G no se llevaron a cabo experimentos en la realización del proyecto, aunque sí fueron analizados en la redacción del articulo (ver Anexo B), armando que el coste energético asociado a las operaciones criptográcas es mucho menor si se compara con el coste asociado a la interfaz de red. 42 Capítulo 4. Resultados Experimentales 4.3. Rendimiento y coste adicional Figura 4.13: Estudio individual del coste energético de los distintos componentes empleados en SSL para el caso RSA Figura 4.14: Estudio individual del coste energético de los distintos componentes empleados en SSL para el caso DHE 43 Capítulo 5. Conclusiones En este Capítulo se presentan las conclusiones generales del trabajo desarrollado junto con la valoración personal y una posibles vía de investigación futura para continuar con el estudio. 5.1 Conclusiones a nivel técnico En este trabajo se ha presentado un estudio de medición del consumo de diferentes algoritmos criptográcos y de protocolos de seguridad, centrándose en el protocolo Secure Socket Layer (SSL). Para su estudio, se ha presentado una conguración consistente en un cliente móvil ejecutándose en un terminal móvil Nokia N95 y una aplicación servidor gobernada por un ordenador portátil. Además se ha realizado un completo estudio de los diferentes servicios remotos más utilizados en la actualidad, como son Google o Facebook, obteniéndose conclusiones signicativas en los diversos aspectos analizados y observándose que el consumo energético en la fase de handshake varía considerablemente entre los diferentes servicios. Mientras que en la especicación de HTTP/1.1 se menciona que un cliente no debería de mantener más de 2 conexiones con cualquier servidor o proxy  [FGM + 99], los navegadores de hoy en día constantemente rompen esta parte de la especicación y establecen muchas más conexiones [DRC + 10]. Esto supone un impacto signicativo en el consumo adicional de energía en el caso de los clientes móviles, especialmente cuando se utiliza SSL y el servidor al que se desea acceder no soporta la reanudación de sesión. Sorprendentemente, los servidores de Facebook, por ejemplo, son uno de esos casos. Existen otras oportunidades para la optimización, especialmente para transferencias pequeñas de datos donde la fase de handshake juega un papel importante. Esta pasa por reducir el tamaño del certicado del servidor y evitar el uso de Die-Hellman en favor de RSA, a menos que sea absolutamente necesario. De cualquier otro modo, reducir, por ejemplo, la longitud de la clave pública del servidor tiene un impacto pequeño. Quizá el factor más importante a tener en cuenta, contrariamente a investigaciones previas realizadas [PRRJ06, SGM09], es que los resultados obtenidos en este estudio revelan que una vez el tamaño de los datos supera los 500 KB, el coste adicional comienza a ser mucho menos importante independientemente del uso de WLAN o 3G como interfaz de red. Además, el coste adicional que supone la encriptación, la protección de la integridad o los accesos de lectura/escritura en el protocolo de registro es prácticamente insignicante. 45 Bibliografía [Lab93] RSA Laboratories. PKCS #6: Extended-certicate syntax standard. http://www.rsa.com/rsalabs/node.asp?id=2128 - Último acceso: 2 Noviembre 2010, 1993. [Ope10] OpenSSL project , 2010. Disponible en http://www.openssl.org - Ultimo acceso: 2 Noviembre 2010. [oST01] National Institute of Standards and Technology. Specication for the ADVANCED ENCRYPTION STANDARD (AES) , 2001. Available at http://csrc.nist.gov/publications/ps/ps197/ps-197.pdf. [oST06] National Institute of Standards and Technology. FIPS PUB 186-3: Digital signature standard (DSS) , 2006. Available at http://csrc.nist.gov/publications/drafts/ps_186-3/Draft-FIPS-186-3%20_- March2006. pdf. [PP06] Charles P. Peeger and Shari Lawrence Peeger. Security in Computing (4th Edition) . Prentice Hall PTR, Upper Saddle River, NJ, USA, 2006. [PRRJ06] Nachiketh R. Potlapally, Srivaths Ravi, Anand Raghunathan, and Niraj K. Jha. A study of the energy consumption characteristics of cryptographic algorithms and security protocols. IEEE Transactions on Mobile Computing , 5(2):128143, 2006. [Riv92] R. Rivest. The md5 message-digest algorithm, 1992. [RSA78] R.L. Rivest, A. Shamir, and L. Adleman. A method for obtaining digital signatures and public-key cryptosystems. Communications of the ACM , 21:120126, 1978. [SGM09] Youngsang Shin, Minaxi Gupta, and Steven Myers. A study of the performance of SSL on PDAs. In INFOCOM'09: Proceedings of the 28th IEEE international conference on Computer Communications Workshops , pages 1 6, Piscataway, NJ, USA, 2009. IEEE Press. [WGE + ] A.S. Wander, N. Gura, H. Eberle, V. Gupta, and S.C. Shantz. Energy analysis of public-key cryptography for wireless sensor networks. In Proceedings of PerCom 2005 . [WH76] Die Whiteld and Martin E. Hellman. New directions in cryptography, 1976. [XSK + ] Yu Xiao, Petri Savolainen, Arto Karppanen, Matti Siekkinen, and Antti Ylä- Jääski. Practical power modeling of data transmission over 802.11g for wireless applications. In Proceedings of e-Energy 2010 . 52 Anexos 53 Anexo A. El protocolo de Handshake en SSL Como se ha comentado en la Sección 2.3, este protocolo es el encargado de la negociación de los sistemas criptográcos a utilizar entre los 2 pares que quieren establecer el canal seguro SSL. Con el n de permitir a los usuarios seleccionar el nivel de seguridad que mejor se ajuste a sus necesidades, SSL agrupa los diferentes sistemas criptográcos en suites de cifrado. Cada una de estas suites especica el algoritmo de autenticación de los pares, el de intercambio de clave, el de encriptación de los datos y el de resumen del mensaje o message digest . En la Tabla A.1 se muestran 2 ejemplos de suites criptográcas. Existen diferentes algoritmos criptográcos a utilizar para codicar los datos, para calcular la MAC o autenticar los pares involucrados. Algunos de ellos proporcionan niveles altos de seguridad, pero tiene altos costes computacionales. Otros son menos seguros, pero tienen mejores rendimientos generales sin comprometer la seguridad del sistema. Suite criptográca Autenticación Intercambio clave Encriptación Digest RSA_AES_256_SHA RSA RSA AES-256-CBC SHA1 DHE_RSA_AES_256_SHA RSA DHE AES-256-CBC SHA1 Tabla A.1: Ejemplos de suites criptográcas Cuando se establece una conexión SSL, el cliente y el servidor intercambian información acerca de qué suites soportan y están dispuestos a utilizar. El cliente envía la lista de suites disponibles, ordenadas normalmente en orden de seguridad decreciente. El servidor elige la más adecuada entre las compartidas. Si ambos pares no comparten ninguna, la comunicación SSL no es posible y el servidor cierra el intento de conexión. Con el n de explicar cómo se lleva a cabo un handshake real, aquí se presenta un resumen de los mensajes intercambiados entre el cliente y el servidor. El método más usado y conocido de handshake es mediante el empleo de RSA como protocolo de intercambio de clave y autenticando únicamente al servidor, y no al cliente. La Figura A.1 muestra los mensajes y la información intercambiada. El mensaje entre corchetes es usado únicamente por el protocolo de acuerdo de clave Die-Hellman. 55 Anexo A. El protocolo de Handshake en SSL Figura A.1: Pasos e información intercambiada en la fase de handshake 56 Anexo A. El protocolo de Handshake en SSL La secuencia de acciones que ocurre en el intercambio de mensajes durante la fase de handshake se resume a continuación: 1. La conexión comienza con el cliente enviado un comando ClientHello , el cual contiene: la versión SSL más alta soportada, las suites criptográcas que soporta, métodos de compresión disponibles, ID de la sesión y datos aleatorios para su uso en el proceso de generación de la clave secreta. 2. El servidor responde con un comando ServerHello , que incluye, la versión SSL que se utilizará para la comunicación, la suite criptográca seleccionada por el servidor entre las ofrecidas por el cliente, el método de compresión elegido por el servidor, el ID de la sesión establecido por el servidor y datos aleatorios para su uso en el proceso de generación de la clave secreta. 3. El servidor envía el comando Certificate que incluye el certicado del servidor con la clave pública del mismo incluida. De manera opcional, también incluye la cadena de certicados adicionales comenzando con el de la autoridad certicadora (CA). 4. El servidor envía el comando ServerHelloDone , indicando que al cliente que ha terminado con esta fase del handshake. 5. El cliente envía el mensaje ClientKeyExchange , que contiene el pre_master_secret creado por el cliente y encriptado utilizando la clave pública del servidor. Ambas partes generan la clave secreta de encriptación utilizando dicho pre_master_secret y los datos aleatorios incluidos en los mensajes ClientHello y ServerHello . 6. El cliente envía el comando ChangeCipherSpec , el cual indica que los siguientes mensajes enviados por el cliente durante la sesión serán encriptados utilizando los sistemas criptográcos y claves acordadas previamente. 7. El cliente envía su último mensaje en el protocolo de handshake, Finished , incluyendo un digest de todos los mensajes previos enviados al servidor. Este comando es enviado para asegurar que ninguno de los mensajes previos sin encriptar han sido modicados durante su transmisión. 8. El servidor envía el comando ChangeCipherSpec , el cual indica que los siguientes mensajes enviados por el servidor durante la sesión serán encriptados utilizando los sistemas criptográcos y claves acordadas previamente. 9. El servidor envía su último mensaje en el protocolo de handshake, Finished , incluyendo un digest de todos los mensajes previos enviados a el cliente. Este comando tiene el mismo propósito que el mismo Finished enviado por el cliente. Estas 9 acciones previas muestran los pasos exactos que ocurren en un SSL handshake utilizando RSA como protocolo de autenticación y como intercambio de clave. Aunque RSA es el algoritmo de clave pública más utilizado en el mercado, SSL soporta suites criptográcas basadas en otros algoritmos como Die-Hellman (DH). La idea de estos 57 Anexo A. El protocolo de Handshake en SSL algoritmos es evitar el uso de sistemas patentados y protegidos, en particular RSA. Pero desde el año 2000, cuando la patente sobre este último algoritmo expiró, esta motivación ya no es válida, aunque el soporte para DH está todavía disponible. Al contrario que RSA, que puede ser usado como algoritmo de intercambio de clave o de rma, DH sólo puede ser utilizado como algoritmo de acuerdo de clave. Como consecuencia directa, y para conseguir una solución completa, Die-Hellman y RSA (u otro protocolo como DSS) tienen que ser usados en conjunción. La solución más extendida es el uso de claves efímeras en Die-Hellman o DHE. El servidor genera una clave DHE temporal y la rma utilizando la clave RSA, transmitiendo la clave rmada en el mensaje ServerKeyExchange . En ese caso, el cliente utilizará esa clave DHE para el acuerdo de clave. Es posible utilizar una clave DH de larga duración. En ese caso, el servidor tendrá un certicado rmado con dicha clave. El uso de DH como protocolo de acuerdo de clave únicamente añade un mensaje en el lado del servidor, pero también añade un conjunto de operaciones asimétricas que reduce el rendimiento e incrementa el coste energético. La parte más costosa de un SSL handshake es el establecimiento de el pre_master_- secret , el cual requiere criptografía de clave pública. SSL facilita la reanudación de una sesión previamente establecida. El uso de dicha reanudación conlleva la utilización de una identicación o ID de sesión entre un cliente y un servidor y por tanto el handshake únicamente se lleva a cabo en 5 pasos: 1, 2, 7, 8 y 9 de la Figura A.1. Esto signica que no es necesario negociar de nuevo el master_secret porque la sesión ya había sido creada previamente por los 2 pares. Este hecho evita realizar de nuevo las operaciones computacionalmente costosas que requiere los algoritmos de clave pública, ahorrando tiempo y reduciendo enormemente el consumo energético. 58 Anexo B. Artículo: TLS and Energy Consumption On a Mobile Device: A Measurement Study En este anexo se presenta el artículo de investigación con título TLS and Energy Consumption On a Mobile Device: A Measurement Study enviado al Communications QoS, Reliability and Modeling Symposium enmarcado en el congreso IEEE International Conference on Communications ICC2011 1 que se celebrará en Kyoto (Japón) del 5 al 9 de junio de 2011. Este artículo fue enviado a dicho congreso en septiembre de 2010 y está pendiente de aprobación en enero de 2011. 1 http://www.ieee-icc.org/ - Último acceso: 3 noviembre 2010 59 TLS and Energy Consumption On a Mobile Device: A Measurement Study Pedro Miranda, Matti Siekkinen Aalto University, School of Science and Technology Espoo, Finland Email: [email protected] Heikki Waris Nokia Research Center Helsinki, Finland Email: [email protected] Abstract— We report results from a measurement study on the role of the most popular end-to-end security protocol Transport Layer Security (TLS) in the energy consumption of a mobile device. We measured energy consumed by TLS transactions between a Nokia N95 and several popular Web services over WLAN and 3G network interfaces. Our detailed analysis corroborates some earlier results but also reveals, contrary to earlier studies, that the transmission and I/O energy, both in the TLS handshake and the record protocol, far exceed the required computational energy by the actual cryptograhic algorithms and that with transactions larger than 500KB, the energy required to transmit the actual data clearly overweighs the TLS energy overhead. In addition, we note that the energy consumption varies remarkably between measured services. I. INTRODUCTION In the last few years, mobile devices have evolved significantly in terms of power, throughput, and in terms of new functionalities, but they are still severely constrained by limited battery life-time. Secure communications are achieved by employing security protocols, which are based on cryptographic algorithms. Executing certain cryptographic algoritms requires rather intesive computations. Therefore, their energy consumption on these battery powered devices is naturally a concern. In this paper, we study the energy consumption of Transport Layer Security (TLS), which is used to establish a secure communication channel between two end hosts and exchange data over that channel. TLS is a transport level protocol that uses asymmetric and symmetric encryption algorithms and hash algorithms in order to provide data secrecy, authentication of the communication parties, and data integrity for applications in a transparent manner. We use a Symbian mobile device (Nokia N95) to establish TLS connections to different web services, such as electronic email or social networks, over both WLAN and 3G network interfaces and measure the energy consumption. TLS comprises two phases. First, a security association is created through a handshake protocol after which the actual data is transferred over an encrypted and integrity protected channel. We perform detailed analysis of the different steps involved in TLS transactions, compute the amount of energy overhead in a TLS transaction, and explain the major causes that determine this overhead. Energy consumption of different cryptographic algorithms as well as the performance of TLS on PDAs and in computers have been studied earlier in, e.g. [1]–[3]. Among other things, they show that public key cryptography has the highest energy consumption, while hash algorithms have a little impact in the battery life-time. The key size chosen has a dramatic impact to the energy consumed in public key cryptography but not for symmetric algorithms. While some of our results corroborate those presented in these earlier studies, some of our conclusions concerning the overall TLS overhead differ significantly. In addition, we study real on-line services in a comparative manner and conduct experiments over both WLAN and 3G interfaces. Furthermore, we drill down into the individual steps involved in a transaction in order to pinpoint reasons for observed differences. Our main findings are the following: •The amount of energy consumed during the handshake phase differs a lot between different services. The main reasons turn out to be the length of the server certificate and RTT which are both related to transmission energy. Public key length seems to have only a marginal impact. •Transactions over 3G access consume several times more energy than those over WLAN access. Contrary to earlier reported results, we found that the energy overhead of the TLS record protocol (encryption and hashing) is rather insignificant for WLAN and completely insignificant for 3G. •For very small transactions (less than 10KB), the TLS overhead accounts for more than 60% (and up to 95% with DH) of the total energy consumed for both access types, while for transactions larger than 500KB the overhead is rather small if RSA is used in the handshake. II. TLS AND ENERGY CONSUMPTION A. TLS overview TLS [4] is a protocol that provides confidentiality, authentication, and data integrity over a channel between two machines. It is divided in two parts: Handshake protocol and Record protocol. The Handshake protocol allows the client and the server to authenticate each other and to negotiate the cryptographic algorithms and encryption keys needed to secure the channel. TLS packs the different cryptographic algorithms into cipher suites each of which specifies the server authentication algorithm, the key exchange algorithm, the bulk encryption algorithm and the message digest algorithm. Figure 1 shows the exchanged messages during a Aalto University School of Science and Technology Faculty of Information and Natural Sciences Degree programme of Computer Science and Engineering Pedro Miranda Energy consumption of cryptographic algorithms and security protocols in Symbian mobile devices Final Project Espoo, May 2010 Supervisor: Professor Antti Ylä-Jääski, Aalto University Instructors: Matti Siekkinen, Aalto University Heikki Waris, Nokia Corporation 1 Aalto University School of Science and Technology ABSTRACT OF Faculty of Information and Natural Sciences FINAL PROJECT Degree Programme of Computer Science and Engineering Author: Pedro Miranda Title of nal project: Energy consumption of cryptographic algorithms and security protocols in Symbian mobile devices Date: May 2010 Pages: 15 + 96 Professorship: Data Communications Software Code: T-110 Supervisor: Professor Antti Ylä-Jääski Instructors: Matti Siekkinen, Heikki Waris Mobile communications have redened the way people communicate. Electronic devices, whereby these communications are established, have evolved signicantly in terms of power, throughput and new functionalities, but they are still constrained by the battery life-time. This study focuses on this constraint and studies how it is impacted by the use of cryptography and security protocols, paying attention at the most popular transport-layer security protocol: the Secure Socket Layer (SSL). For the study, a experimental setup has been developed, by using a Nokia N95 Symbian mobile device, a PC running Linux, the Nokia Energy Proler for the energy measurements and the OpenSSL implementation of the SSL protocol for the coding of the client and server test applications. Based on the results, the use of security generates an overhead involving a high impact in energy consumption for small transaction sizes, that decreases as the size is increased. Keywords: AES, SHA, SSL, TLS, Die-Hellman, RSA, Symbian OS cryptographic algorithms, security protocols, OpenSSL energy analysis, battery-constrained devices Language: English i This work was supported by TEKES as part of the Future Internet programme of TIVIT (Finnish Strategic Centre for Science, Technology and Innovation in the eld of ICT). iii Acknowledgements First, I would like to thank my supervisor Professor Antti Ylä-Jääski for giving me the opportunity to work on this project and for his support. Special thanks to my instructors Matti Siekkinen and Heikki Waris for their continuous guidance and support during my research and project development. Also to Sampo Sovio and Jussi Ruutu from Nokia Corporation, for their supervision and guidelines all along these months. To my parents Pedro and Carmen and my sister Pilar because, even in the distance, they were there when I needed them. Last but not least, to all my friends and special people I have met during my almost two years in Helsinki. Thank you for the great moments. In Espoo, May 2010 Pedro Miranda iv Abbreviations and Acronyms 3G 3rd Generation 3GPP 3rd Generation Partnership Project AES Advanced Encryption Standard API Application Programming Interface CFB Cipher Feedback CBC Cipher Block Chaining CSV Comma Separated Values CTR Cipher Block Counter mode DES Data Encryption Standard DSS Digital Signature Standard ECB Electronic Code Book DH Die-Hellman HMAC Hash-based Message Authentication Code HSPA High-Speed Packet Access HSDPA High-Speed Downlink Packet Access IEEE Institute of Electrical and Electronics Engineers IETF Internet Engineering Task Force LAN Local Area Network MAC Message Authentication Code MD5 Message Digest 5 NEP Nokia Energy Proler NSA National Security Agency NIST National Institute of Standards and Technology v OFB Output Feedback PNG Portable Network Graphics RC4 Rivest Cipher 4 RSA Rivest Shamir Adelman SHA Secure Hash Algorithm SSL Secure Socket Layer SVG Scalable Vector Graphics TCP Transmission Control Protocol TLS Transport Layer Security UEA2 UMTS Encryption Algorithm Suite 2 UIA2 UMTS Integrity Algorithm Suite 2 UMTS Universal Mobile Telecommunication System WLAN Wireless Local Area Network vi Contents Abbreviations and Acronyms v 1 Introduction 1 1.1 Motivation............................. 1 1.2 Problem statement and objectives . . . . . . . . . . . . . . . . 2 1.3 Organization of this work . . . . . . . . . . . . . . . . . . . . 3 2 Security and energy background 4 2.1 Computer security and security objectives . . . . . . . . . . . 4 2.2 Security Terminology . . . . . . . . . . . . . . . . . . . . . . . 6 2.3 Symmetric Cryptography . . . . . . . . . . . . . . . . . . . . . 7 2.3.1 Blockciphers ....................... 7 2.3.2 Stream Ciphers . . . . . . . . . . . . . . . . . . . . . . 8 2.4 Message Digest and Message Authentication Codes . . . . . . 8 2.4.1 SHA............................ 9 2.5 Public Key Cryptography . . . . . . . . . . . . . . . . . . . . 9 2.5.1 Key establishment protocol . . . . . . . . . . . . . . . 10 2.5.2 Digital signatures . . . . . . . . . . . . . . . . . . . . . 10 2.5.3 RSA............................ 11 2.5.4 Die-Hellman . . . . . . . . . . . . . . . . . . . . . . . 12 2.6 EnergyAnalysis.......................... 13 2.6.1 Energy Consumption of Network Interfaces . . . . . . . 13 2.6.2 Energy Consumption of Cryptographic Algorithms . . 16 vii 5.5 Handshake steps Execution time using DHE with WLAN . . . 63 5.6 Handshake steps Execution time using RSA with 3G . . . . . 64 5.7 Handshake steps Execution time using DHE with 3G . . . . . 66 5.8 Comparing Energy Consumption using WLAN and 3G . . . . 67 5.9 Comparing Handshake steps Execution time using RSA for WLANand3G .......................... 67 5.10 Comparing Handshake steps Execution time using DHE for WLANand3G .......................... 68 5.11 Percentage of communication data overhead of SSL usage for dierent transaction sizes . . . . . . . . . . . . . . . . . . . . . 70 5.12 Comparing the throughput of using SSL and non secure connection............................... 72 5.13 Energy overhead of SSL usage using WLAN . . . . . . . . . . 74 5.14 Energy overhead of SSL usage using 3G . . . . . . . . . . . . . 74 5.15 Comparing energy consumption overhead using WLAN or 3G 75 A.1 Energy consumption and CPU usage of UEA2 and UIA2 with FAST_SNOW 3G Disabled . . . . . . . . . . . . . . . . . . . 87 A.2 Energy consumption and CPU usage of UEA2 and UIA2 with FAST_SNOW 3G Enabled . . . . . . . . . . . . . . . . . . . . 88 B.1 Energy consumption of various algorithms with dierent parameters for a le of size 1.1 Mbytes stored in phone memory. 90 B.2 The result from encryption operation of a le read & stored at the memory location and operation performed in steps as read, encrypt and added write cost. . . . . . . . . . . . . . . . 91 xiv Chapter 1 Introduction This chapter includes a motivation about the study of energy consumption of security protocols in battery-constrained devices as well as the objectives of this nal project work. Finally, an explanation about the organization of this report is presented. 1.1 Motivation In the last few years, mobile communications have redened the way people communicate. Electronic devices, whereby these communications are established, have evolved signicantly in terms of power, throughput, and above all in new functionalities, but they are still constrained by the battery life-time. This issue has been always an important issue in research, and although this life-time has evolved considerably, the increase has not followed the same rapid evolution as the device processing capabilities. While the processor performance doubles every 18 months according to Moore's Law , it is claimed that the battery capacity has only increased by 80% in the last 10 years [Fit07]. This improved performance and the arrival of Internet to these devices have made the communication through dierent channels possible, searching for information or performing purchases, all of these in a secure and condential way. Secure communications using wired or wireless networks are achieved by employing security protocols, which are based on cryptography algorithms. These algorithms are selected based on the security objectives needed in the security protocol to use. They include asymmetric and symmetric encryption 1 CHAPTER 1. INTRODUCTION 2 algorithms, which are used to provide authentication and secrecy, as well as message digest or hash algorithms, used to provide message integrity. The use of security protocols not only aects connections throughput, but also represents a strong impact in the energy consumption in these battery powered devices. Thus, one of the foremost challenges is to achieve a balanced security performance/energy consumption in order to obtain a good throughput using the minimum amount of battery. In this context, Nokia corporation, together with Aalto University School of Science and Technology (Helsinki, Finland), collaborate in a research project in order to address the energy consumption of dierent security protocols and cryptographic algorithms running on Symbian, the leader mobile devices platform. 1.2 Problem statement and objectives The main objective of the study, is to perform an exhaustive analysis of the energy impact involved in the creation of a secure connection using the security protocol Secure Sockets Layer(SSL), used to establish secure communication between electronic devices. This protocol, uses dierent cryptographic algorithms in order to protect the information exchanged between dierent connected peers, providing not only data secrecy but also legitimacy and integrity. Furthermore, the use of this protocol provides the most common security services to secure network communications in such a way that the need for cryptography knowledge is minimized. Thus, the objective is to study the most used cryptosystems and analyze their consumption in dierent scenarios. In order to complete all the needs, the process will begin with the development of a client application in a Symbian mobile device, capable of understanding and performing secure SSL connections with dierent online services, such as electronic email or social networks, and in that way, being able to measure the energy consumption dissipated in the establishment of that connection. In addition, the development includes also a server capable of managing dierent secure connections with the mobile client, in order to model the dierent scenarios to study: Sending/receiving data, client authentication, resume a secure session previously used and the selection of the cryptographic suite to use. CHAPTER 1. INTRODUCTION 3 For the establishment of the communications with the dierent services and the SSL server, WLAN and 3G interfaces will be used in order to compare also their dierent energy consumption and the impact due to the dierent communication nature. 1.3 Organization of this work This nal project work is divided into the following chapters: • Chapter 1 - Introduction provides an overview to the problematic studied and the objectives of the project. • Chapter 2 - Security and Energy Background includes an introduction to cryptography, the goals, and the dierent techniques used in the eld, with an eye towards its use in SSL. It also contains an introduction to energy consumption involved in network interfaces and cryptographic protocols. • Chapter 3 - SSL and TLS is a guide of the history of SSL/TLS and the security features that it provides. An entire SSL/TLS connection is detailed from start to nish. • Chapter 4 - Designed Setup of Experiments with a description of all the used technologies to create the experimentation setup, the analysis of the requirement and the followed measuring methodology. • Chapter 5 - Analysis of Measurements containing the dierent conclusions obtained for the dierent test scenarios. • Chapter 6 - Conclusions includes the overall conclusions of the research, together with the future work. At the end of the report, dierent appendices are included: • Appendix A - Study of Snow 3G shows the result of an experimental study about the energy consumption and performance of the Snow3G algorithm. • Appendix B - Study of Symmetric and Hash algorithms analyzes the energy consumption of symmetric algorithms like AES, and dierent uses of Hash algorithms and message digest like HMAC-SHA1 or the SHA2 family. Chapter 2 Security and energy background This chapter is intended to provide a basic approach to computer security and cryptography along with a little introduction to the most important network interfaces in mobile devices, WLAN and 3G. It starts with an introduction to what computer security is and the goals that are behind security. It continues giving a denition of the dierent algorithms and protocols involved in cryptography: symmetric encryption, digest algorithms, message authentication codes and public key cryptography, as well as the dierent most used solutions in each case. Finally, an introduction to energy consumption of the dierent network interfaces is included along with the energy impact of dierent cryptographic algorithms. 2.1 Computer security and security objectives The term security is used in many ways in our daily lives. A security system protects our house from burglars and alerts the police, a nancial security involves a set of investments that are adequately funded, or when physical security is mentioned in order to protect people from potential harm. As all these terms have a specic meaning in each context, so does the term computer security. The purpose of computer security is to devise ways to prevent the weaknesses from being exploited [PP06] while allowing the information to remain available and productive. The words security objectives are usually associated to the security services or functionality required in a system or network in order to protect sensitive data or the identity of the dierent parties involved. There are 4 main 4 CHAPTER 2. SECURITY AND ENERGY BACKGROUND 5 objectives including: • Condentiality ensures the data is kept secret from unintended listeners and can only be accessed by authorized parties. Usually these listeners are eavesdroppers with malicious intended purposes. Con- dentiality is often called privacy or secrecy • Availability means that the information is accessible to authorized parties at appropriate times. For this reason, availability is sometimes known by its opposite, denial of service . • Integrity protects data from being modied by unauthorized parties and only in authorized ways. • Nonrepudiation is the concept that proves the origin of the information. When nonrepudiation can be provided, the information is intended to be genuine. Security in computing addresses these 4 goals. One of the challenges in building a secure system is nding the right balance among these goals, which often conict. But balance is not all. In fact, these four characteristics can be independent, can overlap (as shown in Figure 2.1) and can even be mutually exclusive. For example, ensuring a strong condentiality can aect severely the availability. Figure 2.1: Relationship between condentiality, integrity, availability and non repudiation CHAPTER 2. SECURITY AND ENERGY BACKGROUND 6 2.2 Security Terminology The original form of a message is called plaintext, and the encrypted form is known as ciphertext. This relation is shown in Figure 2.2. A plaintext message P is denoted as a sequence of characters P=hp1, p2, . . . , pni . In the same way, the ciphertext is written as C=hc1, c2, . . . , cmi . Encryption is the process of encoding a message so that its meaning is not obvious. Decryption is the reverse process, transforming and decrypting a previously encrypted message back into its original form. A system capable of encrypting and decrypting is called a cryptosystem . Figure 2.2: Relation between plaintext, ciphertext, encryption and decryption In order to describe the transformations between plaintext and ciphertext ,a formal notation like C=E(P) and P=D(C) can be used. C represents the ciphertext, E is the encryption rule, P is the plaintext, and D is the decryption rule. The main goal of a cryptosystem is being able to convert the message to protect it from an intruder, but being also able to get the original message back, so that the receiver can read it properly. Cryptosystems involve a set of rules in order to know the encryption and decryption method or rules. These rules, called algorithms, use a device called a key, denoted by K, so the resulting ciphertext depends on three factors: The original plaintext, the algorithm and the key used ( C=E(K, P) ). Sometimes encryption and decryption keys are the same ( P=D(K, E(K, P)) ). This method is called Symmetric encryption because encryption and decryption are the same processes. At other times, encryption and decryption are dierent operations. Then, a decryption key, KD , inverts the encryption of key KE so that the process can be represented like P=D(KD, E(KE, P)) . Encryption in this form is called Asymmetric encryption because converting C back to P involves a series of steps and a key that are dierent from the steps and key of E. A better approach in this issue is done in Sections 2.3 and 2.5. CHAPTER 2. SECURITY AND ENERGY BACKGROUND 7 2.3 Symmetric Cryptography As mentioned before, Symmetric Cryptography uses the same process to encrypt and decrypt, using the same secret-key as input. There are two major variants of symmetric encryption: Block ciphers and Stream ciphers. 2.3.1 Block ciphers A block cipher is a type of symmetric-key encryption algorithm that transforms a xed-length block of plaintext (unencrypted text) data into a block of ciphertext (encrypted text) data of the same length [Lab93]. The transformation function depends on an encryption key provided by the user, while the xed length is called the block size, usually containing 64 bits. In order to encrypt a message of an arbitrary length, dierent modes of operations for the block cipher can be used. These modes must be at least as secure and as ecient as the underlying cipher. The most used standard mode of operation is Cipher Block Chaining (CBC) but there also exist others such as Electronic Code Book (RCB), Cipher Feedback (CFB), Output Feedback (OFB) or CTR mode (CM) [Dwo01]. Block ciphers are a more conservative solution than stream ciphers because they are better studied. Examples of block ciphers are DES and AES. AES In 1997, NIST put out a call for submission for an Advanced Encryption Standard (AES) [oST01] in order to substitute its predecessor, the Data Encryption Standard (DES) [oST99]. The 5 nal algorithms presented to NIST were MARS [IBM99], Serpent [ABK99], Twosh [Sch99], RC6 [RRSY99] and the winner, Rijndael [DR99]. AES is a strong and fast algorithm that uses as primary operations substitution, transportation, shift, exclusive OR, and additional operations. It supports 128, 192 and 256 bits key-length, using 10, 12 or 14 rounds respectively. Each round consists of four steps: Byte substitution, Shift row, Mix column and Add subkey. The security level depends on the number of rounds. Higher security is provided with 14 rounds. For more details about the implementation and how it works, please refer to [Sch95]. CHAPTER 2. SECURITY AND ENERGY BACKGROUND 8 2.3.2 Stream Ciphers Stream ciphers work with a function that generates a stream of data one byte at a time. The generated data is called keystream . This function has as input the encryption key, which controls exactly what keystream is generated. This keystream is usually XORed with a byte of plaintext to get a byte of ciphertext. Stream ciphers can be highly secured if they are used properly, but they are vulnerable to attacks if certain precautions are not followed. The same key cannot be used twice and a valid encryption should never be used to provide authentication. Along with the previous precautions, the use of a strong MAC (see Section 2.4) to generate the encryption keys is mandatory. Stream ciphers tend to be faster than block ciphers. One of the most used stream cipher is RC4. RC4 RC4 [Kau99] was designed by Ron Rivest in 1994 and it is the most used stream cipher algorithm. RC4 is a variable-key-length cipher, with a key that can be anywhere between 8 and 2048 bits long. This key is expanded into an internal state table of constant size, so no matter the key length, the overall performance is really good. The normal use of the algorithm is with a 128 bits key length. 2.4 Message Digest and Message Authentication Codes A Message digest (also known as Hash algorithms) is essentially a procedure that takes an arbitrary data length and generates as output a xed-size checksum, called hash value. The same input will always produce the same output. Thus, an accidental or intentional change to the data will change the hash value. Message digest functions have two important properties: • Irreversibility : It should be practically infeasible to compute a message given its digest. CHAPTER 2. SECURITY AND ENERGY BACKGROUND 9 • Collision-resistance : Given digest D , it should be dicult to produce two messages M and M0 such they have the same digest D . The primary use of a message digest is the computation of a digital signature (see Section 2.5.2). The most used message digest algorithms in digital signature computing are Message Digest 5 (MD5) [Riv92] and Secure Hash Algorithm 1 (SHA-1)(see Subsection 2.4.1). Apart from the use for digital signature, message digests are also utilized in Message authentication code (MAC), which are sort of like a digest algorithm, but they also incorporate a key into the computation. The creation of the MAC depends on both the key and the content of the message being MACed. The most used MAC algorithm is HMAC [KBC97], which describes how to create a MAC with security properties based on any digest algorithm that presents a reasonable set of cryptographic properties. The most used applications are HMAC-SHA-1 [KBC97] or HMAC-MD5 [CG97]. 2.4.1 SHA Secure Hash Algorithm is a set of cryptographic hash functions designed by the National Security Agency (NSA) and published by the National Institute of Standards and Technology (NIST) as a Federal Information Processing Standard (FIST). SHA-1 produces a 160 bits (20 bytes) message digest. SHA-1 has been examined closely since its release and it became a standard for SHA hash functions. It is the most used algorithm in several security applications and protocols. Nevertheless, in 2005, some security aws were discovered 1 , suggesting that a stronger algorithm might be needed in the future. The SHA-2(SHA-224, SHA-256, SHA-384, and SHA-512) family has been released with higher security, but as SHA-2 family is also similar to SHA-1, a new standard SHA-3 is being developed and will be released in 2012. 2.5 Public Key Cryptography Public Key Cryptography involves the use of asymmetric algorithms instead of symmetric algorithms. These algorithms are used to create a pair of related keys: one secret private key and one published public key. A user can 1 http://www.schneier.com/blog/archives/2005/02/cryptanalysis_o.html - Last accessed: April 2010 CHAPTER 2. SECURITY AND ENERGY BACKGROUND 16 • The transfer energy is proportional to the size of the data transferred and the transmit power level. This transmission energy using WLAN is substantially smaller than for 3G, specially for larger transfer sizes. With increasing data sizes, the eciency increases dramatically. On the other hand, for smaller transactions, WLAN becomes inecient compared to 3G. • WLAN is more energy ecient than 3G once it is associated to an access point. • The maintenance energy to keep the 3G interface up is about 1-2 Joules per minute while for the WLAN is about 3-3.5 Joules per minute. All these conclusions will serve to explain better the results obtained in Section 5 where the 3G and WLAN energy consumptions are compared for the studied cases. 2.6.2 Energy Consumption of Cryptographic Algorithms As commented before, the arrival of the Internet to handheld devices has made mobile communications possible, allowing users to search for information, buy things or share information in a secure and condential way. This privacy is achieved thanks to the use of cryptographic algorithms and security protocols, which have an important impact in the battery life-time, increasing the number of calculations in the CPU and also augmenting the number of exchanged messages and their length. While previous works [PRRJ06], [SGM09], [APS99], analyze the energy consumption of dierent cryptographic algorithms as well as the performance of SSL and TLS (explained in Section 3) on PDAs and in computers, they do not perform a complete study analyzing both energy consumption and performance. In this work, both are studied, addressing the high energy consumption steps with time execution increases. These previous studies show dierent observations, in addition to dierent suggested improvements. Here just a few of them are mentioned: • Public key cryptography has the highest energy consumption, while hash algorithms have a little impact in the battery life-time. • The key size chosen aects dramatically to energy in public key cryptography, but not in such a way for symmetric algorithms. CHAPTER 2. SECURITY AND ENERGY BACKGROUND 17 • The use of Die-Hellman as a key agreement protocol during the handshake stage in SSL improves security, but it also increases dramatically the energy consumption and decreases the performance, compared with other key exchange protocol like RSA. This higher energy consumption is due to the extra CPU computations needed, in addition to the necessity to maintain the network interface up for a longer time. • The use of SSL as a security protocol aects signicantly the overall performance of the connection, but this can be gently eased choosing the most suitable algorithms depending on the security requirements of the user and the hardware capabilities of the device. All of these observations will be conrmed in Chapter 5 and will also help to understand better the obtained results. Chapter 3 SSL and TLS This chapter is intended to introduce the reader with a brief introduction to SSL and TLS. It also denes the dierent protocols involved and also how a connection is established, including the dierent SSL handshakes. 3.1 SSL overview Secure Socket Layer is a protocol that provides a secure channel between two machines. The protocol was designed in order to protect data in transit and to identify the machines involved in the communication. Data is encrypted between the peers, but the data that one side writes is exactly what the other side reads. The secure channel also oers transparency, which means that it passes the data through unchanged. This property, allows to any protocol that runs over TCP to be run over SSL with minimal modications. Since the rst version of SSL, originally designed by Netscape in 1994, it has gone through a number of revisions beginning with version 1 (unreleased), going through SSLv2 [Cor94], SSLv3 [Cor96] and culminating in its adoption by the IETF as the Transport Layer Security (TLS) standard [DA99]. Once SSL and the dierent revisions have been introduced, from now on, all the references to SSL will refer to TLS as well. 3.2 The Secure Socket Layer protocol The primary goal of the SSL Protocol is to provide privacy and data integrity between two communicating applications in such a way that the need for 18 CHAPTER 3. SSL AND TLS 19 cryptography expertise is minimized. In order to provide a transparent and secure communication channel, the SSL protocol is placed in the protocol stack, just below the application layer and just above TCP layer (see Figure 3.1 for more details). Figure 3.1: SSL protocol structure The SSL protocol is divided in two layers: 1. The Record protocol provides secrecy and reliability of the transfered data. The Record Protocol is responsible for data transfer. 2. The Handshake protocol allows the client and the server to authenticate each other and to negotiate the cryptographic algorithms in addition of encryption keys needed in order to secure the channel. Both protocols are described in detail in Sections 3.3 and 3.4. 3.3 The Record Protocol As described before, the Record Protocol is responsible for the data transfer and the interpretation of the type of the received message. The protocol works by breaking up the data stream to be transmitted into a series of fragments, each of which is independently protected and transmitted. This behavior allows data to be transferred as soon as it is ready. Before any fragment can be transmitted, integrity protection has to be provided. A MAC is computed over the data and is then appended to the data fragment. The concatenated data is encrypted and a record header is attached and the whole packet is sent to the receiving peer. The job of the record header is to provide information that is necessary for the receiving CHAPTER 3. SSL AND TLS 20 implementation to interpret the record. In the header the following elements are included [Res01]: • Message length: allows the receiver to know how many bytes to read from the wire before it can process the message. • SSL version: to ensure each side agrees on the same version. • Content type: SSL supports 4 message content types including: 1. Application Data: all data sent and received by applications that use SSL is sent as this content type. 2. Alert: primarily used for signalling various types of errors. Most of them alert that something went wrong in the handshake, but some indicate errors related with decryption or authenticating records. Other uses are to signal that the connection is about to close. 3. Handshake messages: used to carry the dierent messages that are presented in the handshake protocol. 4. ChangeCipherSpec: this message has the special purpose to indicate a change in the encryption and authentication of records. This message is sent to indicate that all the data transferred from now on will be encrypted using the agreed cryptographic algorithms. While the Record Protocol is responsible for the data transfer, the Handshake Protocol is in charge of establishing SSL session states between communicating peers. In next section 3.4, the dierent purposes of the Handshake Protocol as well as the dierent operations modes are explained. 3.4 The Handshake Protocol The purpose of the Handshake protocol is threefold: 1. Client and server need to negotiate a set of cryptographic algorithms which will be used to protect the data. 2. They need to agree on the cryptographic keys to be used by those algorithms. 3. The handshake may optionally request authentication from the client side. CHAPTER 3. SSL AND TLS 21 In order to allow the users to select the level of security that suits best their needs, SSL packs the dierent cryptographic algorithms into cipher suites, or sets of ciphers. This protocol is responsible of the agreement between the client and the server on these cipher suites. 3.4.1 Cipher suites There are many dierent cryptographic algorithms which can be used for encrypting data, for computing the MAC or to authenticate the peers. Some of them provide the highest levels of security, but they have higher computational requirements. Others are less secure, resulting in a higher performance encrypting and decrypting. Each cipher suite species the server authentication algorithm, the key exchange algorithm, the bulk encryption algorithm and the message digest algorithm. In Table 3.1, two dierent examples of cipher suites are described. Cipher Suite Auth Key Exchange Encryption Digest RSA_AES_256_SHA RSA RSA AES-256-CBC SHA1 DHE_RSA_AES_256_SHA RSA DHE AES-256-CBC SHA1 Table 3.1: Examples of cipher suites When an SSL connection is established, the client and the server exchange information about which ciphers suites they are willing to use. The client sends the cipher suites listed in the order of descending client preference, usually sorted by highest level of security. The server chooses the most suitable shared cipher suite. If they don't have a cipher suite in common, the SSL communication is not possible and the server closes the connection. 3.4.2 Handshake overview An overview of the handshake process is explained here: 1. The client sends to the server a list of the algorithms (bundled in cipher suites) that it is willing to support, along with a random number in order to generate the symmetric encryption key. 2. The server chooses a cipher suite out of the list and sends it back to the client along with a certicate, which contains the server's public key. CHAPTER 3. SSL AND TLS 22 The certicate also provides the needed information to authenticate the server. This also sends a random number that will be part of the encryption key generation process. 3. The client veries the server's certicate and extracts the public key. Once the client has the public key from the server, it generates a random secret string called the pre_master_secret and encrypts it using the server's public key. It sends the encrypted public key to the server. 4. Both sides, client and server, independently compute the encryption and the MAC keys from the pre_master_secret and both random values from client and server. 5. The client sends a MAC of all the previous handshake messages sent to the server. 6. The server sends a MAC of all the previous handshake messages sent to the client. These six steps are just an overview of how an SSL handshake is done. Section 3.4.3 shows how a real handshake is done and the messages involved. 3.4.3 A Real Handshake In order to explain how a real handshake is done, a brief introduction to the messages exchanged between the client and the server is needed. The most used and common SSL handshake is using RSA as a key exchange protocol and only authenticating the server, but not the client. Figure 3.2 shows the exchanged messages. The sequence of actions that occur when messages are exchanged during an SSL handshake are summarized here: 1. The connection starts with the client sending a ClientHello command, that contains: • The highest SSL version supported by the client. • The cipher suites supported by the client. • Compression methods if available. • Session ID. • Random data for its use in the secret-key generation process. CHAPTER 3. SSL AND TLS 23 2. The server answers with a ServerHello command, which includes: • The SSL version that will be used in the connection. • The cipher suite chosen by the server among those oered by the client. • The compression method chosen by the server. • The session ID for the SSL connection. • Random data for its use in the secret-key generation process. Figure 3.2: Normal RSA handshake 3. The server sends the Certificate command, that includes the server's certicate with the server's public key. Optionally, it also includes the chain of certicates beginning with the Certicate Authority (CA). 4. The server sends the ServerHelloDone command, indicating the client that the server is done with this stage of the SSL handshake. CHAPTER 3. SSL AND TLS 24 5. The client sends the ClientKeyExchange message, that contains the pre_master_secret created by the client and encrypted using the server's public key. Both sides, the client and the server, generate the secret encryption key using the pre_master_secret and the random data included in the ClientHello and ServerHello messages. 6. The client sends the ChangeCipherSpec command, which indicates that the subsequent messages sent by the client during the SSL session will be encrypted using the agreed cryptographic systems. 7. The client sends its last message in the Handshake protocol, Finished , containing a digest of all the previous messages sent by the client to the server. This command is sent to ensure that none of the messages sent previously unencrypted were not altered in ight. 8. The server sends the ChangeCipherSpec command, which indicates that the subsequent messages sent by the client during the SSL session will be encrypted using the agreed cryptographic systems. 9. The server sends its last message in the Handshake protocol, Finished , containing a digest of all the previous messages sent by the server to the client. This command has the same purpose as the Finished command in the client. These previous nine actions shows the exact steps that occurs in a SSL handshake using RSA for both key exchange and authentication protocol. The reader can nd a more detailed explanation of the dierent types of handshake using dierent key exchange protocols, authenticating the client or the reuse of a previous session in Section 3.4.4. 3.4.4 Dierent SSL Handshakes This section is intended to explain in more details how the dierent SSL handshakes, using dierent key exchange protocols are done and which kind of operations are involved, paying attention to the most energetically-computationally expensive. Normal RSA Handshake In Section 3.4.3, the normal RSA handshake was already explained. The use of RSA as a signing and key exchange protocol is the most used all over the CHAPTER 3. SSL AND TLS 25 world. It provides good performance with competitive energy consumption costs. In general, RSA operations are divided in: 1. Private key operations used in digital signature and private key decryption. 2. Public key operations used in signature verication and public key encryption. This distinction is important in this context because private key operations are much slower than public key operations. Decryption of a ciphertext using public key operations is really hard, computationally speaking. The vast majority of the CPU time is consumed processing three messages, two on the client side and one in the server side. • Client side  Server's Certificate processing: The certicate sent by the server contains the chain of certicates. In order to process it, the client needs to parse and verify each certicate. This means performing RSA veries, one verify per each certicate included in the chain.  ClientKeyExchange : This message contains the pre_master_- secret encrypted under the server's public key. The dominant operation here is RSA encryption, where the limiting factor is the length of the server's public key. • Server side  ClientKeyExchange : The dominant operation here is the server's RSA decryption of the pre_master_secret . As with the previous operation, the longer the key, the longer the decryption takes. It is important to mention that this operation is much slower than the encryption (it uses a private key operation) and the verication that take place in the client. As this operation takes place in the server, it is the bottleneck in SSL throughput. The client needs to wait for the server to complete this step. The cost of the decryption depends on the server's key length, making the server's RSA key length the most important factor limiting performance. CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 32 4.2 Hardware and Software used In the next sections, a brief introduction to all the technologies and components used is included. 4.2.1 Symbian Symbian 1 is the world's most used and popular smartphone platform. It is implemented in a diverse range of devices and provides application and media developers with a consistent set of technologies. The Symbian Operating System is a 32-bit multi-tasking OS. Symbian platform provides most of the functionalities via subsystems. Each subsystem has a set of libraries that implements method and functions accessible using dierent APIs. Developers can create applications using dierent languages such as Qt, Symbian C++, a set of Open C/C++ APIs, Java, Web Runtime (WRT) or Adoble Flash Lite. 4.2.2 Nokia N95 The Nokia N95 2 terminal was released in 2007 by Nokia under the N series. It is based on Symbian 9.2 , the third generation of the Symbian OS and It is the rst Nokia phone with HSDPA connectivity, the evolution of the 3G (third generation) mobile telephony communications protocol in the HSPA family, also coined as 3.5G. The most important specications of the N95 terminal are presented in Table 4.1. 1 http://www.symbian.org - Last accessed: April 2010 2 http://europe.nokia.com/support/product-support/nokia-n95 - Last accessed: April 2010 CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 33 Figure 4.1: N95 terminal GENERAL 2G Network GSM 850 / 900 / 1800 / 1900 3G Network HSDPA 2100 HSDPA 850 / 1900 - American version Announced 2006, September. Released 2007, March DISPLAY Type TFT, 16M colors Size 240 x 320 pixels, 2.6 inches, 40 x 53 mm DATA GPRS Class 10 (4+1/3+2 slots), 32 - 48 kbps EDGE Class 32, 296 kbps; DTM Class 11, 177 kbps 3G HSDPA WLAN Wi-Fi 802.11 b/g, UPnP technology USB Yes, v2.0 miniUSB FEATURES OS Symbian OS 9.2, S60 rel. 3.1 CPU Dual ARM 11 332 MHz processor; 3D Graphics HW Accelerator BATTERY Type Standard battery, Li-Ion 950 mAh (BL-5F) Stand-by Up to 220 h (2G) / 192 h (3G) Talk time Up to 6 h 30 min (2G) / 2 h 42 min (3G) Table 4.1: Nokia N95 specications CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 34 4.2.3 Carbide.C++ IDE Carbide.C++ 3 is a software application for development in Symbian OS. It is used to build applications and other components that use Symbian OS. It is based on the Eclipse Integrated Development Environment (IDE), enhanced with extra plug-ins to support the Symbian OS development. It provides the needed tools to develop C++ applications but using additional components, it also includes the possibility to develop applications in other coding languages like C, Python, Java, among others. Carbide.C++ 2.0 has been used for the development of the applications. 4.2.4 Open C/C++ Open C/C++ plug-in 4 is a set of libraries that provides the developer with a serie of C/C++ programming interface libraries, in order to enable a faster application development in Symbian OS. It includes nine well-known standard POSIX and middleware C libraries: libc, libdl, libpthread, libm, libz, libcrypt, libglib, libcrypto and libssl. These two last ones are part of the OpenSSL implementation (see Section 4.2.5 for more information). Figure 4.2 shows where the Open C/C++ standard libraries t in the Symbian architecture. 4.2.5 OpenSSL OpenSSL [Ope10], is an open source toolkit implementing the Secure Socket Layer protocol, the Transport Secure Layer protocol, and a full-strength general purpose cryptography library. OpenSSL provides an API that facilitates the developing of SSL applications. At the time of writing, the current version 1.0.0 was released on Mar 29th, 2010. Although there are dierent alternatives like GNUTLS 5 , Network Security Services (NSS) 6 or PolarSSL 7 , OpenSSL was selected attending to these reasons: 3 http://developer.symbian.org/main/create_applications/index.php - Last accessed: April 2010 4 http://www.forum.nokia.com/Technology_Topics/Development_Platforms/Open_- C_and_C++/ - Last accessed: April 2010 5 http://www.gnu.org/software/gnutls/ - Last accessed: April 2010 6 http://www.mozilla.org/projects/security/pki/nss/ - Last accessed: April 2010 7 http://www.polarssl.org - Last accessed: April 2010 CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 35 Figure 4.2: Open C/C++ in the Symbian architecture • It is included with the Open C/C++ plug-in. • It is the most used secure toolkit implementing SSL/TLS and it is well documented. • It is already installed in most of Linux distributions. Having explained the most important factors that determined the selection of the development tools, next Section 4.2.6 explains the tools selected for the energy measuring, the Nokia Energy Proler. 4.2.6 Nokia Energy Proler Nokia Energy Proler 8 is a stand-alone test and measurement application for S60 3rd Edition, Feature Pack 1 and later devices. The application enables developers to test and monitor their application's energy usage in real time on target devices. The Nokia Energy Proler is capable of measuring the following: • Power view: shows the power consumption over a measurement period in Watts(W). 8 http://www.forum.nokia.com/Technology_Topics/Application_Quality/Power_- Management/Nokia_Energy_Proler_Quick_Start.xhtml - Last accessed: April 2010 CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 36 • Current view: displays current consumption, which is the measured current draw from the battery. • Processor view: shows the CPU load over a measurement period as a percentage of the total available CPU-processing capability. • RAM Memory view: displays the RAM memory usage over the measurement period. • Network Speed view: presents the downlink (download) and uplink (upload) speeds through the IP stack. • WLAN view: shows the received-signal strength when the device is connected to a WLAN base station. • Signal Levels view: shows the cellular signal levels as RX and TX levels. • Energy view: shows the cumulative energy consumed over the measurement period. • Voltage view: shows the battery-voltage levels. • 3G Timers view: shows the 3G-network-data inactivity timers, also known as T1 and T2. All the collected data can be exported into several formats: CSV, SVG or JPEG. As the Nokia Energy Proler is an independent measurement application, it also provides an external API that gives developers the ability to control the recording process and to retrieve the data collection. The use of the API and the connection procedure is explained in Section 4.5.2. 4.3 Cipher suites selection This section is intended to justify the selection of the chosen cipher suites. The main decision factor to select these cipher suites was the use of a good symmetric cryptography algorithm. As one of the most used algorithms and dened as a cryptographic standard by the NIST, the Advanced Encryption Standard have been used. Furthermore, previous studies [PRRJ06] of symmetric algorithms have shown that AES has good performance with CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 37 Cipher Suite Certicate type and Key exchange algorithm TLS_RSA_WITH_AES_128_CBC_SHA RSA TLS_DH_DSS_WITH_AES_128_CBC_SHA DH_DSS TLS_DH_RSA_WITH_AES_128_CBC_SHA DH_RSA TLS_DHE_DSS_WITH_AES_128_CBC_SHA DHE_DSS TLS_DHE_RSA_WITH_AES_128_CBC_SHA DHE_RSA TLS_DH_anon_WITH_AES_128_CBC_SHA DH_anon TLS_RSA_WITH_AES_256_CBC_SHA RSA TLS_DH_DSS_WITH_AES_256_CBC_SHA DH_DSS TLS_DH_RSA_WITH_AES_256_CBC_SHA DH_RSA TLS_DHE_DSS_WITH_AES_256_CBC_SHA DHE_DSS TLS_DHE_RSA_WITH_AES_256_CBC_SHA DHE_RSA TLS_DH_anon_WITH_AES_256_CBC_SHA DH_anon Table 4.2: List of Cipher suites using AES included in TLS competitive energy costs. With these facts, the use of AES is more than justied. Thus, the AES cipher suites extending TLS v1.0, dened in [Cho02] have been used. From the 12 cipher suites supporting AES in the TLS (presented in Table 4.2), some of them needed to be discarded. As the reader can see, all the cipher suites in the list use the same protocols for encryption/decryption, AES, and for message digest, HMAC-SHA-1. Thus, the reasons behind these discards are related to the algorithms used in the authentication and the key exchange algorithm. These reasons are presented here: • The use of Anonymous Die-Hellman (ADH) provides condentiality but no authentication. This lack of authentication is vulnerable to man-in-the-middle attacks [PP06]. That fact implies that in order to authenticate the peers, an external authentication method should be used. • The use of the Digital Signature Standard (DSS) [oST06] results in a slower performance [Res01] if it is compared to RSA. • OpenSSL only implements ephemeral Die-Hellman (DHE), but not Die-Hellman (DH). Having discussed the decision factors, the selected cipher suites list is presented in Table 4.3. These cipher suites present high levels of security, as by default DHE-RSA-AES-256-SHA provides the highest level of security. CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 38 Cipher Suite Auth Key Exchange Encryption Digest RSA-AES-128-SHA RSA RSA AES-128-CBC SHA1 RSA-AES-256-SHA RSA RSA AES-256-CBC SHA1 DHE-RSA-AES-128-SHA RSA DHE AES-128-CBC SHA1 DHE-RSA-AES-256-SHA RSA DHE AES-256-CBC SHA1 Table 4.3: List of Cipher suites selected for the experiments 4.4 Design of the dierent scenarios The use of the SSL protocol to secure a communication channel involves an overhead of computational work and exchanged data, that incurs into a higher energy consumption. To perform an exhaustive analysis of the energy consumption involved in the creation of an SSL secure channel, it is important to remark that the SSL overhead can be divided up into: 1. Increased data volume due to additional items such as certicates and message digests. 2. Computational overhead generated by cryptographic algorithms such as encryption/decryption, authentication or message digests. As commented in Chapter 3, the SSL protocol is divided into two dierent phases detailed as: 1. The handshake phase, computationally expensive and costly due to the usage of several network ows. 2. The transfer phase, using the agreed secret key to exchanged the data securely and eciently. In order to measure the data overhead and the energy consumption overhead of the establishment of a SSL session, dierent scenarios need to be built. The dierent scenarios must be divided into: 1. Local cases, where the server and the mobile client are located in the same network (latency < 1ms). 2. Remote cases, where the mobile client connects to a server, but they are not in the same network (latency depending on the remote service, the Internet provider and the overall network status). CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 39 Test scenarios: Local cases For the Local cases, the implementation of a server capable of accept SSL connections is needed (the server specications are explained in details in Section 4.5.1). To obtain a complete analysis of the energy consumption and the extra overhead, the next test scenarios have been designed: • The use of a secure channel increases the exchanged data. To measure this increase, two scenarios are necessary: the use of a non secure channel (just a TCP connection) and the use of an SSL channel. The dierence of the data exchanged will be the real overhead of the SSL usage. Dierent le sizes are tested: 1K, 10K, 50K, 100K, 500K, 1MB and 5 MB. • The same previous scenario can be used to measure the energy consumption overhead. • An important part of the SSL connection is the handshake, where public key operations are involved, with high energy consumption impact. Several handshakes are performed using each of the selected cipher suites to measure both the data exchanged and the power consumption. • Analyze the impact of cached sessions vs. not cached. SSL oers a session resumption mechanism to allow a client-server pair to skip the recalculation of the master secret key that they already computed and exchanged in a previous session. This feature can greatly reduce the cost of the connection setup. • Study the energy consumption generated due to client authentication. Most of the servers do not require client authentication, but it is interesting to measure the extra data sent by the client. • Measure the impact of using the dierent communication interfaces, the ones that the mobile device is equipped with: WLAN and 3G. Test scenarios: Remote cases The remote cases are intended to test how the dierent remote services perform an SSL session establishment, measuring not only the energy consumption, but also the exchanged data and the total execution time. Before explaining the dierent test scenarios designed to cover all the presented issues, a list of the remote services to test are presented here: CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 40 • Google (www.google.com) is the top 1 site with 42,51% of global Internet users who visit google.com (according to Alexa.com). The main service oered is to enable users to search the Web, but it also has dierent services like webmail, maps, online oce tools, just to name a few of them. • Facebook (www.facebook.com) is the top 2 site with 32.69% of global Internet users who visit facebook.com (according to Alexa.com). It is a social networking website that allows user to interact with other users adding them as friends, sending messages, tagging pictures or using applications. Actually facebook, oers 3 dierent ways to acces to the website: 1. The original version (www.facebook.com) 2. The secure version (ssl.facebook.com) oering SSL protocol in order to encrypt all the communications. 3. The mobile version (m.facebook.com) an optimized site for mobile devices. • Ovi (www.ovi.com) is the brand for Nokia's Internet services. It is a service focused on ve key service areas: Games, Maps, Media, Messaging and Music. Users can access these services via website, or using the existing application for mobile devices or desktop computers. The reason for choosing this service is obvious, it is a Nokia service. • Verisign (www.verisign.com) has been selected as a reference of security. This American company was born as a spin-o of RSA Security certication but nowadays is not only one of the major certicate authorities, but also it is in charge of two of the Internet thirteen root nameservers and it manages also the top-level domains .com and .net. All of them have dierent characteristics that will be described in Section 5.2.1. Having introduced the remote services tested, it is time now to explain the scenarios to obtain results for the dierent interesting issues: • Study of a complete prole of the dierent services in order to understand the obtained results. • Measure the energy impact establishing an SSL session with the dierent services using the dierent cipher suites. CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 41 • Analyze the impact of cached sessions compared to not cached. SSL oers a session resumption mechanism to allow a client-server pair to skip the recalculation of the master secret key that they already computed and exchanged in a previous session. This feature can greatly reduce the cost of the connection setup but not all the services support this feature. • Measure the impact of using dierent communications interfaces, the ones that the mobile device is equipped with: WLAN and 3G. Test scenarios: Overhead of SSL usage From the previous experiments, the overall energy consumption and time executions can be obtained, but it is also important to know the real performance and the overhead involving secure connections using the SSL protocol. This scenario is useful to study dierent aspects of SSL, like: • SSL data overhead, showing the extra bytes sent using security. • SSL throughput, showing how the use of SSL protocol aects the overall performance. • SSL energy consumption overhead, showing the extra energy involving the use of SSL. 4.5 Experimental and Measuring Setup This section explains how the experimental setup works, the connection between the client and server, as well as the measuring methodology. 4.5.1 Design of the applications The most important coding aspects of the applications are discussed as well as the dierent options and modes oered by both the server and the client are explained in the following lines. Client design The SSL client is coded in C language with some additional functions like the connection with the Nokia Energy Proler coded in C++. For the codi- CHAPTER 4. DESIGNED SETUP OF EXPERIMENTS 48 Figure 4.5: Secure client-server experimental setup Chapter 5 Analysis of Measurements In this chapter, a comprehensive empirical analysis of the energy consumption of the SSL protocol is done, using the experimental setup described in Chapter 4. 5.1 Test scenario: Local case This test scenario groups all the experimental cases performed in the same local area network, where latency was less than 1ms. 5.1.1 Exchanged data To understand well how much data is being exchanged in the TLS handshake, the tests include an option to measure the bytes exchanged in the operation. As in the handshake only public key cryptography (RSA) and public key exchange mechanism (RSA or Die-Hellman) are used, the algorithms related with encryption (AES) and with integrity and authentication (HMAC-SHA1) do not aect and the results show that the data exchanged is the same either we use AES128 or AES256, the only dierence is because of the use of RSA or Die-Hellman. Table 5.1 shows the results divided into the three operation modes: Client Authentication, No Client Authentication and Session Resumption. For each mode, the 4 cipher suites have been tested. The row headed with C→S means data sent by the client to the server. The next row is the data sent in the other way, from the server to the client. 49 CHAPTER 5. ANALYSIS OF MEASUREMENTS 50 Operation Mode Cipher suite C→S S →C No Client AES128-SHA 249 2368 Authentication AES256-SHA 249 2368 DHE-RSA-AES128-SHA 249 2770 DHE-RSA-AES256-SHA 249 2770 Client AES128-SHA 1772 2348 Authentication AES256-SHA 1772 2348 DHE-RSA-AES128-SHA 1772 2752 DHE-RSA-AES256-SHA 1772 2752 Session Resumption NOT RELEVANT 142 168 Table 5.1: Exchanged data performing a handshake for the local case Analyzing the results: • The client always sends the same amount of data, independently of the cipher suite used. • For the client authentication, the increase of data is important. The server requests a client certicate and the client has to send it. This exchanged data depends, of course, of the client certicate length. • The impact of using session resumption is really important. The data sent by the client is reduced nearly 50% and the data sent by the server is divided by 16, either with client authentication or not. Also the data is invariable no matter the cipher suite used. • Using Die-Hellman algorithm for Key agreement increases in 402 bytes the data sent by the server, in comparison with RSA. 5.1.2 Energy consumption Once the exchanged data involved in an SSL handshake have been discussed, they will help to understand the energy consumption dissipated in the handshake process. Table 5.2 shows the power consumption in milijoules (mJ) for the dierent cipher suites, requesting or not client authentication. CHAPTER 5. ANALYSIS OF MEASUREMENTS 51 Cipher Suite Non Client Client Authentication Authentication RSA-AES-128-SHA 99 155 RSA-AES-256-SHA 101 155 DHE-RSA-AES-128-SHA 739 839 DHE-RSA-AES-256-SHA 742 842 Session Resumption 64 Non secure 25 Table 5.2: Energy consumption for the SSL handshake in the local case Analyzing Image 5.1, dierent conclusions can be obtained: • The most important conclusion is that the use of Die-Hellman aects critically to the energy consumption per connection, compared with RSA. This was explained in Section 2.6.2. Die-Hellman protocol has harder computational operations compared with RSA, involving longer execution times where the network interface must be kept up, increasing the energy consumption. In addition, these operations mean higher work for the CPU, involving higher power needs. • The use of Client Authentication also increases the consumption, as more data is exchanged. These values depend on the data length of the client certicate, as mentioned before. • The use of session resumption can greatly save energy, specially avoiding the use of Die-Hellman where the savings can be from 842 mJ per connection (for the worst case) to only 64 mJ. • The establishment of a non secure connection costs only 25 mJ, compared with the 100 mJ using RSA or more than 700 mJ using DHE. CHAPTER 5. ANALYSIS OF MEASUREMENTS 52 Figure 5.1: Energy consumption for the SSL handshake in Local case 5.2 Test scenario: Remote cases While the previous sections describes the test cases where latency is less than 1 ms, in the remote cases, these values changes depending the remote service and the network interface used. 5.2.1 Services prole study Before starting with the experiments and the measurements, a full prole study of the chosen remote services needs to be done. This study is intended to analyze the properties of each service including: • SSL protocols available • The Server SSL implementation • Default cipher suite • Server Certicate length • Public server-key length • Support of Session resumption CHAPTER 5. ANALYSIS OF MEASUREMENTS 53 • Support of Ephemeral Die-Hellman • List of Cipher suites available The SSL protocols available refer to the version of the SSL protocol supported by the server. Due to SSLv2 is vulnerable to attacks, none of them supports that protocol, only SSLv3 and TLSv1 are supported. SSLv2 does not support either useful features like client authentication. Newer TLS versions like TLSv1.1 and TLSv1.2 are not supported yet. The Server implementation is related with the internal implementation used. The most important are Apache mod_SSL 1 , Apache mod_NSS 2 or Internet Information Services (IIS) 3 . The default cipher suite is used in order to know the level of security the server is willing to use by default. This selection is mostly based on a right balance between security and performance. The server certicate length shows the size of the server's certicate, being one of the most important factors in the energy consumption. The level of security desired by the server depends also on the public serverkey length, which is usually 1024 bits but if better security levels are required, higher values like 2048 bits can be used, but aecting signicantly to performance and energy consumption. The support of session resumption, as shown in previous experiments for the local case, can greatly reduce the energy consumption. All the services with the exception of Facebook allow this feature. The most important reason behind this issue is that maintaining a cache of all the shared secrets computed with each SSL client is really expensive, in data storage meanings. In some cases, the improvement obtained with the use of session resumption is not worth it, and the servers from the remote services request a complete SSL handshake each time a client wants to establish a secure connection using SSL. The use of Ephemeral Die-Hellman provides better security levels compared with RSA but also aects considerably to performance and energy consumption. Dierent services here do not allow this protocol, as they prefer better performance and scalability. Finally, a list of the supported cipher suites is presented. This can help to understand the dierent policies of each service attending to performance- 1 http://www.modssl.org/ - Last accessed: April 2010 2 http://www.mozilla.org/projects/security/pki/nss/ - Last accessed: April 2010 3 http://www.iis.net/overview - Last accessed: April 2010 CHAPTER 5. ANALYSIS OF MEASUREMENTS 54 security-scalability. This study will help to understand better the dierent exchanged data and the energy consumption variations. All the gathered information can be checked in Table 5.3 CHAPTER 5. ANALYSIS OF MEASUREMENTS 55 Service Google Facebook SSL.Facebook M.Facebook Verisign Ovi Protocols available SSLv3, TLSv1.0 SSLv3, TLS1.0 SSLv3, TLS1.0 SSLv3, TLS1.0 SSLv3, TLSv1.0 SSLv3, TLS1.0 Server Implementation Apache mod_SSL Apache mod_NSS Apache mod_NSS Apache mod_NSS Apache mod_SSL IIS 7.5 Default Cipher Suite AES256-SHA RC4-MD5 RC4-MD5 RC4-MD5 DHE-RSA-AES256-SHA DHE-RSA-AES256-SHA Server Certicate length 1625 bytes 4553 bytes 4642 bytes 836 bytes 4519 bytes 1738 bytes Public server-key 1024 bits 1024 bits 2048 bits 1024 bits 2048 bits 1024 bits Session resumption YES NO NO NO YES YES Ephemeral Die Hellman NO NO YES YES YES YES Cipher suites available AES256-SHA 256 bit AES256-SHA 256 bit DHE-RSA-AES256-SHA 256 bit DHE-RSA-AES256-SHA 256 bit DHE-RSA-AES256-SHA 256 bit ADH-AES256-SHA 256 bit DES-CBC3-SHA 168 bit DES-CBC3-SHA 168 bit AES256-SHA 256 bit AES256-SHA 256 bit AES256-SHA 256 bit DHE-RSA-AES256-SHA 256 bit AES128-SHA 128 bit AES128-SHA 128 bit EDH-RSA-DES-CBC3-SHA 168 bit EDH-RSA-DES-CBC3-SHA 168 bit EDH-RSA-DES-CBC3-SHA 168 bit AES256-SHA 256 bit RC4-SHA 128 bit RC4-SHA 128 bit DES-CBC3-SHA 168 bit DES-CBC3-SHA 168 bit DES-CBC3-SHA 168 bit ADH-DES-CBC3-SHA 168 bit RC4-MD5 128 bit RC4-MD5 128 bit DHE-RSA-AES128-SHA 128 bit DHE-RSA-AES128-SHA 128 bit DHE-RSA-AES128-SHA 128 bit EDH-RSA-DES-CBC3-SHA 168 bit AES128-SHA 128 bit AES128-SHA 128 bit AES128-SHA 128 bit DES-CBC3-SHA 168 bit RC4-SHA 128 bit RC4-SHA 128 bit RC4-SHA 128 bit ADH-AES128-SHA 128 bit RC4-MD5 128 bit RC4-MD5 128 bit RC4-MD5 128 bit DHE-RSA-AES128-SHA 128 bit EDH-RSA-DES-CBC-SHA 56 bit EDH-RSA-DES-CBC-SHA 56 bit EDH-RSA-DES-CBC-SHA 56 bit AES128-SHA 128 bit DES-CBC-SHA 56 bit DES-CBC-SHA 56 bit DES-CBC-SHA 56 bit ADH-RC4-MD5 128 bit EXP-EDH-RSA-DES-CBC-SHA 40 bit EXP-EDH-RSA-DES-CBC-SHA 40 bit RC4-SHA 128 bit EXP-DES-CBC-SHA 40 bit EXP-DES-CBC-SHA 40 bit RC4-MD5 128 bit EXP-RC2-CBC-MD5 40 bit EXP-RC2-CBC-MD5 40 bit ADH-DES-CBC-SHA 56 bit EXP-RC4-MD5 40 bit EXP-RC4-MD5 40 bit EDH-RSA-DES-CBC-SHA 56 bit DES-CBC-SHA 56 bit EXP-ADH-DES-CBC-SHA 40 bit EXP-ADH-RC4-MD5 40 bit EXP-EDH-RSA-DES-CBC-SHA 40 bit EXP-DES-CBC-SHA 40 bit EXP-RC2-CBC-MD5 40 bit EXP-RC4-MD5 40 bit Table 5.3: Full prole of the remote services analyzed CHAPTER 5. ANALYSIS OF MEASUREMENTS 56 5.2.2 Exchanged data As the same experiments performed for the local case, it is important to measure the amount of exchanged data to understand well the energy consumption involved in the establishment of an SSL handshake. Table 5.4 show the results of the experiment. Attending to these results, dierent statements can be mentioned: • The client always sends 286 bytes in the handshake, but this amount is increased when the server uses 2048 bits public key length up to 414 bytes. This case is only for services like SSL.facebook and Verisign. • Depending on the server's certicate length, the data sent by the server is dierent. The longest certicates correspond to Verisign, Facebook and SSL.facebook. This issue will be reected in the energy consumption. • Related with the previous point, the total amount of data sent by the server is lightly increased when using Ephemeral Die-Hellman instead of RSA. The increase is 370 bytes when using 1024 bits public key length and 498 bytes for 2048 bits. • Session resumption can reduce the exchanged data from more than 5 KB to only 179 bytes, increasing the battery life. SSL client authentication can not be tested on these services, as they do not allow client authentication. The reader should not be confused with client authentication using a username or password in the remote service. This authentication is related with the server requesting a certicate from the client in the SSL handshake. 5.2.3 Energy consumption using WLAN Once a full prole of the services and the total data exchanged has been described, the energy consumption using WLAN interface is presented in Figure 5.2 and Table 5.5. The results show dierent conclusions: • The use of Die-Hellman aects dramatically in the setup energy consumption, not only increasing the execution time but also increasing the data sent by the parties during all the handshake. This was already commented in Section 2.6.2 and observed in Section 5.1.2. CHAPTER 5. ANALYSIS OF MEASUREMENTS 57 Operation Mode Cipher suite C → S S → C Google AES128-SHA 286 1777 AES256-SHA 286 1777 DHE-RSA-AES128-SHA Not supported DHE-RSA-AES256-SHA SESSION RESUMPTION 138 179 Facebook AES128-SHA 286 4705 AES256-SHA 286 4705 DHE-RSA-AES128-SHA Not supportedDHE-RSA-AES256-SHA SESSION RESUMPTION m.Facebook AES128-SHA 286 1004 AES256-SHA 286 1004 DHE-RSA-AES128-SHA 286 1374 DHE-RSA-AES256-SHA 286 1374 SESSION RESUMPTION Not supported ssl.Facebook AES128-SHA 414 4794 AES256-SHA 414 4794 DHE-RSA-AES128-SHA 286 5292 DHE-RSA-AES256-SHA 286 5292 SESSION RESUMPTION Not supported Verisign AES128-SHA 414 4671 AES256-SHA 414 4671 DHE-RSA-AES128-SHA 286 5201 DHE-RSA-AES256-SHA 286 5201 SESSION RESUMPTION 138 179 Ovi AES128-SHA 286 3682 AES256-SHA 286 3682 DHE-RSA-AES128-SHA 286 4084 DHE-RSA-AES256-SHA 286 4084 SESSION RESUMPTION 138 179 Table 5.4: Exchanged data performing a handshake for remote cases