Algunos consejos prácticos sobre criptografía para programadores

cueva Ya hemos hablado otras veces de criptografía: que no hay que inventarla, que hay que usar métodos conocidos y reconocidos… Sin embargo, no es tan fácil ponerse a utilizar criptografía, sobre todo cuando lo que alguien quiere es tan sencillo como cifrar sus datos de manera razonable, sin tener que convertirse en un critptógrafo o un criptoanalista. Por eso me gustó leer Cryptography for programmers 2: Blocks and Randomness donde explican justamnente esa parte, los bloques y cómo se emplean en el cifrado y el tema de la aleatoriedad (otro ‘favorito’ de este sitio).

Si alguien está interesado la entrada forma parte de una serie de cuatro, dedicadas a los principios básicos, y otros temas interesantes, además de este.

Se habla de cifrado simétrico y asimétrico para luego hablar de la criptografía de bloques, que es la que suele utilizarse cuando se habla de cifrado simétrico.

Block cryptography is the default symmetric cryptography used nowadays, and so it will be the only symmetric cryptography that will be covered in the series.

La idea es cifrar una cantidad fija de bits mediante un algoritmo simétrico y los bloques nos permiten manejar estas cuestiones. Luego pasa a explicarnos qué tipo de bloques serían recomendables.

For the purpose of this post I would say as a programmer there is no reason you should be using anything other than AES. AES is the current standard, it is secure enough and will very likely continue to be for a long time, specially if you are using the variant with a 256 bit key, which I would recommend.

Luego habla de los generadores de números seudoaleatorios, que es un tema que hemos tocado más veces aquí.

Interesante.

Ataques laterales para obtener información: la memoria como WiFi

Memorias. Hay toda una familia de ataques que se basan en tratar de obtener información sobre un sistema a partir de lo que llaman canales laterales: variaciones de diferentes parámetros que pueden medirse y que pueden ayudar a un atacante a obtener información.

Hoy traemos Exfiltrating Data from Air-Gapped Computers via Wi-Fi Signals (Without Wi-Fi Hardware) que habla de cómo se puede comprometer un sistema para que los chips de memoria de nuestro ordenador pudieran llegar a generar emisiones electromagnéticas en la banda de 2.4GHz como si fuera una WiFi. Estas señales podrían ser recibidas por múltiples dispositivos que estuvieran en las proximidades y se podrían utilizar para robar información.

Dubbed “AIR-FI,” the attack hinges on deploying a specially designed malware in a compromised system that exploits “DDR SDRAM buses to generate electromagnetic emissions in the 2.4 GHz Wi-Fi bands” and transmitting information atop these frequencies that can then be intercepted and decoded by nearby Wi-Fi capable devices such as smartphones, laptops, and IoT devices before sending the data to remote servers controlled by an attacker.

Al ser generado por los chips de memoria, no es necesario que el sistema tenga antenas WiFi ni nada parecido; el atacante simplemente puede generar esas emisiones electromagnéticas y enviar datos a través de ellas.

“Instead, an attacker can exploit the DDR SDRAM buses to generate electromagnetic emissions in the 2.4 GHz Wi-Fi bands and encode binary data on top of it.”

Esta sería una posible vía de ataque para robar información de sistemas desconectados de la red, claro.

Para poder realizar el ataque es necesario infectar el equipo, y disponer de otro que haga de receptor y que esté suficientemente cerca.

Curioso.

IoT, nuestra casa y la seguridad

Puerta. Troy Hunt ha estado domotizando su casa y ha escrito una serie de entradas sobre las decisiones que iba tomando. Me pareció particulamente interesante el aspecto de la seguridad, siendo un experto como es él. Lo contaba en IoT Unravelled Part 3: Security.

En el internet de las cosas IoT, siempre se nombra la seguridad como una preocupación (dispositivos pequeños, poco potentes… Pero también falta de madurez, fabricantes muy diversos y algunos oportunistas…). Lo resumía así:

