Web application security

bemutefrogtownΑσφάλεια

18 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

81 εμφανίσεις

SECURE PROGRAMMING TECHNIQUES
Web application security
• SQL Injection
• Parameterized statements
• PHP security
MEELIS ROOS 1
SECURE PROGRAMMING TECHNIQUES
SQL Injection
• A SQL injection attack consists of insertion or"injection"of a
SQL query via the input data from the client to the application
• A successful SQL injection exploit can read sensitive data from
the database,modify database data (Insert/Update/Delete),
execute administration operations on the database (such as
shutdown the DBMS),recover the content of a given file present
on the DBMS file system and in some cases issue commands to
the operating system
• Blind SQL Injection —when you don’t get to see the query
output
– But you can see whether error messages appear or not,or
how long the query takes
MEELIS ROOS 2
SECURE PROGRAMMING TECHNIQUES
Fixing SQL Injection
• Input filtering —only harmless input parameter allowed
• Input escaping —dangerous characters are allowed but
escaped
• Explicit type conversions in SQL —int() etc
• Parameterized statements with type-aware parameter
substitution
• Stored procedures —fixes SQL query structure,parameters
still might need validation
MEELIS ROOS 3
SECURE PROGRAMMING TECHNIQUES
Parameterized statements
• Java with JDBC:
PreparedStatement prep =
conn.prepareStatement("SELECT
*
FROM USERS
WHERE USERNAME=?AND PASSWORD=?");
prep.setString(1,username);
prep.setString(2,password);
prep.executeQuery();
MEELIS ROOS 4
SECURE PROGRAMMING TECHNIQUES
Parameterized statements
• C#with ASP.NET:
using (SqlCommand myCommand =
new SqlCommand("SELECT
*
FROM USERS WHERE
USERNAME=@user AND PASSWORD=HASHBYTES('SHA1',@pwd)",
myConnection))
{
myCommand.Parameters.AddWithValue("@user",user);
myCommand.Parameters.AddWithValue("@pwd",pass);
myConnection.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
...
}
MEELIS ROOS 5
SECURE PROGRAMMING TECHNIQUES
Parameterized statements
• PHP5:
$db = new PDO('pgsql:dbname=database');
$stmt = $db->prepare("SELECT priv FROM testUsers WHERE
username=:username AND password=:password");
$stmt->bindParam(':username',$user);
$stmt->bindParam(':password',$pass);
$stmt->execute();
MEELIS ROOS 6
SECURE PROGRAMMING TECHNIQUES
Parameterized statements
• php-mysqli:
$db = new mysqli("host","user","pass","database");
$stmt = $db -> prepare("SELECT priv FROM testUsers
WHERE username=?AND password=?");
$stmt -> bind_param("ss",$user,$pass);
$stmt -> execute();
MEELIS ROOS 7
SECURE PROGRAMMING TECHNIQUES
Parameterized statements
• Perl:
use DBI;
my $db = DBI->connect('DBI:mysql:mydatabase:host',
'login','password');
$statment = $db->prepare("UPDATE players SET name =?,
score =?,active =?WHERE jerseyNum =?");
$rows_affected = $statment->execute("Smith,Steve",
42,'true',99);
MEELIS ROOS 8
SECURE PROGRAMMING TECHNIQUES
Parameterized statements
• Python:
import sqlite3
db = sqlite3.connect(':memory:')
db.execute('update players set name=:name,score=:score,
active=:active where jerseyNum=:num',
{'num':100,
'name':'John Doe',
'active':False,
'score':-1}
)
MEELIS ROOS 9
SECURE PROGRAMMING TECHNIQUES
Parameterized statements
• Hibernate Query Language (HQL):
Query safeHQLQuery = session.createQuery(
"from Inventory where productID=:productid");
safeHQLQuery.setParameter("productid",
userSuppliedParameter);
MEELIS ROOS 10
SECURE PROGRAMMING TECHNIQUES
PHP
Good:
• Powerful,lots of builtin features
• Lots of libraries
• Simple scripting language
• Simple to start programming
Bad:
• Security has been an afterthought
• Lots of possibilities to shoot yourself in the leg
• Several features can not be used securely
• Makes the newbie mistakenly think he understands PHP
• As a result,lots of vulnerable PHP programs are written
MEELIS ROOS 11
SECURE PROGRAMMING TECHNIQUES
Some PHP security dangers
• include,fopen can accept URLs if configured
• ⇒allow_url_fopen = off,allow_url_include = off,
open_basedir =...
• External programs are run though shell command line
interpreter:system(),exec(),popen(),passthru(),
`...`—so shell special characters are dangerous
• escapeshellarg() and escapeshellcmd() —these help but
understand the exact semantics before using
MEELIS ROOS 12
SECURE PROGRAMMING TECHNIQUES
More PHP security
• PHP has loose typing for easily implementing dynamic typing —
loses many type checks,do them by hand
– Do type conversions explicitly if in doubt (int vs string)
– Variables are automatically initialized
• Always use the new $_GET,$_POST,$_SESSION variables,not
old $_HTTP_*VARS or register_globals
• Use the new $_FILES for uploaded file info
• Disable error reporting to clients,only log errors
• Log errors verbosely and do read and understand the logs
• Hide that PHP is in use?Either in server signature or with
header(...)
MEELIS ROOS 13
SECURE PROGRAMMING TECHNIQUES
PHP and magic quotes
• When magic quotes are on,all ’ (single-quote),"(double quote),
\(backslash) and NULL characters are escaped with a
backslash automatically
– This is identical to what addslashes() does
• Helps to protect programs that do no input validation
• magic_quotes_gpc,magic_quotes_runtime,
magic_quotes_sybase INI-file options
• Deprecated nowadays
MEELIS ROOS 14
SECURE PROGRAMMING TECHNIQUES
Why magic quotes are bad
• Portability —assuming it to be on,or off,affects portability.
Use get_magic_quotes_gpc() to check for this,and code
accordingly
• Performance —Because not every piece of escaped data is
inserted into a database,there is a performance loss for
escaping all this data.Simply calling the escaping functions
(like addslashes()) at runtime is more efficient
• Inconvenience —because not all data needs escaping,it’s often
annoying to see escaped data where it shouldn’t be.For
example,emailing from a form,and seeing a bunch of ´within
the email.To fix,this may require the use of stripslashes().
• Security —You could be lulled in a feeling of false security if
you have magic_quotes=On on a test server and Off on
production server
MEELIS ROOS 15
SECURE PROGRAMMING TECHNIQUES
Escaping functions
• addslashes() —Quote ’"\with slashes
• addcslashes() —Quote string with slashes in C style
• quotemeta() —Quote meta characters.\+ *?[ ˆ ] ( $ )
• htmlentities() —Convert all applicable characters to entities
• htmlspecialchars() —Convert special characters to entities
• nl2br() —Inserts HTML line breaks before all newlines
• stripslashes() —Un-quotes a quoted string
• stripcslashes() —Un-quote string quoted with
addcslashes()
• preg_match() —Perform a regular expression match
• preg_quote() —Quote regular expression characters
MEELIS ROOS 16
SECURE PROGRAMMING TECHNIQUES
Escaping functions
• Additionally,addslashes() is not a cure-all against SQL
injection attacks.
• You should use your database’s dedicated escape function
(such as mysql_real_escape_string()) or better yet,use
parameterized queries through mysqli->prepare():
$query = sprintf("SELECT
*
FROM users where
UserName='%s'and password='%s'",
mysql_real_escape_string($username),
mysql_real_escape_string($password));
mysql_query($query);
MEELIS ROOS 17