Algumos mitos sobre computación distribuida

Nasas La computación distribuida trata de sacar partido de diferentes recursos de cálculo que podemos tener a nuestra disposición. Es un modelo que tiene sus ventajas (aumento de capacidad) y sus inconvenientes (complicaciones). En Navigating the 8 fallacies of distributed computing nos habla de algunos mitos.

Los mitos:

  • La red es fiable. Las redes son complejas, dinámicas y a veces impredecibles. Hay demasiadas cosas que pueden fallar.

Networks are complex, dynamic, and often unpredictable. Many reasons could lead to a network failure

  • La latencia es cero. Mientras que en una red de área local esto puede ser cierto, en redes más amplias veremos rápidamente que no.

Latency may be close to zero when you’re running apps in your local environment, and it’s often negligible on a local area network. However, latency quickly deteriorates in a wide area network.

  • El ancho de banda es infinito. Cuando usamos la red parece que no tenemos limitaciones, sin embargo, si tenemos que manejar volúmenes de datos importantes, encontraremos rápidamente las dificultades.

… the capacity of networks is not infinite (partially because our appetite for generating and consuming data has also increased). When a high volume of data is trying to flow through the network, and there is insufficient bandwidth support, various issues can arise…

  • La red es segura. Nuevamente, muchas cosas pueden fallar: fallos, vulnerabilidades, ataques, …

There are many ways a network can be attacked or compromised: bugs, vulnerabilities in operating systems and libraries, unencrypted communication, oversights that lead to data being accessed by unauthorized parties, viruses and malware, cross-site scripting (XSS), and DDoS attacks, …

  • La topología no cambia. La forma en que se conectan los equipos y las redes entre sí es algo más o menos permanente, menos cuando no lo es: fallos, accidentes, … pero también reconfiguraciones y rediseños.

In a nutshell, network topology refers to the manner in which the links and nodes of a network are arranged and relate to each other. In a distributed system, network topology changes all the time. Sometimes, it’s for accidental reasons or due to issues, such as a server crashing. Other times it’s deliberate — we add, upgrade, or remove servers.

  • Hay un administrador. Si el sistema es muy pequeño, puede ser cierto (y también que no haya ninguno). En cualquier sistema un poco más grande las posibilidades aumentan.

There might be only one administrator in the case of a very small system, or perhaps in the context of a personal project. Beyond that, there is usually more than one administrator of a distributed system in nearly all real-life scenarios.

  • El coste de transporte es cero. Vivimos en la ficción de que el coste de enviar información por las redes es cero. Sin embargo, la infraestructura tiene coste, los aparatos también y luego hay que gestionar y mantener esos recursos.

First of all, networking infrastructure has a cost. Servers, network switches, load balancers, proxies, firewalls, operating and maintaining the network, making it secure, not to mention staff to keep it running smoothly — all of these cost money. The bigger the network, the bigger the financial cost.

  • La red es homogénea. Esto no es cierto ni en una red doméstica. En muchos casos las redes van creciendo de forma casi orgánica, con sistemas diferentes, protocolos, etc.

Often, not even your home network is homogenous. It’s enough to have just two devices with different configurations (e.g., laptops or mobile devices) and using different transport protocols, and your network is heterogeneous.

Como conclusión, lo que anticipábamos arriba: construir sistemas distribuidos es difícil.

A brief conclusion: building distributed systems is hard

Un caso real de un generador de contraseñas malas y cómo hacerlo bien

Generador Siempre recomendamos utilizar un gestor de contraseñas. Y aprovechar la función de generación de contraseñas. Generar buenas claves es un problema difícil, de todas formas, si nos fijamos en Kaspersky Password Manager: All your passwords are belong to us.

Allí nos cuentan algunos problemas que tenía su generador, que serán familiares para quien lea por aquí de vez en cuando:

  • Utilizaban un generador de números aleatorios no criptográfico.
  • La fuente de entropía era la hora (en segundos).

The password generator included in Kaspersky Password Manager had several problems. The most critical one is that it used a PRNG not suited for cryptographic purposes. Its single source of entropy was the current time. All the passwords it created could be bruteforced in seconds.

El artículo explica cómo hacer un buen generador. Incluye código de ejemplo y buenos consejos, con la base en un caso real.

Desarrollo de criptografía para no especialistas

Candados y cintas rojas En Cryptography is not Magic hablan sobre el tema de diseñar sistemas criptográficos y programarlos.

Trata de atraer a más desarrolladores a la materia porque, afirma, los consejos habituales hacen que alguna gente se eche para atrás.

Sin embargo, nos dice, la realidad es que programar primitivas criptográficas requiere poco conocimiento sobre criptografía. Lo más delicado sería la elección de cuales (por aquello de no elegir algún método obsoleto).

Perhaps surprisingly, implementing cryptographic primitives & protocols requires little cryptographic knowledge. Choosing what to implement is more delicate (you need to know the state of the art), but once you’ve made your choice, your only worries are side channels and correctness.

Nos habla sobre los canales laterales y remarca que la idea fundamental es no permitir el flujo de datos hacia ellos. La mayoría pueden ser ignorados sin demasiados problemas (energía, emisiones electromagnéticas, …) pero que nunca hay que olvidar los relacionados con el tiempo.

Side channels have one rule: don’t let any data flow from secrets to that channel. Interesting side channels include timings, energy consumption, electromagnetic emissions… Most can be ignored most of the time (energy consumption for instance requires physical access), except timings. Never ignore timings, they’re part of most threat models.

Sobre la corrección, nos avisa de su importancia: cualquier error hará que nuestro sistema sea inadecuado.

Then we have correctness. The slightest error may throw cryptographic guarantees out the window, so we cannot tolerate errors. Your code must be bug free, period. It’s not easy, but it is simple: it’s all about tests and proofs.

