I have always though that ssh-agent has some limitations. One of those limitations is that when invoked from .bashrc or .zshrc in the following way:

`eval ssh-agent`

will cause one ssh-agent instance to be spawned for every shell, which is a waste of resources. An easy solution is to use Keychain, which is also described here.

Basically, Keychain is a wrapper for ssh-agent. Keychain will start a ssh-agent and tell it to load one or several private keys. Additionally, Keychain will create two shell scripts into ${HOME}/.keychains named ${HOST}-sh (for SH-compatible shells) and ${HOST}-csh (for CSH-compatible shells) that can be sourced, for example, from within .bashrc, .zshrc or .cshrc, in order to set up the environment variables required for ssh-agent to be usable by other tools like ssh.

A typical ${HOME}/.keychains/${HOST}-sh file looks like this:

SSH_AUTH_SOCK=/tmp/ssh-AIVkg1MfHH/agent.942; export SSH_AUTH_SOCK;
SSH_AGENT_PID=943; export SSH_AGENT_PID;

Adding the following lines at the end of .bashrc or .zshrc will get Keychain invoked automatically by the shell:

### KEYCHAIN ###
/opt/local/bin/keychain ~/.ssh/id_dsa
source ~/.keychain/${HOST}-sh

Keychain will search for an existing ssh-agent process. If no existing ssh-agent process exists, Keychain will spawn one telling it to load one or several private keys (passed as parameters to Keychain). Next, Keychain will update ${HOME}/.keychain/${HOST}-sh and ${HOME}/.keychain/${HOST}-csh to set up the proper environment variables and their corresponding values.

Kudos to Daniel Robbins — the original author — and Aron Griffis — the current Gentoo mantainer. This neat piece of software is extremely useful to me and I use it every day :-)

Anti-virus

November 13th, 2006

Recently, I read a nice post (Spanish only) published by Sergio Hernando on anti-virus software. After reading it, I decided to go on and write my own personal opinions on security and anti-virus software. In this particular case, although unusual, I disagree — most of the time, I can’t agree more with Sergio — with some of the points he made in this post ;-)

The last time I used an anti-virus software was more than ten years ago, and the last virus that infected one of my computers was called Omicron. In fact, my computer got infected due to a MS-DOS floppy that somebody copied for me that was already infected. In those days, it was pretty common to exchange floppy disks between friends.

I don’t like anti-virus software, at least in their current form, and I think I’m not the only one ([1] and [2]). I think I don’t need one anymore — and so does Jim Allchin ([4]).

Personally, I find anti-virus software to be:

Inefficient

Most of the anti-virus products I have ever used try to attach to the operating system itself — either the kernel, file system driver, disk driver, etc. — which makes the system slower, or crash-prone and unstable or all at the same time They are pretty much reactive beings.

I think reactiveness in isolation does not lead to a secure system. In real life, I tend to have a healthy diet, make some exercise, have enough sleep, etc., so that I can stay away of becoming ill or sick. That is, I’m being proactive: instead of waiting to become ill or sick, then going to the doctor, I do take actions, actions aimed at keeping me on the safe side.

Ineffective

There is a small joke that I think reflects the problems I see with anti-virus software:

- I think I’m ill, Doctor
- You suffer of Smith Sindrome
- What’s that?
- We don’t know yet, Mr. Smith

Most anti-virus products are reactive. Most of them include really good and ingenious engines that are able to even debug suspicious code in order to guess whether it is good or bad to run it. The problem is, however, that the user has little or no way to influence that decision — and it would be probably a bad idea to do so, since there are a lot of people out there that aren’t trained enough to decide by themselves.

Right now, anti-virus software is totally useless against new forms of malware, like Blue Pill ([3]). To me, the resources (time and money) of running an anti-virus can be wisely used to do other things, which I find far from perfect but more effective.

Misleading

Some people I know think that having an anti-virus software is all they need to keep their computers safe and clean from malware. They think that, as long they have an anti-virus software installed churning all of they available CPU cycles, it is safe to browse malicious sites, click on any banner, download dubious software, or open an e-mail message even when the sender is totally unknown or the subject is written in a language they don’t understand.

Whoever thinks this way is quite frankly wrong. And what’s worse, I don’t like the fact that anti-virus manufacturers (yes, I think they manufacture software, instead of handcrafting or designing it) don’t try to stop this insane advertising. I don’t take flu shot and expect being healthy forever. Things don’t work this way: medicines aren’t perfect and doctors, from time to time, make mistakes. You need to be wiser, smarter. You need to be proactive.

Anti-virus software is like a vaccine: it can’t only fight, and eventually defeat, known threats. It tries to defeat unknown threats by using heuristics and even IA, but it is far from perfect and sometimes can’t detect or defeat new kinds of malware that haven’t been properly analyzed. In fact, there a new breeds of malware that can’t be detected, even less be defeated, by current anti-virus products [3]. It the same way in real life: does H5N1 sound familiar?

These are the advices, rules, mantras and habits that have helped me staying secure for a very long time:

Use a (more) secure platform.

