Sobre inclusión más segura de contenidos con iframes

Enmarcado La utilización de frames es vieja en la red: permite incluir contenido de otros sitios en nuestra página y es un mecanismo que algunos servicios ofrecen como el habitual para este cometido.

Nowadays, old-school (Netscape style) frames have fallen out of fashion, but iframes are more popular than ever. They’re used for advertising, social plugins (e.g. Facebook “like” buttons and “Share on Twitter” functionality), webpage widgets, and so on.

En You’ve Been Framed! A survey of iframes and the sandbox attribute se comenta sobre estas técnicas y su prevalencia, así como el atributo sandbox, que permite controlar políticas de seguridad sobre contenido incrustado en nuestra web:

Just how popular are iframes? Not all websites have them but those that do tend to have quite a lot. To find out, I recently crawled the top ranking sites on the web and counted the iframes. Most iframes are dynamically generated by javascript, so you need to use a crawler which evaluates js. I wrote about the method I used in a follow-up post.

72% of the Alexa top 5000 sites have iframes on their landing pages. Of those, each has on average 7.1 iframes. Some sites have well over 50 frames.

Of all these 25,849 iframes on the top 5000 sites, only 10 use the HTML5 sandbox security attribute. That’s a whopping 0.04%! We’ll learn more about this attribute in a bit.

Examining the top 50 sites, there are a lot fewer iframes. But no one is using the aforementioned sandbox attribute. Of the top 1000, only two sites employ it.

Los riesgos son, esencialmente, que alguien saque partido de estar en nuestra página web al estar integrando contenido que está fuera de nuestro control:

However, external content is completely beyond your control. It can control the browser and the user experience to a degree. Unrestricted iframes can run javascript, Flash and other plugins, open pop-up windows, and even navigate from the containing page. If the site is just intended to display an ad or social button, does it really need to be able to do all (or even any) of these things?

En sitios de perfil alto esto no debería ser un problema (pero mejor no fiarse) pero nunca sabemos lo que puede pasar con otros sitios: esos botones tan chulos que proporcionaba alguien y que, en algún momento, no puede seguir con el servicio, abandona el dominio y es utilizado por otra persona.

En Play safely in sandboxed IFrames se habla un poco más del marco general (principios básicos de seguridad, mínimo privilegio y compartimentalización) y se explica la forma de incluir iframes de forma más segura:

The sandbox attribute of the iframe element gives us just what we need to tighten the restrictions on framed content. We can instruct the browser to load a specific frame’s content in a low-privilege environment, allowing only the subset of capabilities necessary to do whatever work needs doing.

Algunas técnicas contra el análisis de ejecutables

Pantalla En Jugando con técnicas anti-debugging José Manuel Fernández hace una panorámica de las ténicas anti depurado que utilizan los programas maliciosos para evitar que su detección y análisis.

En particular en esta entrada hablaba de la función IsDebuggerPresent.

En Jugando con técnicas anti-debugging (II) comenta sobre el campo NtGlobalFlag.

Finalmente, en Jugando con técnicas anti-debugging (III) se habla de las técnicas basadas en tiempo (un programa ejecutándose en condiciones normales no debería tardar más de … Si tarda más, a lo mejor alguien lo está ejecutando paso a paso, o haciendo algo ‘indebido’ con él). En este caso la función es GetTickCount().

Como bola extra, la lectura recomendada de [PDF] The ultimate Anti-debugging Reference y los programas utilizados como ejemplo en reverc0de/saw-anti-debugging. Muy interesante.

SSL para todos en CloudFare y la escala

Candados Uno de los problemas e utilizar SSL (TLS hoy en día) es el coste computaional: con muchas visitas las conexiones cifradas pueden ser un sobrecoste que no estemos dipuestos a asumir.

En Universal SSL: How It Scales Nick Sullivan de CloudFlare nos habla de su proyecto (ya tiene más de un año) de proporcionar HTTPS para todos los sitios albergados por ellos (que es una decisión a la que parece que se está dirigiendo mucha más gente cada vez) y hablan de este sobrecoste:

People have asked us, both in comments and in person, how our servers handle this extra load. The answer, in a nutshell, is this: we found that with the right hardware, software, and configuration, the cost of SSL on web servers can be reduced to almost nothing.

