Automágica: durante 2017 estoy trabajando bastante en Automágica, mi software para editar libros: Más información - Posts relacionados

Coloreando código fuente en WordPress

Tengo este blog hace unos 5 años y en él tengo muchos posts con código fuente, pero nunca usé un plug-in para hacer syntax highlight o resaltado de sintáxis, es decir que las distintas partes del código fuente se pinten de distintos colores según su significado. Mi idea es solucionarlo.

El escenario es bastante complicado. Hay bloques de código en los que uso la etiqueta HTML <pre> y otros en los que uso la etiqueda <code>. También tengo código in-line (es decir líeas de código que forman parte de una oración) arcadas con la etiqueta <code>.

¿Qué busco?

  • No quiero posts con código coloreado de ahora en adelante y que los anteriores sigan en blanco y negro.
  • No quiero tener que editar cada posts para agregar algún atributo en las etiquetas pre o code. Por ejemplo, muchos plug-ins te piden que marques el código con algo como <pre lang="python"> o similar.
  • Quiero que los bloques de código <pre> y <code> se vean igual.

Luego de buscar un poco, decidí instalar y probar estos plug-ins:

  • WP-SynHighlight (lo descarté enseguida, tiene una GUI pesada con muchas opciones y las marcas que introduce en el post son bastante poco estándar e intrusivas)
  • WP-Syntax (usa GeSHI, por lo que el coloreado se realiza en el lado del servidor)
  • JQuery.Syntax (hecho con la popular librería de JavaScript)
  • Google Code Prettify (está basado en tecnología de Google y posiblemente lo hayan visto en acción en StackOverflow. Su principal ventaja es que no requiere decirle en qué lenguaje está escrita la porción de código, sino que este lo adivina)

Intentar empezar a usar uno de estos plug-ins ahora, me genera un gran problema

de compatibilidad hacia atrás :)

Veamos... WP-SynHighlight no me gustó de arranque. Modifica la GUI del editor WYSIWYG the WordPress, uno selecciona una porción de código, aprieta el botón y te da unas 10 opciones para elegir (desde lenguaje hasta el número de espacios para los tabs). Puede funcionar para algún tipo de usuario, pero no para un programador. Además agrega bastante código sucio al HTML del post. Paso.

El segundo que probé fue WP-Syntax. Me gustó mucho, entre otras cosas:

  • Usa CSS in-line para que el código coloreado se mantenga incluso si el posts no es leído en el blog; por ejemplo en un planeta o por RSS.
  • Si el texto es más ancho que la página, agrega una barra de desplazamiento en la cajita de código.

Luego probé JQuery.Syntax y Google Code Prettify. Estos funcionan de la siguiente forma: luego de que se carga el HTML del sitio, corre código JavaScript que se encarga del coloreado. Esto hace que la carga de la página sea más lenta.

¿Qué hice?

Me decidí a usar WP-Syntax y para no editar todos los bloques de código, creé un pequeño plug-in para WordPress que cambia todos los <pre> por <pre lang="python" escaped="true">, cambié a mano los pocos bloques code que tenía por bloques pre y agregué a mano la especificación para los bloques de código que no son Python (no eran muchos).

Tampoco tengo coloreado del código in-line. De las opciones que probé solo el plug-in que usa tecnología de Google, tenía esta característica.

Si ven algún post en el que algo no quedó del todo bien, avisen!


Diccionario bidireccional en Python

Bidirectional dict o Injective mapping es una estructura de datos muy útil.

Por lo general cuando usamos un diccionario o tabla hash, tenemos un valor asociado a una clave:

>>> d = {1:'uno', 2:'dos'}

>>> d[1]

'uno'

Pero algunas veces también resulta útil indexar por el valor y obtener la clave.

>>> d['uno']

1

Por ejemplo, en un programa tengo un archivo de configuración que contiene un diccionario dónde las claves son strings de 3 caracteres representando un edificio ('SFE', 'GDP', ...) y las claves números de puerto (5007, 5008, ...). En algunas partes el programa requiere conocer el edificio a partir del número de puerto y en otras el puerto a partir del edificio.

