- HACKING UNIX -
                -----------------------------------

This is the combined version of all parts.

Author: detach (XT) - [email protected]
WWW: http://www.duho.org/

INDEX:

1. - Security and Vulnerabilities
  1.0. - Forword
  1.1. - Audience
  1.2. - Conventions
  1.3. - Orientation
  1.4. - Vulnerabilities
       1.4.1 - Full Disclosure
       1.4.2 - Exploit Code
       1.4.3 - 'Access Levels' and 'Environments' and 'Security'
  1.5. - Where do vulnerabilities occur?
  1.6. - Who finds vulnerabilities
  1.7. - Last words
2. - System Profiling
  2.0. - Forword
  2.1. - Introduction
  2.2. - Protocols
       2.2.1 - Network Protocols
       2.2.2 - Application Protocols
  2.3. - Portscanning well-known network services
  2.4. - Widely used Application Protocols - Detailed
       2.4.1 - FTP
       2.4.2 - SSH
       2.4.3 - TELNET
       2.4.4 - SMTP
       2.4.5 - DNS
       2.4.6 - HTTP
       2.4.7 - POP3
  2.5. - OSI (network protocols - a deeper look)
       2.5.1 - The Application layer
       2.5.2 - The Presentation layer
       2.5.3 - The Session layer
       2.5.4 - The Transfer layer
       2.5.5 - The Network layer
       2.5.6 - The Data-Link layer
       2.5.7 - The Physical layer
  2.6. - Back to system profiling
       2.6.1 - The importance of system profiling
       2.6.2 - "Planning"
             2.6.2.1 - Available Information
             2.6.2.2 - Active Server-oriented Information probing
             2.6.2.2.1 - PING
             2.6.2.2.2 - DNS & Zone Transfers
             2.6.2.2.3 - WHOIS
             2.6.2.2.4 - Scanning Services
  2.7. - Last words
3. - After the break-in
  3.0. - Forword
  3.1. - Introduction
  3.2. - Hiding your source location
       3.2.1 Hopping the internet
  3.3. - Wiping the logs
       3.3.1 - UTMP
       3.3.2 - WTMP
       3.3.3 - LASTLOG
       3.3.4 - Using logwipers
       3.3.5 - Other logs
       3.3.6 - Wiping the plaintext logs
  3.4. - Installing rootkits
       3.4.1 - Trojaned binaries
       3.4.2 - Kernel Modules
  3.5. - Installing backdoors
       3.5.1 - Basic local backdoors
       3.5.2 - Basic remote backdoors
       3.5.3 - Trojaned services
       3.5.4 - Advanced Backdooring
             3.5.4.1 - Covert channels
             3.5.4.2 - WebApplication backdoors
             3.5.4.3 - Others
  3.6. - Spy!
       3.6.1 - Sniffers
       3.6.2 - Other stuff
  3.7. - Final words
4. - Dealing with Firewalls
  4.0. - Forword
  4.1. - Introduction
  4.2. - Packet Filtering Firewalls
       4.2.1 - A pracical Example
  4.3. - How does the packet filter work
       4.3.1 - Introduction
       4.3.2 - Stateless or Stateful
  4.4. - Dealing with Firewalls
       4.4.1 - Introduction
       4.4.2 - 2D mapping of a firewall ruleset
       4.4.3 - 3D mapping of a firewall ruleset
  4.5. - Using the gathered information
  4.6. - Final words
5. - Passive network attacks
  5.1. - Introduction
  5.2. - Sniffing shared networks
       5.2.1 - Introduction
       5.2.2 - Sniffer construction
       5.2.3 - Sniffer detection
             5.2.3.1 - Local
             5.2.3.2 - Remote
  5.3. - Sniffing switched networks
       5.3.1 - Introduction
       5.3.2 - ARP poisoning
             5.3.2.1 - ARP Introduction
             5.3.2.2 - ARP table poisoning
             5.3.2.3 - DoS
             5.3.2.4 - ARP Man in the Middle
             5.3.2.5 - Detection
       5.3.3 - Switch table poisoning
             5.3.3.1 - Switch Introduction
             5.3.3.2 - Switch redirection
             5.3.3.3 - Man in the Middle

****************************************************************

                         - HACKING UNIX -
                           CHAPTER ONE:

                   Security and Vulnerabilities
                -----------------------------------

0. Forword

Yes, this is another tutorial trying to put 'all-in-one'. As far is I know
there is not a good and recent written tutorial like this. Old texts do
still have a value though, but i think much is obsolete now. Examples of
such tutorials are:

