The Fork Bomb and what to do about it

Last night on #crunchbang @Freenode the infamous fork bomb came up. Some people didn’t know what it was and what it did, and some people knew what it’s “side effect” was but didn’t know how it works, so I thought I’d break it down here and give a hint what you can do to prevent someone freezing your machine up with it.

The most common form of the fork bomb is

:(){ :|:&};:

Entering that to your terminal most likely will cause your machine to freeze as it chokes on insane amount of processes.  Despite of looking a bit cryptic to untrained eye, it’s really a very simple piece of shell script. Let’s take it apart, now.

:() { ... }

This construct is used to define a function. A function also needs a name, which comes before the parenthesis i.e. my_awesome_function() { return 0 }. So in this case, where we have :(){ …} we define a function called :.

:|:&

Now, this is the contents of the function. What it does is call the function : (itself) and pipe the result to the function :. So in effect the the function calls itself twice. The ampersand means the function call is moved to background so the child processes couldn’t get killed.

;:

; is there only to tell the parser that the function definition ends here, and what follows is a new command. It’s only needed because we want to keep the bomb as a one-liner. The last character, : is of course the command to start the bomb: call the function we just defined.

There’s no magic there, it’s just a regular recursive function. Only that it doesn’t terminate, but starts instantly eating up more and more of your system’s resources until the machine freezes. To make it look more like regular shell script it could be re-written for example like this:

bomb() {
    bomb | bomb &
}
bomb

I don’t recommend running that on your local machine. Even if a hard reset wouldn’t harm your machine it never does any good, either.

Protective measures

Since the fork bomb works by spawning processes, you can shield your system against it by limiting the amount of processes a user can simultaneously have.

On a Linux system you can do this by editing your /etc/security/limits.conf file. There’s probably some kind of template for you to take example of. What you want to limit is nproc:

harski hard nproc 100
@users hard nproc 50

The target whose attributes you want to target can be a single user (like on the first line) or a group (the second line). If it’s a group, you need to indicate it by prepending the group name by @. “hard” on that line means it’s a hard limit. The other possible value would be soft limit (only warns about having too many processes).

It also takes wildcards and can enforce limits to many more resources than just the number of processes, take a look at its man page for more information.

Posted in Linux | Tagged , , | Leave a comment

How to recover a root password

after the death of the admin was more or less the title of a thread I read a while ago in reddit. The thread was about this one guy being the admin of his houses machines and would would happen to the data on them if he suddenly died.

Besides the question of how to recover the password of a local machine this in my community spawned also discussion on how would one distribute for example his email password to someone else if he died. Email in particular would be a resource that would be valuable to have an access to after its primary user is gone, to shut down it and other services linked to it, if for nothing else. (Turns out there are services for distributing your passwords [for example deadmansswitch], if you trust them enough.)

Anyway, this post is about recovering root password in case you forgot it or happen to acquire dead man’s laptop or whatever. I have collected here four different ways to possibly gain root access to the machine without relying on any software exploits, some of them more convenient than others. After you have a root (or in some cases just write) access to the disk, you can go and edit /etc/shadow manually, or change it with passwd.

Note that all these rely on the fact that the media the target system is on is unencrypted. If the disk is encrypted and you don’t have the password, getting the data out is pretty much a lost cause.

Runlevel 1

Probably the easiest way to go about this is booting straight to runlevel one. It is a single user mode for admin tasks. Booting a linux kernel to runlevel one is as easy as appending “1″ (without the quotes) to your kernel parameters in your bootloader.

This method is very easy to do, but in practice it has a couple of “defects”. Defects as in security measures involved. Firstly, on some systems booting the kernel in to runlevel one doesn’t drop you immediately to a root console, but instead prompts you for the root password which makes this approach a dead-end. This is the case in for example my Arch Linux install.

The second problem can be giving the kernel the “1″ -option. If the bootloader is locked for editing you simply can’t hand it to the kernel and the system will boot up as it always does. In this case the only way to edit the boot menu you’d need to log in as root and then edit the menu… which again puts us to a dead-end.

init=/bin/bash

Trying this method out is pretty similar to runlevel one trick above, but circumvents the first problem in it. Adding init=/bin/bash (or init=/bin/sh or whatever) to the kernel options in you bootloader instructs the kernel to run the specified command first, instead of the usual /sbin/init. This drops you straight into a root shell, and you should see your filesystem just fine. One thing to note here is that the filesystem is now mounted as read only, so to change the root password you first need to remount the fs with read/write access:

mount -o remount,rw / 

You are now ready to modify /etc/shadow. As you can see, this too relies on being able to edit the kernel options in your boot loader, which can potentially render this method useless.

Booting a live-cd

