SlideShare uma empresa Scribd logo
1 de 23
Database Input
Issues
Writing Secure Code
Agenda
• Introduction
• Sql Injection
  • Issue
  • Remedies
• Inference Problem
  • Issue
  • Remedies
• Sql Stored procedures
• Defense in Depth Example
• Conclusion
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)
Web Application Vulnerabilities
          Source



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

                                                            Critical
                                                           Database
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 user
What 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.
Imagine that the database table
 schema looks like this
                                              C us tome r *
                                                  C ustome rID
                                                  La stNa me
                                                  F irstNa me
                                                  Middle Initia l
              C us tome r C r e ditC ar d *
                  C ustome rID                    A ddre ss

                  C re ditC a rdID                A pa rtme nt
                                                  C ity
                                                  Sta te
                                                  Posta lC ode
                                                  C ountry




              C r e ditC ar d *
                  C re ditC a rdID
                  Ty pe
                  Numbe r
                  Ex pire s




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.
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 --
Can you spot security flaws?
string Status = “No";
string sqlstring = “";                            Connecting as a super admin.
try {
SqlConnection sql= new SqlConnection(
            @"data source=localhost;” +           Sa is to SQL Server what SYSTEM is to
            “user id=sa;password=password;”);     Windows NT and later.
             sql.Open();
sqlstring="SELECT HasShipped” +
        “ FROM detail WHERE ID=‘“ + Id + “‘";     What if the connection fails to the
SqlCommand cmd = new SqlCommand(sqlstring,sql);   database due to some network issue.
if ((int)cmd.ExecuteScalar() != 0)
       Status = “Yes";
                                                  A complete description of how the
} catch (SqlException se) {                       failure occurred is given to the attacker.
       Status = sqlstring + “ failednr";
       foreach (SqlError e in se.Errors) {
       Status += e.Message + “nr";
}
} catch (Exception e) {
       Status = e.ToString();
}
Pseudoremedy:Quoting the Input
int age = ...; // age from user

string name = ...; // name from user
name = 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 age
field, 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.
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 user
     SqlConnection 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 example
     CREATE PROCEDURE sp_MySProc @input varchar(128)
     AS
     exec(@input)
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
Remedy #2: Building SQL Statements Securely
                                   Function IsValidUserAndPwd(strName, strPwd)
                                   ’ Note I am using a trusted connection to SQL Server.
• Use parameterized commands.      ’ Never use uid=sa;pwd=
                                   strConn = “Provider=sqloledb;” + _
   • SELECT count(*) FROM client   “Server=server-sql;” + _
                                   “database=client;” + _
     WHERE name=? AND pwd=?        “trusted_connection=yes"
                                   Set cn = CreateObject(“ADODB.Connection”)
                                   cn.Open strConn

                                   Set cmd = CreateObject(“ADODB.Command”)
                                   cmd.ActiveConnection = cn
                                   cmd.CommandText = _
                                   “select count(*) from client where name=? and pwd=?"
                                   cmd.CommandType = 1 ’ 1 means adCmdText
                                   cmd.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 parm1
                                   parm1.Value = strName

                                   Set parm2 = cmd.CreateParameter(“pwd", 200, 1, 32, ““)
                                   cmd.Parameters.Append parm2
                                   parm2.Value = strPwd

                                   Set rs = cmd.Execute
                                   IsValidUserAndPwd = false
                                   If rs(0).value = 1 Then IsValidUserAndPwd = true
                                    rs.Close
                                   cn.Close
                                   End Function
Building SQL Stored Procedures
Securely
  • Use quotename function
             select 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=0x74735D27
          select @a
          set @a=quotename(@a)
          select @a

          set @a=‘ts]’’’
          select @a
          set @a=quotename(@a)
          select @a
Use sp_executesql to execute sql statements build dynamically.
          -- Test the code with these variables
          declare @name varchar(64)
          set @name = N’White’

          -- Do the work
          exec sp_executesql
          N’select au_id from pubs.dbo.authors where au_lname=@lname’,
          N’@lname varchar(64)’,
          @lname = @name
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
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
Inference Problem 3
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
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.
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
Defense in Depth Example
//
// SafeQuery
//
                                                              //Add shipping ID parameter.