* User's Guide 1.0 - Phantom
* A Novice's Guide to Hacking (1989) - The Mentor [LOD]
* NEWBIES HANDBOOK ; HOW TO BEGIN IN THE WORLD OF H/P - Plowsk� Phreak
* THE ULTIMATE BEGINNER'S GUIDE TO HACKING AND PHREAKING - REVELATION [LOA--ASH]
* Beginners Guide to VAX/VMS Hacking (1989) - ENTITY [Corrupt Computing Canada]
* THE NEOPHYTE'S GUIDE TO HACKING (1993) - Deicide

I have read all these when i was first interested and they didn't help me
much in really learning the subject. Especially now much in these
tutorials is outdated and irrelevant. But i think it's not bad to read
them afterall, this is oldskool hacking which is always fun-reading. Also
take a look in the phrack archives (www.phrack.org) in the old issues, for
a look in the past.

At first I wanted to release the 'HACKING UNIX' tutorial as a whole. But I
couldn't wait to release it. I decided to break it up in parts and release
it in parts. I will do my best to complete everything a.s.a.p. This part
on 'Vulnerabilities and security' was finished awhile ago though.  And I'm
almost finished with the next part.

1. Audience

You're probably using windows and you're interested in hacking. You
searched for hacking sites on the internet and there you found tools
(wares) which you can use to hack other people. You have tried netbus and
back orifice or other tools, you've collected them and put them on a new
'hacking page'. You found out that you need a strong l33t handle that
reflects your skillz; like "inv1sibl3 predat0r". You have hacked into your
friends' computers and your friends are truly impressed and people phear
you.

Allright it's over now. Did you ever try any of your stupid warez against
your internet service provider's webserver uh? Didn't work exactly did it?
Well, I think that's why you're here right? Well, you're still a zombie
and I hope that I'll break the lameness out of you with this tutorial so
you can work on becoming a true and well respected hacker for the
community. You'll find out that hacking is not about the results it will
give you, it's the act itself that drives the hacker. Eventually only a
few of you will survive.

2. Conventions

I wanted to make this paper accessible for both beginners and more
advanced readers. Therefor, explanations (like technical jargon) are
explained in side-comments.

E.g.:

...the inetd superdaemon....
{
       The Inetd superdaemon is a service that handles network
       connections for network services that use it.
}

This way, the more advanced reader isn't bothered with information that he
already knows, and the beginner is still able to understand what I am
talking about.

3. Orientation

In a nutshell these are the steps the hacker takes:

An attacker first searches a system that he interested in.
Then he explores the system and it's weaknesses, break into the system and
get full control over the system, remove the traces of the hack and use
methods like backdoors to keep access to the system.
{
       Exploring the system means evaluating it's security and see if you
       are capable of breaking in. In this stage you have to make sure
       you are not showing the victim that you are trying to break in!
}
{
       Breaking into the system means finding vulnerabilities in
       the configuration of a system, or see if there is a known
       vulnerability in the software and exploiting them.
}

In the first few parts I will cover all the steps the attacker takes. You
should then understand how attackers attack, and -with some practice- be
able to do it yourself.
In the later parts (the advanced section) I will go deep into hacking
issues, I will talk about low-level network attacks, trust relations,
encryption, authentication and everything.

In this first part I skip the information gathering (profiling) of your
victim, and start off by introducing you with vulnerabilities; the
problems in systems that make attacks possible.

4. Vulnerabilities

Programs have bugs and bugs can often be taken advantage of.
{
       Bugs that can be taken advantage of to bypass security
       restrictions are called vulnerabilities.
}

This chapter introduces you to the community that searches and fixes
vulnerabilities.

If some individual finds a vulnerability in a server application like the
apache webserver (HTTP server) the individual often notifies the vendor
(the apache project in this example) of the problem. The vendor then looks
into the problem and fixes the vulnerability.
The fix is then provided to the users of the apache webserver in the form
of a work-around, a patch or a new release.

People are made aware of the vulnerability in the product they use, and
fix their servers, or they don't.

Because of this, vulnerabilities are often present in certain versions. So
if the attacker finds out which version of a product the victim uses, he
might find out that his victim uses a vulnerable version of the product.

This being said, the chance of being able to attack the target through a
known vulnerability depends on the degree of detail that the founder of
the problem has disclosed in his publication of the problem.
{
       Papers/Articles that discuss a security vulnerability are called
       'advisories'.
}

4.1 Full-disclosure

__When someone releases the details of a security problem in the degree
that another individual is capable of reproducing the
"state of exploitation"*, we call it a "full-disclosure advisory"__
{
       The "state of exploitation" means 'the compromise of whole or
       part of the target's environment* after bypassing the
       security-policy that the target should have enforced.

       Bypassing the intended security restrictions are -ofcourse-
       discussed in the (full-disclosure) advisory.

       *What exactly I mean with 'environment' in this context will be
       explained in chapter 4.3.
}