In part 1 of this series, I posited that the IoT landscape is an absolute mess but Home Assistant (HA) does an admirable job of tying it all together.

Algunos fabricantes ya dan cuenta de la seguridad con dispositivos que se actualizan automáticamente. Si nos salimos del camino, es posible que nos metamos en líos.

For your average consumer (and remember, that’s probably 99%+ of people buying TP-Link smart plugs), automatically updating firmware is key. For the rest of us, we need to recognise that we take on risks when using IoT devices in ways they weren’t designed for.

Otro debate interesante es analizar si nuestros dispositivos deben ‘vivir’ dentro de nuestra red local, o tener interacciones con la nube.

This whole discussion about devices updating their firmware raised another philosophical debate which I want to delve into now, and that’s the one about how self-contained the IoT ecosystem should be within the LAN versus having cloud dependencies.

La nube, y los fabricantes emergentes nos pueden colocar en situaciones comprometidas: ¿qué sucedería si el fabricante de nuestros dispositivos deja de proporcionar sus servicios?

That resiliency extends beyond just a cloud outage too; what if Tuya shuts down the service? Still want to be able to turn your lights on?

Desde un punto de vista, entonces, de seguridad y privacidad, parece natural apostar por aparatos que dependan exclusivamente de nuestra propia red.

That said, from a simple security and privacy perspective (and often a performance perspective too), I always prioritise local communication.

También hay que considerar la compartimentalización: una solución es aislar estos dispositivos en su propia red, para que si hay problemas de seguridad no afecten al resto de nuestra vida.

One popular approach is to isolate the network the IoT things are on from the network the non-IoT things are on. This mindset is akin to putting all the potentially bad eggs in the one basket and the good eggs (such as your PC) in another basket.

Pero queremos poder controlar nuestros dispositivos desde nuestro ‘dispositvo seguro’ y empieza el lío de interactuar entre esas redes diferentes.

The main problem is that you end up with all sorts of scenarios where a particular IoT device needs to see the app that controls it but because the very purpose of the VLAN is to lock the IoT things away, things would fail.

Entonces, hay que asegurar la cosa, y … usar sólo lo que realmente queramos/necesitemos, porque no podemos perder lo que no tenemos (por ejemplo, a la hora de apuntar una cámara):

  1. You cannot lose what you do not have … As it relates to my own approach to IoT, all cameras I have point at places that are publicly observable.

Y, por lo tanto, más vale ser selectivos en lo que conectamos. Hace nuestro análisis de riesgos, decidiendo qué cosas buenas tendremos y qué cosas malas pueden pasar.

  1. Be selective with what you connect: … The point here is that I’m effectively doing my own little risk assessment on each IoT device, and you can too. What upside does it bring you? What downside does it present?

Finalmente, estar seguros de en quién confiamos. Fabricantes, instaladores, apartos… Lo barato puede salirnos muy caro. Y, ojo, una marca conocida no siempre será una garantía de buena calidad.

  1. Choose who to trust: … These companies invest serious dollars in their security things in just the same way Amazon does with their Echo devices.

También hay que vencer la inercia: si no tenemos nada conectado, ¿por qué asumir ese riesgo? Hunt dice que su vida es mejor y más cómoda y, en ese sentido, puede valer la pena.

There will be those who respond to this blog post with responses along the lines of “well, you really don’t need any of these things connected anyway, why take the risk?” There’s an easy answer: because it improves my life.

Tampoco hay que olvidar que un experto puede hacer muchas cosas que alguien menos interesado no hará. Y allí puede estar el peligro para esta persona.

Coming back to a recurring theme from this series, the security situation as it relates to normal everyday people using IoT devices isn’t great and I’ve given plenty of examples of why that’s the case. I also don’t believe the approaches taken by enthusiasts solves the problem in any meaningful way …