Pretty trivial, eh? Insert the media containing the live os, boot it, mount the disk in the machine and edit it accordingly. But! For this to work you need to be able to select the first boot device. If the order is set and BIOS is password protected, you have a minor bump on the road. “Fortunately” as this method already assumes physical access you can open the case and remove the BIOS battery. This should reset the BIOS and you are free to edit it again!

Taking the disk out and modifying it on another system

The title says it all. Since we already have access to the machine physically, and don’t want to bother ourselves with downloading live systems and burning CDs, simply:

  • take out the disk
  • plug it in your own machine
  • boot the system normally
  • mount the foreign disk
  • edit disk accordingly

What can we learn from all this from security’s point of view?

We can turn this whole scene upside down, and take a look at what measures you could take to prevent someone from gaining root access to you box.

The first two methods relied on being able to modify the kernel boot parameters. There’s a simple solution for that: lock it from modifying. There almost certainly is an option for that somewhere in the configs.

The first one also relied on being able to enter runlevel 1 without prompting the root password. In Arch asking for password is achieved by having “su:S:wait:/sbin/sulogin -p” in /etc/inittab, but I don’t dare even try giving a general instructions on how you should do this. Consult your OS manual or so ;) Besides, locking the boot loader prevents also entering to runlevel 1 in the first place so this isn’t an issue, and not locking it still makes it possible to use the init=/bin/bash -parameter instead of this.

Now that the bootloader is secure, let’s move on to BIOS. Set a password for it, and see that the first device the machine looks for something bootable isn’t a removable media like a cd-device or USB port. Some BIOS’ have a function for selecting the bootable device just for that time, by hitting some key before POSTing. Disable this, too.

All in all: physical access is a bitch. If you have a machine you want to keep safe? Don’t let anyone near it. All the tricks above rely on getting physical access to the machine. If your disk is not encrypted and someone gets close enough to touch your machine there’s nothing that will protect your data from being compromised.

So as the last point: encrypt the disks on machines that other people might get to. Laptops are prone to stealing and it would be a child’s play to get your data from there if the disks are unencrypted.

Posted in Linux | Tagged | 1 Comment

Homework template for LaTeX

Since I couldn’t find a suitable homework template, I decided to hack one together myself. It is based on the exam document class, so one can quite neatly present both the questions and their solutions. As I am a computer science student, I also took special care to make sure both pseudocode and freely formatted text work properly.

The pseudocode is formatted with algorithm, algorithmicx and algpseudocode packages. The non-formatted text is achieved with alltt and striked out text with ulem package (\sout command). And who could do without amsmath. Get the packages somewhere if you lack them.

The exam document class didn’t support leaving some of the questions out (a feature not really needed while making exams), so I included a hack for it, \skipquestion. It allows you to answer questions 1 and 4 while keeping the question numbering sane. See the template for example, it’s all there.

Example of what the result pdf could look like is here, and the template can be found here.

Note: To get the page numbering right you might need to run latex a couple of times.

Update

Documentation for the algorithms package (usable commands, examples etc.) can be found at http://mirrors.ctan.org/macros/latex/contrib/algorithms/algorithms.pdf.

Also, as discussed in the comments, the linked template is designed for version 2.4 of the exam package and might not even compile with older version (Debian stable users beware! ;).

Posted in Misc | Tagged , , | 2 Comments

Interpreting machine load averages

A few nights back a few people on #crunchbang IRC channel in Freenode seemed to have some confusion on what the load average values their scripts gave them actually mean.

Programs like w, top and uptime report the load averages by three floating point values.

 $ w
22:26:10 up 14 days,  3:34,  2 users,  load average: 0.12, 0.06, 0.07

The values represent system load on averages for the last 1, 5 and 15 minutes. Each of these values tell how many processes on average were either in runnable or in uninterruptable state during the observation period. Runnable means a process being currently executed by the processor or waiting to be executed, and uninterruptable most often means it is waiting for some resource, typically an I/O device (fetching data from the hard drive is slow).

On a one CPU machine 1.00 would mean a full load for the CPU, 0.25 would mean it was occupied for 25% percent of the time. However, things get a bit more curious when the computer has multiple CPUs or CPU cores.

A dual-core machine similar to my desktop computer has a maximum load average value of 2.00. Now 1.00 load would mean the computation capability of my CPU was 50% utilized. Similarly a 6-core processor with a load average of 2.50 would mean that the full CPU capacity was utilized for about 40% worth.

Unfortunately this reporting scheme doesn’t separate whether all of the CPUs were evenly utilized for half the reporting period, or if one or two did all of the work and the rest sat there idle.

Posted in Linux | Tagged | Leave a comment

Gentoo hwclock error: /dev/rtc file not found

