security - amazon s3 · security security is hard. if it’s easy, then it’s wrong. 2 security...
TRANSCRIPT
Security
Security is hard. If it’s easy, then it’s wrong.
2
Security Considerations• Security is a Process
– It is NOT an event
– Hackers will never stop trying to break into your site; thus you can never stop trying to protect it
• Security should be designed on day one– Building an application and then trying to secure it is foolish
• Security should be similar for external and internal systems– Most breaches come from within
3
Security in APEX• Fortunately, APEX provides a number of different features
to enhance the security of your application
– Access Control• Authentication
• Authorization
– Tamper Proofing• Pages
• Items
• SQL Injection
• Cross Site Scripting
4
Settings
5
Instance Settings
6
Instance Settings• There are a number of settings at the APEX instance than
can be altered to ensure a more secure environment
– Only the APEX instance administrator can alter these settings
– They will only need to be changed once, and will apply to all applications in all workspaces
• Before getting into the specifics, we need to consider Runtime Mode
7
Runtime Only Mode
8
APEX Runtime Environment• An APEX runtime environment contains only the
components needed to run APEX applications
– There is NO web interface for either APEX Developers or APEX Administrators
– All preferences are managed with the APEX_INSTANCE_ADMIN API via SQL*Plus as the APEX schema or SYS/SYSTEM
– Applications can also be managed via SQL Developer
• Almost necessary if you’re deploying on the Internet
9
APEX Runtime Environment• If you elect to use an APEX runtime environment, you will
be able to ignore most instance parameters
– Specifically those that have to do with accessing either the APEX instance administration console or any workspace
10
APEX Runtime Environment• To Install APEX as a Runtime Environment:
– @apxrtins tablespace_apex tablespace_files tablespace_temp images
• Where:
– tablespace_apex is the name of the tablespace for the Oracle APEX schema
– tablespace_files is the name of the tablespace for the Oracle APEX files schema
– tablespace_temp is the name of the temporary tablespace
– images is the virtual directory for the Oracle APEX images
11
APEX Runtime Environment• To convert a normal APEX environment to a runtime
APEX environment:– Navigate to the APEX installation directory
– From there, run SQL*Plus and connect to the database where Oracle APEX is installed as the SYS user, specifying the SYSDBA role
• connect sys/oracle as sysdba
– Run the following script:
• apxdevrm.sql
12
APEX Runtime Environment• To convert a runtime APEX environment to a normal
APEX environment:
– Navigate to the APEX installation directory
– From there, run SQL*Plus and connect to the database where Oracle APEX is installed as the SYS user, specifying the SYSDBA role
• connect sys/oracle as sysdba
– Run the following scripts:
• apxdvins.sql • apxchpwd.sql
– This will reset the APEX Administrator password
13
Recommended Settings
14
APEX Administrators• Two types of APEX Administrators
– APEX Administrator• Manages the entire instance of APEX
– Workspace Administrator• Manages a specific APEX Workspace
– Manage Services
– Manage Users
– Monitor Activity
15
No Developers on the Prod Instance• Remove all APEX developer accounts from the Production
Instance
– Developers have no business logging into production
• Less Liability is a Good Thing
– Only Configuration Managers should have access with the explicit purpose of deploying or disabling an application
• In the case of an emergency, the APEX Administrator can create a temporary account for an APEX Developer
16
Disable Workspace Cookies• Disabling will prevent APEX from setting the last used
Workspace Name & User Name in its cookie
– Can manually remove this setting be removing the following cookie: ORACLE_PLATFORM_REMEMBER_UN
– May have multiple cookies if different URLs are used to access the same environment
• For instance: htmldb.oracle.com & apex.oracle.com
17
Disable Administrator Login• Disabling the Administrator Login will prevent any APEX
administrators from logging in to the APEX Administration Services
• WARNING! This will effectively lock you out of the APEX Administrator Services and should be used with caution
– You can still make some changes via the APEX_INSTANCE_ADMIN API & SQL*Plus
18
Disable Administrator Login• To re-enable Administrator Login access, run the following
SQL as the APEX_050100 or any user with the APEX_ADMINISTRATOR_ROLE role:
19
APEX_INSTANCE_ADMIN.SET_PARAMETER( p_parameter => 'DISABLE_ADMIN_LOGIN', p_value => 'Y' );
Disable Workspace Logins• Disabling Workspace Login will prohibit any user from
logging in to any APEX Workspace
– If this is set to Yes, you will need to use a different method when deploying applications:
• SQL*Plus as the parsing schema or APEX schema
• Oracle SQL Developer
• APEX Administrators can still login to the APEX Administration Services
20
Restrict Access by IP Addresses• Enter a comma-delimited list of IP Addresses that CAN
access the APEX Developer & Admin Services
• All other IP addresses will not be allowed to login to the APEX Development Services
– This does NOT apply to deployed APEX Applications
• Use the * as a wildcard, but only as the last character
– Correct:
• 128.230.*
– Incorrect:
• 128.230.*.10
21
Checksum Hash Function• Used to compute the checksum that’s provided when using
Session State Protection– Should be set to Most Secure– Will use the most secure function based on database version
22
Rejoin Sessions• Application level setting that can has to be enabled at the
instance level
– When enabled, applications can optionally use the session hash in the cookie and not care about the session ID in the URL
– Less secure, as there’s no second factor in play
– Useful for a system that sends out e-mails with APEX links
• Users will not have to login after clicking a link if they already have a valid session
23
Unhandled Errors• When set to Return HTTP 400, APEX will throw a
400 error (bad request) in the event of an unhandled exception
– Safer than potentially exposing the PL/SQL error message
– But much less friendly
• Best option:
– Create a centralized error handling function that handles anticipated and unanticipated exceptions
24
Run Only Mode for Applications• All applications should have their Status set to Run
Application Only– This will prevent any APEX workspace administrator or developer
from editing them
– Only an APEX Workspace Administrator or the APEX Administrator can change the Status back to Run and Build Application
25
Remove Unused Apps & Workspaces• Be sure to delete any Applications and Workspaces that are
no longer being used, as they make for an attractive target for hackers
• Reports to Use to help determine activity
– Monitor Activity > Page Views by Application
– Monitor Activity > Workspace Last Used– Monitor Activity > Page Views by Workspace
26
Monitor Login Attempts• Check the Login Attempts report often to spot
unusual activity– Frequent instances of Authentication Result = Incorrect
Password or Account Expired should cause concern
27
Set Provisioning Status to Manual• Manual Provisioning Status ensures that only the APEX
Administrator can provision new workspaces
– Users will not be able to request a workspace automatically
• Other Provisioning Options
– Request• Users can request a workspace that must be manually be approved by the APEX
Administrator
– Email Verification• User received an e-mail before the request is processed
28
Use Wallet for Secure Web Services• If using secure web services, an Oracle Wallet should be
configured and specified in order to secure the transaction with SSL
– Wallet Path• Enter the path to the wallet on the file system in the format file:<directory-path>
• Examples:
– file:c:\WINNT\Profiles\<username>\WALLETS
– file:/home/<username>/wallets
– Wallet Password• Enter the Password for the Wallet
29
Require HTTPS• Require HTTPS should be set to Enabled
– This is true for any and all environments
• DEV, TEST, QA, etc. - and especially PROD
30
Require Outbound HTTPS• Should also be Enabled, unless there are specific web
services that don’t support HTTPS– Then it’s up to developers to ensure that they use HTTPS when
possible, and ensure that sites that don’t make use of it do not supply sensitive data
31
Account Management
32
Enable Invalid Login Throttling• After each invalid login attempt, APEX can be set to wait
for x seconds
– By default, it’s 5, which is fine
• This will prevent a dictionary attack against any single account, as each try will add x seconds to the delay
• Method for Computing the Delay should be set to Username or Client IP Address, as it provides the most security
33
Require User Account Expiration & Locking
• Enabling this feature enforces the account locking & expiration policy across all APEX workspaces for APEX users only
– This cannot be overridden at the workspace level
• Disabling this feature will allow each workspace administrator to choose whether to enable it or not
• Select No to allow individual workspaces to enable or disable this feature independently.
34
Account Locking & Expiration Options• Maximum Login Failures Allowed
– If the maximum number is exceeded, then the account becomes locked
– Default is 4
• Account Password Lifetime (days)– Number of Days to use a specific password before requiring a new
one
– Default is 45
35
Enforce Workspace Password Policies• Even if you do not have any developers on your production
instance of APEX, it is still important to enforce strong passwords
• Minimum Password Length– If it is set to 0, then no minimum is enforced
• Minimum Password Differences– The minimum number of allowed differences between the old and
new password, character by character
– If it is set to 0, then the same password can be re-used
36
Enforce Workspace Password Policies• Must Contain At Least One:
– Alphabetic Character• As defined in the Alphabetic Characters region
– Numeric Character• 0 through 9
– Punctuation Character• As defined in the Punctuation Characters region
– Upper Case Character– Lower Case Character
37
Enforce Workspace Password Policies• Must Not Contain:
– Username• Regardless of Case
– Workspace Name• Regardless of Case
– Must Not Contain list
• Defaults to:
– oracle:hello:welcome:guest:user:database
38
Service Administrator Password Policy• Determines which Password Policy is applied to APEX
Administrator Accounts
– Workspace Password Policy– Uses the policy as defined
– Default Strong Password Policy• At least six characters
• At least one of each: alphabetic, uppercase alphabetic, digit, & punctuation
• Cannot include the user name
• Cannot include the word “Internal”
• Cannot contain words in the Must Not Contain region
39
Development Environment Credentials• In APEX 5.0+, APEX developers can be sourced from an
external repository, such as an LDAP server
– Recommended to use LDAP or another central user repository, so that multiple APEX credentials need to be create per user
– Also makes it easy to expire developer credentials, since once the LDAP account is terminated, so is the APEX access
40
Application Settings
41
Application Settings• There are a number of Application Settings that can
and should be changed to better secure your application from unauthorized access
– These can all be found at either of the following:
• Shared Components > Edit Definition
• Application Builder > Edit Application > Edit Application Properties
• You will likely have different options set for development vs. production– Critical to ensure that the proper settings are set before deploying
to production
42
Application Settings• Logging
– Useful for any instance, as this is what tells APEX to write to the APEX log tables
• Debugging– Should be disabled for Production
– Can be programmatically enabled when necessary regardless of the value of this setting
– Always enabled when running an application from the application development environment (4.2+)
43
Application Settings• Compatibility Mode
– New feature in APEX 4.2 that enables/disables certain behavior
– Pre-4.1
• Disables Browser Cache & Embed in Frames attributes
– 4.1
• “Standard” - imported applications will be set to this
– 4.2
• Computation & Process execution point changes for new layout options
44
Application Settings• Compatibility Mode
– 5.0
– #WORKSPACE_IMAGES# no longer works; needs to be changed to #APP_IMAGES#
– The API calls to wwv_flow_custom_auth_std.logout, wwv_flow_custom_auth_ std.logout_then_go_to_page, wwv_flow_custom_auth_std.logout_then_go_to_url, and apex_custom_auth.logout are desupported and will raise a runtime error instead of logging out from the Oracle Application Express session. Instead, use the apex_authentication.logout entry point.
– Page items based on a database column where the attribute Source Used is set to Only when current value in session state is null will raise an error when the page item gets rendered.
45
Application Settings• Compatibility Mode
– 5.1
– Buttons where Execute Validations is set to Yes also perform client-side validations and will not submit the page until all validations are cleared.
– Some buttons - typically Cancel or Previous- may have the Execute Validations flag set to Yes; you will either change that to No or use the new client-side validations.
46
Application Settings• Availability
– Allows a developer to turn on or off a single application without having to turn off the web server
– Availability Status• Available for production; any other for development
• Some statuses can also have a Message or Restricted User List
– Build Status• Run Application Only for production; Run and Build Application for
development
47
Application Settings• Error Handling
– With APEX 4.1+, you can specify an application-wide function to augment the reporting & presentation of errors generated in APEX
– Functions must be in this format:
– While not required, using a central error handling function is strongly recommended
48
function my_function_name ( p_error in apex_error.t_error ) return apex_error.t_error_result
Application Settings• Substitutions
– APEX can store up to 20 substitution strings & values at the application level
– Not recommended, since if any values need to change, you will have to redeploy the entire application
• Use these only as static variables that will not change.
– Better approach is to use Application Items & Computations and store the values in a table
• Changing a value is now a simple Update statement
49
Security Settings
50
Security Settings• Each application also has a number of settings specific to
security attributes– Unlike Application Settings, an application’s Security Settings rarely
need to be changed when moving an application into production
– These can all be found at: Shared Components > Security Attributes
51
Security Settings• Authentication
– Public User• Typically set to APEX_PUBLIC_USER; unlikely this needs to change
– Authentication Scheme• Which Authentication Scheme the application will use
– Deep Linking• Controls whether or not Deep Linking is enabled for the application
• Can also be configured at the page level
52
Security Settings• Authorization
– Authorization Scheme• Determines which Authorization Scheme a user must be a member of to access
the application
• If none required, should be set to Must Not Be Public User
– Run on Public Pages• Determines whether or not the application-level Authorization Scheme is run
on a Public Page
53
Security Settings• Database Schema
– Parsing Schema• Determines which schema an application will use to execute all SQL & PL/SQL
Commands
• Can only be set to schemas associated with a workspace
54
Security Settings• Session Timeout
– Determines the total duration of a session and the duration a session can be idle
– Times are in seconds
• Session State Protection– Controls whether or not Session State Protection is enabled in
your application
– Should be set to Enabled– Enabling it is not enough: each page & item will also have to be
properly configured for it to work
55
Security Settings• Browser Security
– Cache• Applications with sensitive data should set Cache to Disabled
– This will change the page header to direct the browser to not cache pages from this specific application
• HTTP server must support cache-control for this feature to work
– Embed in Frames• Unless you have a specific need, should be set to Deny
• HTTP server must support X-Frame-Options for this feature to work
56
Security Settings• Browser Security (cont)
– HTML Escaping Mode• Determines how APEX will escape characters when outputting data
• Basic
– &, ", < and >
• Extended
– &, ", <, >, ', / and non-ASCII characters if the character set of the database is not AL32UTF8
57
Security Settings• Rejoin Sessions
– As mentioned in Instance Settings, this option determines whether or not you can call an APEX URL without the Session ID
– Should be disabled unless there is a specific need
58
Security Settings• Database Session
– Initialization PL/SQL Code• Formerly called Virtual Private Database PL/SQL call to set
security context
• Called at the earliest possible point when rendering/processing pages
• Can be used for anything that needs to happen early
– Cleanup PL/SQL Code• Called at the latest possible point when rendering/processing pages
• Can be used for anything; close database links, unsettingcontexts, etc.
59
Security Settings• Runtime API Usage
– Determine if and which APEX APIs this application can call that can:
• Alter the application itself
• Alter other applications in the workspace
• Alter the workspace repository
– All three should be disabled unless there is a specific need
60
Authentication
61
Authentication• In APEX, Authentication is the event when the user
provides a set of credentials - typically a username & password - and they are verified or rejected by the corresponding Authentication Scheme– Result is a boolean
• From a technical point of view, it is irrelevant as to how APEX arrives at the result– Typically will be based on a valid username & password combination
– But could be something as simple as “guess my number”
62
Authentication Schemes• Out of the box, APEX can use the following
Authentication Schemes:
– APEX Users
– Database Users
– HTTP Header Variable
– LDAP
– Open Door
– Oracle Application Server Single Sign On
– None
• Additionally, a Custom scheme - which can interface with almost anything - can be developed
63
Unauthenticated User• When an unauthenticated user attempts to access any
restricted page of an APEX application, they will be redirected to the corresponding Session Not Valid location
– Unauthenticated Users can access Public Pages directly
64
URL for Any Restricted Page in App 100
Login PageRestricted Pages Public Page
URL for Any Public Page in App 100
DEMO: Access an app via restricted page; make page public
Login URL• The Login URL determines what page or URL an
unauthenticated user will end up on
– Typically set to the application UI’s corresponding Login Page– Can also be set to an external URL for SSO environments
• Used to be called Session Not Valid and be associated with the Authentication Scheme in previous versions of APEX
– Now found under User Interface > Desktop or Mobile
65DEMO: Change the Login URL property
Changed in
APEX 5 Invalid Credentials• All invalid authentication attempts are logged• APEX can be configured to wait X seconds before allowing
the next login attempt
– Instance-level setting, applied to all applications
• Some authentication schemes only allow X number of invalid attempts before locking the account
– Workspace-level setting
66DEMO: Show wait time; enter invalid password and lock out
Authenticated Session• Once authenticated, a unique Session ID is generated and
associated with the user & application combo– Programmatically referred to as APP_SESSION
• A session cookie will also be placed on the client
67
Login PageRestricted Pages Public Page
DEMO: Copy & Paste URL to different browser; view cookies
Session Duration• A user’s session will be valid until any one of the
following occurs:
– An explicit logout event occurs
• Clicking Logout or Quitting the Browser
– The user manipulates the URL and alters the Session ID portion
– Either a Session Duration or Session Idle Timeout is reached
– The ORACLE_APEX_PURGE_SESSIONS job runs
– The user alters or deletes the corresponding session cookie
– An APEX or Workspace administrator manually purges sessions
68DEMO: Logout & try to rejoin; change session ID; delete cookies
Session Rejoining• New in APEX 5.0, Session Rejoining allows a page or
application to accept URLs without the APEX Session ID
• A valid Session Cookie must be set for this to work
• Can be configured per page, per application or per instance
• Note: There is a potential security issue when enabling this feature• When enabled, it is possible for a malicious user to
potentially hijack your session
69
New in APEX 5
DEMO: Remove the Session from a URL and demonstrate re-joining a session
Session State• Any values that are saved to a user’s session state will be
automatically secured from all other sessions– Nothing to do to enable this - it’s default behavior
70DEMO: Edit a record and show the session for that user
Reports• Login Attempts
– Displays all login attempts w/results
• Administration > Monitor Activity > Login Attempts > Login Attempts
• Session State– Shows all active users & their session state
• Administration > Monitor Activity > Sessions > Active Sessions
71
Authorization
72
Authorization Schemes• In APEX, Authorization Schemes determine what an
Authenticated user can or can’t see/access/execute based on some predefined condition
– Result is boolean
• Source can be derived from:
– SQL Query
– PL/SQL Function
– Item Value Comparison
– Preference Value Comparison
73
Association• Authorization Schemes can be associated with every
APEX component - from the application itself to a page to a column in a report, and everything in between
• Best practice to create a “gatekeeper” scheme for each application
– This scheme is associated with the application itself and only allows authorized users to use it
74
Integration• There are APEX APIs available which allow easy integration
of external user-to-role mappings to an APEX Authorization Scheme
• LDAP
– APEX_LDAP.IS_MEMBER
• APEX Users
– APEX_UTIL.GET_GROUPS_USER_BELONGS_TO – APEX_AUTHORIZATION.IS_AUTHORIZED – APEX_AUTHORIZATION.RESET_CACHE
75
Changed in
APEX 5 Evaluation• Authorization Schemes can be evaluated two different ways:
– Per Session• Calculated once per session
– Per Page View• Calculated once per page view and use for all components on the page
– Per Component*• Calculated for each individual component on each page
– Always*• Calculate for everything
• Per Component & Always were added to enhance Authorization Scheme Plugins
76
Changed in
APEX 5
Reports• Batch Assign to Pages
– Allows quick & easy assignment of Authorization Schemes to all Pages
• Application > Utilities > Cross Page Utilities > Grid Edit of All Pages
• Authorization Scheme Utilization– Displays which components are associated with which
Authorization Schemes
• Shared Components > Authorization Schemes > Utilization
77
Best Practices• Start adding Authorization Schemes at the page level and
work up from there– Securing navigational controls - tabs, lists, buttons, etc. - is simply
not enough, as users can easily manipulate the URL to access any page
• Use a federated model that manages access across all applications & all workspaces vs. stove-piping on a per-app basis
• Consider a hybrid approach (LDAP authentication, table-based authorization) when it is not possible to easily change user-to-role mappings in LDAP
78
Data Access
79
Overview• Application Security can typically be divided into two
categories
– What functions we have access to
– What data we can see
80
What Functions We Have Access To• This one is simple - especially in the confines of APEX
– Authentication Scheme• Requires users to login to an application with valid credentials
– Authorization Scheme• Based on a pre-defined list, determines if a user can use an applications, see a
region, run a process, etc.
– Conditions• Are also often used to restrict what a user can see/do within an application
• Securing functions often maps to roles, which are often relatively static
– Thus, once created, little maintenance needs to be done
81
What Data Can We See• This one is a bit more complex
– Data changes all the time
– Regulations also change; what was non-sensitive yesterday may be sensitive today
– Security is often an after-thought and expensive/difficult
– Ignorance is bliss
• As developers, we often to a sub-optimal job at protecting data from users
– When in reality, this should be a top priority
82
Securing Data• Data should be properly secured at the lowest level
possible– Transparent to technology that accesses the data, as that will change
over time
• Oracle Forms > Oracle APEX > RESTful Web Service Calls
• The Oracle Database offers a number of features to do just this
– Secure Views
– Advanced Security Option
• Redaction
• Transparent Data Encryption
– Virtual Private Database
83
Secure Views
84
Secure Views• Economy-Class Solution
– Works in any edition of the database
– Just as secure as VPD & Redaction; harder to maintain
• Allows us to expose only the rows & columns of data from a table that we want to
– Most URL Tampering attempts will be fruitless, as only authorized data is displayed in the view
– Combined with a shadow schema, it’s easy to only expose a subset of rows & columns
– Build APEX forms & reports against the view
85
Application Context• Serves as a secure data cache for attribute-value pairs
needed for fine-grained access control (secure views or VPD)
– Cache eliminated the need to query the database to obtain this data, thus improving performance dramatically
• APEX provides a hook to set the Application Context on each page view
86
Incorporating Contexts Into Views• We can retro-fit any view to incorporate an Application
Context as part of their WHERE clause to filter which rows they return
– For example: limiting which rows are returned based on which department a user is in
• If instrumented properly, the view will work both with and without APEX
– Use NVL(v(‘APP_USER’),USERNAME) when evaluating the logged in user
– This will default to the connected schema if the query is not coming from APEX
87 88
Secure View
CREATE OR REPLACE VIEW employees_v AS SELECT employee_id, first_name, last_name, … FROM employees WHERE department_id = SYS_CONTEXT('ASO_CTX', ‘DEPARTMENT_ID') WITH READ ONLY;
Call to SYS_CONTEXT will return corresponding DEPARTMENT_ID for the
currently logged in user
Runtime WHERE Clause• Modify the Fetch Row process to include a Runtime
Where Clause– This will be automatically added to the SQL executed when
fetching a row
• Less robust of a solution vs. a view with a security context
– Have to apply this on every form vs. one time in the view
89
department_id = SYS_CONTEXT('ASO_CTX', 'DEPARTMENT_ID')
Call to SYS_CONTEXT will filter the process to bring back only records that
have the same DEPARTMENT_ID
Setting & Unsetting the Context in APEX• Application Attributes > Security Attributes >
Initialization PL/SQL Code and Cleanup PL/SQL Code
• Will run each time any page is rendered
– Sure, it’s overhead, but it’s necessary and relatively benign
90
91
SET_CTX ProcedureCREATE OR REPLACE PROCEDURE set_ctx ( p_email IN VARCHAR2 ) IS l_department_id NUMBER; BEGIN
-- Fetch the DEPARTMENT_ID based on the currently signed on APP_USER SELECT department_id INTO l_department_id FROM employees WHERE UPPER(email) = UPPER(p_email);
-- Set the Context dbms_session.set_context( namespace => 'ASO_CTX', attribute => ‘DEPARTMENT_ID', value => l_deptno);
END set_ctx; /
Sets the DEPARTMENT_ID attribute in the ASO_CTX system
context based on l_department_id
Get the corresponding DEPARTMENT_ID for the currently
signed on user
Virtual Private Database
92
Virtual Private Database• VPD dynamically manipulates the WHERE clause of all
queries against a specific table or view and applies a pre-determined condition
– Does so without any modification to application code
• Ideal way to protect data, as it works regardless of how the data is accessed
– SQL*Net, APEX, RESTful web services
• No-cost feature of Oracle Enterprise Edition Database
– Not supported in XE, SE One & SE
93
Virtual Private Database• For example:
– SELECT * FROM EMPLOYEES
• After the VPD function is applied, dynamically & automatically becomes:
– SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 10
94
Automatically added by theVPD Function
95
Unaltered Data
ID Name Department SSN
1 Scott 10 111-11-1111
2 Brian 10 222-22-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
96
Virtual Private Database
ID Name Department SSN
1 Scott 10 111-11-1111
2 Brian 10 222-22-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
Benefits of VPD• Secures data at the database layer
– Works regardless of the application or technology being used to access the table
– Can be used with APEX APP_USER value to secure data from both APEX & SQL*Plus
• nvl(v('APP_USER'),USER)
• Simplifies development– No sophisticated WHERE clauses need to be applied throughout
the application
• Makes things like URL Tampering irrelevant– Simple “No Data Found” messages will be returned
97
Other Features of VPD• Column Relevance
– Policy applied only when a specific column is part of the SELECT clause
• Column Filtering– Only data in a specific column that are allowed by the policy are
displayed; all other columns appear as NULLs
• Application Context– Set and use an Application Context for a more efficient VPD
solution
98
Implementing VPD• VPD rules are implemented through a policy function
– Must adhere to this signature: FUNCTION vpd_function ( p_schema IN VARCHAR2 DEFAULT NULL, p_object IN VARCHAR2 DEFAULT NULL )RETURN VARCHAR2
– Function should return the WHERE clause that will be applied
• Do not actually include the word “WHERE”
99 100
VPD Policy FunctionFUNCTION limit_by_deptno ( p_schema IN VARCHAR2 DEFAULT NULL, p_objname IN VARCHAR2 DEFAULT NULL ) RETURN VARCHAR2 AS l_sql VARCHAR2(255); BEGIN
-- Set the SQL to compare DEPTNO to the application context l_sql := 'department_id = SYS_CONTEXT(''ASO_CTX'',''DEPARTMENT_ID'')';
-- Return the SQL RETURN l_sql;
END limit_by_deptno;DEPARTMENT_ID is set via SYS_CONTEXT so
it can be used outside of APEX
Setting SYS_CONTEXT • Shared Components > Security > Initialization PL/SQL
Code
101
FOR x IN ( SELECT * FROM hr.employees_dir WHERE UPPER(email) = UPPER(p_user) ) LOOP -- Set a Context Value for the users DEPARTMENT_ID dbms_session.set_context ( namespace => 'ASO_CTX', attribute => 'DEPARTMENT_ID', value => x.department_id ); END LOOP;
DBMS_RLS Package• VPD Policies are managed with the DBMS_RLS package
– ADD_POLICY– DROP_POLICY– REFRESH_POLICY– ENABLE_POLICY
• Best Practice:
– You can put the VPD policies in a separate schema so that it is isolated from your developers, if data security is a major concern
102
103
DBMS_RLS.ADD_POLICY
BEGIN DBMS_RLS.add_policy (object_schema => 'HR', object_name => 'EMPLOYEES', policy_name => 'DEPARTMENT_VPD', function_schema => 'ASO_ADMIN', policy_function => 'LIMIT_BY_DEPTNO', statement_types => 'SELECT'); END; /
104
DBMS_RLS.DROP_POLICY
BEGIN DBMS_RLS.drop_policy (object_schema => 'HR', object_name => 'EMPLOYEES', policy_name => 'DEPTNO_VPD'); END; /
OLS
105
Oracle Label Security• For-cost option for Oracle Database EE
• Allows each row to be classified– Only users with the corresponding clearance can see those rows
• Helps enforce regulatory compliance– Ability to implement “need to know” access
• Integration with Oracle Database Vault & Oracle Identity Management
106
107
Oracle Label Security
Name Salary Data Label
SMITH 1000 Highly Sensitive ✘
JONES 1500 Sensitive ✔
KING 1250 Confidential ✔
User Label: SENSITIVE
SELECT * FROM EMP Redaction
108
Redaction• Oracle Data Redaction is a feature introduced in Oracle
Database 12c– Also back-ported to 11.2.0.4
• Included as part of Advanced Security Option or ASO
– List price is $15,000 per processor + support*
• Hides or “redacts” data automatically from user queries without any application modifications
– For example - 123-45-6789 becomes XX-XXX-6789
• Source data remains unchanged
109
* as of 29-DEC-2015
Redaction Use Case• Redaction fits best where users need to see any record,
but not all sensitive information– Call centers, hotels, airlines, etc.
• Part of the sensitive data can be used to help authenticate the user
– “Last 4 digits of your Credit Card/SSN”
• There should be no way for the user to see the entire value of sensitive data
– Thus reducing the likelihood of internal data theft
110
111
Unaltered Data
ID Name Department SSN
1 Scott 10 111-11-1111
2 Brian 10 222-22-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
112
Redaction
ID Name Department SSN
1 Scott 10 XXX-XX-1111
2 Brian 10 XXX-XX-2222
3 Jack 20 XXX-XX-3333
4 Anita 30 XXX-XX-4444
Redaction Types• Full
– Redacts entire value and replaces with a space for VARCHARs, “0” for NUMBERs or “1-JAN-2001” for DATEs
• Partial– Redacts part of a value with a placeholder and displays a portion of
the actual data
• Regular Expression– Uses a Regular Expression to filter data
• Random– Replaces characters with random equivalents
113
Redaction Management• Management of Redaction Policies requires EXECUTE on
DBMS_REDACT package
– End users or parse-as users need no such grant
• Can configure via Oracle Enterprise Manager (in 12c) or via command line
114
Redaction Management• Redaction policy data is accessible via two views:
– REDACTION_POLICIES • Contains the object, policy name and expression
– REDACTION_COLUMNS • Contains which columns are redacted, what type is used and all supporting
informations
• Link back to REDACTION_POLICIES with OBJECT_OWNER and OBJECT_NAME concatenated key
• Explicit access to the views must be granted
• Can create a redaction “surrogate” user that will manage policies and own policy functions
115
ADD_POLICY• Can not only create a policy, but also create a policy and
add a column and its attributes in one call
116
OBJECT_SCHEMA VARCHAR2 IN OBJECT_NAME VARCHAR2 IN POLICY_NAME VARCHAR2 IN POLICY_DESCRIPTION VARCHAR2 IN COLUMN_NAME VARCHAR2 IN COLUMN_DESCRIPTION VARCHAR2 IN FUNCTION_TYPE BINARY_INTEGER IN FUNCTION_PARAMETERS VARCHAR2 IN EXPRESSION VARCHAR2 IN ENABLE PL/SQL BOOLEAN IN REGEXP_PATTERN VARCHAR2 IN REGEXP_REPLACE_STRING VARCHAR2 IN REGEXP_POSITION BINARY_INTEGER IN REGEXP_OCCURRENCE BINARY_INTEGER IN REGEXP_MATCH_PARAMETER VARCHAR2 IN
ALTER_POLICY• Alter policy attributes or add/remove additional columns
to/from an existing policy
117
OBJECT_SCHEMA VARCHAR2 IN OBJECT_NAME VARCHAR2 IN POLICY_NAME VARCHAR2 IN ACTION BINARY_INTEGER IN COLUMN_NAME VARCHAR2 IN FUNCTION_TYPE BINARY_INTEGER IN FUNCTION_PARAMETERS VARCHAR2 IN EXPRESSION VARCHAR2 IN REGEXP_PATTERN VARCHAR2 IN REGEXP_REPLACE_STRING VARCHAR2 IN REGEXP_POSITION BINARY_INTEGER IN REGEXP_OCCURRENCE BINARY_INTEGER IN REGEXP_MATCH_PARAMETER VARCHAR2 IN POLICY_DESCRIPTION VARCHAR2 IN COLUMN_DESCRIPTION VARCHAR2 IN
ENABLE_, DISABLE_ & DROP_POLICY• Enables, Disables or Drops an existing Redaction Policy
– Same parameters for all three
118
OBJECT_SCHEMA VARCHAR2 IN OBJECT_NAME VARCHAR2 IN POLICY_NAME VARCHAR2 IN
UPDATE_FULL_REDACTION_VALUES• Changes the default values used for Full Redaction
– Requires a restart of the database
119
NUMBER_VAL NUMBER(0 BYTE) IN BINFLOAT_VAL BINARY_FLOAT IN BINDOUBLE_VAL BINARY_DOUBLE IN CHAR_VAL CHAR IN VARCHAR_VAL VARCHAR2 IN NCHAR_VAL NCHAR IN NVARCHAR_VAL NVARCHAR2 IN DATE_VAL DATE IN TS_VAL TIMESTAMP IN TSWTZ_VAL TIMESTAMP WITH TIME ZONE IN
Redaction vs. Data Masking• Oracle Data Masking & Subsetting is a for-cost
feature for Oracle Enterprise Edition– List price is $11,500 per processor + support*
• Designed to change actual values of data from a production data set when it’s moved downstream to Dev/QA
– Maintains the “shape” of the data
– Updates it with random values
– For example
• “Scott” becomes “Rfsgo”
• 012-34-5678 becomes 361-72-8427
120
* as of 29-DEC-2015
Redaction Warning• Redaction is only applied to data as it is displayed
– Not applied in the WHERE clause of a query
• Thus, use it only where there user will not have control over the WHERE clause
• Precautions to take in APEX
– When using an IR & Redaction, disable options to filter the report for the redacted column(s)
– Code change may be needed to exclude redacted column from WHERE clause of Classic Reports or other regions that the user can filter via input
121
Transparent Data Encryption
122
Transparent Data Encryption• Transparent Data Encryption is a part of the
Advanced Security Option that allows you to secure data at the datafile level
– By Tablespace
– By Column
• Included as part of Advanced Security Option or ASO
– List price is $15,000 per processor + support*
123
* as of 29-DEC-2015
Transparent Data Encryption• TDE encrypts data at the data file level
– Key stored outside of the database itself in Oracle Wallet or Oracle Key Vault
• Prevents unauthorized users from reading any data that is encrypted without the key
• Example:
– Hacker gains access to database files or physical disk that contains database file and tries to access them on another machine
– Any data that was encrypted with TDE will be unreadable
124
125
Unaltered Data
ID Name Department SSN
1 Scott 10 111-11-1111
2 Brian 10 222-22-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
126
TDE: Column Level
ID Name Department SSN
1 Scott 10 XXX-XX-1111
2 Brian 10 XXX-XX-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
D4g-12-
E%f
R52-C$er)(ue2
0(LJHLKjn453
127
TDE: Tablespace Level
ID Name Department SSN
1 Scott 10 XXX-XX-1111
2 Brian 10 XXX-XX-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
D4g-12-
E%f
R52-C$er)(ue2
0(LJHLKjn453
NNWLv3423
&&Hh2146dsa
Vsb12i2e!
**7cxnAOSr
4wef ;r23;
2r4vdls
xwqdzLR#Q
345vcaÔ2D
rm2o3fwd
J4lk2)(
nMSR$r2
t34ml345
Transparent Data Encryption• No triggers need to be created and existing applications do
not need any modifications
– That’s the “T” in Transparent Data Encryption
• Useful for protecting sensitive data
– Credit Card Numbers, SSNs, Account Numbers
• Will not work on columns used as FK constraints
– Also a few other scenarios; see Database Advanced Security Administrator's Guide for specifics
• Once implemented, data will be shown un-obfuscated in your applications
128
129
TDE In Action
Oracle Wallet
Master Encryption Key
Oracle Database
ID Name Sal
1 Scott 200
2 Brian 150
3 Jack 300
$j4
Jd9
#d6
Column Encryption
Tablespace Encryption
Steps to Implement TDE• Create an Oracle Wallet
• Modify sqlnet.ora and add parameter that identifies the Encryption Wallet
• Open the Wallet
– Needs to be done each time the database is restarted
• Set Master Encryption Key
– Only needs to be done once
• Create an encrypted tablespace, column or modify existing columns
130
Create an Oracle Wallet• Easiest to do with Oracle Wallet Manager
– But can also be done with the command line
• Best to keep this wallet separate from wallets used for other purposes like outbound SSH traffic
– Save in different directory should be good enough
• Absolutely critical to backup the wallet file, as once the Master Encryption Key is installed, if you lose or delete the wallet file, you’re done
131
Modify sqlnet.ora• Add the following to the sqlnet.ora file, using the
directory where the wallet was created
132
ENCRYPTION_WALLET_LOCATION = ( SOURCE = ( METHOD = FILE ) ( METHOD_DATA = ( DIRECTORY = /u01/app/oracle/product/11.2.0/db_1/owm/wallets/oracle ) ) )
Open the Wallet• Each time the database is restarted, the encryption wallet
must be opened
– You’ll get a fairly concise warning if it is not
• Done so with the following command as SYS or SYSTEM:
– ALTER SYSTEM SET ENCRYPTION WALLET OPEN IDENTIFIED BY "<PASSWORD>"
– Use the password specified when creating the wallet enclosed in double-quotes
– Can also be opened from OEM
133
Set Master Encryption Key• This will generate a random master encryption key that will
be used by Transparent Data Encryption
• Key will be stored in the Encryption Wallet as defined in sqlnet.ora in the previous step
• Only needs to be done one time per instance ever– ALTER SYSTEM SET ENCRYPTION KEY IDENTIFIED BY "<PASSWORD>"
– Use the password specified when creating the wallet enclosed in double-quotes
134
Master Encryption Key in Oracle Wallet• You can verify that the Master Encryption Key was created
by opening the Encryption Wallet
– There should be an entry called Secret Store
135
Encrypted Tablespace• To create an encrypted tablespace:
– Can pass values for other encryption algorithms to the USING clause
136
CREATE TABLESPACE DEMO DATAFILE '/u01/app/oracle/oradata/sumner/demo2.dbf' SIZE 1M LOGGING EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO DEFAULT STORAGE (ENCRYPT) ENCRYPTION USING 'AES256' /
Encrypted Tablespace in APEX• APEX can be set to create encrypted tablespaces via
TDE by default
– Instance Admin > Manage Instance > Instance Settings
– Set Encrypted Tablespaces to Yes
• Must have a valid ASO license
137
Create or Alter Encrypted Columns• Run a simple SQL command to encrypt/decrypt existing
columns
– ALTER TABLE EMPLOYEES MODIFY (SALARY ENCRYPT) – ALTER TABLE EMPLOYEES MODIFY (SALARY DECRYPT)
• New tables can be created with columns already encrypted
– CREATE TABLE FOO (ID NUMBER, SAL NUMBER ENCRYPT)
• See the documentation for additional encryption options such as available algorithms
138
TDE Warning• When changing columns with existing date to encrypted,
the data will likely still be readable in the data files until it is overwritten by the database
– There is no way to tell when or if this will happen
• Thus, if that is a concern - and it should be - consider creating a new tablespace on a new data file and migrating the table there
– Drop the old tablespace with INCLUDING CONTENTS KEEP DATAFILES option and delete the original datafile via a secure method
139
HTTPS
140
HTTPS• Also referred to as SSL (Secure Socket Layer)
• Encrypts all traffic between your web browser & the web listener
141
Web Browser Web Server & Oracle Database
w/APEX
APEX HTTPS Options• Instance Level
– Secures your APEX development environment– Not always necessary for development
– Necessary if you allow developers to log in to prod, as data queried in SQL Workshop needs to also be encrypted
• Three parameters to be concerned with:
– Require HTTPS– Require Outbound HTTPS
– HTTP Response Headers
142
APEX HTTPS Options• Application Level
– Authentication Scheme > Cookie Attributes• Should be called “Require HTTPS for This Application”
– When set to Yes, APEX will not set session cookie if the application is run over HTTP
• Thus no one will be able to login to your application
143
Packet Peeper• Open source packet capture utility for the Mac
– Plenty of similar utilities available on Windows & Linux
• Allows anyone on the network to “listen” to anyone else on the network
– Anyone can run & download
• Thus, anyone can easily compromise HTTP packets
144
145
Packet Peeper Results
146
Packet Capture Without SSL
p_t01=internal...&p_t02=ADMIN...&p_t03=oracle
Workspace Username Password
147
Packet Capture With SSL
148
Packet Capture With SSL
Shadow Schema
149
Shadow Schema• All secure APEX applications should parse as a limited
or no privilege schema– Can’t use SQL Injection to run DML and/or DDL if the schema can
not execute DML and/or DDL
• This schema should contain only two types of objects:
– Read-Only Views
– Synonyms to call APIs (packages)
150
151
Shadow Schema
• Views • EMP_V
• Synonyms • EMP_API • SET_CTX
• Views • EMP_V
• Procedures • EMP_API • SET_CTX
• Tables • EMP
SHADOW DATA
APE
X “P
arse
As”
Sch
ema
GRANT SELECT ON
GRANT EXECUTE ON
GRANT EXECUTE ON
Shadow Schema Workspace• Create a new workspace
– As part of this process, also create the SHADOW schema
• Thus, all applications in this workspace will parse as the SHADOW schema
– All secure applications will live in this workspace
152
Typical APEX System & Role Privileges• A schema created by
APEX’s wizards will contain the following system privileges
• You should remove ALL system privileges from the SHADOW schema
– APEX 3.2 will create schemas w/the CONNECT role; APEX 4.0+ will not
153
White Listing• Removing all system & role privileges allows us to
mitigate a range of SQL Injection attacks– If the schema has no privileges, then a hacker can not maliciously
create or modify objects
• We can selectively add views & APIs and strictly control what this schema will have the ability to see & do vs. trying to restrict this schema to only with with a subset of a larger set of objects
154
Preventing Dropped Objects• Despite removing these privileges, a schema will still have
the ability to drop its own objects
– Not catastrophic in our case, since they will only be dropping views & synonyms to APIs
– But still something we need to prevent
• Thus, we can add a system-level trigger to prevent objects from being dropped by the SHADOW schema
155 156
System Level Trigger
CREATE OR REPLACE TRIGGER prevent_shadow_drop BEFORE DROP ON DATABASE BEGIN IF ORA_DICT_OBJ_OWNER = 'SHADOW' AND ORA_LOGIN_USER NOT IN ('SYS','SYSTEM','SURROGATE') THEN RAISE_APPLICATION_ERROR(-20000, ORA_DICT_OBJ_OWNER || ' can not drop ' || ORA_DICT_OBJ_TYPE || 'S.'); END IF; END; /
Allows only SYS, SYSTEM & SURROGATE schemas to drop objects owned by SHADOW
Data Schema• All tables, views, packages & other database objects will
reside in the DATA schema
– No APEX application will ever parse as this schema
– All of our tables, data & PL/SQL code will go here
• For this presentation, we’ll stick with the standard EMP & DEPT Oracle demonstration tables
157
Providing Access to Data• The shadow schema will need to see at least some data
from the data schema
• Best to grant SELECT on a VIEW vs. the entire table
– Give us the ability to restrict which columns & rows are exposed to the shadow schema
158
Creating a Shadow View• First, we’ll create EMP_V in the DATA schema
– It will only reference EMPNO, ENAME, JOB & DEPTNO– We’ll grant SELECT on DATA.EMP_V to SHADOW
• Then, we’ll create EMP_V in the SHADOW schema
– Which will reference all rows & all columns of DATA.EMP_V
• Last, we’ll build a form & report in our application
159
Running Our Application• When we run our application, we should see all rows of the
EMP table
– But only the specified four columns as per the secure view definition
• We can click edit/create/delete
– But it will fail when we attempt to save the changes with ORA-01031: insufficient privileges, since we do not have access to update the view
160
Facilitating DML Transactions• Since our views are read-only, we can not use the build
in APEX Row Processing processes
– We must create our own APIs with PL/SQL
– In our APIs, we can run additional security checks or auditing transactions, should we want to
– We can also limit which DML transactions we support, based on business rules
161
Automating API Generation• Little known feature of the Object Browser:
– Create Package with Methods on Database Tables
• Creates a packages based on a list of tables that will provide insert, update & delete APIs
– With support for lost update detection
162
Automating API Generation• In order to do this, you will need to create an APEX
workspace on the DATA schema
– This will be used only to create the APIs
– No applications will be developed here
• Then, create the table APIs for the EMP table
– You can modify the APIs to restrict what they can & can’t do
– Grant EXECUTE on the resulting package to SHADOW
163
Retrofitting the APIs• Next, we’ll need to retrofit our application with the new
APIs so that we can perform DML transactions on the EMP table
– Disable or delete the Automated Row Processing (DML) Process in our application
– Create a synonym for the EMP_DML package in the SHADOW schema
– Add a new PL/SQL process that calls the EMP_DML package from the data schema for each supported transaction
164
165
EMP DML ProcessIF :REQUEST = 'CREATE' THEN emp_dml.ins_emp ( p_empno => :P2_EMPNO, p_ename => :P2_ENAME, p_job => :P2_JOB, p_deptno => :P2_DEPTNO ); ELSIF :REQUEST = 'DELETE' THEN emp_dml.del_emp ( p_empno => :P2_EMPNO ); ELSIF :REQUEST = 'SAVE' THEN emp_dml.upd_emp ( p_empno => :P2_EMPNO, p_ename => :P2_ENAME, p_job => :P2_JOB, p_deptno => :P2_DEPTNO ); END IF;
Data Security• So far, any user can see any row of data from our view
– This may be fine as per our business requirements
• But what if we need to secure the actual data?
– Virtual Private Database– Secure Views– Oracle Label Security
166
Surrogate Schema• Since we’ve revoked all system & role privileges from SHADOW, we can’t even sign on to it - let alone create the required VIEWs and SYNONYMs
• There’s a couple of options:
– Get access to SYS or SYSTEM• Unlikely
– Create a surrogate schema• Which has CREATE ANY VIEW & CREATE ANY SYNONYM granted to it
167
Surrogate Schema• All tables, views & procedures will go into the DATA
schema
• The SURROGATE schema will be used to create the corresponding Views & Synonyms in the SHADOW schema
– In APEX, simply reference the local Views & Synonyms
168
Summary
169
Summary• Securing data from unauthorized access is easiest and
best when done with built-in database features inside the database– Works across multiple application technologies
– Future-proof as tech stack changes
– Little to no code changes cause minimal impact
170
171
Unaltered Data
ID Name Department SSN
1 Scott 10 111-11-1111
2 Brian 10 222-22-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
172
Redaction
ID Name Department SSN
1 Scott 10 XXX-XX-1111
2 Brian 10 XXX-XX-2222
3 Jack 20 XXX-XX-3333
4 Anita 30 XXX-XX-4444
173
Virtual Private Database
ID Name Department SSN
1 Scott 10 111-11-1111
2 Brian 10 222-22-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
174
Redaction & Virtual Private Database
ID Name Department SSN
1 Scott 10 XXX-XX-1111
2 Brian 10 XXX-XX-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
175
Redaction, VPD & TDE (column)
ID Name Department SSN
1 Scott 10 XXX-XX-1111
2 Brian 10 XXX-XX-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
D4g-12-
E%f
R52-C$er)(ue2
0(LJHLKjn453
176
Redaction, VPD & TDE (tablespace)
ID Name Department SSN
1 Scott 10 XXX-XX-1111
2 Brian 10 XXX-XX-2222
3 Jack 20 333-33-3333
4 Anita 30 444-44-4444
D4g-12-
E%f
R52-C$er)(ue2
0(LJHLKjn453
NNWLv3423
&&Hh2146dsa
Vsb12i2e!
**7cxnAOSr
4wef ;r23;
2r4vdls
xwqdzLR#Q
345vcaÔ2D
rm2o3fwd
J4lk2)(
nMSR$r2
t34ml345
Tamper Proofing
177
Tampering• Every web application is subject to tampering
• Malicious users may try to exploit weaknesses in your APEX application using a number of different techniques
– Page Attributes
– URL Tampering
– SQL Injection
– Cross Site Scripting
• Fortunately, steps can be taken to prevent these types of attacks
178
Pages
179
Pages• Each APEX page has a number of attributes that can
enhance its security
• Depending on your business rules, it may be OK and secure to choose a “less secure” option for some attributes
• For example: if you need a page to be public, thats OK - as long as you mitigate what can be done on that page with other mechanisms
180
Page Security Options• Can be easily set in the new Page Designer view
181
Changed in
APEX 5 Authorization• Pages can have Authorization Schemes associated
with them
• Authorization Scheme must return true for the user to see the corresponding page(s)
• Most efficient to set Authorization Scheme to Once Per Session
• User will have to log out & log in to see changes
• By default, pages will not have Authorization Schemes associated with them
• Slightly more secure to set to Must Not Be Public User
182
Authentication• Page Authentication has two options
• Page Requires Authentication• User must be logged in to view this page
• Authorization Schemes & Build Options must also be met
• Page is Public• User can be the public user and view this page
• Authorization Schemes & Build Options must also be met
183
Rejoin Sessions• As mentioned before, Session Rejoining allows a page
or application to accept URLs without the APEX Session ID– A valid Session Cookie must be set for this to work
184
New in APEX 5
Deep Linking• Allows users to “deep link” to a page after successful
authentication
– Enabled• Users will be able to bookmark this page and return directly to if after
authenticating
– Disabled• Users will always end up on the home page after authenticating
• Can override the Application Level setting on a page-by-page basis
• Best to set to Application Default and set it to the desired value at the Application Level
185
Page Access Protection• Page Access Protection determines how pages can
be accessed via the URL and at what level
• Protected parameters include:
• Request
• Clear Cache• Item & Value pairs
• Note: Session State Protection must be enabled at the Application Level for this attribute to have any impact
186
Form Autocomplete• Option that will remember previous values and pop open a
window, allowing the user to select one
– By default, set to On
– Should be set to Off when sensitive data could be displayed in page items
• When disabled, will result in autocomplete="off" being printed in the page header, which will prevent the browser from remembering values entered into form items
187
Browser Cache• Determines whether or not APEX will preserve previous
pages in its cache
– Enabled• Browser will cache pages in both memory & disk, introducing potential security
and usability risks
– Disabled• Browser will not cache pages, resulting in a mode secure
and usable application
• Can override the Application Level setting on a page-by-page basis
• Best to set to Application Default and set it to Disabled at the Application Level
188
Items
189
URL Tampering• Consider this scenario:
– An authenticated, legitimate yet malicious and/or curious user logs on to your application
– He notices that when he hovers the mouse over the Edit link on Page 2, the end of the URL looks something like this: ...:P2_EMPNO:10
– Curious, he manually changes the URL in his browser to read: ...:P2_EMPNO:20
– And he is now viewing Department 20, which he should not be able to
190DEMO: Change value in the URL to 7499
URL Tampering• This is called URL Tampering
– One of the most dangerous forms of attacks, as:
• No programming is required
• Anyone can do it
• Developers do not always protect against it
• Results can be disastrous!
• Essentially, a clever, malicious user can alter the value of their session state by passing item & value pairs through the URL
– Unless precautions are taken
191
Session State Protection• Session State Protection is a feature in APEX that
combats URL Tampering– Generates an additional Checksum and passes that as part of the
URL
– If the Checksum is absent or altered, the page will not render, and thus the values will not be set
– Must be enabled at the Application Level for it to work
• Shared Components > Security > Session State Protection
192DEMO: Enable SSP and note the difference
Session State Protection• New report in APEX 5 summarizes page, page item and
application item SSP settings
193
Page Access Protection• Once Session State Protection is enabled, Page Access
Protection should then be enabled for all pages in your application
• Four options for Page Access Protection
– Unrestricted• Default and Least Secure
– Arguments Must Have Checksum
– No Arguments Allows
– No URL Access
194DEMO: Enable PAP at each level
Page Access Protection Warning• Page Access Protection is not always enough
• A malicious user can set an item on Page 2 by passing values to that item via Page 1 and then changing the URL to view Page 2
195
Page 2
P2_DEPTNOPage 1
P2_DEPTNO:20P2_DEPTNO:20
Page Access Protection
DEMO: Set page 2 item from page 1
Error
Item Protection• Item Protection will restrict how an item’s value can be set
• Five Options:
• Unrestricted• Default and Least Secure
• Checksum Required - Application
• Checksum Required - User• Checksum Required - Session• Restricted - may not be set from a browser
196
Item Protection• With Item Protection enabled, an additional checksum
needs to be present or an item’s value cannot be changed via the URL
197
Page 2
P2_DEPTNOPage 1
P2_DEPTNO:20P2_DEPTNO:20
Page Access Protection
Error
DEMO: Set page 2 item from page 1
Item Protection
Error
Item-Level Encryption• APEX stores session state values in the database in clear
text in the table WWV_FLOW_DATA– There is adequate security in place so that unauthorized users
cannot see session state values from other sessions
• However, a curious DBA or APEX administrator can view anyones session state– Even if you do not want them to!
198
Item-Level Encryption• Can easily be configured on an item-by-item basis
199
Changed in
APEX 5
200
No Encryption - Session State
201
No Encryption - SQL*Plus
1 SELECT 2 flow_id application_id, 3 item_name, 4 is_encrypted, 5 item_value 6 FROM 7 wwv_flow_data 8 WHERE 9* item_name = 'P3_SAL' SQL> /
APPLICATION_ID ITEM_NAME IS_ENCRYPTED ITEM_VALUE -------------- --------------- ------------- ---------------- 136 P3_SAL N 5000
202
Encryption - Session State
203
Encryption - SQL*Plus
1 SELECT 2 flow_id application_id, 3 item_name, 4 is_encrypted, 5 item_value 6 FROM 7 wwv_flow_data 8 WHERE 9* item_name = 'P3_SAL' SQL> /
APPLICATION_ID ITEM_NAME IS_ENCRYPTED ITEM_VALUE -------------- --------------- ------------- ---------------- 136 P3_SAL Y 9839BEFE425E74DX 5C0318373DE67FCD C8B66BEF97B13AB3
Restricted Characters• Certain special characters (<, >, “, &, etc.), when rendered,
can be instrumental in launching an attack
• APEX has an option to limit which characters are allowed in text fields in order to proactively prevent this
– Four Options:
• All characters can be saved
• Whitelist for a-Z, 0-9 and space
• Blacklist HTML command characters (<>”)
• Blacklist &<>"/;,*|=% and --
• Blacklist &<>"/;,*|=% or -- and new line
• Keep in mind if there are other unvalidated ways of inputting data, this feature will not help
204
SQL Injection
205
SQL Injection• Code injection technique
– Presented where user input isn’t escaped or strongly typed and is then used in the formation of a SQL statement.
– Effectively allows the user to alter the core functionality of the SQL that is executed
• 3 potential areas of concern
– Use of &ITEM. notation within SQL or PL/SQL
– Calls to DBMS_SQL– Calls to EXECUTE IMMEDIATE
206
SQL Injection in APEX• Consider the following SQL used for an APEX report: SELECT * FROM EMP WHERE UPPER(ename) LIKE UPPER('%&P1_SEARCH.%') AND deptno = 20
• The goal of this SQL is to allow a user to filter a report based on the ENAME of employees in the same department
– Assume that the item G_DEPTNO is set to the current user’s department via a computation when the user signs on
207
Expected Results• Assuming that the current user is a member of DEPTNO
20, running the report and entering in a simple query string - such as “s” - produces the following results:
208
Unexpected Results• However, entering a malicious string for the filter
returns all of the rows for all departments!
209
') OR '%' =('
\
Here’s Why• The SQL used in our report: SELECT * FROM EMP WHERE UPPER(ename) LIKE UPPER('%&P1_SEARCH.%') AND deptno = '&G_DEPTNO.'
• When run in APEX, turns into this SQL:SELECT * FROM EMP WHERE UPPER(ename) LIKE UPPER('%') OR '%' =('%') AND deptno = '&G_DEPTNO.'
210
Here’s Why• With a little formatting, it’s obvious why all records are
being returnedSELECT * FROM EMP WHERE UPPER(ename) LIKE UPPER('%') OR '%' =('%') AND deptno = '&G_DEPTNO.'
211
The new “OR” condition in the WHERE clause is enough to make
the two other conditions (ENAME & DEPTNO) irrelevant
Prevention• Making a simple change to the SQL to use bind variable
notation will prevent such attacks from succeedingSELECT * FROM EMP WHERE UPPER(ename) LIKE UPPER('%' || :P1_SEARCH || '%') AND deptno = '&G_DEPTNO.'
212
SQL Injection• Be careful when using
– DBMS_SQL – EXECUTE IMMEDIATE
• Always use Bind Variables where ever possible
• When you are forced to use &ITEM. notation
– Be aware where the data in those items is coming from
• APEX application, other web application, web service, etc.
– When in doubt, escape it before rendering
213
SQL Injection• Beware of Bind Variables in Dynamic SQL
– The use of bind variables alone does not eliminate the potential for SQL Injection
– Consider this example: l_sql := 'SELECT * FROM emp WHERE empno =' || :P1_EMPNO;RETURN l_sql;
– It’s no better than this: SELECT * FROM emp WHERE empno = &P1_EMPNO.
214
SQL Injection• Thus, in Dynamic SQL, be sure to embed the bind
variables in the string, so that when the query executes, they appear as bind variables, not evaluated values
– Correct usage in Dynamic SQL: l_sql := 'SELECT * FROM emp WHERE empno = :P1_EMPNO';RETURN l_sql;
215
Cross-Site Scripting
216
Cross Site Scripting (XSS)• Code injection technique
– Allows malicious users to inject client side code - typically JavaScript - into web pages
– Can be used to bypass access control, expose cookie information, capture and send data to other sites, etc.
• Most vulnerable are Input Items that allow unvalidated free-form text input
– If that data were then emitted unescaped into the page, any script entered into the field would execute and possibly cause damage and/or steal data
217
Simple Example• If the user were to enter the following text into a
“Description” field<script>alert('HELLO WORLD!');</script>
• And that text were presented unescaped as part of a report, the following would appear:
• While this example is harmless, this technique can be used for more malicious purposes
218
Cross Site Scripting (XSS)• While JavaScript doesn’t have access to the end user’s
computer it does have access to:
– The entire DOM of the current page
• Your APEX items
• APEX managed session state items
– Cookie information
• Fortunately, there are a number of features and tools in APEX to combat XSS attacks - both when entering and displaying data
219
Restricted Characters• The range of valid characters can be restricted on an
item-by-item basis– All Characters
– Whitelist for a-Z, 0-9 and space
– Blacklist HTML command characters (<>”)
– Blacklist &<>"/;,*|=% and —
– Blacklist &<>"/;,*|=% or -- and new line
• Keep in mind that data in your application may originate where no such restrictions exist
– Thus, always also escape when rendering
220
Column Display Type• The Escape Special Characters attribute of each
column should be set to Yes– Otherwise, any injected JavaScript will execute vs. harmlessly
render on the page
221
APEX_ESCAPE & Escaping Mode• A new API, APEX_ESCAPE will return escaped versions of
strings
– More modern replacement for HTF.ESCAPE_SC
• What gets escaped when APEX_ESCAPE is called is controlled by an application’s HTML Escaping Mode– Standard
• &, ", < and >
– Extended• &, ", <, >, ', / and non-ASCII characters if the database
character set is not AL32UTF8
222
Security Enhancements
223
Browser Security Options• APEX 4.1
– Browser Cache: prevent back button from showing old page content after logout
– Embed in Frames: prevent other apps from embedding and remote controlling your application
• APEX 5.0
– Define custom HTTP headers at instance and application level
224
Authentication and Authorization• APEX 4.2
– Authorizations and conditions for on demand processes
• APEX 5.0
– Flexible authentication - change the authentication of the development environment itself - LDAP, SSO, HTTP Header Variable, etc.
– Assign workspace groups to other groups
– Set group membership for session on login, including external groups
– “Is In Group” authorization
225
Improvements to Deter XSS• APEX 4.1
– HTML Expression attribute for report columns with substitution support instead of concatenating strings in the query
• APEX 4.2
– Restricted Characters attribute for items rejects malicious input
– More restrictive HTML-Escaping and APEX_ESCAPE API
• APEX 5.0
– New escaping syntax, e.g. &P1_ITEM!JS. for fine grained control
226
Instance Lockdown & Workspace Isolation• APEX 4.1
– Limit # of E-Mails Sent
• APEX 4.2
– Resource manager support
• APEX 5.0
– Limit file uploads
– Limit debug output
– Limit concurrent requests per session and per workspace
– Limit workspace access by hostname
227
Cryptography Improvements• APEX 4.2
– Stronger session cookie
• APEX 5.0
– SH-1/SH-2 for checksums
– Improved hashing algorithm for workspace user passwords
– New applications/forms are checksum protected by default
– Support DB 12c DBFIPS_140 mode
• DBFIPS_140 enables Transparent Data Encryption (TDE) and DBMS_CRYPTO PL/SQL package program units to run in a mode compliant to the Federal Information Processing Standard ("FIPS mode”)
228
APEX-SERT
229
Overview
230
231
Security is hard.If it’s easy, it’s likely wrong.
232
Security Budget Disparities
Before a Breach After a Breach
Most FundedMost Emphasized
233
NOT ENOUGH TIME
UNIMPORTANT DATA
INTERNAL ONLY STUPID USERS
NOT MY JOB
SMALL APP
REASONS WE IGNORE SECURITY IN OUR APPS
Recipe for Disaster• Given:
– The stresses of getting our applications released quickly
– The lack of time we have to do so
• Our applications - APEX & otherwise - are likely to have potential security vulnerabilities that we could easily fix– If we only knew what they were and had the time...
234
About APEX-SERT
235
APEX-SERT• APEX-SERT:
APEX Security Evaluation & Recommendation Tool
• APEX application designed to evaluate and identify potential security issues in other APEX applications
– Support for APEX 4.2 & 5.0
• Installs once and can be accessed instantly from any workspace with existing developer credentials
• Now available as open source underGPLv3 license
236
How it Works• APEX-SERT evaluates your application’s
metadata for potential security issues
– Takes only a few seconds to run
• Result is an interactive APEX application that allows developers to easily explore and mitigate potential threats
– Each application is scored based on APEX-SERT’s findings
• Designed to clearly identify what needs attention and steer developers or managers in that direction
– Click on a defect to edit and remedy it
237
Vulnerabilities Addressed• APEX-SERT will look for 5 classifications of potential
vulnerabilities
238
URL Tampering
Cross Site Scripting
SQL Injection
Page Settings
Application Settings
Complete Evaluation• APEX-SERT evaluates all components of an
application, regardless of their condition & authorization scheme– Nothing gets skipped
• APEX-SERT can be pre-configured with a set of valid values and rules– Which can be changed or augmented depending on your
interpretation or business needs
239 240
Security is not a product, but rather a process.
Ongoing Evaluation• APEX-SERT allows developers to add exceptions for
false positives and acceptable risks• All exceptions must be reviewed & approved by a manager
before the “approved” score increases
• As exceptions are logged, the value of the attribute in question is also captured
– If this value changes at any time, the exception will be instantly flagged as “stale” and require re-approval
241
Without APEX-SERT• Correcting each additional security vulnerability may cause
other functional issues
– Thus, a high number of vulnerabilities corrected at once will yield more functional defects and increase development time
242
Time
Vuln
erab
iliti
es
Fixing issues here will likely break something else
• Using APEX-SERT to keep security vulnerabilities to a minimum reduces the number of functional defects introduced
With APEX-SERT
243
Time
Vuln
erab
iliti
es
Preventing a high number of vulnerabilities ensures fewer defects introduced
Demonstration
244
Demonstration• Installation Overview
• Management Application
• Evaluating an Application
• Approving & Rejecting Exceptions
• Preview of Printing
245
Summary
246
“Yesterday, you said tomorrow”• With APEX-SERT, there is no longer an excuse to
ignore the security of your APEX applications
– Installs & configures in minutes
– Totally integrated into the APEX builder
– Easy to lean and use
– Evaluations can be automated
– No license costs
247
Summary• APEX-SERT provides you with the ability to easily and
quickly identify and remedy most APEX security vulnerabilities– It is designed to be used throughout the development
process, not as a checkpoint at the end
– As a side-effect, your developers will become more security-conscious by using APEX-SERT and incorporate secure best practices by default
248
Availability• APEX 4.2
– Available today
– No new features; only bug fixes for supported customers
• APEX 5.0
– Available today
– Limited new features
• Committed to PDF Printing
• APEX 5.1
– Available “Soon”
249
Downloads• All releases & source code available on GitHub:
– https://github.com/OraOpenSource/apex-sert– Click on releases
– Download & extract sert_050000.zip
• APEX-SERT home page via OraOpenSource:
– http://oraopensource.com/apex-sert
250
Support• Sumner Technologies provides complete for-cost support
for APEX-SERT
– Per-instance or per-site basis
• Contact us for details & pricing
– http://www.sumnertech.com/apex-sert
– 703-722-1495
251 252