How to secure an Ubuntu 12.04 LTS server

This guide is intended as a relatively easy step by step guide to:

Harden the security on an Ubuntu 12.04 LTS server by installing and configuring the following:

  1. Install and configure Firewall – ufw
  2. Secure shared memory – fstab
  3. SSH – Disable root login and change port
  4. Protect su by limiting access only to admin group
  5. Harden network with sysctl settings
  6. Disable Open DNS Recursion and Remove Version Info  – Bind9 DNS
  7. Prevent IP Spoofing
  8. Harden PHP for security
  9. Restrict Apache Information Leakage
  10. Install and configure Apache application firewall – ModSecurity
  11. Protect from DDOS (Denial of Service) attacks with ModEvasive
  12. Scan logs and ban suspicious hosts – DenyHosts and Fail2Ban
  13. Intrusion Detection – PSAD
  14. Check for RootKits – RKHunter and CHKRootKit
  15. Scan open Ports – Nmap
  16. Analyse system LOG files – LogWatch
  17. SELinux – Apparmor
  18. Audit your system security – Tiger

Continue reading

Advertisements

Windows Installer logging

Windows Installer handles its installations through Msiexec.exe. The logging options offered by this tool allow you to create different types of logs, depending on the information you need about the installation. These options are:

  • i – Status messages
  • w – Nonfatal warnings
  • e – All error messages
  • a – Start up of actions
  • r – Action-specific records
  • u – User requests
  • c – Initial UI parameters
  • m – Out-of-memory or fatal exit information
  • o – Out-of-disk-space messages
  • p – Terminal properties
  • v – Verbose output
  • x – Extra debugging information
  • + – Append to existing log file
  • ! – Flush each line to the log
  • * – Log all information, except for v and x options

ImportantThe logging command is issued by the /L parameter. The above options can be used only after this parameter (the options cannot be used by themselves).

Create a log

The most used logging command is /L*V. This command will create a verbose log which offers a lot of information about the installation. Here are the steps for creating a log:

  • find out the path of the MSI file, for example C:\MyPackage\Example.msi
  • decide the path of the log, for example C:\log\example.log
  • open cmd.exe (you can use any command shell)
  • use the msiexec command line to launch the MSI with logging parameters

Install Log

For creating an installation log, you can use a command line which looks like this:

msiexec /i "C:\MyPackage\Example.msi" /L*V "C:\log\example.log"

The /i parameter will launch the MSI package. After the installation is finished, the log is complete.

NoteThe example command line uses the sample paths in this How-To. For your package you must use the path of your MSI file.

Note that any logging command line should have this form:

msiexec /i <path_to_msi> /L*V <path_to_log>

After you use the logging command, you need to specify the log’s complete path. If you want the log to be created next to the MSI, you can specify only the name of the log file:

msiexec /i "C:\MyPackage\Example.msi" /L*V "example.log"

When the package is included in an EXE bootstrapper, the command line no longer uses “msiexec”. For example, the command line can look like this:

"C:\MyPackage\Setup.exe" /L*V "example.log"

Uninstall Log

In order to create a log for an uninstall process, you can replace the /i parameter with /x. Therefore, a command line which creates a log for an uninstall can look like this:

msiexec /x "C:\MyPackage\Example.msi" /L*V "C:\log\example.log"

The package path can also be replaced by the package Product Code (it can be obtained by using the Project -> Options menu inside the project). The command line would look like this:

msiexec /x {B40D5AC5-6120-4AD6-BBD4-AF5EF7E04351} /L*V "C:\log\example.log"

When the package is included in an EXE bootstrapper and it’s already installed on the machine, you can launch the installer again with the logging command. For example:

"C:\MyPackage\Setup.exe" /L*V "example.log"

This will make the package go into maintenance mode and you can choose to uninstall it. Since the package was launched with logging, an uninstall log will be generated.

Patch Install Log

You can create a log for a patch installation by using the /p parameter instead of /i:

msiexec /p "C:\MyPackage\Patch.msp" /L*V "C:\log\patch.log"

Use the EXE boostrapper

Another approach is to create a log file by using the /L*V parameters in the command line of the Advanced Installer Bootstrapper. Also, these parameters can be always passed to the MSI when the package is launched through the EXE bootstrapper.

If you want your installation package to always create a log, you can follow these steps:

  • open your installation package’s Advanced Installer project
  • go to the Media page and select the Configuration Settings Tab tab
  • check the EXE setup option
  • set the MSI Command Line field to: /L*V “C:\package.log”