Alguno de los trucos está basado en cuestiones como retomar sesiones:

For returning visitors of a site we have a shortcut that eliminates the need for our servers to perform these expensive operations. The shortcut is called session resumption and it’s built into the TLS specification.

Otras medidas utilizadas son el Lazy Loading:

Lazy loading of certificates helps relieve that bottleneck. Using custom modifications to nginx by CloudFlare engineer Piotr Sikora, we are able to dynamically load certificates into memory only when they’re needed. Now, if one site changes their certificate, the server does not have to reload every certificate. This change allows our servers to scale up to handle millions of HTTPS sites.

Todo ello combinado con algoritmos modernos (Criptografía de curvas elípticas, ECDSA) y hardware actualizado:

All Intel CPUs based on the Westmere CPU microarchitecture (introduced in 2010) and later have specialized cryptographic instructions.

Desbordamientos de enteros recientes

Agua desbordando Me repito. Pero cuando salen fallos de seguridad relacionados con los temas típcos no podemos dejarlos pasar sin comentarlos. En este caso se trata de desbordamientos de enteros (lectura clásica recomendada: Basic Integer Overflog).

El primero se trata de un desbordamiento de enteros en `strncat’ Integer overflow in strncat.

I didn’t look into the details but it looks like strncat(s1, s2, n) misbehave when n is near SIZE_MAX, strlen(s2) >= 34 and s2 has specific offset.

Hay algunos comentarios interesantes en Integer overflow in glibc strncat donde no queda claro del todo si es fallo o característica, pero vale la pena leerlos, sobre todo si nos gusta o no sinteresa el lenguaje C.

Por otro lado, leíamos el otro día en Desbordamiento de entero en PuTTY y en PuTTY vulnerability vuln-ech-overflow sobre un desbordamiento de enteros en PuTTY. En este caso el atacante debería ser capaz de insertar una secuencia de escape sofisticada que afectaría a una variable que almacena el número de caracteres que hay que borrar en determinadas condiciones.

The vulnerability arises because PuTTY uses signed integer variables to hold the number of characters to be erased and doesn’t adequately check for overflow. This means that by passing a very large parameter to ECH, an attacker could cause check_boundary to inspect memory outside the terminal buffer.

Lecciones aprendidas desarrollando GitHub pages

Crecimiento GitHub Pages Recientemente se ha cumplido un año que estamos escribiendo en este sitio Cuata Etapa. Me viene bien recordarlo porque recientemente leíamos Eight lessons learned hacking on GitHub Pages for six months en el que nos cuentan algunos principios generales aprendidos desarrollando el servicio.

El primero de ellos (previo, más bien) es ser usuario de tu propio servicio para conocerlo bien, conocer sus virtudes, encontrar sus defectos…

Y luego la lista:

  • Test, test, and then test again

Desarrollo basado en pruebas, para estar seguros de que cuando se introducen cambios nada va a fallar.

  • Use public APIs, and when they don’t exist, build them

En la línea del principio ‘previo’ no utilizar componentes secretos o privados y si se detecta la necesidad de algo que no existe, ponerlo a disposición de los usuarios.

  • Let the user make the breaking change

Permitir a los usuarios que controlen los cambios importantes que pueden afectar a sus sitios.

  • In every communication, provide an out

Cuando se comunican los errores se informa al usuario no sólo del problema sino también de dónde tiene que mirar para solucionar el fallo.

  • Optimize for your ideal use case, not the most common

No hay que olvidar que el servicio es para dar a conocer los proyectos. Eso debería ser lo más fácil de hacer, independientemente de lo que la gente esté haciendo.

  • Successful efforts are cross-team efforts

Como tantos proyectos, no son cosa sólo de un equipo que se encarga de ellos, sino que, seguramente, hará falta hablar y trabajar con otros equipos.

  • Match user expectations, then exceed them

Que los usuarios tengan lo que esperaban del proyecto, pero mejor. No hay mucho que añadir aquí.

  • It makes business sense to support open source

Una parte de su producto está basado en Jekyll, que es software libre y que ha ganado su propio espacio como producto independiente, que siguen apoyando y en el que siguen participando.