Buenas prácticas en criptografía

Billetería y caja

Es fácil encontrar información sobre criptografía y su uso, pero no lo es tanto encontrar información actualizada: un algoritmo, una recomendación que era prudente y sensata hace algún tiempo puede haber dejado de serlo ya.

Por eso es bueno tener fuentes recientes y que se actualizan (al menos, mientras lo hagan). En este caso Cryptographic Best Practices con recomendacioens concretas y bastante al día de qué usar según nuestras necesidades.

Ataques de voz a asistentes conectados

Micro y Ayuntamiento

En Uncovering the unheard: Researchers reveal inaudible remote cyber-attacks on voice assistant devices nos cuentan una nueva preocupación para los que tengan asistentes basados en la voz.

La idea parece ser enviar instrucciones al dispositivo que no sean audibles para los humanos. Como todos sabemos hay frecuencias que el oido humano no puede percibir y, en este caso, usando aquellas que están cerca del espectro ultrasónico pueden atacar a estos dispositivos.

The researchers developed Near-Ultrasound Inaudible Trojan, or NUIT (French for “nighttime”) to study how hackers exploit speakers and attack voice assistants remotely and silently through the internet.

Técnicamente, nos dicen, la solución es sencilla pero es necesario conocer el ataque para adoptarla.

“The technically interesting thing about this project is that the defense solution is simple; however, in order to get the solution, we must discover what the attack is first,” said Xu.

Este tipo de ataques aprovecharían alguno de los altavoces que podemos tener conectados a internet para reproducir algunas instrucciones que podrían desencadenar alguna autorización para poder hacer cosas más ‘interesantes’. Y quien dice un altavoz conectado a internet dice un altavoz que usamos en una videoconferencia, o escuchando un vídeo de YouTube y otras situaciones similares.

“If you play YouTube on your smart TV, that smart TV has a speaker, right? The sound of NUIT malicious commands will become inaudible, and it can attack your cell phone too and communicate with your Google Assistant or Alexa devices. It can even happen in Zooms during meetings. If someone unmutes themselves, they can embed the attack signal to hack your phone that’s placed next to your computer during the meeting,” Chen explained.

Cuidado.

Un desbordamiento de enteros de 40 segundos

Cohete Arianne

En How a single line of code brought down a half-billion euro rocket launch la historia del lanzamiento en 1996 del cohete Arianne 5 y su explosión 40 segundos después del lazamiento.

Just 40 seconds after take-off, however, huge chunks of metal and burning fragments of Ariane Flight 501 are crashing down over the launch area. A shocking disaster for the ESA and a rough setback for the mission.

¿El problema? Un trozo de código, que provenía de la misión Arianne 4 y que ni siquiera se utilizaba.

The cause? A simple, and very much avoidable coding bug, from a piece of dead code, left over from the previous Ariane 4 mission, which started nearly a decade before. Here’s what happened exactly.

El problema se debió a un fallo típico de desbordamiento pero de los que ni siquiera se suele hablar mucho: cuando se convierte un número real de 64 bits en uno de 16 bits con signo.

To achieve this, the guidance system converts the velocity readings, from 64 bit floating point to 16 bit signed integer.

Si hacemos las cuentas, con 16 bits podemos almacenar cualquier número entre 0 y 65535 sin signo, y entre -32768 y 32767 si contemplamos números con signo.

With 16-bit unsigned integers, you can store anything from 0 to 65,535. If you use the first bit to store a sign (positive/negative) and your 16-bit signed integer now covers everything from -32,768 to +32,767 (only 15 bits left for the actual number). Anything bigger than these values and you’ve run out of bits.

Por otra parte, los números reales se almacenan de manera diferente porque tṕicamente almacenan números más grandes y, además, deben gestionar la parte decimal (me gustó como lo cuentan en Examples of floating point problems, por ejemplo).

En el caso del cohete, al almacenar un número real en las posiciones reservadas para un número entero se quedó sólo con la primera parte del mismo, generando un desbordamiento de enteros.

Well, in this case, when the 16-bit signed integer was used, the conversion from float to integer wrapped around to the beginning again and finally ran into the very familiar integer overflow. Riight, so back to the rocket story.

El sistema de control detecta que los datos son inconsistentes, trata de arreglar el problema y (aquí viene el segundo problema) lanza el sistema secundario que ejecuta exactamente el mismo código.