This way, when the user launches the installation through the bootstrapper, an installation log (“package.log”) will be created automatically in the “C:\” drive.

ImportantThe command line received by the bootstrapper overrides the command line in the “MSI Command Line” field. Therefore, if you launch an EXE package with logging parameters, these parameters will be used for creating the log.

Automated logging with the Windows Installer Logging Policy

The logging policy is particularly useful for troubleshooting Active Directory/Group Policy deployments, in which case the installation is carried out without a user interface and there is no possibility to specify a command line for the MSI package.

In order to enable this option, you need to import the registry settings below. Please create a new text file with a “.reg” extension and then copy the following lines into it. After this, double click the “.reg” file you just created and answer “Yes” to the confirmation prompt.

REGEDIT4

[HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer]
"Logging"="voicewarmup"
"Debug"=dword:00000007

The .LOG file will be created in the currently logged on user’s Temp folder and will have a name in the following format:”MSI*.LOG”.

NoteIn case of a Active Directory/GPO deployment, there will be no logged on user at the time the installation occurs. In this case the log file will be created in the “Windows\Temp” folder.

ImportantThis option should not be left active since every install/uninstall operation of a MSI package will create a new log file, thus unnecessarily occupying disk space. Therefore, this option should only be used for debugging purposes.

In order to disable the debugging policy, you can delete the registry values you have previously added using “RegEdit.exe” or you can import the following .reg file as you did with the previous one:

REGEDIT4

[HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\Installer]
"Debug"=-

Git Tutorial Part 1: Working with branches and release versions of your Rails app

This week I am working with branches in git for the first time.  Up until now I just used my master branch for everything which works ok since I am the only developer on most of my apps, but now I realize branches will make my life alot easier in more than a few situations.  I am working with my brother on a project where it is necessary for us to use branches, so he started me on the path to git branch knowledge.  Here is my workflow so far.. and most of this relates to working with a Ruby on Rails web app that has stable milestone releases and a master branch for the future version.

I guess lets start with the basics of initializing git and using Github to host your code.  I am assuming you have git installed and you are using Github to host your main repository.. if no, proceed to Google.  Also, I am assuming you already have a project.. Rails or other.

ONE BIG NOTE: REALIZE THAT JUST BECAUSE YOU CREATE A BRANCH OR MAKE A CHANGE AND COMMIT IT ON YOUR LOCAL MACHINE, THAT DOES NOT MEAN THAT IT SENDS IT TO GITHUB OR THE MAIN REPOSITORY!!!  I WAS TOTALLY CONFUSED ABOUT THAT THE FIRST TIME I USED GIT.  LEARN TO PUSH AND PULL!

Go to your project directory, initialize git, add all the files and then make your first local commit with a message

1 cd /your_app
2 git init
3 git add *
4 git commit -m 'initial commit'

Now you are set up with your local repo. Next you need to login to (or create) your github account. You will create a new repository and name it the same thing as your local app. They will give you instructions similar to what I am telling you here after it is set up. This will add an origin to your local git config and then push all the local files that you just committed to that origin. If you have problems getting this to work, take a look in the github help about security and setting up your ssh keys here

1 git remote add origin git@github.com:your_username/your_app.git
2 git push origin master

You will get the following output

Counting objects: 22, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (19/19), done.
Writing objects: 100% (22/22), 3.73 KiB, done.
Total 22 (delta 3), reused 0 (delta 0)
To git@github.com:your_username/your_app.git
* [new branch] master -> master

What you see here is that your files were transferred to github and a new branch was created called “master”. The new branch was created automatically since there were no branches in this github project. To see what branches you have available on your local machine type:

1 git branch
* master

Your local machine knows about one branch and it is called master. Lets do some more branching now. My project is already at Version 1.0 but I am just now adding it to Github. Version 1.0 is stable and I may or may not make fixes or small additions to it. I am planning out my development roadmap and some major changes are going to happen in V2. So I don’t want to have to worry about changing and adding a bunch of crap and then realize that I need a minor fix on V1.. that would be a mess because I would have a codebase that was moving toward V2 and I would have to hack and hack in order to deploy that small change back to version 1.. what a mess. Thats where branching comes in. We need a Version 2 branch so we can keep things separate. To create another branch on your local machine do this:

1 git branch version-1_0-stable

Lets see if it worked..

1 git branch

OUTPUT:

* master
  version-1_0-stable

Yep.. there is our new branch. But notice that we are still on the master branch. Git puts a asterisks beside the current branch. In order to switch branches on our local machine, we need to use the checkout command.

1 git checkout version-1_0-stable

OUTPUT:

1 Switched to branch 'version-1_0-stable'

If you run “git branch” again, you will see a star beside version-1_0-stable. Wouldn’t it be easier if you could branch and switch all in one command? Oh yeah.. you can. Why didn’t I just say that in the first place?? Who knows, why I do alot of stuff… Here is how you delete your branch and then create it with the one-liner. Note that you can’t delete a branch you are currently on, so you must checkout back to master first:

1 git checkout master
2 git branch -D version-1_0-stable
3 git checkout -b version-1_0-stable

By throwing in that -b flag, you are telling git to create the branch and then switch to it all in one move.

Ok, cool, so I got another local branch. Why don’t I see the new branch in Github?? Because I have been working with git branches locally. Github is not aware of these changes because I have not pushed anything to it. You can see what github has by logging in and clicking on the “Switch Branches” dropdown in your project or by using the -r flag on your local box -> “git branch -r”. So now we need to tell Github about this branch.

1 git push origin version-1_0-stable

OUTPUT:

Total 0 (delta 0), reused 0 (delta 0)
To git@github.com:your_username/your_app.git
 * [new branch]      version-1_0-stable -> version-1_0-stable

Frickin awesome dude… I gots a new branch and github has it too. So I have 2 branches that I can work in separately. Most of my work will be in the master branch which is on the path to version 2, but if something craps out in V1 and I have to put in a bug fix, I just “git checkout version-1_0-stable”, make my changes, commit them, and push them to the the V1 branch. Then I could easily deploy the new code without worry about V2 code getting in the way. Lets try that out:

You are already using version-1_0-stable. So go to your editor of choice and change a file. You must commit the changes locally first. This will commit to only the current branch, so master will not get these changes since you are on version-1_0-stable. You can commit your files several ways. Here are the 2 ways I do it.
1. Commit all local changes at the same time and use -v to view the changes

1 git commit -a -v

2. Commit a single file if you have other outstanding changes that you don’t want committed yet. Just use the relative path to a single file (or * wildcard it for a whole dir).

1 git commit -v path/to/your/file

Now your local machine knows about the committed files, but not Github. You have to push.

1 git push

OUTPUT:

warning: You did not specify any refspecs to push, and the current remote
warning: has not configured any push refspecs. The default action in this
warning: case is to push all matching refspecs, that is, all branches
warning: that exist both locally and remotely will be updated.  This may
warning: not necessarily be what you want to happen.
warning:
warning: You can specify what action you want to take in this case, and
warning: avoid seeing this message again, by configuring 'push.default' to:
warning:   'nothing'  : Do not push anything
warning:   'matching' : Push all matching branches (default)
warning:   'tracking' : Push the current branch to whatever it is tracking
warning:   'current'  : Push the current branch
Counting objects: 14, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (7/7), done.
Writing objects: 100% (9/9), 815 bytes, done.
Total 9 (delta 5), reused 0 (delta 0)
To git@github.com:your_username/your_app.git
   d8b9507..862d326  version-1_0-stable -> version-1_0-stable

Look at all those warnings. WTF is git talking about?? They want us to type more options in?? Well.. I actually think this is crap, but there is probably a good reason behind the default behavior. By default it is going to push all branches that it finds on your local box over to the origin server. So for instance, if you change and commit something on master, switch branches to V1 and change and commit something on that branch too, then git will push both of them. That could potentially be dangerous if you were not ready to push master or V1. So in order to fix that you need to pass your git config some options to make it only push the current branch you are working in.

1 git config push.default current

If you look at /your_app/.git/config, then you will see it added some options to your config.

[push]
        default = current

Next time you issue the git push command the warning goes away and it only pushes the current branch. Thanks for not being an asshole this time git… I really appreciate it.

So we are looking pretty good, but there is one more thing that is bugging me. What if I make a change to V1 and I want the changes to show up in V2 also. The bug is most likely in V2, unless I removed that feature or completely re-coded it. So how do I get them darn changes over to me other branch?? Move back to master (V2), maybe check the differences so you don’t totally mess it up, and then issue the merge command:

1 git checkout master
2 git diff master version-1_0-stable
3 git merge version-1_0-stable

If you have any conflicts, the merge might not work and it will tell you to fix them. Here is the message “Automatic merge failed; fix conflicts and then commit the result.” So how do I fix the conflicts? Go to the files that it marked as conflicting. In my case, my LICENSE file was conflicted so it said:

Auto-merging LICENSE
CONFLICT (content): Merge conflict in LICENSE

So I look at the file and git has put some junk in there that shows where the conflicts are and which branch they are coming from. Just edit the file to make it work and get rid of the junk (<<<<<<<<<<).

<<<<<<< HEAD:LICENSE Copyright (c) 2010 John McAliley  ======= Copyright (c) 2009 John McAliley >>>>>>> version-1_0-stable:LICENSE

Hmm.. its 2010, the file should say that, so I edit and make it look like this:

Copyright (c) 2010 John McAliley

Then I do a “git commit -a” and the conflict has been resolved. If you issue a “git merge version-1_0-stable” then it will tell you its up to date. Cool, I guess we are done. Not so fast chief!!! Don’t forget to push it to Github

1 git push

Now we done! The change in V1 is also in V2. Go drink a beer. You deserve it.

I think that about covers my workflow as it stands now aside from pulling using the rebase command. Yehuda Katz has an excellent tutorial on his Git workflow regarding pulling, pushing and resolving conflicts (although he does not go into branching). I have only been doing branching and versioning in git for a week, so I am sure some of you git masters might have a better workflow. If so, don’t be stingy.. leave a comment and show people a better way. Next tutorial will cover tagging as related to minor version changes in the master before it is actually considered stable. Check out the ruby on rails source in github if you can’t wait. They use branches and tagging for major and minor releases (including betas in the master branch)

Guide To Buying A Linux Laptop

ll major laptop (notebook) hardware is supported by Linux. The important things to take into account when looking to buy a Linux powered laptops are as follows to avoid any hardware compatibility problems. Selecting correct specification is important. In this first part, I will cover what to look out for when buying a Linux powered laptop.

Laptop Usage

First, you need to decide and define the purpose of your laptop. Linux laptop can be used for simple office tasks and browsing the Internet or sending e-mails, than a mid-range laptop may be good enough:

  1. Define your budget
  2. Define screen size notebook (13″ or 15″ or 17″)
  3. Define your tasks such as Internet, sys admin, software development, some gaming using Win Vista / 7, dual booting etc.
  4. How many hours of battery life do you need?
  5. Define optical media types – Do you want to watch movies using DVD or Blu ray? Do you want to burn DVDs?
  6. To play games you need a top spec laptop. Please note that Linux has limited support for popular PC gaming titles. So you need to dual boot your laptop with MS-Windows operating systems.
  7. Finally, some people prefer desktop replacements with mobile workstations.

In short, decide how you are going to be using the Linux laptop.

Central Processing Unit (CPU)

CPU is the brain of your laptop. Linux supports all sort of mobile cpus. Linux does supports SMP cpus on servers and it does support portables cpus too. The following are well know mobile cpus:

  • Intel Atom
  • Intel Core 2 Duo
  • Intel Core i5 Duo
  • Intel Core i7 Duo or Quad
  • AMD Athlon 64 Mobile
  • AMD Turion 64 X2

The speed range from 1.3GHz to 2.2GHz or more. The number of cores plays an important role too. Naturally, a quad core CPU should be able to increase the number of calculations. This is useful when you run multiple applications, you will get fast and smooth response from the system. The Intel Core 2 Duo or AMD Turion 64 II (dual core) is pretty popular choice for CPU. My advice is go for 64 bit CPU with 64 bit Linux distro.

Video Card and X Server

This is the most important part in Laptop which is used by X Windows. However, selecting correct Video card is important; otherwise you will end up with 3D hardware accelerated card with 2D Linux driver or just basic display. So make sure your video card with 3D acceleration is supported under Linux. Nvidia has pretty good support with a proprietary driver which can deliver full 3D acceleration with 24 bit color. On other hand ATI drivers are open source. My advice is simple visit the following driver pages and make sure your video card is fully supported including 3D acceleration:

Low End Video Cards

The following list summaries low end fully supported Linux video cards:

  • Intel GMA 4500MHD
  • Intel 945GM
  • Intel 950 GMA
  • Intel X3100 GMA
  • NVIDIA Quadro NVS 160M (256MB)