I personally like to use little-used, little-known, secure, well-designed platforms. That leaves me out with GNU/Linux, FreeBSD, OpenBSD, NetBSD, Solaris and, at some extent, Mac OS X. They are far from perfect — there is no completely software at all, by the way — but they do a really decent job.

I consider the rest of them to be either insecure (i.e., Windows) or so unknown and/or obscure to me that I don’t feel confident enough to install, configure or run them in a secure and safe way (i.e., BeOS, QNX, etc.).

Use a safe(r) browser.

Or the safest browser that you can find. I mean, stay away from Internet Explorer. It is insecure, doesn’t comply with standards and it is a privative, closed-source software —it’s difficult to audit software whose source code is closed away from you.

Be proactive, not only reactive.

Keep yourself up-to-date, well-informed by subscribing to security mailing lists, like SANS, CERT, vendor-driven mailing lists, Kriptópolis, una-al-día, etc., so that you stay aware of new exploits and vulnerabilities, their consequences and how to fix or overcome them if possible.

Talk to other people, to colleagues, to friends and share experiences and knowledge (right know, sharing knowledge is not yet illegal), read books and learn from your own experience and from others’ experience.

Also, be prudent and use your common sense (it comes by default in you, so it is free).

Keep your system up-to-date.

Updating production systems, particularly if you run a lot of them or they run critical software, is not an easy task. From time to time, security updates break things, change functionality or create problems. They aren’t supposed to behave this way, but software is not perfect. You should know :-) That’s when auto-updating software comes to rescue, doesn’t it?

That doesn’t mean you should run stupid, automated auto-updating software, like Windows Update. For me, I find that letting any sort of automated, clueless system, other than me, deciding what to update and when to do it is, at least, crazy. Current auto-updating software doesn’t have sense of risk since it doesn’t fully understand the system it’s running on. The risk of rendering your daughter’s game-playing PC useless is completely different — and probably lower — than the risk of rendering your working/corporate PC useless because of a broken security patch. However, auto-updating software will probably make sense for a game-playing PC or a PC used to sporadically surfing the Web. Knowing if auto-updating software makes sense or not is tricky business. What is worse: Having an un-patched system running several Trojan horses at the same time, or a patched, but broken system?

So my personal advice is: before applying a fix, make a backup of the system and, if you can, deploy the fix on a canary or test system before you do that on production or critical (like your laptop with invoices and your whole digital life) systems.

Use a real firewall.

But please, really use a real firewall. One that is powerful enough to to filter both incoming and outgoing traffic, like the IPTables (GNU/Linux) or PF (FreeBSD and OpenBSD).

For example, I can’t think of any machine of mine sending traffic to any of the following ports: SMTP, NetBIOS, CIFS, BGP, etc. I know that it is easy to defeat that kind of blocking by using HTTP tunneling, but that’s another story.

Ask yourself the following questions three times in a row before installing software.

Can I do fine without this software? Was I thinking of installing this software cause it is super-cool?

If my answer to any of these questions is yes, then I don’t install that particular piece or software, or do it on a test machine (like a virtual machine). This is my first level of filtering.

Do I know who wrote the software? Do I know where the software came from? Do I know why the author wrote the software? Is anybody else using that software? Do I have the right to access, read and modify the source code of the program?

This is my second level of filtering. I don’t like running closed-source software for a couple of reasons: I can’t debug it easily in case it doesn’t work as expected, which is a hassle to me and, second, if it is insecure or has a defect, I can’t fix it or, more commonly, find someone else to fix it for me.

If I ever need to install suspicious or untrusted software, I usually start up a virtual machine and install the software on it just for testing. In fact, I very rarely do run Windows but if I ever have to do it, I always use a virtual machine. Once I end my session, I undo all the changes (unless I can’t afford to do it by risking losing data or configuration changes).

Capture network traffic from time to time.

This allows me to check my expectations. I know my computers should never ever send NetBIOS or SMTP traffic. If they ever do, I know something is wrong. Maybe some component is misconfigured, or maybe something else has been installed that is triggering this behavior.

Knowing how your systems should behave and how they behave is really helpful. Not only for security, but for reliable systems. Also, I’m not the only one doing it ([2]).

Disable JavaScript.

I do for any Web site and I do only enable JavaScript for sites that do require it, like Google Maps or Google Mail. If you use Internet Explorer, I recommend you to do the same for ActiveX.

Disable Java.

Although Java is not insecure by itself, I usually find it pretty annoying. I usually enable it specifically for some Web sites that require it or lose functionality I like or depend on..

Sorry, Sun. No pun intended.

Don’t ever open e-mails from a sender you don’t know about.

My father told me this when I was a child:

Don’t talk to strangers!

My mother told me this when I was a child:

Never open the door if you don’t recognize the guy on the other side.

My mom’s advice was extremely restrictive. Should I have followed it, I think I would have never allowed the gas or cable technician to get into my house in order to check or fix broken things. So, I would rephrase that to:

Never let anyone in your house unless you invited or expected him.

I apply this mantra in the real life as well to my e-mail messages: “I never ever open an e-mail message from someone I don’t expect to talk to me”. Of course I can be deceived by some viruses which cloak themselves or pretend to be a friend of mine — typically those that send themselves to recipients of someone else’s address book.

