Upload
darlene-gilmore
View
221
Download
0
Tags:
Embed Size (px)
Citation preview
Database System Database System SecuritySecurity
UW-Stout Information and Cyber UW-Stout Information and Cyber Security WorkshopSecurity Workshop
8/24/20068/24/2006
Paul Wagner, [email protected] Wagner, [email protected]
BackgroundBackground
NeedNeed Security curriculum is relatively light in Security curriculum is relatively light in
database systems areadatabase systems areaFocus currently on protecting information through Focus currently on protecting information through network configuration, systems administration, network configuration, systems administration, application securityapplication security
Need to specifically consider database system Need to specifically consider database system security issuessecurity issues
Background (cont.)Background (cont.)
GoalsGoals Understand security issues in:Understand security issues in:
a general database system environmenta general database system environment
a specific DBMS (Oracle) environmenta specific DBMS (Oracle) environment Consider database security issues in context Consider database security issues in context
of general security principles and ideasof general security principles and ideas Consider issues relating to both database Consider issues relating to both database
storage and database system communication storage and database system communication with other applicationswith other applications
Main MessageMain Message
Database system security is more than securing Database system security is more than securing the databasethe database Secure databaseSecure database Secure DBMSSecure DBMS Secure applications / application developmentSecure applications / application development Secure operating system in relation to database Secure operating system in relation to database
systemsystem Secure web server in relation to database systemSecure web server in relation to database system Secure network environment in relation to database Secure network environment in relation to database
systemsystem
Secure databasesSecure databases
Database – a domain-specific collection of Database – a domain-specific collection of data; e.g. an Employee databasedata; e.g. an Employee databaseHistorical database security topics and Historical database security topics and issuesissues Users, PasswordsUsers, Passwords
Default users/passwordsDefault users/passwords Oracle: sys, system accounts – privileged (Oracle 8i and Oracle: sys, system accounts – privileged (Oracle 8i and
prior - with default passwords)prior - with default passwords) Oracle: scott account – well-known account and password, Oracle: scott account – well-known account and password,
part of public grouppart of public groupe.g. public can access all_users tablee.g. public can access all_users table
general password policies (length, domain, changing, general password policies (length, domain, changing, protection)protection)
Secure Databases (cont.)Secure Databases (cont.)
Privileges, Roles, Grant/RevokePrivileges, Roles, Grant/RevokePrivilegesPrivileges
System - actionsSystem - actions Objects – dataObjects – data
RolesRoles Collections of system privilegesCollections of system privileges
Grant / RevokeGrant / Revoke Giving (removing )privileges or roles to (from) usersGiving (removing )privileges or roles to (from) users
Secure DBMSSecure DBMS
Database Management System (DBMS) – the domain-Database Management System (DBMS) – the domain-independent set of software used to manage and access independent set of software used to manage and access your database(s)your database(s)Possible Holes in DBMSPossible Holes in DBMS
http://http://technet.oracle.com/deploy/security/alerts.htmtechnet.oracle.com/deploy/security/alerts.htm (50+ listed) (50+ listed) Majority of problems - buffer overflow problems in (legacy) DBMS Majority of problems - buffer overflow problems in (legacy) DBMS
codecode Miscellaneous attacks (Denial of Service, source code disclosure Miscellaneous attacks (Denial of Service, source code disclosure
of JSPs, others)of JSPs, others) Oracle example - UTL_FILE package in PL/SQLOracle example - UTL_FILE package in PL/SQL
allows read/write access to files in directory specified in utl_file_dir allows read/write access to files in directory specified in utl_file_dir parameter in init.oraparameter in init.orapossible access through symbolic linkspossible access through symbolic links
Secure DBMS (2)Secure DBMS (2)
Need for continual patching of DBMSNeed for continual patching of DBMS Encourage awareness of issues, continuous Encourage awareness of issues, continuous
vigilancevigilance Cost of not patchingCost of not patching
SQL Slammer Worm - ~100,000 systems affectedSQL Slammer Worm - ~100,000 systems affected
Secure DBMS (3)Secure DBMS (3)
US-CERT US-CERT advisoriesadvisories List of major List of major
software software packages packages currently currently watched watched includes includes OracleOracle
Secure Application Secure Application DevelopmentDevelopment
Access to Oracle Database or Access to Oracle Database or Environment Through ApplicationsEnvironment Through Applications
Need to consider security of applications Need to consider security of applications using database as well as security of data using database as well as security of data in database itselfin database itself
Example: SQL Injection AttackExample: SQL Injection Attack
SQL InjectionSQL Injection
SQL InjectionSQL Injection Definition – inserting malicious SQL code through an Definition – inserting malicious SQL code through an
application interfaceapplication interfaceOften through web application, but possible with any Often through web application, but possible with any interfaceinterface
Typical scenarioTypical scenarioThree-tier application (web interface, application, database)Three-tier application (web interface, application, database)
Overall application tracks own usernames and passwords in Overall application tracks own usernames and passwords in database (advantage: can manage users in real time)database (advantage: can manage users in real time)
Web interface accepts username and password, passes Web interface accepts username and password, passes these to application layer as parametersthese to application layer as parameters
SQL Injection (2)SQL Injection (2)
Example: Application Java code contains SQL Example: Application Java code contains SQL statement:statement:
String query = String query = "SELECT * FROM users_table " +"SELECT * FROM users_table " + " WHERE username = " + " ‘ " + username + " ‘ " +" WHERE username = " + " ‘ " + username + " ‘ " +" AND password = " + " ‘ " + password + " ‘ "" AND password = " + " ‘ " + password + " ‘ " ; ;
Note: String values must be single quoted in SQL, Note: String values must be single quoted in SQL, so application provides this for each passed so application provides this for each passed string parameterstring parameter
Expecting one row to be returned if success, no Expecting one row to be returned if success, no rows if failurerows if failure
Common variant – SELECT COUNT(*) FROM …Common variant – SELECT COUNT(*) FROM …
SQL Injection (3)SQL Injection (3) Attacker enters:Attacker enters:
any username (valid or invalid)any username (valid or invalid) password of: password of: Aa‘ OR ‘ ‘ = ‘ Aa‘ OR ‘ ‘ = ‘
Query becomes: Query becomes: SELECT * FROM users_table SELECT * FROM users_table WHERE username = ‘anyname‘ AND password WHERE username = ‘anyname‘ AND password = ‘Aa‘ OR ‘ ‘ = ‘ ‘; = ‘Aa‘ OR ‘ ‘ = ‘ ‘;
Note: WHERE clause => F and F or T => F or T Note: WHERE clause => F and F or T => F or T => T=> T
AND has higher precedence than ORAND has higher precedence than OR All user/pass rows returned to applicationAll user/pass rows returned to application If application checking for 0 vs. more than 0 If application checking for 0 vs. more than 0
rows, attacker is inrows, attacker is in
SQL Injection - PreventionSQL Injection - Prevention
What’s the problem here?What’s the problem here? Not checking and controlling input properlyNot checking and controlling input properly
Specifically, not controlling string inputSpecifically, not controlling string input Note: there are a variety of ways SQL Note: there are a variety of ways SQL
injection can happeninjection can happenRegular inclusion of SQL metacharacters throughRegular inclusion of SQL metacharacters through
Variable interpolationVariable interpolation String concatenation with variables and/or constantsString concatenation with variables and/or constants String format functions like sprintf()String format functions like sprintf() String templating with variable replacementString templating with variable replacement
Hex or Unicode encoded metacharactersHex or Unicode encoded metacharacters
SQL Injection Prevention (2)SQL Injection Prevention (2)
How to resolve this?How to resolve this? First (Attempted) Solution: Check ContentFirst (Attempted) Solution: Check Content
Client code checks to ensure certain content rules Client code checks to ensure certain content rules are metare metServer code checks content as wellServer code checks content as wellSpecifically – don’t allow apostrophes to be passedSpecifically – don’t allow apostrophes to be passedProblem: there are other characters that can cause Problem: there are other characters that can cause problemsproblems
---- // SQL comment character// SQL comment character ;; // SQL command separator// SQL command separator %% // SQL LIKE subclause wildcard // SQL LIKE subclause wildcard
charactercharacter
Which characters do you filter (blacklist) / keep Which characters do you filter (blacklist) / keep (whitelist)?(whitelist)?
SQL Injection – Variant 1SQL Injection – Variant 1
Any username, password: ‘ or 1=1--Any username, password: ‘ or 1=1-- Note: -- comments out rest of line, including Note: -- comments out rest of line, including
terminating single quote in applicationterminating single quote in application
Query becomes: Query becomes: SELECT * FROM SELECT * FROM users_table WHERE username = ‘anyname‘ users_table WHERE username = ‘anyname‘ AND password = ‘‘ OR 1=1--‘;AND password = ‘‘ OR 1=1--‘;
SQL Injection – Variant 2SQL Injection – Variant 2
Any username, password: foo’;DELETE FROM Any username, password: foo’;DELETE FROM users_table WHERE username LIKE ‘%users_table WHERE username LIKE ‘%
Query becomes: Query becomes: SELECT * FROM users_table SELECT * FROM users_table WHERE username = ‘anyname‘ AND password = WHERE username = ‘anyname‘ AND password = ‘foo‘; DELETE FROM users_table WHERE ‘foo‘; DELETE FROM users_table WHERE username LIKE ‘%’username LIKE ‘%’
Note: system executes two statementsNote: system executes two statements SELECT * FROM users_table WHERE username = SELECT * FROM users_table WHERE username =
‘anyname’ AND password = ‘foo’;‘anyname’ AND password = ‘foo’; // returns nothing// returns nothing DELETE FROM users_table WHERE username LIKE ‘%’DELETE FROM users_table WHERE username LIKE ‘%’
SQL Injection – Variant 3SQL Injection – Variant 3
ODBC allows shell injection using ‘|’ characterODBC allows shell injection using ‘|’ character ‘‘|shell(“cmd /c echo “ & char(124) & “format c:”)|’|shell(“cmd /c echo “ & char(124) & “format c:”)|’
Similar issue exists with MS SQL Server Similar issue exists with MS SQL Server Extended Stored ProceduresExtended Stored Procedures
SQL Injection – Variant 4SQL Injection – Variant 4
Second-Order SQL InjectionSecond-Order SQL Injection User creates account with user = root’--User creates account with user = root’-- Application escapes and inserts as root’’--Application escapes and inserts as root’’-- User resets passwordUser resets password Your query fetches username from database to Your query fetches username from database to
verify account exists with correct old passwordverify account exists with correct old password UPDATE users_table SET PASSWORD=‘pass’ UPDATE users_table SET PASSWORD=‘pass’
WHERE username = ‘root’--’WHERE username = ‘root’--’ NOTE: above scenario allows user to reset the NOTE: above scenario allows user to reset the
password on the real root accountpassword on the real root account
SQL Injection – Prevention (3)SQL Injection – Prevention (3)
Second (better) solutionSecond (better) solution Use Prepared StatementsUse Prepared Statements instead of regular Statements in instead of regular Statements in
your SQL codeyour SQL code Regular StatementsRegular Statements
SQL query is generated entirely at run-timeSQL query is generated entirely at run-timeCustom procedure and data are compiled and runCustom procedure and data are compiled and run
Compilation allows combination of procedure and data, allowing Compilation allows combination of procedure and data, allowing problems with SQL metacharactersproblems with SQL metacharacters
String sqlQuery = null;String sqlQuery = null;StatementStatement stmt = null;stmt = null;sqlQuery = "select * from users where " + sqlQuery = "select * from users where " +
"username = " + "'" + fe.getUsername() + "'" + " and " + "username = " + "'" + fe.getUsername() + "'" + " and " + "upassword = " + "'" + fe.getPassword() + "'";"upassword = " + "'" + fe.getPassword() + "'";
stmt = conn.createStatement();stmt = conn.createStatement();rset = stmt.executeQuery(sqlQuery);rset = stmt.executeQuery(sqlQuery);
SQL Injection – Prevention(4)SQL Injection – Prevention(4) Prepared StatementsPrepared Statements
SQL query is precompiled with placeholdersSQL query is precompiled with placeholdersData is added in at run-time, converted to correct type for the Data is added in at run-time, converted to correct type for the given fieldsgiven fields
String sqlQuery = null;String sqlQuery = null;PreparedStatementPreparedStatement pStmt = null; pStmt = null;
sqlQuery = "select * from users where username = sqlQuery = "select * from users where username = ? ? and upassword = and upassword = ??";";
pStmt = conn.prepareStatement(sqlQuery);pStmt = conn.prepareStatement(sqlQuery);pStmt.setString(1, fe.getUsername());pStmt.setString(1, fe.getUsername());pStmt.setString(2, fe.getPassword());pStmt.setString(2, fe.getPassword());rset = pStmt.executeQuery();rset = pStmt.executeQuery();
SQL Injection – Prevention (5)SQL Injection – Prevention (5)
Issues with PreparedStatementsIssues with PreparedStatements Cannot use them in all situationsCannot use them in all situations
Generally limited to replacing field values in Generally limited to replacing field values in SELECT, INSERT, UPDATE, DELETE statementsSELECT, INSERT, UPDATE, DELETE statements
E.g. our use for username field value, password field E.g. our use for username field value, password field valuevalue
Example: if also asking user for information that Example: if also asking user for information that determines choice of table name, cannot use a determines choice of table name, cannot use a prepared statementprepared statement
SQL Injection Prevention (6)SQL Injection Prevention (6)
Additional PrecautionsAdditional Precautions Do not access the database as a privileged userDo not access the database as a privileged user
Any user who gains access will have that user’s privilegesAny user who gains access will have that user’s privileges Limit database user to only what they need to doLimit database user to only what they need to do
e.g. reading information from database, no insert/update/deletee.g. reading information from database, no insert/update/delete Do not allow direct access to database from the internetDo not allow direct access to database from the internet
Require users to go through your applicationsRequire users to go through your applications Do not embed database account passwords in your codeDo not embed database account passwords in your code
Encrypt and store them in a repository that is read at application Encrypt and store them in a repository that is read at application startupstartup
Do not expose information in error messagesDo not expose information in error messagesE.g. do not display stack tracesE.g. do not display stack traces
Other Application IssuesOther Application Issues
Be aware of how information is transmitted Be aware of how information is transmitted between client applications and databasebetween client applications and databaseResearch Project at UWECResearch Project at UWEC Most common client applications (vendor-supplied or Most common client applications (vendor-supplied or
user-programmed) at least encrypt the connection user-programmed) at least encrypt the connection passwordpassword
Some clients encrypt the connection userSome clients encrypt the connection user Certain DBMSs have varying levels of security (e.g. Certain DBMSs have varying levels of security (e.g.
PostgreSQL)PostgreSQL) One DBMS transmits the connection password length One DBMS transmits the connection password length
(MS SQL Server 2005 Express)(MS SQL Server 2005 Express)
Secure Application Secure Application DevelopmentDevelopment
Application Security in the Enterprise Application Security in the Enterprise EnvironmentEnvironment J2EE – JDBC, Servlets, JSPs, JNDI, EJBs, …J2EE – JDBC, Servlets, JSPs, JNDI, EJBs, … .NET – many components.NET – many components
Use of Proxy ApplicationsUse of Proxy Applications Assume network filtering most evil trafficAssume network filtering most evil traffic Application can control fine-grain behavior, Application can control fine-grain behavior,
application protocol securityapplication protocol security
Secure Application Secure Application Development (cont.)Development (cont.)
Security Patterns (from J2EE Design Security Patterns (from J2EE Design Patterns Applied)Patterns Applied) Single-Access Point PatternSingle-Access Point Pattern
single point of entry into systemsingle point of entry into system Check Point PatternCheck Point Pattern
centralized enforcement of authentication and centralized enforcement of authentication and authorizationauthorization
Role PatternRole Patterndisassociation of users and privilegesdisassociation of users and privileges
Secure Operating SystemSecure Operating System
Interaction of Oracle and OSInteraction of Oracle and OS WindowsWindows
Secure administrative accountsSecure administrative accounts
Control registry accessControl registry access
Need good account policiesNeed good account policies
Others…Others…
Secure Operating System Secure Operating System (cont.)(cont.)
Linux/UnixLinux/UnixChoose different account names than standard Choose different account names than standard suggestionssuggestionsRestrict use of the account that owns Oracle Restrict use of the account that owns Oracle softwaresoftwareSecure temporary directorySecure temporary directorySome Oracle files are SUID (root)Some Oracle files are SUID (root)Command line SQL*Plus with user/pass Command line SQL*Plus with user/pass parameters appears under ps outputparameters appears under ps outputOthers…Others…
Secure Web ServerSecure Web Server
Interaction of Oracle and Web ServerInteraction of Oracle and Web ServerApache now provided within Oracle as its Apache now provided within Oracle as its application server, started by defaultapplication server, started by defaultApache issuesApache issues Standard configuration has some potential problemsStandard configuration has some potential problems
See Oracle Security Handbook for more discussionSee Oracle Security Handbook for more discussion Ensure secure communication from web clients to Ensure secure communication from web clients to
web serverweb server Use MaxClients to limit possible connectionsUse MaxClients to limit possible connections Others…Others…
Secure Web Server (cont.)Secure Web Server (cont.)
Internet Information Server (IIS) issuesInternet Information Server (IIS) issues Integration with other MS products (e.g. Integration with other MS products (e.g.
Exchange Server)Exchange Server) Many known vulnerabilities over recent Many known vulnerabilities over recent
versions (patches available)versions (patches available) Others…Others…
Secure NetworkSecure Network
Interaction of Oracle and NetworkInteraction of Oracle and Network Oracle Advanced Security (OAS) productOracle Advanced Security (OAS) product
Features for:Features for: AuthenticationAuthentication IntegrityIntegrity Encryption – use of SSLEncryption – use of SSL
Oracle server generally behind firewallOracle server generally behind firewallGood to separate DB and web serversGood to separate DB and web serversConnections normally initiated on port 1521, but then Connections normally initiated on port 1521, but then dynamically selecteddynamically selected
Other Network Issues To ConsiderOther Network Issues To ConsiderPossibility of hijacking a sys/sysmgr connectionPossibility of hijacking a sys/sysmgr connectionVarious sniffing and spoofing issuesVarious sniffing and spoofing issues
Miscellaneous IssuesMiscellaneous Issues
Newer Oracle Security FeaturesNewer Oracle Security Features Virtual Private Databases (VPDs)Virtual Private Databases (VPDs) Oracle Label SecurityOracle Label Security
AuditingAuditing Good policy: develop a comprehensive Good policy: develop a comprehensive
audit system for database activity trackingaudit system for database activity trackingCan write to OS as well as into database for Can write to OS as well as into database for additional security, accountability for all working additional security, accountability for all working with databaseswith databases
ExerciseExercise
Overall Security Examination of Oracle in Overall Security Examination of Oracle in Networked EnvironmentNetworked Environment 1) Database: Set up Oracle client, test known 1) Database: Set up Oracle client, test known
database for:database for:Privileged access through sys or system accountsPrivileged access through sys or system accountsPublic access through scott, other known/discovered Public access through scott, other known/discovered usernamesusernames
2) DBMS: Check for known vulnerabilities2) DBMS: Check for known vulnerabilitiesCheck overall system level, patch levelCheck overall system level, patch levelTest for specific problems from Oracle listTest for specific problems from Oracle list
3) Application:3) Application:Test for SQL Injection, other application weaknessesTest for SQL Injection, other application weaknesses
Exercise (cont.)Exercise (cont.)
Similar types of tasks for OS, Web Server, Similar types of tasks for OS, Web Server, Network componentsNetwork components
Task: develop report, including specifics for all Task: develop report, including specifics for all areasareas
ReferencesReferences
““Oracle Security Handbook” by Theriault and Oracle Security Handbook” by Theriault and Newman; Osborne/Oracle Press, 2001.Newman; Osborne/Oracle Press, 2001.““Oracle Database Administration: The Essential Oracle Database Administration: The Essential Reference”, Kreines and Laskey; O’Reilly, 1999.Reference”, Kreines and Laskey; O’Reilly, 1999.Pete Finnigan’s Oracle Security web site, Pete Finnigan’s Oracle Security web site, http://www.petefinnigan.com/orasec.htmhttp://www.petefinnigan.com/orasec.htm James Walden’s SIGCSE 2006 workshop on James Walden’s SIGCSE 2006 workshop on “Software Programming Security: Buffer Overflows “Software Programming Security: Buffer Overflows and Other Common Mistakes”and Other Common Mistakes”Eric Lobner, Matthew Giuliani, Paul Wagner; Eric Lobner, Matthew Giuliani, Paul Wagner; “Investigating Database Security in a Network “Investigating Database Security in a Network Environment”, paper published at MICS 2006, Environment”, paper published at MICS 2006, www.micsymposium.orgwww.micsymposium.org