Diego Woitasen

Linux, BSD and Free Software.

Sep 282011
 

Today I had a problem with cron. One of that typical situation where a cron job doesn’t run and you don’t know the reason. If I ran the cron daemon from the command line, the cron job was executed. If I ran the daemon from the init script, nothing. Debugging the problem I executed the init script with “bash -x” where I saw that the script set the variable TZ with the content of /etc/timezone. This file had a different timezone from /etc/locatime link. The problem was that the job was working, but at different time. Cron has been a source of headaches…

Conclusion, if you have a problem with check, check /etc/localtime and /etc/timezone. They should point to the same timezone.

Post to Twitter

Sep 212011
 

Today chatting via IRC I remembered a problem that I had some years ago with virtualization, iptables, nat and bridge. The situation of the guy asking was pretty similar. He has a one virtual machine (Qemu/KVM) connected to the world using a bridge and its default gateway is the virtualization host. He was trying to apply destination NAT to the VM in the host machine but it didn’t work. The rule was simple:


iptables -t nat -A POSTROUTING -s 10.0.3.11 -o eth0 -j MASQUERADE

It is perfect, there is nothing wrong there but he never saw the packet in the POSTROUTING chain. Why? The quick answer is “packets don’t cross nat table twice”. There is a flag in the Linux bridge to enable filtering with Iptables. Packets go to Iptables in the kernel when they are forwarded by the bridge. This includes the NAT table.

In the bridging process, you don’t know the outgoing interface so the previous rule doesn’t work. He needs the interface because he’s using MASQUERADE. In the routing process, the packets go to iptables but they never cross NAT tables because the packet already crossed the table in the bridging process.

How can we fix this? There are two options I think:

  • echo 0 > /proc/sys/net/bridge/bridge-nf-call-iptables #To disable Iptables in the bridge.
  • Raw table: Some years ago appeared a new tables in Iptables. This table can be used to avoid packets (connection really) to enter the NAT table: iptables -t raw -I PREROUTING -i BRIDGE -s x.x.x.x -j NOTRACK.
If you still don’t understand why this happens, I’ll try to explain one more thing. If you have an scenario with Virtualization and you host is your gateway, the packets follow this steps: [VM]->[bridge]->[virtual interface]->[host]->[physical interface]->[net]. When they cross the host, you have the routing process there.

Post to Twitter

Sep 182011
 

When you have to synchronize configuration files between servers you always think in Ssh/Rsync at first. Then you remember that you need to enable login to some account and some security issues appears. You are giving full shell access and you only need copy and execution and nothing else. If you have root login disabled you’ll have problem with permissions too.

I always desired an application that only synchronizes files and executes some action after the copy until I found Csync2. This application is a simple tool to copy configuration files (and other types of files) and do something after that (usually reload the config.). It doesn’t require a shell account because it runs as service. The configuration of Csync2 is simple: a list of hosts, a list of files and a list of actions to execute if it detects a change in a file. Let’s start the configuration.

The following steps must be executed in all servers.

First, you need the configuration file, /etc/csync2.cfg:

group cluster1 {

        host server1;
        host (server2);
        host (server3);

        include /etc/resolv.conf;
        include /etc/apache2/;
        exclude /etc/apach2/ports.conf;

        action {
                pattern /etc/apache2;
                exec "/etc/init.d/apache2 restart";
                logfile "/var/log/csync2/apache-restart.log";
                do-local;
        }
}

Looks easy, right? I’ll explain it anway:

  • host: Each line defines the members of the syncronization group. The hosts with parenthesis are slaves, they only receive files from the member with parenthesis. I usually have all the servers as slaves except one. I prefer to have only one point where you modify the configuration.
  • include: This lines list the files to sync.
  • exclude: If you are synchronizing directories, sometimes you need to exclude some files inside them.
  • action: This section defines a command to execute if a file matching the pattern changes. You can set a file to save the output of the command and do-local tells Csync2 to execute the action in the host where you are going to dispatch the sync.

This file must be in all the servers.

In the second step, you have to create the X.509 certificates to use SSL. Csync2 doesn’t use X.509 authentication, it only requires the certificates to enable a secure communication. This should be in the developer’s TODO list. So, don’t worry about creating good certs, the following commands are enough:

# openssl genrsa -out /etc/csync2_ssl_key.pem 1024
# yes '' | openssl req -new -key /etc/csync2_ssl_key.pem -out /etc/csync2_ssl_cert.csr
# openssl x509 -req -days 600 -in /etc/csync2_ssl_cert.csr -signkey /etc/csync2_ssl_key.pem -out /etc/csync2_ssl_cert.pem

