Technical stuff

Adding a simple system call to the Linux 3.2.0 Kernel from scratch


As a part of my Operating System lab works, I had recently implemented a simple system call to the Linux 3.2.0 Kernel.

We can add changes in the kernel only if it is compiled or not. So in our case before adding a system call, we need to compile the kernel in our machine. Remember, you need to have at least 8 GB of free space in your root folder before you start compilation. Otherwise the compilation will end up with showing the error message that there’s not enough disk space in your machine and you will not be able to use that linux machine anymore. So it is preferred to test it in a virtual box with atleast 8 GB of free space!

Dependencies

Lets install all the dependency packages (gcc and libncurses5-dev)

$ sudo apt-get install gcc libncurses5-dev

Then update and install all the upgrade your machine.

$ sudo apt-get update && sudo apt-get upgrade

I am trying with Linux kernel 3.2 there are various other kernels available like 3.0, 3.4, 3.6 etc. You can download the kernel from kernel.org .

$ wget http://www.kernel.org/pub/linux/kernel/v3.0/linux-3.X.tar.bz2

Extract the tarball to /usr/src/linux-3.X/

$ sudo tar -xvf linux-3.X.tar.bz2 -C /usr/src/linux-3.X/

Change the directory to /usr/src/linux-3.x

$ cd /usr/src/linux-3.x

Configure

Lets configure our new Linux Kernel with the configuration of old kernel (which is already installed in our machine)

$ sudo make oldconfig

Linux kernel source compilation

$ sudo make -j2

‘-j2’ is useful for multiprocessing in multiprocessor machines.

Compilation errors and solutions

There’s a possibility that you may come across an ERROR message like this while compiling

ERROR: "__modver_version_show" [drivers/staging/rts5139/rts5139.ko] undefined!
WARNING: modpost: Found 4 section mismatch(es).
To see full details build your kernel with:
'make CONFIG_DEBUG_SECTION_MISMATCH=y'
make[1]: *** [__modpost] Error 1
make: *** [modules] Error 2

I got it to work by changing the value of CONFIG_RTS5139=n in .config file in source pre directory. This will disable that Realtek RTS5139 USB card reader support module which is not necessary for kernel compilation.
Again I compiled the kernel with CONFIG_DEBUG_SECTION_MISMATCH flag enabled. And this time, it worked for me! (it took me almost 23 minutes to compile in a machine with a 3 GHz xeon processor and with 4 GB of physical memory).

To Install

Next step is to install the compiled kernel

$ sudo make modules_install install

The above command will install the Linux Kernel 3.0 into your system. It will create some files under /boot/ directory and it will automatically make a entry in your grub.cfg. Check whether it made correct entry and check for the files it created.
The files under /boot/ directory are,

  • System.map-3.0.0
  • vmlinuz-3.0.0
  • initrd.img-3.0.0
  • config-3.0.0

If you unable to find the initrd.img-3.0.0 file then create it. Run the below command to create it.

$ sudo update-initramfs -u -k 3.X.X

To Update

If the above command unable to update / generate the initramfs then run the following command to create new initramfs.

$ sudo update-initramfs -c -k 3.X.X

You can update the grub in-order to make changes in grub

$ sudo update-grub2

Restart your system and from the previous kernels you can choose the newly installed kernels name. To check after booting open a terminal and type “uname -r“.

Writing simple “hello world” system call

Now lets add the system call!!

Writing the system call itself is pretty much the simplest part of this whole process, so we shall start there. First, create a new directory in the root of a clean copy of the kernel sources created for this tutorial. Call the new directory “hello”. In this directory, we need to create two files. The first of which is the implementation of the system call itself, hello.c:

#include <linux/kernel.h>:

asmlinkage long sys_hello(void) {
    printk("Hello World\n");
    return 0;
}

After creating the system call, we need to set up the Makefile to build it. Add the following to a Makefile in the same directory as hello.c:

obj-y := hello.o

This is a very simple Makefile, since the build system of the kernel takes care of most of the work for you. This concludes the new files that will need to be added to the kernel sources to make a new system call.

Kernel changes needed to reflect the new system call

There are a few source files in the kernel that will need to be updated in order to reflect the new system call to be added to the kernel. The first, and simplest of these is the root-level Makefile. Find the following line, around line 711 of the root-level Makefile:

core-y := kernel/ mm/ fs/ ipc/ security/ crypto/ block/

Assuming you created the new hello directory, add a hello/ to the end, as shown:

core-y := kernel/ mm/ fs/ ipc/ security/ crypto/ block/ hello/