Additionally, e-mail based Spam and viruses are usually one-shot only: if I ever discard a mail message, either on purpose or by accident, which is important, from someone that I don’t know about, he or she will probably try to get in contact with me again by either resending the message or by finding a different communication channel.

These are, of course, my personal opinions. They might or might not make sense or apply to you :-)

References:

[1] Why the Top-Selling Antivirus Programs Aren’t the Best

[2] Rutkowska: Anti-Virus Software Is Ineffective

[3] Introducing Blue Pill

[4] Allchin Suggests Vista Won’t Need Antivirus

Install crypsetup and dmsetup:

# apt-get install crypsetup dmsetup

Install pam_mount:

# apt-get install libpam-mount

Configure PAM to use pam_mount for authentication and session management. PAM authentication captures the user login password, while PAM session set ups the dmcrypt device and mounts it during log on, and unmounts the dmcrypt device during log off.

# echo “@include common-pammount” >> /etc/pam.d/common-auth
# echo “@include common-pammount” >> /etc/pam.d/common-session

Sets up some variables used to make the rest of the steps a little bit easier and more generic:

# USER=solana
# KEYSIZE=128
# DEVICE=/dev/whatever

The meaning of the previous variables is:

  • USER defines the username.
  • KEYSIZE defines the AES keysize used to encrypt the data. Valid keysizes are 128, 192 and 256.
  • DEVICE defines the device that will hold the crypted volume. This can be standard partition, a LVM volume, a NBD, etc..

Generate an AES random encryption key, encrypts it with the user log on password and stores it:

# dd if=/dev/urandom bs=1c count=$((${KEYSIZE}/8)) | openssl enc -aes-${KEYSIZE}-ecb > /home/${USER}.key

When prompted for the passphrase, enter the user’s log on password.

Sets up the dmcrypt device:

# openssl enc -d -aes-${KEYSIZE}-ecb -in /home/${USER}.key | cryptsetup -c aes -s ${KEYSIZE} create crypt-${USER} ${DEVICE}

When asked for the passphrase, just enter the user’s log on password.

Make a new ext3 filesystem on top of the cryptoloop device:

# mkfs.ext3 /dev/mapper/crypt-${USER}

Change the owner, so the user will be able to write to this volume:

# mkdir /mnt/crypt-${USER}
# mount /dev/mapper/crypt-${USER} /mnt/crypt-${USER}
# chown ${USER} /mnt/crypt-${USER}
# umount /dev/mapper/crypt-${USER}
# rmdir /mnt/crypt-${USER}

Frees the dmcrypt device:

# dmsetup remove crypt-${USER}

To test whether mount.crypt and mount the encrypted volume:

# openssl enc -d -aes-${KEYSIZE}-ecb -in /home/${USER}.key | mount.crypt ${DEVICE} /home/${USER} -o keysize=${KEYSIZE}

Frees the dmcrypt device after the test:

# dmsetup remove _dev_mapper_${DEVICE}

Configure pam_mount:

# echo “volume ${USER} crypt – ${DEVICE} /home/${USER} keysize=${KEYSIZE} aes-${KEYSIZE}-ecb /home/${USER}.key” >> /etc/security/pam_mount.conf

Michal Zalewski

August 19th, 2006

Leo en un artículo de Kriptópolis una excepcional crítica hacia el comportamiento de Zalewski. Para quien no lo sepa, Zalewski ha encontrado últimamente unas cuantas vulnerabilidades en algunos de los navegadores más utilizados, como Firefox, tales como ésta o ésta.

Me ha parecido tan bueno, que me limito a reproducir a continuación la totalidad del artículo:

Estimado Sr. Zalewski (conste que “estimado” es sólo de forma):

Me dirijo a usted con el único fin de solicitarle sea tan amable de desarrollar los parches correspondientes a las vulnerabilidades halladas en Mozilla Firefox en base a sus sapientes investigaciones.

De lo contrario me inclino a pensar que su trabajo ha sido totalmente destructivo y meramente publicitario, un simple ejercicio de alimentación del ego y del super ego.

Esta conclusión, excesivamente personal y para nada apresurada, a la que he llegado después de leer y releer sus artículos en los que expone sus razones, totalmente justificadas según mi limitado entender, para eludir procedimientos y reglas impuestas de forma unilateral y totalmente arbitrarias por corporaciones con tendencias monopólicas y hegemónicas, de ninguna manera son aplicables a un desarrollo Open Source, de código libre y abierto a la buena voluntad de aquellos que deseen modificarlo en búsqueda de la excelencia o, cuanto menos, en pos de mejorar su funcionalidad y extremar las medidas de seguridad para tranquilidad de los usuarios amantes de la libertad y la gratuidad obtenidas como único pago a su desinteresado esfuerzo…