Sobre el diseño de protocolos dice que si el desarrollo criptográfico es tedioso, el diseño de protocolos es delicado.

That’s where things become interesting. Where implementing crypto was mostly tedious, designing protocols is delicate. One is not necessarily harder than the other, but they’re very different.

Habla de las amenazas para recordarnos que una vez que conocemos a las que se enfrentan nuestros casos de uso (threat model) es necesario demostrar que el protocolo las maneja adecuadamente.

Once you know your threat model, you need to demonstrate that your protocol addresses it.

Termina diciendo que desarrollar nuestra propia criptografía no es sencillo. Es fácil equivocarse, pero eso no significa que no pueda hacerse

I won’t sugar coat it, rolling your own crypto is not easy. Mistakes are easy to make, and the stakes are often high — getting it wrong can even get people killed. Don’t rush it, and if you can, seek guidance and feedback. Some communities are very welcoming.

En mi opinión, no es un campo donde yo me desenvolvería a gusto. Pero, tal vez, una aproximación más activa nos ayudaría a aprender y a mejorar.

Ataques a los datos de entrenamiento de inteligencias artificiales

Calentando Solemos decir que tomamos decisiones basadas en los datos. El problema que surje con esto es cuando nuestros datos no reflejan adecuadamente la realidad. En el mundo de la inteligencia artificial esto podría ser un problema, tal y como nos cuentan en Data poisoning in action.

Si podemos introducir errores en los modelos que se utilizan para entrenar las inteligencias artificiales, podremos causar problemas:

Data poisoning attacks compromise the integrity of machine learning models by injecting incorrect data in their training set.

Se trata de modificar un conjunto de datos de los que se emplean en el entrenamiento, para lograr que el resultado sean predicciones incorrectas.

A data poisoning attack aims to modify a training set such that the model trained using this dataset will make incorrect prediction

El objetivo es degradar el modelo obtenido (en el entrenamiento o cuando se le alimentan nuevos datos para volver a entrenarlo). Estos ataques podrían tener un efecto duradero, porque comprometen la integridad del modelo y le hacen cometer errores de manera consistente. Una vez comprometido, recuperar el sistema es un problema de solución no trivial.

Poisoning attacks have a long-lasting effect because they compromise the integrity of the model and cause it to make consistent errors at runtime when making predictions. Once a model has been poisoned, recovering from the attack at a later date is a non-trivial procedure.

Como ejemplo, nos habla de lo que sucedería si en un modelo orientado a detectar pedidos fraudulentos (y que, lógicamente, se entrenará con pedidos reales anteriores). Podría contaminarlo realizando una serie de pedidos y luego pagando algunos y otros no, con lo que podría conseguir degradar la capacidad de predicción.

The model should be able to predict whether a placed order will be paid for ( legitimate ) or not ( fraudulent ) based on information about the given order. The training set for this model consists of details contained in historical orders placed on the website. In order to poison this training set, an attacker would pose as a user or users of the site and place orders. The attacker pays for some orders and doesn’t pay for others such that the predictive accuracy of the model is degraded when it is next trained.

Hay dos formas de contaminar estos datos:

  • Inyección de datos, tal y como decíamos arriba.

Data injection: by injecting new data in the training set, as illustrated above with the attacker creating new orders. This new data can be synthetic in nature.

  • Cambio de etiquetas. Esto es, se trata de cambiar los valores que asigna el modelo a algunos datos.

Label flipping: by changing labels of existing real data in the training set.

Si conocemos el modelo utilizado y los datos que se utilizan para entrenarlo, se podría ir más allá, sintentizando (generando) datos que podrían optimizar el proceso de contaminación.

Given some knowledge about the model and its training data, an attacker can generate synthetic training data points that will optimally degrade the accuracy of the model.

Como defensa, se pueden utilizar modelos lo más complejos posibles, que serán más resistentes y robustos frente a los ataques.

In general, this means that complex models (models having a high capacity) are more resilient than simple models to DoS poisoning attacks, they require more poisoning data points to be compromised, and it is difficult to decrease their accuracy as a whole.

Muy interesante. Cada vez que hagamos un sistema automático, alguien intentará hacer que se comporte de manera diferente a la prevista.

Sobre la verificación en tiempo de ejecución del kernel de Linux

Vigilantes En [RFC PATCH 00/16] The Runtime Verification (RV) interface un texto sobre la interfaz de verificación en tiempo de ejecución del Kernel de Linux.

Se trata de un método ligero que complementa las técnicas tradicionales de verificación exhaustiva mediante el análisis de la traza de la ejecución del sistema.

Runtime Verification (RV) is a lightweight (yet rigorous) method that complements classical exhaustive verification techniques (such as model checking and theorem proving) with a more practical approach for complex systems.

Instead of relying on a fine-grained model of a system (e.g., a re-implementation a instruction level), RV works by analyzing the trace of the system’s actual execution, comparing it against a formal specification of the system behavior.

Existe un documento de referencia, que es:

DE OLIVEIRA, Daniel Bristot; CUCINOTTA, Tommaso; DE OLIVEIRA, Rômulo Silva. Efficient formal verification for the Linux kernel. In: International Conference on Software Engineering and Formal Methods. Springer, Cham, 2019. p. 315-332.

En el RFC se presenta un sistema basado en monitores que ayudan a observar el uso y cómo se genera código automáticamente. Esto ha venido motivado por el uso de Linux en sistemas críticos.

In this RFC I am still not proposing any complex model. Instead, I am presenting only simple monitors that help to illustrate the usage of the automatic code generation and the RV interface. This is important to enable other researchers and developers to start using/extending this method.

It is also worth mentioning that this work has been heavily motivated by the usage of Linux on safety critical systems, mainly by the people involved in the Elisa Project.