* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download bh-usa-01-Andrews-SQL
Tandem Computers wikipedia , lookup
Database model wikipedia , lookup
Clusterpoint wikipedia , lookup
Microsoft Access wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Relational model wikipedia , lookup
Team Foundation Server wikipedia , lookup
Open Database Connectivity wikipedia , lookup
SQL Server 2000 Security From the Attacker’s Perspective Chip Andrews Black Hat Security Conference July 2001 5/22/2017 www.sqlsecurity.com 1 Presentation Outline • Section 1 – The Good – SQL Server Security Overview – Logins/Roles/Groups/Users/Applications – Net-libs/Encryption/Integrity • Section 2 – The Bad – Fingerprinting – Account Acquisition – Privilege Escalation • Section 3 – The Ugly – SQL-Injection – Input Validation – Best-Practices 5/22/2017 www.sqlsecurity.com 2 Presence • • • • Biztalk Server 2000 Commerce Server 2000 Application Center Server 2000 Third-Party Apps (MSDE) – – – – 5/22/2017 Tumbleweed Worldsecure Valadeo Technologies, Inc. O’Reilly & Associates, Inc. (WebBoard) Telemate.net www.sqlsecurity.com 3 Security Framework SQL Server 2000 Security Pathway Client Named Pipes Net-lib IP Sockets Net-lib Multi-Protocol Net-lib Other Net-lib sysxlogins table master database sysusers table database1 sp_myprocedure syspermissions 5/22/2017 sysusers table database2 mytable table syspermissions myview view syspermissions www.sqlsecurity.com 4 Net Libraries • By default, TCP/IP and Named Pipes are enabled – Super Sockets net-lib allows SSL over any other netlib when trusted certificate is installed on SQL Server – Multi-protocol (RPC) is not longer necessary since all net-libs now support encryption and multi-protocol does not support named instances (Microsoft code words for “soon to be retired”) – Other net-libs include Appletalk, NWLink IPX/SPX, and Banyan VINES, (shared memory and Virutal Interface Architecture SAN) 5/22/2017 www.sqlsecurity.com 5 SQL Server Service Context • MSSQLSERVER service configured at install-time • Tempting to use LocalSystem – Better choice • Local User Account with minimal rights including access (SQL Server install will take care of rights) • Domain User is also an option but only to be used in cases of replication or heterogeneous queries/ linked servers 5/22/2017 www.sqlsecurity.com 6 SQL Server Security Modes (cont.) • Mixed Mode – Both SQL Server and Windows Authentication Mode logins are allowed access – Lacks strong authentication controls such as password complexity, expiration, lockout, or history when using SQL Server logins – Provided for backwards compatibility and Windows 98/Me installations (Personal Edition) 5/22/2017 www.sqlsecurity.com 7 Good Idea – What’s the problem? • Microsoft recommends Windows Authentication Mode – The Problems • Microsoft can’t seem to take it own medicine (MSCS 2000, Biztalk 2000, and most reference applications require mixed mode) • Many developers avoid anything that involves having to learn a security model usually reserved for IT personnel as it burdens the deployment phase with “complexity” • Developers assume its someone else’s responsibility to protect their connection strings 5/22/2017 www.sqlsecurity.com 8 Mode Guidelines • Windows Security – SQL Server exposed to possible attackers (Intranet apps, client/server apps) – Heavy auditing requirements – Granular security requirements • Mixed Mode – SQL Server completely isolated and tunneled to client – Shared context acceptable or administrative overhead in supporting multiple security models is acceptable – Need for simple connectivity as cost of weak access control acceptable (why would either of these be 5/22/2017 acceptable?) www.sqlsecurity.com 9 SQL Server Logins – Kept in the sysxlogins table • SIDs of users or groups stored for Windows Authentication logins • 16-byte GUID generated for SQL Server native logins and stored in SID column SQL Server Users – Users are stored in individual databases in the sysusers table • Determines who has access to database objects • Can be assigned to fixed (db_owner, db_ddladmin, etc.) or user-defined database roles • User privileges can be managed using GRANT, DENY, and REVOKE 5/22/2017 www.sqlsecurity.com 10 SQL Server Roles • Used to group users for special tasks and for ease of administration – Fixed Server Roles • Sysadmin, serveradmin, securityadmin, etc. – Fixed Database Roles • Db_owner, db_accessadmin, db_securityadmin, etc. – User Database Roles (think “groups”) • Ease of administration – Application Roles (sp_setapprole) • Give users access to an application but not the SQL server itself 5/22/2017 www.sqlsecurity.com 11 C2 Level Auditing exec sp_configure ‘C2 Audit Mode’,1 go reconfigure go – Automatically creates a trace file called audit_YYYYMMDDHHMMSS_[seq].trc in directory \microsoft sql server\mssql\data – Trace files can easily be imported for thorough analysis 5/22/2017 www.sqlsecurity.com 12 Some Other SQL 2K Goodies • Features that affect security (good and bad) – – – – – – – 5/22/2017 Multiple instancing Variant Datatype CrytoAPI now used for all internal encryption Delegation now supported for SQL Server Updatable federated database servers User-defined functions Cascading referential integrity www.sqlsecurity.com 13 Section 1 Conclusion • Microsoft has made some great strides to improve the security of SQL Server – Some ideas for future releases • Come to grips with the fact that native SQL Security is weak and improve it rather than simply recommend integrated security • Do a better job of “leading by example” when it comes to recommending SQL Server security models • Consider displaying warnings before allowing administrators to use LocalSystem account for the MSSQLServer service since Certificates are not supported and the account is usually over-privileged 5/22/2017 www.sqlsecurity.com 14 Section 2 – The Bad • • • • Fingerprinting/Discovery Acquiring Access Privilege Escalation Potential Pitfalls – Custom DLLs – Application Requirements – Source Disclosure 5/22/2017 www.sqlsecurity.com 15 Target Acquisition • IIS Web Servers - a good bet SQL Server is driving it – telnet targetname 80 – HEAD / HTTP/1.0 – www.netcraft.com • Dig for hints about target database usage – Newsgroups • www.dejanews.com • SQL discussion boards (www.swynk.com) – Job Postings • Corporate website (click ‘careers’) • www.monster.com etc. • If all else fails - ask 5/22/2017 www.sqlsecurity.com 16 Newsgroups • The Good News: Most developers need help somewhere along the way and newsgroups are great for that • The Bad News: You may be announcing your architecture to potential attackers • http://groups.google.com – Advanced search • Containing : sql server yourcompany.com 5/22/2017 www.sqlsecurity.com 17 SQL Scanning • TCP port 1433 – SQL Server defaults to listen on these ports since ipsockets net-lib is installed by default (along with named pipes) • UDP port 1434 (requirement) – Thanks to multiple instancing, having to know the exact port is not needed to connect since the SQL client will be more than happy to auto-connect you to the instance through auto-discovery 5/22/2017 www.sqlsecurity.com 18 SQL Scanning Starting nmapNT V. 2.53 SP1 by [email protected] eEye Digital Security ( http://www.eEye.com ) based on nmap by [email protected] ( www.insecure.org/nmap/ ) Interesting ports on (10.6.6.205): (The 1507 ports scanned but not shown below are in state: closed) Port State Service 21/tcp open ftp 25/tcp open smtp 80/tcp open http 88/tcp open kerberos-sec 135/tcp open loc-srv 139/tcp open netbios-ssn 389/tcp open ldap 443/tcp open https 445/tcp open microsoft-ds 464/tcp open kpasswd5 593/tcp open http-rpc-epmap 636/tcp open ldapssl 1026/tcp open nterm 1080/tcp open socks 1433/tcp open ms-sql-s ------3389/tcp open msrdp 5/22/2017 www.sqlsecurity.com 19 SQL Server Discovery • Multiple instancing capabilities of SQL Server 2000 make enumeration a functional requirement • A specially formed UDP packet directed at port 1434 will cause the SQL 2K listener service to divulge information about every instance of SQL Server running on that machine – Packet Information • • • • 5/22/2017 Instance names Net-libs supported TCP ports and pipe names Clustering support (juicy targets) www.sqlsecurity.com 20 Broadcast Discovery • Since the listener may exist on multiple machines, it is possible to send a broadcast UDP packet to port 1434 to discover all instances of SQL Server 2000 on a subnet – Osql –L (will return a raw listing) but only of server names and only via broadcast to 255.255.255.255 – Capture returned packets – Analyze 5/22/2017 www.sqlsecurity.com 21 SQL Server Discovery The following is a sample response from a SQL Server to the UDP broadcast: (Captured using Snort-1.6.3 – http://www.snort.org) =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ [**] SQL Server Reply [**] 12/22-14:18:22.320099 10.6.7.37:1434 -> 10.6.6.194:4412 UDP TTL:128 TOS:0x0 ID:15054 Len: 133 .z.ServerName;DEV-REPORT2;InstanceName;MSSQLSERVER;IsClustered;N o;Version;8.00.194;tcp;1433;np;\\DEV-REPORT2\pipe\sql\query;; =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ 5/22/2017 www.sqlsecurity.com 22 SQLPing Utility http://www.sqlsecurity.com/utils/sqlping.zip • Directs a custom udp packet at a specific target or subnet and enumerates the server info across multiple instances Listening.... ServerName:LANDROVER InstanceName:SQL2K IsClustered:No Version:8.00.194 tcp:1241 np:\\LANDROVER\pipe\MSSQL$SQL2K\sql\query ServerName:LANDROVER InstanceName:MSSQLServer IsClustered:No Version:7.00.623 np:\\LANDROVER\pipe\sql\query tcp:1433 rpc:LANDROVER 5/22/2017 www.sqlsecurity.com 23 Account Acquisition • Brute Force (mixed security model) – Attacks the inherent weakness of the native SQL Server security model – Multiple freeware tools (sqldict, sqlpoke,sqlbf) – Mssqlserver lacks account lockouts or password complexity requirements – Do we even need to mention null ‘sa’ account passwords? 5/22/2017 www.sqlsecurity.com 24 Account Acquisition (cont.) • Sniffing (mixed or NT security mode) – L0phtcrack (to obtain NT account) – TCP 1433 traffic (non SSL) • Plaintext transmission of credentials • Passwords trivially obfuscated • Connection strings (mixed mode) – Client registry (regedit) – Imbedded in ASP source or client-side script (RDS) – Config files (global.asa, connect.inc, etc.) 5/22/2017 www.sqlsecurity.com 25 Source Code Disclosure • • • • • • • • • • • • 2001-06-21: Microsoft IIS Unicode .asp Source Code Disclosure Vulnerability 2001-06-18: MS Index Server and Indexing Service ISAPI Extension Buffer Overflow Vulnerability 2001-05-15: MS IIS/PWS Escaped Characters Decoding Command Execution Vulnerability 2001-05-11: Microsoft Index Server Buffer Overflow Vulnerability 2001-01-29: Microsoft IIS File Fragment Disclosure Vulnerability 2000-10-17: Microsoft IIS 4.0 / 5.0 Extended UNICODE Directory Traversal Vulnerability 2000-08-14: Microsoft IIS 5.0 "Translate: f" Source Disclosure Vulnerability 2000-07-17: Microsoft IIS 4.0/5.0 Source Fragment Disclosure Vulnerability 2000-05-11: Microsoft IIS 4.0/5.0 Malformed Filename Request Vulnerability 2000-03-31: MS Index Server '%20' ASP Source Disclosure Vulnerability 2000-11-06: Microsoft IIS Executable File Parsing Vulnerability 2000-02-09: NT IIS ASP VBScript Runtime Error Viewable Source Vulnerabilityy *Source: www.securityfocus.com 5/22/2017 www.sqlsecurity.com 26 Privilege Escalation • xp_cmdshell – Extended stored procedure that allows access to the operating system – SQL Server 2000 does not allow non-sysadmins to access xp_cmdshell – Administrators can assign a proxy account under which non-sysadmins can use xp_cmdshell – The real problem is that if an attacker can access SQL Server as a system administrator, they can execute operating system commands with the security context of the MSSQLServer service 5/22/2017 www.sqlsecurity.com 27 Privilege Escalation (cont.) • Other methods – – – – 5/22/2017 xp_regread/xp_regwrite Sp_OACreate Enumeration functions Openrowset – heterogeneous queries can allow attackers to brute-force their way into other systems www.sqlsecurity.com 28 Other Potential Pitfalls • System extended stored procedures have been found to have buffer overflow vulnerabilities http://www.atstake.com/research/advisories/2000/index.html#120100-2 – Some of these were executable by all users so lowprivilege SQL Server users instantly gained MSSQLServer service context – Custom DLLs can cause same issue – be careful when writing your own extended stored procs 5/22/2017 www.sqlsecurity.com 29 They’re in - Now What? • Create a backdoor SQL or NT account • Insert trojan extended stored procedures to capture passwords/data/events • Use tftp to pull in toolkits • Use this SQL Server to launch attacks against other hosts • Install proxy server to make this machine your patsy for other applications (netcat or other redirectors) • Take your data and make you suffer • Data diddling • As usual – possibilities are limited only by the imagination 5/22/2017 www.sqlsecurity.com 30 Your Defenses • Intrusion detection/Auditing – Create auto-start stored procedure to initiate a trace • sp_trace_create • sp_trace_setevent • sp_procoption ‘sp_mytrace', 'startup', 'true' – (SQL Profiler) Trace can be used to input records into audit log – (SQL Profiler) Trigger in audit log table alerts administrator to IDS signature match and can take other actions (stop server, close connection) – Completely isolate SQL Server. Only allow connectivity to specific hosts 5/22/2017 www.sqlsecurity.com 31 Section 2 Conclusion • Sensible configuration management will help secure SQL Server itself – Take the time to scan your networks and determine what people on the inside and the outside can access – Brute-force your own systems to be sure password complexity and account policies (if using Windows security) are sufficient 5/22/2017 www.sqlsecurity.com 32 Section 3 – The Ugly • • • • • SQL Code Injection Best Practices .NET Beta Functionality The Future “What can I do TODAY?” 5/22/2017 www.sqlsecurity.com 33 Scope of SQL Injection • Not specific to SQL Server – Oracle, MySQL, DB2, Sybase, etc. are also vulnerable • SQL injection attacks rarely alerts IDS systems especially over SSL (NIDS) • Difficult to track down all the areas of exploitation since the only real solution is manual code review • No amount OS security, firewalls, patch diligence will stop SQL injection. • The solution is good coding practices 5/22/2017 www.sqlsecurity.com 34 SQL Injection Sample • ASP Code (can you count the mistakes?) <% Set Conn = Server.CreateObject("ADODB.Connection") Conn.open “dsn=myapp;uid=sa;pwd=45nf3k332fhj“ Set RS = Conn.Execute("SELECT * from users where username=‘" & request.form(“username”) & “’ AND password=‘“ & request.form(“password”) & "’" ) %> 5/22/2017 www.sqlsecurity.com 35 SQL Injection Example 1 • Normal login Login Page UserName: bob Password: b2oQeDr! SQL Server sees • select * from users where username=‘bob’ and password=‘b2oQeDr!’ • All is well (or so it seems) 5/22/2017 www.sqlsecurity.com 36 SQL Injection Example 1 • Malicious Login Login Page UserName: bob Password: ‘ union select * from users where admin=1— SQL Server sees • select * from users where username=‘bob’ and password=‘’ union select * from users where admin=1 • In this case the user logs in as the site administrator 5/22/2017 www.sqlsecurity.com 37 SQL Injection Example 2 • Normal usage User Search Enter Last Name : andrews Results: Last First Andrews, chip email [email protected] – Notice that on a search page we get immediate feedback – good target for injection – Also, since we see three columns we can assume that’s all the SQL statement is selecting 5/22/2017 www.sqlsecurity.com 38 SQL Injection Example 2 • Malicious Usage User Search Enter Last Name : ‘ union select ’’,’’,@@version Results: Last X86) 5/22/2017 First email Microsoft SQL Server 2000 - 8.00.194 (Intel Aug 6 2000 00:57:48 Copyright (c) 1988-2000 Microsoft Corporation Standard Edition on Windows NT 5.0 (Build 2195: Service Pack 1) www.sqlsecurity.com 39 Live Demonstration • Casing An Application 5/22/2017 www.sqlsecurity.com 40 SQL Injection Samples • Problems – Poor input validation – Secret in ASP code (source code disclosure) – Poorly typed – SQL server and ASP not checking data-types – Security context too high for needed functionality 5/22/2017 www.sqlsecurity.com 41 SQL Injection - Tricks • Tricks attackers use – UNION statements to append data ripped from other SQL – “—” double hyphen comment indicator to block out the rest of the intended SQL – Try a single quote in input fields to see if the query fails (failure usually indicates bad input validation and possible exploitation) – exec master..xp_cmdshell ‘ping HACKER_IP’ to check for ‘sa’-level exploitable hosts – select name from sysobjects where type = ‘u’ can expose tables to exploit – Insert tablename exec sp_whatever – good way to see output of stored procedures – Use @@version to return SQL Server and OS versions and Service Packs 5/22/2017 www.sqlsecurity.com 42 SQL Injection – Variants • New sql_varaiant datatype – Usually, when UNION-ing select statements, the difficult part is matching data-types – With the sql_variant data-type it is possible to include any type other than text, ntext, image or timestamp Result: Attackers spend less time guessing about column order 5/22/2017 www.sqlsecurity.com 43 SQL Injection – Variants sql_variant sample: Before: – select job_lvl, fname from employee union select name,id from sysobjects where type=‘u’ Result: Syntax error converting the varchar value 'Paolo' to a column of data type int. After: – select job_lvl, fname from employee union select convert(sql_variant,name), convert(sql_variant,id) from sysobjects where type=‘u’ Result: authors 1977058079 discounts 245575913 dtproperties 645577338 employee 405576483 ….(and then some) 5/22/2017 www.sqlsecurity.com 44 Solutions: Input Validation • Scrub input data to make sure it contains only acceptable characters replace(inputstring,’,’’) Remove single quotes to help prevent quote-closing attacks Set myregex = new regexp myregex.global = True myregex.pattern = “\W+” cleaninput=myregex.replace Remove all characters except azA-Z0-9 Set myregex = new regexp myregex.global = True myregex.pattern = “\D+” cleaninput=myregex.replace Numbers only 5/22/2017 www.sqlsecurity.com 45 Input Validation (cont.) – Helps but not 100% effective – consider this: <% x = replace(inputstring,’,’’) rs = conn.execute “Select accesslevel from usertable where userID=“ & x %> • User inputs ‘0 union select accesslevel from usertable where uid like 1’ – The problem: » Input still not strongly typed – Solutions: » Manual datatype filtering (isnumeric) » SQL Stored Procedures 5/22/2017 www.sqlsecurity.com 46 Input Validation – Stored Procedures • Stored procedures can help enforce stronger typing but using them at every database access can be brutal due to the sheer number of procs that may need to be created – Since SQL Server has already compiled the query plan for the query, no further code injection is possible if we properly invoke the procedure Create procedure sp_login @username varchar(20), @password varchar(20) AS Select * from users where username = @username and password = @password 5/22/2017 www.sqlsecurity.com 47 SP Poorly Implemented • This sp uses string-building – Injection still possible <% Set Conn = Server.CreateObject("ADODB.Connection") Conn.open “dsn=myapp;Trusted_Connection=Yes“ Set RS = Conn.Execute(“exec sp_login ‘" & request.form(“username”) & “’,‘“ & request.form(“password”) & "’" ) %> 5/22/2017 www.sqlsecurity.com 48 Better Implementation of SP • Use Command object to explicitly identify parameters Dim cn As New ADODB.Connection Dim cmd As New ADODB.Command Dim rs As New ADODB.Recordset Dim param1 As Parameter, param2 as Parameter cn.Open “dsn=myapp;Trusted_Connection=yes" Set cmd.ActiveConnection = cn cmd.CommandText = “sp_login" cmd.CommandType = adCmdStoredProc Set param1 = cmd.CreateParameter(“username", adVarChar, adParamInput) cmd.Parameters.Append param1 Set param1 = cmd.CreateParameter(“password", adVarChar, adParamInput) cmd.Parameters.Append param2 Set rs = cmd.Execute • Expose stored procedures as methods of the connection object and let ADO do the work for you – Conn.sp_login request.form(“username”), request.form(“password”), rs 5/22/2017 www.sqlsecurity.com 49 Discipline • Make sure developers adhere to the standards – Develop a methodology • Command objects / stored procs / sp_executesql • No access to production servers (keep developers off production systems – period) • Consistent database access and developer education – – – – 5/22/2017 Encourage reusable security components Code review QA Test Plans Code with an intruder’s mindset www.sqlsecurity.com 50 Best Practices • Use principle of least-privilege • Assign MSSQLServer service non-administrator user context • Take the time to properly implement trusted security (Integrated Mode) • Don’t place passwords in script/code • Assign complex ‘sa’ password even when using Integrated security • Consider dropping certain procedures in the interest of security. They can always be added later. 5/22/2017 www.sqlsecurity.com 51 Best Practices (cont.) • Write re-usable input validation routines and make their use mandatory • Use stored procedures wherever possible but avoid “string building” for executing them • Code reviews are an absolute necessity • Evaluate third-party code and applications with great scrutiny • Use SSL (through use of net-libs) or IPSec to encrypt network traffic on suspect subnets (more applicable to client/server deployments but a powerful option) 5/22/2017 www.sqlsecurity.com 52 Best Practices – Minimize Risk • Assume your connection strings are compromised – Deny access to all tables – Use stored procedures and views to force access only through your own database constructs – Consider using asymmetric encryption on valuable data – Egress filtering – Never place administrative pages on same server with normal website code or administrative stored procedure in same database with normal procedures 5/22/2017 www.sqlsecurity.com 53 Best Practices - Integrity • SQL-DMO has method for database object to script entire database – Could easily be used to periodically generate script profiles and compare them to previous versions – Deltas could easily expose code changes and alert administrators – There are code examples with SQL server that demonstrate these methods (Microsoft SQL Server/80/tools/devtools/samples/sqldmo) 5/22/2017 www.sqlsecurity.com 54 Microsoft .NET • Web services – Most will probably front-end database operations – Prime target for automated attacks – SSL used to secure SOAP calls should foil intrusion detection systems – Make sure to perform diligent validation and authentication – UDDI raises interesting possibilities 5/22/2017 www.sqlsecurity.com 55 Microsoft .Net (cont.) • .NET Framework includes input validation, encryption, and session management functions – While this is a great time-saver for developers, if problems are found then instead of a single operation being affected, all applications designed using the framework are potentially vulnerable – You should find most SQL credentials in web.config file in the <appSettings> section • Even the .NET reference application Fitch and Mather stores SQL credentials here in plaintext • Make use of the <httpHandlers> section of web.config to restrict certain extensions (*.cs, *.config, *.asax, etc.) 5/22/2017 www.sqlsecurity.com 56 Reference Links • • • • • • • • • http://www.microsoft.com/sql/techinfo/security.htm http://www.mssqlserver.com http://www.sqlsecurity.com http://www.ntfaq.com http://www.wiretrip.net/rfp http://www.swnkp.com http://packetstorm.securify.com http://www.securityfocus.com http://www.sqlmag.com 5/22/2017 www.sqlsecurity.com 57 Recommended Reading • Howard, Levy, and Waymire. Designing Secure WebBased Applications for Microsoft Windows 2000. Microsoft Press, 2000. • McClure, Scambray, and Kurtz. Hacking Exposed: Second Edition. Osborne, 2001. • Rain Forest Puppy – Phrack Magazine Volume 8, Issue 54 Dec 25th, 1998, article 8 of 12. • David Litchfield. Remote Web Application Disassembly With ODBC Error Messages http://www.blackhat.com/presentations/win-usa01/Litchfield/BHWin01Litchfield.doc 5/22/2017 www.sqlsecurity.com 58