Archive for the Linux Category

Linux server and security scripts, now on GitHub

I started posting some Linux and security notes, the collection has been increasing with new entries and I'm also using GitHub's Gists to save them and a central page for easier reference.

Here's the current list:

Apache security: installing mod_security
Linux Server Utilization
Linux disk/memory stress test
Linux honeypots
Linux remote syslog
Monitoring Plesk with Monit
Linux check DNS cache snooping
Linux shell here document on the fly
Heroku Python
Apache password protect directory
Linux making disk space
Mysql status, check & repair
Linux: Block IP with iptables
Replace relative to absolute URL in a file
Set permissions for web files & directories
Linux find IPs with most web connections
Linux monitor & react to event in log file
Defending against Spam using Linux Postfix
Apache optimization with Google's mod_pagespeed
Linux mail server for sending only
Linux Passwordless SSH
Linux better command history
Linux get email for SSH Logins
Linux SSH Filesystem
Linux cloning packages (Debian/Ubuntu)
Linux protecting critical directories
Linux file integrity with tripwire
Linux server monitoring with monit
Linux server stats with munin
Linux encryption and decryption
Linux Rootkit check
Linux disk space email alert

Collection of Linux Scripts

I end up repeating many Linux commands and scripts over, so I figure other people may find them useful, I'm putting them in my Pastebin.

These include Passwordless SSH, mounting an SSH Filesystem from another server and getting an email alert when someone logs in a server.

Also for setting up a server, better command history and cloning the packages (base software) from one server to another.

For monitoring and statistics there's an entry for Munin and another one for Monit, as well as a little script for getting an email alert if we are running out of disk space.

If there's no mail server running and you don't want to set it up to listen on public port but you just want it for sending out the alerts to you then you can just set up Postfix to listen to the local interface.

There's also a general server utilization script that can be piped to a log file every x minutes with cron as a poor's man (or customized lightweight) monitoring solution.

For security I have a tip for how to protect critical directories from changes (this is not for everybody), checking file integrity with Tripwire (to warn about intrusions or to do forensics), checking for rootkits and quick encryption of files

I'll be adding also notes for applications I use, like this one for mod_pagespeed

- First things First

Probably one of the most frequent commands to be entered right after logging in is 'w'.

w not only tells you if there's somebody else logged in, but also the uptime and the load average.

To check the latest log-ins (say 10) we can do:

last -a -10