4.1.1 Advantages and Disadvantages

The full-disclosure method has advantages and disadvantages for security.

Disadvantages of Full-Disclosure:

The disadvantage for security when writing and publishing a full disclosed
advisory is that many people are capable of attacking vulnerable servers.
And as many administrators do not care about vulnerabilities in software
they use, they have a high chance of being hacked by evil people like you
;-}.

Advantages of Full-Disclosure:

The advantage of full-disclosure is that security-concious programmers
will learn what programming methods are insecure. It also presses the
vendors of programs to quickly fix their crap and make sure it doesn't
happen again.

Full-dislosure has another advantage; admins will feel themselves
pressured to keep their software up-to-date as many people in the public
are capable of exploiting the software.

4.2 Exploit code

Full-disclosure reports often include 'exploit-code' which makes it even
easier to reproduce exploitation state, sometimes the 'sploit-code' is
this user-friendly* that a kid could break into a system with it.
{
       *Though, most of the time the (ab)user has to modify the exploit
       program alittle to make it work against his target.
}

Exploit code is simply a program that will automatically reproduce
exploitation state when you point it to a vulnerable server that
runs the vulnerable software.

The exploit-code is supposed to only be used by admins to test if their
systems are vulnerable. Therefor, some of the exploit code only proves
that the vulnerability exists without being usable for attackers. Although
a good attacker knows how to modify the exploit program to fit his needs.

When someone releases an advisory but doesn't include an exploit, it often
doesn't take long before someone writes one and submits it to bug tracking
mailing lists and exploit archive sites.

4.3 'Access Levels' and 'Environments' and 'Security'

When an attacker exploits a network service, this often doesn't mean that
the system is fully compromised yet. Most network service programs do not
require full system access for their tasks and are preferred to have
low-privileges.
{
       Privileges involve access control rights on files, network
       resources, memory access, system calls etc.

       This will be called the program's (or users') 'environment'
       throughout the rest of this guide.
}

Though sometimes a network service requires superuser privileges for
certain tasks. A good process only runs particular tasks with super-user
privilege and not the whole process.

When an attacker compromises whole or part of a target process' the
attacker atleast has a more flexible environment where it becomes easier
to gain superuser privileges.
{
       The scenario where the attacker has compromised an environment
       where he can read files and execute programs is called 'local
       access'. Many admins don't really care about vulnerabilities in
       programs that are not accessible through network services and
       often don't bother to fix these problems because it doesn't seem
       like a direct threat.
}

No system is totally secure, all an admin can do to minimize the danger of
a vulnerable or misconfigured server program, is to minimize the
resources the programs have access to. This minimizes the environment of
an attacker that gained access to that program's environment and makes it
harder for the attacker to gain full access.
{
       A good security setup is created by first disabling everything,
       and then discover what *has* to be enabled.

       After that the admin simply fixes known security problems when
       they come out.
}