Mid to High-End Video Cards

The following list summaries mid-high end priced fully supported Linux dedicated video cards (useful for playing 3D videogames or engineering Linux apps or video / photo editing):

  • NVIDIA Quadro FX 880M (1024 MB)
  • NVIDIA Quadro FX 2800M (1024 MB)
  • NVIDIA Quadro NVS 3100M (256 or 512 MB)
  • NVIDIA GeForce 9300M GS
  • NVIDIA GeForce 9300M
  • Intel GMA X4500 HD
  • ATI FirePro M7740 (1024 MB)
  • ATI Radeon HD 3650 (512 MB)
  • ATI Mobility Radeon HD4650 (1024 MB)

Finally, make sure external X display to your desktop monitor is fully supported. This can come handy when you want to watch movies, play games or do business presentation.

RAM

RAM (Random Access Memory) is another factor which can boost your speed easily, especially if you use RAM intensive apps like virtualization desktop software (e.g., VMWareor VirtualBox), photo editing (e.g., Gimp), video editing etc. 2 to 4 GB should be more than sufficient for most apps. A few high end laptops can support upto 16GB ram and Linux canaccess more than 4GB ram using PAE or 64bit kernel out of the box.

Hard Disk

Hard disk is used to store all your data and boot into Linux. Hard disks are cheaper, nosier and stores data on moving parts called rotating platters. You can have 7200rpm drives. Another option is to use SSD ( Solid State Drives ) as storage device which offers the following benefits:

  1. Speed (2 times faster than hard disk)
  2. Lighter and quieter (no moving parts)
  3. Consume less power
  4. Faster booting time.

You can add additional storage using USB or Firewire ports (i.e. external hard disk). My advice is go for SSD.

Optical Disk

Linux does support DVDs, Blu ray and other optical formats. This is useful for playing DVDs or backing up data via DVD/CD burner. DVD burner is fine for most applications. But, if you are interested in playing movies using Blu ray (HD DVD / Blu Ray disks), you will need to get Blue ray optical drive which can read and write DVDs too. However, the AACS ‘Digital Rights Management’ system in most HD-DVD and all Blu-Ray discs attempts to stop consumers from exercising fair use rights, including – playing purchased Blu-Ray and HD DVD films using Open Source software. To play Blu ray you need the latest version of mplayer and DumpHDto perform the decryption necessary to play the film. If you can afford go for Blu ray. See how to play Blu-Ray and HD DVD video under Ubuntu Linux.

Power Management: Suspend and Hibernate

Linux supports both AMP ( Advanced Power Management ) and ACPI (Advanced Configuration and Power Interface ) which allows you to hibernate the system to a disk partition using swsusp (Software Suspend). It is a suspend-to-disk implementation in the 2.6 series Linux kernel. However, some laptop may give you problem with swsusp. You may also need to compile kernel to include swsusp support. Make sure you get ACPI compliant BIOS and you should be fine with power management. Some time you may need to download a patch from 3rd party or vendor site to enable suspend and hibernate support under Linux.

Wireless 802.11

Another hardware device may not work at all; if you do not pay attention to wireless devices. Most laptops comes with on-board 802.11 (a/b/g/N) wireless cards. Not all card supported so make sure you get Intel Pro series card such as 3945 or Atheros based cards. My advice is use Google to search for your driver or use specialized databases (a more or less complete listing of wireless devices with information about the chipset they are based on and whether or not they are supported in Linux) to search for your laptop card.

Biometric Fingerprint Scanner

Fingerprint scanners are security systems of biometrics. If you work for Government, DoD, police, security industries and, if data security and authentication is your top priority, you need “Biometric Fingerprint Scanner”. Every fingerprint is special and different from each other. You can use Linux PAM to hook fingerprint reader with KDM, GDM, sudo, su and many other services. The fingerprint scanners on the following models are known to work:

  • IBM ThinkPad T and X series selected models (see list of supported devices)
  • Dell Latitude selected models
  • HP Pavilion (selected model)

Please refer the following additional pages and make sure your laptop model is supported:

  • The fprint project aims to plug a gap in the Linux desktop: support for consumer fingerprint reader devices.
  • Fedora project wiki page describing supported devices and software for fingerprint devices.

Fn key (BlueKey) Support