Saturday usually is a day during which I update my OS’, and so it was on this past week. I fancied it was time to update the kernel, too, since it had been a while. Everything went as smoothly as ever, despite the fact that I didn’t use an existing config but set everything up manually this time. Until…

Today I launched off Anki on the desktop instead of reviewing the flashcards on my phone, and I was greeted with a notification that told me that my clock was 7198 seconds off, and continuing could cause some serious trouble for my deck.

7198 seconds is roughly two hours, so I figured it had something to do with time zones. It was only then that I noticed my desktop’s clock was indeed off by that two hours. Hwclock would spit me an error:

 # hwclock
Cannot access the Hardware Clock via any known method.
Use the –debug option to see the details of our search for an access method.
# hwclock –debug
hwclock from util-linux 2.19.1
hwclock: Open of /dev/rtc failed, errno=2: No such file or directory.
No usable clock interface found.
Cannot access the Hardware Clock via any known method.

Now, I have had this problem before, but I couldn’t remember the solution straight away, which is why I’m making this note. /dev/rtc wasn’t available because rtc wasn’t enabled in the kernel. Enabling it (Device Drivers -> Real-time Clock) got the hwclock working. This episode also revealed me that the desktop didn’t have ntpd installed, so I set openntpd up to keep the clock in time in the future.

Posted in Linux | Tagged , , | Leave a comment

(EE) module ABI major version (12) doesn’t match the server’s version (13)

I logged in to my Gentoo today only to find the X session freeze as soon as I launched it. The logs revealed the following output repeated multiple times:

(EE) module ABI major version (12) doesn't match the server's version (13)
(EE) Failed to load module "evdev" (module requirement mismatch, 0)
(EE) No input driver matching `evdev'

As I had updated over 80 ebuilds the previous time I ran the system I had a long list of possible culprits. Additionally I noticed my / partition was 100% full, so anything could have gone awry the last time I ran the machine.

After first emerging all of the updated x11 related packages again nothing changed: X session would still freeze. What I should have done in the first place is reinstall all of the x11-related packages, not just the ones I had updated. So the solution is a simple

$ emerge $(qlist -IC x11-drivers)
Posted in Linux | Tagged , , | Leave a comment

Setting up TShock Terraria server on Gentoo

Steam holiday sale is now over. I managed to get away with only three new titles on my account, one of which was Terraria. I got exited about it, and looked into how I could set up my own multi-player server in Linux. The game itself offers the option to host a world for other players, but the client is only for Windows and I wanted to have the host up all the time, not just when I happen to boot into Windows.

Anyway, from what I gather most of the problems people have had with getting the server software to work have been related to outdated version of mono. In addition, the TShock installation guide doesn’t cover installation on Linux other than mentioning it is possible.

TShock requires version 2.8+ of mono. For my Gentoo installation that wasn’t a problem, I’m following amd64/10.0/server. If you don’t mind pulling a bunch of x11 libraries, you can just go ahead and

emerge dev-lang/mono

If you’re like me and don’t have X installed, give “minimal” use flag for mono and then emerge it:

echo "dev-lang/mono minimal" >> /etc/portage/package.use
emerge dev-lang/mono

Then head to TShock download pageand get the latest and gratest. Unzip the package and run it with

mono TerrariaServer.exe

The server should launch, ask you some questions about the port to be listened to for incoming connections and world generation. Refer for more info on the TShock web page.

Posted in Linux | Tagged , , , | Leave a comment

git: reseting changes

I’ve been using git for quite a while now for my own projects. My work flow usually involves getting the project to some meaningful point and committing. After that it often happens that I try something out and pretty soon realize it makes absolutely no sense whatsoever. To get the project back to the state it was after the last commit I’ve gotten used to do:

$ git reset --hard

What I do more rarely is keep changes to the most of the files, but reset one (or just a few) of them to the state they were at last commit. I keep thinking of this too as “reseting” the file and usually try to command something like “git reset my-source-file.c” and get “fatal: Cannot do hard reset with paths” as a reward. In this case what I should do is checkout the file, e.g.

 $ git checkout my-source-file.c

With git checkout out can check files out from older commits or other branches, too, if need be:

$ git checkout HEAD~2 my-source-file.c

For more information refer to man git-checkout ;)

Posted in Misc | Tagged | Leave a comment

Incorrect table or figure references in LaTeX

This bit me today, hard. It would be interesting to hear why someone thought it would be funny if \caption and \label had a mandatory order they have to appear inside a table or figure block. If they are in the wrong order there’s no error message either, it compiles nicely but the reference numbers in the text where you refer from are wrong.

Remember kids: always put \caption above the \label.

Posted in Misc | Tagged | Leave a comment