web application security - ut · secure programming techniques sql injection a sql injection attack...
Post on 28-Jan-2021
13 Views
Preview:
TRANSCRIPT
-
SECURE PROGRAMMING TECHNIQUES
Web application security
• SQL injection
• Parameterized statements
• Other injections
• Cross-site scripting
• Persistent and reflected XSS
• AJAX and cross-domains access
• Javascript
• Cross-Site Request Forgery
• Clickjacking
• OAuth 2 and OpenID Connect
MEELIS ROOS 1
-
SECURE PROGRAMMING TECHNIQUES
SQL injection
• A SQL injection attack consists of insertion or "injection" of aSQL query via the input data from the client to the application
• A successful SQL injection exploit can read sensitive data fromthe database, modify database data (Insert/Update/Delete),execute administration operations on the database (such asshut down the DBMS), recover the content of a given filepresent on the DBMS file system and in some cases issuecommands to the operating system
• Blind SQL injection — when you don’t get to see the queryoutput
– But you can see whether error messages appear or not, orhow long the query takes
MEELIS ROOS 2
-
SECURE PROGRAMMING TECHNIQUES
Fixing SQL injection
• Input filtering — only harmless input parameters allowed
• Input escaping — dangerous characters are allowed butescaped
• Explicit type conversions in SQL — int() etc
• Parameterized statements with type-aware parametersubstitution
– Parameters are sent as metadata (in a structured way, notinline)
– Also allows for performance gains with most databases
• Stored procedures — fixes SQL query structure, parametersstill 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
• PHP 5+:
$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
LDAP injection
• Attacker can inject special characters for structural changesinto any structured query if validation is missing
• LDAP as an example
String ldapSearchQuery =
"(&(cn=" + $user + ")(password=" + $pwd + "));
• What about ’*’/’*’ or ’joe)(|(password=*)’?
• Distinguished name (DN) and search filters have differentmeta-characters:
– DN: \ , . " < > ; and trailing space
– Filter: \ * ( ) and 0 bytes
• Blind injection attacks are also possible
MEELIS ROOS 11
-
SECURE PROGRAMMING TECHNIQUES
XPath injection
• We have XML in databases too, need to make queries fromthese bases
• XPath and XQuery — identification and querying of elementsfrom XML structures
• Example: query = "/orders/client[@id=’" + clientId +"’]/order/item[price >= ’" + priceFilter + "’]";
• Attack: clientId = "’] | /* | /foo[bar=’"
MEELIS ROOS 12
-
SECURE PROGRAMMING TECHNIQUES
XPath injection — sample data
Meelis Roos mroos@ut.ee
1
25.00 Foo
10
2.50 Bar
MEELIS ROOS 13
-
SECURE PROGRAMMING TECHNIQUES
Security implications of AJAX
• Client-side security controls are not enough
• Increased attack surface (more entry points on the server)
• Bridging the gap between users and services — previouslyinternal services (SOA!) are made accessible to the users
• New possibilities for Cross-Site Scripting (XSS) — exploitingXSS in background, in less visible manner
• Untrusted information sources
• Dynamic script construction — for example JSON serializationand injection
MEELIS ROOS 14
-
SECURE PROGRAMMING TECHNIQUES
AJAX and security testing
• The issue with state — many asychronous queries, state isspread between server and browser
• Requests are initiated through timer events
• Dynamic DOM updates — eval() is the easiest method
• XML Fuzzing — tester needs to do it on XML, not GET/POSTlevel
MEELIS ROOS 15
-
SECURE PROGRAMMING TECHNIQUES
JSON
• JSON is a syntax for passing around objects that containname/value pairs, arrays and other objects
• JSON is based on a subset of Javascript, it is script content,which potentially can contain malicious code
• However, JSON is a safe subset of Javascript that excludesassignment and invocation
• Therefore, many Javascript libraries simply use the eval()function to convert JSON into a Javascript object
• To exploit this, attackers send malformed JSON objects to theselibraries so the eval() function executes their malicious code
• Secure the use of JSON — for example with regular expressions
• Use native JSON parsers instead of eval() (JSON.parse)
MEELIS ROOS 16
-
SECURE PROGRAMMING TECHNIQUES
JSON example
{"skills": {
"web":[
{"name": "html",
"years": "8"
},
{"name": "css",
"years": "3"
}]
"database":[
{"name": "sql",
"years": "7"
}]
}}
MEELIS ROOS 17
-
SECURE PROGRAMMING TECHNIQUES
Browser and XSS
• Many languages: HTTP, HTML, URL, CSS, Javascript, XML,JSON, plaintext, SQL . . .
• Each language has different quoting and commentingconventions
• The languages can be nested inside each other
• A text that is benign in one context might be dangerous inanother
• Sloppy encoding allows injection of evil scripts
MEELIS ROOS 18
-
SECURE PROGRAMMING TECHNIQUES
Cross-Site Scripting
• Also abbreviated as XSS
• Protect the browser from receiving malicious content throughyour web application
• Input may come from other users via the web site, from URL-s,other web sites, ...
• History: guestbooks, webmail
• Persistent and reflected XSS
MEELIS ROOS 19
-
SECURE PROGRAMMING TECHNIQUES
Cross-Site Scripting
• Example: NetBeans example HelloWebApp
Hello ${param.name}!
• What if we give it input like this?%3Cscript%20src%3D%22http%3A//example.com/evil.js%22
%3E%3C/script%3E
• Decodes toHello !
• Example exploitation:Click!
MEELIS ROOS 20
-
SECURE PROGRAMMING TECHNIQUES
Persistent XSS
• Persistent XSS — scripts are first uploaded to server via oneuser, stored there and later served to other users as part ofsome web page
MEELIS ROOS 21
-
SECURE PROGRAMMING TECHNIQUES
Reflected XSS
• Reflected XSS — scripts on page use page parameters directly
var queryStr = window.location.search.substr(1);
var i, splitArray;
queryStr=unescape(queryStr)
queryStr=queryStr.replace("+"," ").replace("+"," ")
if (queryStr.length != 0) {
splitArray = queryStr.split("&")
for (i=0; i
-
SECURE PROGRAMMING TECHNIQUES
Example: MySpace samy worm
• Heavily filtered HTML but div works:
• Need quotes, store them in other variables and eval:
• Now there are single quotes but the word javascript is alsofiltered:
MEELIS ROOS 23
-
SECURE PROGRAMMING TECHNIQUES
Example: MySpace samy worm
• We also need double quotes, escaped quotes are stripped too
• Need to refer to document body to get to the profile, innerHTMLis filtered
alert(eval(’document.body.inne’ + ’rHTML’));
• Need XmlHttpRequest, onreadystatechange is filtered
eval(’xmlhttp.onread’ + ’ystatechange = callback’);
• Searching for data finds the search string itself, hide it:
var index = html.indexOf(’frien’ + ’dID’);
MEELIS ROOS 24
-
SECURE PROGRAMMING TECHNIQUES
Example: MySpace samy worm
• Profiles and posting reside on different servers, XmlHttpRequestneeds the same server... but main server happens to work forprofiles too:
if (location.hostname == ’profile.myspace.com’)
document.location = ’http://www.myspace.com’ +
location.pathname + location.search;
• Finally, a POST to profile! But it needs to provide a hash fromconfirmation page — just request the page and parse it
• Finally, to spread the code itself, it needs to be manuallyURL-encoded
MEELIS ROOS 25
-
SECURE PROGRAMMING TECHNIQUES
Preventing XSS
• Input validation with whitelists
• Blacklisting is hard — depends of which layer we are looking:
<
%3C
<
<
<
MEELIS ROOS 26
-
SECURE PROGRAMMING TECHNIQUES
How to fix it
• Server-side input validation, of course
• Don’t make the security worse by working around it
• Don’t generate and execute code dynamically
• Don’t insert untrusted HTML content without sanitizing
• Use sandboxing when integrating distrusted content(give that data its own Javascript execution context and DOMtree)
MEELIS ROOS 27
-
SECURE PROGRAMMING TECHNIQUES
Same-Origin Policy
• There is no single same-origin policy (exact mechanisms dependon API)
• Documents retrieved from distinct origins are isolated fromeach other
• Tries to make it possible for largely unrestrained scripting andother interactions between pages served as a part of the samesite whilst almost completely preventing any interferencebetween unrelated sites
• DOM access (Javascript and other languages)
• XMLHttpRequest
• Cookies
• Flash, Java, Silverlight, . . .
MEELIS ROOS 28
-
SECURE PROGRAMMING TECHNIQUES
Same-Origin Policy: DOM
• Browser permits scripts contained in a first web page to accessdata in a second web page, but only if both web pages have thesame origin
• Same origin means that URI protocol, host and port mustmatch
• If two windows or frames set the document.domain value tosame superdomain, access is also permitted
• Cross-Origin Resource Sharing (CORS) can also enable accessvia origin verification using special HTTP headers
• Content-Security-Policy header can also be used against XSS toindicate, which pages can provides scripts for this web page
MEELIS ROOS 29
-
SECURE PROGRAMMING TECHNIQUES
Same-Origin Policy: CORS
• Client can indicate the origin of the request using Origin:request header
• Server can add HTTP response header that describes the set oforigins that are permitted to read that information using a webbrowser
– Access-Control-Allow-Origin: http://example.com
• Also usable for XmlHttpRequest
• Note that query is sent by the browser, processed by the serverand full response retrieved, only then verified
MEELIS ROOS 30
-
SECURE PROGRAMMING TECHNIQUES
Same-Origin Policy: CORS
• Arbitrary HTTP methods can be used, verifying if the areallowed using pre-flighting the request for approval
– Access-Control-Request-Method: andAccess-Control-Request-Headers: for requests
– Access-Control-Allow-Origin:,Access-Control-Allow-Methods:,Access-Control-Allow-Headers: and Access-Control-Max-Age:in responses
– Also possible to indicate that authentication credentials areneeded, using Access-Control-Allow-Credentials: true
MEELIS ROOS 31
-
SECURE PROGRAMMING TECHNIQUES
Same-Origin Policy: Cookies
• Cookies are identified by (name, domain, path) triple
• Server can set cookie for any domain suffix of hostname, excepttoplevel domains
• Path can be anything
• Browser sends all matching cookies with request
• Cookies can be deleted by sending expired TTL
• Can be read and stolen by scripts on page (except HttpOnly)
• Secure cookies are only sent using https (but can be set byanyone)
• 3rd party cookies for cooperative multi-site user tracking
MEELIS ROOS 32
-
SECURE PROGRAMMING TECHNIQUES
Cross-site data access
• It is extremely useful to obtain data from other sites and mashit up
• Same Origin Policy for HTML to prevent XSS
– Prevents useful things
– Allows dangerous things
• Scripts, images and other resources are an exception tosame-origin policy
– Dynamic script tag can make a GET request to a server
– Impossible to quarantee that server does not send an evilscript
MEELIS ROOS 33
-
SECURE PROGRAMMING TECHNIQUES
Avoiding the Same-Origin Policy
• Same origin policy is enforced with string matching of domainname
• Browsers allow a web application to relax its domain definitionto the super domain of the application itself
• Even with the server being the same, it might not be theoriginator of the contents, especially in the context ofuser-uploaded content
• Padded JSON expression (JSPONP) returned from script tagwith params
• AJAX proxy
MEELIS ROOS 34
-
SECURE PROGRAMMING TECHNIQUES
Flash and XSS
• Flash has XSS protection with same origin domain policy
• For exceptions, the other servers need to declare they allowaccess from flash from different domains
• crossdomain.xml in web root
• Easy to be too sloppy:
MEELIS ROOS 35
-
SECURE PROGRAMMING TECHNIQUES
Javascript
• Javascript’s Global Object is the root cause of XSS attacks
• All scripts run with the same authority
• Insecure by design?
• Therefore, mashups and ads are also insecure . . .
• More generally — If there is script from two or more sources,the application security depends on trusting all the sources
MEELIS ROOS 36
-
SECURE PROGRAMMING TECHNIQUES
Cross-Site Request Forgery
• Also CSRF
• User is logged on to site A (in one browser tab)
• Malicious code in site B contains hidden links to site A thatwork when a user is logged on there
• User can not do much besides logging out before opening othersites, fix needs to be in application in site A
MEELIS ROOS 37
-
SECURE PROGRAMMING TECHNIQUES
CSRF remedies
• Require a secret token on form submissions
• Require authentication data along with the query
• Check Referer header
• Limit lifetime of session, maybe also source IP
• Do not allow GET for URLs that modify data (but scripts canuse POST too)
MEELIS ROOS 38
-
SECURE PROGRAMMING TECHNIQUES
Clickjacking
• UI Redress attack
• When users click somewhere, attacker makes the click go tosome other object transparently
• The user thinks he is clicking something harmless, whileactually clicking on something dangerous
• Client-side workaround: prevent any click on transparentobjects (NoScript allows this)
• Server-side workaround: prevent pages from being opened inrandom pages iframe
– Content-Security-Policy: frame-ancestors ...
– ’none’, ’self’, www.friendlysite.com
• Server-side workaround (legacy): X-Frame-Options header
MEELIS ROOS 39
-
SECURE PROGRAMMING TECHNIQUES
Content-Security-Policy
• This header can restrict much more to enforce security policy
• Restrict ways of running javascript (inline, dynamic, eval, linksource)
• Restricting ways of declaring CSS (inline, link source)
• Child resource locations (iframes, objects, fonts, images,WebSocket connects, media)
• Mandatory subresource integrity policy
• Additional header for reporting violations to the server
MEELIS ROOS 40
-
SECURE PROGRAMMING TECHNIQUES
OAuth 2.0
• Standardised authorization protocol for web applications
• OAuth 2.0 is a protocol for granting clients limited access to aprotected web service or API
• This is done by an authorization server which issues the clientswith access tokens
• Different kinds of tokens:
– access token (usually bearer tokens)
– refresh token
– ID token
• Different token types:
– Bearer token
– MAC token
MEELIS ROOS 41
-
SECURE PROGRAMMING TECHNIQUES
OAuth endpoints
• Server discovery
• Server JWK set
• Authorization
• Token
• Token introspection
• Token revocation
• UserInfo
• Logout
MEELIS ROOS 42
-
SECURE PROGRAMMING TECHNIQUES
OAuth protocol
• Service redirects browser to authorization server
• Authorization server authenticates users in any way it wants
• Authorization server redirects browser back to initial server
– Preconfigured list of allowed domains for redirecting back
• Additional queries between servers for token introspection
MEELIS ROOS 43
-
SECURE PROGRAMMING TECHNIQUES
OpenID Connect (OIDC)
• Uses OAuth flows for user identification in addition toauthorization
• ID Token is a signed JSON Web Token (JWT)
MEELIS ROOS 44
-
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 45
-
SECURE PROGRAMMING TECHNIQUES
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, notold $_HTTP_*VARS
• Use the new $_FILES for uploaded file info
• External programs are run though shell command lineinterpreter: system(), exec(), popen(), passthru(),‘...‘ — so shell special characters are dangerous
• Disable error reporting to clients, only log errors
• Log errors verbosely and do read and understand the logs
MEELIS ROOS 46
-
SECURE PROGRAMMING TECHNIQUES
• Hide that PHP is in use? Either in server signature or withheader(...)
MEELIS ROOS 47
-
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 withaddcslashes()
• preg_match() — Perform a regular expression match
• preg_quote() — Quote regular expression characters
MEELIS ROOS 48
-
SECURE PROGRAMMING TECHNIQUES
Escaping functions
• Additionally, addslashes() is not a cure-all against SQLinjection attacks.
• You should use your database’s dedicated escape function(such as mysql_real_escape_string()) or better yet, useparameterized 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 49
top related