Fn, or Function, is a modifier key on many keyboards, especially on laptops, used in a compact layout to combine keys which are usually kept separate. It is mainly used for the purpose of changing display or audio settings quickly, such as brightness, contrast, or volume, and is held down in conjunction with the appropriate key to change the settings. These features may be supported under Linux via driver or software. I found most laptop from reputed manufacture (such as Dell, IBM) does supports Fn keys.

Ports

The following are common ports for laptop:

  1. USB – It is well supported under Linux for external hard disk, pen, mouse, keyboard and much more.
  2. FireWire – It may or may not work out of box. In most cases you need to compile the Linux kernel so that you can access Zip drives, hard drives, and CDRW/DVD drives. However, support is limited. See Linux kernel IEEE 1394/ FireWire drivers wiki page for more information.
  3. eSATA -External SATA provides a variant of SATA meant for external connectivity. It allows you to connect external SATA hard drives directly to the SATA bus. You get faster speed as compare to USB or Firewire external hard disks. This may or may not work out of box.

Sound

Most on board sound card should work fine with Linux. You can play all sort of music file such as .mp3, .wav, .ogg and much more. Linux comes with various playback and mp3 players. You can rip audio cds too.

Docking Station (Port Replicator)

Docking station and port replicator provides a simplified way of “plugging-in” an electronic device such as a laptop computer via common peripherals. You can plug desktop monitor, keyboard, printer, mouse, Palm Pilot and so on. Most docking station should work out of the box. Just confirm this with your vendor.

Ethernet (NIC)

Most NICs are supported but it is a good idea to go through Google and make sure your Ethernet card is supported. Usually, Intel and Broadcom (tg3) Ethernet cards are well supported. See Linux PCI ids database and search for your sound and Ethernet card names. Usually, most drivers are included in running kernel. In rare case you may have to compile the kernel or driver to support your Ethernet card.

Tip: Test Your Laptop With Linux (Try Before You Buy)

Most vendors have a showrooms and shops. Visit nearest shop with Linux Live CD (such asKnoppix or Ubuntu or Fedora ) and ask them to boot laptop using Live CD. See if it works or not; boot into Linux. Make sure you can see X Windows, connects to the Internet via wireless card and so on. If you get 100% result, then just purchase it.

Recommend Linux Distribution

Linux is all about choices. Personally, I use Redhat v5.x 64 bit at work and Ubuntu Linux 64 bit at home. My recommendation:

  1. Ubuntu (any flavor) Linux – For the average user, with a strong focus on usability and ease of use and installation.
  2. Fedora Linux – Another popular disro for the average user with rpm based packages. Fedora is also popular among Windows and UNIX sys admins.
  3. OpenSuse Linux – Easy to use and certified on selected HP / IBM laptops.
  4. Debian Linux – For the advanced users, sys admin and academic researchers.
  5. Slackware Linux – One of the oldest distro, preferred by sys admins, BSD lovers and academic researchers.

Linux Laptop Vendors

Now, you know how to choose a laptop, especially you need to pay attention to wireless, video card and Ethernet card. And here is exact model names & number that will be fully compatible to LINUX and vendor website (the list is for information and ready references only; please do your own research before purchasing system):

  1. Dell sales Ubuntu Laptop in USA, Canada, UK, France, Germany, Spain and Latin America. (See official Ubuntu page). Dell India also sales high end Redhat Linux based laptop for business use.
  2. HCL provides Ubuntu / Redhat / Fedora Linux based laptop in India.
  3. Acer India provide Aspire series Linux based laptop in India.
  4. HP Novell / Suse Linux certification and support matrix for HP laptops.
  5. Asus Linux based eeepc netbooks in USA, India, UK, and various other places across the globe.
  6. EmperorLinux provides Linux laptops with full hardware support under Linux in USA.
  7. LinuxCertified provide Linux laptop and support in USA.
  8. Linuxemporium provide Linux laptop and support in UK.
  9. System76 provides Ubuntu Linux laptop and support in USA and Canada.
  10. Zareason provides Ubuntu Linux laptop in USA, but claims to ship to many other places across the globe.

Your Own Linux Kernel Module with a Simple Example

What are kernel modules?

Kernel modules are piece of code, that can be loaded and unloaded from kernel on demand.

Kernel modules offers an easy way to extend the functionality of the base kernel without having to rebuild or recompile the kernel again. Most of the drivers are implemented as a Linux kernel modules. When those drivers are not needed, we can unload only that specific driver, which will reduce the kernel image size.