It would be a good idea to set the EXTRAVERSION in the Makefile as well, to differentiate it from your normal kernel.

Next, open the include/linux/syscalls.h file, and add a definition for your new system call. Right after the line mentioning sys_setns (around line 849 of the file), add the following:

asmlinkage long sys_hello(void);

This step makes your system call available to other parts of the kernel that may wish to call it. While this is not necessary for this simple system call, it is still good practice for when adding a real system call to the kernel.

Next, open the arch/x86/include/asm/unistd_32.h file, and search for the following lines:

#define __NR_setns 346
#ifdef __KERNEL__
#define NR_syscalls 347

Between the __NR_setns and #ifdef __KERNEL__ lines, add the following:

#define __NR_hello 350

In addition, update the NR_syscalls line to 348, since you have added a new system call.

The final file that needs to be updated is the system call table, which resides in arch/x86/kernel/syscall_table_32.S. Add the definition for your new system call, by adding the following:

 .long sys_hello

You should add this after the definition for the previous latest syscall, which should be a line that mentions sys_setns.

Congratulations, you have now added a new system call to the Linux kernel. Follow the normal steps to build the kernel, and fix any problems you may find in compilation (if you followed this exactly, you should not have any).

Testing the new system call

The next step is to test out your system call to make sure it works. Be sure to reboot into your new kernel, then write the following in a new .c file (not in the kernel source tree):

#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <linux/kernel.h>
#include <sys/syscall.h>
#define __NR_hello 350

long int hello_syscall(void) {
    return syscall(__NR_hello);
}

int main(int argc, char *argv[]) {
    long int output = hello_syscall();
    printf ("The hello_syscall() returned %ld\n", output);
    return 0;
}

Compile the program, run it and check the dmesg command to see the “Hello World” output!

$ gcc hello.c -o hello
$ ./hello && dmesg
The hello_syscall() returned 0

References: [1] http://www.cs.carleton.edu/faculty/jondich/courses/cs307_s02/documents/syscall.html
[2] http://bluegrit.cs.umbc.edu/~lsebald1/cmsc421/new-syscall.php
[3] http://askubuntu.com/questions/121807/error-when-i-compile-kernel-3-3-2-in-ubuntu-12-04
[4] http://www.howopensource.com/2011/08/how-to-compile-and-install-linux-kernel-3-0-in-ubuntu-11-04-10-10-and-10-04/

Advertisements

An overview of Stack


In this semester, I’ve a core subject named Computer Language Engineering,
which mainly focuses on the design of Compilers. But today, Prof.
SushasKurup M took a very good session on the stack structure, this
intended me to write a blog on “Stack”. Hope that you will enjoy it!!

A stack is a contiguous block of memory containing data. A register called
the stack pointer (SP) points to the top of the stack. The bottom of the
stack is at a fixed address. Its size is dynamically adjusted by the kernel
at run time. The CPU implements instructions to PUSH onto and POP off of the
stack.

The stack consists of logical stack frames that are pushed when calling a
function and popped when returning. A stack frame contains the parameters to
a function, its local variables, and the data necessary to recover the
previous stack frame, including the value of the instruction pointer at the
time of the function call.

Depending on the implementation the stack will either grow down (towards
lower memory addresses), or up. In our examples we’ll use a stack that grows
down. This is the way the stack grows on many computers including the Intel,
Motorola, SPARC and MIPS processors. The stack pointer (SP) is also
implementation dependent. It may point to the last address on the stack, or
to the next free available address after the stack. For our discussion we’ll
assume it points to the last address on the stack.

In addition to the stack pointer, which points to the top of the stack
(lowest numerical address), it is often convenient to have a frame pointer
(FP) which points to a fixed location within a frame. Some texts also refer
to it as a local base pointer (LB). In principle, local variables could be
referenced by giving their offsets from SP. However, as words are pushed onto
the stack and popped from the stack, these offsets change. Although in some
cases the compiler can keep track of the number of words on the stack and
thus correct the offsets, in some cases it cannot, and in all cases
considerable administration is required. Further more, on some machines, such
as Intel-based processors, accessing a variable at a known distance from SP
requires multiple instructions.

Consequently, many compilers use a second register, FP, for referencing
both local variables and parameters because their distances from FP do
not change with PUSHes and POPs. On Intel CPUs, BP (EBP) is used for this
purpose. On the Motorola CPU’s, any address register except A7 (the stack
pointer) will do. Because the way our stack grows, actual parameters have
positive offsets and local variables have negative offsets from FP.