Espiar lo que tecleamos en una videoconferencia

Teclado flexibilizado En This horrifying Zoom hack will deter you from ever side-chatting again nos contaban cómo un grupo de investigadores de la Universidad de Texas en San Antonio pueden adivinar lo que estamos tecleando en nuestra sesión de videoconferencia con una precisión del 93%.

Researchers from the University of Texas at San Antonio and the University of Oklahoma have demonstrated something terrifying: They can read what people are typing during video calls on Zoom, Skype, and Google Hangouts with up to 93% accuracy.

Y no se refieren a la típica metedura de pata de tener otra cámara, o que la que tenemos apunte a donde no debe o, que escribamos la contraseña por error en el chat.

We’ve all side-chatted, saying one thing to the camera, and another on the side. Maybe it was a joke over Gchat at a coworker’s expense. Maybe it was just multitasking some emails. Maybe it was entering a password into another site.

¿Cómo lo hacen? Observando e interpretando los movimientos de nuestra espalda.

Without using any special machine learning or artificial intelligence techniques, Jadliwala’s team figured out how to read the subtle pixel shifts around someone’s shoulders to make out their basic cardinal movements: north, south, east, and west.

Por ejemplo, para escribir CAT (gato) parece que primero escribirmos la ‘C’, nos movemos a la izquierda, hacia la ‘A’ y, finalmente, hacia la derecha para teclear la ‘T’.

Applied to a keyboard, these four directions actually mean a lot. If you are typing “cat,” you start with the C, move west to the A, then back east to the T.

Es suficiente con registrar los movimientos de la espalda y relacionarlos con un diccionario de palabras habituales.

Once researchers figured out how to read these directions through shoulder movements, they were able to create software that could cross-reference them with what they call “word profiles” built with an English dictionary, which turned the maze of directions into meaningful words.

El problema es que los proveedores no pueden hacer mucho para defendernos, tal vez emborronar nuestro contorno un poco.

But our research is not Zoom or Google specific. They cannot do anything about it at the software level in some sense.”

Las formas en que nos pueden atacar son múltiples, y cada vez hay personas más igeniosas.

Complejidad y diseño de sistemas seguros

Defensa He estado leyendo un libro que me ha parecido interesante: This Is How They Tell Me the World Ends: The Cyberweapons Arms Race. No voy a hacer una reseña, pero sí que recomiendo su lectura porque es una aproximación interesante y fácil de leer de la historia reciente que nunca se cuenta (al menos en nuestro entorno, donde el periodismo tecnológico está orientado a las novedades comerciales y al miedo a la tecnología en sus diversas vertientes) en los aspectos relacionados con el mercado de los fallos de día cero zero days y cómo los diversos agentes han estado interactuando con los expertos para conseguirlos y utilizarlos con obejtivos diversos. Es un libro escrito por Nicole Perlroth y que ha trabajado con un montón de fuentes para traernos esta información. Se puede leer una (bastante critica, casi me desanimó de comprar el libro) en Book Review: “This Is How They Tell Me the World Ends” pero estaba muy bien ‘puntuado’ en diversos sitios, así que me decidí.

En uno de los capítulos se habla del tema de la seguridad en los programas informáticos y se aporta información interesante sobre la complejidad de los programas y cómo influye en su seguridad (y en nuestra capacidad de estar seguros de que no hacen algo malo, si los examinamos). Tradicionalmente se ha dicho (es fácil encontrar referencias) que la complejidad hace más difícil asegurar los programas. En este caso se habla de una complejidad muy sencilla (el tamaño) y aún así, se ve que la cosa no pintaba bien.

En particular se habla de Penetrate, Exploit, Disrupt, Destroy: The Rise of Computer Network Operations as a Major Military Innovation que se puede descargar en PDF.