Using System;                                                 string str="sp_GetName";
Using System.Data;                                            cmd = new SqlCommand(str,sqlConn);
Using System.Data.SqlTypes;                                   cmd.CommandType = CommandType.StoredProcedure;
Using System.Data.SqlClient;                                  cmd.Parameters.Add(“@ID",Convert.ToInt64(Id));
Using System.Security.Principal;
Using System.Security.Permissions;                            cmd.Connection.Open();
Using System.Text.RegularExpressions;                         Status = cmd.ExecuteScalar().ToString();
Using System.Threading;
Using System.Web;                                             } catch (Exception e) {
Using Microsoft.Win32;                                        if (HttpContext.Current.Request.UserHostAddress == “127.0.0.1”)
...                                                           Status = e.ToString();
                                                              else
[SqlClientPermissionAttribute(SecurityAction.PermitOnly,      Status = “Error Processing Request";
AllowBlankPassword=false)]                                    } finally {
[RegistryPermissionAttribute(SecurityAction.PermitOnly,       //Shut down connection--even on failure.
Read=@"HKEY_LOCAL_MACHINESOFTWAREClient”)]                  if (cmd != null)
static string GetName(string Id)                              cmd.Connection.Close();
{                                                             }
                                                              return Status;
SqlCommand cmd = null;                                        }

string Status = “Name Unknown";                               //Get connection string.
(continued)                                                   internal static string ConnectionString {
                                                              get {
try {                                                         return (string)Registry
//Check for valid shipping ID.                                .LocalMachine
Regex r = new Regex(@"^d{4,10}$”);                           .OpenSubKey(@"SOFTWAREClient”)
if (!r.Match(Id).Success)                                     .GetValue(“ConnectionString”);
throw new Exception(“Invalid ID”);                            }
                                                              }
//Get connection string from registry.
SqlConnection sqlConn= new SqlConnection(ConnectionString);
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.
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.
Thank you
 Questions?

Mais conteúdo relacionado

Mais procurados

Indexing thousands of writes per second with redis
Indexing thousands of writes per second with redisIndexing thousands of writes per second with redis
Indexing thousands of writes per second with redispauldix
 
IPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curseIPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curseYonatan Levin
 
Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseYonatan Levin
 
Optimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and CreativityOptimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and CreativityMongoDB
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebChristian Baranowski
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserHoward Lewis Ship
 
JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011Stephen Chin
 
A Brief Introduction To Reactive Extensions
A Brief Introduction To Reactive ExtensionsA Brief Introduction To Reactive Extensions
A Brief Introduction To Reactive ExtensionsJames World
 
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)Stephen Chin
 
Spring has got me under it’s SpEL
Spring has got me under it’s SpELSpring has got me under it’s SpEL
Spring has got me under it’s SpELEldad Dor
 
Cassandra summit keynote 2014
Cassandra summit keynote 2014Cassandra summit keynote 2014
Cassandra summit keynote 2014jbellis
 
Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Ralph Schindler
 
More Stored Procedures and MUMPS for DivConq
More Stored Procedures and  MUMPS for DivConqMore Stored Procedures and  MUMPS for DivConq
More Stored Procedures and MUMPS for DivConqeTimeline, LLC
 
Rails Concurrency Gotchas
Rails Concurrency GotchasRails Concurrency Gotchas
Rails Concurrency Gotchasmarcostoledo
 
JavaFX and Scala - Like Milk and Cookies
JavaFX and Scala - Like Milk and CookiesJavaFX and Scala - Like Milk and Cookies
JavaFX and Scala - Like Milk and CookiesStephen Chin
 
Mongo db basic installation
Mongo db basic installationMongo db basic installation
Mongo db basic installationKishor Parkhe
 

Mais procurados (20)

Indexing thousands of writes per second with redis
Indexing thousands of writes per second with redisIndexing thousands of writes per second with redis
Indexing thousands of writes per second with redis
 
IPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curseIPC: AIDL is sexy, not a curse
IPC: AIDL is sexy, not a curse
 
Ipc: aidl sexy, not a curse
Ipc: aidl sexy, not a curseIpc: aidl sexy, not a curse
Ipc: aidl sexy, not a curse
 
Optimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and CreativityOptimizing Slow Queries with Indexes and Creativity
Optimizing Slow Queries with Indexes and Creativity
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
Backbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The BrowserBackbone.js: Run your Application Inside The Browser
Backbone.js: Run your Application Inside The Browser
 
JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011JavaFX 2.0 With Alternative Languages - JavaOne 2011
JavaFX 2.0 With Alternative Languages - JavaOne 2011
 
A Brief Introduction To Reactive Extensions
A Brief Introduction To Reactive ExtensionsA Brief Introduction To Reactive Extensions
A Brief Introduction To Reactive Extensions
 
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)
Cleaner APIs, Cleaner UIs with Visage (33rd Degrees)
 
Spring has got me under it’s SpEL
Spring has got me under it’s SpELSpring has got me under it’s SpEL
Spring has got me under it’s SpEL
 
Developer Testing Tools Roundup
Developer Testing Tools RoundupDeveloper Testing Tools Roundup
Developer Testing Tools Roundup
 
Cassandra summit keynote 2014
Cassandra summit keynote 2014Cassandra summit keynote 2014
Cassandra summit keynote 2014
 
Xm lparsers
Xm lparsersXm lparsers
Xm lparsers
 
What are arrays in java script
What are arrays in java scriptWhat are arrays in java script
What are arrays in java script
 
Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2Zend Framework 1 + Doctrine 2
Zend Framework 1 + Doctrine 2
 
More Stored Procedures and MUMPS for DivConq
More Stored Procedures and  MUMPS for DivConqMore Stored Procedures and  MUMPS for DivConq
More Stored Procedures and MUMPS for DivConq
 
Rails Concurrency Gotchas
Rails Concurrency GotchasRails Concurrency Gotchas
Rails Concurrency Gotchas
 
JavaFX and Scala - Like Milk and Cookies
JavaFX and Scala - Like Milk and CookiesJavaFX and Scala - Like Milk and Cookies
JavaFX and Scala - Like Milk and Cookies
 
Mongo db basic installation
Mongo db basic installationMongo db basic installation
Mongo db basic installation
 

Destaque

可扩展网站架构(for 网志年会)
可扩展网站架构(for 网志年会)可扩展网站架构(for 网志年会)
可扩展网站架构(for 网志年会)Dahui Feng
 
Linux必备知识与Unix基础文化
Linux必备知识与Unix基础文化Linux必备知识与Unix基础文化
Linux必备知识与Unix基础文化Dahui Feng
 
SXSW interactive 2008
SXSW interactive 2008SXSW interactive 2008
SXSW interactive 2008kapookababy
 
Social Computing in AIC Schools
Social Computing in AIC SchoolsSocial Computing in AIC Schools
Social Computing in AIC SchoolsTrish Everett
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your BusinessBarry Feldman
 

Destaque (7)

可扩展网站架构(for 网志年会)
可扩展网站架构(for 网志年会)可扩展网站架构(for 网志年会)
可扩展网站架构(for 网志年会)
 
Linux必备知识与Unix基础文化
Linux必备知识与Unix基础文化Linux必备知识与Unix基础文化
Linux必备知识与Unix基础文化
 
Ibm irl
Ibm irlIbm irl
Ibm irl
 
SXSW interactive 2008
SXSW interactive 2008SXSW interactive 2008
SXSW interactive 2008
 
Buffer OverFlow
Buffer OverFlowBuffer OverFlow
Buffer OverFlow
 
Social Computing in AIC Schools
Social Computing in AIC SchoolsSocial Computing in AIC Schools
Social Computing in AIC Schools
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
 

Semelhante a Database security

JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
Owasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiOwasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiowaspindy
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracleyazidds2
 
Php Security - OWASP
Php  Security - OWASPPhp  Security - OWASP
Php Security - OWASPMizno Kruge
 
Chapter 14 sql injection
Chapter 14 sql injectionChapter 14 sql injection
Chapter 14 sql injectionnewbie2019
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRPeter Elst
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCOUM SAOKOSAL
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programmingchhaichivon
 
SQL Server with CSharp WinForms.pdf
SQL Server with CSharp WinForms.pdfSQL Server with CSharp WinForms.pdf
SQL Server with CSharp WinForms.pdfMona686896
 
Microsoft Ado
Microsoft AdoMicrosoft Ado
Microsoft Adooswchavez
 
8 sql injection
8   sql injection8   sql injection
8 sql injectiondrewz lin
 
Bigger Stronger Faster
Bigger Stronger FasterBigger Stronger Faster
Bigger Stronger FasterChris Love
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manualsameer farooq
 
ShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlChema Alonso
 

Semelhante a Database security (20)

Sql injection
Sql injectionSql injection
Sql injection
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Owasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLiOwasp Indy Q2 2012 Advanced SQLi
Owasp Indy Q2 2012 Advanced SQLi
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Php Security - OWASP
Php  Security - OWASPPhp  Security - OWASP
Php Security - OWASP
 
Chapter 14 sql injection
Chapter 14 sql injectionChapter 14 sql injection
Chapter 14 sql injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
Sql injection
Sql injectionSql injection
Sql injection
 
For Beginers - ADO.Net
For Beginers - ADO.NetFor Beginers - ADO.Net
For Beginers - ADO.Net
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
SQL Server with CSharp WinForms.pdf
SQL Server with CSharp WinForms.pdfSQL Server with CSharp WinForms.pdf
SQL Server with CSharp WinForms.pdf
 
Microsoft Ado
Microsoft AdoMicrosoft Ado
Microsoft Ado
 
8 sql injection
8   sql injection8   sql injection
8 sql injection
 
Bigger Stronger Faster
Bigger Stronger FasterBigger Stronger Faster
Bigger Stronger Faster
 
Java programming lab manual
Java programming lab manualJava programming lab manual
Java programming lab manual
 
ShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)SqlShmooCon 2009 - (Re)Playing(Blind)Sql
ShmooCon 2009 - (Re)Playing(Blind)Sql
 