The first thing a procedure must do when called is save the previous FP
(so it can be restored at procedure exit). Then it copies SP into FP to
create the new FP, and advances SP to reserve space for the local variables.
This code is called the procedure prolog. Upon procedure exit, the stack
must be cleaned up again, something called the procedure epilog. The Intel
ENTER and LEAVE instructions and the Motorola LINK and UNLINK instructions,
have been provided to do most of the procedure prolog and epilog work
efficiently.

Let us see what the stack looks like in a simple example:

Example1.c:

#include
void function(int a, int b, int c)
{
char buffer1[5];
char buffer2[10];
}

void main()
{
function(1,2,3);
}

To understand what the program does to call function() we compile it with
gcc using the -S switch to generate assembly code output:

 $ gcc -S -o example1.s example1.c

By looking at the assembly language output we see that the call to
function() is translated to:

pushl $2
pushl $1
call function

This pushes the 3 arguments to function backwards into the stack, and
calls function(). The instruction ‘call’ will push the instruction pointer
(IP) onto the stack. We’ll call the saved IP the return address (RET). The
first thing done in function is the procedure prolog:

pushl %ebp
movl %esp,%ebp
subl $20,%esp

This pushes EBP, the frame pointer, onto the stack. It then copies the
current SP onto EBP, making it the new FP pointer. We’ll call the saved FP
pointer SFP. It then allocates space for the local variables by subtracting
their size from SP.

We must remember that memory can only be addressed in multiples of the
word size. A word in our case is 4 bytes, or 32 bits. So our 5 byte buffer
is really going to take 8 bytes (2 words) of memory, and our 10 byte buffer
is going to take 12 bytes (3 words) of memory. That is why SP is being
subtracted by 20. With that in mind our stack looks like this when
function() is called (each space represents a byte):


bottom of top of
memory memory
buffer2 buffer1 sfp ret a b c
<------ [ ][ ][ ][ ][ ][ ][ ]

top of bottom of
stack stack

Crack Windows-XP Administrator account Password


Computer Lab sessions seems to be the most boring sessions, if it is not utilized properly. I hacked into Windows XP Administrator account using Ubuntu 10.10. Before getting into windows it is important to become a root user in Ubuntu/Linux. Grub (a list shown during system startup to choose the Operating systems installed in the system) can be used to get root shell. Move the cursor to the Linux Distro’s (say Ubuntu 11.10 Natty) option and press ‘e’ (option to edit the grub). At the end of the third line in the new list there will be ro quit splash replace that word by rw init=/bin/bash. This will redirect you to a bash shell of root user. Then press ctrl + x to boot. Prompt with ‘root’ as prefix will appear. This means full access to the system! Now, edit /etc/sudoers
In order to edit /etc/sudoers you have to use visudo editor

Find this line: root ALL=(ALL) (ALL) and just under this line add a line, in which desired User name should be given.
your-username ALL=(ALL) ALLNow reboot system using this command Login in to the system using the given user name and password and you are now the root user of the system. Open a terminal (applications->terminal or use default shortcut: ctrl+alt+t) and install chntpw – utility to overwrite Windows NT/2000 SAM passwords.Find out the partition in which you have install the windows using any of these commands:

$ sudo fdisk -l
$ sudo parted /dev/sda print

Now, mount the Windows File system(C drive in most of the case) Using this command:

$ sudo umount /dev/sda# /mnt/

#-the respective number of the Windows partition that you found using the command fdisk and parted
/mnt- the directory where you are going to mount. You can give it anywhere you want. I prefer this directory.

Change the directory to Windows partition under the directory mnt, using cd command. Then using your basic Linux skills try to get into the directory Windows/System32/config using cd command.
You are now almost done. Use this command to modify the file SAM – Security Account Manager (is a database present on servers running Windows Server 2003 that stores user accounts and security descriptors for users on the local computer):

$ sudo chntpw SAM

When you use this command you will get this.

* SAM policy limits:
Failed logins before lockout is: 0
Minimum password length : 0
Password history count : 0
| RID -|---------- Username ------------| Admin? |- Lock? --|
| 01f4 | Administrator | ADMIN | dis/lock |
| 03e8 | corelabs | ADMIN | |
| 01f5 | Guest | | *BLANK* |
| 03ee | HomeGroupUser$ | | |
| 03e9 | VUSR_CORELABS-PC | | |
---------------------> SYSKEY CHECK Not Set (not installed, good!)
SAM Account\F : 0 -> off
SECURITY PolSecretEncryptionKey: -1 -> Not Set (OK if this is NT4)
Syskey not installed!