Si Ud. no hiciera lo sugerido por el abajo firmante, estaríamos presenciando el nacimiento de una nueva era en las ciencias, donde la tendencia investigadora estaría dirigida a demostrar como se destruye, se enferma, o se inutiliza, no sólo un desarrollo informático sino (y por qué no con tanto loco suelto), un ser vivo, una cosecha completa o la cerradura de la puerta del vecino, y sabido es que mucho más fácil es destruir que construir. Pero como esto no es biología donde la sumatoria de pares puede dar nones, así como usted analizó el código fuente para hacerlo estallar, haga lo mismo pero a la inversa, y no me diga que no puede ya que bajo ningún aspecto su argumento será creíble, recién entonces publique su hazaña, nunca antes, porque usted señor Zalewski no ignora que ahora, en este mismo momento, un ejército de idiotas desocupados está copiando el código de sus torpedos para inundar esta saturada red, más parecida a un campo minado que a un crucero de placer, la misma que a usted le sirve de teatro de operaciones e investigación, y reitero, por qué no de promoción, dicho esto con el mayor de los respetos y sin intención peyorativa alguna, conste.

En cambio si una vez demostrada la falla, usted publica la receta del antídoto, el reconocimiento público, quizás, llegaría hasta el mismo bronce.

Lo saluda atentamente, sin la mínima esperanza de recibir respuesta alguna de su parte, un simple observador y crítico de actitudes humanas insensatas.

Víctor Hugo

Espero que al autor no le moleste que haya hecho referencia literal al artículo de Kriptópolis.

Install pam_mount:

# apt-get install libpam-mount

Configure Ubuntu to load the loop and cryptoloop kernel modules during boot or else pam_mount won’t be able to mount the cryptoloop devices:

# cat >> /etc/modules
loop
cryptoloop

Configure PAM to use pam_mount for authentication and session management. PAM authentication captures the user login password, while PAM session set ups the cryptoloop device and mounts it during log on, and unmounts the cryptoloop during log off.

# echo “@include common-pammount” >> /etc/pam.d/common-auth
# echo “@include common-pammount” >> /etc/pam.d/common-session

Sets up some variables used to make the rest of the steps a little bit easier and more generic:

# USER=solana
# SIZE=2048
# KEYSIZE=128

The meaning of the previous variables is:

  • USER defines the username.
  • SIZE defines how much space to allocate for the file-based cryptoloop, as a quantity expressed in MiB.
  • KEYSIZE defines the AES keysize used to encrypt the data. Valid keysizes are 128, 192 and 256.

Creates the loop file and fills it with random junk:

# dd if=/dev/urandom of=/home/${USER}.img bs=1M count=${SIZE}

Generate an AES random encryption key, encrypts it with the user log on password and stores it:

# dd if=/dev/urandom bs=1c count=$((${KEYSIZE}/8)) | openssl enc -aes-${KEYSIZE}-ecb > /home/${USER}.key

When prompted for the passphrase, enter the user’s log on password.

Loads the cryptoloop kernel driver (if not already):

# modprobe -q cryptoloop

Finds the first loopback device available:

# LOOP=$(losetup -f)

Make sure that ${LOOP} is something like /dev/loop0.

Sets up the cryptoloop device:

# openssl enc -d -aes-${KEYSIZE}-ecb -in /home/${USER}.key | losetup -e aes -k ${KEYSIZE} -p0 ${LOOP} /home/${USER}.img

When asked for the passphrase, just enter the user’s log on password.

Make a new ext3 filesystem on top of the cryptoloop device:

# mkfs.ext3 ${LOOP}

Frees the cryptoloop device:

# losetup -d ${LOOP}

Configure pam_mount:

# echo “volume ${USER} auto – /home/${USER}.img /home/${USER} loop,user,exec,encryption=aes,keybits=${KEYSIZE} aes-${KEYSIZE}-ecb /home/${USER}.key” >> /etc/security/pam_mount.conf

I’ve read a ZDNet articile about Barclays Bank deploying a new security system for on-line financial transactions using a two-factor athentication system.

I can agree that this will raise the bar for financial transactions — but only slightly. The problem with two-factor authentication systems is that I think they can’t fully deter, stop or avoid man-in-the-middle (MITM) attacks.

Let’s think about this scenario:

A malicious user, Malory, wants to hijack a financial transaction being performed, or about to be performed, by Alice over the Internet against a merchant, called Bob. Malory could forge the merchant’s website, let’s name it X, and hijack Alice communication by diverting it to X’s website — this can be done by hijacking the communication channel or by using social engineering, like phising. Since X’s website looks identical to Bob’s website — or else, the transaction between Alice and Bob can be forged into a new transaction between Alice and X that looks like the original one —, it is possible to deceive Alice into thinking that X is the website she wants to deal with. SSL won’t help much since X’s website can install a valid SSL certificate and yet the browser won’t complain.

Once Alice has got into X’s website, this site can launch a man-in-the-middle-attack: X website contacts Bob’s website in order to retrieve all the authentication details, and sends them back to Alice. This will include a request for Alice to generate and show back the 12-digit, single-use code (One time password, OTP). Alice will use his secure device to generate the 12-digit, single-used code, but will send it back to X’s website.