Jdbc
JdbcJdbc
Jdbc
 
Linq
LinqLinq
Linq
 

Último

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 

Último (20)

Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 

Database security

  • 2. Agenda • Introduction • Sql Injection • Issue • Remedies • Inference Problem • Issue • Remedies • Sql Stored procedures • Defense in Depth Example • Conclusion
  • 3. 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)
  • 4. Web Application Vulnerabilities Source void ProcessRequest() { Sanitizer string s = GetUserInput("name"); … s = Validate(s); … … ExecuteQuery(“select …" + s + “…”); } Sink Critical Database
  • 5. 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 user What 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.
  • 6. Imagine that the database table schema looks like this C us tome r * C ustome rID La stNa me F irstNa me Middle Initia l C us tome r C r e ditC ar d * C ustome rID A ddre ss C re ditC a rdID A pa rtme nt C ity Sta te Posta lC ode C ountry C r e ditC ar d * C re ditC a rdID Ty pe Numbe r Ex pire s 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.
  • 7. 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 --
  • 8. Can you spot security flaws? string Status = “No"; string sqlstring = “"; Connecting as a super admin. try { SqlConnection sql= new SqlConnection( @"data source=localhost;” + Sa is to SQL Server what SYSTEM is to “user id=sa;password=password;”); Windows NT and later. sql.Open(); sqlstring="SELECT HasShipped” + “ FROM detail WHERE ID=‘“ + Id + “‘"; What if the connection fails to the SqlCommand cmd = new SqlCommand(sqlstring,sql); database due to some network issue. if ((int)cmd.ExecuteScalar() != 0) Status = “Yes"; A complete description of how the } catch (SqlException se) { failure occurred is given to the attacker. Status = sqlstring + “ failednr"; foreach (SqlError e in se.Errors) { Status += e.Message + “nr"; } } catch (Exception e) { Status = e.ToString(); }
  • 9. Pseudoremedy:Quoting the Input int age = ...; // age from user string name = ...; // name from user name = 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 age field, 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.
  • 10. 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 user SqlConnection 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 example CREATE PROCEDURE sp_MySProc @input varchar(128) AS exec(@input)
  • 11. 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
  • 12. Remedy #2: Building SQL Statements Securely Function IsValidUserAndPwd(strName, strPwd) ’ Note I am using a trusted connection to SQL Server. • Use parameterized commands. ’ Never use uid=sa;pwd= strConn = “Provider=sqloledb;” + _ • SELECT count(*) FROM client “Server=server-sql;” + _ “database=client;” + _ WHERE name=? AND pwd=? “trusted_connection=yes" Set cn = CreateObject(“ADODB.Connection”) cn.Open strConn Set cmd = CreateObject(“ADODB.Command”) cmd.ActiveConnection = cn cmd.CommandText = _ “select count(*) from client where name=? and pwd=?" cmd.CommandType = 1 ’ 1 means adCmdText cmd.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 parm1 parm1.Value = strName Set parm2 = cmd.CreateParameter(“pwd", 200, 1, 32, ““) cmd.Parameters.Append parm2 parm2.Value = strPwd Set rs = cmd.Execute IsValidUserAndPwd = false If rs(0).value = 1 Then IsValidUserAndPwd = true rs.Close cn.Close End Function
  • 13. Building SQL Stored Procedures Securely • Use quotename function select 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=0x74735D27 select @a set @a=quotename(@a) select @a set @a=‘ts]’’’ select @a set @a=quotename(@a) select @a Use sp_executesql to execute sql statements build dynamically. -- Test the code with these variables declare @name varchar(64) set @name = N’White’ -- Do the work exec sp_executesql N’select au_id from pubs.dbo.authors where au_lname=@lname’, N’@lname varchar(64)’, @lname = @name
  • 14. 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
  • 15. 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
  • 17. 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
  • 18. 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.
  • 19. 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
  • 20. Defense in Depth Example // // SafeQuery // //Add shipping ID parameter. Using System; string str="sp_GetName"; Using System.Data; cmd = new SqlCommand(str,sqlConn); Using System.Data.SqlTypes; cmd.CommandType = CommandType.StoredProcedure; Using System.Data.SqlClient; cmd.Parameters.Add(“@ID",Convert.ToInt64(Id)); Using System.Security.Principal; Using System.Security.Permissions; cmd.Connection.Open(); Using System.Text.RegularExpressions; Status = cmd.ExecuteScalar().ToString(); Using System.Threading; Using System.Web; } catch (Exception e) { Using Microsoft.Win32; if (HttpContext.Current.Request.UserHostAddress == “127.0.0.1”) ... Status = e.ToString(); else [SqlClientPermissionAttribute(SecurityAction.PermitOnly, Status = “Error Processing Request"; AllowBlankPassword=false)] } finally { [RegistryPermissionAttribute(SecurityAction.PermitOnly, //Shut down connection--even on failure. Read=@"HKEY_LOCAL_MACHINESOFTWAREClient”)] if (cmd != null) static string GetName(string Id) cmd.Connection.Close(); { } return Status; SqlCommand cmd = null; } string Status = “Name Unknown"; //Get connection string. (continued) internal static string ConnectionString { get { try { return (string)Registry //Check for valid shipping ID. .LocalMachine Regex r = new Regex(@"^d{4,10}$”); .OpenSubKey(@"SOFTWAREClient”) if (!r.Match(Id).Success) .GetValue(“ConnectionString”); throw new Exception(“Invalid ID”); } } //Get connection string from registry. SqlConnection sqlConn= new SqlConnection(ConnectionString);
  • 21. 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.
  • 22. 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.