(Of course, to learn more about any of the commands mentioned here you can do man command or http://google.com/linux it).

- Processes

To get a quick idea of the services that a server is providing:
netstat -tlpnu

This will give us a list of the programs accepting connections (listening) and their ports.

To get a list of all connections (this gives us an idea of current traffic) we can add the 'a' option:

netstat -tapnu

To get a quick breakdown of the number of connections:

ss -s

If you have the network scanner nmap installed, then the list of open ports given above by netstat should coincide with the one by nmap:
nmap --open -p0-65535 localhost

It's very important from a security standpoint to expose publicly only the services/ports that we really need and stop all other services.

To get a list of all the running processes in a nice tree-view:
ps auxf |less

This gives us interesting information like the % memory each process is using and its status (under the STAT column).

Check for processes in the D status, that means that it's waiting and it gives as a clue of a possible hard disk I/O bottleneck.

An alternative view of processes is given by the top utility which contains also current CPU utilization. For 'top' the status column is 'S'.

We can gather more advanced information with the all-powerfull lsof tool.
It tells us info about files opened by a process, user etc. Since in Unix almost everything is treated like a file (sockets etc) lsof yields a lot of useful information: who's accesing what, what's holding a resource etc.

To check what files are involved with a process:
lsof -p pid (where 'pid' is the process number we get from 'ps', 'top' or 'nstat')

Files open by a user:
lsof -u username

Port info:
lsof -i :portnumber

- Memory usage

There are several tools to check for memory usage, the simplest way is probably:

free -m

Where values are in MB.
Ignore the first line, since once Linux grabs memory it won't release it until the memory is needed, even if it's not using it (that's kind of the idea); this means we really have to look at the second line '-/+ buffers/cache' to know currently how much memory is used and how much is free (available).

The 'swap' line is interesting too; if there's any value used that means that at some point Linux ran out of RAM and used the disk ('swapped') as memory and this slows down the system. Resorting to some swap from time to time to deal with spikes in activity can be OK, but using it all the time is not.

Another handy tool to check the memory and CPU utilization is vmstat.
If we want to run it every second for example we can do vmstat 1. To see the changes in place we can use the cool 'watch' tool:
watch -n1 vmstat

If a program stopped responding or there's a general sluggishness it's possible the we have run out of memory before.

To check the number of times we've run out of memory recently we can do:
grep -i kill /var/log/messages |wc -l

or:

dmesg |grep -i kill | wc -l

The whole list (without the line count '| wc -l') will give us details of what processes were killed by the out-of-memory (oom) killer.

- Disk usage

To get disk space info we can use df or du:
df -h

The biggest (for example 5) directories (this command and the next may take a while):
du -mxS / | sort -n | tail -5

Or for the detailed files (credit Rimuhosting support):
du -a --max-depth=3 / | sort -n | awk '{ if($1 > 102400) print $1/1024 "MB" " " $2 }'

Note that sometimes 'du' and 'df' can report different disk usage; this is because they count space for deleted files that are open differently. (Not that you need to but a reboot would get rid of this discrepancy).

If you ran out of space you can delete some unneeded files (like logs perhaps), purge packages for programs you are not using or compress files with gzip.

For example to archive a directory into one file and also compress it with the tar utility:
tar cvfz dir.tar.gz dir

Here's a couple of tips to safely reclaim some disk space in an emergency situation.

- For Debian-like systems (like Ubuntu) with the 'apt' package management we can clear out the local repository of retrieved package files with:
apt-get clean, the equivalent for the yum updater is yum clean.

- The ext2 and ext3 file systems have by default 5% capacity of partition reserved to root (to check if your filesystem is ext2 or ext3 see for ex: df -T or mount)
We can free up that reserved space in case of emergency and leave just 1% with:

tune2fs -m1 /dev/hda1

, where /dev/hda1 is an example of a disk partition (use 'df' for example to get the name in your case).

We could also set the reserved % value ('m' option) to zero but perhaps that's not a very good idea; in case the disk becomes full we still want to be able to get in (as root) to do maintenance, that's the whole idea of the 5% reserve in the first place.

- Logs

Logs are a sysdamin's best friend. Look at logs at the /var/log directory like /var/log/messages etc. To look at large files we can use 'tail' to see the last lines like: tail -20 /var/log/secure.
If the file keeps growing fast we see the instant changes with tail -f file

Another option to see the end of a file is use 'less' and then press the '>' key to go to the end, this way we can go back up.

Other navigation control for 'less' are 'b' to scroll up and space bar to scroll down or enter to move down a line. We can also look for keywords in 'less' by typing the forward slah / followed by the keyword.

Most logs print a timestamp; check with the date command what the server thinks the current time is.

Also very useful for systems where more than one user uses the same account is the history utility to see previous entered commands for the current account.
For other users see the file: /home/username/.bash_history or similar.

I think it's a good idea to add a timestamp to the command history, this is done by setting the HISTTIMEFORMAT like for example:
HISTTIMEFORMAT="%d/%h - %H:%M:%S "

- Scheduled jobs

For problems that appear only at certain times check users with cron jobs with: ls /var/spool/cron/ and then to see the cron jobs for a user (for example 'maiman'): crontab -u mailman -l

- Network Settings

Very basic commands are ifconfig and route.

A couple of important files are:
/etc/resolv.conf, this file lists the DNS servers. If the server cannot access a hostname or url in the Internet, check if it's accesible by IP address and it that's the case this indicates a problem with domain name resolution.

In this case yry inserting in the /etc/resolv.conf file well-known solid DNS servers (instead of the ones provided by your ISP) like the ones by OpenDNS ( 208.67.222.222, 208.67.220.220) or the easy to remember 4.4.4.1, 4.4.4.2.

/etc/hosts: in this file we can tie a hostname with an IP address, bypassing resolution through DNS servers.
A source of problems is when the entry 127.0.0.1 localhost is missing from this file (to test: doing a ping localhost would fail).
Many programs (database access, mail servers etc) rely on this mapping so they would fail because of this.

In a server networking review is important too to check if we have firewall rules (redirections etc) with:

iptables -L; iptables -t nat -L

Note that the rules for the 'nat' table are not displayed with just 'iptables -L'.

- Software installed and their versions

For many popular programs to get its version it's sometimes small v, sometimes big V and sometimes it's 'version' ; sometimes one dash and sometimes two:

python -V
perl -v
httpd -v or apache2 -v
java -version
mysql --version

For Linux kernel and distro version:

uname -a
cat /proc/version

(There are lots of information under /proc , many commands just read from this pseudo file system and it's a matter of knowing where to look and how to interpret the info).

To get a list of installed packages:

For rpm-based distros: rpm -qa
For dpkg (debian): dpkg --get-selections

- Finding stuff

This is just one of my favorite Linux command combinations:

Say you need to find all the instances of a keyword that can be in one or more files under a directory structure (say /etc ), this can be done with:
find /etc |xargs grep keyword

So just 11 days ago there were new Wordpress releases: 2.1.1 and 2.0.9 , which included security fixes and less than a day ago we got the announcement WordPress 2.1.1 dangerous, Upgrade to 2.1.2, where we learnt that the previous release may include a security exploit that was added by a cracker. Gotta update wordPress.

Oh well, things happens but I guess I'm closer to getting my site un-php-fied and using Python or Ruby on Rails intead (yes, I fall for fads, especially when they involve better programming languages).

Anyways, to upgrade WordPress there are good instructions at the official site wordpress.org, but if you use the Linux command prompt things can be simplified a little, like making a copy of the database without need of a GUI, getting the new version without having to download it first to your desktop and then to your server or overwriting the old WordPress files automatically without having to delete them first.

Unless you've had WordPress for a while most likely you already have the minimum requirements for PHP and MySQL but it won't hurt to test; WordPress requires PHP version 4.2 or greater, and MySQL version 4.0 or greater, we can check with:

# php -v
# mysql --version

It's also recommended that from your wordpress' administration dashboard you deactivate your plug-ins.

Now, we go to the parent directory that holds the WordPress directory, for instance something like:

# cd /var/www/mywebsite/public_html

or

# cd /home/mywebsite/public_html

This will change if you are in a shared hosting environment.

Let's backup the database and the WordPress directory:

# mysqldump -u root -p --add-drop-table --extended-insert --quote-names database_name > wordpress_back.sql

This will prompt for your root password. If you have no root privileges (like in shared hosting), replace 'root' with your user name. Replace also database_name with the name of your wordpress database.
Do a minimum check with # less wordpress_back.sql to verify that your data is indeed there.

Making a tar backup of the current wordpress files:

# tar -cf wordpress.tar ./wordpress

check the tar file by printing its contents:

# tar -tf wordpress.tar

OK, so now let's get the newest WordPress package and deploy it:

# wget http://wordpress.org/latest.tar.gz
# tar -xzvf latest.tar

There's no need to delete any previous files since tar overwrites them.

The tar file extracts a 'wordpress' directory and files within it; if your current installation uses another directory name (or it's at the document root) you'll have to delete the old directory and rename the 'wordpress' directory: # mv wordpress old_directory_name

Now when you browse back to your site you'll be prompted to update by clicking in a link (pretty much like an interface with a big red button that Dilbert created once). And that's it for the update.

You can also check in your administrator's dashboard that you have the latest version (at the very bottom) and reactivate your plug-ins.

Ubuntu Security Toolkit LiveCD

There are several Linux Live CDs that are specialized in network security tools like:

L.A.S.
Trinux
PHLAK
Knoppix STD

I like Knoppix STD; it's a very complete infosec toolkit. (First time users: remember to right-click with the mouse once you're on the desktop).

I've been getting involved in Ubuntu and a project I just started is the Ubuntu Security LiveCD, an Ubuntu LiveCD remastered with many security tools.

The security live CD I put together works pretty well and I intend to publish the iso file once I polish it a little more.

Ubuntu Linux Revisited

I installed Ubuntu Linux in a second system, a $75 barebone refurbished with components from a failed Asus Pundit that was very cute but it will shut down every now and then and lately it wouldn't even boot. By the way, the barebone is an MSI MBOX P4MAM-V, just to confirm that it's Linux-compatible.

I updated some multimedia issues in my previous Ubuntu post. The problems with Totem (DVD playing) is a legal issue: Multimedia support
The no sound problem with Totem was solved again with:
# apt-get remove totem-gstreamer
# apt-get install totem-xine

The way Ubuntu manages the root account is a non-standard Unix arrangement, made for simplified desktop use and somehow controversial.
The root account is disabled by deafult and administrative usage is encouraged through the sudo command; the first user has root powers, as explained in this FAQ answer. It's just a bit confusing because usually when you su or sudo in a Unix system you do it from an unprivileged account, and so you enter the password for root, but in this Ubuntu setup the first user account created after or at installation has administrative rights, so in Ubuntu when doing sudo you enter the user's password, not root's.

Some commands and graphical control applications are missing when compared with other distributions like Red Hat / Fedora. For instance, there's no command like chkconfig to view what services would be started at boot time. The Debian equivalent is update-rc.d, but this command is limited to the installation or removal of the initialization scripts, it won't summarize the current status of the /etc/rc?.d directories. The tool that we can use is rcconf, that is not packaged in Ubuntu by default but can be easily installed with the usual "apt-get install rcconf".

There's no firewall (netfilter/iptables) configuration tool, and this was a conscious decision made by the Ubuntu team as explained in this FAQ answer. Again, it's easy to install a firewall configuration program with the powerful Debian package system, for instance: apt-get install firestarter and voila, the firewall wizard is installed under Applications -> System Tools.

ubuntu

Goodbye Red Hat, Hello Ubuntu

I just installed Ubuntu "Warty" in my Dell Inspiron 8200 laptop on top of my old Red Hat 8.
The summary: it gets an 8 out of 10; I'm keeping Ubuntu, bye bye Red Hat.

I've been working with Linux for over 6 years but mainly in the server side. I had a dual boot in my laptop with WinXP Pro and Red Hat 8 that I was using mainly for some security tools like Nessus. Since Red Hat branched its distribution in the paid version and the "amateur" Fedora project, I was wanting to look elsewhere and specially to a Debian distribution and its apt package management. My version of Red Hat was getting old; it couldn't recognize my (crappy D-Link) wireless card, and Firefox wouldn't install because of some missing libraries.

Yesterday I took the plunge and installed Ubuntu from a single downloaded CD image to my old Red Hat partition.
As a nice surprise, the Nvidia video card was recognized and the video settings and everything just worked fine into the great 1600x1200 native resolution (before I had to download and install an rpm from Nvidia). The other nice thing is that my wireless card was also recognized, although it didn't work at first.

After some troubleshooting, I got the wireless working only by disabling the WAP encryption. Anyways, because I'm a security paranoic, I had a MAC address filter in my access point among other measures, so it should be still somehow secure, or at least someone war driving would pick first any of the other 6 wireless open networks from my neighbors. I read in Ubuntu's FAQ about typing the key with dashes like: 1234-5678-9A, but that didn't work either.
The networking setting dialog is kind of weak though. And when both wireless and regular eth are connected, the connectivity is lost.

I found that some dialogs don't have the OK button, just the "Close" one and changes are kept, but it's not consistent (besides, some have an "Apply" instead of "OK").

I showed the desktop to someone who has never seen any Linux desktop before and she immediately clicked the world icon to browse the Internet and she said she liked the desktop (I chose the Ocean Blue theme).

Firefox works great and with Gaim I don't need to install the Yahoo messenger client.

OK, now on to try the apt-get thingy. What? there's no nmap? no Nessus? OK, I just did an initial "apt-get update" , "apt-get upgrade" and then I could grab both "apt-get install nessus", "apt-get install nmap". So that's really great. Actually there's a GUI for apt (Synaptic). But first you have to uncomment the repository sources in /etc/apt/sources.list . I don't know why this is not done by default.

I couldn't listen to any music or watch a DVD movie, but then (San Google) I discovered that there's some IRQ allocation conflict in my laptop between sound and parallel printer, and the whole thing (at least the sound, haven't checked is printer) is solved by adding "acpi_irq_isa=7" to the boot command in /boot/grub/menu.lst

So now I could play music, but the Totem DVD wasn't working yet (actually I was able to crash the system). After searching the Ubuntu forums I tried uninstalling totem-gstreamer and installing totem-xine, and now it showed the FBI warning at the beginning, but then it crashed (I'm getting closer). I know if I read a little more documentation and I apt-install the right program/codecs whatever it would eventually work, but the point is, viewing DVDs in Ubuntu it's not ready for your mother yet. Update:The issue of (not) playing DVDs has to do with encryption and licenses fees for the media players. Commercial Linux versions like Xandros and Linspire (previously Lindows) have an incorporated licensed media. There are free / open source programs that break this encryption but their legal standing is not good or unclear in some countries (amazing but true).

This multimedia stuff is not ready yet from the default Ubuntu installation; I wanted to burn a CD with family pictures but the only program available is a music ripper. Update: I don't know how I missed it, but upon inserting a blank CD a new window for the burner opens, I just dragged-and-dropped the folder I wanted to copy to the CD and that's all!

Another thing I couldn't do in Red Hat 8 was to mount my Windows ntfs partition. Now it worked without any problems. I added a line in /etc/fstab to mount automatically:
/dev/hda2 /home/fernando/win ntfs auto,rw,exec,user,umask=000 0 0

OpenOffice seems to work fine, and Evolution looks great, who needs Outlook?

My flash thumbdrive was really plug-and-play; I plugged it in the USB slot in the back and when I moved my head back the new icon of the drive was already in my desktop. By the way, maybe it would be a good idea to add some basic icons to the desktop in the default distribution, like "home" and "disks". For example when my Windows partition is mounted its icon is shown on the desktop but it's alone.

The root privileges are treated differently than standard Unix, I guess as not to confuse novice users.

So there's some post-installation issues, and some of them are addressed in the Ubuntu documentation and forums, like: http://www.ubuntuforums.org/showthread.php?t=3713&highlight=mp3
The Ubuntu Guide: http://www.ubuntuguide.org/ and the Debian reference documentation: http://www.debian.org/doc/manuals/reference/reference.en.html are some excellent sources.

Besides the package management (apt versus rpm and maybe yum) the other noticeable difference is the initialization runlevel scripts. In Red Hat there's also the "service" command, like in "service network restart" that basically calls the network script (/etc/rc.d/init.d/network) but in Debian style it's /etc/init.d/networking

Another good point is that I only needed one single CD for the installation of Ubuntu, instead of the three usually required in Red Hat. The installation process itself is not as graphical as Anaconda or YasT, but I don't particularly care; the crucial steps to me are the partition and the video detection and in Ubuntu it was explained better in the first case and it worked better in the latter. Since Ubuntu is aimed at desktop users, it doesn't have package selection options at installation time, so this step is simplified. (hey, it doesn't even come with gcc by default!).

There's no iptables firewall rules by default, but there are no listening ports after installation either. Red Hat always had something open that you have to close after the first install, although in every new version they reduce the number of open services.

OK, that was my experience of one day with Ubuntu Linux, so far I'm keeping it. It's a a nice general desktop distro.

I have a customer with several web sites hosted on a dedicated server.

The server uses qmail as MTA and I wanted to install SpamAssassin to filter out spam.




Aftert a little search, I didn't find a clear documentation of how to connect SpamAssassin with qmail. Two useful pages I found were:
How to use Spamassassin together with Qmail and SpamAssassin with qmail / Vpopmail



I wanted to filter on a per-account basis and I was having some problem with the recipe from the 1st page. So basically I adapted the information and here's what it worked for me:




  1. I installed SpamAssassin, more or less like explained in the 2nd page

  2. I edited the file /etc/mail/spamassassin/local.cf

  3. I checked with a spam example (save a spam email with full headers) that it works from the command line: spamc < spam.txt
  4. I downloaded and installed safecat (contains the maildir tool)
    by the way, it gives an error warning when maildir is executed but it works.

  5. As mail user ("popuser") I edited the .qmail file of the account ("webmaster") located at /var/qmail/mailnames/domainhere.com/webmaster/.qmail with the following:

    | spamc |maildir ./Maildir/

  6. I checked that it was working: cat spam.txt | spamc |maildir ./Maildir/

  7. I (re)started SpamAssassin: /etc/init.d/spamassassin restart