¿Cómo obtenemos este comportamiento?

Pregunté en StackOverflow y si bien me apuntaron a una implementación, la solución que más me gustó fue esta:

>>> d.update( dict((d[k], k) for k in d))

Así se ve d ahora:

{1: 'uno', 2: 'dos', 'uno': 1, 'dos': 2}

Y podemos efectivamente indexar por clave o por valor:

>>> d[1]

'uno'

>>> d['uno']

1

Advertencias

No se pueden usar objetos mutables

En los diccionarios de Python solo objetos inmutables pueden ser clave de diccionarios, por lo tanto, en nuestro diccionario bidireccional, tanto las claves como los valores deberán serlo.

Actualizaciones

Otra limitación de este enfoque son las desincronizaciones que puede sufrir al modificar el bidict luego de realizar la transformación; hay que tener cuidado!

  • Luego de agregar un nuevo elemento debemos volver a ejecutar la línea mágica para que cree la entrada inversa.
  • No podemos agregar un par que tenga como clave algo que ya existía como valor o que tenga como valor algo que ya existía como clave.
  • Si borramos una entrada, hay que también borrar su inversa.

Conclusión personal

Como les contaba antes, yo estaba usando el diccionario original en un archivo de configuración, por lo que no toco la estructura de datos durante la ejecución del programa, así que esta solución compacta y elegante... como dijo el filósofo: me viene al pelo!

Espero a alguien más le sirva.



Pilas y colas en Python

La forma más directa de tener pilas y colas en Python es usando listas, una de las poderosas estructuras de datos que vienen con el lenguaje.

Una pila es una estructura de datos secuencial en la que el último elemento insertado es el primero en retirarse (LIFO) y puede implementarse directamente con los métodos append y pop.

Una operación común en las pilas es top, que devuelve el elemento en el tope de la pila, pero sin quitarlo; esta operación se puede emular indexando por -1.

>>> pila = [6,7,8]

>>> pila.append(9)

>>> pila

[6, 7, 8, 9]

>>> pila.pop()

9

>>> pila.pop()

8

>>> pila[-1]

7

Implementar una cola requiere algo más. En las colas, a diferencia de las pilas, el primer valor insertado es el primero en quitarse (FIFO).

Un primer intento es implementarla con append y pop(0) que obtiene el primer elemento (o con insert insertando al principio y pop). Pero las listas de Python, si bien están optimizadas para insertar al final y quitar del final, no lo están para insertar al principio o quitar del principio. La solución es utilizar collections.deque que si está implementada con estas operaciones optimizadas.

>>> from collections import deque

>>> cola = deque([1,2,3])

>>> cola.append(4)

>>> cola

deque([1, 2, 3, 4])

>>> cola.popleft()

1

>>> cola.popleft()

2

>>> cola

deque([3, 4])


Asimov sobre Inteligencia Artificial

En El monstruo subatómico, un libro de difusión, Isaac Asimov habla sobre Iteligencia Artificial. Hace más o menos dos años que lo leí y tenía la intención de transcribir el artículo para que esté disponible en Internet. Casi lo olvidé, hasta que hoy alguien lo mandó en la lista de PyAr. Copio y pego a continuación.

Capítulo 11

Más pensamientos acerca del pensamiento

Podés leerlo en http://www.librosmaravillosos.com/elmonstruosubatomico/capitulo11.html

Gracias a Diego Avendaño, Patricio Barros y Antonio Bravo.


Cómo cambiar el puerto de salida por defecto de ssh

Si en una terminal tipeamos:

ssh user@domain.com

el cliente ssh intentará contactarse al puerto 22 de domain.com. Cómo cambiamos ese puerto?

ssh -p 2222 user@domain.com

Pero qué pasa si no tenemos acceso a cambiar ese parámetro? Puede pasarnos esto? Sí, por ejemplo si accedemos a un repositorio cvs por ssh; cuando ejecutamos uno de los comandos cvs, el tunel ssh se hace sin que nos demos cuenta. Si el servidor al que nos queremos conectar escucha en un puerto distinto al por defecto, tenemos un problema.