Now, X’s website has a valid, single-use, 12-digit code for a transaction. Malory, the owner of X, could try forging the transaction at its will, for example by trying to change the amount of the transaction or any of its conditions, like payment timeframe, modifying or even cancelling the transaction. The only thing X has to do is taking the 12-digit code, plus the original transaction information and modify it in such a way that it is somehow altered, but sill valid. This can lead to Denial of Service (DoS) attacks — if Malory simply stops the transaction from taking place —, an active attack that modifies the terms of the transaction in Malory’s benefit or even Bob’s benefit, reducing the amount of the transaction, etc.

In general, I think two-authentication systems are not completely inmune against man-in-the-middle attacks. The user still has the responsability to check that the end-to-end communication channel is secure, that is, that no Malory-like guy has hijacked it. SSL itself won’t prevent this since Alice can still establish a SSL-secured connection against X. The problem is authenticating X identity to be Bob’s website and not Malory’s, that is, asserting that the communication channel is clear and secure. If both Alice and Bob have met before, this can be achieved with relative ease. However, if Alice has never met Bob before this can prove challenging.

Of course, this is my personal opinion. Comments are always welcome.

The Cisco Linksys WRT54G/GS/GL is made up of a six-port configurable switch, a standard Ethernet controller (usually a Broadcom controller named eth0) and a Wireless controller (usually a Broadcom controller named eth1).

The following diagram tries to illustrate the different components that made up the Cisco Linksys and how are they interconnected:

                                            Linksys rear
 Trunk    Internet    1     2     3     4   port number
  ---        ---     ---   ---   ---   ---
  |5|        |4|     |3|   |2|   |1|   |0|  switch port number
  ---        ---     ---   ---   ---   ---
  |           |       |                 |
  |         vlan1     |----- vlan0 -----|
  |
  | Miniswitch
  ----------------------------------------
  | Linux
  |
  |           ---- vlan0 -> LAN
  |           |
  |----- eth0 -
              |
              ---- vlan1 -> Internet/WAN