The kernel modules will have a .ko extension. On a normal linux system, the kernel modules will reside inside /lib/modules/<kernel_version>/kernel/ directory.

Earlier we discussed how to compile a kernel from the source.

This tutorial explains how to write a Kernel module using a simple Hello World example.

I. Utilities to Manipulate Kernel Modules

1. lsmod – List Modules that Loaded Already

lsmod command will list modules that are already loaded in the kernel as shown beblow.

# lsmod
Module Size Used by
ppp_deflate 12806 0
zlib_deflate 26445 1 ppp_deflate
bsd_comp 12785 0
..
2. insmod – Insert Module into Kernel

insmod command will insert a new module into the kernel as shown below.

# insmod /lib/modules/3.5.0-19-generic/kernel/fs/squashfs/squashfs.ko

# lsmod | grep “squash”
squashfs 35834 0
3. modinfo – Display Module Info

modinfo command will display information about a kernel module as shown below.

# modinfo /lib/modules/3.5.0-19-generic/kernel/fs/squashfs/squashfs.ko

filename: /lib/modules/3.5.0-19-generic/kernel/fs/squashfs/squashfs.ko
license: GPL
author: Phillip Lougher
description: squashfs 4.0, a compressed read-only filesystem
srcversion: 89B46A0667BD5F2494C4C72
depends:
intree: Y
vermagic: 3.5.0-19-generic SMP mod_unload modversions 686
4. rmmod – Remove Module from Kernel

rmmod command will remove a module from the kernel. You cannot remove a module which is already used by any program.

# rmmod squashfs.ko
5. modprobe – Add or Remove modules from the kernel

modprobe is an intelligent command which will load/unload modules based on the dependency between modules. Refer to modprobe commands for more detailed examples.

II. Write a Simple Hello World Kernel Module

1. Installing the linux headers

You need to install the linux-headers-.. first as shown below. Depending on your distro, use apt-get or yum.

# apt-get install build-essential linux-headers-$(uname -r)
2. Hello World Module Source Code

Next, create the following hello.c module in C programming language.

#include <linux/module.h> // included for all kernel modules
#include <linux/kernel.h> // included for KERN_INFO
#include <linux/init.h> // included for __init and __exit macros

MODULE_LICENSE(“GPL”);
MODULE_AUTHOR(“Lakshmanan”);
MODULE_DESCRIPTION(“A Simple Hello World module”);

static int __init hello_init(void)
{
printk(KERN_INFO “Hello world!\n”);
return 0; // Non-zero return means that the module couldn’t be loaded.
}

static void __exit hello_cleanup(void)
{
printk(KERN_INFO “Cleaning up module.\n”);
}

module_init(hello_init);
module_exit(hello_cleanup);
Warning: All kernel modules will operate on kernel space, a highly privileged mode. So be careful with what you write in a kernel module.

3. Create Makefile to Compile Kernel Module

The following makefile can be used to compile the above basic hello world kernel module.

obj-m += hello.o

all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
Use the make command to compile hello world kernel module as shown below.

# make

make -C /lib/modules/3.5.0-19-generic/build M=/home/lakshmanan/a modules
make[1]: Entering directory `/usr/src/linux-headers-3.5.0-19-generic’
CC [M] /home/lakshmanan/a/hello.o
Building modules, stage 2.
MODPOST 1 modules
CC /home/lakshmanan/a/hello.mod.o
LD [M] /home/lakshmanan/a/hello.ko
make[1]: Leaving directory `/usr/src/linux-headers-3.5.0-19-generic’
The above will create hello.ko file, which is our sample Kernel module.

4. Insert or Remove the Sample Kernel Module

Now that we have our hello.ko file, we can insert this module to the kernel by using insmod command as shown below.

# insmod hello.ko

# dmesg | tail -1
[ 8394.731865] Hello world!

# rmmod hello.ko

# dmesg | tail -1
[ 8707.989819] Cleaning up module.
When a module is inserted into the kernel, the module_init macro will be invoked, which will call the function hello_init. Similarly, when the module is removed with rmmod, module_exit macro will be invoked, which will call the hello_exit. Using dmesg command, we can see the output from the sample Kernel module.

Please note that printk is a function which is defined in kernel, and it behaves similar to the printf in the IO library. Remember that you cannot use any of the library functions from the kernel module.

Now you have learned the basics to create your own Linux Kernel module.