FIT3173: Web Application Security I
Dr Xiao of Software Systems and Cybersecurity Faculty of Information Technology
Learning Outcomes of This Lecture
Copyright By PowCoder代写 加微信 powcoder
• Review the basics of Web
• Understand the significance of web security and threats in Web
• Evaluate the security of web cookies and understand session hijacking • Know how SQL injection works
• Analyse the vulnerability of second-order SQL injection
• Know the countermeasures against SQL injection
Security for The Web • Previously: Applications written in C and C++
• Issues like remote code injection and sensitive data theft arise from violations of memory safety
• Now: Security for the World-Wide Web (WWW)
• New vulnerabilities to consider: cookies, SQL injection, Cross-site Scripting (XSS), Session Hijacking, and Cross-site Request Forgery (CSRF)
• These share some common causes with memory safety vulnerabilities; like confusion of code and data
• Defense also similar: validate untrusted input!
Web & HTTP (HTTPS)
• Requests (user clicks) contain:
• The URL of the resource the client wishes to obtain; Headers describing what the browser can do
• Special characters are encoded as hex:
• E.g., %0A = newline, %20 or + = space, %2B = +
HTTP Request
A correctly composed HTTP request contains the following elements:
A request line (method, file path, HTTP version)
o GET method: asks the server to send a resource
o POST method: sends input data to the server
A series of HTTP headers, or header fields
A message body, if needed
HTTP Response An HTTP response contains:
A status line (HTTP version, status code, reason phrase)
o 4xx – Client Error. E.g., 404 Not Found
o 5xx – Server Error. E.g., 503 Service Unavailable
A series of HTTP headers, or header field
o Cookies: Represent state the server would like the browser to store on its behalf
A message body, which is usually needed
Web: Client and Server
(Much) user data is part of the browser
DB is a separate entity, logically (and often physically)
Browser (Client) Side
• HyperText Markup Language (HTML): Tag based language for formatting web page documents
Introduction Heading
First paragraph.
Browser (Client) Side
• Javascript: General-purpose programming language running in web browser
(see http://www.w3schools.com/js/)
• Allows processing/computation on client side;
• Example usages:
• Validating/processing user input locally, fast / dynamically modifying user interface in response to user input
• Reading / Updating HTML elements of the web page
• Document Object Model (DOM) – allows scripts to access individual HTML elements (including URL, cookies, click/keystroke events,…)
Example: Change paragraph (
) element
My First Page
document.getElementById(“demo”).innerHTML = “Hello World!”;
Browser output:
Server Side
• General purpose languages for implementing web application logic: • Generate dynamic page content
• Create, open, read, write, delete, and close files on the server
• Collect form data
• Send and receive cookies
• Add, delete, modify data in your database
• Restrict users to access some pages on your website • Encrypt data
• Server side programming languages: • PHP, ASP.NET, Java Platform,…
Server Side: Database Query Language
• Structured Query Language (SQL)
• Variants: Oracle, MS-SQL, MySQL
• SQL manages relational databases: • Database consists of tables
• Each table has a number of rows (database records) , e.g., a row per user
• Each row has a number of columns (data fields), e.g., “email address”, “name”, “age”,… • SQL language queries: read, update, add, or delete data
• E.g., SELECT email FROM users WHERE name = ‘alice’ -> returns email column value for rows in users table where the name column value = ‘alice’.
• Check http://www.w3schools.com/sql/ for SQL tutorials
General Goals of Web Security
• Safely browse the web: users should be able to visit a variety of web sites, without incurring harm
• No stolen information (without user’s permission)
• Site A cannot compromise session at Site B • Secure web applications
• Applications delivered over the web should have the same security properties we require for stand-alone applications
Web Security ‘History’
• The web is an example of “bolt-on security”
• Originally, the web was invented to allow physicists to share their research papers • Only textual web pages + links to other pages;
• No security model
• Then we added embedded images
• Crucial decision: a page can embed images loaded from another web server
• Then, audio/video, Javascript, dynamic HTML, AJAX, CSS, plug-ins, …
• Today, a web site is a distributed application
Goals of Web Security (Revisited)
• Safely browse the web: users should be able to visit a variety of web sites, without incurring harm • No stolen information (without user’s permission)
• Site A cannot compromise session at Site B
• Secure web applications
• Applications delivered over the web should have the same security properties we require for stand-alone applications
• https – http over SSL (Secure Socket Layer)
• provides encryption for the browser-server traffic
• prevents eavesdropping, and man-in-the-middle attacks (if certificate verification is done correctly)
• helps users ensure the authenticity of the server
• Does not prevent attacks on the client side (Cross-site scripting) or the server side (SQL Injection)
Significance of Web Security • Web applications are:
• often much more useful than desktop software => popular
• often publicly available
• easy target for attackers
• finding vulnerable sites, automating and scaling attacks • easy to develop, not so easy to develop well and securely
• often vulnerable, thus making the server, the database, internal network, data insecure
Threats in Web
• information disclosure (lost data confidentiality)
• e.g., business secrets, financial information, client database, medical data, government documents
• tampering (or lost data integrity)
• spoofing/ elevation of privilege (unauthorised access)
• functionality of the application abused
• denial of service
• loss of availability or functionality (and revenue)
• “foot in the door” (attacker inside the firewall)
• Web defacement
• lossofreputation(clients,shareholders)
• fear, uncertainty and doubt
Open Web Application Security Project
source: https://owasp.org/www-project-top-ten/
How browser renders a page
Running Remote Code is Risky • Integrity
• Compromise your machine • Install malware rootkit
• Transact on your accounts
• Confidentiality
• Read your information • Steal passwords
• Read your email
Isolation is Indispensable
Frame and iFrame
• Window may contain frames from different sources • Frame: rigid division as part of frameset
• iFrame: floating inline frame
• iFrame example
• Why use frames?
• Delegate screen area to content from another source • Browser provides isolation based on frames
Chrome Security Architecture
Browser Sandbox
• Run remote web applications safely
• Limited access to OS, network, and browser data
• Approach
• Isolate sites in different security contexts • Browser manages resources, like an OS
Comparison with OS
• Security of Web Cookies
• Web-based state using hidden fields and cookies • Session hijacking
• Session management
HTTP is Stateless
• The lifetime of an HTTP session is typically: • Client connects to the server
• Client issues a request
• Server responds
• Client issues a request for something in the response • …. repeat ….
• Client disconnects
• HTTP has no means of noting “oh this is the same client from that previous session” • How is it you don’t have to log in at every page load?
Maintaining State
• Web application maintains ephemeral state
• Server processing often produces intermediate results (Not ACID, long-lived state)
• Send such state to the client
• Client returns the state in subsequent responses • Two kinds of state: hidden fields and cookies
Case Study: Online Ordering
Case Study: Online Ordering
Case Study: Online Ordering
Case Study: Online Ordering
Solution: Capabilities
• Server maintains trusted state (while client maintains the rest) • Server stores intermediate state
• Send a capability to access that state to the client
• Client references the capability in subsequent responses
• Capabilities should be large, random numbers so that they are hard to guess
• To prevent illegal access to the state
Using Capabilities
Using Capabilities
• But: we don’t want to pass hidden fields around all the time!
• Tedious to add/maintain on all the different pages
• Have to start all over on a return visit (after closing browser window)
Statefulness with Cookies
• Server maintains trusted state
• Server indexes/denotes state with a cookie
• Sends cookie to the client, which stores it
• Client returns it with subsequent queries to that same server
HTTP Cookies
Cookies are Key-Value Pairs
• Set-Cookie:key=value; options; ….
• Store “us” under the key “edition” in browser • This value is no good as of Wed Feb 18… Request with Cookies Why Use Cookies? Why Use Cookies? Why Use Cookies? Cookies and Web Authentication Session Hijacking and Cookie Theft Stealing Session Cookies Countermeasure: Unpredictability Mitigating Hijack Non-defence Session Management Common Threats at Server Side Server-side Data SQL (Standard Query Language) • SQL Injection: Demo: SQL injection • “Login code” (PHP) Demo: SQL injection Demo: SQL injection Why does this work? SQL Injection Vulnerabilities • Bypassing simple SQLi filter countermeasures: Bypass Method: Injection into Numeric Data Bypass Method: Second-order SQL Injection Bypass Method: Second-order SQL Injection • Attack second phase: As a registered user, attacker performs a password lookup function Countermeasures Parameterised Queries Tips / Pitfalls in Parameterised Queries • Use parameterised queries for every database query Limitations of Parameterised Queries • Table and column names in a query cannot be parameterised Tips for Testing for SQLi Vulnerabilities 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com
• This value should only be readable by any domain ending in zdnet.com • This should be available to any resource within a subdirectory of /
• Send the cookie with any future requests to
Set cookies
Subsequent request
• Session identifier
• After a user has authenticated, subsequent actions provide a cookie • So the user does not have to authenticate each time
• Personalisation
• Let an anonymous user customise your site • Store font choice, etc., in the cookie
• Tracking users
• Advertisers want to know your behaviour
• Ideally build a profile across different websites
• Visit the , then see iPad ads on Amazon? • How can site B know what you did on site A?
• A shows you an ad from B and B scrapes the referrer URL
• Option 1: B maintains a DB, indexed by your IP address
• Option 2: B maintains a DB indexed by a cookie • Problem: IP address change
• “Third-party cookie”
• Commonly used by large ad networks
• An extremely common use of cookies is to track users who have already authenticated
• If the user already visited http://website.com/login.html?user=alice&pass=secret with
the correct password, then the server associates a “session cookie” with the logged-in user’s info
• Subsequent requests include the cookie in the request headers and/or as one of the fields:
http://website.com/doStuff.html?sid=81asf98as8eak
• The idea is to be able to say “I am talking to the same browser that authenticated Alice earlier.”
• Session cookies are, once again, capabilities
• The holder of a session cookie gives access to a site with the privileges of the user that established that session
• Thus, stealing a cookie may allow an attacker to impersonate a legitimate user
• Actions that will seem to be due to that user
• Permitting theft or corruption of sensitive data
• Compromise the server or user’s machine/browser, and predict it based on other information you know • Sniff the network
• DNS cache poisoning
• Trick the user into thinking you are Facebook • The user will send you the cookie
Network attacks
• Avoid theft by guessing; cookies should be
• Randomly chosen,
• Sufficiently long (Same goes with hidden field identifiers)
• Can also require separate, correlating information
• Only accept requests due to legitimate interactions with web site (e.g., from clicking links)
• Sad story: Twitter https://packetstormsecurity.com/files/119773/twitter-cookie.txt • Use one cookie (auth_token) to validate user
• Does not change from one login to the next
• Does not become invalid when the user logs out
• Thus: steal this cookie once, and you can log in as the user any time you want (until password change)!
• Defence: Time out session IDs and delete them once the session ends
• Address-based (non) defence: Store client IP address for session; if session changes to a different address, must be a session hijack, right?
• Problem, false positives: IP addresses change!
• Moving between WiFi network and 3G network • DHCP renegotiation
• Problem, false negatives: could be hijacked to different machine with same IP address
• Both requests via same NAT box
• generate new session ID on login (do not reuse old ones) • use cookies for storing session id
• set session timeout and provide logout possibility
• consider enabling “same IP” policy (not always possible) • user agent (browser version)
• require https (at least for the login / password transfer)
• Attacks on Server side:
• Attack setting: Attacker interacts as web app client with server web application
• Goal: Inject attacker code to modify web app behaviour on server • Common Vulnerability: SQL code injection
•SELECT Age FROM Users WHERE Name=‘Dee’;
•UPDATE Users SET WHERE Age=32; — this is a comment •INSERT INTO Users Values(‘Frank’, ‘M’, 57, …);
•DROP TABLE Users;
• Lack of user input validation vulnerability
• Allows attacker to directly inject SQL code into SQL database server • Often gives attacker complete control!
$result = mysql_query(“select * from Users! where(name=‘$user’ and password=‘$pass’);”);
• Suppose you successfully log in as $user if this returns any results
$result = mysql_query(“select * from Users where(name=‘$user’ and password=‘$pass’);”);
$result = mysql_query(“select * from Users
where(name=‘frank’ OR 1=1); — and password=‘whocares’);”);
$result = mysql_query(“select * from Users! where(name=‘$user’ and password=‘$pass’);”);
$result = mysql_query(“select * from Users! where(name=‘frank’ OR 1=1);DROP TABLE Users; –and
password=‘whocares’);”);
• Can chain together statements with semicolon:STATEMENT 1; STATEMENT 2
• Login verification checked by server by passing a command string to an SQL database interpreter
• Command string consists of a concatenation of SQL language commands and user input data
• Attacker’s password input string contains both data (guess) and command (‘ –), which is Line Comment
• Attacker’s command string passed to SQL interpreter and executed!
• Vulnerable due to invalid assumption by developer: assumed users will only enter alphabetic characters!
• In previous attacks, attacker needed to add ‘ character to terminate the data string and start entering commands
• What if the ’ character is escaped by the application? e.g., Application can replace any occurrence of ’ char by ’’
• SQL interprets ‘‘ in a data string as the data character ‘ rather than the string termination symbol (Our previous injection attack examples fail )
• Lots of variants of SQLi exploits
• Can often be used to bypass simple SQLi countermeasures, such as character escaping filters
• The application may also accept numeric user input data
• Numeric data can be passed directly to database without ‘ quotes, e.g. for vulnerable code like
$lQueryString = ” SELECT * FROM customers WHERE customerID=” . $customerID;
Attacker input: 1 OR 5=5 — (no need for quote symbol)
• ‘ character in user input string was escaped (replaced by ’’) by web application
• A second-order vulnerability for string inputs may still be exploitable:
• Consider app registering users in database and then retrieving
• Attack first phase: attacker registers escaped input into database
• Attacker registers into database user name such as: bob‘ OR 5=5 —
• Due to escaping of ‘ character, user name is processed and inserted into database
• No injected code execution in phase 1. But now the stored username string is bob‘ OR 5=5 — without escaping…
• Web app. retrieves user’s name from database into a variable $username: resulting value of $username is bob‘ OR 5=5 —
• Since username is retrieved from database and not from user input, no escaping is performed by application:
$lQueryString = ” SELECT password FROM accounts WHERE username=‘” . $username . “’”;
Executed query:
SELECT password FROM accounts WHERE username=‘bob‘ OR 5=5 –-
• Now injected code is executed in second phase – all passwords revealed!
• How to defend effectively against SQLi?
• Filtering (input validation): whitelist untrusted against a safe list
• Input escaping: escape untrusted input so it will not be treated as a command • Filtering / escaping is tricky / can often be bypassed
• Preferred robust solution: parameterised queries
• Prepared statements
• Fix root cause of injection problem: SQL database treating user data as code
• Idea: Application passes SQL statement to SQL server in two distinct phases:
• Phase 1 (pass code): Pass desired SQL statement with placeholders (? Symbol) for data values, e.g.
$stmt = $mysqli->prepare(“SELECT District FROM City WHERE Name=?”);
• Phase 2 (pass data): Pass the data values for placeholders, e.g.:
$stmt->bind_param(”bob”, $Name);
• Finally, execute and get result, e.g.:
$stmt->execute(); /* This executes the prepared statement $stmt */ $result = $stmt->get_result(); /* Get result into $result */ $stmt->close(); /* This completes the prepared statement */
• Any malicious user data passed in Phase 2 will be interpreted as data, not code.
• Don’t use it just for queries that directly process user input
• Remember the second-order SQLi attacks – malicious input can be stored and only later executed!
• Easy to misjudge which data is user-controllable: much safer to use it for all queries!
• Remember to parameterise every query data item
• Even a single concatenated parameter can be used for injection!
• If any chance of those names being user-controlled:
• Use a white list of acceptable values (e.g. list of known names in database)
• If not possible, use a strict validation restriction (e.g. allow only alphanumeric characters, reject any spaces, and limit length)
• Other parts of query code also cannot be parameterized
• E.g., SQL keywords like ASC (ascending) or DESC (descending), as in queries like
SELECT * FROM Customers ORDER BY Country DESC;
• Use whitelists of valid options (e.g., ASC or DESC)
• If reviewing code, look for SQL queries without prepare statements • If doing penetration testing, try:
• Entering single quote in a data input field
• If an error occurs (name=‘$user’ becomes name=‘’’), that is a good hint of a SQLi bug
• If entering two single quotes ’’ in a data input field eliminates error, confirms hint (escaping)
• Further test: try injecting code generating equivalent result (if interpreted as code), e.g., • Does input alice give the same output as ‘ ‘alice?
• Space allows string concatenation in MySQL
• Other databases have different syntax: e.g. ‘+‘alice for MS-SQL