But wait a minute, there might be a saving chance! The system is designed to have a backup, standby system, which unfortunately, runs the exact same code. It tries the same conversion, gets the same error and just 72 milliseconds later, promptly crashes.

El sistema de control da por bueno el resultado, y el cohete recibe las instrucciones incorrectas.

Sin embargo, si este sistema ya se usaba anteriormente, ¿por qué no había fallado antes? Parece que el problema en este caso era que en las versiones del cohete la velocidad era menor y, por lo tanto, no tenían este problema.

The same software was designed and used successfully on many flights previously, on the Ariane 4 rockets, which were much smaller. But the new Ariane 5 model was designed to fly faster than the systems engineers had planned when that code was originally created.

Finalmente, el código no era necesario después del despegue, así que no debería haber estado ejectutándose, pero para evitar reconfiguraciones en ese momento permitieron que ese código siguiera ejecutándose un poco más, ¡esos 40 segundos!

The worst part? The code wasn’t necessary after takeoff, it was only part of the launch pad alignment process. But sometimes a trivial glitch might delay a launch by a few seconds and, in trying to save having to reset the whole system, the original software engineers decided that the sequence of code should run for an extra… 40 seconds after the scheduled liftoff.

Ascon: criptografía ligera para dispositivos limitados

Raspberry Pi Pico

Uno de los problemas del internet de las cosas y sus dispositivos mínimos es la criptografía; al fin y al cabo, los algoritmos criptográficos suelen utilizar operaciones matemáticas costosas, que no siempre son posibles en estos aparatitos.

Tratando de aligerar el problema conocíamos la noticia de que el NIST Selects ‘Lightweight Cryptography’ Algorithms to Protect Small Devices.

Se trataría de proteger la información en estos dispositivos de capacidad escasa con algún mecanismo de lo que llaman criptografía ligera.

The chosen algorithms are designed to protect information created and transmitted by the Internet of Things (IoT), including its myriad tiny sensors and actuators. They are also designed for other miniature technologies such as implanted medical devices, stress detectors inside roads and bridges, and keyless entry fobs for vehicles. Devices like these need “lightweight cryptography” — protection that uses the limited amount of electronic resources they possess.

Los parámetros considerados eran la seguridad, claro, pero también prestaciones y flexibilidad en términos de velocidad, tamaño y utilización de la energía.

“We considered a number of criteria to be important,” McKay said. “The ability to provide security was paramount, but we also had to consider factors such as a candidate algorithm’s performance and flexibility in terms of speed, size and energy use.

El anuncio está en Lightweight Cryptography Standardization Process: NIST Selects Ascon y se trata de la estandarización de la familia de algoritmos criptográficos denominada Ascon desarrollada en 2014 por un equipo de criptógrafos de Graz University of Technology, Infineon Technologies, Lamarr Security Research y Radboud University.

Acceso a APIs, credenciales y uso desde clientes

Vías, valla y cartelería

Las APIs permiten el acceso a nuestros programas (y, al final, a los datos) de manera alternativa a la tradicional de las interfaces web o mediante programas. Últimamente veo bastantes lecturas relacionadas con la seguridad. En parte, probablemente, porque al tratarse de accesos más controlados (o aparentemente más controlados) no siempre están tan bien aseguradas como deberían.

En Quick way to Secure API Keys for the Frontend nos hablan de un problema interesante, que tiene que ver con el acceso a estas APIs a través de diversos frontales (frontends) y la gestión de las contraseñas (que pueden estar incluso en el código).

We all know that API keys and connections can not be secured on the client side of an application. Hard coding API keys on the frontend is a quick and surefire way to have your API connection shutdown, API keys stolen, and have your API provider’s bill skyrocket.

Hay formas de evitar exponer secretos de esta forma y las tres que proponen son:

  • Funciones serverless que interactúan con algún servicio que gestiona las contraseñas (por ejemplo AWS Lambda).
  • Funciones de Netlify. En este caso es un servicio, que interactuaría con el verdadero almacén (nuevamente AWS Lambda).
  • Otro servicio, KOR Connect que permite gestionar los accesos sin que las credenciales aparezcan el código de nuestro frontal.

Igual es demasiado técnico (y orientado a productos) pero creo que nos puede ayudar a pensar en las nuevas necesidades que provoca hacer las cosas de una forma determinada.