The standard Ethernet controller is attached to the sixth port (port #5) of the switch and is configured as a 802.1q VLAN trunk port. This allows running several VLANs using a single connection to the switch.

By default, OpenWRT configures two per-VLAN network interfaces:

  • vlan0:

    stands on the VLAN0 (the Local Area Network which comprises the four ports labeled as 1, 2, 3 and 4 at the rear of the box).

  • vlan1:

    stands on the WAN network (the port labeled Internet at the rear of the box).

The VLAN configuration is controlled using NVRAM variables. The variable labeled vlan0ports defines which switch ports are assigned onto the VLAN0, while vlan1ports defines which switch ports are assigned onto the VLAN1.

This is the default NVRAM configuration:

nvram set vlan0ports="3 2 1 0 5*"
nvram set vlan0hwname=et0
nvram set vlan1ports="4 5"
nvram set vlan1hwname=et0
  • vlan0ports:

    states that ports #3, #2, #1 and #0 (the ports labeled as 1, 2, 3 and 4 at the rear of the box) are assigned onto VLAN0. Additionally, port #5 is also assigned onto VLAN0.

    The asterisk sitting besides the 5 means VLAN0 is the default, native VLAN for this port, so any untagged traffic is considered to belong to VLAN0.

  • vlan1ports:

    states that port #4 (the port labeled as Internet at the rear of the box) is assigned onto VLAN1. Additionally, port #5 is also assigned onto VLAN1 since it’s a trunk port.

    The lack of an asterisk means VLAN1 is not the default, native VLAN for this port.

NOTE: vlannhwname needs to have a value assigned to it, even when it’s value is never used by the init scripts. This value is usually et0.

NOTE: Care must be exercised as ports numbers are zero-based, as illustrated before, and the sixth-port (port #5) must be assigned to every VLAN, since it is an VLAN trunk port.

The following code snippet from /etc/init.d/S10boot shows how the init script tells the switch which ports are onto which VLANs:

# configure the switch based on nvram
[ -d /proc/switch/eth0 ] && {
  for nr in $(seq 0 15); do
    vp="$(nvram get vlan${nr}ports)"
    [ -z "$vp" -o -z "$(nvram get vlan${nr}hwname)" ] || {
        echo "$vp" > /proc/switch/eth0/vlan/$nr/ports
    }
  done
}

We can also see that up to sixteen VLANs are supported by the switch.

Custom VLANs

The Linksys and OpenWRT combination is so flexible that we can configure additional VLANs. In fact, I was looking to add an additional administrative VLAN (VLAN2) granting me full access to the box while I could restrict access from the LAN and WAN to the minimum — for example, by using additional firewall rules.

This is depicted in the following figure:

                                            Linksys rear
 Trunk    Internet    1     2     3     4   port number
  ---        ---     ---   ---   ---   ---
  |5|        |4|     |3|   |2|   |1|   |0|  switch port number
  ---        ---     ---   ---   ---   ---
  |           |       |     |           |
  |         vlan1   vlan2   |-- vlan0 --|
  |
  | Linksys
  ----------------------------------------
  | Linux
  |
  |           ---- vlan0 -> LAN
  |           |
  |----- eth0 ---- vlan1 -> Internet/WAN
              |
              ---- vlan2 -> Administrative VLAN

To achieve this configuration, we need to remove port #3 (labeled as 1 at the rear of the box) from VLAN0 and assign it onto VLAN2. We also need to add port #5 to the VLAN2 since it is the VLAN trunk port used to carry the traffic from the switch to Linux through the standard Ethernet controller:

nvram set vlan0ports="2 1 0 5*"
nvram set vlan0hwname=et0
nvram set vlan1ports="4 5"
nvram set vlan1hwname=et0
nvram set vlan2ports="3 5"
nvram set vlan2hwname=et0

I’ve defined three custom NVRAM variables that will get used by an additional init script to configure the VLAN2 as an administrative VLAN, granting full access to the box:

  • adm_ifname:

    defines the Linux network interface name assigned to the administrative VLAN, in the form of vlann, where n is the VLAN number.

  • adm_ipaddr:

    defines the IP address for the administrative interface.

  • adm_netmask:

    defines the network mask for the administrative interface.

For example:

nvram set adm_ifname=vlan2
nvram set adm_ipaddr=192.168.0.100
nvram set adm_netmask=255.255.0.0

I’ve also coded up an additional init script, named /etc/init.d/S41network, used to bring up the administrative interface. I’ve decided not to fiddle with /etc/init.d/S40network to avoid breaking things and having problems during upgrades.

These are the contents of /etc/init.d/S41network:

#!/bin/sh
IFNAME=$(nvram get adm_ifname)
VLAN=${IFNAME##vlan}
IPADDR=$(nvram get adm_ipaddr)
NETMASK=$(nvram get adm_netmask)
vconfig add eth0 $VLAN
ifconfig vlan${VLAN} up ${IPADDR} netmask ${NETMASK}

Testing

To test this custom configuration, I recommend disabling the firewall, my removing the executable permission bit from /etc/init.d/S45firewall and /etc/init.d/S41network just to prevent being locked out from the box in case problems arise.

Firewalling

I’ve also replaced the firewalling init script, /etc/init.d/S45firewall, with my own version. This allows for a fine-grained and thighter configuration.

Since the box will act as a routing firewall, and since it has 3 VLANs, I wanted to apply the following policy:

  • Any traffic coming from or going to the administrative VLAN (VLAN2) is allowed:

    This rule allows administering the box from a computer attached to the VLAN2, while blocking administrative access from other VLANs.

  • Incoming ICMP Echo Requests and ICMP Time Exceeded control messages are allowed from any interface:

    This rule allows certain ICMP control messages to reach the box. ICMP Echo Request is needed in order for the box to respond to ping and ICMP Time Exceeded (TTL) so we don’t break the PMTU discovery algorithm.

  • Any other incoming traffic from the LAN is rejected:

    This rule rejects any other traffic which does not match previous rules. Traffic is explicitly rejected, so we avoid having clients blocked waiting for an RST TCP segment.

  • Any other incoming traffic from the WAN is dropped:

    This rule silently drops any traffic coming from the WAN which does not match any previous rule. This will make external scan attacks much slower.

  • Local DNS queries coming from the local box going to configured DNS servers are allowed:

    This rule allows the local machine to resolve DNS queries sent against configured DNS servers (those configured in the wan_dns NVRAM variable). This is rarely needed, but the ipkg command requires a working DNS name resolution.

  • HTTP traffic from the local machine to the WAN is allowed:

    This rule allows upgrading and installing packages using the ipkg command.

  • Outgoing ICMP Echo Requests and ICMP Time Exceeded control messages are allowed from any interface:

    This rule allows certain ICMP control messages to depart from the box. ICMP Echo Request is needed in order for the box to invoke ping and ICMP Time Exceeded (TTL) so we don’t break the PMTU discovery algorithm.

  • Forwarding SSH/NX traffic coming from WAN to the designated SSH/NX server in the LAN:

    This rule allows accesing the SSH/NX traffic from the WAN. In addition, I apply SNAT to make IP datagrams appear to come from the firewall box since I have multiple DSL links.

  • Forwarding HTTP and HTTP/S traffic coming from the LAN targeted to the WAN:

    This rule allows using HTTP and HTTP/S services from the LAN.

  • DNS queries coming from the LAN going to configured DNS servers are allowed:

    This rule allows the machines in the LAN to resolve DNS queries sent against configured DNS servers (those configured in the wan_dns NVRAM variable).

  • Forwarding ICMP Echo Requests coming from the LAN to the WAN:

    This allows pinging external hosts from the LAN. ICMP Time Exceeded, however, is not forwarded, since the firewall sits in the middle between the LAN and the WAN (and I do use SNAT and DNAT).

Here is the complete /etc/init.d/S45firewall script:

#!/bin/sh
IPTABLES=/usr/sbin/iptables
FW_INET_IFACE=$(nvram get wan_ifname)
FW_INET_IP=$(nvram get wan_ipaddr)
FW_PRIVATE_IFACE=$(nvram get lan_ifname)
FW_PRIVATE_IP=$(nvram get lan_ipaddr)
FW_ADM_IFACE=$(nvram get adm_ifname)
NX_IP=10.200.0.10

$IPTABLES -F
$IPTABLES -t nat -F

# Configure SNAT/DNAT/MASQUERADE
$IPTABLES -t nat -A PREROUTING -i ${FW_INET_IFACE} -p tcp \
                               -d ${FW_INET_IP} --dport 179 \
                               -j DNAT --to-destination ${NX_IP}:22
$IPTABLES -t nat -A POSTROUTING -o ${FW_PRIVATE_IFACE} -p tcp \
                                -d ${NX_IP} --dport 22 \
                                -j SNAT --to-source ${FW_PRIVATE_IP}
$IPTABLES -t nat -A POSTROUTING -o ${FW_INET_IFACE} -j MASQUERADE

# Configure input firewall filtering:
# Allow:
#   - Traffic flowing from the loopback interface
#   - Traffic coming from the administrative VLAN
#   - ICMP Echo Request coming from WAN
#   - ICMP Time Exceeded (TTL) coming from WAN
#   - Traffic from an already established or related connection
# Block:
#   - Any traffic coming from the WAN
# Reject:
#   - Any other traffic coming from the LAN
$IPTABLES -A INPUT -i lo -j ACCEPT
$IPTABLES -A INPUT -i ${FW_ADM_IFACE} -j ACCEPT
$IPTABLES -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A INPUT -p icmp --icmp-type echo-request -j ACCEPT
$IPTABLES -A INPUT -p icmp --icmp-type time-exceeded -j ACCEPT
$IPTABLES -A INPUT -i ${FW_INET_IFACE} -j DROP
$IPTABLES -A INPUT -j REJECT

# Configure output firewall filtering:
# Allow:
#   - Traffic flowing to the loopback interface
#   - HTTP traffic
#   - ICMP Echo Request going to WAN
#   - ICMP Time Exceeded (TTL) going to WAN
#   - DNS queries to configured WAN name servers
#   - Traffic from an already established or related connection
# Reject:
#   - Any other traffic
$IPTABLES -A OUTPUT -o lo -j ACCEPT
$IPTABLES -A OUTPUT -o ${FW_INET_IFACE} -p tcp -m tcp \
                     --dport 80 -m state --state NEW -j ACCEPT
$IPTABLES -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A OUTPUT -p icmp --icmp-type echo-request -j ACCEPT
$IPTABLES -A OUTPUT -p icmp --icmp-type time-exceeded -j ACCEPT
for ns in $(nvram get wan_dns); do
        $IPTABLES -A OUTPUT -o ${FW_INET_IFACE} -p udp -m udp \
                            -d "$ns" --dport 53 -j ACCEPT
        $IPTABLES -A OUTPUT -o ${FW_INET_IFACE} -p tcp -m tcp \
                            -d "$ns" --dport 53 -j ACCEPT
done
$IPTABLES -A OUTPUT -j REJECT

# Configure forward firewall filtering:
# Allow:
#   - Incoming SSH/NX traffic -> the filtering takes place after the
#     PREROUTING chain has been processed and, since DNAT has been already
#     being performed, the traffic is filtered accordingly to its final
#     destination (the SSH/NX server)
#   - Outgoing DNS queries to configured WAN name servers
#   - Outgoing HTTP and HTTP/S traffic
#   - ICMP Echo Request coming from LAN going to WAN
#   - Trafic from an already established or related connection
# Drop:
#   - Any other traffic
$IPTABLES -A FORWARD -i ${FW_INET_IFACE} -o ${FW_PRIVATE_IFACE} -p tcp -m tcp \
                     -d ${NX_IP} --dport 22 -m state --state NEW -j ACCEPT
$IPTABLES -A FORWARD -i ${FW_PRIVATE_IFACE} -o ${FW_INET_IFACE} -p tcp -m tcp \
                     --dport 80 -m state --state NEW -j ACCEPT
$IPTABLES -A FORWARD -i ${FW_PRIVATE_IFACE} -o ${FW_INET_IFACE} -p tcp -m tcp \
                     --dport 443 -m state --state NEW -j ACCEPT
$IPTABLES -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT
$IPTABLES -A FORWARD -i ${FW_PRIVATE_IFACE} -o ${FW_INET_IFACE} \
                     -p icmp --icmp-type echo-request -j ACCEPT
for ns in $(nvram get wan_dns); do
        $IPTABLES -A FORWARD -i ${FW_PRIVATE_IFACE} -o ${FW_INET_IFACE} \
                             -p udp -m udp -d "$ns" --dport 53 -j ACCEPT
        $IPTABLES -A FORWARD -i ${FW_PRIVATE_IFACE} -o ${FW_INET_IFACE} \
                             -p tcp -m tcp -d "$ns" --dport 53 -j ACCEPT
done
$IPTABLES -A FORWARD -j DROP

Web 2.0 y seguridad

June 7th, 2006

Francamente, estoy bastante cansado de oir hablar de la Web 2.0 por todas partes cuando ni siquiera soy capaz de encontrar lo que busco utilizando la última tecnología del planeta. Me refiero a la búsqueda semántica.

Independientemente de estos hechos, lo que resulta innegable que cada vez aparecen más y más aplicaciones basadas en Web. Muchos las llaman aplicaciones Web 2.0, pero para mí son la evolución lógica de las aplicaciones Web: mayor versatilidad y potencial, haciendo posible la implementación de aplicaciones, antes territorio exclusivo del escritorio pesado, como hojas de cálculo y procesadores de texto que aprovechan cada vez más el potencial de los navegadores. Sea JavaScript, sea CSS, o XML, la Web 2.0 resulta muy atractiva. ¿Alguien ha probado la integración entre Google Mail y Google Talk? Resulta escalofriante observar cómo puedes empezar a escribir un correo y, si de repente, el destinatario entra en el chat de Google Talk, puedes optar por enviarle el texto como un mensaje instantáneo en lugar de un correo electrónico. O la integración entre el navegador Firefox y Google Notebook.

Ciertamente, las ventajas son increíbles: La Red se convierte en un sistema de almacenamiento, donde la información y el conocimiento están (casi) siempre accesibles, desde cualquier parte del mundo. La flexibilidad de consultar tu correo, tu calendario, tus contactos, tus notas, las últimas búsquedas o tus hojas de cálculo desde cualquier ordenador y cualquier ricón del mundo con acceso a Internet. Ya no tendría que preocuparme de sincronizar mi teléfono móvil con mi ordenador, sino que simplemente bastaría con mantener mis contactos y calendario en servicios Web 2.0, y utilizar mi móvil (de momento, con las tarifas actuales no) para navegar por Internet y acceder a ellos.

Sin embargo, toda tecnología, toda ventaja, tiene su contrapunto. Poder acceder universalmente a la información implica que deben hacerse ciertos sacrificios, y uno de ellos sea probablemente hacer que información antes confidencial y privada ahora esté en manos de terceros. Esto no es nada nuevo: la Policía dispone de información muy personal mía, como mi huella digital. La Seguridad Social dispone de mi vida laboral, así como la información de cotización. Hacienda sabe con bastante exactitud en qué gasto mi dinero y de dónde vienen mis ingresos. Sin embargo, no es lo mismo confiar en La Policía, en La Seguridad Social, en Hacienda o algún otro ente público (que idealista soy), que confiar en una empresa privada, quizá extranjera, cuyo único fin es ganar dinero. A cualquier precio, en muchos casos.

Curiosamente, la mayoría de los servicios Web 2.0 que permiten almacenar datos, información, e incluso conocimiento, son gratuitos. ¿Cómo es posible que una empresa que ofrece semejante potencial no cobre por ello? Está claro que la publicidad es una fuente de ingresos realmente suculenta, pero opino que detrás se esconde el As bajo la manga, y es el acceso por parte de estos proveedores de aplicaciones a información con la que nunca antes habían soñado: mensajes, hojas de cálculo, notas, y por ello, información sobre hábitos, pensamientos, proyectos, intereses, etc. Este conocimiento no tiene precio, y estoy seguro de que en manos de empresas de márketing, ventas o finanzas podrían hacer inclinar la balanza a favor de unas o de otras, y ellas estarían dispuesta a hacer casi cualquier cosa para tener acceso a él. ¿Cómo yo, pobre consumidor, puedo sentirme seguro cuando se me ofrece un servicio de almacenamiento que no me cuesta dinero? El espacio de almacenamiento que Google ofrece para GMail es inmenso. Mantener esa infraestructura de hardware y energía cuesta mucho dinero, ¿y puede pagarse sólo con la publicidad? Creo que hay más estrategia detrás. Sinceramente, la única forma de sentirme algo más seguro dejando mis datos más personales en manos de un tercero sería firmando un contrato de nivel de servicio y confidencialidad, es decir, pagar por el derecho a que mi información esté siempre disponible, en la red, pero sólo para mí, y nadie más.

Creo que la decisión entre privacidad o seguridad y flexibilidad, dados los modelos de negoio actuales, es casi una decisión exclusiva: los servicios Web 2.0 que se ofertan hoy en día son, en su mayoría, gratuitos, así que si técnicamente no puedo exigir que el servicio sea íntegro, seguro, fiable y que esté disponible cuando lo necesito, menos aún puedo exigir la confidencialidad de la información hospedada. Por mi parte, la información que almacenaría en un sistema Web 2.0 gratuito, sin un contrato que cubra mis necesidades, se limitaría a mi correo personal y a mis fotos. El resto, lo guardaría en un lugar mucho más seguro, uno que sólo yo conociera, y al que sólo yo tuviera acceso.

A new security vulnerability has been disclosed for WordPress < = 2.0.2.

The only solution at the moment seems to restrict web access to the wp-content/cache/userlogins/ and wp-content/cache/users/ directories (e.g. with a .htaccess file). Thus, I’ve done so while the WordPress staff confirms and fixes this problem.

In Red Hat Enterprise Linux ES 4.1 Update 3, both /etc/pam.d/imap and /etc/pam.d/pop contain hard-coded paths pointing to pam_stack.so, actually /lib/security/pam_stack.so. This causes problems on x86_64 since pam_stack.so is located under /lib64/security/pam_stack.so.

A workaround is to modify /etc/pam.d/imap and /etc/pam.d/pop to look like this:

#%PAM-1.0 auth required pam_stack.so service=system-auth account required pam_stack.so service=system-auth

I filled in a bug report against Red Hat Enterprise Linux 4:

https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=192550