So security is all about evaluating what privileges a program or user
needs (and doesn't need).

The 'environment' I'm talking about is enforced by the kernel. The kernel
allows or denies access to files, to network sockets, to I/O devices and
all.

The operating system controls only the program's environment and users's
environment. The programs that provide services to users are responsible
for restricting user access to their own environment
{
       A webserver has a directory like '/var/www/htdocs' where the
       DocumentRoot of the HTTP service resides. The webserver program
       itself is allowed to access the /etc, /usr, /home and /proc
       directory's by the operating system. So the environment that the
       operating system provides to the webserver program is much wider
       than the environment that the webserver provides to site visitors;
       It only gives read access to /var/www/htdocs/, and all
       attempts to access directory's beneith htdocs/ are denied by the
       webserver. Any succesful attempt to break out of the virtual
       environment that is provided by the webserver is a vulnerability.

       Such a vulnerability will give a degree or full access to the webservers
       environment within the system. A full access to the webserver's
       environment means that we can execute programs, browse directory's and
       read all files that the webserver program has access to within
       the system.
}

5. Where do vulnerabilities occur?

Basically vulnerabilities occur in (to list some):

- input handling
- configuration errors
- communication
- trust relationships
- authentication handling
- cryptography bugs
- wrong security policy

So it happens everywhere... it happens at the vendor of a specific
program. It happens at the operating system vendor which puts programs
into a distribution. It happens when admins install things wrong or set
things wrong. It happens when communication protocols are unreliable. It
happens between communication of programs. It happens when users are
stupid. It happens when two programs on a system form security problems.

5. Who finds vulnerabilities

Real hackers find the vulnerabilities.
{
       Hackers search for ways to make a *system do things that shouldn't
       be possible.

       *A system can be anything: a program, a user (person), a
       protocol.
}

A hacker will examine a program on how it works.
{
       This is done for example through tests, reverse engineering or
       simply reading the *source code.

       Source code (for the total beginner) are the programmers'
       instructions in a certain programming language that make up the
       program before it is converted into machine language.
}

He will learn about the procedures a program takes and he will investigate
whether the methods used are secure. The procedures might rely on other
software, kernel calls and network communication.

To make you understand, here's a security advisory to make you see what I
mean;

------------------------------------------------------------------------------
Date: Thu,�20�Sep�2001�21:48:34�+0200
From: "Przemyslaw�Frasunek"�<[email protected]>
Subject: Local�vulnerability�in�libutil�derived�with�FreeBSD�4.4-RC
        (and�earlier)
Organization: babcia�padlina�ltd.
To: <[email protected]>

Hello, OpenSSH derived with FreeBSD 4.4 (and earlier) doesn't drop
privileges before messing with login class capability database. The most
problematic is:
       if (newcommand == NULL && !quiet_login && !options.use_login)
{
               fname = login_getcapstr(lc, "copyright", NULL, NULL);
               if (fname != NULL && (f = fopen(fname, "r")) != NULL) {
                       while (fgets(buf, sizeof(buf), f) != NULL)
                               fputs(buf, stdout);
                               fclose(f);

and
               f = fopen(login_getcapstr(lc, "welcome", "/etc/motd",
                   "/etc/motd"), "r");
[...]
                       while (fgets(buf, sizeof(buf), f))
                               fputs(buf, stdout);
                       fclose(f);

in session.c, which allows to read ANY file in system with superuser
privileges, by defining:

default:\
:copyright=/etc/master.passwd:

or

:welcome=/etc/master.passwd: in user's ~/.login_conf. login(1), which is
suid and spawned by telnetd also is vulnerable to similar attack:

       if (!rootlogin)
               auth_checknologin(lc);
[...]
       (void)setegid(pwd->pw_gid);
       (void)seteuid(rootlogin ? 0 : pwd->pw_uid);

Checking for nologin is performed with superuser privileges.
auth_checklogin() is libutil function which displays nologin file, as
defined in login capability database. User can read ANY file in system by
defining:

default:\
:nologin=/etc/master.passwd:

FreeBSD core team has been aleady informed and official patches were
incorporated into CVS repository *before* 4.4-RELEASE, although 4.4-RC and
earlier verions are vulnerable and needs to be patched with:

http://www.freebsd.org/cgi/cvsweb.cgi/~checkout~/src/lib/libutil/login_cap.c?rev=1.17.2.3&content-type=text/plain

Official advisory is pending. It's possible, that other *BSD systems,
supporting login capability database are also vulnerable.

--
* Fido: 2:480/124 ** WWW: http://www.frasunek.com/ ** NIC-HDL: PMF9-RIPE
*
* Inet: [email protected] ** PGP: D48684904685DF43EA93AFA13BE170BF
*
------------------------------------------------------------------------------

This is a nice full-disclosure advisory example: It explains the
programming error, the way it can be exploited and it links to the
vendor's patch.

I don't expect you to understand this advisory, but you should have
figured out how it can be exploited (on unpatched systems).

What it says is that a user can create a file called '.login_conf' (which
is probably already there) in their home directory, and when putting a
line like:

----
default:\
:copyright=/etc/master.passwd:
----

or

----
default:\
:welcome=/etc/master.passwd:
----

in the .login_conf file, the login process will then read that file once
you re-login. And because it still has root privileges (it doesn't return
to it's normal user-id) you can place any file name in the .login_conf,
and it will be displayed when you log in! This means you can read the
master.passwd file where the password-hashes for all users are stored.
Ofcourse that file should not readable for a normal user. But if you are
able to read it, like in this case, you can perform a brute-force attack
using password-crackers like CRACK-5.0, and then it will only be a matter
of time before you the root password is recovered.
{
       Though when the root users' password consists of more than 8
       characters and he uses a combination of numeric and alphanumeric
       and other characters as a password, it might take the fastest
       computer on earth over a year to crack it.
}

Now back to the subject...
Note that the hacker had first informed the vendor FreeBSD which created a
patch. After the patch was released, the hacker posted the vulnerability
information as full-disclosure advisory to the BugTraq mailing list and
included a link to the patch (the fix) for the bug which FreeBSD released.

There are also people that don't report bugs to vendors and the public and
use their information for their own sake.

There are alot people in the underground (black-hat hackers)  that keep
the information to themselves. Exploits which are not publicated are
called zero-day's (0-day).

There is nothing you can do about that, you can only minimize the risk by
disabling services that you don't need. And you can restrict service
programs that you do need as explained in chapter 4.3.

7. Last words

I hope that you understand the basic picture of security and
vulnerabilities.


                         - HACKING UNIX -
                           CHAPTER TWO:

                         System Profiling
                         ----------------

******

INDEX:

0. - Forword
1. - Introduction
2. - Protocols
    2.1 Network Protocols
    2.2 Application Protocols
3. - Portscanning well-known network services
4. - Widely used Application Protocols - Detailed
    4.1 FTP
    4.2 SSH
    4.3 TELNET
    4.4 SMTP
    4.5 DNS
    4.6 HTTP
    4.7 POP3
5. - OSI (network protocols - a deeper look)
    5.1 The Application layer
    5.2 The Presentation layer
    5.3 The Session layer
    5.4 The Transfer layer
    5.5 The Network layer
    5.6 The Data-Link layer
    5.7 The Physical layer
6. - Back to system profiling
    6.1 The importance of system profiling
    6.2 "Planning"
        6.2.1 Available Information
        6.2.2 Active Server-oriented Information probing
              6.2.2.1 PING
              6.2.2.2 DNS & Zone Transfers
              6.2.2.3 WHOIS
              6.2.2.4 Scanning Services
7. - Last words

****************************************************************

0. Forword

This is the second part of the 'Hacking Unix' tutorial project found at:
http://duho.cjb.net/ -> projects -> Hacking Unix.
This part is released two days after the first release (just had to add a
few chapters). Don't be afraid of the size of this text, the text is
designed so that you can skip parts that you already know.

1. Introduction

Okay, i introduced you to vulnerabilities in the first part to keep the
spirit of hacking with us. But not less important to understand is how we
search for vulnerabilities. It may not be hard to find them, but it's
important to not raise any alerts in this stage. We want to leave less
than fingerprints rather than footprints in the logs. This step
involves network services, network protocols and application protocols.

You know that we want to attack applications in a remote system. So we
should find out which applications run on the remote server that can be
interacted with. Any software that is accessed remotely on the server can
suffer a security hole. In this step we have no access to the server or
whatsoever, so we need to take a good look at outside of the nut before
cracking it.

When we can only look from the outside of the server we only have it's
network services* that possibly contain a hole somewhere.
{
       * Client-Server model - The server is a host computer that employs
         particular service software to serve a client.
         The service passively waits for a client to call for it's
         service. There are standards towards how a client and a service
         should talk to each other (the protocol).
}

One thing we can do is use all kinds of clients for different network
services like FTP, WWW (HTTP), email and stuff like that to see what
services are running out there. But we could do better than that, but this
requires us to know a little about network protocols and application
protocols.

2. Protocols

2.1 Network Protocols

The internet is a network of computers which all have an identifying
number, the IP number (Internet Protocol Number). Every computer or other
device connected to the internet has an Internet Protocol number.

IP is built into the operating systems of these devices. Simply stated,
all IP networked systems capture the IP data packets that are destined to
theirselves, and try to forward those destined to other addresses
(numbers).

{
       All that IP is ought to do is reliably routing (for IP) unknown data to
       any address on the network. This is a shared responsibility of all IPs
       that reside on the network.
}

But in order to actually communicate information we use higher level
protocols (on top of IP - Or: encapsulated in IP packets):

Between the IP protocol and the application we have the transfer protocol.
On the internet there are two major transfer protocols; UDP and TCP. When
IP receives a datagram destined to it's own address, it forwards the
packet to one of the transfer protocol modules in it's operating system.
IP knows which module should handle it because the sender writes the
destination (transfer) protocol number on the packet. Like '6'
for TCP. The transfer protocol module has a series of addresses available
(ten thousands of them) where communication applications can listen on
(passive mode) or sent to (active mode). So the sender must also add
information to the protocol header which port (address) the application
should be listening on.

For example:

TCP states that we have to use two different applications; a service and a
client. The client connects to the server's TCP port and the service will
acknowledge the request and a connection is open.
{
       When a TCP port is open there is almost always an application listening on
       that port to start a session with any client that connects.
}

TCP provides ports 1 through 65535 for connections. So how does a client
know which TCP port to connect to? That's easy, for all known services
like HTTP we have well-known ports. To make a service application publicly
available you use the well-known port. HTTP has TCP port 80 to listen to.
{
       NOTE: These well-known ports are not a standard defined in the TCP
       specification! As far as TCP is concerned, it would be happy to
       address ANY kind of service on ANY port, even well-known ports.
       Only, the application protocol specification recommends the use
       of a certain port.
       If you want to hide your webserver or FTP server, you could set it
       on a different port (if your software is configurable for it).
       This hiding ofcourse is 'security through obscurity' and it won't
       hide from curious people.
}
And when you type in an IP address in your browser which has a HTTP server
running, you will receive the webpage through the connection.

2.2. Application Protocols:

I'm going to introduce you to several well-known application protocols
just a few pages ahead of you. First you should know what basically an
application protocol is for.

An application protocol is a language for requesting resources of any kind
in a certain format. Resources may be; file transfer; information; news;
sound transfer and mail.

3. Portscanning well-known network services

In order to find out which network services are available on a remote
computer, we could simply try out some different clients and see the
results. But I think you can figure another way if you have read the
former chapter.

We can 'scan' for TCP ports (and UDP ports) simply by trying to connect to
every possible port and see which ones are open.

So see which port numbers are open and compare them to a list of
well-known services.
I have a list of the most well-known services and their ports here:

21      -       FTP (File Transfer Protocol)
22      -       SSH (Secure SHell)
23      -       TELNET
25      -       SMTP (sendmail server)
53      -       DNS (Domain Name Service - Nameserver)
79      -       FINGERd (finger daemon)
80      -       HTTPd (Hyper Text Transfer Protocol Daemon)
110     -       POP3 (Post Office Protocol version 3)
111     -       SUNRPC Portmapper (SUN's Remote Procedure Call service port mapper)

You can program your own scanner but i bet it won't be as l33t as Fyodor's
nmap so give it up. Download Nmap from http://www.insecure.org/nmap/.
Nmap has many features to stay undetected. For the following example i
will use the old stealth scan option in nmap to scan myself kay?:

bash# nmap -sS localhost

Starting nmap V. 2.54BETA29 ( www.insecure.org/nmap/ )
Interesting ports on localhost (127.0.0.1):
(The 1541 ports scanned but not shown below are in state: closed)
Port       State       Service
22/tcp     open        ssh
25/tcp     open        smtp
80/tcp     open        http
587/tcp    open        submission
1024/tcp   open        kdm
1988/tcp   open        tr-rsrb-p2
6000/tcp   open        X11


Nmap run completed -- 1 IP address (1 host up) scanned in 2 seconds
bash5#

Ewh damn, looks pretty insecure, should have installed firewall but who
carez.

We go on to the next chapter now, don't worry; you'll see alot of the use
of portscanning techniques later.


4. Widely used Application Protocols - Detailed

Most application protocols (which i will just call protocols for the rest
of this chapter) are easy to interact with by normal humans without using
a special User-side protocol interpreter. Perhaps this is because most
protocols that are developed in the early 70s use simple commands like
'GET <file>' and 'user <name>' and 'mail from: <mailaddress>'.
{
       This was back in the time that opensource was all there was. In the
       present the company's try to hide the workings of their protocols to
       create a monopoly.
       That these protocols look so easy doesn't mean they are not good,
       why do you think they survived for somany years?
}
It shouldn't be hard to build your own clients when you are a programmer.

The knowledge of each protocol is very important for a hacker.
In this chapter i will give you some practical examples which you can try
out. You will need a TELNET application (most systems just have a program
'telnet' in console mode which will do; even windows has!). And you need
the netcat program for some of them.
{
       Netcat is a very 'basic' yet advanced application, it is the swiss
       army-knife of the hacker. With netcat you can initiate UDP and TCP
       connections in full-duplex (like telnet), netcat can handle binary data
       and you can open a port in passive listening mode on the port you specify
       (which is very convenient you'll see). Download netcat here:
       http://packetstormsecurity.org/UNIX/netcat/nc110.tgz

       ************ Download+Install netcat: ********************

       --
       bash# mkdir netcat
       bash# cd netcat
       bash# lynx -source http://packetstormsecurity.org/UNIX/netcat/nc110.tgz > nc110.tgz
       bash# tar xvzf ./nc110.tgz
       bash# make linux
       --

       If you get this compiler error:
       ------
       make -e nc  XFLAGS='-DLINUX' STATIC=-static
       make[1]: Entering directory `/root/netcat'
       cc -O -s          -DLINUX -static -o nc netcat.c
       /tmp/ccZHNpqq.o: In function `main':
       /tmp/ccZHNpqq.o(.text+0x15b7): undefined reference to `res_init'
       collect2: ld returned 1 exit status
       make[1]: *** [nc] Error 1
       make[1]: Leaving directory `/root/netcat'
       make: *** [linux] Error 2
       ------

       If you got that compiler error you must remove the following ifdef from
       the netcat.c file:

       ------
       #ifdef HAVE_BIND
       /* can *you* say "cc -yaddayadda netcat.c -lresolv -l44bsd" on SunLOSs? */
         res_init();
       #endif
       ------

       And reinitiate 'make linux'.

       The compiler didn't show any errors anymore, you can run netcat with:

       # ./nc

********************************
}

I'm glad you made it this far. We're gonna use netcat to learn how
services really work. After this chapter you should be able to do alot of
things without requiring a special client. You would be able to email
without using a mailer, you can read files on webservers without a
webbrowser, you will download files without an ftp client program.
{
       In the past there were many people simply using TELNET to send mail, but
       people have become lazy and they demand a flashy graphical user interface
       to get turned on.
       Hehe funny to note; I have heard about someone that was fired at his job
       because people thought he was hacking; he was checking his POP3 mail with
       telnet.exe because his outlook crap seemed dead :-}. So I want to remember
       you; I'm not responsible! hahaha
}

I encourage you to lookup the Request for Comments (RFCs) at
www.rfc.org.uk to learn more about a specific application protocol (or
transfer and communication protocols). Hacking is about understanding a
system so you can defeat it remember? So if you know how a standard
*should* be implemented, you can test if vendors of services implement the
standard securely.

I will introduce you to the following services in a practical manner: FTP,
SSH, TELNET, SMTP, HTTP, POP3

4.1 FTP - File Transfer Protocol

FTP is a pretty simple protocol to use. FTP uses a control connection and
a data connection. The control connection is initiated by the client PI
(Protocol Interpreter) and it is used to send commands. The control
connection uses TELNET control characters like <CRLF> (Carriage Return and
Line Feed). So if we can't use an FTP client we can use the telnet client
for the control connection. And concerning the data connection... that's
where netcat comes in. Let's just start a session. First you got to know
that everything starting with a 3-digit number is the reply of the FTP
server, the rest are my commands. I use console tty1 for the control
session and i use netcat in console tty2 for the data connection:

Console TTY1                  | Console TTY2
-------------------------------|--------------------------------------------
bash# telnet ftp.kernel.org 21 | bash#
Trying 204.152.189.113...      |
Connected to zeus.kernel.org.  |
Escape character is '^]'.      |
220 ProFTPD 1.2.2 Server       |
USER anonymous                 |
331 Anonymous login ok,        |
   send your complete email   |
   address as your password.  |
PASS [email protected]             |
230-   Welcome to the          |
                              |
   LINUX KERNEL ARCHIVES      |
     ftp.kernel.org           |
                              |
"Much more than just kernels" |
                              |
230 restrictions apply.        |
                              |
PORT 213,93,39,87,4,1          | bash# nc -v -v -l -p 1025
200 PORT command successful.   | listening on [any] 1025 ...
NLST                           | connect to [213.93.39.87] from zeus.kernel.org [204.152.189.113] 20
150 Opening ASCII mode data    | lost+found
   connection for file list.  | pub
226 Transfer complete.         | welcome.msg
                              | for_mirrors_only
                              | debian
                              | debian-cd
                              |  sent 0, rcvd 67
                              | bash#
-------------------------------|--------------------------------------------

The console on TTY1 is used for the control connection, and the TTY2
console represents the data connection.

With the PORT command you specify which local data port we use to receive
the data (a file, a directory listing etc.). So the command looks like
this;

PORT h1,h2,h3,h4,p1,p2

the h* represents the IP address of yourself, and the p* is for the port
address (TCP). When i don't have my local port open i will get an error:

PORT 213,93,39,87,4,2
200 PORT command successful.
LIST
425 Can't build data connection: Connection refused

So in this case port 1026 was not listening on my PC... if i had a netcat
in listening passive mode like in the example or like this: ./nc -l -p
1026 i would have received the listing. By the way; the NLST is almost
same as LIST only it shows less information on the filelist.

In the past it was possible to create a data connection on a different
system, with a different address, like this (i am using 213.93.39.87 as IP
and i'm gonna try to retrieve a file on the IP address 213.93.39.1):

PORT 213,93,39,1,4,1
500 Illegal PORT command.

This is illegal because i don't use my own IP address. I think it's a
pitty that you can't receive the file on another system. It was possible
in the past but it happens to open a security vulnerability. Where it
is enabled you could abuse it to scan ports of a server with it in this
way:

-------
PORT 213,93,39,1,4,2
200 PORT command successful.
LIST
150 Opening ASCII mode data connection for file list.
226 Transfer complete.
PORT 213,93,39,1,4,1
200 PORT command successful.
LIST
425 Can't build data connection: Connection refused
-------

You see, on host 213.93.39.1 the port 1026 is open and port 1025 is
closed. You'll have a hard time finding hosts nowadays that suffer this
FTP bounce attack. It can also be used to execute certain exploits this
way. You should have noted that this technique is of interest to attack a
third system without revealing your address on the internet but that of
the FTP server.

Now i bet you wondered what a weird port address i was entering (4,1).
Well... it's easy, p1 and p2 are both 8bit so i need to define the port
address i want to use and then / 256... so if i want to use port 1024 i do
1024 / 256 = 4,0
What is 4 times 256 ?? 1024!

Here are some other commands for the control connection:

CWD <directory> (change working directory to... -> (allows only one dir at
                                                   a time))
RETR <file> (RETRieve file through data connection (setup netcat!))
PASV (tells which port the server is listening to for uploads over data
     connection)
STOR <file> (dump the file using netcat to the remote port found with PASV)
PWD (prints current working directory)
RNFR (first command specifying the current name of path to change)
RNTO (Rename To ... second command to complete rename of file)
ABOR (stop data transfer in data connection)
DELE <file> (delete file)
RMD <directory> (remove empty directory)
MKD <directory> (create directory)
SITE (vary's coz these are site specific commands, lookup with HELP SITE)

Using this information you should be able to browse FTP servers simply
with telnet and netcat! :)))

4.2 SSH - Secure SHell

I don't know much about the internals of SSH. I use it myself by replacing
it for TELNET and FTP. For what i know of SSH is that it exists of three
layers; the transport layer, the user-authentication layer and the
connection-layer. I believe the Transport-layer of SSH is the lowest of
the layers which delivers a secure transport layer before the
authentication proceeds. Then the user logs in and the password (and the
rest of the communication) cannot be captured in a readable form by spies
on untrusted networks. The connection protocol serves the session. A login
is almost similar to telnet:

bash# ssh -l user localhost
XT@localhost's password:
Last login: Mon Sep 24 18:52:36 2001
Linux 2.4.9.

A student who changes the course of history is probably taking an exam.

user@stealth:~$

As i said, i only use SSH, i never used it to hack into a system... but i
know of difficult attacks involving hijacking of sessions and stuff like
that. You should search for it yourself.

4.3 TELNET

The telnet protocol itself is a simple standardization of control
characters for terminal usage so that users at different systems can login
to a system while using the TELNET standard. People can use different
keyboards and different keyboard control characters, different operating
systems, telnet converts the characters into a defined standard character
set.

There is a IAC (Interpret As Command) byte followed by the control code.
The IAC has the value 255 (FFh) followed by the TELNET command code.
TELNET commands include erasing a character or a line, break input and
interrupt process.

When you connect to the TELNET login service you are asked for username
and password. What happens behind the scene:

The Inet super daemon listens on port 23, when someone connects the
in.telnetd process is run which in turn runs the login process
{
       The INET SuperDaemon is a service that is able to run a specific
       Unix network service when a connection for that particular service
       is requested.
       It is configured like this (config file);

       ftp     stream  tcp     nowait  root    /usr/sbin/tcpd  proftpd
       telnet stream  tcp     nowait  root    /usr/sbin/tcpd  in.telnetd

       You see... if there is someone knocking on port 23, the inetd
       service runs in.telnetd.

       In Unix systems you can seperate services in processes of INETD or
       standalone. Apache webserver almost always runs standalone (I
       don't even know if it is ever put under INETD parent)
}

When the login process has successfully authenticated a user it will check
which shell to spawn in /etc/passwd:

user:x:1004:100:,,,:/home/duho:/bin/bash
{
       Only notice '/bin/bash'.. the rest is explained later in this book
}

As you see the user 'user' gets the bash shell (bourne-again shell). This
is very simple. On recent systems the superuser 'root' is not allowed to
telnet into the box.. so don't be lame to try 'root' with password 'root'
logins as i've seen alot in the past (people trying that on my box).
Ohyeah, i've got to admit that i've tried this stuff when i was a newbie
:). But I don't believe there's even one unix box on the internet nowadays
where the password of root is root and while the telnet service enables
root logins. All login tries are logged on unix systems so don't be stupid
to try passwords.

I'll do one example telnet login:

bash# telnet
telnet> o localhost
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

stealth login: user
Password:
Linux 2.4.9.
Last login: Tue Sep 25 15:45:26 +0200 2001 on pts/10 from localhost.
No mail.

People say I live in my own little fantasy world... well, at least they
*know* me there!
               -- D.L. Roth

XT@stealth:~$ logout
Connection closed by foreign host.
bash#

4.4 SMTP - Simple Mail Transfer Protocol

SMTP is only for sending mail, retrieving mail is often done from POP3 or
IMAP services.

SMTP is easier to use than FTP. So this goes quick.

telnet <sendmail-server> 25

Example:

--------------
bash# telnet localhost 25
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 stealth.duho ESMTP Sendmail 8.11.6/8.11.4; Tue, 25 Sep 2001 17:15:21
+0200
HELO x
250 stealth.duho Hello localhost [127.0.0.1], pleased to meet you
MAIL FROM:[email protected]
250 2.1.0 [email protected]... Sender ok
RCPT TO:[email protected]
250 2.1.5 [email protected]... Recipient ok
DATA
354 Enter mail, end with "." on a line by itself
Subject: Haia
How's life?

Me.