I was in need of a time tracking application to log the time I work for several customers & projects, but did not find a tool that both fit my needs and my budget, so here is my own application:
http://truetimer.com
dtemes
miércoles, 21 de marzo de 2012
sábado, 21 de mayo de 2011
Secure downloads with Apache and mod_rewrite/RewriteMap
In one of the projects i am working we need to protect some media files so that only authorized users can access them, and only the files they should have access to.
Our current solution uses a php script to check the permissions based on a token created from the file name and a timestamp, very similar to the secure download module available in lighttpd. The PHP script then reads the file and passes it to the user. This is far than optimal in terms of processing speed and memory consumption, so I satrted to search for a solution.
The first idea that came to my mind was using Ligttpd to serve those files with the secure download module, using apache as a proxy to a locally runinng insance of http://www.blogger.com/img/blank.gifLighttpd or using a dedicated server with Lighttpd to host the media files....yet another server to manage, not a good idea...
There must be something out there....if only mod_rewrite could do some string manipulation and calculate md5 hashes...as far as i know it does not, but wait a minute, we have RewriteMap!. The RewriteMap option within mod_rewrite allows the lookup of key/value pairs from plain files, db files or....external programs. The key is in this last feature. Let's see how we can do it.
1. Our token
As I said before we are using a token to control access to the files. This 40 bytes token consists of a md5 hash (32 bytes) plus a timestamp (8 bytes). The hash is calculated from the filename, the timestamp and a "secret" string.
token = md5(secret+filename+timestamp)+timestamp
a sample url to get the file could be:
2. The RewriteMap script
Apache comunicates with the RewriteMap external program via stdin/stdout. Only one instance of the progrm is run, and it serves for all the key lookup. In order to use it we have to set it up in our apache config, for instance at vhost level:
And here is the script, at this point is just a shell script to try the concept, not ready for production:
The script get the complete url and validates the hash and compares the timestamp with the current time to see if we are within the allowed time frame, specified by DURATION. If all is ok then it returns the file name, so in this case the url will be converted to :
If not valid it will return "noaccess.jpg", and we have two options: create that file and return it, or let apache return a 404 code,:not found.
3. The RewriteRule
And this is the .htaccess file inside the secure directory:
See how we append the token and file name and pass it to the securedownload rewritemap if the url matches the pattern with the 40 bytes token and the filename.
To avoid direct access to the file we block it and force a forbidden response, unless we have the magic query string added by the previous rewrite rule. This trick is the only way I have found to set a "flag" that prevents blocking access to the file after internal reruns of the rewrite engine.
4. The results
Our tests with ab show that this method is 10x times faster than our previous php script. Again, remember that using .htaccess files inside directories might not be optimal.
And that's all, drop me a line if you need more details!
Our current solution uses a php script to check the permissions based on a token created from the file name and a timestamp, very similar to the secure download module available in lighttpd. The PHP script then reads the file and passes it to the user. This is far than optimal in terms of processing speed and memory consumption, so I satrted to search for a solution.
The first idea that came to my mind was using Ligttpd to serve those files with the secure download module, using apache as a proxy to a locally runinng insance of http://www.blogger.com/img/blank.gifLighttpd or using a dedicated server with Lighttpd to host the media files....yet another server to manage, not a good idea...
There must be something out there....if only mod_rewrite could do some string manipulation and calculate md5 hashes...as far as i know it does not, but wait a minute, we have RewriteMap!. The RewriteMap option within mod_rewrite allows the lookup of key/value pairs from plain files, db files or....external programs. The key is in this last feature. Let's see how we can do it.
1. Our token
As I said before we are using a token to control access to the files. This 40 bytes token consists of a md5 hash (32 bytes) plus a timestamp (8 bytes). The hash is calculated from the filename, the timestamp and a "secret" string.
token = md5(secret+filename+timestamp)+timestamp
a sample url to get the file could be:
http://www.example.com/secure/1fb5dcde52ec59f7308c301e5126395b4dd6f000/file.jpg
2. The RewriteMap script
Apache comunicates with the RewriteMap external program via stdin/stdout. Only one instance of the progrm is run, and it serves for all the key lookup. In order to use it we have to set it up in our apache config, for instance at vhost level:
RewriteEngine on
Rewritemap securedownload prg:/etc/apache2/scripts/securedownload.sh
And here is the script, at this point is just a shell script to try the concept, not ready for production:
#!/bin/bash
KEY=VerySecret
DURATION=18000
while read line; do
PREV_HASH=${line:0:32}
PREV_TIME=${line:32:8}
FILENAME=${line:40}
#calculate our hash
MD5=`echo -n $KEY$FILENAME$PREV_TIME|md5sum`
NEW_HASH=${MD5:0:32}
#Time check
NOW=`date +%s`
let TIME=0x${PREV_TIME};
#Add duration
TIME=$(($TIME+$DURATION));
if [ $TIME -ge $NOW ];then
#check hash
if [ $NEW_HASH = $PREV_HASH ]; then
echo $FILENAME
else
echo "NOACCESS.${FILENAME:(-3)}"
fi
else
echo "NOACCESS.${FILENAME:(-3)}"
fi
done;
The script get the complete url and validates the hash and compares the timestamp with the current time to see if we are within the allowed time frame, specified by DURATION. If all is ok then it returns the file name, so in this case the url will be converted to :
http://www.example.com/secure/file.jpg
If not valid it will return "noaccess.jpg", and we have two options: create that file and return it, or let apache return a 404 code,:not found.
3. The RewriteRule
And this is the .htaccess file inside the secure directory:
RewriteEngine on
#secure download via rewrite map
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.{40})/(.*)$ ${securedownload:$1$2}?SECURE=123asd[L]
#no direct access to files
RewriteCond %{QUERY_STRING} !^SECURE=123asd$
RewriteRule ^(.*)$ - [F,L]
See how we append the token and file name and pass it to the securedownload rewritemap if the url matches the pattern with the 40 bytes token and the filename.
To avoid direct access to the file we block it and force a forbidden response, unless we have the magic query string added by the previous rewrite rule. This trick is the only way I have found to set a "flag" that prevents blocking access to the file after internal reruns of the rewrite engine.
4. The results
Our tests with ab show that this method is 10x times faster than our previous php script. Again, remember that using .htaccess files inside directories might not be optimal.
And that's all, drop me a line if you need more details!
miércoles, 3 de septiembre de 2008
Probando el navegador de Google