The third and last step of configuration is to create the authentication key. This key must be the same in all servers. It’s created with the following command:

csync2 -k /etc/csync2.key

At this point, you are ready to sync files:

csync -xr

You have to execute that command in the server without parenthesis in the csync2.cfg. As I said before, I prefer to have one master server where I make the configuration changes.
If you have problems, Csync2 is not very verbose by default. There are two things that you can do. You can execute “csync2 -xr” with -vvv and you should see something useful. If not, you can execute the service in the failing server in foreground. First, stop inetd (Csync2 runs under Inetd by default in Debian/Ubuntu) and then execute “csync2 -ii -vvv”. Now try the sync. again.

Post to Twitter

Aug 142011
 

There is a bug in some place of Ubuntu 10.04 that does crazy things with virtual machines using KVM. Symptoms are a inconsistent cron process and time moving backwards. I didn’t know the root of the problem but I suspected that it was related to power saving. Why? Because the problems appeared at night, when the systems are usually idle. Solution: processor.max_cstate=0. That disables CPU power saving. I don’t have an entire explanation, but that has been working for me.

Post to Twitter

Apr 082011
 

Attaching a sieve script to a shared folder is a little tricky. First, you need to understand that Cyrus has two types of repositories where you can have Sieve scripts: Personal and Global. Personal is per user and global is for every user. Global scripts aren’t applied on incoming messages by default, users must include them in their scripts.

Also, there are two types of Global scripts: global and global per domain.

When you log into Cyrus IMAP with sieveshell you have the following combinations (I suppose that you have manager and manager@example.com as admin in imapd.conf):

  • sieveshell -a manager -u manager localhost: To edit global scripts.
  • sieveshell -a manager@example.com -u manager@example.com localhost: To edit global script of example.com domain.
  • sieveshell -a user@example.com -u user@example.com localhost: To edit personal scripts of some user.

Scripts for shared folders work different from user scripts. The last ones are uploaded to the user’s repository and attached to the inbox when you activate them. The first ones must be uploaded to the global domain repository and attached to a shared folder by an user that has permission on it. You have to use the second combination of the listed above to load them and cyradm (or another compatible client) to do the attach:


sieveshell -u manager@example.com -a manager@example.com localhost
> put /tmp/my_script my_script
cyradm -u user@example.com localhost
localhost.localdomain> mboxcfg shared.folder@example.com sieve my_script

Post to Twitter

Dec 182010
 

Hacía rato que seguía OSM y por fin de decidí a aportar. Viajo mucho, me meto por caminos raros así que puedo recopilar mucha información para ayudar. Por ahora empiezo con las calles de mi barrio que tienen varios detalles para corregir.

Voy a tener que invertir en una Tablet PC con GPS para tirar a la basura Garmin que no sirve para ésto. Muy limitado.

Lo único malo es que ésto empezó con un poco de indignación por la gente de Mapear. Lo vivos utilizan información provista por los usuarios y se la adueñan, para beneficio propio. Todo ésto surgió luego de investigar un poco por el foro y hacer algunas preguntas. No les interesa compartir. Una lástima. OSM podría crecer gracias a ellos y el revés también. El dinamismo de OSM haría que Mapear creciera mucho más rápido.

Lo mejor que se puede hacer ahora es aportar a la alternativa libre y lograr que algún día le permita a los usuarios reemplazar Mapear.

Para cerrar. Me puse a investigar porque OSM usa Yahoo y no Google Maps. Problemas de licencia obviamente. Google Maps no permite crear trabajos derivados de sus mapas o imágenes aéreas. No permitirme crear un mapa desde una imágen aérea, es como si no pudiera poner en un texto que el caballo de San Martín era blanco porque lo vi en una foto. Ridículo.

Post to Twitter

Sep 302010
 

Hoy estaba probando en un cliente el módulo de ppolicy de OpenLDAP. Su función es agregar políticas de password como bloqueo de cuentas por ingreso de contraseña inválido, caducidad de claves, forzar complejidad de claves en el cambio de las mismas, etc. Haciendo las pruebas cree un usuario “diegows” con password “lanux123″ y empezó a loguearme con la clave “lanux1234″ para ver si la cuenta se bloqueaba. Supuestamente se tenía que bloquear a los 3 intentos y yo iba por 20 y nada. Es más, me el login (bind en lenguaje LDAP) funcionaba perfecto.

Luego de revisar la configuración 20 veces, me doy cuenta de un detalle, algo que ya me había pasado hace un tiempo. Las claves estaban guardadas en el LDAP cifradas con Crypt. Ésta algoritmo usa solamente los 8 primeros caractéres para encriptar la clave. Intentar loguearme con “lanux123″ era lo mismo que loguearme usando “lanux1234567890″.