Allí se describen los experimentos CHAPERON 1 y CHAPERON 2, como ejercicios para determinar si era posible diseñar aplicaciones seguras. También si era posible que alguien insertase código malicioso en una aplicación sin que los defensores pudieran detectarlo. Nos cuentan como se diseñaron dos equipos (atacantes y defensores). Estos últimos, sabiendo que algo peligroso había, debían encontrarlo. En el primer experimento, uno de los atacantes implantó dos trozos de código malicioso, que nadie encontró.

In time, based on the knowledge he acquired examining software/hardware interfaces and the residual vulnerabilities the use of microelectronics and microcontrollers engender, Gosler convinced Sandia management to perform proof of principle technical studies that came to be known as the CHAPERON 1 and CHAPERON 2 exercises. The premises of the CHAPERON exercises were simple: Can a person design a secure application? Can a person insert malicious constructs that are not detected even through detailed evaluation? Two groups were created as part of the study: Group 1 was designated as Subverters and Group 2, which consisted of two subteams of evaluators, was responsible for uncovering the subversion. As a practical matter, the design of the exercise purposefully provided all advantages to the Evaluator: The subverter would inform evaluators that one or two vulnerabilities were placed in a system, within certain parameters and constraints, and provide them comprehensive system documentation. Gosler was designated as a subverter and immediately set out to undermine a specific security-critical application. As part of the study, he created a “Guideline for Subversive Software Development” to outline principles for subversion design and implementation, which included prohibitions against the use of extraneous code: Any code utilized must have a justifiable reason for being a part of the system, and the subversive design could not compromise the encryption algorithm. Through a painstaking trial-and-error process, Gosler developed and implanted two subversions in the system which none of the evaluators were able to find: (1) the insertion of Zork text which revealed secret system variables, and (2) another subversion.

Tanto es así, que mostrar los fallos y explicarlos llevó un buen número de horas. La segunda parte del experimento se diseñó con más limitaciones (692 líneas de lenguaje máquina) y sólo uno de ellos pudo encontrar el nuevo problema.

The Sandia evaluation team spent several months examining the doctored system, to no avail. In fact, it took three 8-hour-long days of briefing the evaluators on how the subversive design worked. Gosler initially planned to train future Sandia evaluators to uncover the more complicated subversion using the CHAPERON 1 exercise as a teaching tool, but the subversion he created was so complicated that no one could solve it and led the evaluators to become extremely frustrated. This required the creation and development of the CHAPERON 2 exercise, which was designed to be less complex. 423 Sandia employee Tom Barger created the follow-on exercise as the subverter, which was severely limited to 692 machine-level instructions. Close to 100 people were given an opportunity to be evaluators of the subversion, but only Gosler successfully identified the exploit (although a couple other evaluators came very close to discovering the exploit), which was a spoofed code execution sequence embedded in a particular machine instruction.

Así las cosas, y ya teorizando, se preguntaban cuántas líneas de código podria tener un programa para estar razonablemente seguros de que hacía lo que se suponía que tenía que hacer. Los que no conocían el experimento hablaban de 10000.

The CHAPERON 2 exercise came to the attention of Rick Proto, and Robert Morris Sr., Chief of Research and Chief Scientist at NSA National Computer Security Center respectively (among others in the IC), who thought these exercises were insightful and could be helpful. Upon meeting, Gosler asked Morris, “How complex can software be for you to have total knowledge of what it would do?” Morris replied, “100% confident at 10,000 machine level instructions or less. We would have no confidence at more than 100,000 machine level instructions.” Immediately after this interaction, Gosler shared the subversion he created for the CHAPERON 1 exercise with Morris and Proto. Clearly, the implications of what Gosler achieved in the CHAPERON exercises was not lost on NSA technical leadership, and their assumptions about their abilities to detect subversions in computer hardware and software interfaces would need to be adjusted accordingly.

Después de esto, la NSA pudo ver que con sus recursos no tenía capacidad para cumplir con su cometido y empezó a contratar más personal, pero esto ya es otra historia.