RID : 0500 [01f4]
Username: Administrator
fullname:
comment : Built-in account for administering the computer/domain
homedir :

User is member of 1 groups:
00000220 = Administrators (which has 2 members)

Account bits: 0x0211 =
[X] Disabled | [ ] Homedir req. | [ ] Passwd not req. |
[ ] Temp. duplicate | [X] Normal account | [ ] NMS account |
[ ] Domain trust ac | [ ] Wks trust act. | [ ] Srv trust act |
[X] Pwd don't expir | [ ] Auto lockout | [ ] (unknown 0x08) |
[ ] (unknown 0x10) | [ ] (unknown 0x20) | [ ] (unknown 0x40) |

Failed login count: 0, while max tries is: 0
Total login count: 1

- - - - User Edit Menu:
1 - Clear (blank) user password
2 - Edit (set new) user password (careful with this on XP or Vista)
3 - Promote user (make user an administrator)
4 - Unlock and enable user account [probably locked now]
q - Quit editing user, back to user select
Select: [q]>

Based on your necessity, you can use any of these options [1, 2, 3, 4, q]
Don’t forget to save the file-SAM after changes or else there wont be any results. When you boot to Windows next time you will be able to access Administrative account if you have used options-[1 & 2].

Hacking is fun, so Have fun!!

Summer Vacation!! It time to think wisely and do something great.


I have found the summers to be most productive. So i urge students, to use that time very wisely, you can accomplish a lot. There are many such opportunities available.

1. Open Source contribution

a. *Google Summer of Code* – http://socghop.appspot.com Google Summer of Code is a global program that offers student developers a stipend of $5000 to write code for various open source software projects.

b. *Season of KDE* – http://blog.lydiapintscher.de/2011/04/25/announcing-season-of-kde-2011/ – For all those who applied for KDE for GSoC and could not get through, here is a second chance.

Do not be under the impression that one needs a lot of experience to participate in these contests. Students even without prior open source experience, but who show interest to learn more, always get accepted!

2. Programming contests: If you like programming, there are many places you can start off.

1. *SPOJ* – Its an online judge where you can test your programming skills by solving interesting problem. http://www.spoj.pl/problems/classical/sort=-6 It also has a forum where you can discuss problems in case you are not getting the solution. There are always people there to help out.

2. *CodeChef* – Its the local online judge in India. http://www.codechef.com/problems/easy

3. *Coding bat* – If you like python, here is the place to start off -> http://codingbat.com/

4. *Google Code Jam* – is a programming competition in which professional and student programmers are asked to solve increasingly complex algorithmic challenges in a limited amount of time. The contest is all-inclusive: Google Code Jam lets you compete in the programming language and development environment of your choice. For more information – http://code.google.com/codejam

3. *Application for science competition* – You can build applications to enhance and customize the end-user’s search needs, improving their research through a library Sciverse application. For more information about the challenge go to http://appsforscience.com

4. *One month – Internship for pre-final year students* :- Opensoft initiates a Month – Internship & Research Workshop” in  various Languages like PHP, Perl, Python. And Web CMS’s like Drupal, Joomla & WordPress. For information go to -> http://www.opensoftworkshop.com

5. *Graphic designer full time intern* –  If you are interested in Web Sites(HTML & Flash) and iPhone/iPad/Android you are in the right place. visit – > http://columbusagain.recruiterbox.com/jobs/3239/ . Note : location – Chennai.

6. *Software developer full time intern* – Software Developer with strong skills in programming, Exposure to Linux, PHP, mySQL, Web Technologies HTML/CSS/JS. Visit -> http://columbusagain.recruiterbox.com/jobs/3177 . Note : location – Chennai.

7. *Mobile Application Development for Desktop Summit* – Desktop Summit is the both GUADEC(GNOME’s annual conference) and  Akademy(KDE’s annual conference) being held together. This time it’s from  August 5th to August 12th. The organizers are looking for people to create  mobile apps for the event. More details can be found here<http://blog.lydiapintscher.de/2011/05/26/mobile-apps-for-the-desktop-…>

8. *HIT Lab NZ Winter of Code Internship Opportunity June 2011* –  The HIT Lab NZ is looking for three extremely talented graduate or undergraduate students that would like to spend the winter in New Zealand working as student interns on a very interesting outdoor Augmented Reality (AR) project. Click here to apply Winter of Code Internship Application. For more information please contact info@hitlabnz.org