Hoy no me acordaba cómo se configuraba esto y resultó bastante tedioso buscarlo en Internet (todas las respuestas a la búsqueda era sobre como cambiar el puerto en el que un servidor ssh escucha). Lo dejo aquí para futuras referencias.

La forma de configurar un puerto por defecto para un cliente ssh en GNU/Linux es editando el archivo .ssh/config y añadiendo la línea:

Port NNNN

dónde NNNN es el número de puerto.



Talk: Taint Mode for Python via a Library (slides)

These are my slides for the presentation Taint Mode for Python via a Library I gave in OWASP App Sec 2010 in Stockholm last 24th of June. The organizers will be publishing some media (photos and video) from the talk.

This presentation is called A Taint Mode for Python via a Library and is a joint work of me, Juan José Conti and Alejandro Russo.

img0

Today most of the computer attacks are produced against web applications rather than to desktop applications (which requires knowledge of an specific domain) or to the operating system (which requires low level knowledge).

Attack web sites is much more easier.

The consequences of these kind of attacks can vary, for example:

Impersonate: when an attacker stills the identity of a user in in web site.

Compromise confidential data: when an unauthorized user reaches data he wasn't suppose to reach.

Denial of Service: when a resource is not available to its genuine users.

And

Data destruction.

So the attacker goal is to craft input data to gain some control over certain operations. It's important to mention here that the attacker has no control over the executed code, just over the input data.

img1

These are examples of different sensitive sinks an attacker could attack.

The attacker can manipulate the data that will be use to produce an SQL query and obtain some secret information.

…make an operating system injection and execute arbitrary commands on it

or

.... exploit an XSS vulnerability and stole a user's credentials in some web site.

img2

A way to face these problems is using Taint Analysis. Usually enforcesd

Data received from a client is considerer tainted. We can't trust in data from the outside because we don't know who generate it. May be a real user, maybe an attacker or even an attacker program.

Tainted data can be untainted by a sanitization process.

We don't want tainted data to reach sensitive sinks.

In the image you can see different sanitization processes represented with different colors. This means that data that will finish in different sinks needs to be properly cleaned for that kind of sink.

It's not the same the function you'll use to protect a page renderer against XSS than the DB against SQLI.

img3

For example, look a this chunk of data. If it's used in the where clause of an SQL query and that query says something like: delete all rows from table X where id equals to VALUE, then all the rows will be deleted. But if the VALUE is used to generate a web page, it's harmless.

Something similar happens with this code. If it's used as is it to render a web page, a message will pop-up and we'll have in front of our eyes an XSS vulnerability. Again, if the chunk of data finish in a logging process on the operating systems, it would be harmless.

img4

Taint analysis can be performed in two ways. Dynamic or static.

Dynamic analysis is usually implemented as a Monitor and have the advantage to produce less false alarms that static analysis. Its main drawbacks are the overhead produced (because the program and the monitors runs at the same time) and the need to modify the interpreter in order the achieve the desire behavior.

On the other hand, static analysis produce no overhead because it analyze the text of the program without need to run it and no modification of the interpreter is needed. A mayor disadvantage is that they usually generate more false alarms than Monitors.

Our approach is a library written in Python where no interpreter modification is needed, so we solve one of the monitors drawbacks.

img5

In order to implement Taint Analysis, several tasks need to be performed.

We need a way to identify untrusted inputs, sanitization functions and sensitive sinks. They can be marked in the source code using some syntax or described in a configuration file.

Data must be untainted after a sanitization process.

Detect when tainted data reaches sensitive sinks

And the hardest one, propagate taint information on the program

img6

I'll show you an example of what I mean with taint propagation.

Suppose a is tainted because we receive it from the outside and b is clean because it was generated inside the program. Then, a concatenated with b need to be tainted too.

We also want taint propagation to take place when we do: a eight times, get an slice of a, use a for string formatting or apply to a any of its methods.

With all these concepts in mind, we can now see the implementation details of our library.