Tras la accidentada publicación del cómic de presentación de Google Chrome, por fin ha sido lanzada la versión Beta del mismo. Las primeras impresiones son más que positivas pero habrá que seguir investigando antes de tomar decisiones. Entre otras cosas aún no se si exsiste una versión para Linux, ni cómo funcionará en esa plataforma caso de existir.
Una de las cosas que no me gustan es que no he visto forma de cambiar el color de fondo de la aplicación, que no contrasta lo suficiente con el escritorio y por ejemplo cuesta localizar la barra de título para arrastrar la ventana. Y otra cosa, para que sirve el navegador "de incógnito" tengo sospechas de por dónde van los tiros, pero se echa en falta una explicación al respecto en la ayuda.
Mantendré un ojo puesto en este prometedor navegador...
viernes, 30 de mayo de 2008
No todo es trabajo
martes, 20 de mayo de 2008
¿Google digitalizando Barcelona?
Ayer por la mañana me llamó la atención un coche negro con una torreta sobre su capó que finalizaba en un dispositivo óptico que apuntaba hacia adelante, izquierda y derecha. En la puerta lucía el logotipo de Google. ¿acaso están digitalizando la ciudad?
En esos momentos yo iba caminando y con las manos ocupadas, así que no pude hacerle una foto con el movil.
Unas horas más tarde de publicar esta entrada veo que el asunto comentado es portada de "el Periódico" en su versión impresa, y online se puede encontrar aquí. Eso sí, no me ha gustado nada encontrarme al entrar publicidad que ocupaba toda la pantalla en la versión electrónica.
En esos momentos yo iba caminando y con las manos ocupadas, así que no pude hacerle una foto con el movil.
Unas horas más tarde de publicar esta entrada veo que el asunto comentado es portada de "el Periódico" en su versión impresa, y online se puede encontrar aquí. Eso sí, no me ha gustado nada encontrarme al entrar publicidad que ocupaba toda la pantalla en la versión electrónica.
jueves, 15 de mayo de 2008
Mini PBX basada en Asterisk
Desde hace meses tengo en casa funcionando a la perfección un mini ordenador con Asterisk, pero a pesar del pequeño tamaño el equipo consume bastante y sus ventiladores, que no dejan de funcionar durante todo el día, resultan cansinos.
Motivados por el incesante ruido de esos ventiladores y el propio placer de cacharrear nos hemos puesto manos a la obra con el objetivo de sustituir ese PC por un equipo embebido.
Aquí teneis una foto del resultado y un pdf explicando la experiencia.

Podéis descargar el pdf aquí: PBX Asterisk embebida.pdf.
Motivados por el incesante ruido de esos ventiladores y el propio placer de cacharrear nos hemos puesto manos a la obra con el objetivo de sustituir ese PC por un equipo embebido.
Aquí teneis una foto del resultado y un pdf explicando la experiencia.

Podéis descargar el pdf aquí: PBX Asterisk embebida.pdf.
martes, 5 de febrero de 2008
Hasta las orejas
Suscribirse a:
Entradas (Atom)
