How to Log/Drop TCP packets on the Linux kernel level

Most companies requiring sophisticated manipulation of network traffic rely on firewall devices capable of layer 7 protocol analysis. However, with the ease of deploying web applications into the cloud, you may find yourself managing a web server that is not sitting behind a firewall and exposed to hackers to play with. Most modern web services allow for access to be controlled via configuration (e.g. .htaccess for apache), but suppose you want to prevent certain packets from hitting your web service in the first place, that is where [**iptables**](http://en.wikipedia.org/wiki/Iptables) comes in.

I advice caution when using this and you'll need to use sudo or run as root to see try what I am describing below.

If you want to see what rules are currently in place you may run it with the -L parameter:

```
iptables -vL
```

Suppose you want to drop all incoming packets on port 80 containing the string 'sex', here is what you can do:

```
iptables -A INPUT -p tcp --dport 80 -m string --algo=bm --string "sex" -j DROP
```

There you can also log packets using -j LOG

If you decide that you no longer want a certain rule to be applied, use the -D option

```
iptables -D INPUT x # where x is the rule number
```

Finally, if you want your changes to persist across reboots you need to save your changes:

```
service iptables save
```

This is just a brief overview. I recently used this technique to block a Wordpress comments spam bot (it identified itself in request headers which was very helpful).