img7

We wrap python built-in types for 2 reasons: 1) in order to add a taints attribute which contains the tags identifying the taints an object has in certain moment.

And 2) to overload its methods in order to make them work in this way: if any of the method arguments is tainted or the object that receive the message is tainted, then the resulting object should be tainted too.

It's important to mention that our implementation support tainting of different types, while other only works with strings and that we provide tags to identify different kind of taints while other only use a boolean tag: tainted or not tainted.

In addition, to improve the taint propagation mechanism we also provide taint aware functions to replace some Python built-in functions. For example, len, which applied to a string, returns its length. If the original string is tainted, the resulting integer will be tainted too.

img8

We use decorators to mark untrusted sources, sensitive sinks and sanitization functions. Decorators are a Python abstraction that let us add certain behavior to functions, methods or classes.

For example, untrusted is the decorator used to mark a function as an untrusted source. We can apply it using a regular function call or, if we have access to the definition of the function we want to decorate, using Python's syntactic sugar for this.

The behavior added by this decorator is: mark every object returned by the function as tainted; and tainted with all the possible tags. Because we don't know which kind of attack could be hidden behind it.

img9

The second kind of decorator provided let the programmer specify which elements of his programs are considerer sensitive sinks. A difference with the previous one is that here we need to explicitly say which kind of attack the sink is sensitive to. We do it providing a parameter to the decorator. In the first example, an appropriate one would be SQLI.

img10

The third kind of element we need to mark are the sanitization functions. Again, we need to specify which kind of taint they are able to clean.

These are the principal decorators but others are provided as variations of the ones presented here.

img11

Now, we'll see a little demo of a web application.

note: the example shown can be downloaded from http://svn.juanjoconti.com.ar/dyntaint/trunk/webdemo/

img12

Finally, the main conclusion of this work is that it's possible to provide a lightweight taint analysis library for python with NO interpreter modification needed.

Future works could address us to make similar implementations in other languages and evaluate it in popular web applications; in order to achieve this, the library must be integrated with some web frameworks or in a platform like Google App Engine.

img13

More information on the library can be found in the presented paper. It can be downloaded from the author's web sites.

img14


location update: Freiburg, Alemania

El 26 dejé Gotemburgo para volar a Alemania. Llgué a la noche a Frankfurt y de ahí tomé un ICE (Inter City Express) a Freiburg (con transbordo en Monheim). Cuando llegué a media noche, mi amigo Federico me estaba esperando en la plataforma que un mes atrás, al comprar el boleto, sabíamos que llegaría.

Estuve subiendo algunas fotos de ayer domingo y hoy lunes al álbum Freiburg.

update: el álbum Freiburg tiene fotos de la ciudad de varios días

update: álbum SeePark con fotos del lago.

update: álbum Zurich y oficinas de Google.

update: álbum visita a la Selva Negra.


Midsummer 2010

Ayer se celebró en Suecia Midsummer, uno de los feriados más importantes del país y de los países nórdicos en general. Festejan el día más largo de año (eran las 12 de la noche y todavía había claridad).

Una de las actividades tradicionales consiste en levantar un gran poste y bailar alrededor. Antes de levantarlo, juntan flores y retoños para cubrirlo enteramente. La mayoría de la gente se llega hasta el bosque para celebrarlo. El "bosque" es el parque más grande dentro de la ciudad.

Van familias, jóvenes y extranjeros. Tocan música tradicional y algunos incluso están vestidos con los trajes tradicionales. Otros llevan puestas coronas hechas con flores y retoños.

Después de ver el baile, nos sentamos en el pasto a hacer un grill. El asado y las parrillas no son muy comunes en Suecia; utilizamos una parrilla descartable (ver foto) y asamos chorizos españoles (se hacen en 4 minutos) y carne de cerdo.

La gente se reúne en pequeños grupos, comiendo y charlando hasta las7 y 8 de la tarde. Luego, con el sol aún arriba se van volviendo lentamente a sus casas a terminar la noche tomando algo.

Tengo un álbum con fotos.