La moraleja es: no usar nunca CRYPT!!!! Además de ser inseguro, te hace perder el tiempo.

Si le pasa, ya saben…

Post to Twitter

Sep 282010
 

Escribí un script para hacer “Message Archiving” en la versión Open Source/Community de Zimbra. Está en producción desde julio del 2010 sin quejas hasta ahora.

Espero que les sirva.

I wrote an script to do “Message Archiving” for the Zimbra Open Source/Community Edition. It’s been running since July 2010 without any problems.

I hope it helps…

Post to Twitter

Aug 282010
 

Hice un upgrade de mi viejo módulo de Netlink ping. Primero lo renombré a Netlink Echo que encaja mejor a lo que hace. Después le hice unos cambios por que la API de netlink del kernel cambió desde la primera vez que lo armé con kernel 2.4. Está probado con el kernel 2.6.31 y funciona sin problemas.

Lo que publico acá es un módulo de kernel y su respectiva herramienta de userspace. La idea es mandar un mensaje de texto al kernel y que el kernel devuelva el mismo mensaje. Por eso el nombre Netlink Echo.

Netlink es un mecanismo que provee el kernel para comunicarse con él. Distintos subsitemas del kernel (Networkin en general, Udev, SCSI, etc) lo usan para que podamos configurarlos y pasarle parámetros. Netlink es un tipo de socket y se utilizan las mismas funciones que en otro tipos de socket: connect, bind(), send(), recv().

Les dejo el link del ejemplo en GitHUB, espero que les sirva. Más informacion “man 7 netlink”.

Post to Twitter

Jun 172010
 

Introducción

Este artículo describe como usar SMTP y TLS para cifrar la comunicación entre el cliente y el servidor, incluyendo la autenticación de ambas partes. La ides es que el servidor nos autentique como usuarios validos usando certificados x509.

Configuración en el servidor (Postfix)

smtpd_tls_cert_file=/etc/postfix/tls-cert.pem
smtpd_tls_key_file=/etc/postfix/tls-key.pem
smtpd_tls_CAfile = /etc/postfix/cacert.pem
smtpd_use_tls=yes
smtpd_tls_session_cache_database = btree:${queue_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${queue_directory}/smtp_scache
smtpd_tls_ask_ccert = yes
smtpd_tls_loglevel = 1

smtpd_recipient_restrictions =
        permit_mynetworks
        permit_tls_clientcerts
        reject_unauth_destination

relay_clientcerts = hash:/etc/postfix/relay_clientcerts

Este es un fragmento con los parámetros de configuración que se agregaron al main.cf de Postfix. A continuación la explicacion:

  • tls-cert.pem y tls-key.pem son las claves publica y privada del SMTP servidor.
  • cacert.pem es la clave publica de la CA.
  • El certificado, la clave privada y el certificado de la CA se crearon con el script CA.sh que viene con openssl:
    1. Agregue -extensions v3_ca a la linea
      $CA -out ${CATOP}/$CACERT $CADAYS -extensions v3_ca -batch
    2. ./CA.sh -newca

      pide la passphrase y otros parámetros necesarios para el certificado.

    3. Edite el CA.sh y le agregue -nodes a la línea:
      $REQ -new -keyout newkey.pem -out newreq.pem $DAYS
    4. ./CA.sh -newreq

      para crear el request del certificado para el postfix.

    5. ./CA.sh -sign

      para firmar el request.

    6. cp newcert.pem /etc/postfix/tls-cert.pem
      cp newreq.pem /etc/postfix/tls-key.pem
    7. Pongan los permisos de tls-key.pem a 600 por seguridad.

Y listo!

Configuración de un cliente (msmtp)

Como uso Mutt+msmtp para enviar correo configure el segundo para que se valide con Postfix usando los certificados x509.

  1. Cree el certificado del lado cliente de la misma forma que lo hice del lado servidor (ver sección anterior, ./CA.sh -newreq y ./CA.sh -sign).
  2. Copie elnewcert.pem y newkey.pem como postfix-cert.pem y postfix-key.pem respectivamente al ~/.ssl/ de mi desktop.
  3. Luego configure el ~/.msmtprc con los siguientes datos:
    account example
    host mail.example.com.ar
    from diego@example.com.ar
    tls on
    tls_starttls on
    tls_certcheck off
    tls_key_file ~/.ssl/postfix-key.pem
    tls_cert_file ~/.ssl/postfix-cert.pem
    tls_trust_file ~/.ssl/cacert.pem
    
    account default: example
    

Y eso seria todo…

Post to Twitter