Aleatoriedad y bloqueos en el kernel de Linux

 La suerte (?) En esta ocasión traemos una entrada un poco técnica que habla de aleatoriedad. Se trata de Really fixing getrandom() y habla de las herramientas disponibles en el núcleo de Linux para generar aleatoriedad.

Es un tema que parece que se ha discutido con amplitud:

The final days of the 5.3 kernel development cycle included an extensive discussion of the getrandom() API and the reversion of an ext4 improvement that was indirectly causing boot hangs due to a lack of entropy.

Y los problemas venían del bloqueo de getrandom() cuando en el sistema no había entropía suficiente:

The root of the problem in 5.3 was the blocking behavior of getrandom(), which will prevent a caller from proceeding until enough entropy has been collected to initialize the random-number generator.

No son cambios que se puedan hacer de cualquier forma, porque hay sistemas que confían en que estas funciones se comporten adecuadamente:

This behavior was subjected to a fair amount of criticism, and few felt the need to defend it. But changing getrandom() is not easy; any changes that might cause it to return predictable “random” numbers risks creating vulnerabilities in any number of security-sensitive applications.

Para evitar este bloqueo, se proponía asegurarse de que habría suficiente entropía para evitar los bloqueos.

There is another way to ensure that getrandom() doesn’t block during the bootstrap process: collect enough entropy to ensure that the random-number generator is fully initialized by the time that somebody needs it.

Una posibilidad era utilizar los mecanismos de la CPU cuando estuvieran disponibles:

If the CPU has a hardware random-number generator, that can be used; some people distrust this solution, but mixing entropy from the hardware with other sources is considered to be safe by most, even if the hardware generator is somehow suspect.

Aunque esto no siempre es posible.

También se podría emplear una función que lee valores del contador de tiempos:

On most architectures, random_get_entropy() just reads the timestamp counter (TSC) directly. The TSC increments for every clock cycle, so two subsequent calls should always return different values. Just how different they will be, though, is where the unpredictability comes in.

Y luego añadir un temporizador que expire los valores, de forma que todo sea un poco más complejo y, por lo tanto, menos predecible:

The timer declared above is armed to expire in the near future (the next “jiffy”, which be anytime between 0ms and 10ms); that expiration will happen by way of an interrupt and may occur on a different CPU.

Se calcula que esto añade un bit de entropía en cada expiración:

In other words, every time the timer expires, the entropy pool is deemed to have gained one bit of entropy.

Si el sistema espera al arrancar podría provocar pausas apreciables:

… potentially just over one second on a system with a 100HZ tick frequency — if the system in question has no other sources of entropy. That could result in a perceivable pause during the boot process, but it is far better than blocking outright.

En definitiva, un artículo que se siguen bien para un problema interesante al que no siempre prestamos la debida atención. o

Posteriormente se ha publicado Removing the Linux /dev/random blocking pool continuando con el debate, aunque en términos ya menos técnicos.

Scrapping con Google Sheets. Obteniendo información de la web

 Araña Entre las múltiples utilidades de GoogleSheets que uno no esperaba encontrar está la del scraping (¿’arañado’?; se trata de descargarse una página web y extraer la información que nos interese de allí. Hay muchas herramientas pero para algunas cosas pueden bastarnos lo consejos que aparecen en Web Scraping with Google Sheets: The Definitive Guide.

Esencialmente nos da pistas para manejar tablas, listas, información en XML y alguna cosilla más. Todo ello sin demasiado esfuerzo.

¿Puedo tener problemas de seguridad utilizando Python? Puedo tener problemas de seguridad utilizando Python

Serpiente No se suele hablar mucho de la seguridad en los lenguajes que se consideran más o menos seguros. Nada hay como el C y otros para meter la pata y tener problemas; pero eso no impide que tengamos que tener en cuenta algunas cosas y de eso hablaban en 10 common security gotchas in Python and how to avoid them.

Empieza hablando de que cuando aprendemos a programar aprendemos cómo se supone que debe usarse un lenguaje o lo que sea; sin embargo, cuando hablamos de seguridad tenemos que cambiar a pensar en cómo podría ser usado para conseguir algo malo.

… you learn how it supposed to be used. When thinking about security, you need to think about how it can be misused

Y, claro, aunque hablemos de lenguajes seguros, algunas cosas malas siguen siendo posibles. La lista:

  • Inyección de entrada
  • Problemas al analizar XML
  • Instrucciones ‘assert’
  • Ataques basados en el tiempo
  • Paquetes maliciosos o el lugar desde donde se importan
  • Ficheros temporales
  • Problemas al cargar ficheros YAML
  • Datos serializado
  • Problemas del entorno Python por no estar actualizado
  • Problemas por no tener actualizadas las dependencias

Como puede verse, algunos son bastante específicos (aunque casi todos aplicables a diversos lenguajes) pero otros son completamente genéricos.

En todo caso, un buen repaso generalista.

Sobre aprender a programar y la frase 'independiente del lenguaje'

Sobre programación En We Should Stop Saying ‘Language Independent.’ We Don’t Know How To Do That una nota interesante sobre la famosa frase ‘independiente del lenguaje’ y cómo el lenguaje en el que aprendemos nos influye.

Habla de la investigación de Allison Elliott Tew y Miranda Parker sobre estudiantes de programación con diferentes lenguajes y cómo los errores que se comenten en unos se parecen más a algunos otros que a la generalidad:

Notice that the most common wrong answer is exactly the same. The 2nd most common wrong answer in Java is idiosyncratic (which is interesting), but the 2nd most common wrong answer for both MATLAB and Python is the 3rd most common wrong answer for Java. The 4th most common wrong answer for Java is the same as the 5th most common wrong answer for Python. We didn’t see that wrong answer in MATLAB, but surprisingly, there were only 4 wrong answers for MATLAB.

Lo que dice el autor es que tenemos lenguajes diferentes porque creemos que eso tiene algún valor (marca alguna diferencia).

We have different languages because we think that those differences make a difference. For an assessment to be language independent, it would have to be measuring something deeper than those differences.

Interesante.

Almacenamiento de información sobre nuestra navegación: cookies y LocalStorage

Galletas Un artículo técnico pero no demasiado sobre cómo almacenan información los navegadores: Cookies vs. LocalStorage: What’s the difference?.

Todos hemos oido hablar de las ‘cookies’ (de manera irremediable por la absurda regulación sobre los avisos y esas cosas que tanto dolor causan en nuestra navegación diaria). No es tan habitual haber escuchado hablar de ‘LocalStorage’, otro sistema de almacenamiento de información (siempre local, otra cosa es lo que se haga con esa información después, claro).

Sobre las cookies, lo de siempre: un poco de información que se utiliza principalmente para hacer seguimiento de nuestra navegación mediante algún tipo de identificador que se nos asigna.

So, what are cookies? According to whatarecookies.com, they are small text files that are placed on a user’s computer by a website.

Que las hay persistentes y de sesión, las primeras tienen fecha de caducidad y las segundas expiran en cuanto cerramos la ventana del navegador (o la pestaña, o lo que sea). Las persistentes quedan almacenadas en nuestro sistema y son las que permiten que no tengamos que identificarnos una y otra vez en los sitios que usamos habitualmente.

Sobre LocalStorage, se trata de un mecanismo introducido con HTML5, que tiene la ventaja de que no es necesario que viaje de un sitio para otro en nuestra navegación en cada enlace que pinchamos (está orientado a almacenar información localmente).

This is because data is stored on the user’s local disk and is not destroyed or cleared by the loss of an internet connection.

Para repasar.