23
Database Input Issues Writing Secure Code

Database security

Embed Size (px)

DESCRIPTION

Database Input Issues

Citation preview

Page 1: Database security

Database Input IssuesWriting Secure Code

Page 2: Database security

Agenda• Introduction• Sql Injection• Issue• Remedies

• Inference Problem• Issue• Remedies

• Sql Stored procedures• Defense in Depth Example• Conclusion

Page 3: Database security

Introduction• Many applications, like web based applications and xml based web services

store persistent data in databases.• Trusting that the user has given well-formed input data to your application,

when infact the user has not• Misplaced trust• Database input vulnerabilities (aka sql injection)

Page 4: Database security

Web Application Vulnerabilities

CriticalDatabase

void ProcessRequest() { string s = GetUserInput("name"); … s = Validate(s); … … ExecuteQuery(“select …" + s + “…”);}

Source

Sink

Sanitizer

Page 5: Database security

Sql Injection

• Many applications include code that looks something like the following.

String sql = “select * from client where name = ‘”+name+”’”The variable name is provided by the userWhat if an attacker enters this: Blake’ or 1=1 –• select * from client where name = ’Blake’ or 1=1 –• The comment operator “--” is supported by many

relational database servers, including Microsoft SQL Server, IBM DB2, Oracle, PostgreSQL, and MySql.

Page 6: Database security

Imagine that the database table schema looks like this

CreditCard *CreditCardID

Type

Number

Expires

Customer *CustomerID

LastName

FirstName

MiddleInitial

Address

Apartment

City

State

PostalCode

Country

CustomerCreditCard *CustomerID

CreditCardID

When the attacker is happy that the SQL statement or statements are complete he places a comment operator at the end to comment out any characters added by the programmer.

Page 7: Database security

SQL Injection• Some database servers allow a client application to perform

more than one SQL statement at once. • select * from table1 select * from table2• SQL engines include support for data manipulation constructs,

such as the ability to create, delete (called drop),an attacker could enter:• Blake’ drop table client --

Page 8: Database security

Can you spot security flaws?Connecting as a super admin.

Sa is to SQL Server what SYSTEM is to Windows NT and later.

What if the connection fails to the database due to some network issue.

A complete description of how the failure occurred is given to the attacker.

string Status = “No";string sqlstring = “";try {SqlConnection sql= new SqlConnection( @"data source=localhost;” + “user id=sa;password=password;”); sql.Open();sqlstring="SELECT HasShipped” + “ FROM detail WHERE ID=‘“ + Id + “‘";SqlCommand cmd = new SqlCommand(sqlstring,sql);

if ((int)cmd.ExecuteScalar() != 0) Status = “Yes";} catch (SqlException se) { Status = sqlstring + “ failed\n\r"; foreach (SqlError e in se.Errors) { Status += e.Message + “\n\r";}} catch (Exception e) { Status = e.ToString();}

Page 9: Database security

Pseudoremedy:Quoting the Input

int age = ...; // age from user string name = ...; // name from username = name.Replace(“‘","‘‘“); SqlConnection sql= new SqlConnection(...);sql.Open();sqlstring=@"SELECT *” + “ FROM client WHERE name= ’” + name + “‘ or age=“ + age;SqlCommand cmd = new SqlCommand(sqlstring,sql);

Replacing single quotes with two single quotes. Statement becomes invalid SQL Statement.

• select * FROM client WHERE ID = ’Michael’’ or 1=1 -- ’ or age=35 However, this does not deter our wily attacker; instead, he uses the agefield, which is not quoted, to attack the server. For example, age could be 35;shutdown --.declare @a char(20) select @a=0x73687574646f776e exec(@a)

This construct, when added to another SQL query, calls the shutdown command. The hexadecimal sequence is the ASCII hex equivalent of the word shutdown.

Page 10: Database security

Pseduremedy #2: Use Stored Procedures

• A stored procedure is a procedure (like a subprogram in a regular computing language) that is stored in the database

• Stored procedure: sp_GetName:string name = ...; // name from userSqlConnection sql= new SqlConnection(...);sql.Open();sqlstring=@"exec sp_GetName ’” + name + “‘";SqlCommand cmd = new SqlCommand(sqlstring,sql);

• exec sp_GetName ’Blake’ or 1=1 -- ’ will fail

However performing data manipulation is perfectly valid.• exec sp_GetName ’Blake’ insert into client values(1005, ’Mike’) -- ’

Another Scariest exampleCREATE PROCEDURE sp_MySProc @input varchar(128)ASexec(@input)

Page 11: Database security

Remedy 1: Never Ever Connect as sysadmin• Delete (drop) any database or table in the system• Delete any data in any table in the system• Change any data in any table in the system• Change any stored procedure, trigger, or rule• Delete logs• Add new database users to the system• Call any administrative stored procedure or extended stored procedure.

• Support authenticated connections by using native operating system authentication and authorization by setting Trusted_connection = true

• create a specific database account that has just the correct privileges to read, write, and update the appropriate data in the database,and you should use that to connect to the database.

• SQL Server includes extended stored procedures such as xp_cmdshell through which an attacker can invoke shell commands.

• Oracle databases include utl_file, which allows an attacker to read from and write to the file system

Page 12: Database security

Remedy #2: Building SQL Statements Securely

• Use parameterized commands.• SELECT count(*) FROM client

WHERE name=? AND pwd=?

Function IsValidUserAndPwd(strName, strPwd)’ Note I am using a trusted connection to SQL Server.’ Never use uid=sa;pwd=strConn = “Provider=sqloledb;” + _“Server=server-sql;” + _“database=client;” + _“trusted_connection=yes"Set cn = CreateObject(“ADODB.Connection”)cn.Open strConn Set cmd = CreateObject(“ADODB.Command”)cmd.ActiveConnection = cncmd.CommandText = _“select count(*) from client where name=? and pwd=?"cmd.CommandType = 1 ’ 1 means adCmdTextcmd.Prepared = true ’ Explanation of numeric parameters:’ data type is 200, varchar string;’ direction is 1, input parameter only;’ size of data is 32 chars max.Set parm1 = cmd.CreateParameter(“name", 200, 1, 32, ““)cmd.Parameters.Append parm1parm1.Value = strName Set parm2 = cmd.CreateParameter(“pwd", 200, 1, 32, ““)cmd.Parameters.Append parm2parm2.Value = strPwd Set rs = cmd.ExecuteIsValidUserAndPwd = falseIf rs(0).value = 1 Then IsValidUserAndPwd = true rs.Closecn.CloseEnd Function

Page 13: Database security

Building SQL Stored Procedures Securely

• Use quotename functionselect top 3 name from mytable would become select top 3 [name] from [mytable]

if you quote name and mytable .

declare @a varchar(20)set @a=0x74735D27select @aset @a=quotename(@a)select @a set @a=‘ts]’’’select @aset @a=quotename(@a)select @a

Use sp_executesql to execute sql statements build dynamically.-- Test the code with these variablesdeclare @name varchar(64)set @name = N’White’ -- Do the work exec sp_executesqlN’select au_id from pubs.dbo.authors where au_lname=@lname’,N’@lname varchar(64)’,@lname = @name

Page 14: Database security

Inference Problem 1‐

• The inference problem is a way to infer or derive sensitive data from non sensitive data.‐• Sum: An attack by sum tries to infer a value from

reported sum. Often helps us determine a negative result.• This report reveals that no female living in Grey is receiving

financial aid

Page 15: Database security

Inference problem 2

• Count: count + sum average; average + count sum• This report reveals that two males in Holmes and West are

receiving financial aid in the amount of $5000 and $4000, respectively.

• Holmes Adams• West Grof

Page 16: Database security

Inference Problem 3

Page 17: Database security

Remedies: Statistical Inference Controls Attacks• Controls are applied to queries• Difficult to determine if query discloses sensitive data

• Controls are applied to individual items within the database (security vs. precision)• Suppression: sensitive data values are not provided; query is

rejected without response• Many results suppressed; precision high

• Concealing: answer provided is close to by not exactly the actual value• More results provided; precision low

Page 18: Database security

Remedies: Limited Response Suppression• The n item k percent rule eliminates certain low frequency ‐ ‐ ‐

elements from being displayed• When one cell is suppressed in a table with totals for rows and

columns, must suppress at least one additional cell on the row and one on the column to provide some confusion.

Page 19: Database security

Other Suppression and Concealing• Combine rows or columns to protect sensitive values

• Take a random sample (sample must be large enough to be valid)• Same sample set would be repeated for equivalent queries

• Query analysis• Query and its implications are analyzed• Can be difficult• Maintain query history for each user

• … no perfect solution to inference problem• … recognizing the problem leads to being defensive

Page 20: Database security

Defense in Depth Example//// SafeQuery//

Using System;Using System.Data;Using System.Data.SqlTypes;Using System.Data.SqlClient;Using System.Security.Principal;Using System.Security.Permissions;Using System.Text.RegularExpressions;Using System.Threading;Using System.Web;Using Microsoft.Win32;... [SqlClientPermissionAttribute(SecurityAction.PermitOnly,AllowBlankPassword=false)][RegistryPermissionAttribute(SecurityAction.PermitOnly,Read=@"HKEY_LOCAL_MACHINE\SOFTWARE\Client”)]static string GetName(string Id){ SqlCommand cmd = null; string Status = “Name Unknown";(continued) try {//Check for valid shipping ID.Regex r = new Regex(@"^\d{4,10}$”);if (!r.Match(Id).Success)throw new Exception(“Invalid ID”); //Get connection string from registry.SqlConnection sqlConn= new SqlConnection(ConnectionString);

//Add shipping ID parameter.string str="sp_GetName";cmd = new SqlCommand(str,sqlConn);cmd.CommandType = CommandType.StoredProcedure;cmd.Parameters.Add(“@ID",Convert.ToInt64(Id)); cmd.Connection.Open();Status = cmd.ExecuteScalar().ToString(); } catch (Exception e) {if (HttpContext.Current.Request.UserHostAddress == “127.0.0.1”)Status = e.ToString();elseStatus = “Error Processing Request";} finally {//Shut down connection--even on failure.if (cmd != null)cmd.Connection.Close();}return Status;} //Get connection string.internal static string ConnectionString {get {return (string)Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Client\”).GetValue(“ConnectionString”);}}

Page 21: Database security

Defense in Depth Example• Blank passwords are never allowed when connecting to the database. • Read only one specific key from the registry; it cannot be made to perform

other registry operations. • The code is hard-core about valid input: 4–10 digits only. Anything else is

bad.• The database connection string is in the registry, not in the code and not in

the Web service file space, such as a configuration file.• The code uses a stored procedure, mainly to hide the application logic in

case the code is compromised.• connection is not using sa. Rather, it’s using a least-privilege account that

has query and execute permissions in the appropriate tables.• use parameters, not string concatenation, to build the query.• The code forces the input into a 64-bit integer.• On error, the attacker is told nothing, other than that a failure occurred.• The connection to the database is always shut down regardless of whether

the code fails.

Page 22: Database security

Conclusion• Do not trust the user’s input!• Be strict about what represents valid input and reject

everything else. Regular expressions are your friend.• Use parameterized queries—not string concatenation—to

build queries.• Do not divulge too much information to the attacker.• Connect to the database server by using a least-privilege

account, not the sysadmin account.

Page 23: Database security

Thank you

Questions?