Sunteți pe pagina 1din 504

Oracle Database 12c: Security

Activity Guide – Volume I


D81599GC10
Edition 1.0 | November 2015 | D84091

Learn more from Oracle University at oracle.com/education/


Author Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Dominique Jeunot Disclaimer

Hans Forbrich This document contains proprietary information and is protected by copyright and
other intellectual property laws. You may copy and print this document solely for your
own use in an Oracle training course. The document may not be modified or altered
Technical Contributors in any way. Except where your use constitutes "fair use" under copyright law, you
and Reviewers may not use, share, download, upload, copy, print, display, perform, reproduce,
publish, license, post, transmit, or distribute this document in whole or in part without
Jean-Francois Verrier the express authorization of Oracle.
Mark Fuller
The information contained in this document is subject to change without notice. If you
James Spiller find any problems in the document, please report them in writing to: Oracle University,
500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
Lachlan Williams warranted to be error-free.
Jody Glover
Restricted Rights Notice
Jeff Ferriera
Peter Fusek If this documentation is delivered to the United States Government or anyone using
the documentation on behalf of the United States Government, the following notice is
Jim Womack applicable:
Daniela Hansell
U.S. GOVERNMENT RIGHTS
Maria Billings The U.S. Government’s rights to use, modify, reproduce, release, perform, display, or
disclose these training materials are restricted by the terms of the applicable Oracle
Waleed Ahmed license agreement and/or the applicable U.S. Government contract.
Jagan Athreya
Trademark Notice
Rhonda Bassett
Todd Bottger Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names
may be trademarks of their respective owners.
Roxana Bradescu
Andrey Brozhko
Guru Prasad Cavalay
Xiaobin Chen
Ricky Cheung
Chi Ching Chui
Alessandro Colonna
Stefan Dolea Technical Contributors and Reviewers
Mark Doran Paul Needham
Gerlinde Frenze William O'Brien
Frank Fu Dinesh Rajasekharan
Philip Garm Amoghavarsha Ramappa
Laurent Goldsztejn
Veeranjaneyulu Goli Editors
Nathalie Gonnet-Gouronc Malavika Jinka
Joel Goodman Anwesha Ray
Vira Goorah Daniel Milne
Ashish Gupta
Min-Hank Ho Graphic Designer
Chandrasekharan Iyer Rajiv Chandrabhanu
Prathiba Kalirengan
Publishers
Feroz Khan
Jobi Varghese
Chao Liang
Pavithran Adka
Yio-Liong Liew
Sumesh Koshy
Kurt Lysy
Srividya Rameshkumar
Petr Macak
Jayanthy Keshavamurthy
Ammar Semle
Table of Contents
Practices for Lesson 1: Introduction ..............................................................................................................1-1
Practices for Lesson 1: Overview ...................................................................................................................1-2
Practice 1-1: Environment Familiarization ......................................................................................................1-3
Practices for Lesson 2: Security Requirements ............................................................................................2-1
Practices for Lesson 2: Overview ...................................................................................................................2-2
Practice 2-1: SQL Injection Exploit Tutorial (optional) ....................................................................................2-3
Practice 2-2: Using Invoker's Rights Procedure .............................................................................................2-4
Practice 2-3: Using Static SQL and Bind Arguments .....................................................................................2-8
Practice 2-4: Avoiding SQL Injection Through Dynamic PL/SQL block ..........................................................2-13
Practice 2-5: Validating Input Using the DBMS_ASSERT Package ...............................................................2-18
Practices for Lesson 3: Security Solutions ...................................................................................................3-1
Practices for Lesson 3: Overview ...................................................................................................................3-2
Practice 3-1: Choosing Oracle Solutions........................................................................................................3-3
Practice 3-2: Configuring Monitoring Credentials Using Enterprise Manager Cloud Control..........................3-5
Practice 3-3: Viewing Compliance Frameworks .............................................................................................3-11
Practice 3-4: Maintaining Integrity by Using Constraints ................................................................................3-16
Practice 3-5: Maintaining Integrity by Using Triggers .....................................................................................3-20
Practice 3-6: Controlling Data Access by Using Views ..................................................................................3-23
Practice 3-7: Using Database Vault Realms to Disallow Access to Objects ..................................................3-26
Practices for Lesson 4: Implementing Basic Database Security .................................................................4-1
Practices for Lesson 4: Overview ...................................................................................................................4-2
Practice 4-1: Creating the Security Officer Account .......................................................................................4-3
Practice 4-2: Managing Secure Passwords ...................................................................................................4-12
Practice 4-3: Protecting the Data Dictionary ..................................................................................................4-26
Practice 4-4: Investigating Security Violations Against Compliance Framework ............................................4-29
Practices for Lesson 5: Securing Network Services.....................................................................................5-1
Practices for Lesson 5: Overview ...................................................................................................................5-2
Practice 5-1: Configuring the Listener on Another Port ..................................................................................5-3
Practice 5-2: Securing the Listener Administration.........................................................................................5-9
Practice 5-3: Configure the Listener to Allow Access Only from Your Client Computer (optional) .................5-12
Practices for Lesson 6: Implementing Basic and Strong Authentication ...................................................6-1
Practices for Lesson 6: Overview ...................................................................................................................6-2
Practice 6-1: Using Basic OS Authentication Method ....................................................................................6-3
Practice 6-2: Observing Passwords in Database Links ..................................................................................6-6
Practice 6-3: Restricting Database Links With Views .....................................................................................6-10
Practice 6-4: Configuring the External Secure Password Store .....................................................................6-13
Practice 6-5: Connecting to a CDB or a PDB .................................................................................................6-20
Practices for Lesson 7: Using Enterprise User Security ..............................................................................7-1
Practices for Lesson 7: Overview ...................................................................................................................7-2
Practice 7-1: Using Enterprise User Security .................................................................................................7-3
Practices for Lesson 8: Using Proxy Authentication ....................................................................................8-1
Practice 8-1: Using Proxy Authentication .......................................................................................................8-2
Practices for Lesson 9: Using Privileges and Roles .....................................................................................9-1
Practices for Lesson 9: Overview ...................................................................................................................9-2
Practice 9-1: Exploring DBA Privileges ..........................................................................................................9-3

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Oracle Database 12c: Security Table of Contents


iii
Practice 9-2: Granting SYSBACKUP Administrative Privilege .......................................................................9-10
Practice 9-3: Implementing a Secure Application Role ..................................................................................9-15
Practice 9-4: Enabling Roles at Run Time Using CBAC ................................................................................9-24
Practice 9-5: Executing Invoker's Right Procedure Using INHERIT PRIVILEGES Privilege (Optional) .........9-30
Practice 9-6: BEQUEATH Current_user Views Using INHERIT PRIVILEGES (Optional)..............................9-35
Practice 9-7: Managing Local and Common Privileges and Roles in CDB/PDBs ..........................................9-39
Practices for Lesson 10: Privilege Analysis ..................................................................................................10-1
Practices for Lesson 10: Overview .................................................................................................................10-2
Practice 10-1: Capturing Privileges ................................................................................................................10-3
Practice 10-2: Capture Privileges Used Through Roles .................................................................................10-12
Practice 10-3: Capture Privileges Used In Contexts (Optional) ......................................................................10-16
Practices for Lesson 11: Using Application Contexts ..................................................................................11-1
Practice 11-1: Creating an Application Context ..............................................................................................11-2
Practices for Lesson 12: Implementing Virtual Private Database................................................................12-1
Practice 12-1: Implementing a Virtual Private Database Policy .....................................................................12-2
Practice 12-2: Implementing a Dynamic VPD Policy ......................................................................................12-13
Practice 12-3: Troubleshooting VPD Policies .................................................................................................12-18
Practice 12-4: Cleaning Up VPD Policies .......................................................................................................12-23
Practices for Lesson 13: Implementing Oracle Label Security Policies .....................................................13-1
Practice 13-1: Registering and Enabling Oracle Label Security .....................................................................13-2
Practice 13-2: Implementing Oracle Label Security .......................................................................................13-9
Practice 13-3: Cleaning Up OLS Policies .......................................................................................................13-41
Practices for Lesson 14: Oracle Data Redaction...........................................................................................14-1
Practices for Lesson 14: Overview .................................................................................................................14-2
Practice 14-1: Redacting Protected Column Values with FULL Redaction ....................................................14-3
Practice 14-2: Redacting Protected Column Values with PARTIAL Redaction ..............................................14-12
Practice 14-3: Changing the Default Value for FULL Redaction ....................................................................14-15
Practice 14-4: Cleaning Up Redaction Policies ..............................................................................................14-23
Practices for Lesson 15: ADM and Data Masking .........................................................................................15-1
Practices for Lesson 15: Overview .................................................................................................................15-2
Practices for Lesson 16: Transparent Sensitive Data Protection ................................................................16-1
Practices for Lesson 16: Overview .................................................................................................................16-2
Practice 16-1: Implementing a TSDP Policy ..................................................................................................16-3
Practice 16-2: Using REDACT_ AUDIT Policy ...............................................................................................16-17
Practice 16-3: Disabling TSDP Policies .........................................................................................................16-21
Practices for Lesson 17: Encryption Concepts .............................................................................................17-1
Practices for Lesson 17: Overview .................................................................................................................17-2
Practices for Lesson 18: Using Application-Based Encryption ...................................................................18-1
Practice 18-1: Using DBMS_CRYPTO for Encryption....................................................................................18-2
Practice 18-2: Checksumming by Using the HASH Function .........................................................................18-8
Practices for Lesson 19: Applying Transparent Data Encryption ...............................................................19-1
Practice 19-1: Configuring the Password-Based Keystore for TDE ...............................................................19-2
Practice 19-2: Implementing Table Column Encryption .................................................................................19-12
Practice 19-3: Implementing Tablespace Encryption .....................................................................................19-30

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Oracle Database 12c: Security Table of Contents


iv
Practices for Lesson 20: Applying File Encryption.......................................................................................20-1
Practice 20-1: Using RMAN Backup File Encryption ......................................................................................20-2
Practice 20-2: Exporting Encrypted Data .......................................................................................................20-15
Practice 20-3: Importing Encrypted Data .......................................................................................................20-25
Practices for Lesson 21: Using Unified Auditing ..........................................................................................21-1
Practices for Lesson 21: Overview .................................................................................................................21-2
Practice 21-1: Enabling Unified Auditing ........................................................................................................21-3
Practice 21-2: Creating and Enabling Audit Policies ......................................................................................21-12
Practice 21-3: Cleaning Up Audit Policies and Data ......................................................................................21-24
Practice 21-4: Auditing SYS User (Optional)..................................................................................................21-28
Practice 21-5: Auditing Data Pump Export (Optional) ....................................................................................21-30
Practice 21-6: Auditing RMAN Backups .........................................................................................................21-40
Practice 21-7: Auditing Database Vault Violations (Optional) ........................................................................21-44
Practices for Lesson 22: Using Fine-Grained Audit......................................................................................22-1
Practice 22-1: Implementing Fine-Grained Auditing .......................................................................................22-2
Practice 22-2: Viewing the FGA Trail .............................................................................................................22-5
Practice 22-3: Using an Event Handler ..........................................................................................................22-7
Appendix E: Source Code ...............................................................................................................................23-1
Appendix E: Source Code ..............................................................................................................................23-2
Appendix F: USERENV and SYS_SESSION_ROLES Contexts ....................................................................24-1
Practices for Appendix F: Overview ...............................................................................................................24-2

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Oracle Database 12c: Security Table of Contents


v
Practices for Lesson 1:
Introduction
Chapter 1

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 1
Practices for Lesson 1: Overview
Practices Overview

Background:

In the practices of this course, you assume the role of a database administrator (DBA) and of
the security officer. The operating system (OS) accounts on your computer are:
• The oracle user with a password of oracle
• The root user with a password of oracle
Simple and easy-to-remember passwords will be used in order to not detract from the purpose
of the exercise. In real development and production environments, use strong passwords
following the guidelines presented in this course and in the Oracle Database Security Guide
12c.

The existing installation resides in the following ORACLE_HOME:


/u01/app/oracle/product/12.1.0/dbhome_1

You find the following instances and databases:


• The instance and non-container database, repository for Enterprise Manager Cloud
Control: em12rep
• The instance and a non-container database: orcl
• The instance and multitenant container database: cdb1
• The pluggable database: pdb1_1 within cdb1
• The pluggable database: pdb1_2 within cdb1

The login information for the various connections is the following:


• Database accounts: SYS and SYSTEM, and all other new accounts and sample
accounts are assigned the oracle_4U password.
• The security officer account is assigned a different password: oracle_4sec
• Enterprise Manager Cloud Control: sysman user is assigned the Oracle123
password.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 2
Practice 1-1: Environment Familiarization
Overview
In this practice, you will explore the server environment and create users for later practices.

Tasks
1. Verify that you are logged in as the oracle user when you right-click the desktop and click
Open in Terminal to open a terminal window. The UID and GID may have different values
than yours. Do not care about the values but do care about the user used to log in.
$ id
uid=54321(oracle) gid=54321(oinstall)
groups=54321(oinstall),54322(dba),54323(oper),54324(backupdba),5
4325(dgdba),54326(kmdba),54327(asmdba)
$
2. Before you start reviewing the practices environment, verify the permissions set for the labs
scripts in /home/oracle/labs directory and the demos in /home/oracle/labs/demos
directory. If the permissions are not appropriately set, execute the following UNIX
commands to set the right permissions for all practices and demos. Then set the proper
network aliases in the tnsnames.ora file.
$ su
Password: ******
# chown -R oracle:oinstall /home/oracle/labs
# exit
exit
$ chmod -R 777 /home/oracle/labs
$ cp /home/oracle/labs/admin/tnsnames.ora
/u01/app/oracle/product/12.1.0/dbhome_1/network/admin
$
3. Move the glogin.sql file to the appropriate destination. This script is automatically run each
time you start SQL*Plus. This file avoids you having to enter SQL*Plus commands each
time you disconnect and reconnect to SQL*Plus.
$ cp /home/oracle/labs/admin/glogin.sql
/u01/app/oracle/product/12.1.0/dbhome_1/sqlplus/admin
$
4. To list the running instances, you can search for the SMON background process. Any
running instance includes the SMON background process at least.
$ pgrep -lf smon
1024 ora_smon_cdb1
4322 ora_smon_orcl
29667 ora_smon_em12rep
$
There are three running instances, orcl, cdb1 and em12rep. Notice that the user running
the orcl and cdb1 instances is oracle.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 3
5. Connect to the orcl instance as the SYS user.
a. Use the oraenv utility to set the ORACLE_SID environment variable to the orcl value.
The utility automatically sets the ORACLE_HOME to
/u01/app/oracle/product/12.1.0/dbhome_1.
$ . oraenv
ORACLE_SID = [oracle] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
b. Use SQL*Plus to connect to the instance.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
SYS orcl >
c. View the instance name.
SYS orcl > select instance_name from v$instance;

INSTANCE_NAME
----------------
orcl

SYS orcl > exit


$
d. Execute the create_users.sh script to create new users in the database. The users
JIM, TOM will be used in later practices. Make sure you are in the ~/labs/USERS
directory.
$ cd ~/labs/USERS
$ ./create_users.sh
$
6. Connect to the cdb1 instance as the SYS user.
a. Use the oraenv utility to set the ORACLE_SID environment variable to the cdb1 value.
$ . oraenv
ORACLE_SID = [orcl] ? cdb1
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 4
b. Use SQL*Plus to connect to the instance.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
SYS cdb1 >
c. View the instance name.
SYS cdb1 > select instance_name from v$instance;

INSTANCE_NAME
----------------
cdb1

SYS cdb1 >


d. Quit the SYS session.
SYS cdb1 > EXIT
$
7. Connect to the pdb1_1 pluggable database as the SYS user.
a. Use the oraenv utility to set the ORACLE_SID environment variable to the cdb1 value.
The instance for all pluggable databases in the cdb1 container database is the cdb1
instance.
$ . oraenv
ORACLE_SID = [cdb1] ? cdb1
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
b. Use the service name of the PDB to connect to pdb1_1.
1) Explore the services to check if the pdb1_1 service name is started.
$ lsnrctl status

Services Summary...
Service "em12rep" has 1 instance(s).
Instance "em12rep", status READY, has 1 handler(s) for this
service...
Service "em12repxdb" has 1 instance(s).
Instance "em12rep", status READY, has 1 handler(s) for this
service...
Service "cdb1" has 1 instance(s).

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 5
Instance "cdb1", status READY, has 1 handler(s) for this
service...
Service "cdb1XDB" has 1 instance(s).
Instance "cdb1", status READY, has 1 handler(s) for this
service...
Service "orcl" has 1 instance(s).
Instance "orcl", status READY, has 1 handler(s) for this
service...
Service "orclXDB" has 1 instance(s).
Instance "orcl", status READY, has 1 handler(s) for this
service...
Service "pdb1_1" has 1 instance(s).
Instance "cdb1", status READY, has 1 handler(s) for this
service...
Service "pdb1_2" has 1 instance(s).
Instance "cdb1", status READY, has 1 handler(s) for this
service...
The command completed successfully
$
2) Connect to pdb1_1.
$ sqlplus sys@pdb1_1 as sysdba

Enter password: ******


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
SYS pdb1_1 >
3) View the instance name.
SYS pdb1_1 > select instance_name from v$instance;

INSTANCE_NAME
----------------
cdb1

SYS pdb1_1 >


4) View the pluggable database name.
SYS pdb1_1 > select name from v$pdbs;

NAME
----------------
PDB1_1
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 6
SYS pdb1_1 >
c. Connect to pdb1_2.
SQL pdb1_1 > CONNECT sys@pdb1_2 as sysdba
Enter password: ******
Connected.
SYS pdb1_2 >
1) View the instance name.
SYS pdb1_2 > select instance_name from v$instance;

INSTANCE_NAME
----------------
cdb1

SYS pdb1_2 >


2) View the pluggable database name.
SYS pdb1_2 > SHOW con_name

CON_NAME
------------------------------
PDB1_2
SYS pdb1_2 >
d. Quit the SYS session.
SYS pdb1_2 > EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 7
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 1: Introduction


Chapter 1 - Page 8
Practices for Lesson 2:
Security Requirements
Chapter 2

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 1
Practices for Lesson 2: Overview
Practices Overview
The practices show how secure-coding practices can be used to reduce or eliminate the
possibility of SQL injection exploits. The basic methods used in reducing the possibility of SQL
injection can be adapted and applied to other common exploits. Specifics such as removing
dynamic SQL would be changed to not allowing certain characters in XML or HTML to prevent
cross-scripting. But general techniques such as peer review and testing are applicable across
all type of exploits.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 2
Practice 2-1: SQL Injection Exploit Tutorial (optional)
Overview
Without proper safeguards, applications are vulnerable to various forms of security attack. One
particularly pervasive method of attack is called SQL injection. Using this method, a hacker can
pass string input to an application with the hope of gaining unauthorized access to a database.
By taking this self-study “Defending Against SQL Injection Attacks!” tutorial, you can arm
yourself with techniques and tools to strengthen your code and applications against these
attacks. This tutorial employs text and diagrams to present concepts, design issues, coding
standards, processes, and tools.

Tasks
1. Launch a browser and enter: file:////home/oracle/labs/SQL_Injection/index.htm.
Note: You may get an Adobe Flash Player 10 settings window when launching demos in
the topics by clicking on the mouse image. This Adobe Flash Player 10 settings window
includes the following messages:
Adobe Flash Player has stopped a potentially unsafe operation
The following local application on your computer or network:
//home/oracle/labs/SQL_Injection/html/lesson1/les01_first_order_attack_skin.swf
is trying to communicate with this Internet-enabled location:
//home/oracle/labs/SQL_Injection/html/lesson1/les01_first_order_attack.htm
To let this application communicate with the internet, click Settings.
You must restart the application after changing your settings.
Click the Settings button the first time you need to view a demo. Another window opens and
let you view the demo. In this window, the lesson number and the file names vary based on
the demos you launch for which topic.
Note: If you click the link - More ST Curriculum Tutorials, it is not working displaying "504
Gateway Timeout". If you need more tutorials, go to Oracle Learning Library (OLL)
Note: Please don’t use the link Lesson 3.1 because the page navigates to 3.2 Use Static
SQL instead of 3.1 Use Compile-Time-Fixed SQL Statement. If you really need to view this
Lesson 3.1, enter file:////home/oracle/labs/SQL_Injection/html/lesson3/les03_tm_static1.htm
in the browser.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 3
Practice 2-2: Using Invoker's Rights Procedure
Overview
In this practice, you reduce SQL injection vulnerability by using invoker’s rights.
If you do not provide an interface to an attacker, clearly it is not available to be abused. Thus,
the first, and arguably the most important, line of your defense is to reduce the exposed
interfaces to only those that are absolutely required. You can reduce the exposed interfaces by:
• Using invoker’s rights to reduce SQL injection vulnerability
• Reducing arbitrary inputs
Stored program units and SQL methods execute with a set of privileges. By default, the
privileges are those of a schema owner, also known as the definer. Definer’s rights not only
dictate the privileges, but are also used to resolve object references. If a program unit does not
need to be executed with the escalated privileges of the definer, you should specify that the
program unit executes with the privileges of a caller, also known as the invoker.

Tasks
1. Create a definer’s rights procedure in the orcl instance. The CHANGE_PASSWORD
procedure is created under the SYS schema. It accepts two parameters and uses them in
the ALTER USER statement.
a. Use the oraenv utility to set the ORACLE_SID environment variable to the orcl value.
$ . oraenv
ORACLE_SID = [cdb1] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
b. Use SQL*Plus to connect to the instance.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
SYS orcl >
c. Create the CHANGE_PASSWORD procedure.
SYS orcl > CREATE OR REPLACE
PROCEDURE change_password(p_username VARCHAR2 DEFAULT NULL,
p_new_password VARCHAR2 DEFAULT NULL)
IS
v_sql_stmt VARCHAR2(500);
BEGIN
v_sql_stmt := 'ALTER USER '||p_username ||' IDENTIFIED BY '
|| p_new_password;
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 4
EXECUTE IMMEDIATE v_sql_stmt;
END change_password;
/
2 3 4 5 6 7 8 9 10 11

Procedure created.
SYS orcl >
Note the use of dynamic SQL with concatenated input values within the v_sql_stmt
character string.
2. As the SYS user, grant OE, HR, and SH the ability to execute the CHANGE_PASSWORD
procedure.
SYS orcl > GRANT EXECUTE ON change_password to OE, HR, SH;

Grant succeeded.

SYS orcl >


3. Result: Anyone that connects as SH, OE, or HR can change the password of any user,
without knowing that user’s password. Connect as OE to test that you can change the
password of SYS.
SYS orcl > CONNECT oe
Enter password: ******
Connected.
OE orcl >
OE orcl > EXECUTE sys.change_password ('SYS', 'mine')

PL/SQL procedure successfully completed.

OE orcl >
4. Check that the password of SYS has changed.
OE orcl > CONNECT sys@orcl as sysdba
Enter password: ****** (oracle_4U)
ERROR:
ORA-01017: invalid username/password; logon denied

Warning: You are no longer connected to ORACLE.


>
> CONNECT sys@orcl as sysdba
Enter password: ****** (mine)
Connected.
SYS orcl >

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 5
5. Reset the SYS password to the initial value oracle_4U.
SYS orcl > EXECUTE sys.change_password ('SYS', 'oracle_4U')

PL/SQL procedure successfully completed.

SYS orcl >


6. To disallow another user from changing a password that does not belong to the user,
redefine the CHANGE_PASSWORD procedure with the invoker’s rights adding the AUTHID
CURRENT_USER clause.
SYS orcl > CREATE OR REPLACE PROCEDURE change_password
(p_username VARCHAR2 DEFAULT NULL,
p_new_password VARCHAR2 DEFAULT NULL)
AUTHID CURRENT_USER
IS
v_sql_stmt VARCHAR2(500);
BEGIN
v_sql_stmt := 'ALTER USER '||p_username ||' IDENTIFIED BY '
|| p_new_password;
EXECUTE IMMEDIATE v_sql_stmt;
END change_password;
/
2 3 4 5 6 7 8 9 10 11 12
Procedure created.

SYS orcl >


7. Reconnect as OE to test that you cannot change the password of SYS.
SYS orcl > CONNECT oe
Enter password: ******
Connected.
OE orcl > EXECUTE sys.change_password ('SYS', 'yours')
BEGIN sys.change_password('SYS', 'yours'); END;

*
ERROR at line 1:
ORA-01031: Insufficient privileges
ORA-06512: at "SYS.CHANGE_PASSWORD", at line 10
ORA-06512: at line 1

OE orcl >

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 6
8. Use the same procedure to change OE password.
OE orcl > EXECUTE sys.change_password ('OE', 'oracle')

PL/SQL procedure successfully completed.

OE orcl > EXECUTE sys.change_password ('OE', 'oracle_4U')

PL/SQL procedure successfully completed.

OE orcl >
.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 7
Practice 2-3: Using Static SQL and Bind Arguments
Overview
Poor application design can lead to “designed in” vulnerabilities, where there are no apparent
coding problems and everything works as intended.
However, you must design your code such that it is (ideally) entirely free of SQL injection
vulnerabilities, or contains measures that mitigate the impact of a successful attack.
The common flaw of all code vulnerable to SQL injection is the construction of dynamic SQL by
using string concatenation. Complete immunity from SQL injection attack can be achieved only
through the elimination of input string concatenation in dynamic SQL.
• Avoid input string concatenation.
• Use bind arguments, whether automatically via static SQL or explicitly via dynamic
SQL statements. Bind arguments are immune to SQL injection.
Design your code to use bind arguments wherever possible. The only exceptions should be
when you need to concatenate identifiers or keywords because you have no other choice.
In this practice, you will create a SQL code to demonstrate SQL injection in LIKE operators and
how to redefine the code to prevent SQL injection.

Tasks
1. Define two LIST_PRODUCTS procedures. The LIST_PRODUCTS_DYNAMIC procedure
does not use bind arguments but contains concatenated input values. The
LIST_PRODUCTS_STATIC procedure uses bind arguments.
Create the LIST_PRODUCTS_DYNAMIC procedure containing dynamic SQL with
concatenated input values. Why is the SQL considered as dynamic? The ‘SELECT
product_name, min_price, list_price FROM products WHERE product_name like
‘’%’||p_product_name||’%’’’’ statement is unresolved at compile-time.
OE orcl > CONNECT oe
Enter password: ******
Connected.
OE orcl > SET SERVEROUTPUT ON
OE orcl > CREATE OR REPLACE PROCEDURE list_products_dynamic
(p_product_name VARCHAR2 DEFAULT NULL)
AS
TYPE cv_prodtyp IS REF CURSOR;
cv cv_prodtyp;
v_prodname products.product_name%TYPE;
v_minprice products.min_price%TYPE;
v_listprice products.list_price%TYPE;
v_stmt VARCHAR2(400);
BEGIN
v_stmt := 'SELECT product_name, min_price, list_price
FROM products
WHERE product_name like ''%'||p_product_name||'%''';
OPEN cv FOR v_stmt;
dbms_output.put_line(v_stmt);
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 8
LOOP
FETCH cv INTO v_prodname, v_minprice, v_listprice;
EXIT WHEN cv%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Product Info: '||v_prodname ||', '||
v_minprice ||', '|| v_listprice);
END LOOP;
CLOSE cv;
END;
/
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16 17 18 19 20 21 22 23 24
Procedure created.

OE orcl >
2. Execute the procedure.
OE orcl > EXEC list_products_dynamic('Laptop')
SELECT product_name, min_price, list_price
FROM products

WHERE product_name like '%Laptop%'


Product Info: Laptop 128/12/56/v90/110, 2606, 3219
Product Info: Laptop 16/8/110, 800, 999
Product Info: Laptop 32/10/56, 1542, 1749
Product Info: Laptop 48/10/56/110, 2073, 2556
Product Info: Laptop 64/10/56/220, 2275, 2768

PL/SQL procedure successfully completed.

OE orcl >
The result is correct because the user entered an appropriate product name.
3. Execute the procedure performing a SQL injection attack and see that you can retrieve the
list of database accounts.
OE orcl > EXEC list_products_dynamic(''' and 1=0 union select
cast(username as nvarchar2(100)), null, null from all_users --')
SELECT product_name, min_price, list_price
FROM products
WHERE product_name like '%' and 1=0 union select cast(username
as
nvarchar2(100)), null, null from all_users --%'
Product Info: ANONYMOUS, ,
Product Info: APEX_040200, ,
Product Info: APEX_PUBLIC_USER, ,
Product Info: APPQOSSYS, ,
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 9
Product Info: AUDSYS, ,
Product Info: BI, ,
Product Info: CTXSYS, ,
Product Info: DBSNMP, ,
Product Info: DIP, ,
Product Info: DVF, ,
Product Info: DVSYS, ,
Product Info: FLOWS_FILES, ,
Product Info: GSMADMIN_INTERNAL, ,
Product Info: GSMCATUSER, ,
Product Info: GSMUSER, ,
Product Info: HR, ,
Product Info: IX, ,
Product Info: JIM, ,
Product Info: LBACSYS, ,
Product Info: MDDATA, ,
Product Info: MDSYS, ,
Product Info: OE, ,
Product Info: OJVMSYS, ,
Product Info: OLAPSYS, ,
Product Info: ORACLE_OCM, ,
Product Info: ORDDATA, ,
Product Info: ORDPLUGINS, ,
Product Info: ORDSYS, ,
Product Info: OUTLN, ,
Product Info: PM, ,
Product Info: SCOTT, ,
Product Info: SH, ,
Product Info: SI_INFORMTN_SCHEMA, ,
Product Info: SPATIAL_CSW_ADMIN_USR, ,
Product Info: SPATIAL_WFS_ADMIN_USR, ,
Product Info: SYS, ,
Product Info: SYSBACKUP, ,
Product Info: SYSDG, ,
Product Info: SYSKM, ,
Product Info: SYSTEM, ,
Product Info: TOM, ,
Product Info: WMSYS, ,
Product Info: XDB, ,
Product Info: XS$NULL, ,

PL/SQL procedure successfully completed.

OE orcl >
Notice the SQL injection attack succeeded through the concatenation of a UNION set
operator to the dynamic SQL statement.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 10
4. Create the LIST_PRODUCTS_STATIC procedure that contains static SQL with bind
arguments. Why is SQL considered as static? Although the ‘SELECT product_name,
min_price, list_price FROM products WHERE product_name like v_bind’ statement is not a
compile-time-fixed SQL statement text, the SQL syntax, however, is frozen at compile time.
It is clear that the SQL statement extracts the prices of the product_name specified by the
bind variable v_bind. This kind of statement is a run-time static SQL statement.
OE orcl > CREATE OR REPLACE PROCEDURE list_products_static
(p_product_name VARCHAR2 DEFAULT NULL)
AS
v_bind VARCHAR2(400);
BEGIN
v_bind := '%'||p_product_name||'%';
FOR i in
(SELECT product_name, min_price, list_price
FROM products
WHERE product_name like v_bind)
LOOP
DBMS_OUTPUT.PUT_LINE('Product Info: '||i.product_name
||','||
i.min_price ||', '|| i.list_price);
END LOOP;
END;
/
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16
Procedure created.

OE orcl >
5. Execute the procedure.
OE orcl > EXEC list_products_static('Laptop')
Product Info: Laptop 128/12/56/v90/110,2606, 3219
Product Info: Laptop 16/8/110,800, 999
Product Info: Laptop 32/10/56,1542, 1749
Product Info: Laptop 48/10/56/110,2073, 2556
Product Info: Laptop 64/10/56/220,2275, 2768

PL/SQL procedure successfully completed.


OE orcl >
Notice that the procedure runs correctly with a “normal” input.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 11
6. Execute the same static procedure to verify that it is not vulnerable to SQL injection.
OE orcl > EXEC list_products_static(''' and 1=0 union select
cast(username as nvarchar2(100)), null, null from all_users --')

PL/SQL procedure successfully completed.

OE orcl >
Notice that the SQL injection attempt failed.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 12
Practice 2-4: Avoiding SQL Injection Through Dynamic PL/SQL block
Overview
In this practice, you will create a code to demonstrate SQL injection through dynamic PL/SQL
block and redefine the code to prevent SQL injection. The practice shows how SQL injection via
dynamic PL/SQL can be even more dangerous than via dynamic SQL.

Tasks
1. Create the GET_AVG_SALARY function containing a dynamic PL/SQL block used to
retrieve the average salary with a concatenated input parameter p_job. This is a SQL
injection vulnerability.
OE orcl > CONNECT hr
Enter password: ******
Connected.
HR orcl > SET SERVEROUTPUT ON
HR orcl > CREATE OR REPLACE FUNCTION get_avg_salary (p_job
VARCHAR2)
RETURN NUMBER
AS
avgsal employees.salary%TYPE;
v_blk VARCHAR2(4000);
BEGIN
v_blk := 'BEGIN
SELECT AVG(salary) INTO :avgsal
FROM hr.employees
WHERE job_id = '''||P_JOB||'''; END;
';
EXECUTE IMMEDIATE v_blk
USING OUT avgsal;
dbms_output.put_line('Code: ' || v_blk);
RETURN avgsal;
END;
/
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16 17
Function created.
HR orcl >
2. Execute the dynamic PL/SQL block.
HR orcl > exec dbms_output.put_line('Average salary is: ' ||
get_avg_salary('SH_CLERK'))

Code: BEGIN
SELECT AVG(salary) INTO :avgsal
FROM
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 13
hr.employees
WHERE job_id = 'SH_CLERK'; END;

Average salary is: 3215

PL/SQL procedure successfully completed.

HR orcl >
It works fine and provides the correct result.
3. You will now attempt to change the salary of an employee although the function exists to
show the average of a salary for a job.
HR orcl > select salary from employees where email='PFAY';

SALARY
----------
6000

HR orcl > exec dbms_output.put_line('Average salary is: ' ||


get_avg_salary('SH_CLERK''; UPDATE hr.employees SET salary=4500
WHERE email=''PFAY''; COMMIT; END;--'))

Code: BEGIN
SELECT AVG(salary) INTO :avgsal
FROM
hr.employees
WHERE job_id = 'SH_CLERK'; UPDATE hr.employees SET
salary=4500 WHERE email='PFAY'; COMMIT; END;--'; END;

Average salary is: 3215

PL/SQL procedure successfully completed.

HR orcl >
The UPDATE statement was injected successfully.
4. Check the salary of the PFAY employee.
HR orcl > select salary from employees where email='PFAY';

SALARY
----------
4500
HR orcl >

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 14
The salary updated has also been committed. Multiple statements can be injected through
a PL/SQL block.
5. Reset the salary of the PFAY employee to 6000.
HR orcl > UPDATE hr.employees SET salary=6000 WHERE
email='PFAY';

1 row updated.

HR orcl > COMMIT;

Commit complete.

HR orcl >
6. Redefine the function so as to eliminate the SQL injection vulnerability by using an IN bind
argument, p_job, with the dynamic PL/SQL.
HR orcl > CREATE OR REPLACE FUNCTION get_avg_salary (p_job
VARCHAR2)
RETURN NUMBER
AS
avgsal employees.salary%TYPE;
v_blk VARCHAR2(4000);
BEGIN
v_blk := 'BEGIN
SELECT AVG(salary) INTO :avgsal
FROM hr.employees
WHERE job_id = :p_job; END;
';
EXECUTE IMMEDIATE v_blk
USING OUT avgsal, IN p_job;
dbms_output.put_line('Code: ' || v_blk);
RETURN avgsal;
END;
/
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16 17
Function created.

HR orcl >

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 15
7. Retest the new function and verify that the new code still works for a valid input.
HR orcl > exec dbms_output.put_line('Average salary is: ' ||
get_avg_salary('SH_CLERK'))

Code: BEGIN
SELECT AVG(salary) INTO :avgsal
FROM
hr.employees
WHERE job_id = :p_job; END;

Average salary is: 3215

PL/SQL procedure successfully completed.

HR orcl >
8. Retest the new function and verify that the new code does not work for an invalid input with
the same SQL injection attack.
HR orcl > select salary from employees where email='PFAY';

SALARY
----------
6000

HR orcl > exec dbms_output.put_line('Average salary is: ' ||


get_avg_salary('SH_CLERK''; UPDATE hr.employees SET salary=4500
WHERE email=''PFAY''; COMMIT; END;--'))

Code: BEGIN
SELECT AVG(salary) INTO :avgsal
FROM
hr.employees
WHERE job_id = :p_job; END;

Average salary is:

PL/SQL procedure successfully completed.

HR orcl >
The block executes but returns a NULL value for the average salary because no JOB_ID
column value matched the 'SH_CLERK''; UPDATE hr.employees SET
salary=4500 WHERE email=''PFAY''; COMMIT; END;-- ' value.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 16
9. Check the salary of the PFAY employee.
HR orcl > select salary from employees where email='PFAY';

SALARY
----------
6000

HR orcl >
The UPDATE statement was not executed. The SQL injection failed.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 17
Practice 2-5: Validating Input Using the DBMS_ASSERT Package
Overview
To guard against SQL injection in applications that do not use bind arguments with dynamic
SQL, you must filter and sanitize concatenated strings. The primary use case for dynamic SQL
with string concatenation is when an Oracle identifier (such as a table name or a user name) is
unknown at code compilation time.
DBMS_ASSERT is an Oracle-supplied PL/SQL package containing functions that can be used to
filter and sanitize input strings, particularly those that are meant to be used as Oracle identifiers.
In this practice, you will improve the CHANGE_PASSWORD procedure avoiding inappropriate input
values for the user name and the password. Using bind arguments like in the previous practice
is not possible in a DDL statement.
Use several DBMS_ASSERT functions to filter and sanitize the input values:
• ENQUOTE_NAME function to enclose the user’s name in double quotes.
• SCHEMA_NAME function to verify that the input string is an existing user name.
• SIMPLE_SQL_NAME function to verify that the password is a simple SQL name. The
input value must meet the following conditions:
− The name must begin with an alphabetic character. It may contain alphanumeric
characters as well as the characters _, $, and # in the second and subsequent
character positions.
− Quoted SQL names are also allowed.
− Quoted names must be enclosed in double quotes.
− Quoted names allow any characters between the quotes.
− Quotes inside the name are represented by two quote characters in a row, for
example, "a name with "" inside" is a valid quoted name.
− The input parameter may have any number of leading and/or trailing white space
characters.
− The length of the name is not checked.

Tasks
1. The input for the user name is user-supplied and so is in a normal identifier format. It needs
to be pre-processed using a conversion routine. Create a function that converts a normal
quoted value to an internal format value when a user-supplied value is to be used as a bind
argument for a lookup of an internal object name.
HR orcl > CONNECT / AS SYSDBA
Connected.
SYS orcl > CREATE OR REPLACE FUNCTION toInternal(Id varchar2)
RETURN varchar2 IS
Temp varchar2(40);
begin
Temp := trim(Id);
-- See comments in text re trimming
-- Remove quotes
IF substr(Temp,1,1) = '"' AND

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 18
substr(Temp,length(Temp),1) = '"' then
Temp := substr(Temp,2,length(Temp)-2);
else
-- Not quoted, so make sure is upper case
Temp := nls_upper(Temp);
end IF;
RETURN Temp;
end;
/
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16 17

Function created.

SYS orcl >


2. Redefine the CHANGE_PASSWORD procedure by using DBMS_ASSERT checking functions.
SYS orcl > SET SERVEROUTPUT ON
SYS orcl > CREATE OR REPLACE PROCEDURE change_password
(p_username IN VARCHAR2,
p_password IN VARCHAR2)
AUTHID CURRENT_USER
AS
v_stmt VARCHAR2(4000);
BEGIN
v_stmt :=
'ALTER USER '|| sys.dbms_assert.enquote_name(
sys.dbms_assert.schema_name(toInternal(p_username)),FALSE) ||
' IDENTIFIED BY '
|| sys.dbms_assert.simple_sql_name(p_password);
DBMS_Output.Put_Line('SQL stmt: '|| v_stmt);
EXECUTE IMMEDIATE v_stmt;
EXCEPTION WHEN OTHERS THEN
RAISE;
END;
/
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16 17 18
Procedure created.

SYS orcl >

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 19
3. Check that the procedure does not allow any invalid input value for the password.
SYS orcl > CONNECT hr
Enter password: ******
Connected.
HR orcl > SELECT default_tablespace from user_users
WHERE username='HR';
2
DEFAULT_TABLESPACE
------------------------------
USERS

HR orcl > EXEC sys.change_password('hr','hr default tablespace


system quota unlimited on system')
BEGIN sys.change_password('hr','hr default tablespace system
quota unlimited on system'); END;

*
ERROR at line 1:
ORA-44003: invalid SQL name
ORA-06512: at "SYS.CHANGE_PASSWORD", line 16
ORA-06512: at line 1

HR orcl > SELECT default_tablespace from user_users


WHERE username='HR';
2
DEFAULT_TABLESPACE
------------------------------
USERS

HR orcl >
4. Check that the procedure does not allow any invalid input value for the user name.
HR orcl > EXEC sys.change_password('hr oe','hr')
BEGIN sys.change_password('hr oe','hr'); END;

*
ERROR at line 1:
ORA-44001: invalid schema
ORA-06512: at "SYS.CHANGE_PASSWORD", line 16
ORA-06512: at line 1

HR orcl >

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 20
HR orcl > CONNECT hr
Enter password: ******
Connected.
HR orcl > EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 21
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 2: Security Requirements


Chapter 2 - Page 22
Practices for Lesson 3:
Security Solutions
Chapter 3

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 1
Practices for Lesson 3: Overview
Practices Overview
The first practice is a case study where for each of the following scenarios, you can suggest
security solutions. There is more than one correct solution for each scenario.
The other practices ask you to set up miscellaneous solutions appropriate to the situation.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 2
Practice 3-1: Choosing Oracle Solutions
Overview
In this practice, you suggest security solutions according to each scenario.

Scenario 1
Your company sends backup tapes off site to a disaster recovery site. Payment information
(including credit card numbers, customer names, and addresses) is in the data files included on
the tapes. The PCI_DSS requirement 3 says “Protect stored cardholder data” and requirement 4
says “Encrypt transmission of cardholder data across open, public networks.” The chief
information officer (CIO) wants to secure this information to prevent bad publicity if the backup
tapes are lost or stolen, or if any cardholder information is acquired by intercepting network
traffic.
Answer
Oracle Net Services enables you to use native network encryption for all Oracle Network traffic.
Oracle Advanced Security allows you to use Transparent Data Encryption (TDE); the sensitive
data in the database files will be encrypted. Thus, the image file backups will contain encrypted
data. Using RMAN with Oracle Secure Backup to tape will ensure that the tape backup files are
encrypted. Using RMAN can allow you to ensure that sensitive data is encrypted on backup sets
to disk.

Scenario 2
The network security officer has detected abnormal activity involving port 1521 through a
firewall and several desktop machines inside the firewall. The normal activity is for users outside
the firewall to contact an application server; therefore, all the database activity should be
through the application server and not on port 1521 through the firewall.
Answer
Port 1521 is the default port for the Oracle database listener. This may indicate an attempt to
attack the database. Some or all of the following protections can be implemented.
• Port 1521 should be closed through the firewall. The only outside users allowed
through the firewall contact the application server on its listener port (usually, this is an
HTTP or HTTPS port, not port 1521).
• The database can be configured to accept connections only from the application server
and to reject connections from any other machine.
• A good practice is to place the application server in one zone and the database in
another zone with a firewall between them.

Scenario 3
The company is considering outsourcing the DBA activities to a third party. The concern is that
a DBA who is not an employee will be able to access company-proprietary information,
customer financial information, and employee medical information.
Answer
There are powerful system privileges assigned to the DBA role that allow the DBA to view data.
There are two main solutions:
• Oracle Database Vault can be very easily configured to limit the data that the DBA can
view.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 3
• Use application-based encryption to encrypt sensitive data. Use a scheme that does
not allow the DBA to access the encryption keys stored in a keystore. Use the SYSKM
administrative privilege to hand over the key management to someone else.

Scenario 4
The current DBA has been granted the SYSDBA role to effectively start up and shut down the
database instance, and use RMAN to make database backups. There have been some
incidents in the past when company confidential information has been discovered on the Web.
How can the current DBA protect himself or herself from accusations that he or she is the most
likely suspect for any further security breaches because he or she had access?
Answer
There are two situations:
• The DBA has not yet migrated to unified auditing:
− He can enable the AUDIT_SYS_OPERATIONS parameter to record every command
that the SYS user issues.
− In addition, the DBA can send these records to the SYSLOG facility, setting the
AUDIT_SYSLOG_LEVEL parameter, so that the records can be written to an OS
account to which he or she has no access.
− In a CDB, the scope of the settings for this initialization parameter is the CDB.
Although the audit trail is provided per PDB in a CDB, this initialization parameter
cannot be configured for individual PDBs.
• The DBA has migrated to unified auditing, there is no action to take:
− The AUDIT_SYS_OPERATIONS and AUDIT_SYSLOG_LEVEL parameters have no
effect anymore.
− When SYS is connected as SYSDBA, SYSOPER, SYSBACKUP, SYSASM, SYSKM, or
SYSDG, it is subjected to all top-level statements, such as STARTUP, SHUTDOWN,
ALTER DATABASE, and ALTER SYSTEM, until the database opens.
− Unlike other Oracle Database components, Oracle RMAN events such as BACKUP,
RESTORE and RECOVER are systematically audited and this is not necessary to
create and enable an audit policy.
A complementary solution is to use Oracle Audit Vault to centralize all the audit records and
keep them in a safe repository.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 4
Practice 3-2: Configuring Monitoring Credentials Using Enterprise
Manager Cloud Control
Overview
In this practice, you act as an Enterprise Manager administrator. You access Oracle Enterprise
Manager Cloud Control 12c as the sysman user with the Oracle123 password. You create the
credorcl credential used for any connection as SYS user sharable in the database instance
orcl.

Tasks
1. You check that the Enterprise Manager Cloud Control is available. Click the Firefox icon on
the top panel (toolbar region) above the desktop to open a browser to access the Enterprise
Manager Cloud Control console.
2. Enter the URL for Cloud Control:
https://<em_server_hostname>.<domain>:7802/em. In the current setup, use
https://localhost:7802/em. If an error appears, you must first start the OMS, else
proceed directly with step 3.
a. Start the Enterprise Manager Repository Database em12rep if not started already.
$ . oraenv
ORACLE_SID = [orcl] ? em12rep
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as sysdba

Connected to an idle instance.


SYS em12rep > startup
ORACLE instance started.

Total System Global Area 400846848 bytes


Fixed Size 2271568 bytes
Variable Size 339740336 bytes
Database Buffers 50331648 bytes
Redo Buffers 8503296 bytes
Database mounted.
Database opened.
SYS em12rep > EXIT
$
b. Restart the OMS.
$ export OMS_HOME=/u01/app/oracle/product/middleware/oms
$ $OMS_HOME/bin/emctl start oms
Oracle Enterprise Manager Cloud Control 12c Release 2
Copyright (c) 1996, 2012 Oracle Corporation. All rights
reserved.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 5
Starting Oracle Management Server...
Starting WebTier...
WebTier Successfully Started
Oracle Management Server Successfully Started
Oracle Management Server is Up
WARNING: Limit of open file descriptors is found to be 1024.
The OMS has been started but it may run out of descriptors under
heavy usage.
For proper functioning of OMS, please set "ulimit -n" to be at
least 4096.
$
3. Most likely, you receive an “Untrusted Connection’ message and you need to add a security
exception.
a. At the end of the alert box, click I Understand the Risks.
b. At the bottom of the page, click Add Exception.
c. Confirm that “Permanently store this exception” is selected in your training environment
and click Confirm Security Exception.
4. The Enterprise Manager Cloud Control console appears.
5. Enter sysman in the User Name field and Oracle123 in the Password field. Then click
Login.
6. The first time a new user logs in to Enterprise Manager, a page asks you to accept the
license agreement. You have to accept only once. Then each time you will log in to
Enterprise Manager, you will not get the license agreement page.

7. Then the “Select Enterprise Manager Home” page appears with choices, such as:
− Summary
− Databases
− Incidents
− SOA

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 6
− Middleware
− Composite Application
− Service Request
− Services
− Business Applications
− Compliance Dashboard
Each choice has a Preview and a Select As My Home button.
The page also has global menus with the following choices: Enterprise, Targets,
Favorites, History, and Search Target Name (next to the search entry field). Each of the
menu items has drop-down menus with further choices.
Preview any images that interest you.
8. Click “Select As My Home” in the top right hand corner of the page. After being successfully
set, it informs you how to change it.

9. Add the orcl Database Instance as a new target in Enterprise Manager Cloud Control.
a. In the top right hand corner of the page, click the “Setup” > “Add Target” > “Add
Targets Manually”.

b. In “Add Targets Manually”, choose “Add Non-Host Targets Using Guided Process
(Also Adds Related Targets)”. Then in “Target Types”, choose “Oracle Database,
Listener and Automatic Storage Management” for “Target Type”. Click “Add Using

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 7
Guided Discovery …” button.

c. In “Add Database Instance target: Specify Host”, click the magnifying glass to find your
host. Select your host, then click “Continue”.

d. In the “Databases” list, deselect all databases except orcl. Deselect the listener.
1) Unlock the DBSNMP user. This user is the monitoring user used to test the
connection once the target is being added. Open a terminal window.
$ . oraenv
ORACLE_SID = [em12rep] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as sysdba

Connected to:
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 8
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
SYS orcl > alter user dbsnmp identified by oracle_4U account
unlock;

User altered.

SYS orcl > EXIT


$
2) Enter oracle_4U for the “Monitor Password”.

e. Click the “Test Connection” button. You should receive the following message:

f. Click the “Finish” then “Save” buttons to complete the operation, and finally “OK”.
10. To create the monitoring credentials for your orcl database credentials, navigate to Setup
> Security > Named Credentials. Click Create.
a. Enter the following values, then complete the Access Control section:
Field Choice or Value
General Properties
Credential Name credorcl
Credential description Credentials for Database
Authenticating Target Type Database Instance
Credential type Database Credentials
Scope Target
Target type Database Instance
Target Name orcl (Click the magnifying glass

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 9
Field Choice or Value
to find orcl and select)

Credential Properties
Username SYSTEM
Password oracle_4U
Confirm Password oracle_4U
Role NORMAL
b. Specify who can share, edit or even delete this shared credential by using one of the
three privileges (Full, Edit, View).
• SYS user with Full privilege will be able to use, edit, and delete the credential.
• SYSTEM user with Edit privilege will be able to use and edit the credential.
1) Click “Add Grant” then select the user SYS to be added in the Access Control list.
2) Repeat this operation to add the user SYSTEM.
By default, the selected users are granted the View privilege only.
3) To grant Full privilege to SYS, select the SYS user and click “Change Privilege”.
Choose Full and click OK.
4) To grant Edit privilege to SYSTEM, select the SYSTEM user and click “Change
Privilege”. Choose Edit and click OK.
11. Test against the orcl database instance, click Test and Save until you get the following
message: Confirmation Credential Operation Successful. This means that the credential
was successful and saved.
12. Test the credorcl named credential to connect to orcl database.
a. Click Targets and then select Databases.
b. Click the “Search List” radio button.
c. Click the orcl link.
d. Click Administration, then Security and then Users. The named credential
credorcl is displayed.
e. Click Login if you accept this named credential to log in the orcl database else
choose New to define new login username and password.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 10
Practice 3-3: Viewing Compliance Frameworks
Overview
In this practice, you will view the PCI DSS (Version 2) compliance framework and the Oracle
Generic Compliance Framework supplied in Enterprise Manager Cloud Control. With the
compliance feature, the former policies and groups of policies in Enterprise Manager Grid
Control have been reinvented in a new hierarchy defined in Enterprise Manager Cloud Control
12c. This starts off with rules that are specific items to check for a particular target type.
What are the rules: they are checks, tests performed against the environment, for example — Is
a parameter value set properly as per best practice guidelines?
There are three kinds of rules:
• The first one: the repository rule which is very similar to the user-defined policy that we
had in Enterprise Manager 11g. A repository rule is evaluated against the repository
data only when the data changes underneath, but it uses the current data that exists in
the repository. And we provide a repository browser to aid in rule creation to build the
query.
• The second type of rule is the real-time rule that activates the agent to perform real-
time change detection for file actions, for schema actions, process actions to detect
when, where a particular action took place and who performed the action. And again
you can apply the rule to a particular target type. This also detects unauthorized
changes and correlate them to the Change Management System.
• The third type of rule is the Weblogic rule that performs BEA Guardian health checks
integrated in Enterprise Manager. You can apply out-of-the-box 1300 rules to a
particular target type.
To glue all the different compliance standards for particular target types together, you use the
compliance framework. The frameworks can help the administrators to create rules and
standards; the compliance and security officers and auditors can take advantage of the
standards and frameworks to manage compliance reports.

Tasks
1. To review predefined compliance objects, navigate to Enterprise > Compliance > Library.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 11
2. The Compliance Library has several tabbed pages. A list of predefined compliance
frameworks appears.

3. On the Compliance Frameworks tabbed page, select a framework that interests you and
click Show Details. Select the PCI DSS (Version 2.0) compliance framework.
4. Expand the hierarchy nodes several levels and review the descriptions; then click Done.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 12
5. Back on the Compliance Frameworks tabbed page, select the Oracle Generic
Compliance Framework.

6. The hierarchy nodes displays several levels. Review the descriptions; then click Done.

7. Click the Compliance Standards tab. There are quite a few standards, each for a specific
target type.

8. Review the predefined standards and then select Basic Security Configuration For
Oracle Database (which is applicable to the Database Instance target type).

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 13
9. Expand the hierarchy node. Review the descriptions; then click Done.

10. Select High Security Configuration For Oracle Database (which is applicable to the
Database Instance target type).

11. Review any other descriptions that may interest you, and then click Done.

12. Click the Compliance Standard Rules tab.


Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 14
13. There are so many rules that you decide to use the Search functionality for finding the
IFILE Referenced File Permission. Click the ">" icon before Search. Enter %IFILE% as
Rule and click Search. Then select IFILE Referenced File Permission.

14. Scroll to review all details including the SQL Source of how this rule is checked in the data
dictionary.

15. Click Done when you are finished reviewing the rule details.
16. Click Enterprise then Summary to return to the Enterprise Summary page.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 15
Practice 3-4: Maintaining Integrity by Using Constraints
Overview
In this practice, you will use CHECK constraint and referential constraints to control data update
and deletion.

Tasks
1. Display the existing constraints on HR.EMPLOYEES table in the orcl database.
$ sqlplus hr
Enter password: ******

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
HR orcl > COL table_name format a10
HR orcl > COL key_name format a14
HR orcl > COL referencing_table format a12
HR orcl > COL foreign_key_name format a14
HR orcl > COL fk_status format a8
HR orcl > SELECT A.TABLE_NAME table_name,
A.CONSTRAINT_NAME key_name,
B.TABLE_NAME referencing_table,
B.CONSTRAINT_NAME foreign_key_name,
B.STATUS
FROM USER_CONSTRAINTS A, USER_CONSTRAINTS B
WHERE A.CONSTRAINT_NAME = B.R_CONSTRAINT_NAME
AND A.TABLE_NAME = 'EMPLOYEES'
ORDER BY 1, 2, 3, 4;
2 3 4 5 6 7 8 9

TABLE_NAME KEY_NAME REFERENCING_ FOREIGN_KEY_NA STATUS


---------- -------------- ------------ -------------- --------
EMPLOYEES EMP_EMP_ID_PK DEPARTMENTS DEPT_MGR_FK ENABLED
EMPLOYEES EMP_EMP_ID_PK EMPLOYEES EMP_MANAGER_FK ENABLED
EMPLOYEES EMP_EMP_ID_PK JOB_HISTORY JHIST_EMP_FK ENABLED

HR orcl >
2. Insert a new employee in the HR.EMPLOYEES table as follows:
HR orcl > INSERT INTO hr.employees (EMPLOYEE_ID, LAST_NAME ,
EMAIL, HIRE_DATE , JOB_ID, DEPARTMENT_ID)

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 16
VALUES (9, 'VERRIER', 'VERRIER@test', sysdate,
'ST_MAN',99);
2 3 INSERT INTO hr.employees (EMPLOYEE_ID, LAST_NAME ,
EMAIL,
*
ERROR at line 1:
ORA-02291: integrity constraint (HR.EMP_DEPT_FK) violated -
parent key not found

HR orcl >
The statement fails because the department does not exist. The referential constraint
controls that invalid data is not inserted into the table.
3. Delete the department 30 in the HR.DEPARTMENTS table as follows:
HR orcl > DELETE FROM hr.departments WHERE department_id=30;
DELETE FROM hr.departments WHERE department_id=30
*
ERROR at line 1:
ORA-02292: integrity constraint (HR.EMP_DEPT_FK) violated -
child record found

HR orcl >
The statement fails because the referential constraint does not permit that the department
deletion deletes all employees working in that department in cascade. The referential
constraint controls that you first move the employees working in this department to another
department before you can delete the department.
a. Move the employees to another department.
HR orcl > UPDATE hr.employees SET department_id=40
WHERE department_id=30;
2
6 rows updated.

HR orcl >
b. Reattempt to remove the department.
HR orcl > DELETE FROM hr.departments WHERE department_id=30;
DELETE FROM hr.departments WHERE department_id=30
*
ERROR at line 1:
ORA-02292: integrity constraint (HR.JHIST_DEPT_FK) violated -
child record
found

HR orcl >

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 17
The statement fails because there is another referential constraint in another table. The
JOB_HISTORY table contains the history of employees who had worked in that department.
First remove the history records related to these employees.
HR orcl > DELETE FROM hr.job_history WHERE department_id=30;

6 rows deleted.

HR orcl > DELETE FROM hr.departments WHERE department_id=30;

1 row deleted.

HR orcl > ROLLBACK;

Rollback complete.

HR orcl >
4. Insert a new employee with a salary below the minimum legally allowed.
HR orcl > INSERT INTO hr.employees (EMPLOYEE_ID,
LAST_NAME,EMAIL,
HIRE_DATE, JOB_ID, SALARY, DEPARTMENT_ID)
VALUES (9, 'VERRIER', 'VERRIER@test', sysdate,
'ST_MAN',0, 30);
2 3 4 INSERT INTO hr.employees (EMPLOYEE_ID, LAST_NAME
, EMAIL,
*
ERROR at line 1:
ORA-02290: check constraint (HR.EMP_SALARY_MIN) violated

HR orcl >
The statement fails because a CHECK constraint checks that the salary is higher than a
minimum. Invalid value cannot be inserted into the table.
a. Examine the HR.SALARY_MIN constraint.
HR orcl >
COL table_name format a10
HR orcl >
COL search_condition format a14
HR orcl >
COL constraint_name format a18
HR orcl >
SELECT CONSTRAINT_NAME, CONSTRAINT_TYPE, TABLE_NAME,
SEARCH_CONDITION
FROM user_constraints
WHERE CONSTRAINT_NAME='EMP_SALARY_MIN';
2 3 4
CONSTRAINT_N C TABLE_NAME SEARCH_CONDITI
--------------- - ---------- --------------
EMP_SALARY_MIN C EMPLOYEES salary > 0
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 18
HR orcl >
b. Insert a new employee with a salary above the minimum legally allowed.
HR orcl > INSERT INTO hr.employees (EMPLOYEE_ID, LAST_NAME ,
EMAIL, HIRE_DATE , JOB_ID, SALARY,
DEPARTMENT_ID)
VALUES (9, 'VERRIER', 'VERRIER@test', sysdate,
'ST_MAN',500, 30);
2 3 4
1 row created.

HR orcl > ROLLBACK;

Rollback complete.

HR orcl >

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 19
Practice 3-5: Maintaining Integrity by Using Triggers
Overview
In this practice, you will use triggers to maintain the stock inventory when products are sold.

Tasks
1. Find if any trigger already exist to maintain the stock inventory when products are sold.
HR orcl > CONNECT oe
Enter password: ******
Connected.
OE orcl > SELECT table_name, trigger_name, status, trigger_body
FROM user_triggers
WHERE trigger_name like 'STOCK%';
2 3
no rows selected

OE orcl >
2. Create a simple trigger (for test purposes only) that updates the QUANTITY_ON_HAND in
the stock when ordering product is 3515.
CREATE OR REPLACE TRIGGER oe.update_stock
AFTER INSERT ON order_items
FOR EACH ROW
WHEN (NEW.product_id = 3515)
DECLARE
prod_id NUMBER;
BEGIN
prod_id := :NEW.product_id;
UPDATE inventories
SET quantity_on_hand = quantity_on_hand - 100
WHERE product_id = prod_id;
END;
/
OE orcl > CREATE OR REPLACE TRIGGER oe.update_stock
AFTER INSERT ON order_items
FOR EACH ROW
WHEN (NEW.product_id = 3515)
DECLARE
prod_id NUMBER;
BEGIN
prod_id := :NEW.product_id;
UPDATE inventories
SET quantity_on_hand = quantity_on_hand - 100

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 20
WHERE product_id = prod_id;
END;
/
2 3 4 5 6 7 8 9 10 11 12 13
Trigger created.

OE orcl >
3. Display the amount of remaining items of the product ID 3515 in the stock.
OE orcl > SELECT QUANTITY_ON_HAND FROM OE.INVENTORIES
WHERE PRODUCT_ID=3515;
2
QUANTITY_ON_HAND
----------------
213

OE orcl >
4. Order 100 items of the product ID 3515.
OE orcl > INSERT INTO oe.orders (
ORDER_ID, ORDER_DATE, CUSTOMER_ID, ORDER_TOTAL)
VALUES (17, sysdate, 980, 100);
2 3
1 row created.

OE orcl > INSERT INTO oe.order_items


VALUES (17, 1, 3515, 1, 100);
2
1 row created.

OE orcl > COMMIT;

Commit complete.

OE orcl >

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 21
5. Verify that the stock inventory has been updated and that the amount of remaining items of
the product ID 3515 in the stock has decreased by 100.
OE orcl > SELECT QUANTITY_ON_HAND FROM OE.INVENTORIES
WHERE PRODUCT_ID=3515;

QUANTITY_ON_HAND
----------------
113

OE orcl >

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 22
Practice 3-6: Controlling Data Access by Using Views
Overview
In this practice, you create different views based on the HR.EMPLOYEES and HR.DEPARTMENTS
tables displaying selected rows and columns according to the user’s role in the company. JIM,
the HR assistant, should be able to view all information of any employee except those of the
managers. TOM should only be allowed to view the first and last names, and the department ID
and name where any employee works.

Tasks
1. Create the HR_ASSISTANT view.
OE orcl > CONNECT HR
Enter password: ******
Connected.
HR orcl > CREATE VIEW hr_assistant
AS SELECT * FROM HR.EMPLOYEES
WHERE job_id NOT IN
(SELECT job_id FROM HR.JOBS WHERE
job_title='President');
2 3 4
View created.

HR orcl > GRANT SELECT ON hr.hr_assistant TO jim;

Grant succeeded.

HR orcl >
2. Create the HR_CLERK view.
HR orcl > CREATE VIEW hr_clerk
AS SELECT first_name, last_name, department_name
FROM hr.employees e, hr.departments d
WHERE e.DEPARTMENT_ID = d.DEPARTMENT_ID;
2 3 4
View created.

HR orcl > GRANT SELECT ON hr.hr_clerk TO tom, jim;

Grant succeeded.

HR orcl >
3. Verify that only JIM can view all information of any employees except the president, and
that TOM can only view some information of the employees.
HR orcl > CONNECT jim
Enter password: ******
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 23
Connected.
JIM orcl > SELECT * FROM hr.employees;
SELECT * FROM hr.employees
*
ERROR at line 1:
ORA-00942: table or view does not exist

JIM orcl > SELECT count(*) FROM hr.hr_assistant;

COUNT(*)
----------
106

JIM orcl >


Notice that the view returns 106 rows and not 107 rows.
JIM orcl > CONNECT tom
Enter password: ******
Connected.
TOM orcl > SELECT * FROM hr.employees;
SELECT * FROM hr.employees
*
ERROR at line 1:
ORA-00942: table or view does not exist

TOM orcl > SELECT * FROM hr.hr_assistant;


SELECT * FROM hr.employees
*
ERROR at line 1:
ORA-00942: table or view does not exist

TOM orcl > SELECT * FROM hr.hr_clerk WHERE


last_name='Greenberg';

FIRST_NAME LAST_NAME DEPARTMENT_NAME


-------------------- ------------------------- -----------------
Nancy Greenberg Finance

TOM orcl > SELECT salary FROM hr.hr_clerk


WHERE last_name='Greenberg';
SELECT salary FROM hr.hr_clerk WHERE last_name='Greenberg'
*
ERROR at line 1:

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 24
ORA-00904: "SALARY": invalid identifier

TOM orcl >


4. Drop the views.
TOM orcl > CONNECT hr
Enter password: ******
Connected.
HR orcl > DROP VIEW hr.hr_assistant;

View dropped.

HR orcl > DROP VIEW hr.hr_clerk;

View dropped.

HR orcl > EXIT


$
.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 25
Practice 3-7: Using Database Vault Realms to Disallow Access to
Objects
Overview
In this practice, you will verify that Database Vault realms configuration can disallow HR from
viewing any data in his own schema objects, protecting objects from any user being granted
system and or object privileges.

Tasks
1. Make sure you are in the ~/labs/DV directory and your environment points to the orcl
instance.
$ cd ~/labs/DV
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
2. Run the DV_setup.sh script to configure Database Vault in the database. This may take
several minutes to complete.
$ ./DV_setup.sh

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options

drop user sec_admin cascade


*
ERROR at line 1:
ORA-01918: user 'SEC_ADMIN' does not exist

drop user accts_admin cascade


*
ERROR at line 1:
ORA-01918: user 'ACCTS_ADMIN' does not exist

User created.

User created.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 26
Grant succeeded.

PL/SQL procedure successfully completed.

Connected.

PL/SQL procedure successfully completed.


$
3. Restart the instance.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SYS orcl > shutdown immediate
Database closed.
Database dismounted.
ORACLE instance shut down.
SYS orcl > startup
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2289400 bytes
Variable Size 264241416 bytes
Database Buffers 226492416 bytes
Redo Buffers 8036352 bytes
Database mounted.
Database opened.
SYS orcl > exit
$
4. Run the DV_create_realm.sh script to create a Database Vault realm protecting the
HR.EMPLOYEES and HR.DEPARTMENTS tables from any access, even from HR access.
$ ./DV_create_realm.sh

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Oracle Database Vault and Real Application Testing
options

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 27
PL/SQL procedure successfully completed.

PL/SQL procedure successfully completed.

PL/SQL procedure successfully completed.


$
Notice that the banner shows the Oracle Database Vault option enabled.
5. Connect as HR to verify that HR does not have any access to the HR.EMPLOYEES and
HR.DEPARTMENTS tables.
$ sqlplus hr
Enter password: ******
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Oracle Database Vault and Real Application Testing
options

HR orcl >
HR orcl > select * from hr.employees;
select * from hr.employees
*
ERROR at line 1:
ORA-01031: insufficient privileges

HR orcl > select * from hr.departments;


select * from hr.departments
*
ERROR at line 1:
ORA-01031: insufficient privileges

HR orcl >
6. Verify that HR can access to other tables owned in his schema.
HR orcl > select * from hr.jobs;

JOB_ID JOB_TITLE MIN_SALARY MAX_SALARY


---------- ------------------------------- ---------- ---------
AD_PRES President 20080 40000
AD_VP Administration Vice President 15000 30000
AD_ASST Administration Assistant 3000 6000
FI_MGR Finance Manager 8200 16000
FI_ACCOUNT Accountant 4200
9000
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 28
AC_MGR Accounting Manager 8200 16000
AC_ACCOUNT Public Accountant 4200 9000
SA_MAN Sales Manager 10000 20080
SA_REP Sales Representative 6000
12008
PU_MAN Purchasing Manager 8000 15000
PU_CLERK Purchasing Clerk 2500 5500
ST_MAN Stock Manager 5500 8500
ST_CLERK Stock Clerk 2008 5000
SH_CLERK Shipping Clerk 2500 5500
IT_PROG Programmer 4000
10000
MK_MAN Marketing Manager 9000 15000
MK_REP Marketing Representative 4000 9000
HR_REP Human Resources Representative 4000 9000
PR_REP Public Relations Representative 4500 10500

19 rows selected.

HR orcl >
7. Select from a non-existing table.
HR orcl > select * from hr.test_tab;
select * from hr.test_tab
*
ERROR at line 1:
ORA-00942: table or view does not exist

HR orcl > EXIT


$
The error message is not the same as in task 5 or task 6.
8. Run the DV_drop_realm.sh script to remove the Database Vault protection on the
HR.EMPLOYEES and HR.DEPARTMENTS tables.
$ ./DV_drop_realm.sh

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Oracle Database Vault and Real Application Testing
options

PL/SQL procedure successfully completed.


$
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 29
9. Run the DV_disable.sh script to disable Database Vault in the database.
$ ./DV_disable.sh

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Oracle Database Vault and Real Application Testing
options

Connected.

PL/SQL procedure successfully completed.


$
10. Restart the instance.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Oracle Database Vault and Real Application Testing
options

SYS orcl > shutdown immediate


Database closed.
Database dismounted.
ORACLE instance shut down.
SYS orcl > startup
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2289400 bytes
Variable Size 264241416 bytes
Database Buffers 226492416 bytes
Redo Buffers 8036352 bytes
Database mounted.
Database opened.
SYS orcl > exit
Disconnected from Oracle Database 12c Enterprise Edition Release
12.1.0.1.0 - 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 30
Notice that the banner does not show the Oracle Database Vault option anymore. It is
disabled.
11. Verify the HR can view the tables he is the owner of.
$ sqlplus hr

Enter password: ******

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

HR orcl > SELECT count(*) FROM hr.employees;

COUNT(*)
----------
107

HR orcl > exit


Disconnected from Oracle Database 12c Enterprise Edition Release
12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 31
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 3: Security Solutions


Chapter 3 - Page 32
Practices for Lesson 4:
Implementing Basic Database
Security
Chapter 4

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 1
Practices for Lesson 4: Overview
Practices Overview
In these practices, you will implement the basic database security features and investigate if
your databases are compliant with the Basic Security Configuration For Oracle Database
compliance standards.
Note: From now on, in the following practices, the SQL prompt will be displayed with the default
value “SQL>” to make the practice documents reading easier.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 2
Practice 4-1: Creating the Security Officer Account
Overview
In this practice, you will create the security officer account that has privileges to create user
accounts, grant privileges, and administer fine-grained auditing and fine-grained access control
in the orcl database.
In this and subsequent practices, security is administered by a single user. Be sure to use this
account whenever possible.

Tasks
1. Connect as SYSTEM in orcl instance to create the SEC user, giving it the following
properties:
− Name is SEC
− Password is oracle_4sec
− This user must be able to allocate space in the USERS tablespace for security
related tables, and objects
− Can create a session and grant the privilege to other users to create a session
− Can select from any table in the database, including the SYS schema
− Can create or drop any context in the database
− Can create, alter, and drop users
− Can create roles and can alter and drop any roles
− Can create tables, procedures, and triggers (including the ADMINISTER DATABASE
TRIGGER privilege, which allows the user to create database triggers)
− Can administer OS file access through DIRECTORY objects
− Can administer profiles
− Can execute audit commands
− Can execute ALTER SYSTEM commands (allows the user to change initialization
parameters)
− Can grant and revoke any object privilege
− Can execute DBMS_SESSION. This privilege is granted from the SYS user to
PUBLIC by default
a. Use the oraenv utility to set the ORACLE_SID environment variable to the orcl value.
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
b. Execute the create_sec.sh script. Make sure you are in the ~/labs/USERS
directory.
$ cd ~/labs/USERS
$ ./create_sec.sh

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 3
SQL*Plus: Release 12.1.0.1.0 Production on Thu Jun 13 23:07:05
2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> DROP USER sec CASCADE;


DROP USER sec CASCADE
*
ERROR at line 1:
ORA-01918: user 'SEC' does not exist

SQL> CREATE USER sec IDENTIFIED BY oracle_4sec


2 DEFAULT TABLESPACE USERS
3 QUOTA UNLIMITED ON USERS;

User created.

SQL>
SQL> GRANT create session
2 TO sec
3 WITH ADMIN OPTION;

Grant succeeded.

SQL>
SQL> GRANT select_catalog_role, select any table,
2 create any context, drop any context,
3 create user, alter user, drop user,
4 create role, alter any role, drop any role,
5 create table, create procedure,
6 create any trigger, administer database trigger,
7 create any directory, alter profile, create profile,
8 drop profile, audit system, alter system,
9 grant any object privilege, grant any privilege,
grant any role

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 4
10 TO sec;

Grant succeeded.

SQL>
SQL> GRANT execute on DBMS_SESSION to sec;

Grant succeeded.

SQL> GRANT execute on UTL_FILE to sec;

Grant succeeded.

SQL>
SQL> EXIT
Disconnected from Oracle Database 12c Enterprise Edition Release
12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
$
2. The security officer immediately takes some actions due to basic security issues.
a. Sample schema accounts HR, OE, SH, PM, BI, and IX are well known; they should not
be installed unless needed. If they are not needed, the passwords should be expired
and the accounts locked when not being used. After a password is marked as expired,
the password must be changed before the account can be used again.
$ sqlplus sec
Enter password: *******

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
SQL> ALTER USER PM PASSWORD EXPIRE ACCOUNT LOCK;

User altered.

SQL> ALTER USER BI PASSWORD EXPIRE ACCOUNT LOCK;

User altered.

SQL> ALTER USER IX PASSWORD EXPIRE ACCOUNT LOCK;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 5
User altered.

SQL>
b. Because it is dangerous to work with UTL_FILE_DIR parameter set to *, you reset the
UTL_FILE_DIR parameter to NULL, so that no one can read from or write to any
directory using the UTL_FILE package. Then you configure the database so that users
can write to the /home/oracle/student directory:
1) Reset the UTL_FILE_DIR parameter to NULL.
SQL> ALTER SYSTEM SET utl_file_dir='' SCOPE=spfile;

System altered.

SQL> CONNECT / AS SYSDBA


Connected.
SQL> SHUTDOWN IMMEDIATE
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> STARTUP
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2290024 bytes
Variable Size 264244888 bytes
Database Buffers 226492416 bytes
Redo Buffers 8032256 bytes
Database mounted.
Database opened.
SQL>
2) Configure the database to allow writes using the DIRECTORY objects. Create the
/home/oracle/student directory on the OS. Create a directory object for the
/home/oracle/student directory. You can later grant READ or WRITE
privileges to the directory to certain users.
SQL> !mkdir /home/oracle/student

SQL> CONNECT sec


Enter password: *******
Connected.
SQL> CREATE DIRECTORY student AS '/home/oracle/student';

Directory created.

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 6
3) Test the configuration. The following PL/SQL block writes the current database
time to the db_time.lst file. The PL/SQL block accepts a single parameter: the
uppercase name of the directory object that you want to write to (STUDENT).
SQL> DECLARE
file_handle UTL_FILE.FILE_TYPE;
file_mode VARCHAR2(1) := 'w';
file_name VARCHAR2(15) := 'db_time.lst';
file_location VARCHAR2(80) := '&1';
file_data VARCHAR2(100);
BEGIN
file_handle := utl_file.fopen(file_location, file_name,
file_mode);
IF utl_file.is_open(file_handle) THEN
file_data := current_timestamp;
utl_file.put(file_handle, file_data);
utl_file.fclose(file_handle);
ELSE
dbms_output.put_line('The file was not opened.');
END IF;
END;
/
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16 17 Enter value for 1: /home/oracle
old 5: file_location VARCHAR2(80) := '&1';
new 5: file_location VARCHAR2(80) := '/home/oracle';
DECLARE
*
ERROR at line 1:
ORA-29280: invalid directory path
ORA-06512: at "SYS.UTL_FILE", line 41
ORA-06512: at "SYS.UTL_FILE", line 478
ORA-06512: at line 8

SQL>
Notice the error. The /home/oracle OS directory is not a directory object defined in the
database. Use a directory defined in the database.
SQL> DECLARE
file_handle UTL_FILE.FILE_TYPE;
file_mode VARCHAR2(1) := 'w';
file_name VARCHAR2(15) := 'db_time.lst';
file_location VARCHAR2(80) := '&1';
file_data VARCHAR2(100);
BEGIN
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 7
file_handle := utl_file.fopen(file_location, file_name,
file_mode);
IF utl_file.is_open(file_handle) THEN
file_data := current_timestamp;
utl_file.put(file_handle, file_data);
utl_file.fclose(file_handle);
ELSE
dbms_output.put_line('The file was not opened.');
END IF;
END;
/
Enter value for 1: STUDENT
old 5: file_location VARCHAR2(80) := '&1';
new 5: file_location VARCHAR2(80) := 'STUDENT';

PL/SQL procedure successfully completed.

SQL>
4) Verify that the db_time.lst file is written to the directory after executing the
PL/SQL block.
SQL> HOST cat /home/oracle/student/db_time.lst
05-JUL-13 10.01.49.700632000 AM +00:00
SQL>
c. Do any users in your database have the DBA role, SYSOPER, SYSDBA, SYSKM, SYSDG,
or SYSBACKUP privilege that they do not need? Fix this problem.
1) Find users who are granted the DBA role by querying the DBA_ROLE_PRIVS view.
SQL> COL grantee FORMAT a12
SQL> COL granted_role FORMAT a12
SQL> SELECT * FROM dba_role_privs WHERE granted_role='DBA';

GRANTEE GRANTED_ROLE ADM DEF COM


-------------------- ---------------------- --- --- ---
SYS DBA YES YES NO
SCOTT DBA NO YES NO
SYSTEM DBA YES YES YES

SQL>
2) SCOTT has no need for the DBA role because this is a demo account that has been
locked and the password expired. Revoke the DBA role from SCOTT. To revoke a
role, you must have been granted the role with ADMIN OPTION. You can revoke
any role if you have the GRANT ANY ROLE system privilege.
SQL> REVOKE DBA FROM scott;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 8
Revoke succeeded.

SQL> SELECT * FROM dba_role_privs WHERE granted_role='DBA';

GRANTEE GRANTED_ROLE ADM DEF COM


-------------------- ---------------------- --- --- ---
SYS DBA YES YES NO
SYSTEM DBA YES YES YES

SQL>
d. The users with the SYSDBA or SYSOPER privilege are listed in the oracle password file.
SCOTT and HR have no need for these privileges. Only SYSDBA can GRANT or REVOKE
these privileges.
SQL> COL username FORMAT a12
SQL> SELECT * FROM v$pwfile_users;

USERNAME SYSDB SYSOP SYSAS SYSBA SYSDG SYSKM CON_ID


------------ ----- ----- ----- ----- ----- ----- ----------
SYS TRUE TRUE FALSE FALSE FALSE FALSE 0
SYSDG FALSE FALSE FALSE FALSE TRUE FALSE 0
SYSBACKUP FALSE FALSE FALSE TRUE FALSE FALSE 0
SYSKM FALSE FALSE FALSE FALSE FALSE TRUE 0
SCOTT TRUE FALSE FALSE FALSE FALSE FALSE 0
HR FALSE TRUE FALSE FALSE FALSE FALSE 0

6 rows selected.

SQL> REVOKE SYSOPER FROM hr;


REVOKE SYSOPER FROM hr
*
ERROR at line 1:
ORA-01031: insufficient privileges

SQL> CONNECT / AS SYSDBA


Connected.
SQL> REVOKE SYSOPER FROM hr;

Revoke succeeded.

SQL> REVOKE SYSDBA FROM scott;

Revoke succeeded.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 9
SQL>
SQL> SELECT * FROM v$pwfile_users;

USERNAME SYSDB SYSOP SYSAS SYSBA SYSDG SYSKM CON_ID


------------ ----- ----- ----- ----- ----- ----- ---------
SYS TRUE TRUE FALSE FALSE FALSE FALSE 0
SYSDG FALSE FALSE FALSE FALSE TRUE FALSE 0
SYSBACKUP FALSE FALSE FALSE TRUE FALSE FALSE 0
SYSKM FALSE FALSE FALSE FALSE FALSE TRUE 0

SQL>
1) Do any users in your database have the RESOURCE role? If there are some users
being granted the RESOURCE role, check that the UNLIMITED TABLESPACE
system privilege is not granted. In Oracle Database 12c, the RESOURCE role is not
granted the UNLIMITED TABLESPACE system privilege anymore.
SQL> CONNECT sec
Enter password: *******
Connected.
SQL> SELECT grantee, privilege, granted_role
FROM dba_sys_privs JOIN dba_role_privs USING (grantee)
WHERE granted_role='RESOURCE'
AND privilege = 'UNLIMITED TABLESPACE';

GRANTEE PRIVILEGE GRANTED_ROLE


-------------- -------------------- ---------------------
HR UNLIMITED TABLESPACE RESOURCE
OE UNLIMITED TABLESPACE RESOURCE
BI UNLIMITED TABLESPACE RESOURCE
IX UNLIMITED TABLESPACE RESOURCE
SH UNLIMITED TABLESPACE RESOURCE
PM UNLIMITED TABLESPACE RESOURCE
XDB UNLIMITED TABLESPACE RESOURCE
OJVMSYS UNLIMITED TABLESPACE RESOURCE
MDSYS UNLIMITED TABLESPACE RESOURCE
APEX_040200 UNLIMITED TABLESPACE RESOURCE
SYS UNLIMITED TABLESPACE RESOURCE
OUTLN UNLIMITED TABLESPACE RESOURCE
CTXSYS UNLIMITED TABLESPACE RESOURCE
DVSYS UNLIMITED TABLESPACE RESOURCE
LBACSYS UNLIMITED TABLESPACE RESOURCE

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 10
15 rows selected.

SQL>
2) Find other users who may be granted the UNLIMITED TABLESPACE privilege by
querying the DBA_SYS_PRIVS view.
SQL> SELECT grantee FROM dba_sys_privs
WHERE privilege = 'UNLIMITED TABLESPACE'
AND grantee NOT IN (SELECT grantee
FROM dba_sys_privs JOIN dba_role_privs USING (grantee)
WHERE granted_role='RESOURCE'
AND privilege = 'UNLIMITED TABLESPACE');

2 3 4 5 6
GRANTEE
--------------------
TOM
SI_INFORMTN_SCHEMA
WMSYS
DBSNMP
ORDSYS
ORDDATA
SYSTEM
SYSBACKUP

8 rows selected.

SQL>
3) If necessary, revoke the UNLIMITED TABLESPACE privilege from TOM user.
SQL> REVOKE unlimited tablespace FROM tom;

Revoke succeeded.

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 11
Practice 4-2: Managing Secure Passwords
Overview
In this practice, the security officer will ensure that the use of simple passwords is not possible
and that all users will follow strong password management rules. Oracle Database 12c provides
password management by default with one of the three password verification function effective
by default.

Tasks
1. Determine what limits are applied with the DEFAULT profile. Then, set up password
management by performing the following steps:
a. List the rows related to password management from the current profiles in the system.
Use the SEC account. Save the command that you use.
$ sqlplus sec
Enter password: ******

Last Successful login time: Tue May 21 2013 03:58:51 +00:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> set pagesize 40
SQL> col profile format A10
SQL> col limit format A22
SQL> col resource_name format A25
SQL> SELECT profile, resource_name, limit
FROM dba_profiles
WHERE PROFILE = 'DEFAULT'
AND resource_type = 'PASSWORD';
2 3 4
PROFILE RESOURCE_NAME LIMIT
---------- ------------------------ ----------------------
DEFAULT FAILED_LOGIN_ATTEMPTS 10
DEFAULT PASSWORD_LIFE_TIME 180
DEFAULT PASSWORD_REUSE_TIME UNLIMITED
DEFAULT PASSWORD_REUSE_MAX UNLIMITED
DEFAULT PASSWORD_VERIFY_FUNCTION NULL
DEFAULT PASSWORD_LOCK_TIME 1
DEFAULT PASSWORD_GRACE_TIME 7

7 rows selected.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 12
SQL> SAVE $HOME/labs/default_profile.sql REPLACE
Wrote file /home/oracle/labs/default_profile.sql
SQL> EXIT
$
b. Because the password verification function must be owned by SYS, connect as the SYS
user and verify that the default profile is assigned to all users to apply one of the three
available password verification functions. Read each of them and choose the strongest
one. The script explains in the last part how to apply one of the three verify functions to
the DEFAULT profile.
$ cd $ORACLE_HOME/rdbms/admin
$ cat utlpwdmg.sql

Rem Function: "ora12c_verify_function" - provided from 12c
onwards
Rem
Rem This function makes the minimum complexity checks like
Rem the minimum length of the password, password not same as the
Rem username, etc. The user may enhance this function according
to
Rem the need.
Rem This function must be created in SYS schema.
Rem connect sys/<password> as sysdba before running the script

CREATE OR REPLACE FUNCTION ora12c_verify_function


(username varchar2,
password varchar2,
old_password varchar2)

Rem Function: "ora12c_strong_verify_function" - provided from12c
onwards for
Rem stringent password check requirements.
Rem
Rem This function is provided to give stronger password
complexity function
Rem that would take into consideration recommendations from
Department of
Rem Defense Database Security Technical Implementation Guide.

CREATE OR REPLACE FUNCTION ora12c_strong_verify_function


(username varchar2,
password varchar2,
old_password varchar2)
RETURN boolean IS
differ integer;
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 13

Rem Function: "verify_function_11G" - provided from 11G onwards.
Rem
Rem This function makes the minimum complexity checks like
Rem the minimum length of the password, password not same as the
Rem username, etc. The user may enhance this function according
to
Rem the need.

CREATE OR REPLACE FUNCTION verify_function_11G


(username varchar2,
password varchar2,
old_password varchar2)

-- This script alters the default parameters for Password
Management
-- This means that all the users on the system have Password
Management
-- enabled and set to the following values unless another
profile is
-- created with parameter values set to different value or
UNLIMITED
-- is created and assigned to the user.

ALTER PROFILE DEFAULT LIMIT


PASSWORD_LIFE_TIME 180
PASSWORD_GRACE_TIME 7
PASSWORD_REUSE_TIME UNLIMITED
PASSWORD_REUSE_MAX UNLIMITED
FAILED_LOGIN_ATTEMPTS 10
PASSWORD_LOCK_TIME 1
PASSWORD_VERIFY_FUNCTION ora12c_verify_function;

/**
The below set of password profile parameters would take into
consideration
recommendations from Center for Internet Security[CIS Oracle
11g].

ALTER PROFILE DEFAULT LIMIT


PASSWORD_LIFE_TIME 90
PASSWORD_GRACE_TIME 3
PASSWORD_REUSE_TIME 365
PASSWORD_REUSE_MAX 20
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 14
FAILED_LOGIN_ATTEMPTS 3
PASSWORD_LOCK_TIME 1
PASSWORD_VERIFY_FUNCTION ora12c_verify_function;
*/

/**
The below set of password profile parameters would take into
consideration recommendations from Department of Defense
Database
Security Technical Implementation Guide[STIG v8R1].

ALTER PROFILE DEFAULT LIMIT


PASSWORD_LIFE_TIME 60
PASSWORD_REUSE_TIME 365
PASSWORD_REUSE_MAX 5
FAILED_LOGIN_ATTEMPTS 3
PASSWORD_VERIFY_FUNCTION ora12c_strong_verify_function;
$
c. Using SQL*Plus, connect to the database AS SYSDBA and verify that the three
password verification functions are not created yet.
$ sqlplus / AS SYSDBA

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> SET ECHO ON
SQL> SELECT object_name, object_type
FROM dba_objects
WHERE object_name LIKE '%VERIFY_FUNCTION%';
2 3
no rows selected.

SQL> SELECT LIMIT from dba_profiles


where profile = 'DEFAULT'
and resource_name = 'PASSWORD_VERIFY_FUNCTION';
2
LIMIT
--------------------------------------------------------------
NULL

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 15
Note: If the database had been created with DBCA, the DEFAULT profile would have the
PASSWORD_VERIFY_FUNCTION limit set to ora12c_verify_function function.
d. Alter the DEFAULT profile to apply the strong password verification function chosen in
task b. Be aware that all new accounts will be under the rules of the new password
verify function. If you do not want this situation, create a profile and assign another
password verify function to the new profile. This allows you to keep the DEFAULT
profile with the basic password verify function.
1) Create the functions.
SQL> @$ORACLE_HOME/rdbms/admin/utlpwdmg.sql

Function created.

Function created.

Function created.

Grant succeeded.

Function created.

Grant succeeded.

Function created.

Grant succeeded.

Function created.

Grant succeeded.

Profile altered.
The output has been modified to show only the results.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 16
2) Verify that the password verify functions are created.
SQL> col OBJECT_NAME format A38
SQL> col OBJECT_TYPE format A20
SQL> SELECT object_name, object_type
FROM dba_objects
WHERE object_name LIKE '%VERIFY_FUNCTION%';
2 3

OBJECT_NAME OBJECT_TYPE
---------------------------------------- --------------------
ORA12C_VERIFY_FUNCTION FUNCTION
ORA12C_STRONG_VERIFY_FUNCTION FUNCTION
VERIFY_FUNCTION_11G FUNCTION
VERIFY_FUNCTION FUNCTION

SQL>
3) Update the DEFAULT profile with the password verify function.
SQL> ALTER PROFILE default LIMIT
PASSWORD_VERIFY_FUNCTION ora12c_strong_verify_function;
2
Profile altered.

SQL>
e. View the changes applied. Repeat the command from step 2a as the SEC user and
note the differences.
SQL> CONNECT SEC
Enter password: ******
Connected.
SQL> COL profile format A7
SQL> COL resource_name format A32
SQL> COL limit format A30
SQL> @$HOME/labs/default_profile.sql
SQL> SELECT profile, resource_name, limit
FROM dba_profiles
WHERE PROFILE = 'DEFAULT'
AND resource_type = 'PASSWORD';

PROFILE RESOURCE_NAME LIMIT


------- ------------------------ -----------------------
DEFAULT FAILED_LOGIN_ATTEMPTS 10
DEFAULT PASSWORD_LIFE_TIME 180
DEFAULT PASSWORD_REUSE_TIME UNLIMITED
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 17
DEFAULT PASSWORD_REUSE_MAX UNLIMITED
DEFAULT PASSWORD_VERIFY_FUNCTION ORA12C_STRONG_VERIFY_FUNCTION
DEFAULT PASSWORD_LOCK_TIME 1
DEFAULT PASSWORD_GRACE_TIME 7

7 rows selected.

SQL>
2. Create a user and verify that the password is secure with the verify function applied in the
profile.
SQL> CREATE USER ann IDENTIFIED BY xxx12345;
CREATE USER ann IDENTIFIED BY xxx12345
*
ERROR at line 1:
ORA-28003: password verification for the specified password
failed
ORA-20001: Password length less than 9

SQL> CREATE USER ann IDENTIFIED BY A_xxx12345667890???!!!_yyy;


CREATE USER ann IDENTIFIED BY A_xxx12345667890???!!!_yyy
*
ERROR at line 1:
ORA-00911: invalid character

SQL> CREATE USER ann IDENTIFIED BY A_xxx12345667890_yyy;


CREATE USER ann IDENTIFIED BY A_xxx12345667890_yyy
*
ERROR at line 1:
ORA-28003: password verification for the specified password
failed
ORA-20023: Password must contain at least 2 uppercase
character(s)

SQL> CREATE USER ann IDENTIFIED BY A_xxx12345667890_Yyy;

User created.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 18
3. What happens to the SYS user when he alters his own password?
SQL> CONNECT / AS SYSDBA
Connected.
SQL> ALTER USER sys IDENTIFIED BY oracle_4U;
User altered.

SQL>
Notice that SYS is not under the rules of any password checking function even if defined in
the DEFAULT profile.
4. What happens to a user being granted the SYSDBA privilege when he alters his own
password?
SQL> GRANT sysdba TO tom;

Grant succeeded.

SQL> CONNECT tom AS SYSDBA


Enter password: ******
Connected.
SQL> ALTER USER tom IDENTIFIED BY oracle_4U;
ALTER USER tom IDENTIFIED BY oracle_4U
*
ERROR at line 1:
ORA-28003: password verification for the specified password
failed
ORA-20023: Password must contain at least 2 uppercase
character(s)

SQL> ALTER USER tom IDENTIFIED BY Strong_pass_6W;


ALTER USER tom IDENTIFIED BY Strong_pass_6W
*
ERROR at line 1:
ORA-28003: password verification for the specified password
failed
ORA-20025: Password must contain at least 2 digit(s)

SQL> ALTER USER tom IDENTIFIED BY Strong_pass_65W;

User altered.

SQL>
Notice that TOM falls under the rules of the password checking function defined in the
DEFAULT profile even if being granted the SYSDBA privilege.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 19
5. Set the password verification function to NULL in the DEFAULT profile. In a production
environment, the password verification function should be set to a password verification
function in the DEFAULT profile. You use simple passwords in the course for ease of
remembrance.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> ALTER PROFILE default LIMIT
PASSWORD_LIFE_TIME unlimited
FAILED_LOGIN_ATTEMPTS unlimited
PASSWORD_VERIFY_FUNCTION null;
2 3 4
Profile altered.

SQL>
6. Reset the password of TOM to its initial value and revoke the SYSDBA.
SQL> ALTER USER tom IDENTIFIED BY oracle_4U;

User altered.

SQL> REVOKE sysdba FROM tom;

Revoke succeeded.

SQL> EXIT
$
7. The security officer will now define different DEFAULT profiles within pdb1_1 and pdb1_2
setting the following password limits:
− In pdb1_1: A life time period set to 1 minute (for the practice purpose) and no
password verify function
− In pdb1_2: Account locked after 2 failed login attempts only and the password
verify function set to ora12c_strong_verify_function
a. Set the ORACLE_SID and ORACLE_HOME to point to the CDB instance.
$ . oraenv
ORACLE_SID = [orcl] ? cdb1
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 20
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
SQL>
b. The PDBs are not opened. You can either open them all each time the instance is
restarted as follows:
SQL> alter pluggable database all open;

Pluggable database altered.

SQL>
or create the following trigger that will open them at each instance startup. You can use
the following trigger code:
CREATE TRIGGER open_all_PDBs
AFTER STARTUP ON DATABASE
begin
execute immediate 'alter pluggable database all open';
end open_all_PDBs;
/

SQL> CREATE TRIGGER Open_All_PDBs


after startup on database
begin
execute immediate 'alter pluggable database ALL open';
end Open_All_PDBs;
/
2 3 4 5 6
Trigger created.

SQL>
c. Connect to pdb1_1 as SYSTEM to alter the DEFAULT profile.
SQL> CONNECT system@pdb1_1
Enter password: ******
Connected.
SQL> ALTER PROFILE default LIMIT
PASSWORD_LIFE_TIME 1/1440
PASSWORD_VERIFY_FUNCTION null;
2 3
Profile altered.

SQL> COL profile format A7


SQL> COL resource_name format A32
SQL> COL limit format A30

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 21
SQL> @$HOME/labs/default_profile.sql

PROFILE RESOURCE_NAME LIMIT


------- ----------------------------- -----------------------
DEFAULT FAILED_LOGIN_ATTEMPTS 10
DEFAULT PASSWORD_LIFE_TIME .0006
DEFAULT PASSWORD_REUSE_TIME UNLIMITED
DEFAULT PASSWORD_REUSE_MAX UNLIMITED
DEFAULT PASSWORD_VERIFY_FUNCTION NULL
DEFAULT PASSWORD_LOCK_TIME 1
DEFAULT PASSWORD_GRACE_TIME 7

7 rows selected.

SQL>
d. Connect to pdb1_2 as SYSTEM to alter the DEFAULT profile.
SQL> CONNECT system@pdb1_2
Enter password: ******
Connected.
SQL> ALTER PROFILE default LIMIT
FAILED_LOGIN_ATTEMPTS 10
PASSWORD_VERIFY_FUNCTION ora12c_strong_verify_function;

2 3 ALTER PROFILE default LIMIT


*
ERROR at line 1:
ORA-07443: function ORA12C_STRONG_VERIFY_FUNCTION not found

SQL> CONNECT sys@pdb1_2 AS SYSDBA


Enter password: ******
Connected.
SQL> @$ORACLE_HOME/rdbms/admin/utlpwdmg.sql

Function created.

Function created.

Function created.

Grant succeeded.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 22
Function created.

Grant succeeded.

Function created.

Grant succeeded.

Function created.

Grant succeeded.

Profile altered.

SQL> CONNECT system@pdb1_2


Enter password: ******
Connected.
SQL> ALTER PROFILE default LIMIT
FAILED_LOGIN_ATTEMPTS 10

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 23
PASSWORD_VERIFY_FUNCTION ora12c_strong_verify_function;
2 3
Profile altered.

SQL> @$HOME/labs/default_profile.sql

PROFILE RESOURCE_NAME LIMIT


------- ------------------------ -----------------------
DEFAULT FAILED_LOGIN_ATTEMPTS 10
DEFAULT PASSWORD_LIFE_TIME 180
DEFAULT PASSWORD_REUSE_TIME UNLIMITED
DEFAULT PASSWORD_REUSE_MAX UNLIMITED
DEFAULT PASSWORD_VERIFY_FUNCTION ORA12C_STRONG_VERIFY_FUNCTION
DEFAULT PASSWORD_LOCK_TIME 1
DEFAULT PASSWORD_GRACE_TIME 7

7 rows selected.

SQL>
e. Connect to the root container of cdb1 as SYSTEM and display the DEFAULT profile.
SQL> CONNECT system
Enter password: ******
Connected.
SQL> @$HOME/labs/default_profile.sql

PROFILE RESOURCE_NAME LIMIT


------- ---------------------------- -------------------
DEFAULT FAILED_LOGIN_ATTEMPTS 10
DEFAULT PASSWORD_LIFE_TIME 180
DEFAULT PASSWORD_REUSE_TIME UNLIMITED
DEFAULT PASSWORD_REUSE_MAX UNLIMITED
DEFAULT PASSWORD_VERIFY_FUNCTION NULL
DEFAULT PASSWORD_LOCK_TIME 1
DEFAULT PASSWORD_GRACE_TIME 7

7 rows selected.

SQL>
Notice that the root container has its own DEFAULT profile.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 24
f. Set the password verification function to NULL in the DEFAULT profile. Set the
password life time to unlimited so that passwords do not expire during the course.
You use simple passwords in the course for ease of remembrance.
SQL> ALTER PROFILE default LIMIT
FAILED_LOGIN_ATTEMPTS unlimited
PASSWORD_LIFE_TIME unlimited
PASSWORD_VERIFY_FUNCTION null;
2 3 4
Profile altered.

SQL> CONNECT system@pdb1_2


Enter password: ******
Connected.
SQL> ALTER PROFILE default LIMIT
FAILED_LOGIN_ATTEMPTS unlimited
PASSWORD_LIFE_TIME unlimited
PASSWORD_VERIFY_FUNCTION null;
2 3 4
Profile altered.

SQL>
SQL> CONNECT system@pdb1_1
Enter password:
Connected.
SQL> ALTER PROFILE default LIMIT
FAILED_LOGIN_ATTEMPTS unlimited
PASSWORD_LIFE_TIME unlimited
PASSWORD_VERIFY_FUNCTION null;
2 3 4
Profile altered.

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 25
Practice 4-3: Protecting the Data Dictionary
Overview
In this practice, you will verify that the data dictionary is protected from users’ visibility.

Tasks
1. After creating an Oracle database, what action do you need to take to prevent users with
the *ANY* privilege from using their privileges against the data dictionary? Which types of
users require the *ANY* privilege?
Verify that the O7_DICTIONARY_ACCESSIBILITY parameter is set to FALSE. This
restricts access to the data dictionary to users with the SELECT_CATALOG_ROLE or
SELECT ANY DICTIONARY privilege. Users who require the *ANY* privilege may be DBAs
who need privileges to create, alter, and drop objects, perform data manipulation language
(DML), and select objects in any schema. Note that in Oracle Database 12c, the default
value for O7_DICTIONARY_ACCESSIBILITY is FALSE.
a. Use the oraenv utility to set the ORACLE_SID environment variable to the orcl value.
$ . oraenv
ORACLE_SID = [cdb1] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
b. Display the value for O7_DICTIONARY_ACCESSIBILITY parameter.
$ sqlplus system
Enter password: ******
SQL> SHOW PARAMETER DICTIONARY

NAME TYPE VALUE


------------------------------------- ----------- ------------
O7_DICTIONARY_ACCESSIBILITY boolean FALSE
SQL>
2. Which users have been granted SELECT_CATALOG_ROLE?
SQL> COL GRANTEE FORMAT A20
SQL> COL GRANTED_ROLE FORMAT A22
SQL> SELECT * FROM dba_role_privs
WHERE GRANTED_ROLE LIKE 'SELECT_CATALOG%';

GRANTEE GRANTED_ROLE ADM DEF COM


------------------- -------------------- --- --- ---
SH SELECT_CATALOG_ROLE NO YES NO
SEC SELECT_CATALOG_ROLE NO YES NO
SYS SELECT_CATALOG_ROLE YES YES NO
IX SELECT_CATALOG_ROLE NO YES NO

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 26
OEM_MONITOR SELECT_CATALOG_ROLE NO YES YES
SYSBACKUP SELECT_CATALOG_ROLE NO YES YES
DBA SELECT_CATALOG_ROLE YES YES YES
IMP_FULL_DATABASE SELECT_CATALOG_ROLE NO YES YES
EXP_FULL_DATABASE SELECT_CATALOG_ROLE NO YES YES
EM_EXPRESS_BASIC SELECT_CATALOG_ROLE NO YES YES

10 rows selected.

SQL>
3. Which users have the SELECT ANY DICTIONARY privilege?
SQL> SELECT * FROM dba_sys_privs
WHERE privilege = 'SELECT ANY DICTIONARY';

GRANTEE PRIVILEGE ADM COM


-------------------- --------------------------------- --- ---
IX SELECT ANY DICTIONARY NO NO
SYSBACKUP SELECT ANY DICTIONARY NO YES
OLAPSYS SELECT ANY DICTIONARY NO YES
DBA SELECT ANY DICTIONARY YES YES
WMSYS SELECT ANY DICTIONARY NO YES
SYSDG SELECT ANY DICTIONARY NO YES
ORACLE_OCM SELECT ANY DICTIONARY NO YES
OEM_MONITOR SELECT ANY DICTIONARY NO YES
DBSNMP SELECT ANY DICTIONARY NO YES

9 rows selected.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 27
4. Verify that SYSTEM cannot view the SYS.ENC$ nor the SYS.LINK$ tables although being
granted the SELECT ANY DICTIONARY privilege.
SQL> SELECT * FROM SYS.ENC$;
SELECT * FROM SYS.ENC$
*
ERROR at line 1:
ORA-01031: insufficient privileges

SQL> SELECT * FROM SYS.LINK$;


SELECT * FROM SYS.LINK$
*
ERROR at line 1:
ORA-01031: insufficient privileges

SQL> SELECT count(*) FROM SYS.TAB$;

COUNT(*)
----------
2446

SQL>
5. Verify that SYS can view the SYS.ENC$.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> SELECT * FROM SYS.ENC$;

no rows selected

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 28
Practice 4-4: Investigating Security Violations Against Compliance
Framework
Overview
In this practice, you investigate the security violations existing in the orcl, cdb1, pdb1_1 and
pdb1_2 databases against the predefined compliance standard, called Basic Security
Configuration For Oracle Database. Assign both of your database instances to this
compliance standard. Then view the compliance evaluation results.

Tasks
1. To assign compliance standards to your database instances, navigate to Enterprise >
Compliance > Library.
2. Click the Compliance Standards tabbed page, and then the ">" icon before Search.
3. Select Database Instance from the Applicable To drop-down and click Search.
4. Because you want to ensure that there are no unexpected changes coming from predefined
standards (which may be updated in the future), you create your own set. Select Basic
Security Configuration For Oracle Database and click Create Like.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 29
5. Enter My Security for DB as Name and click Continue.

6. Click Save. Then OK.

7. Select My Security for DB and click Associate Targets.

8. To associate targets, click Add.


9. On the “Search and Select: Targets” window, select the orcl database instance and click
the Select button.
10. Click OK.
11. Read the Save Association message and click Yes.
12. You should receive the information that the compliance standard is submitted for
processing. Click OK.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 30
13. Repeat the previous two steps to associate the cdb1 database instance to this compliance
standard if you wish to investigate security violations in this target instance. To retrieve the
cdb1 instance, add the cdb1 instance as a possible target managed in EM Cloud Control.
(Execute the steps described in practice 3-2 step 9)
14. To evaluate the compliance standards, navigate to Enterprise > Compliance > Results.
15. Question: What is the compliance score for security best practices in each database? Click
a digit under Target Evaluations in the Compliance Standards tab. If there is no result in
the Compliance Standards tab, click the Target Compliance tab and click a digit under
Evaluations.
You may get different results than those displayed below.

16. Possible answer: In this example it is 100%. Close the Compliant Targets if you were
looking at Target Evaluations in the Compliance Standards tab or Compliant Standards
page if you were looking at Evaluations in the Target Compliance tab.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 31
17. In the Target Compliance tab, click the Violation link, then the Violation Count link: The
database does not conform to the compliance standard rules as recommended by Oracle
Corporation. You may get different results than those displayed below.

18. Close the “Violations” window.


19. Log out Enterprise Manager Cloud Control by clicking the Logout button.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 4: Implementing Basic Database Security


Chapter 4 - Page 32
Practices for Lesson 5:
Securing Network Services
Chapter 5

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 1
Practices for Lesson 5: Overview
Practices Overview
In these practices, you will implement the network security features like configuring the listener
on another port, securing the listener administration, and creating ACLs to restrict access by
users to network services.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 2
Practice 5-1: Configuring the Listener on Another Port
Overview
In this practice, you create a listener on an alternate port.

Tasks
1. Configure the listener to use an alternate port. Your network configuration files are stored in
the $TNS_ADMIN directory (/home/oracle/labs/NET). Then, start your listener.
a. Create the /home/oracle/labs/NET directory.
$ mkdir /home/oracle/labs/NET
$
b. Set the TNS_ADMIN environment variable to /home/oracle/labs/NET directory.
$ export TNS_ADMIN=/home/oracle/labs/NET
$
c. Use Oracle Net Manager to create a listener.ora file for a separate listener.
$ netmgr

Step Page Action


a. Oracle Net Manager - Expand Local.
/home/oracle/labs/NET Select Listeners.
Click Create (green “+” icon).
b. Choose Listener Name Enter LISTEN1 as the listener name.
Click OK.
c. Oracle Net Manager Click Add Address.
d. Address1 tab Enter the following information:
Port: 13001
Verify the host name.
Host : <Your hostname>
Change Listening Locations to General
Parameters.
e. General tab Click the Logging & Tracing tab.
Deselect “Enable ADR.”
Enter the following in the Log File field:
/home/oracle/labs/NET/listen1.log
f. General tab Select File > Save As.
Find the /home/oracle/labs/NET Directory.
Click OK.
Click Exit.
2. Start the LISTEN1 listener with the lsnrctl utility. Note where the log file is located.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 3
$ lsnrctl start LISTEN1

LSNRCTL for Linux: Version 12.1.0.1.0 - Production on 14-JUN-


2013 06:49:04

Copyright (c) 1991, 2013, Oracle. All rights reserved.

Starting /u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr:
please wait...

TNSLSNR for Linux: Version 12.1.0.1.0 - Production


System parameter file is /home/oracle/labs/NET/listener.ora
Log messages written to /home/oracle/labs/NET/listen1.log
Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=<your
hostname>)(PORT=13001)))

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=<your
hostname>)(PORT=13001)))
STATUS of the LISTENER
------------------------
Alias LISTEN1
Version TNSLSNR for Linux: Version 12.1.0.1.0
- Production
Start Date 14-JUN-2013 06:49:04
Uptime 0 days 0 hr. 0 min. 0 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File /home/oracle/labs/NET/listener.ora
Listener Log File /home/oracle/labs/NET/listen1.log
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=<your
hostname>)(PORT=13001)))
The listener supports no services
The command completed successfully
$
3. Display the new network configuration files and the first log created.
$ ls /home/oracle/labs/NET
listen1.log listener.ora sqlnet.ora
$
a. View the listener.ora file.
$ more /home/oracle/labs/NET/listener.ora

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 4
# listener.ora Network Configuration File:
/home/oracle/labs/NET/listener.ora
# Generated by Oracle configuration tools.

LOG_DIRECTORY_LISTEN1 = /home/oracle/labs/NET

LISTEN1 =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = <your hostname>)(PORT =
13001))
)

LOG_FILE_LISTEN1 = listen1.log

DIAG_ADR_ENABLED_LISTEN1 = OFF

$
b. View the sqlnet.ora file.
$ more /home/oracle/labs/NET/sqlnet.ora
# sqlnet.ora Network Configuration File:
/home/oracle/labs/NET/sqlnet.ora
# Generated by Oracle configuration tools.

ADR_BASE = /u01/app/oracle

$
c. View the listen1.log file.
$ more /home/oracle/labs/NET/listen1.log

TNSLSNR for Linux: Version 12.1.0.1.0 - Production on 14-JUN-


2013 06:49:04

Copyright (c) 1991, 2013, Oracle. All rights reserved.

System parameter file is /home/oracle/labs/NET/listener.ora


Log messages written to /home/oracle/labs/NET/listen1.log
Trace information written to
/u01/app/oracle/product/12.1.0/dbhome_1/network/trace/listen1.tr
c
Trace level is currently 0

Started with pid=29243

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 5
Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=<your
hostname>)(PORT=13001)))
Listener completed notification to CRS on start

TIMESTAMP * CONNECT DATA [* PROTOCOL INFO] * EVENT [* SID] *


RETURN CODE
WARNING: Subscription for node down event still pending
14-JUN-2013 06:49:04 * (CONNECT_DATA=(CID=(PROGRAM=)(HOST=<your
hostname>)(USER=oracle))(COMMAND=status
)(ARGUMENTS=64)(SERVICE=LISTEN1)(VERSION=202375424)) * status *
0
$
4. Create a net service name to allow connections to your ORCL service. Your service name is
O1. Use the Net Manager tool to create this entry.
a. Set the LOCAL_LISTENER parameter in the ORCL instance to the new address list of
Oracle Net local listener that is, listeners that run on the same system as this instance.
By default when the parameter is set to no value, the PORT is by default 1521.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> show parameter local_listener

NAME TYPE VALUE


----------------------------- ----------- --------------
local_listener string

SQL> ALTER SYSTEM SET local_listener =


'(ADDRESS = (PROTOCOL=TCP)(HOST=localhost)(PORT=13001))'
SCOPE=BOTH;
2 3
System altered.

SQL> EXIT
$
b. Create a net service name. Invoke NETMGR.
$ netmgr

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 6
Ste Page Action
p
a. Oracle Net Manager - Expand Local.
/home/oracle/labs/NET Select Service Naming.
Click Create (green “+” icon).
b. Net Service Name Wizard: Welcome Enter O1 as Net Service Name.
Click Next.
c. Net Service Name Wizard, page 2 of 5: Select TCP/IP (Internet Protocol).
Protocol Click Next.
d. Net Service Name Wizard, page 3 of 5: Enter the following information:
Protocol Settings Host : <Your hostname>
Port: 13001
Click Next.
e. Net Service Name Wizard, page 4 of 5: Enter the following information:
Service
Service Name: orcl
Click Next.
f. Net Service Name Wizard, page 5 of 5: Click Test.
Test
g. Connection Test Message indicates a failure.
Click Change Login.
h. Change Login Enter the following information:
Username: SYSTEM
Password: oracle_4U
Click OK.
i. Connection Test Click Test.
Expect connecting to the database to take a few
seconds to complete. Repeat until it succeeds.
Message: Connection test was
successful
Click Close.
j. Net Service Name Wizard, page 5 of 5: Click Finish.
Test
k. Oracle Net Manager - - From the menu, select File > Save Network
/home/oracle/labs/NET Configuration.
Select File > Exit.
5. Verify that the net service name that you created is working. Connect from your student
computer to the service on the instructor’s PC by using the net service name. Start
SQL*Plus on the student PC, and then connect by using the net service name.
$ sqlplus system@O1

Enter password:
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 7
Last Successful login time: Fri Jun 14 2013 07:44:44 +00:00

Connected to: ******


Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> select name from v$database;

NAME
---------
ORCL

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 8
Practice 5-2: Securing the Listener Administration
Overview
In this practice, you use the listener that you configured in the previous practice.
The environment variable $TNS_ADMIN points to the directory where the network administration
files are located. This variable was set in task 1 of the previous practice.

Tasks
1. Prevent online administration of the listener and test the setting by performing the following
steps:
a. Set up the listener to prevent online administration. Do not forget to include your
listener name. Add the line ADMIN_RESTRICTIONS_LISTEN1=ON to the
listener.ora file. Edit the listener.ora file on the server with your favorite
editor; gedit is suggested.
$ cd $TNS_ADMIN
$ gedit listener.ora
Add ADMIN_RESTRICTIONS_LISTEN1=ON

cat of your file should look like this:


$ cat listener.ora
# listener.ora Network Configuration File:
/home/oracle/labs/NET/listener.ora
# Generated by Oracle configuration tools.

LOG_DIRECTORY_LISTEN1 = /home/oracle/labs/NET

LISTEN1 =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = <Your hostname>)(PORT =
13001))
)

ADMIN_RESTRICTIONS_LISTEN1=ON
LOG_FILE_LISTEN1 = LISTEN1.log

DIAG_ADR_ENABLED_LISTEN1 = OFF
$
b. Stop and start your listener to force the listener.ora file to be read.
$ lsnrctl

LSNRCTL> SET CURRENT_LISTENER listen1


Current Listener is listen1
LSNRCTL> stop
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 9
Connecting to (ADDRESS=(PROTOCOL=tcp)(HOST=<Your
hostname>)(PORT=13001))
The command completed successfully stop LISTEN1

LSNRCTL> start

Starting /u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr:
please wait...

TNSLSNR for Linux: Version 12.1.0.1.0 - Production


System parameter file is /home/oracle/labs/NET/listener.ora
Log messages written to /home/oracle/labs/NET/listen1.log
Listening on: (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=<Your
hostname>)(PORT=13001)))

Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=<Your
hostname>)(PORT=13001)))
STATUS of the LISTENER
------------------------
Alias LISTEN1
Version TNSLSNR for Linux: Version 12.1.0.1.0
- Production
Start Date 14-JUN-2013 07:54:37
Uptime 0 days 0 hr. 0 min. 0 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File /home/oracle/labs/NET/listener.ora
Listener Log File /home/oracle/labs/NET/listen1.log
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=<Your
hostname>)(PORT=13001)))
The listener supports no services
The command completed successfully
LSNRCTL>
c. Attempt online administration. Set the trace level by using the following command:
LSNRCTL> SET TRC_LEVEL user
This verifies that you cannot administer the listener online.
LSNRCTL> SET TRC_LEVEL user
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=<Your
hostname>)(PORT=13001)))
TNS-12508: TNS:listener could not resolve the COMMAND given
LSNRCTL> exit
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 10
2. Edit the listener.ora file, removing the online administration restriction by deleting the
ADMIN_RESTRICTIONS_LISTEN1=ON entry.
$ gedit listener.ora
Remove ADMIN_RESTRICTIONS_LISTEN1=ON
3. Reload the listener.ora file. Do not forget to set your current listener.
$ lsnrctl

LSNRCTL> SET CURRENT_LISTENER listen1


Current Listener is listen1
LSNRCTL> reload
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=<Your
hostname>)(PORT=13001)))
The command completed successfully
LSNRCTL>
4. Test the change. In Listener Control, set the trace level by using the following command:
LSNRCTL> SET TRC_LEVEL user
This verifies that you can currently administer the listener online.
LSNRCTL> SET TRC_LEVEL user
Connecting to
(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=EDRSR1P1)(PORT=13001))
)
listen1 parameter "trc_level" set to user
The command completed successfully
LSNRCTL> exit
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 11
Practice 5-3: Configure the Listener to Allow Access Only from Your
Client Computer (optional)
Overview
In this practice, you configure your listener on the server to allow access only from your client
computer.

Tasks
1. Determine the IP address of your neighbor’s PC. Ask your neighbor to use nslookup
`hostname` to determine the IP address of his/her computer. This command uses the
grave (`) punctuation marks to execute the hostname command. IP address:
________________________________
$ nslookup `hostname`

Server: 192.0.2.1
Address: 192.0.2.1#53

Name: His/Her_servername
Address: 192.0.2.254
$
2. Set up Oracle Net Services to allow connections from his/her client computer and deny all
others. When tcp.invited_nodes is set, all nodes except those invited are excluded.
The tcp.invited_nodes and tcp.excluded_nodes parameters can be used
independently; if tcp.excluded_nodes is used by itself, only the nodes listed are
blocked. If tcp.invited_nodes is used by itself, only tcp.invited_nodes are allowed
to connect. If both are used together, the tcp.invited_nodes list takes precedence.
a. Stop the listener before applying changes to the sqlnet.ora file.
$ lsnrctl

LSNRCTL> set current_listener listen1


Current Listener is listen1
LSNRCTL> stop
Connecting to (ADDRESS=(PROTOCOL=tcp)(HOST=<Your
hostname>)(PORT=13001))
The command completed successfully
LSNRCTL> exit
$
b. Use gedit to edit the sqlnet.ora file. Include his/her server host name in
tcp.invited_nodes. Add the lines shown in bold in the following code. Substitute
his/her IP address and add your own host server name.
# sqlnet.ora Network Configuration File:
# Generated by Oracle configuration tools.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 12
ADR_BASE = /u01/app/oracle
NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)

tcp.validnode_checking = YES
tcp.invited_nodes = (<your hostname>, <neighbor’s hostname>)

$ cd $TNS_ADMIN
$ gedit sqlnet.ora

c. Start your listener for these changes to be applied to the listener.


$ lsnrctl

LSNRCTL> set current_listener listen1


Current Listener is listen1
LSNRCTL> start

Starting /u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr:
please wait...

TNSLSNR for Linux: Version 12.1.0.1.0 - Production


System parameter file is /home/oracle/labs/NET/listener.ora
Log messages written to /home/oracle/labs/NET/listen1.log
Listening on:
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=edRSr1p1.us.oracle.com
)(PORT=13001)))

Connecting to
(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=EDRSR1P1)(PORT=13001))
)
STATUS of the LISTENER
------------------------
Alias listen1
Version TNSLSNR for Linux: Version 12.1.0.1.0
- Production
Start Date 14-JUN-2013 09:15:18
Uptime 0 days 0 hr. 0 min. 0 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File /home/oracle/labs/NET/listener.ora
Listener Log File /home/oracle/labs/NET/listen1.log
Listening Endpoints Summary...

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 13
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=<Your
hostname>)(PORT=13001)))
The listener supports no services
The command completed successfully
LSNRCTL>
LSNRCTL> exit
$
3. Ask your neighbor to test by attempting to connect to your Oracle server instance. He will
use the EZCONNECT connect string that does not require a service name to be in the
tnsnames.ora file. The backslash is required to escape the quote.
$ sqlplus system@\'<your hostname>:13001/orcl\'
Enter password: ******
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics,
Real Application Testing and Unified Auditing options

SQL> EXIT
$
4. Ask another student, whose PC’s address is not one of the invited nodes, to use the
EZCONNECT style connection string and attempt to connect to your listener.
$ sqlplus system@\<your hostname>:13001/orcl\'

SQL*Plus: Release 12.1.0.1.0 Production on Tue Sep 10 09:26:15


2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.

Enter password:
ERROR:
ORA-12547: TNS:lost contact

Enter user-name:
$
5. Restore the listener so that it accepts any connections by removing the two parameters or
by just removing the sqlnet.ora file.
$ cd $TNS_ADMIN
$ rm sqlnet.ora
$ lsnrctl stop listen1

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 14
Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=<Your
hostname>)(PORT=13001)))
The command completed successfully
$
6. Analyze the listener log file. Find the following entries: status, stop, a failed attempt at
online administration, and a rejected connection.
$ cd /home/oracle/labs/NET
$ less listen1.log
26-JUN-2013 01:57:56 *
(CONNECT_DATA=(CID=(PROGRAM=)(HOST=EDRSR32P1)(USER=oracle))(COMM
AND=status)(ARGUMENTS=64)(SERVICE=listen1)(VERSION=202375424)) *
status * 0

26-JUN-2013 01:58:14 * trc_level * 12508
TNS-12508: TNS:listener could not resolve the COMMAND given

26-JUN-2013 01:57:56 *
(CONNECT_DATA=(CID=(PROGRAM=)(HOST=your_server)(USER=oracl
e))(COMMAND=status)(ARGUMENTS=64)(SERVICE=listen1)(VERSION=20237
5424)) * status * 0

26-JUN-2013 02:27:56 * (CONNECT_DATA=(CID=(PROGRAM=)(HOST=
your_server)(USER=oracl
e))(COMMAND=stop)(ARGUMENTS=64)(SERVICE=listen1)(VERSION=2023754
24)(CRS=ON)) * stop * 0

7. Clean up the listener configuration.


a. Set the TNS_ADMIN environment variable to $ORACLE_HOME/network/admin.
$ export TNS_ADMIN=$ORACLE_HOME/network/admin
$
b. Reset the LOCAL_LISTENER parameter to the default value.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> show parameter local_listener

NAME TYPE VALUE


--------------- ------ -------------------------
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 15
local_listener string (ADDRESS = (PROTOCOL=TCP)(HOST
=localhost)(PORT=13001))

SQL> ALTER SYSTEM RESET local_listener;

System altered.

SQL>
c. Restart the instance.
SQL> SHUTDOWN IMMEDIATE
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> STARTUP
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2289400 bytes
Variable Size 293601544 bytes
Database Buffers 197132288 bytes
Redo Buffers 8036352 bytes
Database mounted.
Database opened.
SQL> show parameter local_listener

NAME TYPE VALUE


---------------------- ----------- --------------
local_listener string
SQL> EXIT
$
d. Remove all network files created for the purpose of these practices 5.
$ rm /home/oracle/labs/NET/*
$
e. Verify the status of the LISTENER listener.
$ lsnrctl status

Connecting to
(DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
STATUS of the LISTENER
------------------------
Alias LISTENER

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 16
Version TNSLSNR for Linux: Version 12.1.0.1.0
- Production
Start Date 12-JUN-2013 00:45:52
Uptime 5 days 2 hr. 17 min. 16 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File
/u01/app/oracle/product/12.1.0/dbhome_1/network/admin/listener.o
ra
Listener Log File
/u01/app/oracle/diag/tnslsnr/EDRSR32P1/listener/alert/log.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=<Your
hostname>)(PORT=1521)))
Services Summary...
Service "cdb1" has 1 instance(s).
Instance "cdb1", status READY, has 1 handler(s) for this
service...
Service "cdb1XDB" has 1 instance(s).
Instance "cdb1", status READY, has 1 handler(s) for this
service...
Service "em12rep" has 1 instance(s).
Instance "em12rep", status READY, has 1 handler(s) for this
service...
Service "em12repXDB" has 1 instance(s).
Instance "em12rep", status READY, has 1 handler(s) for this
service...
Service "orcl" has 1 instance(s).
Instance "orcl", status READY, has 1 handler(s) for this
service...
Service "orclXDB" has 1 instance(s).
Instance "orcl", status READY, has 1 handler(s) for this
service...
Service "pdb1_1" has 1 instance(s).

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 17
Instance "cdb1", status READY, has 1 handler(s) for this
service...
Service "pdb1_2" has 1 instance(s).
Instance "cdb1", status READY, has 1 handler(s) for this
service...
The command completed successfully
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 5: Securing Network Services


Chapter 5 - Page 18
Practices for Lesson 6:
Implementing Basic and
Strong Authentication
Chapter 6

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 1
Practices for Lesson 6: Overview
Practices Overview
In these practices, you will implement the basic password and OS authentication, secure the
passwords, restrict database links and manage authentication of common and local users in
CDBs and PDBs.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 2
Practice 6-1: Using Basic OS Authentication Method
Overview
In this practice, you will in a first step explore basic authentication techniques for implementing a
no-password login and the weaknesses of this method.

Assumptions
In your company, there are several situations that require exceptions to the standard password
policies. Batch jobs should not have passwords embedded in the script or command line.

Tasks
1. A batch job that runs as the fred operating system user should be able to connect to the
database as the FRED database user without having to embed the database password in
the batch file.
Configure OS_AUTHENT_PREFIX to allow the OS user and database user to have the
same string. What is the default value of OS_AUTHENT_PREFIX? Is OS_AUTHENT_PREFIX
a static parameter?
Connect to the database as the SYS user. Set the OS_AUTHENT_PREFIX parameter to ''.
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> show parameter OS_AUTHENT_PREFIX

NAME TYPE VALUE


-------------------------- ---------- -----
os_authent_prefix string ops$
SQL>
SQL> column value format A10
SQL> column name format A24
SQL> select name, value, isdefault, ISSYS_MODIFIABLE
from v$parameter
where name = 'os_authent_prefix';
2 3
NAME VALUE ISDEFAULT ISSYS_MOD
-------------------------- ---------- --------- ---------
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 3
os_authent_prefix ops$ TRUE FALSE

SQL> ALTER SYSTEM SET OS_AUTHENT_PREFIX='';


ALTER SYSTEM SET OS_AUTHENT_PREFIX=''
*
ERROR at line 1:
ORA-02095: specified initialization parameter cannot be modified

SQL> ALTER SYSTEM SET OS_AUTHENT_PREFIX='' SCOPE=SPFILE;

System altered.

SQL> SHUTDOWN IMMEDIATE


Database closed.
Database dismounted.
ORACLE instance shut down.
SQL>
SQL> STARTUP
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2289400 bytes
Variable Size 264241416 bytes
Database Buffers 226492416 bytes
Redo Buffers 8036352 bytes
Database mounted.
Database opened.
SQL>
2. Create the database user FRED, using the IDENTIFIED EXTERNALLY clause. Allow FRED
to connect to the database.
As the SEC user, create the FRED user and grant the CREATE SESSION privilege.
SQL> CONNECT SEC
Enter password: *****
Connected.
SQL>
SQL> CREATE USER FRED IDENTIFIED EXTERNALLY;

User created.

SQL>
SQL> GRANT CREATE SESSION TO FRED;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 4
Grant succeeded.

SQL> ALTER USER FRED


DEFAULT TABLESPACE EXAMPLE
QUOTA UNLIMITED ON EXAMPLE;
2 3
User altered.

SQL> EXIT
$
3. Test the connection as the fred user. Log in to the OS as the fred user. The OS
password for fred is oracle. Connect to the database with the “/” connect string.
$ su - fred
Password: *****
$ . oraenv
ORACLE_SID = [fred] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus /

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> SHOW USER


USER is "FRED"
SQL> EXIT
$ exit
logout
$
Notice that any connection using an OS or password authentication provides the “Last
Successful Logon Time” for non-SYS users. You can see it in the SQL*Plus banner. You
will see the message when you connected at least once before.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 5
Practice 6-2: Observing Passwords in Database Links
Overview
In this practice, you explore the protection of passwords for database links in Oracle Database
12c.

Tasks
1. Create and test a database link in the PDB1_1 pluggable database. Log in as the oracle
OS user. As the SYSTEM database user, create a database link for the HR user to the ORCL
database.
CREATE PUBLIC DATABASE LINK test_hr
CONNECT TO hr IDENTIFIED BY oracle_4U
USING 'ORCL';

Note: Only users with the CREATE PUBLIC DATABASE LINK privilege can execute this
command.
$ sqlplus system@pdb1_1
Enter password: ******

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
SQL>
SQL> CREATE PUBLIC DATABASE LINK test_hr
CONNECT TO hr IDENTIFIED BY oracle_4U
USING 'ORCL';
2 3
Database link created.

SQL>
2. Test the database connection as the database user SCOTT by selecting from the
EMPLOYEES table through the database link.
Any database user will be able to use this database link because it is declared PUBLIC.
Connected as SYSTEM, open the SCOTT account, and then test the database link.
SQL> ALTER USER scott IDENTIFIED BY oracle_4U ACCOUNT UNLOCK;

User altered.

SQL> connect scott@pdb1_1


Enter password: ******
Connected.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 6
SQL> select max(salary) from employees@test_hr;

MAX(SALARY)
-----------
24000

SQL>
3. View the data dictionary information about the database link. Find the username and
password as they are stored in the database.
a. Connect as SYSTEM and query the DBA_DB_LINKS view for the database link
information.
SQL> CONNECT system@pdb1_1
Enter password: ******
Connected.
SQL> COL username FORMAT A16
SQL> COL owner FORMAT A16
SQL> COL db_link FORMAT A16
SQL> SELECT owner, db_link, username FROM DBA_DB_LINKS;

OWNER DB_LINK USERNAME


---------------- ---------------- ----------------
PUBLIC TEST_HR HR

SQL> SELECT name, authusr, authpwd, passwordx, authpwdx


FROM SYS.LINK$;
2 FROM LINK$
*
ERROR at line 2:
ORA-01031: insufficient privileges

SQL>
The SYSTEM user is granted the SELECT ANY DICTIONARY privilege but cannot view the
SYS.LINK$ table.
4. View the base SYS table for the database links. As the SYS user, view the LINK$ table. Is
the password visible in this table? Describe the table to view all columns. Query the table to
view passwords. Note that all passwords are encrypted. None are stored in clear text.
SQL> CONNECT / as sysdba
Connected.
SQL> desc link$

Name Null? Type

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 7
-------------------------- -------- -------------------
OWNER# NOT NULL NUMBER
NAME NOT NULL VARCHAR2(128)
CTIME NOT NULL DATE
HOST VARCHAR2(2000)
USERID VARCHAR2(128)
PASSWORD VARCHAR2(128)
FLAG NUMBER
AUTHUSR VARCHAR2(128)
AUTHPWD VARCHAR2(128)
PASSWORDX RAW(128)
AUTHPWDX RAW(128)

SQL> SELECT name, authusr, authpwd, passwordx, authpwdx


FROM LINK$;
2
no rows selected

SQL>
Note that you are connected to the root container. You created the database link in the
PDB1_1 container.
SQL> CONNECT sys@pdb1_1 as sysdba
Enter password: ******
Connected.

SQL> SELECT name, authusr, authpwd, passwordx, authpwdx


FROM LINK$;
2

NAME
--------------------------------------------------------
AUTHUSR
--------------------------------------------------------
AUTHPWD
--------------------------------------------------------
PASSWORDX
--------------------------------------------------------
AUTHPWDX
--------------------------------------------------------
TEST_HR

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 8
07C3AA3161B61534381479C836FC0B4681E68548F32D28845EC40B1A
7A4A5421A6D84FE46C53B1E374BF928D0ED35AE8B1E4D9CC5E08A1F7
13471B9CB6C61ED3345FC4D8C75504AA127AD3EB564FA583EE3117BB
37209801CA3F0156C5360F0C2A14A261D6380A100F1ED93257D72C4D
ED56E34907B613BCC96C0AB90F1D9E6

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 9
Practice 6-3: Restricting Database Links With Views
Overview
In this practice, you will restrict to the access to tables in the HR schema authorized by the
hrviewlink database link.

Tasks
1. While you are still connected to pdb1_1, create the MIKE user and grant him the HR_MGR
role.
SQL> SET ECHO ON
SQL> DROP ROLE HR_MGR;
DROP ROLE HR_MGR
*
ERROR at line 1:
ORA-01919: role 'HR_MGR' does not exist

SQL> CREATE ROLE HR_MGR;

Role created.

SQL> DROP USER mike CASCADE;


DROP USER mike CASCADE
*
ERROR at line 1:
ORA-01918: user 'MIKE' does not exist

SQL> CREATE USER mike identified by oracle_4U;

User created.

SQL> GRANT CREATE SESSION TO mike;

Grant succeeded.

SQL> GRANT HR_MGR to mike;

Grant succeeded.

SQL>
2. Create the hrviewlink database link.
SQL> CONNECT hr@pdb1_1
Enter password:

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 10
ERROR:
ORA-28000: the account is locked

Warning: You are no longer connected to ORACLE.


SQL> CONNECT system@pdb1_1
Enter password: ******
Connected.
SQL> ALTER USER hr IDENTIFIED BY oracle_4U ACCOUNT UNLOCK;

User altered.

SQL> CONNECT hr@pdb1_1


Enter password: ******
Connected.
SQL> DROP DATABASE LINK hrviewlink;
DROP DATABASE LINK hrviewlink
*
ERROR at line 1:
ORA-02024: database link not found

SQL> CREATE DATABASE LINK hrviewlink CONNECT TO hr IDENTIFIED BY


oracle_4U USING 'orcl';

Database link created.

SQL>
3. Create the employees_vw view and check that it allows you to retrieve
HR.EMPLOYEES@hrviewlink rows.
SQL> CREATE VIEW employees_vw as
SELECT * FROM HR.EMPLOYEES@hrviewlink;
2
View created.

SQL> GRANT select, insert, update, delete on EMPLOYEES_VW to


HR_MGR;

Grant succeeded.

SQL> SELECT employee_id, salary


FROM employees@hrviewlink
WHERE employee_id = 206;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 11
2 3
EMPLOYEE_ID SALARY
----------- ----------
206 8300

SQL>
4. Connect as MIKE and test the view.
SQL> CONNECT mike@pdb1_1
Enter password: ******
Connected.
SQL> UPDATE hr.EMPLOYEES_VW SET SALARY = 10000
WHERE employee_id = 206;
2
1 row updated.

SQL> SELECT employee_id, salary FROM hr.employees_vw


WHERE employee_id = 206;
2
EMPLOYEE_ID SALARY
----------- ----------
206 10000

SQL> ROLLBACK;

Rollback complete.

SQL>
5. Attempt to view some other table HR.DEPARTMENTS of the HR schema.
SQL> SELECT * FROM hr.departments@hrviewlink;
SELECT * FROM hr.departments@hrviewlink
*
ERROR at line 1:
ORA-02019: connection description for remote database not found

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 12
Practice 6-4: Configuring the External Secure Password Store
Overview
In this practice, you will configure the External Secure Password Store to hide passwords in
batch jobs scripts.

Assumptions
You successfully completed Practice 6-1 Task 1.

Tasks
The batch processes have been moved to a client machine. The batch processes will continue
using the /@netservice_name login for database connections. However, you must follow
security best practices: hence remote OS authentication (REMOTE_OS_AUTHENT) is not
allowed. Configure the external secure password store for the fred user to connect as the HR
database user.
1. Log in to the operating system as fred.
$ su - fred
Password: ******
$
2. Create the following directories required for this practice: /home/fred/oracle/wallet
and /home/fred/oracle/network.
Set the permissions on the wallet directory to be accessible only to fred.
$ mkdir /home/fred/oracle
$ mkdir /home/fred/oracle/wallet
$ mkdir /home/fred/oracle/network
$ ls -l /home/fred/oracle
total 8
drwxr-xr-x 2 fred users 4096 Jan 20 16:35 network
drwxr-xr-x 2 fred users 4096 Jan 20 16:35 wallet
$ chmod 700 /home/fred/oracle/wallet
$ ls -l /home/fred/oracle
total 8
drwxr-xr-x 2 fred users 4096 Jan 20 16:35 network
drwx------ 2 fred users 4096 Jan 20 16:35 wallet
$
3. Create and configure the client-side Oracle wallet in the following directory that is
accessible only to fred: /home/fred/oracle/wallet.
If the wallet does not exist, create the client wallet using the command mkstore -wrl
<wallet_location> -create where <wallet_location> is the path to the directory
where you want to create and store the wallet. This command creates an Oracle wallet with
the auto login feature enabled at the location you specify. When auto login is enabled for a
wallet, only the operating system user who created it can manage it.
a. Use the mkstore utility. Set the wallet password to welcome1.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 13
$ . oraenv
ORACLE_SID = [fred] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ mkstore -wrl /home/fred/oracle/wallet -create
Oracle Secret Store Tool : Version 11.2.0.1.0 - Production
Copyright (c) 2004, 2009, Oracle and/or its affiliates. All
rights reserved.
Enter password: ******
Enter password again: *******
$
b. Add credentials to the wallet using mkstore -wrl <wallet_location> -
createCredential <db_connect_string> <username> [<password>]
where <db_connect_string> is a TNS alias or any service name used to connect to the
database. The service name specified in the mkstore command and the service name
used to connect to the database (in connect /@<db_connect_string>) must be
identical. Add credentials to the wallet so that fred can connect to the HR schema
without a password. Set the service name to hr_sec, with the username hr and the
password oracle_4U.
$ mkstore -wrl /home/fred/oracle/wallet -createCredential hr_sec
hr
Oracle Secret Store Tool : Version 11.2.0.1.0 - Production
Copyright (c) 2004, 2009, Oracle and/or its affiliates. All
rights reserved.
Your secret/Password is missing in the command line
Enter your secret/Password: (oracle_4U)
Re-enter your secret/Password: (oracle_4U)
Enter wallet password: (welcome1)
Create credential oracle.security.client.connect_string1
$
4. Still logged in as fred, set the $TNS_ADMIN environment variable to
/home/fred/oracle/network. Edit the .bashrc file with vi or gedit. The .bashrc
file is in the /home/fred directory. Change the .bashrc file by adding the following line:
export TNS_ADMIN=/home/fred/oracle/network
a. Change the .bashrc file.
# .bashrc

# Source global definitions


if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi

export TNS_ADMIN=/home/fred/oracle/network

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 14
b. Force the changes to take effect and verify that they have.
$ source ./.bashrc
$ echo $TNS_ADMIN
/home/fred/oracle/network
$
5. Copy the sqlnet.ora file from /home/oracle/labs/admin to
/home/fred/oracle/network.
$ cd /home/fred/oracle/network
$ cp /home/oracle/labs/admin/sqlnet.ora ./
$
6. View the sqlnet.ora file, and verify that the following lines are included:
WALLET_LOCATION =
(SOURCE =
(METHOD = FILE)
(METHOD_DATA =
(DIRECTORY =
/home/fred/oracle/wallet)))

SQLNET.WALLET_OVERRIDE = TRUE

The sqlnet.ora file has three parameters for configuring the secure external password
store: WALLET_LOCATION, SQLNET.WALLET_OVERRIDE, and
SQLNET.AUTHENTICATION.SERVICES.
• WALLET_LOCATION points to the directory where the wallet resides; this parameter
exists in earlier versions.
• Set the SQLNET.WALLET_OVERRIDE parameter to TRUE. This setting causes all
CONNECT /@db_connect_string statements to use the information in the wallet at
the specified location to authenticate to databases.
• If an application uses SSL for encryption, the sqlnet.ora parameter,
SQLNET.AUTHENTICATION_SERVICES, specifies SSL and an SSL wallet is created.
If this application wants to use secret store credentials to authenticate to databases
(instead of the SSL certificate), those credentials must be stored in the SSL wallet. If
SQLNET.WALLET_OVERRIDE = TRUE, the usernames and passwords from the wallet
are used to authenticate to databases. If SQLNET.WALLET_OVERRIDE = FALSE, the
SSL certificate is used.
$ cat sqlnet.ora

NAMES.DIRECTORY_PATH= (TNSNAMES, EZCONNECT)

WALLET_LOCATION =
(SOURCE =
(METHOD = FILE)
(METHOD_DATA =
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 15
(DIRECTORY =
/home/fred/oracle/wallet)))

SQLNET.WALLET_OVERRIDE = TRUE

7. Copy the /home/oracle/labs/admin/tnsnames.ora file to


/home/fred/oracle/network/tnsnames.
$ cp /home/oracle/labs/admin/tnsnames.ora tnsnames.ora
8. Edit the /home/fred/oracle/network/tnsnames.ora file. Replace the ORCL alias by
the HR_SEC alias at the beginning of the file:
HR_SEC =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = orcl)
)
)
9. Test the configuration by attempting to connect to the database instance with the connect
string /@hr_sec.
$ sqlplus /@hr_sec

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> show user


USER is "HR"
SQL> exit
$
10. List the contents of the wallet. Use the mkstore command with the listCredential
option. Use the following command:
mkstore –wrl /home/fred/oracle/wallet –listCredential
$ mkstore -wrl /home/fred/oracle/wallet -listCredential
Oracle Secret Store Tool : Version 11.2.0.1.0 - Production
Copyright (c) 2004, 2009, Oracle and/or its affiliates. All
rights reserved.

Enter wallet password:

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 16
List credential (index: connect_string username)
1: hr_sec hr
$ exit
logout
$
11. As the oracle user, attempt to use the wallet belonging to fred to connect with the
connect string /@hr_sec.
a. Set TNS_ADMIN to /home/oracle/labs/admin. The sqlnet.ora file is set up to
use the wallet at /home/fred/oracle/wallet.
$ export TNS_ADMIN=/home/oracle/labs/admin
$ cd $TNS_ADMIN
$
b. Open the tnsnames.ora file from /home/oracle/labs/admin and edit the same
way as in step 8.
HR_SEC =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
)
(CONNECT_DATA =
(SERVICE_NAME = orcl)
)
)
$ gedit tnsnames.ora

$
c. Test the HR_SEC net service name.
$ tnsping HR_SEC

Copyright (c) 1997, 2013, Oracle. All rights reserved.

Used parameter files:


/home/oracle/labs/admin/sqlnet.ora

Used TNSNAMES adapter to resolve the alias


Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS =
(PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))) (CONNECT_DATA
= (SERVICE_NAME = orcl)))
OK (30 msec)
$
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 17
d. Attempt to connect using the HR_SEC service name with a password. Use system.
$ sqlplus /nolog

SQL*Plus: Release 12.1.0.1.0 Production on Mon Jun 17 05:35:29


2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.

SQL> connect system@HR_SEC


Enter password: ******
Connected
SQL> exit
$
e. Attempt to connect using the HR_SEC service name without a password. This fails
because the wallet is owned by fred and has the restrictive permissions rwx------
as shown in step 2.
$ sqlplus /nolog

SQL*Plus: Release 12.1.0.1.0 Production on Mon Jun 17 05:36:28


2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.

SQL> connect /@HR_SEC


ERROR:
ORA-12578: TNS:wallet open failed

SQL> exit
$
f. Clear the TNS_ADMIN environment variable.
$ unset TNS_ADMIN
$
12. To clean up after this practice, reset the OS_AUTHENT_PREFIX parameter to the default
values in the ORCL instance.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 18
SQL> ALTER SYSTEM SET OS_AUTHENT_PREFIX='ops$' SCOPE=SPFILE;

System altered.

SQL> SHUTDOWN IMMEDIATE


Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> STARTUP
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2289400 bytes
Variable Size 293601544 bytes
Database Buffers 197132288 bytes
Redo Buffers 8036352 bytes
Database mounted.
Database opened.
SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 19
Practice 6-5: Connecting to a CDB or a PDB
Overview
In this practice, you will create a common user in the CDB and observe that the common user
will connect with the same password in all PDBs in the CDB. In a second step, you will create a
local user in each of the two PDBs of the CDB and observe how the local users connect to the
PDBs.

Tasks
1. Create the common user C##U1 in cdb1.
$ . oraenv
ORACLE_SID = [cdb1] ? cdb1
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus system
Enter password: ******
Last Successful login time: Mon Jun 17 2013 02:46:48 +00:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options

SQL> CREATE USER c##u1 IDENTIFIED BY oracle_4U CONTAINER=ALL;

User created.

SQL> GRANT create session TO c##u1 CONTAINER=ALL;

Grant succeeded.

SQL>
2. Connect as C##U1 in the root.
SQL> CONNECT c##u1
Enter password: ******
Connected.
SQL> SHOW CON_NAME

CON_NAME
------------------------------
CDB$ROOT
SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 20
3. Connect as C##U1 in pdb1_1.
SQL> CONNECT c##u1@pdb1_1
Enter password: ******
Connected.
SQL> SHOW CON_NAME

CON_NAME
------------------------------
PDB1_1
SQL>
4. Connect as C##U1 in pdb1_2.
SQL> CONNECT c##u1@pdb1_2
Enter password: ******
Connected.
SQL> SHOW CON_NAME

CON_NAME
------------------------------
PDB1_2
SQL>

SQL>
Notice that the same password is used to connect to any container of cdb1.
5. Create the local user LOCAL_EMPLOYEE in pdb1_1.
a. Connect as SYSTEM in pdb1_1.
SQL> CONNECT system@pdb1_1

Enter password: ******


Last Successful login time: Mon Jun 17 2013 03:13:35 +00:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options

SQL>
b. Create the local user LOCAL_EMPLOYEE.
SQL> CREATE USER local_employee IDENTIFIED BY pass_pdb1;

User created.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 21
SQL> GRANT create session TO local_employee;

Grant succeeded.

SQL>
c. Connect as LOCAL_EMPLOYEE in pdb1_1.
SQL> CONNECT local_employee@pdb1_1
Enter password: ******
Connected.
SQL>
d. Connect as LOCAL_EMPLOYEE in pdb1_2.
SQL> CONNECT local_employee@pdb1_2
Enter password: ******
ERROR:
ORA-01017: invalid username/password; logon denied

Warning: You are no longer connected to ORACLE.


SQL>
6. Create the local user LOCAL_EMPLOYEE in pdb1_2.
a. Connect as SYSTEM in pdb1_2.
SQL> CONNECT system@pdb1_2
Enter password: ******
Connected.
SQL>
b. Create the local user LOCAL_EMPLOYEE.
SQL> CREATE USER local_employee IDENTIFIED BY pass_pdb2;

User created.

SQL> GRANT create session TO local_employee;

Grant succeeded.

SQL>
c. Connect as LOCAL_EMPLOYEE in pdb1_2.
SQL> CONNECT local_employee@pdb1_2
Enter password: ******
Connected.
SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 22
d. Connect as LOCAL_EMPLOYEE in pdb1_1 with the password assigned to
LOCAL_EMPLOYEE in pdb1_2.
SQL> CONNECT local_employee@pdb1_1
ERROR:
ORA-01017: invalid username/password; logon denied

Warning: You are no longer connected to ORACLE.


SQL>
SQL> EXIT
$
Notice that the password used by the local user to connect to pdb1_1 and pdb1_2 are
different.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 23
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 6: Implementing Basic and Strong Authentication


Chapter 6 - Page 24
Practices for Lesson 7: Using
Enterprise User Security
Chapter 7
Practices for Lesson 7: Overview
Practices Overview
In the demonstration for this lesson, you will use the Enterprise User Security to connect to a
database with unknown database users, but with directory entry users.
Practice 7-1: Using Enterprise User Security
Overview
In this practice, you use a browser to execute the “Managing_Users_and_Roles_With_EUS”
demonstration. The demonstration explains how to:
• Configure and register a database with an LDAP directory.
• Create and map global private schemas and global shared schemas with directory
entries.
• Test the connections as unknown database users.
• Create global roles and enterprise roles, and map them together to assign enterprise
roles to directory entry users.
• Test the connections of unknown database users being granted enterprise roles.
• View audited connections for unknown users.

Tasks
1. Launch a browser and enter:
file:////home/oracle/labs/EUS/Managing_Users_and_Roles_with_EUS/Managing_Users_an
d_Roles_With_EUS.html
Practices for Lesson 8: Using
Proxy Authentication
Chapter 8

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 1
Practice 8-1: Using Proxy Authentication
In this practice, you use the OCI programs that simulate an in-house developed application
server: proxy_user and proxy_role. For both, the program starts by connecting to the ORCL
database as the HRAPP user and creating a connection pool with 10 connections, and then it
attempts to create sessions for the PFAY user. The conditions will vary and sometimes the
sessions will fail to be created.

Task
1. If you did not create the SEC user in Practice 4-1, run the
/home/oracle/labs/USERS/create_sec.sh script to create this user. As the SEC
user, create a user to simulate a middle-tier user.
a. Create a user with the following properties:
Username: HRAPP
Password: HRAPP
(Note: This password is case-sensitive; it must be in uppercase.)
CREATE SESSION privilege
$ . oraenv
ORACLE_SID = [cdb1] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus sec
Enter password: ******
Last Successful login time: Mon Jun 17 2013 03:07:45 +00:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> CREATE USER hrapp IDENTIFIED by HRAPP;

User created.

SQL>
SQL> GRANT create session TO hrapp;

Grant succeeded.

SQL>
b. Verify that HRAPP can connect. (Be aware of the uppercase password).
SQL> connect hrapp
Enter password: ******
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 2
Connected.
SQL>
SQL> EXIT
$
2. As the SEC user, drop the PFAY user to avoid possible conflicts. Then, create an end user
with the following properties:
Username: PFAY
Password: oracle_4U
PFAY is granted the create session privilege.
PFAY can connect through HRAPP without a password.
3. For PFAY to connect through HRAPP, HRAPP must be a proxy. Use the GRANT CONNECT
THROUGH syntax to allow HRAPP to proxy PFAY.
$ sqlplus sec
Enter password: ******
Last Successful login time: Mon Jun 17 2013 06:05:36 +00:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL>
SQL> DROP USER pfay CASCADE;
DROP USER pfay CASCADE
*
ERROR at line 1:
ORA-01918: user 'PFAY' does not exist

SQL> CREATE USER pfay IDENTIFIED by oracle_4U;

User created.

SQL> GRANT create session TO pfay;

Grant succeeded.

SQL> ALTER USER pfay GRANT CONNECT THROUGH hrapp;

User altered.

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 3
4. The proxy_user program tests connections through the middle tier.
a. This program has the following arguments:
Connection (TNS) name is required.
Username is required.
Password is optional.
b. The program performs the following steps:
1. Connects as the HRAPP user
2. Creates a connection pool of 10 connections
3. Creates 10 threads that connect to the database by using one of the connections
from the pool. The proxy_user program makes these connections using the
username and password parameters.
4. Waits for a return character from the standard input
5. Disconnects the 10 threads, destroys the connection pool, and ends
c. Start a separate terminal window to act as a client. Set the environment variables by
using the oraenv utility to set the instance name to orcl. Change to the
/home/oracle/labs/PROXY directory.
d. Recompile the proxy programs. Ignore the error messages.
$ cd /home/oracle/labs/PROXY
$ ./mk_proxy_user
proxy_user.c: In function 'main':
proxy_user.c:56: warning: incompatible implicit declaration of
built-in function 'strlen'
proxy_user.c: In function 'threadFunction':
proxy_user.c:109: warning: incompatible implicit declaration of
built-in function 'strlen'
$ ./mk_proxy_role
proxy_role.c: In function 'main':
proxy_role.c:60: warning: incompatible implicit declaration of
built-in function 'strlen'
proxy_role.c: In function 'threadFunction':
proxy_role.c:116: warning: incompatible implicit declaration of
built-in function 'strlen'
$ mv proxy_user? proxy_user
$ mv proxy_role? proxy_role
$
e. Test the users that you created by executing proxy_user (from the operating system
prompt) with the following command line:
$ ./proxy_user orcl pfay
where orcl is the TNS name for your local instance
The proxy_user command connects PFAY without a password. Should this work?
Why?
The program should work because you set up PFAY so that the user can connect
without a password. When the program is complete, press the Enter key.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 4
$ ./proxy_user orcl pfay
Database: orcl
Username: pfay
Password:
Successful connection: Username: HRAPP
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Hit enter to end connections:
$
f. Examine the source code for the proxy_user program (see the appendix titled
“Source Code”).
5. Using the terminal window, select the information from the data dictionary that shows the
users for whom HRAPP can proxy. Save this query; you will execute it again.
$ sqlplus sec
Enter password: *******

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL>
SQL> COL proxy FORMAT A6
SQL> COL client FORMAT A6
SQL> COL authentication FORMAT A12 WORD
SQL>
SQL> SELECT proxy,
client,
authentication,
authorization_constraint
FROM dba_proxies
WHERE proxy = 'HRAPP';
2 3 4 5 6
PROXY CLIENT AUTHENTICATI AUTHORIZATION_CONSTRAINT
------ ------ ------------ -----------------------------------
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 5
HRAPP PFAY NO PROXY MAY ACTIVATE ALL CLIENT ROLES

SQL>
6. Modify the PFAY user so that a password is required when connecting through a middle
tier.
SQL> ALTER USER pfay
GRANT CONNECT THROUGH hrapp AUTHENTICATION REQUIRED;
2
User altered.

SQL> exit
$
7. In the terminal window, run proxy_user with the following command line:
$ ./proxy_user orcl pfay
This command connects PFAY without a password. Should this work? Why?
Answer: The program should not work because the PFAY user now requires a password to
connect.
$ ./proxy_user orcl pfay
Database: orcl
Username: pfay
Password:
Successful connection: Username: HRAPP
Error - ORA-28183: proper authentication not provided by proxy

Error - OCI_INVALID_HANDLE
Error - ORA-28183: proper authentication not provided by proxy

Error - OCI_INVALID_HANDLE
Error - ORA-28183: proper authentication not provided by proxy

Error - OCI_INVALID_HANDLE
Error - ORA-28183: proper authentication not provided by proxy

Error - OCI_INVALID_HANDLE
Error - ORA-28183: proper authentication not provided by proxy

Error - OCI_INVALID_HANDLE
Error - ORA-28183: proper authentication not provided by proxy

Error - OCI_INVALID_HANDLE
Error - ORA-28183: proper authentication not provided by proxy

Error - OCI_INVALID_HANDLE
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 6
Error - ORA-28183: proper authentication not provided by proxy

Error - OCI_INVALID_HANDLE
Error - ORA-28183: proper authentication not provided by proxy

Error - OCI_INVALID_HANDLE
Error - ORA-28183: proper authentication not provided by proxy

Error - OCI_INVALID_HANDLE
Hit enter to end connections:
$
8. Run proxy_user with the following command line:
$ ./proxy_user orcl pfay oracle_4U
This command connects PFAY with a password. Should this work? Why?
Answer: The program should work because the PFAY user now connects with a password.
$ ./proxy_user orcl pfay oracle_4U
Database: orcl
Username: pfay
Password: oracle_4U
Successful connection: Username: HRAPP
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Hit enter to end connections:
$
9. Select the information from the data dictionary that shows the users for whom HRAPP can
proxy. (This is the same query as in step 5.) What is different from the query output in step
5?
Answer: The AUTHENTICATION column values have changed to indicate that PFAY
requires a password to connect.
$ sqlplus sec
Enter password: ******

Connected to:

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 7
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL>
SQL> COL proxy FORMAT A6
SQL> COL client FORMAT A6
SQL> COL authentication FORMAT A12 WORD
SQL>
SQL> SELECT
proxy,
client,
authentication,
authorization_constraint
FROM dba_proxies
WHERE proxy = 'HRAPP';
2 3 4 5 6
PROXY CLIENT AUTHENTICATI AUTHORIZATION_CONSTRAINT
------ ------ ------------ -------------------------------
HRAPP PFAY YES PROXY MAY ACTIVATE ALL CLIENT ROLES

SQL>
10. Change the PFAY user so that she can no longer connect through the middle tier.
SQL> ALTER USER pfay REVOKE CONNECT THROUGH hrapp;

User altered.

SQL> exit
$
11. Run proxy_user with the following command:
$ ./proxy_user orcl pfay oracle_4U
This command connects PFAY with a password. Should this work? Why?
Answer: The program works because the PFAY user connects with a password.
$ ./proxy_user orcl pfay oracle_4U
Database: orcl
Username: pfay
Password: oracle_4U
Successful connection: Username: HRAPP
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 8
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Hit enter to end connections:
$
12. Run proxy_user with the following command line:
$ ./proxy_user orcl pfay
This command connects PFAY without a password. Should this work? Why?
The program should not work because the PFAY user requires a password to connect. Note
that the error message is different from the message in step 7. Users do not require the
CONNECT THROUGH privilege if they connect with a username and password.
$ ./proxy_user orcl pfay
Database: orcl
Username: pfay
Password:
Successful connection: Username: HRAPP
Error - ORA-01017: invalid username/password; logon denied

Error - OCI_INVALID_HANDLE
Error - ORA-01017: invalid username/password; logon denied

Error - OCI_INVALID_HANDLE
Error - ORA-01017: invalid username/password; logon denied

Error - OCI_INVALID_HANDLE
Error - ORA-01017: invalid username/password; logon denied

Error - OCI_INVALID_HANDLE
Error - ORA-01017: invalid username/password; logon denied

Error - OCI_INVALID_HANDLE
Error - ORA-01017: invalid username/password; logon denied

Error - OCI_INVALID_HANDLE
Error - ORA-01017: invalid username/password; logon denied

Error - OCI_INVALID_HANDLE
Error - ORA-01017: invalid username/password; logon denied

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 9
Error - OCI_INVALID_HANDLE
Error - ORA-01017: invalid username/password; logon denied

Error - OCI_INVALID_HANDLE
Error - ORA-01017: invalid username/password; logon denied

Error - OCI_INVALID_HANDLE
Hit enter to end connections:
$
13. Display the audited connections as the proxy user.
$ sqlplus / AS SYSDBA

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> COL dbusername FORMAT A10
SQL> COL dbproxy_username FORMAT A10
SQL> COL return_code FORMAT 999999
SQL> SELECT DISTINCT dbusername, dbproxy_username, return_code,
authentication_type
FROM unified_audit_trail
WHERE dbproxy_username='HRAPP';
2 3 4
DBUSERNAME DBPROXY_US RETURN_CODE
---------- ---------- -----------
AUTHENTICATION_TYPE
----------------------------------------------------------------
-
PFAY HRAPP 1017
(TYPE=(DATABASE));(CLIENT
ADDRESS=((ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=
43150))));

PFAY HRAPP 28183


(TYPE=(DATABASE));(CLIENT
ADDRESS=((ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=
24516))));

PFAY HRAPP 28183


(TYPE=(DATABASE));(CLIENT
ADDRESS=((ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 10
24513))));

PFAY HRAPP 28183


(TYPE=(DATABASE));(CLIENT
ADDRESS=((ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=
24443))));

PFAY HRAPP 0
(TYPE=(PROXY));(CLIENT
ADDRESS=((ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=242
83))));

PFAY HRAPP 1017


(TYPE=(DATABASE));(CLIENT
ADDRESS=((ADDRESS=(PROTOCOL=tcp)(HOST=127.0.0.1)(PORT=
43157))));

… rows deleted

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 11
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 8: Using Proxy Authentication


Chapter 8 - Page 12
Practices for Lesson 9: Using
Privileges and Roles
Chapter 9

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 1
Practices for Lesson 9: Overview
Practices Overview
In these practices, the security officer will implement privileges and roles and grant them to
users according to their respective job in the company.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 2
Practice 9-1: Exploring DBA Privileges
Overview
In this practice, the security officer will manage the DBA role privileges in the non-CDB and in
the PDBs of the CDB.

Tasks
1. Investigate the number of privileges of the DBA in the non-CDB.
a. Use the oraenv utility to set the ORACLE_SID environment variable to the orcl value.
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
b. Connect as SYSTEM in orcl instance.
$ sqlplus system

Enter password: ******

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> SELECT * FROM session_roles ORDER BY 1;

ROLE
----------------------------------------------------------------
-
AQ_ADMINISTRATOR_ROLE
CAPTURE_ADMIN
DATAPUMP_EXP_FULL_DATABASE
DATAPUMP_IMP_FULL_DATABASE
DBA
DELETE_CATALOG_ROLE
EM_EXPRESS_ALL
EM_EXPRESS_BASIC
EXECUTE_CATALOG_ROLE
EXP_FULL_DATABASE
GATHER_SYSTEM_STATISTICS
HS_ADMIN_EXECUTE_ROLE

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 3
HS_ADMIN_SELECT_ROLE
IMP_FULL_DATABASE
JAVA_ADMIN
JAVA_DEPLOY
OLAP_DBA
OLAP_XS_ADMIN
OPTIMIZER_PROCESSING_RATE
SCHEDULER_ADMIN
SELECT_CATALOG_ROLE
WM_ADMIN_ROLE
XDBADMIN
XDB_SET_INVOKER
XS_RESOURCE

25 rows selected.

SQL> SELECT * FROM session_privs ORDER BY 1;

PRIVILEGE
----------------------------------------
ADMINISTER ANY SQL TUNING SET
ADMINISTER DATABASE TRIGGER
ADMINISTER RESOURCE MANAGER
ADMINISTER SQL MANAGEMENT OBJECT
ADMINISTER SQL TUNING SET
ADVISOR
… rows deleted
UNLIMITED TABLESPACE
UPDATE ANY CUBE
UPDATE ANY CUBE BUILD PROCESS
UPDATE ANY CUBE DIMENSION
UPDATE ANY TABLE
USE ANY SQL TRANSLATION PROFILE

214 rows selected.

SQL>
Notice that the SYSTEM user is not granted the SYSDBA privilege.
c. Connect as SYS in orcl instance.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> SELECT * FROM session_roles ORDER BY 1;
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 4
no rows selected

SQL> SELECT * FROM session_privs ORDER BY 1;

PRIVILEGE
----------------------------------------
ADMINISTER ANY SQL TUNING SET
ADMINISTER DATABASE TRIGGER
… rows deleted
SYSDBA
SYSOPER
TRANSLATE ANY SQL
UNDER ANY TABLE
UNDER ANY TYPE
UNDER ANY VIEW
UNLIMITED TABLESPACE
UPDATE ANY CUBE
UPDATE ANY CUBE BUILD PROCESS
UPDATE ANY CUBE DIMENSION
UPDATE ANY TABLE
USE ANY SQL TRANSLATION PROFILE

233 rows selected.

SQL> EXIT
$
2. Now investigate if there are distinct DBAs for the root container and in the pdb1_1 and
pdb1_2 containers in cdb1 instance.
a. Use the oraenv utility to set the ORACLE_SID environment variable to the cdb1 value.
$ . oraenv
ORACLE_SID = [orcl] ? cdb1
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
b. Connect as SYSTEM in cdb1 instance.
$ sqlplus system

Enter password: ******


Last Successful login time: Mon Jun 17 2013 05:38:37 +00:00

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 5
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options

SQL> col role format a30


SQL> SELECT role, common, con_id FROM cdb_roles
WHERE role like '%DBA%';

ROLE COM CON_ID


---------------------- --- ------
DBA YES 3
CDB_DBA YES 3
PDB_DBA YES 3
XDBADMIN YES 3
OLAP_DBA YES 3
LBAC_DBA YES 3
DBA YES 2
CDB_DBA YES 2
PDB_DBA YES 2
XDBADMIN YES 2
OLAP_DBA YES 2
LBAC_DBA YES 2
DBA YES 1
CDB_DBA YES 1
PDB_DBA YES 1
XDBADMIN YES 1
OLAP_DBA YES 1
LBAC_DBA YES 1
DBA YES 4
CDB_DBA YES 4
PDB_DBA YES 4
XDBADMIN YES 4
OLAP_DBA YES 4
LBAC_DBA YES 4

24 rows selected.

SQL>
There are two types of DBA roles. The common DBA role systematically granted to any
SYSTEM user created in a new PDB: the DBA role owns many system privileges. The
common PDB_DBA role is also systematically granted to any SYSTEM user created in a new
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 6
PDB. The common PDB_DBA owns only three system privileges. In each PDB, the user
being granted the DBA role, like the SYSTEM user, is able to grant distinct responsibilities to
the administrators of the PDB he is responsible for.
SQL> COL username FORMAT A14
SQL> SELECT username, con_id
FROM cdb_users
WHERE username = 'SYSTEM' ;

USERNAME CON_ID
-------------- ----------
SYSTEM 1
SYSTEM 4
SYSTEM 3
SYSTEM 2

SQL>
There are as many DBAs as containers: one for the root container and one DBA for each
PDB.
c. Connect as the pdb1_1 DBA to create a junior DBA who you grant the local PDB_DBA
role.
SQL> CONNECT system@pdb1_1
Enter password: ******
Connected.
SQL> COL grantee FORMAT A16
SQL> COL privilege FORMAT A26
SQL> SELECT * FROM dba_sys_privs WHERE grantee='PDB_DBA';

GRANTEE PRIVILEGE ADM COM


---------------- -------------------------- --- ---
PDB_DBA CREATE SESSION NO NO
PDB_DBA SET CONTAINER NO NO
PDB_DBA CREATE PLUGGABLE DATABASE NO NO

SQL> CREATE USER dba_junior IDENTIFIED BY oracle_4U;

User created.

SQL> GRANT create any table,


create user, create role,
create tablespace TO pdb_dba;
2 3
Grant succeeded.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 7
SQL> GRANT pdb_dba TO dba_junior;

Grant succeeded.

SQL> CONNECT dba_junior@pdb1_1


Enter password: ******
Connected.
SQL> SELECT * FROM session_privs;

PRIVILEGE
----------------------------------------
CREATE SESSION
CREATE TABLESPACE
CREATE USER
CREATE ANY TABLE
CREATE ROLE
CREATE PLUGGABLE DATABASE
SET CONTAINER

7 rows selected.

SQL>
d. Connect as the pdb1_2 DBA to create a junior DBA who you grant the local PDB_DBA
role with different privileges.
SQL> CONNECT system@pdb1_2
Enter password: ******
Connected.
SQL> CREATE USER dba_junior IDENTIFIED BY oracle_4U;

User created.

SQL> GRANT create user, create role,


create tablespace TO pdb_dba;
2
Grant succeeded.

SQL> GRANT pdb_dba TO dba_junior;

Grant succeeded.

SQL> CONNECT dba_junior@pdb1_2


Enter password: ******

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 8
Connected.
SQL> SELECT * FROM session_privs;

PRIVILEGE
--------------------------
SET CONTAINER
CREATE PLUGGABLE DATABASE
CREATE ROLE
CREATE USER
CREATE TABLESPACE
CREATE SESSION

6 rows selected.

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 9
Practice 9-2: Granting SYSBACKUP Administrative Privilege
Overview
In this practice, you manage the password file with the new 12 format dedicated to new
administrative privileges like SYSBACKUP.

Tasks
1. Make sure you are in the ~/labs/PRIV directory and your environment points to the orcl
instance.
$ cd ~/labs/PRIV
$ . oraenv
ORACLE_SID = [cdb1] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
2. Run the SYSBACKUP_setup.sh script to recreate the password file.
$ ./SYSBACKUP_setup.sh
$
3. Connect with OS authentication with AS SYSBACKUP and check the user connected.
$ sqlplus / as sysbackup

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> show user


USER is "SYSBACKUP"
SQL>
4. List the privileges granted to SYSBACKUP user. Only a few privileges are granted to
SYSBACKUP user. The SYSBACKUP privilege is granted to SYSBACKUP user.
SQL> select * from session_privs;

PRIVILEGE
----------------------------------------
SYSBACKUP
SELECT ANY TRANSACTION
SELECT ANY DICTIONARY
RESUMABLE
CREATE ANY DIRECTORY
ALTER DATABASE
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 10
AUDIT ANY
CREATE ANY CLUSTER
CREATE ANY TABLE
UNLIMITED TABLESPACE
DROP TABLESPACE
ALTER TABLESPACE
ALTER SESSION
ALTER SYSTEM

14 rows selected.

SQL>
5. Connect AS SYSDBA and list the privileges granted to SYS user. There are much more
privileges granted to SYS user.
SQL> connect / as sysdba
Connected.
SQL> select * from session_privs;

PRIVILEGE
----------------------------------------
EXEMPT DDL REDACTION POLICY
EXEMPT DML REDACTION POLICY
LOGMINING
rows deleted …
AUDIT SYSTEM
ALTER SYSTEM

233 rows selected.

SQL>
6. Display from the V$PWFILE_USERS view. SYS user is the only user defined in the
password file with SYSDBA and SYSOPER privileges only. SYSBACKUP user is not registered
in the password file.
SQL> select * from v$pwfile_users;

USERNAME SYSDB SYSOP SYSAS SYSBA SYSDG SYSKM CON_ID


-------- ----- ----- ----- ----- ----- ----- ------
SYS TRUE TRUE FALSE FALSE FALSE FALSE 0

SQL>
7. Create a new user JOHN that will be granted the SYSBACKUP privilege in order to perform
backup, restore, and recover operations, hence act as the SYSBACKUP user.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 11
SQL> CREATE USER john IDENTIFIED BY oracle_4U;

User created.

SQL> GRANT create session, sysbackup TO john;


GRANT create session, sysbackup TO john
*
ERROR at line 1:
ORA-28017: The password file is in the legacy format.

SQL> EXIT
$
8. Because the password file had been created in legacy format, not compatible with the
SYSBACKUP entry, it does not accept any SYSBACKUP entry.
a. Recreate the file in 12 format, compatible with the SYSBACKUP entry.
$ cd $ORACLE_HOME/dbs
$ rm orapworcl
$ orapwd file=orapworcl password=oracle_4U entries=10 format=12
$
b. Finally register JOHN in the password file.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> grant create session, SYSBACKUP to john;

Grant succeeded.

SQL> select * from v$pwfile_users;

USERNAME SYSDB SYSOP SYSAS SYSBA SYSDG SYSKM CON_ID


-------------- ----- ----- ----- ----- ----- ----- ----------
SYS TRUE TRUE FALSE FALSE FALSE FALSE 0
JOHN FALSE FALSE FALSE TRUE FALSE FALSE 0

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 12
c. Attempt a remote connection in SQL*Plus.
SQL> connect john@orcl as SYSBACKUP
Enter password: ******
Connected.
SQL> SHOW USER
USER is "SYSBACKUP"
SQL> EXIT
$
d. Test the remote connection in RMAN.
$ rman target john/oracle_4U@orcl

Recovery Manager: Release 12.1.0.1.0 - Production on Mon Nov 26


06:28:43 2012

Copyright (c) 1982, 2012, Oracle and/or its affiliates. All


rights reserved.

RMAN-00571: ==================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS
RMAN-00571: ==================================================
RMAN-00554: initialization of internal recovery manager package
failed
RMAN-04005: error from target database:
ORA-01031: insufficient privileges
$
$ rman target '"john@orcl AS SYSBACKUP"'

target database Password: ******


connected to target database: ORCL (DBID=1345659572)

RMAN> select user from dual;

using target database control file instead of recovery catalog


USER
------------------------------
SYSBACKUP

RMAN> exit

Recovery Manager complete.


$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 13
Practice 9-3: Implementing a Secure Application Role
Overview

This practice depends on Practices 4-1 and 8-1 for users and roles. It assumes that the SEC
user has been created and granted certain privileges, and that the PFAY and HRAPP users have
also been created.

Tasks
1. As the SEC user, create the HR_EMP_CLERK and HR_EMP_MGR roles. If you need to create
the SEC user, use the /home/oracle/labs/USERS/create_sec.sh shell script.
$ sqlplus sec
Enter password: ******
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> CREATE ROLE hr_emp_clerk;

Role created.

SQL> CREATE ROLE hr_emp_mgr;

Role created.

SQL>
2. Grant PFAY the HR_EMP_CLERK and HR_EMP_MGR roles. The PFAY user was created in
Practice 8-1.
SQL> GRANT hr_emp_clerk, hr_emp_mgr TO pfay;

Grant succeeded.

SQL>
3. Give PFAY the ability to enable the HR_EMP_CLERK role through the HRAPP middle tier.
SQL> ALTER USER pfay
GRANT CONNECT THROUGH hrapp
WITH ROLE hr_emp_clerk;
2 3

User altered.

SQL> EXIT
$
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 14
4. The proxy_role program enables roles through the middle tier. You simulate a middle tier
by using a service name in the connect string. This program has the following arguments:
Connection (TNS) name: Required
Name of the role to be enabled: Required
Username: Required
Password: Optional
The program performs the following steps:
1) Connects as the HRAPP user
2) Creates a connection pool of 10 connections
3) Creates 10 threads that connect to the database by using one of the connections
from the pool. The proxy_role program makes these connections using the
username and password parameters.
4) Enables the role for the user
Test the user that you created by executing proxy_role (from the operating system
prompt) with the following command line:
$ /home/oracle/labs/PROXY/proxy_role orcl hr_emp_clerk pfay
This command connects PFAY without a password and enables the HR_EMP_CLERK role.
Should this work? Why?

Be sure to use the name of your database instead of orcl. This works because PFAY can
enable the HR_EMP_CLERK role through HRAPP.
Note: Because each connection has its own thread, the following output is not sequential
and the order of the output lines may differ for each execution.
$ /home/oracle/labs/PROXY/proxy_role orcl hr_emp_clerk pfay
Database: orcl
Role: hr_emp_clerk
Username: pfay
Password:
Successful connection: Username: HRAPP
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Role successfully enabled: hr_emp_clerk
Successful connection: Username: pfay
Role successfully enabled: hr_emp_clerk
Successful connection: Username: pfay
Successful connection: Username: pfay
Role successfully enabled: hr_emp_clerk
Role successfully enabled: hr_emp_clerk

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 15
Role successfully enabled: hr_emp_clerk
Role successfully enabled: hr_emp_clerk
Role successfully enabled: hr_emp_clerk
Role successfully enabled: hr_emp_clerk
Role successfully enabled: hr_emp_clerk
Role successfully enabled: hr_emp_clerk
Hit enter to end connections:
$
5. Examine the source code for the proxy_role program (see the appendix titled “Source
Code”). Execute proxy_role to enable the HR_EMP_MGR role for PFAY, using the
following command line:
$ /home/oracle/labs/PROXY/proxy_role orcl hr_emp_mgr pfay
This command connects PFAY without a password and enables the HR_EMP_MGR role.
Should this work? Why?
Answer: It does not work. The reason is that PFAY does not have permission to enable the
HR_EMP_MGR role through HRAPP.
$ /home/oracle/labs/PROXY/proxy_role orcl hr_emp_mgr pfay
Database: orcl
Role: hr_emp_mgr
Username: pfay
Password:
Successful connection: Username: HRAPP
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Successful connection: Username: pfay
Error - ORA-01924: role 'HR_EMP_MGR' not granted or does not
exist

Successful connection: Username: pfay


Successful connection: Username: pfay
Error - ORA-01924: role 'HR_EMP_MGR' not granted or does not
exist

Error - ORA-01924: role 'HR_EMP_MGR' not granted or does not


exist

Successful connection: Username: pfay


Error - ORA-01924: role 'HR_EMP_MGR' not granted or does not
exist

Error - ORA-01924: role 'HR_EMP_MGR' not granted or does not


exist
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 16
Successful connection: Username: pfay
Successful connection: Username: pfay
Error - ORA-01924: role 'HR_EMP_MGR' not granted or does not
exist

Error - ORA-01924: role 'HR_EMP_MGR' not granted or does not


exist

Error - ORA-01924: role 'HR_EMP_MGR' not granted or does not


exist

Error - ORA-01924: role 'HR_EMP_MGR' not granted or does not


exist

Error - ORA-01924: role 'HR_EMP_MGR' not granted or does not


exist
Hit enter to end connections:
$
6. Select the information from the data dictionary that shows the users for whom HRAPP can
proxy. What has changed?
The AUTHORIZATION_CONSTRAINT column indicates that the proxy can only set some
roles for the end user.
$ sqlplus sec
Enter password: ******
Connected.
SQL>
SQL> COL proxy FORMAT A6
SQL> COL client FORMAT A6
SQL> COL authentication FORMAT A12 WORD
SQL>
SQL> SELECT proxy,
client,
authentication,
authorization_constraint
FROM dba_proxies
WHERE proxy = 'HRAPP';

PROXY CLIENT AUTHENTICATI AUTHORIZATION_CONSTRAINT


------ ------ ------------ -----------------------------------
HRAPP PFAY NO PROXY MAY ACTIVATE ROLE

SQL>
7. Look at the tab_app_roles.sql script. It creates a table similar to the one presented in
the lesson, which is used to limit the IP addresses from which users can enable roles.
Execute the script. Note that the SEC user connects through the listener. The
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 17
SEC.APP_ROLES table is populated with the IP address of the current client IP address.
The SYS_CONTEXT(‘USERENV’,’IP_ADDRESS’) function is not populated unless the
user connects through the listener. You must enter the net service name of your database.
Enter the name of your database in the form of orcl. Remember that the password for SEC
is oracle_4sec.
SQL> @/home/oracle/labs/PRIV/tab_app_roles.sql
SQL> CONNECT sec@orcl
Enter password: ******
Connected.
SQL>
SQL> ALTER USER sec DEFAULT TABLESPACE example QUOTA UNLIMITED
ON example;

User altered.

SQL>
SQL> DROP TABLE app_roles;
DROP TABLE app_roles
*
ERROR at line 1:
ORA-00942: table or view does not exist

SQL> CREATE TABLE app_roles (id NUMBER CONSTRAINT app_roles_pk


PRIMARY KEY,
username VARCHAR2(30)NOT NULL, role VARCHAR2(30), ip_address
VARCHAR2(15),
CONSTRAINT app_roles_uk UNIQUE (username, role, ip_address));

Table created.

SQL> INSERT INTO app_roles


2 VALUES (1, 'PFAY', 'HR_EMP_MGR',
3 sys_context('userenv','ip_address'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL>
8. As the SEC user, drop the HR_EMP_MGR role.
SQL> DROP ROLE hr_emp_mgr;
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 18
Role dropped.

SQL>
9. Create a secure application role with the following properties:
Name: HR_EMP_MGR
Enabled in the SEC.APP_ROLES_PKG package
SQL> CREATE ROLE hr_emp_mgr IDENTIFIED USING sec.app_roles_pkg;

Role created.

SQL>
10. Review the application code. How does it verify that the role can be enabled? Execute the
application code.
set echo on
DROP PACKAGE app_roles_pkg;

CREATE OR REPLACE PACKAGE app_roles_pkg


AUTHID CURRENT_USER
IS
PROCEDURE set_role (
p_role_name VARCHAR2 );
END;
/

CREATE OR REPLACE PACKAGE BODY app_roles_pkg IS


PROCEDURE set_role (
p_role_name VARCHAR2 )
AS
v_id app_roles.id%TYPE;
BEGIN
SELECT id
INTO v_id
FROM sec.app_roles
WHERE username = sys_context('userenv','current_user')
AND role = p_role_name
AND ip_address = sys_context('userenv','ip_address');
dbms_session.set_role(p_role_name);
END;
END;
/

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 19
The role can be enabled if the role name, username, and IP address of the client are in the
APP_ROLES table. This restricts which users can enable which roles from a particular client
address.
SQL> set echo on
SQL>
SQL> DROP PACKAGE app_roles_pkg;
DROP PACKAGE app_roles_pkg
*
ERROR at line 1:
ORA-04043: object APP_ROLES_PKG does not exist

SQL>
SQL> CREATE OR REPLACE PACKAGE app_roles_pkg
AUTHID CURRENT_USER
IS
PROCEDURE set_role (
p_role_name VARCHAR2 );
END;
/
2 3 4 5 6 7

Package created.

SQL>
SQL> CREATE OR REPLACE PACKAGE BODY app_roles_pkg IS
PROCEDURE set_role (
p_role_name VARCHAR2 )
AS
v_id app_roles.id%TYPE;
BEGIN
SELECT id
INTO v_id
FROM sec.app_roles
WHERE username =
sys_context('userenv','current_user')
AND role = p_role_name
AND ip_address = sys_context('userenv','ip_address');
dbms_session.set_role(p_role_name);
END;
END;
/

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 20
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16
Package body created.

SQL>
11. As the SEC user, allow anyone to execute the SEC.APP_ROLES_PKG package and select
from the SEC.APP_ROLES table. The user needs read access to the table because the
package runs by using the privileges of the current user. What security problems does this
create, and how can they be resolved?
SQL> GRANT execute ON app_roles_pkg TO public;

Grant succeeded.

SQL> GRANT select ON app_roles TO public;

Grant succeeded.

SQL>
12. Allowing anyone to execute the SEC.APP_ROLES_PKG package does not create any
security problems because the appropriate row must appear in the APP_ROLES table
before a role can be enabled. Giving read access to SEC.APP_ROLES allows any user to
see which users can enable which roles from a client. If this is determined to be a security
risk, you can create a view that shows only those rows that are related to the current user.
The view would include the following predicate:
WHERE username = sys_context('userenv','current_user')
Test by performing the following steps:
a. Connect as PFAY through the listener (you must use a service name orcl). Be sure
to use your instance name instead of orcl.
b. Query SESSION_ROLES to see which roles are enabled.
c. Use the SEC.APP_ROLES_PKG package to enable the role.
d. Query SESSION_ROLES to see which roles are enabled.
Note: The HR_EMP_CLERK role that is enabled after the initial connection is from a
previous step.
SQL> CONNECT pfay@orcl
Enter password: ******
Connected.
SQL>
SQL> SELECT * FROM session_roles;

ROLE
------------------------------
HR_EMP_CLERK

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 21
SQL>
SQL> EXEC sec.app_roles_pkg.set_role('HR_EMP_MGR');

PL/SQL procedure successfully completed.

SQL>
SQL> SELECT * FROM session_roles;

ROLE
------------------------------
HR_EMP_MGR

SQL>
13. What do you expect will happen if, as the PFAY user, you try to enable the HR_EMP_MGR
role by using the SET ROLE command? Try it.
Answer: It should return an error because it is a secure application role.
SQL> SET ROLE hr_emp_mgr;
SET ROLE hr_emp_mgr
*
ERROR at line 1:
ORA-28201: Not enough privileges to enable application role
'HR_EMP_MGR'

SQL>
14. As the SEC user, select the secure application role information from the data dictionary.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL>
SQL> COL role FORMAT A12
SQL> COL schema FORMAT A12
SQL> COL package FORMAT A30
SQL>
SQL> SELECT *
FROM dba_application_roles
WHERE ROLE = 'HR_EMP_MGR';
2 3 4

ROLE SCHEMA PACKAGE


------------ ------------ ------------------------------
HR_EMP_MGR SEC APP_ROLES_PKG

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 22
Practice 9-4: Enabling Roles at Run Time Using CBAC
Overview
In this practice, you will learn how to enable database roles at run time, enabling the procedure
unit to execute with the required privileges in the calling user's environment. This is called
CBAC (Code Based Access Control)

Tasks
1. Before testing the CBAC feature, execute the CBAC_priv.sql script. This script creates
the end users U1 and the schema APP, and the APP.T1 table.
SQL> CONNECT / as sysdba
Connected.
SQL> @/home/oracle/labs/PRIV/CBAC_priv.sql
SQL> drop user u1 cascade;
drop user u1 cascade
*
ERROR at line 1:
ORA-01918: user 'U1' does not exist

SQL> drop user app cascade;


drop user app cascade
*
ERROR at line 1:
ORA-01918: user 'APP' does not exist

SQL>
SQL> create user u1 identified by oracle_4U default tablespace
users;

User created.

SQL> grant create session, create procedure to u1;

Grant succeeded.

SQL> create user app identified by oracle_4U default tablespace


users;

User created.

SQL> grant create session, create table, create procedure,


unlimited tablespace to app;

Grant succeeded.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 23
SQL> create table app.T1 (code number);

Table created.

SQL> insert into app.T1 values (1);

1 row created.

SQL>
SQL> commit;

Commit complete.

SQL>
SQL>
2. The APP schema creates two procedures: an invoker’s right procedure, IVPROC and a
definer’s right procedure, DFPROC.
a. Create the two procedures using the following codes:
CREATE OR REPLACE PROCEDURE app.ivproc (CODE in varchar2)
AUTHID CURRENT_USER AS
v_code number;
BEGIN
SELECT code INTO v_code FROM app.t1;
dbms_output.put_line('Code is: '||v_code);
END ivproc;
/
SQL> CONNECT app
Enter password: ******
Connected.

SQL> CREATE OR REPLACE PROCEDURE app.ivproc (CODE in varchar2)


AUTHID CURRENT_USER AS
v_code number;
BEGIN
SELECT code INTO v_code FROM app.t1;
dbms_output.put_line('Code is from Invoker right procedure:
'||v_code);
END ivproc;
/
2 3 4 5 6 7 8
Procedure created.

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 24
b. Create the second procedure.
CREATE OR REPLACE PROCEDURE app.dfproc (CODE in varchar2)
AS
v_code number;
BEGIN
SELECT code INTO v_code FROM app.t1;
dbms_output.put_line('Code is from Definer right procedure:
'||v_code);
END dfproc;
/
SQL> CREATE OR REPLACE PROCEDURE app.dfproc (CODE in varchar2)
AS
v_code number;
BEGIN
SELECT code INTO v_code FROM app.t1;
dbms_output.put_line('Code is from Definer right procedure:
'||v_code);
END dfproc;
/
2 3 4 5 6 7 8
Procedure created.

SQL>
3. You create the ROLE1 role. Grant SELECT on APP.T1 to the role. Create ROLE2. Grant
SELECT on SH.SALES to the role and grant the role directly to the end user U1.
SQL> CONNECT / as sysdba
Connected.

SQL> CREATE ROLE role1;

Role created.

SQL> GRANT select ON APP.T1 to role1;

Grant succeeded.

SQL> CREATE ROLE role2;

Role created.

SQL> GRANT select ON SH.SALES to role2;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 25
Grant succeeded.

SQL> GRANT role2 TO u1;

Grant succeeded.

SQL>
4. Grant the ROLE1 role to invoker’s right procedure, IVPROC and to the definer’s right
procedure, DFPROC.
SQL> CONNECT app
Enter password: ******
Connected.
SQL> GRANT role1 TO PROCEDURE app.ivproc;
GRANT role1 TO PROCEDURE app.ivproc
*
ERROR at line 1:
ORA-01924: role 'ROLE1' not granted or does not exist

SQL>
5. Because the CBAC roles can only be granted to a program unit when the role is directly
granted to the procedures’ owner, grant the ROLE1 role to the APP procedures’ owner.
SQL> CONNECT / as sysdba
Connected.
SQL> GRANT role1 TO app;

Grant succeeded.

SQL>
6. Now grant the role to the procedural units.
SQL> CONNECT app
Enter password: ******
Connected.
SQL> GRANT role1 TO PROCEDURE app.ivproc, PROCEDURE app.dfproc ;

Grant succeeded.

SQL>
7. Grant the EXECUTE privilege on both procedures to the U1 end user.
SQL> GRANT execute ON app.ivproc TO u1;

Grant succeeded.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 26
SQL> GRANT execute ON app.dfproc TO u1;

Grant succeeded.

SQL>
8. Connect as U1 and test how the CBAC enables roles at run time.
a. Test the app.ivproc procedure.
SQL> CONNECT u1
Enter password: ******
Connected.
SQL> SELECT * FROM session_roles;

ROLE
----------------------------------------------------------------
-
ROLE2

SQL> SET SERVEROUTPUT ON


SQL> EXEC app.ivproc(1)
Code is from Invoker right procedure: 1

PL/SQL procedure successfully completed.

SQL> SELECT * FROM session_roles;

ROLE
----------------------------------------------------------------
-
ROLE2

SQL>
Notice that the active role at login time is ROLE2 only.
b. Test the app.dfproc procedure.
SQL> EXEC app.dfproc(1)
Code is from Definer right procedure: 1

PL/SQL procedure successfully completed.

SQL> SELECT * FROM session_roles;

ROLE

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 27
----------------------------------------------------------------
ROLE2

SQL>
Notice that the execution completes as in 8.a.
c. Drop ROLE1 and retest.
SQL> CONNECT system
Enter password: ******
Connected.
SQL> DROP ROLE role1;

Role dropped.

SQL> CONNECT u1
Enter password: ******
Connected.
SQL> SELECT * FROM session_roles;

ROLE
----------------------------------------------------------------
-
ROLE2

SQL> SET SERVEROUTPUT ON


SQL> EXEC app.ivproc(1)
BEGIN app.ivproc(1); END;

*
ERROR at line 1:
ORA-00942: table or view does not exist
ORA-06512: at "APP.IVPROC", line 5
ORA-06512: at line 1

SQL> EXEC app.dfproc(1)


Code is from Definer right procedure: 1

PL/SQL procedure successfully completed.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 28
Practice 9-5: Executing Invoker's Right Procedure Using INHERIT
PRIVILEGES Privilege (Optional)
Overview
In this practice you will use the new INHERIT PRIVILEGES privilege when creating invoker’s
rights procedures.

Tasks
1. Connected as SYSTEM, execute the inherit_priv.sql script to create U1, U2 and KATE users
and the U2.T1 table.
SQL> CONNECT system
Enter password: ******
Connected.
SQL> @/home/oracle/labs/PRIV/inherit_priv.sql
SQL> drop user u1 cascade;

User dropped.

SQL> drop user u2 cascade;


drop user u2 cascade
*
ERROR at line 1:
ORA-01918: user 'U2' does not exist

SQL> drop user kate;


drop user kate
*
ERROR at line 1:
ORA-01918: user 'KATE' does not exist

SQL> create user kate identified by oracle_4U;

User created.

SQL> grant create session to kate;

Grant succeeded.

SQL> revoke INHERIT PRIVILEGES ON USER KATE from public;

Revoke succeeded.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 29
SQL> create user u1 identified by oracle_4U default tablespace
users;

User created.

SQL> grant create session, create procedure to u1;

Grant succeeded.

SQL> create user u2 identified by oracle_4U default tablespace


users;

User created.

SQL> grant create session, create table, unlimited tablespace to


u2;

Grant succeeded.

SQL> create table u2.T1 (code number);

Table created.

SQL> insert into u2.T1 values (1);

1 row created.

SQL> commit;

Commit complete.

SQL> grant select on u2.T1 to u1;

Grant succeeded.

SQL> grant select on u2.T1 to kate;

Grant succeeded.

SQL>
SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 30
2. The developer U1 creates an invoker’s rights procedure that selects rows from U2.T1 table.
The user U1 is granted the SELECT privilege on U2.T1 table.
a. Connect as user U1.
SQL> connect u1
Enter password: ******
Connected.
SQL>
b. Create the U1.PROC2 procedure.
CREATE OR REPLACE PROCEDURE u1.proc2 (CODE in varchar2)
AUTHID CURRENT_USER AS
v_code number;
BEGIN
SELECT code INTO v_code FROM u2.t1;
dbms_output.put_line('Code is: '||v_code);
END PROC2;
/
SQL> CREATE OR REPLACE PROCEDURE u1.proc2 (CODE in varchar2)
AUTHID CURRENT_USER AS
v_code number;
BEGIN
SELECT code INTO v_code FROM u2.t1;
dbms_output.put_line('Code is: '||v_code);
END PROC2;
/
2 3 4 5 6 7 8
Procedure created.

SQL>
c. Execute the procedure to test that it works successfully.
SQL> set serveroutput on
SQL> exec U1.PROC2('Code')
Code is: 1

PL/SQL procedure successfully completed.

SQL>
d. The developer U1 grants the EXECUTE privilege to the KATE user.
SQL> grant execute on U1.PROC2 to KATE;

Grant succeeded.

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 31
3. KATE wants to test the procedure.
a. KATE has no privilege on U2.T1 table. KATE connects and executes the procedure.
SQL> CONNECT kate
Enter password: ******
Connected.
SQL> set serveroutput on
SQL> exec U1.PROC2('Code')
BEGIN U1.PROC2('Code'); END;

*
ERROR at line 1:
ORA-06598: insufficient INHERIT PRIVILEGES privilege
ORA-06512: at "U1.PROC2", line 1
ORA-06512: at line 1

SQL>
b. KATE grants the INHERIT PRIVILEGES on user KATE to procedure owner U1 thus
allowing U1 to inherit her privileges during the execution of the procedure
SQL> grant INHERIT PRIVILEGES ON USER kate TO U1;

Grant succeeded.

SQL>
c. KATE re-executes the procedure.
SQL> exec U1.PROC2('Code')
Code is: 1

PL/SQL procedure successfully completed.

SQL>
4. Display the users being granted the INHERIT PRIVILEGES privilege. There is a new
object type ‘USER’ and the table name is the user name controlling who can access his
privileges when he runs an invoker’s rights procedure.
SQL> connect / as sysdba
Connected.

SQL> COL privilege FORMAT A20


SQL> COL type FORMAT A6
SQL> COL table_name FORMAT A10
SQL> COL grantee FORMAT A8
SQL> select PRIVILEGE, TYPE, TABLE_NAME, GRANTEE
from DBA_TAB_PRIVS where grantee='U1';

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 32
PRIVILEGE TYPE TABLE_NAME GRANTEE
-------------------- ------ ---------- --------
SELECT TABLE T1 U1
INHERIT PRIVILEGES USER KATE U1

SQL>
5. Be aware that newly created users are granted the INHERIT PRIVILEGES privilege
because the INHERIT PRIVILEGES privilege is granted to PUBLIC. The user KATE was
revoked the INHERIT PRIVILEGES privilege at the beginning of the practice.
a. Create a new user.
SQL> CREATE USER newuser IDENTIFIED BY newuser;

User created.

SQL>
b. Check the privileges granted to NEWUSER.
SQL> select PRIVILEGE, TYPE, TABLE_NAME, GRANTEE
from DBA_TAB_PRIVS
where grantor='NEWUSER';
2 3 4

PRIVILEGE TYPE TABLE_NAME GRANTEE


-------------------- ------ ---------- --------
INHERIT PRIVILEGES USER NEWUSER PUBLIC

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 33
Practice 9-6: BEQUEATH Current_user Views Using INHERIT
PRIVILEGES (Optional)
Overview
In this practice you understand the different types of BEQUEATH views: the CURRENT_USER and
the DEFINER views.

Assumption
The bequeath_setup.sql script is successfully completed.

Tasks
1. Make sure you are at the ~/labs/PRIV directory and your environment points to the orcl
instance. Connect under SYSTEM user.
$ cd ~/labs/PRIV
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
2. Execute the bequeath_setup.sql script. The script creates users and grants
appropriate privileges to the developer U1 and the end user KATE.
$ sqlplus SYSTEM

Enter password: ******


Last Successful login time: Mon Jun 17 2013 09:51:24 +00:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL>
SQL> @bequeath_setup.sql
Connected.
REVOKE select any table from OE
*
ERROR at line 1:
ORA-01952: system privileges not granted to 'OE'

User dropped.

User dropped.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 34
User dropped.

User created.

Grant succeeded.

Revoke succeeded.

User created.

Grant succeeded.

SQL>
3. The developer U1 creates a BEQUEATH CURRENT_USER view. The view displays the
current user connected.
a. The user U1 connects and creates the view V_WHOAMI.
SQL> CONNECT u1
Enter password: ******
Connected.
SQL> CREATE OR REPLACE VIEW u1.v_whoami
BEQUEATH CURRENT_USER
AS SELECT ORA_INVOKING_USER "WHOAMI" FROM DUAL;
2 3
View created.

SQL>
b. The developer checks that the view V_WHOAMI works successfully.
SQL> select * from U1.V_WHOAMI;

WHOAMI
---------------------------------------------------------
U1

SQL>
4. The same developer U1 creates an BEQUEATH DEFINER view. The view displays the
current user connected.
a. The user U1 connects and creates the view V_WHOAMI_DEF.
SQL> CREATE OR REPLACE VIEW u1.v_whoami_def
BEQUEATH DEFINER
AS SELECT ORA_INVOKING_USER "WHOAMI" FROM DUAL;
2 3
View created.

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 35
b. The developer checks that the view V_WHOAMI_DEF works successfully.
SQL> select * from U1.V_WHOAMI_DEF;

WHOAMI
---------------------------------------------------------
U1

SQL>
5. The developer U1 grants the SELECT privilege to KATE on both views.
SQL> grant SELECT on U1.V_WHOAMI to KATE;

Grant succeeded.

SQL> grant SELECT on U1.V_WHOAMI_DEF to KATE;

Grant succeeded.

SQL>
6. KATE connects and selects data from the BEQUEATH DEFINER view.
SQL> CONNECT kate
Enter password: ******
Connected.
SQL> select * from U1.V_WHOAMI_DEF;

WHOAMI
--------------------------------------------------------
KATE

SQL>
7. KATE selects data from the BEQUEATH CURRENT_USER view.
SQL> SELECT * FROM U1.V_WHOAMI;
select * from U1.V_WHOAMI
*
ERROR at line 1:
ORA-06598: insufficient INHERIT PRIVILEGES privilege

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 36
8. KATE grants the INHERIT PRIVILEGES ON USER KATE to the view owner U1, allowing
U1 to use her privileges during the view execution.
SQL> grant INHERIT PRIVILEGES ON USER kate TO U1;

Grant succeeded.

SQL>
9. KATE attempts the statement on the BEQUEATH CURRENT_USER view.
SQL> select * from U1.V_WHOAMI;

WHOAMI
----------------------------------------------------------
KATE

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 37
Practice 9-7: Managing Local and Common Privileges and Roles in
CDB/PDBs
Overview
In this practice, you will grant local and common privileges, create and grant local and common
roles in cdb1 and in PDBs.

Assumptions
The following users have been successfully created from previous practice 6-5.
• C##U1 common user in cdb1
• LOCAL_EMPLOYEE local user in pdb1_1 (password pass_pdb1)
• LOCAL_EMPLOYEE local user in pdb1_2 (password pass_pdb2)
Tasks
1. List all pre-defined roles in CDB.
$ . oraenv
ORACLE_SID = [orcl] ? cdb1
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options

SQL> col role format a30


SQL> select ROLE, COMMON, CON_ID from cdb_roles order by role;

ROLE COM CON_ID


------------------------------ --- ----------
ADM_PARALLEL_EXECUTE_TASK YES 3
ADM_PARALLEL_EXECUTE_TASK YES 4
ADM_PARALLEL_EXECUTE_TASK YES 2
ADM_PARALLEL_EXECUTE_TASK YES 1
APEX_ADMINISTRATOR_ROLE YES 3
APEX_ADMINISTRATOR_ROLE YES 4
APEX_ADMINISTRATOR_ROLE YES 1
APEX_ADMINISTRATOR_ROLE YES 2

DBA YES 3
DBA YES 4
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 38
DBA YES 2
DBA YES 1

XS_RESOURCE YES 3
XS_RESOURCE YES 4
XS_RESOURCE YES 1
XS_RESOURCE YES 2
XS_SESSION_ADMIN YES 3
XS_SESSION_ADMIN YES 1
XS_SESSION_ADMIN YES 2
XS_SESSION_ADMIN YES 4

337 rows selected.

SQL>
The common role is replicated in each container. The container ID 1 is the root. The
container ID 2 is the seed. The container ID 3 is the pdb1_1. The container ID 4 is the
pdb1_2.
2. View all common roles of the root.
SQL> select ROLE, COMMON from cdb_roles
WHERE CON_ID = 1
order by role;
2 3
ROLE COM
------------------------------ ---
ADM_PARALLEL_EXECUTE_TASK YES
APEX_ADMINISTRATOR_ROLE YES
APEX_GRANTS_FOR_NEW_USERS_ROLE YES
AQ_ADMINISTRATOR_ROLE YES
AQ_USER_ROLE YES
AUDIT_ADMIN YES
AUDIT_VIEWER YES

CDB_DBA YES
CONNECT YES

DBA YES

XS_RESOURCE YES
XS_SESSION_ADMIN YES

84 rows selected.

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 39
Notice that all roles of the root are common: there cannot be any local roles in the root.
3. List all local roles in PDBs. The HR_MGR local role was created in practice 6-3 task 1.
SQL> SELECT role, con_id FROM CDB_ROLES
WHERE common = 'NO' ;
2
ROLE CON_ID
------------------------------------------------ ----------
HR_MGR 3

SQL>
4. Create a common C##_ROLE in root.
SQL> create role c##_role container=ALL;

Role created.

SQL>
5. Attempt to create a LOCAL_ROLE local role in root.
SQL> create role local_role container=CURRENT;
create role local_role container=CURRENT
*
ERROR at line 1:
ORA-65049: creation of local user or role is not allowed in
CDB$ROOT

SQL>
You get an error message because no local role is authorized in the root.
6. Create a common role in pdb1_2.
SQL> CONNECT system@pdb1_2
Enter password: ******
Connected.
SQL> CREATE ROLE c##_role_PDB1_2 container=ALL;
create role c##_role_PDB1_2 container=ALL
*
ERROR at line 1:
ORA-65050: Common DDLs only allowed in CDB$ROOT

SQL>
You get an error message because no common role can be created from a PDB.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 40
7. Create a local role in pdb1_2.
SQL> CREATE ROLE local_role_PDB1_2 container=CURRENT;

Role created.

SQL> select ROLE, COMMON from dba_roles order by role;

ROLE COM
------------------------------ ---
ADM_PARALLEL_EXECUTE_TASK YES
APEX_ADMINISTRATOR_ROLE YES

C##_ROLE YES
CDB_DBA YES
CONNECT YES

DBA YES

LBAC_DBA YES
LOCAL_ROLE_PDB1_2 NO

PDB_DBA YES

XS_RESOURCE YES
XS_SESSION_ADMIN YES

86 rows selected.

SQL>
8. Grant common or local roles as common or local.
a. Grant a common role to a common user from the root.
SQL> connect / as sysdba
Connected.
SQL> grant c##_role to c##u1;

Grant succeeded.

SQL> col grantee format A16


SQL> col GRANTED_ROLE format A18
SQL> select GRANTEE, GRANTED_ROLE, COMMON, CON_ID
from cdb_role_privs where grantee='C##U1';
2
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 41
GRANTEE GRANTED_ROLE COM CON_ID
---------------- ---------------- --- ------
C##U1 C##_ROLE NO 1

SQL>
Note that the common role is granted locally to the common user. The granted role is only
applicable in the root.
SQL> connect c##u1
Enter password: ******
Connected.
SQL> select * from session_roles;

ROLE
------------------------------
C##_ROLE

SQL> connect c##u1@PDB1_2


Enter password: ******
Connected.
SQL> select * from session_roles;

no rows selected

SQL>
b. Now grant the common role to a common user from the root as common, to be
applicable in all containers.
SQL> connect / as sysdba
Connected.
SQL> grant c##_role to c##u1 container=all;

Grant succeeded.

SQL>

SQL> col grantee format A16


SQL> col GRANTED_ROLE format A18
SQL> select GRANTEE, GRANTED_ROLE, COMMON, CON_ID
from cdb_role_privs where grantee='C##U1';
2
GRANTEE GRANTED_ROLE COM CON_ID
---------------- ---------------- --- ----------

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 42
C##U1 C##_ROLE NO 1
C##U1 C##_ROLE YES 1
C##U1 C##_ROLE YES 4
C##U1 C##_ROLE YES 3

SQL> connect c##u1


Enter password: ******
Connected.
SQL> select * from session_roles;

ROLE
------------------------------
C##_ROLE

SQL> connect c##u1@PDB1_2


Enter password: ******
Connected.
SQL> select * from session_roles;

ROLE
------------------------------
C##_ROLE

SQL>
9. Revoke the common role from the common user so that the role cannot be used in any
container.
SQL> connect / as sysdba
Connected.
SQL> revoke c##_role from c##u1 container=all;

Revoke succeeded.

SQL> connect c##u1


Enter password: ******
Connected.
SQL> select * from session_roles;
ROLE
------------------------------
C##_ROLE

SQL> connect c##u1@PDB1_2


Enter password: ******

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 43
Connected.
SQL> select * from session_roles;

no rows selected

SQL>
10. Grant a common role to a local user from the root.
SQL> connect / as sysdba
Connected.
SQL> grant c##_role to local_employee;
grant c##_role to local_employee
*
ERROR at line 1:
ORA-01917: user or role 'LOCAL_EMPLOYEE' does not exist

SQL>
Note that the user is unknown in root. It is a local user in pdb1_2.
11. Grant a common role to a local user in pdb1_2.
SQL> connect system@PDB1_2
Enter password: ******
Connected.
SQL> grant c##_role to local_employee;

Grant succeeded.

SQL> select GRANTEE, GRANTED_ROLE, COMMON, CON_ID


from cdb_role_privs where grantee='LOCAL_EMPLOYEE';
2
GRANTEE GRANTED_ROLE COM CON_ID
---------------- ---------------- --- ----------
LOCAL_EMPLOYEE C##_ROLE NO 4

SQL>
Note that the user is granted a common role locally (common column = NO) applicable only
in the pdb1_2.
12. Test the connection as the local user. The password is pass_pdb2.
SQL> connect local_employee@PDB1_2
Enter password: ******
Connected.
SQL> select * from session_roles;

ROLE
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 44
------------------------------
C##_ROLE

SQL>
13. Grant a common role to a local user from pdb1_2 applicable in all containers.
SQL> connect system@PDB1_2
Enter password: ******
Connected.
SQL> grant c##_role to local_employee container=all;
grant c##_role to local_user_pdb2 container=all
*
ERROR at line 1:
ORA-65030: one may not grant a Common Privilege to a Local User
or Role

SQL>
Notice that a common role cannot be granted globally from a PDB.
14. Grant a local role to a local user from pdb1_2.
SQL> grant local_role_pdb1_2 to local_employee;

Grant succeeded.

SQL> select GRANTEE, GRANTED_ROLE, COMMON, CON_ID


from cdb_role_privs where grantee='LOCAL_EMPLOYEE';
2
GRANTEE GRANTED_ROLE COM CON_ID
---------------- ------------------ --- ----------
LOCAL_EMPLOYEE C##_ROLE NO 4
LOCAL_EMPLOYEE LOCAL_ROLE_PDB1_2 NO 4

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 45
15. Test the connection as the local user.
SQL> connect local_employee@PDB1_2
Enter password: ******
Connected.
SQL> select * from session_roles;

ROLE
------------------------------
C##_ROLE
LOCAL_ROLE_PDB1_2

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 9: Using Privileges and Roles


Chapter 9 - Page 46
Practices for Lesson 10:
Privilege Analysis
Chapter 10

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 1
Practices for Lesson 10: Overview
Practices Overview
In the practices for this lesson, you configure privileges, roles and contexts captures to make
analyses of unnecessarily granted privileges.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 2
Practice 10-1: Capturing Privileges
Overview
In this practice, you capture privileges used by users during a short period, generate the capture
results, compare between used and unused privileges to decide which privileges might need to
be revoked.

Tasks
1. Make sure you are at the ~/labs/PRIV directory and your environment points to the orcl
instance.
$ cd ~/labs/PRIV
$ . oraenv
ORACLE_SID = [cdb1] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
2. Run the priv_setup.sql script to create JIM and TOM users, HR_MGR and
SALES_CLERK roles.
$ sqlplus system

Enter password: ******


Last Successful login time: Mon Jun 17 2013 09:59:11 +00:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> @priv_setup.sql
Connected.

User dropped.

User created.

User dropped.

User created.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 3
Grant succeeded.

drop role HR_MGR


*
ERROR at line 1:
ORA-01919: role 'HR_MGR' does not exist

drop role SALES_CLERK


*
ERROR at line 1:
ORA-01919: role 'SALES_CLERK' does not exist

drop role HR_MGR_JUNIOR


*
ERROR at line 1:
ORA-01919: role 'HR_MGR_JUNIOR' does not exist

Role created.

Grant succeeded.

Grant succeeded.

Role created.

Grant succeeded.

Grant succeeded.

revoke select any table from oe


*
ERROR at line 1:

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 4
ORA-01952: system privileges not granted to 'OE'

User dropped.

drop user u2 cascade


*
ERROR at line 1:
ORA-01918: user 'U2' does not exist

User dropped.

User created.

Grant succeeded.

Revoke succeeded.

User created.

Grant succeeded.

User created.

Grant succeeded.

Table created.

1 row created.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 5
Commit complete.

Grant succeeded.

Grant succeeded.

SQL>
3. Define a capture of privileges used by all users. Use the following procedure.
exec SYS.DBMS_PRIVILEGE_CAPTURE.CREATE_CAPTURE ( -
name => 'All_privs', -
description => 'All privs used', -
type => dbms_privilege_capture.g_database)

SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.CREATE_CAPTURE ( -


name => 'All_privs', -
description=> 'All privs used', -
type => dbms_privilege_capture.g_database)
> > >
PL/SQL procedure successfully completed.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 6
4. Start capturing the privileges while users are performing their daily work using privileges.
a. Start the capture.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.ENABLE_CAPTURE ( -
name => 'All_privs')

PL/SQL procedure successfully completed.

SQL>

b. Run the priv_used_by_users.sql script. The script connects as JIM who deletes
rows from HR.EMPLOYEES table and TOM who selects rows from SH.SALES table.
SQL> @priv_used_by_users.sql
Connected.

24 rows deleted.

Commit complete.

Connected.

PROD_ID CUST_ID TIME_ID CHANNEL_ID PROMO_ID QUANTITY_SOLD


AMOUNT_SOLD
------- ------- --------- ---------- -------- ------------- ----
------------
120 6452 29-SEP-00 2 999 1
6.4
120 6452 29-SEP-00 4 999 1
6.4

SQL>
5. Stop the capture.
SQL> connect system
Enter password: ******
Connected.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.DISABLE_CAPTURE ( -
name => 'All_privs')

PL/SQL procedure successfully completed.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 7
6. Generate the capture results. It may take a few minutes.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.GENERATE_RESULT ( -
name => 'All_privs')

PL/SQL procedure successfully completed.

SQL>
7. Display the object privileges used during the capture period.
SQL> COL username FORMAT A10
SQL> COL object_owner FORMAT A12
SQL> COL object_name FORMAT A30
SQL> COL obj_priv FORMAT A25
SQL> SELECT username, object_owner, object_name, obj_priv
FROM dba_used_objprivs
WHERE username IN ('JIM', 'TOM');
2 3
USERNAME OBJECT_OWNER OBJECT_NAME OBJ_PRIV
---------- ------------ ------------------------------ -------
JIM SYS DUAL SELECT
JIM SYSTEM PRODUCT_PRIVS SELECT
TOM SYS ORA$BASE USE
TOM SYSTEM PRODUCT_PRIVS SELECT
JIM SYS DBMS_APPLICATION_INFO EXECUTE
JIM SYS ORA$BASE USE
TOM SYS DUAL SELECT
TOM SH SALES SELECT
JIM HR EMPLOYEES DELETE
JIM HR EMPLOYEES SELECT
TOM SYS DBMS_APPLICATION_INFO EXECUTE
JIM SYS DUAL SELECT
TOM SYS DUAL SELECT

13 rows selected.

SQL>
8. Display the system privileges used.
SQL> COL sys_privs form a20
SQL> SELECT username, sys_priv FROM dba_used_sysprivs
WHERE username IN ('JIM', 'TOM');
2
USERNAME SYS_PRIV
---------- --------------------
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 8
TOM CREATE SESSION
JIM CREATE SESSION

SQL>
9. Display the path of the privileges used if the privileges were granted to roles, and roles to
users.
SQL> COL object_name FORMAT A10
SQL> COL path FORMAT A32
SQL> COL obj_priv FORMAT A10
SQL> SELECT username, obj_priv, object_name, path
FROM dba_used_objprivs_path
WHERE username IN ('TOM','JIM')
AND object_name IN ('SALES','EMPLOYEES');
2 3 4
USERNAME OBJ_PRIV OBJECT PATH
---------- ---------- ---------- ---------------------------
TOM SELECT SALES GRANT_PATH('TOM',
'SALES_CLERK')

JIM DELETE EMPLOYEES GRANT_PATH('JIM', 'HR_MGR')

JIM SELECT EMPLOYEES GRANT_PATH('JIM', 'HR_MGR')

SQL>
10. JIM is granted select, update, delete, insert privileges on HR.EMPLOYEES table through
HR_MGR role. He used the DELETE and SELECT privileges until now.
The unused privileges are visible in DBA_UNUSED_PRIVS view.
SQL> SELECT username, sys_priv, obj_priv, object_name, path
FROM dba_unused_privs
WHERE username='JIM';

USERNAME SYS_PRIV OBJ_PRIV OBJECT PATH


-------- -------- -------- --------- ---------------------------
-
JIM INSERT EMPLOYEES GRANT_PATH('JIM', 'HR_MGR')
JIM UPDATE EMPLOYEES GRANT_PATH('JIM', 'HR_MGR')

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 9
11. Compare used and unused privileges. Finally you decide to revoke the INSERT privilege
from JIM, but not impact other users who benefit from the HR_MGR role.
a. You will first create a new role without the INSERT privilege and finally revoke the
HR_MGR role from JIM.
SQL> create role HR_MGR_JUNIOR;

Role created.

SQL> GRANT select, update, delete ON hr.employees


TO hr_mgr_junior;
2
Grant succeeded.

SQL>
b. Grant the new role to JIM.
SQL> grant HR_MGR_JUNIOR to JIM;

Grant succeeded.

SQL>
c. Finally revoke the powerful privileged role HR_MGR from JIM.
SQL> revoke HR_MGR from JIM;

Revoke succeeded.

SQL>
12. Display the definition of the capture. The ENABLED column ensures that the All_privs
capture has been stopped.
SQL> COL name FORMAT A12
SQL> COL type FORMAT A12
SQL> COL enabled FORMAT A2
SQL> COL roles FORMAT A26
SQL> COL context FORMAT a20
SQL> SELECT name, type, enabled,roles, context
FROM dba_priv_captures;
2
NAME TYPE EN ROLES CONTEXT
------------ ------------ -- -------------------------- --------
-
All_privs DATABASE N
SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 10
13. Delete the capture so as to remove all previous captured information from the views.
a. Execute the procedure.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.DROP_CAPTURE ( -
name => 'All_privs')

PL/SQL procedure successfully completed.

SQL>
b. Verify that there is no data left of the All_privs capture.
SQL> SELECT username, sys_priv, obj_priv, object_name, path
FROM dba_unused_privs
WHERE username='JIM';
2 3
no rows selected

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 11
Practice 10-2: Capture Privileges Used Through Roles
Overview
In this practice, you capture the privileges used by roles during a short period, generate the
capture results, compare between used and unused privileges to decide which privileges might
need to be revoked.

Tasks
1. Define a capture of privileges used by roles HR_MGR_JUNIOR and SALES_CLERK. Use the
following procedure.
exec SYS.DBMS_PRIVILEGE_CAPTURE.CREATE_CAPTURE ( -
name => 'Role_privs', -
description => 'Privs used by HR_MGR_JUNIOR, SALES_CLERK', -
type => dbms_privilege_capture.g_role, -
roles => role_name_list('HR_MGR_JUNIOR', 'SALES_CLERK'))

SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.CREATE_CAPTURE ( -


name => 'Role_privs', -
description => 'Privs used by HR_MGR_JUNIOR, SALES_CLERK', -
type => dbms_privilege_capture.g_role, -
roles => role_name_list('HR_MGR_JUNIOR', 'SALES_CLERK'))
> > > >
PL/SQL procedure successfully completed.

SQL>
2. Start capturing the privileges while users perform their daily work.
a. Start the capture.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.ENABLE_CAPTURE ( -
name => 'Role_privs')

PL/SQL procedure successfully completed.

SQL>
b. Run the priv_used_by_users.sql script. The script connects as JIM who deletes
rows from HR.EMPLOYEES table and TOM who selects rows from SH.SALES table.
SQL> @priv_used_by_users.sql
Connected.

0 rows deleted.

Commit complete.

Connected.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 12
PROD_ID CUST_ID TIME_ID CHANNEL_ID PROMO_ID QUANTITY_SOLD
AMOUNT_SOLD
------- ------- --------- ---------- -------- ------------- ----
------------
120 6452 29-SEP-00 2 999 1
6.4
120 6452 29-SEP-00 4 999 1
6.4

SQL>
3. Stop the capture.
SQL> connect system
Enter password: ******
Connected.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.DISABLE_CAPTURE ( -
name => 'Role_privs')

PL/SQL procedure successfully completed.

SQL>
4. Generate the capture results.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.GENERATE_RESULT ( -
name => 'Role_privs')

PL/SQL procedure successfully completed.

SQL>
5. Display the object privileges used by the roles HR_MGR_JUNIOR and SALES_CLERK during
the capture period.
SQL> col username FORMAT a8
SQL> col used_role FORMAT a20
SQL> col own FORMAT a4
SQL> SELECT username, object_owner "OWN", object_name,
obj_priv, used_role
FROM dba_used_objprivs
WHERE used_role IN ('HR_MGR_JUNIOR', 'SALES_CLERK');
2 3
USERNAME OWN OBJECT_NAME OBJ_PRIV USED_ROLE
-------- ---- -------------- ---------- -------------------
JIM HR EMPLOYEES SELECT HR_MGR_JUNIOR
TOM SH SALES SELECT SALES_CLERK
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 13
JIM HR EMPLOYEES DELETE HR_MGR_JUNIOR

SQL>
6. Display the system privileges used by the roles HR_MGR_JUNIOR and SALES_CLERK.
SQL> SELECT username, sys_priv, used_role
FROM dba_used_sysprivs
WHERE used_role IN ('HR_MGR_JUNIOR', 'SALES_CLERK');
2 3
no rows selected

SQL>
7. HR_MGR_JUNIOR is granted select, update, delete on HR.EMPLOYEES table. The role used
by JIM during the capture period used the DELETE and SELECT privileges until now.
The unused privileges are visible in DBA_UNUSED_PRIVS view.
SQL> SELECT sys_priv, obj_priv, object_name, path
FROM dba_unused_privs
WHERE rolename IN ('HR_MGR_JUNIOR', 'SALES_CLERK');
2 3
SYS_PRIV OBJ_PRIV OBJECT PATH
---------- ---------- ---------- ----------------------------
UPDATE EMPLOYEES GRANT_PATH('HR_MGR_JUNIOR')

SQL>
View the list of unused privileges: this list helps you decide whether to revoke or not the
UPDATE privileges granted through the HR_MGR_JUNIOR role.
8. Display the definition of the capture. The ENABLED column shows that the Role_privs
capture has been stopped. The numbers displayed in the roles list can be different from
those here.
SQL> SELECT name, type, enabled,roles, context
FROM dba_priv_captures;

NAME TYPE EN ROLES


------------ ------------ -- --------------------------
CONTEXT
--------------------------------------------------------------
Role_privs ROLE N ROLE_ID_LIST(119, 115)

SQL>
9. Delete the capture so as to remove all previous captured information from the views.
a. Execute the procedure.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.DROP_CAPTURE ( -
name=> 'Role_privs')
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 14
PL/SQL procedure successfully completed.

SQL>
b. Verify that there is no data left of the Role_privs capture.
SQL> SELECT sys_priv, obj_priv, object_name, path
FROM dba_unused_privs
WHERE rolename IN ('HR_MGR_JUNIOR', 'SALES_CLERK');
2 3
no rows selected

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 15
Practice 10-3: Capture Privileges Used In Contexts (Optional)
Overview
In this practice, you capture privileges used by the user TOM or by the specific role
SALES_CLERK during a short period, generate the capture results, compare between used and
unused privileges to decide which privileges might need to be revoked.

Tasks
1. Define a capture of privileges used by the user TOM or by the specific role SALES_CLERK.
Use the following procedure.
exec SYS.DBMS_PRIVILEGE_CAPTURE.CREATE_CAPTURE ( -
name => 'Special_capt', -
description => 'Special', -
type => dbms_privilege_capture.g_role_and_context, -
roles => role_name_list('SALES_CLERK'), -
condition =>
'SYS_CONTEXT(''USERENV'',''SESSION_USER'')=''TOM''')

SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.CREATE_CAPTURE ( -


name => 'Special_capt', -
description => 'Special', -
type => dbms_privilege_capture.g_role_and_context, -
roles => role_name_list('SALES_CLERK'), -
condition =>
'SYS_CONTEXT(''USERENV'',''SESSION_USER'')=''TOM''')
> > > > >
PL/SQL procedure successfully completed.

SQL>
2. Start capturing privileges while users perform their daily work using the privileges.
a. Start the capture.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.ENABLE_CAPTURE ( -
name => 'Special_capt')

PL/SQL procedure successfully completed.

SQL>
b. Run the priv_used_by_users.sql script. The script connects as JIM who deletes
rows from HR.EMPLOYEES table and TOM who selects rows from SH.SALES table.
SQL> @priv_used_by_users.sql
Connected.

0 rows deleted.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 16
Commit complete.

Connected.

PROD_ID CUST_ID TIME_ID CHANNEL_ID PROMO_ID QUANTITY_SOLD


AMOUNT_SOLD
------- ------- --------- ---------- -------- ------------- ----
------------
120 6452 29-SEP-00 2 999 1
6.4
120 6452 29-SEP-00 4 999 1
6.4

SQL>
3. Stop the capture.
SQL> connect / as sysdba
Connected.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.DISABLE_CAPTURE ( -
name => 'Special_capt')

PL/SQL procedure successfully completed.

SQL>
4. Generate the capture results. It may take a few minutes.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.GENERATE_RESULT ( -
name => 'Special_capt')

PL/SQL procedure successfully completed.

SQL>
5. Display the object privileges used.
SQL> SELECT username, object_owner, object_name, obj_priv,
used_role
FROM dba_used_objprivs
WHERE username ='TOM' OR used_role='SALES_CLERK';
2 3
USERNAME OBJECT_OWNER OBJECT_NAME OBJ_PRIV USED_ROLE
-------- ------------ -------------- ---------- --------------
TOM SH SALES SELECT SALES_CLERK

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 17
6. Display the system privileges used.
SQL> SELECT username, sys_priv FROM dba_used_sysprivs;

no rows selected

SQL>
7. TOM is granted the select privilege on the SH.SALES table through SALES_CLERK role. He
used the privilege.
The unused privileges are visible in DBA_UNUSED_PRIVS view.
There are no unused privileges. So there is no privilege that has been unnecessarily
granted.
SQL> SELECT username, sys_priv, obj_priv, object_name, path
FROM dba_unused_privs
WHERE username='TOM' OR rolename='SALES_CLERK';
2 3
no rows selected

SQL>
8. Delete the capture so as to remove all previous captured information from the views.
SQL> exec SYS.DBMS_PRIVILEGE_CAPTURE.DROP_CAPTURE ( -
name=> 'Special_capt')

PL/SQL procedure successfully completed.

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 10: Privilege Analysis


Chapter 10 - Page 18
Practices for Lesson 11:
Using Application Contexts
Chapter 11

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 1
Practice 11-1: Creating an Application Context
In this practice, you create an application context, set the context using a secure package, and
test the context.

Task
1. Match the following terms with their descriptions:
1. Namespace A. An application context that is accessible only
by the current session
2. Attribute B. An application context whose values can be
shared among sessions
3. USERENV C. The identifier of an application context
4. Local D. The built-in application context that contains
information about the current session
5. Global E. An application context that uses values from
OID
6. Externalized context F. Similar to a field. Its value can be modified only
by the appropriate package.
7. Accessed globally G. An application context that gets values from a
source outside of the instance
8. SYS_SESSION_ROLES H. The built-in application context that contains
information about the enabled roles in the
current session

1-C, 2-F, 3-D, 4-A, 5-E, 6-G, 7-B, 8-H


2. Connect as PFAY with the oracle_4U password and the orcl netservice. Using the
SYS_CONTEXT procedure, display the following session-related attributes:
CURRENT_USER
SESSION_USER
PROXY_USER
IP_ADDRESS
NETWORK_PROTOCOL
AUTHENTICATION_TYPE
AUTHENTICATION_DATA
CLIENT_IDENTIFIER
EXTERNAL_NAME

3. You can use either of the following techniques to call SYS_CONTEXT:


SELECT sys_context('userenv','…')FROM dual;
EXEC dbms_output.put_line(syscontext('userenv','…'))
$ sqlplus pfay@orcl

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 2
Enter password: ******
Last Successful login time: Tue Jun 18 2013 00:22:32 +00:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> SET SERVEROUTPUT ON


SQL>
SQL> SELECT sys_context('USERENV', 'CURRENT_USER') FROM DUAL;

SYS_CONTEXT('USERENV','CURRENT_USER')
--------------------------------------------------------------
PFAY

SQL> SELECT sys_context('USERENV', 'SESSION_USER') FROM DUAL;

SYS_CONTEXT('USERENV','SESSION_USER')
--------------------------------------------------------------
PFAY

SQL> SELECT sys_context('USERENV', 'PROXY_USER') FROM DUAL;

SYS_CONTEXT('USERENV','PROXY_USER')
--------------------------------------------------------------

SQL> SELECT sys_context('USERENV', 'IP_ADDRESS') FROM DUAL;

SYS_CONTEXT('USERENV','IP_ADDRESS')
--------------------------------------------------------------
127.0.0.1(loopback)

SQL> SELECT sys_context('USERENV', 'NETWORK_PROTOCOL') FROM


DUAL;

SYS_CONTEXT('USERENV','NETWORK_PROTOCOL')
--------------------------------------------------------------
tcp

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 3
SQL> SELECT sys_context('USERENV', 'AUTHENTICATION_TYPE') FROM
DUAL;

SYS_CONTEXT('USERENV','AUTHENTICATION_TYPE')
--------------------------------------------------------------
DATABASE

SQL> SELECT sys_context('USERENV', 'AUTHENTICATION_DATA') FROM


DUAL;

SYS_CONTEXT('USERENV','AUTHENTICATION_DATA')
--------------------------------------------------------------

SQL> SELECT sys_context('USERENV', 'CLIENT_IDENTIFIER') FROM


DUAL;

SYS_CONTEXT('USERENV','CLIENT_IDENTIFIER')
--------------------------------------------------------------

SQL> SELECT sys_context('USERENV', 'EXTERNAL_NAME') FROM DUAL;

SYS_CONTEXT('USERENV','EXTERNAL_NAME')
--------------------------------------------------------------

SQL>
If the user PFAY was a user known in an LDAP directory, the external name would display
the DN known in the directory, like ‘uid=pfay, ou=People, dc=example, dc=com’.
The session user would display PFAY being the global user name in the database.
SQL> EXEC dbms_output.put_line(sys_context( -
'USERENV', 'CURRENT_USER'));
PFAY

PL/SQL procedure successfully completed.

SQL> EXEC dbms_output.put_line(sys_context( -


'USERENV', 'SESSION_USER'));
PFAY

PL/SQL procedure successfully completed.

SQL> EXEC dbms_output.put_line(sys_context( -


Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 4
'USERENV', 'PROXY_USER'));

PL/SQL procedure successfully completed.

SQL> EXEC dbms_output.put_line(sys_context( -


'USERENV', 'IP_ADDRESS'));
127.0.0.1(loopback)

PL/SQL procedure successfully completed.

SQL> EXEC dbms_output.put_line(sys_context( -


'USERENV', 'NETWORK_PROTOCOL'));
tcp

PL/SQL procedure successfully completed.

SQL> EXEC dbms_output.put_line(sys_context( -


'USERENV', 'AUTHENTICATION_TYPE'));
DATABASE

PL/SQL procedure successfully completed.

SQL> EXEC dbms_output.put_line(sys_context( -


'USERENV', 'AUTHENTICATION_DATA'));

PL/SQL procedure successfully completed.

SQL>
If the user PFAY was a user known in an LDAP directory, the external name would display
the DN known in the directory, like ‘uid=pfay, ou=People, dc=example, dc=com’.
4. The security officer grants new roles to PFAY. Use the built-in SYS_SESSION_ROLES
context to indicate whether the roles are enabled after PFAY’s connection.
Note: The SEC user was created in Practice 4-1, step 1.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> CREATE ROLE role_test;

Role created.

SQL> CREATE ROLE role_test2;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 5
Role created.

SQL> GRANT role_test, role_test2 TO pfay;

Grant succeeded.

SQL> CONNECT pfay


Enter password: ******
Connected.
SQL> SELECT role FROM session_roles;

ROLE
--------
HR_EMP_CLERK
ROLE_TEST
ROLE_TEST2

SQL> SELECT SYS_CONTEXT('SYS_SESSION_ROLES', 'ROLE_TEST')


FROM DUAL;
2
SYS_CONTEXT('SYS_SESSION_ROLES','ROLE_TEST')
--------------------------------------------
TRUE

SQL> SELECT SYS_CONTEXT('SYS_SESSION_ROLES', 'DBA')


FROM DUAL;
2
SYS_CONTEXT('SYS_SESSION_ROLES','DBA')
--------------------------------------
FALSE

SQL> CONNECT sec


Enter password: ******
Connected.
SQL> DROP ROLE role_test;

Role dropped.

SQL> DROP ROLE role_test2;

Role dropped.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 6
5. Implement a local application context with the following properties:
Name: EMP_USER
Owned by: SEC
This contains the following attributes, which are listed with the column from the
HR.EMPLOYEES table that is used to obtain the attribute value:
Attribute Value: Column from HR.EMPLOYEES
ID EMPLOYEE_ID
NAME FIRST_NAME || ' ' || LAST_NAME
EMAIL EMAIL
SQL> CREATE CONTEXT emp_user USING current_emp;

Context created.

SQL>
6. The row in the EMPLOYEES table that is used to populate the attributes is selected by
comparing the EMAIL column to the SESSION_USER attribute from SYS_CONTEXT.
The procedure that sets the application context has the following properties:
Owned by: SEC user
Part of: CURRENT_EMP package
Name: SET_EMP_INFO
This is called from a logon trigger named EMP_LOGON that is also owned by SEC. This
trigger applies to all users.
You re-create a modified version of this package and context in a later practice, so save all
your work.
a. If you are not familiar with creating packages in PL/SQL, use the following code to
create the package and package body:
CREATE OR REPLACE PACKAGE current_emp IS
PROCEDURE set_emp_info;
END;
/
CREATE OR REPLACE PACKAGE BODY current_emp IS
PROCEDURE set_emp_info
IS
v_employee_id hr.employees.employee_id%TYPE;
v_first_name hr.employees.first_name%TYPE;
v_last_name hr.employees.last_name%TYPE;
BEGIN
SELECT employee_id,
first_name,
last_name
INTO v_employee_id,
v_first_name,
v_last_name
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 7
FROM hr.employees
WHERE email = SYS_CONTEXT('USERENV', 'SESSION_USER');
DBMS_SESSION.SET_CONTEXT('emp_user', 'id',
v_employee_id);
DBMS_SESSION.SET_CONTEXT('emp_user', 'name',
v_first_name || ' ' || v_last_name);
DBMS_SESSION.SET_CONTEXT('emp_user', 'email',
SYS_CONTEXT('USERENV', 'SESSION_USER'));
EXCEPTION
WHEN no_data_found THEN NULL;
END;
END;
/
SQL> CREATE OR REPLACE PACKAGE current_emp IS
PROCEDURE set_emp_info;
END;
/
2 3 4
Package created.

SQL>
SQL> CREATE OR REPLACE PACKAGE BODY current_emp IS
PROCEDURE set_emp_info
IS
v_employee_id hr.employees.employee_id%TYPE;
v_first_name hr.employees.first_name%TYPE;
v_last_name hr.employees.last_name%TYPE;
BEGIN
SELECT employee_id,
first_name,
last_name
INTO v_employee_id,
v_first_name,
v_last_name
FROM hr.employees
WHERE email = SYS_CONTEXT('USERENV', 'SESSION_USER');
DBMS_SESSION.SET_CONTEXT('emp_user', 'id',
v_employee_id);
DBMS_SESSION.SET_CONTEXT('emp_user', 'name',
v_first_name || ' ' || v_last_name);
DBMS_SESSION.SET_CONTEXT('emp_user', 'email',
SYS_CONTEXT('USERENV', 'SESSION_USER'));

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 8
EXCEPTION
WHEN no_data_found THEN NULL;
END;
END;
/
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16 17 18 19 20 21 22 23 24 25 26
Package body created.

SQL>
b. Create the logon trigger.
SQL> CREATE or REPLACE TRIGGER emp_logon
AFTER LOGON ON DATABASE
BEGIN
current_emp.set_emp_info;
END;
/
2 3 4 5 6
Trigger created.

SQL>
7. Test the context that you created by performing the following steps:
a. Grant the CREATE SESSION privilege to the user named SKING.
b. Log in as SKING.
c. Use SYS_CONTEXT to verify that the EMP_USER context attributes are set. If you use
DBMS_OUTPUT, remember to issue the SET SERVEROUTPUT ON command.
SQL> GRANT create session TO sking;

Grant succeeded.

SQL>
SQL> CONNECT sking
Enter Password: ******
Connected.
SQL>
SQL> SET SERVEROUTPUT ON
SQL> EXEC dbms_output.put_line(sys_context('emp_user', 'id'))
100

PL/SQL procedure successfully completed.

SQL> EXEC dbms_output.put_line(sys_context('emp_user', 'name'))


Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 9
Steven King

PL/SQL procedure successfully completed.

SQL> EXEC dbms_output.put_line(sys_context('emp_user', 'email'))


SKING

PL/SQL procedure successfully completed.

SQL>
8. Still connected as SKING, list all the application context attributes set in the current session.
If Oracle Label Security is installed, the LBAC$LABELS and LBAC$LASTSEQ attributes are
part of the context. It is populated because Oracle Label Security has been automatically
configured when you executed the /home/oracle/labs/DV/DV_setup.sh script in
practice 3-7 to configure and enable Database Vault. You disabled Database Vault by
executing the /home/oracle/labs/DV/DV_disable.sh script but Oracle Label
Security remains enabled.
SQL> DECLARE
list dbms_session.AppCtxTabTyp;
cnt number;
BEGIN
dbms_session.list_context (list, cnt);
IF cnt = 0
THEN dbms_output.put_line('No contexts active.');
ELSE
FOR i IN 1..cnt LOOP
dbms_output.put_line(list(i).namespace
||' ' || list(i).attribute
|| ' = ' || list(i).value);
END LOOP;
END IF;
END;
/
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16
EMP_USER NAME = Steven King
EMP_USER EMAIL = SKING
EMP_USER ID = 100
LBAC$LABELS LBAC$LASTSEQ = -1

PL/SQL procedure successfully completed.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 10
9. Log in as SEC and select information about the application context that you created from
the data dictionary.
SQL> CONNECT sec
Enter Password: ******
Connected.
SQL> COL namespace FORMAT a10
SQL> COL schema FORMAT a8
SQL> COL package FORMAT a12
SQL> COL type FORMAT a20
SQL> SELECT * FROM dba_context WHERE namespace = 'EMP_USER';

NAMESPACE SCHEMA PACKAGE TYPE


---------- -------- ------------ --------------------
EMP_USER SEC CURRENT_EMP ACCESSED LOCALLY

SQL>
10. What happens when you call DBMS_SESSION.SET_CONTEXT to set an attribute in the
EMP_USER context? Assume that SKING wants to change the context setting.
Because the application context is set with a package, SKING does not have sufficient
privileges to execute the DBMS_SESSION.SET_CONTEXT procedure.
SQL> CONNECT sking
Enter password:
Connected.
SQL> SET SERVEROUTPUT ON
SQL>
SQL> DECLARE
list dbms_session.AppCtxTabTyp;
cnt number;
BEGIN
dbms_session.list_context (list, cnt);
IF cnt = 0
THEN dbms_output.put_line('No contexts active.');
ELSE
FOR i IN 1..cnt LOOP
dbms_output.put_line(list(i).namespace
||' ' || list(i).attribute
|| ' = ' || list(i).value);
END LOOP;
END IF;
END;
/

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 11
EMP_USER NAME = Steven King
EMP_USER EMAIL = SKING
EMP_USER ID = 100
LBAC$LABELS LBAC$LASTSEQ = -1

PL/SQL procedure successfully completed.

SQL> EXEC DBMS_SESSION.SET_CONTEXT('emp_user', 'id', 1);


BEGIN DBMS_SESSION.SET_CONTEXT('emp_user', 'id', 1); END;

*
ERROR at line 1:
ORA-01031: insufficient privileges
ORA-06512: at "SYS.DBMS_SESSION", line 101
ORA-06512: at line 1

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 11: Using Application Contexts


Chapter 11 - Page 12
Practices for Lesson 12:
Implementing Virtual Private
Database
Chapter 12

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 1
Practice 12-1: Implementing a Virtual Private Database Policy
Overview
In this practice, you create, enable, and test a fine-grained access control (FGAC) policy.

Task
1. How does FGAC determine which rows belong in the VPD for the current user?
Fine-grained access control adds a predicate (condition) to the WHERE clause on a SELECT
or DML statement with an AND operator.
2. How does FGAC know which tables are defined in the VPD?
You include a table name or view name when the fine-grained access control policy is
created.
3. In this practice, you implement a security policy that allows users to see only their own rows
in the HR.EMPLOYEES table. The practice uses the SEC and SKING users, and the
application context created in the lesson titled “Using Application Contexts.” If you did not
complete that practice, execute the following scripts after connecting to the database AS
SYSDBA:
~/labs/USERS/create_sec.sql creates the SEC user.
~/labs/VPD/create_context.sql creates the EMP_USER application context.
~/labs/VPD/create_pack_trig.sql creates the packages and trigger.
~/labs/VPD/create_SKING.sql creates the SKING user and tests the application
context.
Your output may vary depending on which objects already exist in the database; however,
you should not receive any errors on the CREATE statements.
4. The SEC user also needs the privilege to create policies. Grant SEC the ability to execute
the package that creates policies.
$ sqlplus / AS SYSDBA

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL>
SQL> GRANT execute ON dbms_rls TO sec;

Grant succeeded.

SQL>
5. What privilege exempts the user from access policies? Why does the SEC user need this
privilege? Grant it to SEC.
The EXEMPT ACCESS POLICY privilege is very powerful. Statements that are issued by a
user with this privilege do not have any FGAC policies applied. This privilege can also be
granted by SYSTEM.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 2
SQL> GRANT exempt access policy TO sec;

Grant succeeded.

SQL>
6. Create the package that is used by the security policy to return a predicate.
a. Create the package specification.
SQL> CONNECT sec
Enter Password: ******
Connected.
SQL>
SQL> CREATE OR REPLACE PACKAGE hr_policy_pkg IS
FUNCTION limit_emp_emp (
object_schema IN VARCHAR2,
object_name VARCHAR2 )
RETURN VARCHAR2;
END;
/
2 3 4 5 6 7
Package created.

SQL>
b. Create the package body.
SQL> CREATE OR REPLACE PACKAGE BODY hr_policy_pkg IS
FUNCTION limit_emp_emp (
object_schema IN VARCHAR2,
object_name VARCHAR2 )
RETURN VARCHAR2
IS
v_emp_id NUMBER;
BEGIN
RETURN 'employee_id = SYS_CONTEXT(''emp_user'', ''id'')';
END;
END;
/
2 3 4 5 6 7 8 9 10 11 12
Package body created.

SQL>
c. What predicate does the policy use to limit the rows returned from the EMPLOYEE
table?
employee_id = SYS_CONTEXT('emp_user', 'id')

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 3
d. How does this predicate limit the rows?
The user making the query must have an EMAIL_ID that matches the database
username, and the emp_user attribute in sys_context is set equal to the
employee_id of the user (see Practice 11-1, step 5). The predicate allows the user to
access only the record describing the user.
7. Test the policy function.
SQL> SELECT hr_policy_pkg.limit_emp_emp('a', 'b') FROM DUAL;

HR_POLICY_PKG.LIMIT_EMP_EMP('A','B')
----------------------------------------------------------
employee_id = SYS_CONTEXT('emp_user', 'id')

SQL>
8. Implement a policy with the following characteristics:
The policy limits the rows that are selected from the HR.EMPLOYEES table.
The policy is named HR_EMP_POL.
The function that is used to return a predicate is SEC.HR_POLICY_PKG.LIMIT_EMP_EMP.
SQL> EXEC dbms_rls.drop_policy('HR', 'EMPLOYEES','HR_EMP_POL')
BEGIN dbms_rls.drop_policy('HR', 'EMPLOYEES', 'HR_EMP_POL')
END;

*
ERROR at line 1:
ORA-28102: policy does not exist
ORA-06512: at "SYS.DBMS_RLS", line 126
ORA-06512: at line 1

SQL> EXEC dbms_rls.add_policy('HR','EMPLOYEES', -


'HR_EMP_POL','SEC', -
'HR_POLICY_PKG.LIMIT_EMP_EMP','SELECT')

PL/SQL procedure successfully completed.

SQL>
9. Set up the SKING user so that he can access the HR.EMPLOYEES table. Because SEC has
GRANT ANY OBJECT PRIVILEGE, the SEC user can grant this privilege. Grant the same
privilege to PFAY.
SQL> GRANT select ON hr.employees TO sking;

Grant succeeded.

SQL> GRANT select ON hr.employees TO pfay;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 4
Grant succeeded.

SQL>
10. As SKING, display the current context attributes.
SQL> connect sking
Enter Password: ******
Connected.
SQL> SET SERVEROUTPUT ON
SQL> DECLARE
list dbms_session.AppCtxTabTyp;
cnt number;
BEGIN
dbms_session.list_context (list, cnt);
IF cnt = 0
THEN dbms_output.put_line('No contexts active.');
ELSE
FOR i IN 1..cnt LOOP
dbms_output.put_line(list(i).namespace
||' ' || list(i).attribute
|| ' = ' || list(i).value);
END LOOP;
END IF;
END;
/

EMP_USER NAME = Steven King


EMP_USER EMAIL = SKING
EMP_USER ID = 100
LBAC$LABELS LBAC$LASTSEQ = -1

PL/SQL procedure successfully completed.

SQL>
11. Which rows are returned when SKING queries the HR.EMPLOYEES table without a WHERE
clause? Try it.
SQL> select employee_id, first_name, last_name, email
from HR.EMPLOYEES;
2
EMPLOYEE_ID FIRST_NAME LAST_NAME EMAIL
----------- --------------- ----------------- -----------------
100 Steven King SKING

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 5
12. Which rows are returned when PFAY queries the HR.EMPLOYEES table without a WHERE
clause? Try it.
SQL> CONNECT pfay
Enter Password: ******
Connected.
SQL> select employee_id, first_name, last_name, email
from HR.EMPLOYEES;
2
EMPLOYEE_ID FIRST_NAME LAST_NAME EMAIL
----------- --------------- ----------------- -----------------
202 Pat Fay PFAY

SQL>
13. Sometimes, it is necessary to view the predicate that is added by the policy.
a. Connect as SEC to view the predicate added by the policy and use the views
V$VPD_POLICY and V$SQL.
SQL> CONNECT sec
Enter Password: ******
Connected.
SQL> SELECT distinct policy, predicate, sql_text
FROM v$vpd_policy p, v$sql s
WHERE s.child_address = p.address;
2 3
POLICY PREDICATE
--------- ----------------------------------------------------
SQL_TEXT
----------------------------------------------------------------
----------------
HR_EMP_POL
SELECT EMPLOYEE_ID, FIRST_NAME, LAST_NAME FROM HR.EMPLOYEES
WHERE EMAIL = SYS_CONTEXT('USERENV', 'SESSION_USER')

HR_EMP_POL employee_id = SYS_CONTEXT('emp_user', 'id')


select employee_id, first_name, last_name, email from
HR.EMPLOYEES

SQL>
b. You can also use SQL tracing. The user must have the ALTER SESSION privilege to
turn on this type of tracing. SYS has the ability to grant this privilege, but this ability has
not been granted to SEC. To enable a trace that will capture the predicate, execute the
following command:
ALTER SESSION SET EVENTS '10730 TRACE NAME CONTEXT FOREVER,
LEVEL 1';

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 6
Grant SKING the ALTER SESSION privilege, and then capture the predicate in a trace
file.
SQL> connect / as sysdba
Connected.
SQL> GRANT ALTER SESSION TO SKING;

Grant succeeded.

SQL> connect SKING


Enter password: ******
Connected.
SQL> ALTER SESSION SET EVENTS '10730 TRACE NAME CONTEXT FOREVER,
LEVEL 1';

Session altered.

SQL> SELECT employee_id, first_name, last_name, email


FROM hr.employees;

EMPLOYEE_ID FIRST_NAME LAST_NAME EMAIL


----------- -------------- --------------- -------------------
100 Steven King SKING

SQL> EXIT
$
14. View the trace file. The trace file will be created in the Automatic Diagnostics Directory by
default. Look for the file in the $ORACLE_BASE/diag/rdbms/orcl/orcl/trace
directory.
Hint: The ls -ltr command lists the trace files in reverse order by time, so the most
recent files will be at the end of the listing. Also, the trace file will have a .trc extension.
$ cd $ORACLE_BASE/diag/rdbms/orcl/orcl/trace
$ ls -ltr *ora*.trc

lines deleted

-rw-r----- 1 oracle oinstall 915 Apr 25 03:03
orcl_ora_11899.trc
-rw-r----- 1 oracle oinstall 1033 Apr 25 05:43
orcl_ora_2762.trc
-rw-r----- 1 oracle oinstall 1348 Apr 25 06:06
orcl_ora_5814.trc
$
$ cat orcl_ora_5814.trc

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 7
Trace file
/u01/app/oracle/diag/rdbms/orcl/orcl/trace/orcl_ora_5814.trc
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
ORACLE_HOME = /u01/app/oracle/product/12.1.0/dbhome_1
System name: Linux
Node name: EDRSR32P1
Release: 2.6.39-200.24.1.el6uek.x86_64
Version: #1 SMP Sat Jun 23 02:39:07 EDT 2012
Machine: x86_64
Instance name: orcl
Redo thread mounted by this instance: 1
Oracle process number: 41
Unix process pid: 5814, image: oracle@EDRSR32P1 (TNS V1-V3)

*** 2013-04-25 06:06:31.769


*** SESSION ID:(275.3461) 2013-04-25 06:06:31.769
*** CLIENT ID:() 2013-04-25 06:06:31.769
*** SERVICE NAME:(SYS$USERS) 2013-04-25 06:06:31.769
*** MODULE NAME:(SQL*Plus) 2013-04-25 06:06:31.769
*** ACTION NAME:() 2013-04-25 06:06:31.769

-------------------------------------------------------------
Logon user : SKING
Table/View : HR.EMPLOYEES
VPD Policy name: HR_EMP_POL
Policy function: SEC.HR_POLICY_PKG.LIMIT_EMP_EMP
RLS view :
SELECT
"EMPLOYEE_ID","FIRST_NAME","LAST_NAME","EMAIL","PHONE_NUMBER","H
IRE_DATE","JOB_ID","SALARY","COMMISSION_PCT","MANAGER_ID","DEPAR
TMENT_ID" FROM "HR"."EMPLOYEES" "EMPLOYEES" WHERE (employee_id
= SYS_CONTEXT('emp_user', 'id'))
-------------------------------------------------------------
$
15. Using Enterprise Manager Cloud Control, delete the HR_EMP_POL fine-grained access
control policy.
Step Page Action
a. In the browser, enter the following URL:
https://localhost:7802/em

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 8
Login Enter:
User Name: sysman
Password: Oracle123
Enterprise Summary Click the Targets tab, then the Databases option.
b. Databases Click the orcl link.
c. orcl Click the Administration tab, then the Security
option, then the Virtual Private Database option.
Database Login Click Login. Use CREDORCL credentials to login.
e. Virtual Private Database Policies Select the HR_EMP_POL policy.
Click Delete.
f. Confirmation Click Yes.
g. Virtual Private Database Policies You receive the following message:
Update Message: POLICY HR_EMP_POL has
been deleted successfully
16. Change the security policy to allow everyone to view the HR.EMPLOYEES table, but not the
SALARY and COMMISSION_PCT columns. The HR.EMPLOYEES table can then be used as a
phone directory.
Create the new policy defining the two following parameters: SEC_RELEVANT_COLS and
SEC_RELEVANT_COL_OPTS.
$ sqlplus sec

Enter password: ******


Last Successful login time: Tue Jun 18 2013 00:49:49 +00:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL>
SQL> BEGIN
dbms_rls.add_policy(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'HR_EMP_POL',
function_schema => 'SEC',
policy_function => 'HR_POLICY_PKG.LIMIT_EMP_EMP',
statement_types =>'SELECT',
sec_relevant_cols => 'SALARY,COMMISSION_PCT',
sec_relevant_cols_opt => dbms_rls.ALL_ROWS);
END;
/
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 9
2 3 4 5 6 7 8 9 10 11
PL/SQL procedure successfully completed.

SQL>
17. Test this new policy with the SKING user. Note that in the first SELECT statement, all the
rows and columns that are requested are shown. In the second SELECT statement, SKING
sees his own salary but no other salary is displayed. Set tracing so that you can view the
changed SQL statement later.
SQL> connect sking
Enter password: *****
Connected.
SQL> COL first_name FORMAT A12
SQL> COL LAST_NAME FORMAT A12
SQL> ALTER SESSION SET EVENTS '10730 TRACE NAME CONTEXT FOREVER,
LEVEL 1';

Session altered.

SQL> select first_name, last_name, email from hr.employees;

FIRST_NAME LAST_NAME EMAIL


------------ ------------ -------------------------
Ellen Abel EABEL
Sundar Ande SANDE
David Austin DAUSTIN
Hermann Baer HBAER
Amit Banda ABANDA
… rows deleted …
Clara Vishney CVISHNEY
Shanta Vollman SVOLLMAN
Alana Walsh AWALSH
Matthew Weiss MWEISS
Jennifer Whalen JWHALEN
Eleni Zlotkey EZLOTKEY

83 rows selected.

SQL> select first_name, last_name, SALARY, COMMISSION_PCT


from hr.employees;

FIRST_NAME LAST_NAME SALARY COMMISSION_PCT


------------ ------------ ---------- --------------
Steven King 24000
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 10
Neena Kochhar
Lex De Haan
Alexander Hunold
… rows deleted …
Hermann Baer
Shelley Higgins
William Gietz

83 rows selected.

SQL> EXIT
$
18. View the trace file and note the change to the SQL statements. A CASE clause is added to
the SELECT clause for each relevant column.
$ cd $ORACLE_BASE/diag/rdbms/orcl/orcl/trace
$ ls -ltr *ora*.trc

lines deleted

rw-r----- 1 oracle oinstall 1272 Apr 25 07:44
orcl_ora_19917.trc
-rw-r----- 1 oracle oinstall 1262 Apr 25 07:45
orcl_ora_20091.trc
-rw-r----- 1 oracle oinstall 914 Apr 25 07:46
orcl_ora_20160.trc
-rw-r----- 1 oracle oinstall 2132 Apr 25 07:51
orcl_ora_20858.trc
$
$ cat orcl_ora_20858.trc
...

-------------------------------------------------------------
Logon user : SKING
Table/View : HR.EMPLOYEES
VPD Policy name : HR_EMP_POL
Policy function: SEC.HR_POLICY_PKG.LIMIT_EMP_EMP
RLS view :
SELECT
"EMPLOYEE_ID","FIRST_NAME","LAST_NAME","EMAIL","PHONE_NUMBER","H
IRE_DATE","JOB_ID", CASE WHEN (employee_id =
SYS_CONTEXT('emp_user', 'id')) THEN "SALARY" ELSE NULL END
"SALARY", CASE WHEN (employee_id = SYS_CONTEXT('emp_user',
'id')) THEN "COMMISSION_PCT" ELSE NULL END

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 11
"COMMISSION_PCT","MANAGER_ID","DEPARTMENT_ID" FROM
"HR"."EMPLOYEES" "EMPLOYEES"
-------------------------------------------------------------

*** 2013-04-25 08:02:13.317


-------------------------------------------------------------
Logon user : SKING
Table/View : HR.EMPLOYEES
VPD Policy name : HR_EMP_POL
Policy function: SEC.HR_POLICY_PKG.LIMIT_EMP_EMP
RLS view :
SELECT
"EMPLOYEE_ID","FIRST_NAME","LAST_NAME","EMAIL","PHONE_NUMBER","H
IRE_DATE","JOB_ID", CASE WHEN (employee_id =
SYS_CONTEXT('emp_user', 'id')) THEN "SALARY" ELSE NULL END
"SALARY", CASE WHEN (employee_id = SYS_CONTEXT('emp_user',
'id')) THEN "COMMISSION_PCT" ELSE NULL END
"COMMISSION_PCT","MANAGER_ID","DEPARTMENT_ID" FROM
"HR"."EMPLOYEES" "EMPLOYEES"
-------------------------------------------------------------
$
19. Clean up after this practice by dropping the policy.
$ sqlplus sec
Enter password: ******
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> EXEC dbms_rls.drop_policy('HR', 'EMPLOYEES','HR_EMP_POL')

PL/SQL procedure successfully completed.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 12
Practice 12-2: Implementing a Dynamic VPD Policy
Overview
In this practice, you will find out how setting the wrong type for your VPD policy leads to wrong
results.

Tasks
1. Create a static policy. The policy calls a function displaying rows in a table depending on
the time.
SQL> exec DBMS_RLS.DROP_POLICY ('HR', 'EMPLOYEES','POL_TIME');
BEGIN DBMS_RLS.DROP_POLICY ('HR', 'EMPLOYEES','POL_TIME'); END;

*
ERROR at line 1:
ORA-28102: policy does not exist
ORA-06512: at "SYS.DBMS_RLS", line 126
ORA-06512: at line 1

SQL> exec DBMS_RLS.ADD_POLICY ( -


object_schema => 'HR', -
object_name => 'EMPLOYEES', -
policy_name => 'POL_TIME', -
function_schema => 'SEC', -
policy_function => 'PREDICATE', -
statement_types => 'SELECT', -
policy_type => DBMS_RLS.STATIC)
> > > > > > >
PL/SQL procedure successfully completed.

SQL>
2. Create the function used by the security policy to return a predicate. If the user executes
the query on the HR.EMPLOYEES table after a certain authorized time, the query returns
only the rows where the EMAIL matches the session username, else it returns all rows
whose SALARY is less than 3100. Adapt the time to an appropriate time in the function
according to the current time so that the test becomes relevant.
SQL> !date
Thu Apr 25 10:29:28 UTC 2013
SQL> create or replace function PREDICATE
(obj_schema varchar2, obj_name varchar2)
return varchar2 is d_predicate varchar2(2000);
begin

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 13
if to_char(sysdate, 'HH24') >= '10'
and to_char(sysdate, 'MI')<'35'
then
d_predicate := 'email = sys_context (''USERENV'' ,
''SESSION_USER'')';
else d_predicate := 'salary <= 3100';
end if;
return d_predicate;
end predicate;
/
2 3 4 5 6 7 8 9 10 11 12 13
Function created.

SQL>
3. Connect as SKING to test the VPD policy.
SQL> connect sking
Enter password: ******
Connected.
SQL> SELECT email, last_name, salary FROM hr.employees;

EMAIL LAST_NAME SALARY


------------------------- ------------------------- ----------
SKING King 24000

SQL> !date
Thu Apr 25 10:30:47 UTC 2013

SQL>
4. Test under another user.
SQL> connect pfay
Enter password: ******
Connected.
SQL> !date
Thu Apr 25 10:36:43 UTC 2013

SQL> SELECT email, last_name, salary FROM hr.employees;

EMAIL LAST_NAME SALARY


------------------------- ------------------------- ----------
PFAY Fay 6000

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 14
The condition in the function is no more true: nevertheless, it is not reparsed nor
reexecuted.
5. You have to change the type of the policy to DYNAMIC.
SQL> conn sec
Enter password: ********
Connected.
SQL> exec DBMS_RLS.DROP_POLICY ('HR', 'EMPLOYEES','POL_TIME');

PL/SQL procedure successfully completed.

SQL> exec DBMS_RLS.ADD_POLICY ( -


object_schema => 'HR', -
object_name => 'EMPLOYEES', -
policy_name => 'POL_TIME', -
function_schema => 'SEC', -
policy_function => 'PREDICATE', -
statement_types => 'SELECT', -
policy_type => DBMS_RLS.DYNAMIC)
> > > > > > >
PL/SQL procedure successfully completed.

SQL>
6. Recreate the function with an appropriate time.
SQL> !date
Thu Apr 25 10:40:54 UTC 2013
SQL> create or replace function PREDICATE
(obj_schema varchar2, obj_name varchar2)
return varchar2 is d_predicate varchar2(2000);
begin
if to_char(sysdate, 'HH24') >= '10'
and to_char(sysdate, 'MI')<'45'
then
d_predicate := 'email = sys_context (''USERENV'' ,
''SESSION_USER'')';
else d_predicate := 'salary <= 3100';
end if;
return d_predicate;
end predicate;
/

2 3 4 5 6 7 8 9 10 11 12 13
Function created.

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 15
7. Connect as SKING and then as PFAY to test the VPD policy.
SQL> connect sking
Enter password: ******
Connected.
SQL> SELECT email, last_name, salary FROM hr.employees;

EMAIL LAST_NAME SALARY


------------------------- ------------------------- ----------
SKING King 24000

SQL> connect pfay


Enter password: ******
Connected.
SQL> /

EMAIL LAST_NAME SALARY


------------------------- ------------------------- ----------
PFAY Fay 6000

SQL>
8. Wait 5 minutes and retest to verify that the function is reexecuted.
SQL> !date
Thu Apr 25 10:45:48 UTC 2013
SQL> SELECT email, last_name, salary FROM hr.employees;

EMAIL LAST_NAME SALARY


------------------------- ----------------- -- ----------
AKHOO Khoo 3100
CDAVIES Davies 3100
JFLEAUR Fleaur 3100
ACABRIO Cabrio 3000
AWALSH Walsh 3100
KFEENEY Feeney 3000

6 rows selected.

SQL>
SQL> connect sking
Enter password: ******
Connected.
SQL> SELECT email, last_name, salary FROM hr.employees;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 16
EMAIL LAST_NAME SALARY
------------------------- ----------------- -- ----------
AKHOO Khoo 3100
CDAVIES Davies 3100
JFLEAUR Fleaur 3100
ACABRIO Cabrio 3000
AWALSH Walsh 3100
KFEENEY Feeney 3000

6 rows selected.

SQL>
9. Clean up the POL_TIME policy.
SQL> connect sec
Enter password: ******
Connected.
SQL> exec DBMS_RLS.DROP_POLICY ('HR', 'EMPLOYEES','POL_TIME')

PL/SQL procedure successfully completed.

SQL>
10. Drop the EMP_USER context, the CURRENT_EMP package and the logon trigger.
SQL> DROP CONTEXT EMP_USER;

Context dropped.

SQL> DROP PACKAGE sec.CURRENT_EMP;

Package dropped.

SQL> DROP TRIGGER sec.EMP_LOGON;

Trigger dropped.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 17
Practice 12-3: Troubleshooting VPD Policies
Overview
In this practice, you will diagnose and troubleshoot VPD policies at creation or execution time.

Tasks
1. Create a VPD policy using the FUN function as follows:
a. Create the function.
SQL> create or replace function fun
(object_schema varchar2, object_name varchar2)
return varchar2
is
d_predicate varchar2(2000);
BEGIN
d_predicate := '(mail = sys_context (''USERENV'',
''SESSION_USER'')';
RETURN d_predicate;
END fun;
/
2 3 4 5 6 7 8 9 10
Function created.

SQL>
b. Create the VPD policy.
SQL> EXEC dbms_rls.drop_policy('HR', 'EMPLOYEES','FUN_POLICY')
BEGIN dbms_rls.drop_policy('HR', 'EMPLOYEES', 'FUN_POLICY')
END;

*
ERROR at line 1:
ORA-28102: policy does not exist
ORA-06512: at "SYS.DBMS_RLS", line 126
ORA-06512: at line 1

SQL> BEGIN
dbms_rls.add_policy
(object_schema => 'HR', object_name => 'EMPLOYEES',
policy_name => 'fun_policy',
function_schema => 'SEC',
policy_function => 'FUN',
statement_types => 'select, index',
policy_type => dbms_rls.CONTEXT_SENSITIVE);

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 18
END;
/
2 3 4 5 6 7 8 9 10 11
PL/SQL procedure successfully completed.

SQL>
2. Connect as SKING to test the policy.
SQL> conn sking
Enter password: ******
Connected.
SQL> SELECT email FROM hr.employees;
SELECT email FROM hr.employees
*
ERROR at line 1:
ORA-28113: policy predicate has error

SQL>
You did not get an error at the policy creation but at run time.
3. Trace the statement and analyze the trace file.
a. Trace your session and reexecute the statement.
SQL> ALTER SESSION SET EVENTS '10730 TRACE NAME CONTEXT FOREVER,
LEVEL 1';

Session altered.
SQL> SELECT email FROM hr.employees;
SELECT email FROM hr.employees
*
ERROR at line 1:
ORA-28113: policy predicate has error

SQL> EXIT
$
b. Analyze the trace file.
$ ls -ltr *ora*.trc

lines deleted

-rw-r----- 1 oracle oinstall 6083 Apr 25 11:46
orcl_mmon_6671.trc
-rw-r----- 1 oracle oinstall 119 Apr 25 11:49
orcl_ora_21114.trm

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 19
-rw-r----- 1 oracle oinstall 3251 Apr 25 11:49
orcl_ora_21114.trc
$ cat orcl_ora_21114.trc
...
-------------------------------------------------------------
Error information for ORA-28113:
Logon user : SKING
Table/View : HR.EMPLOYEES
VPD Policy name : FUN_POLICY
Policy function: SEC.FUN
RLS view :
SELECT
"EMPLOYEE_ID","FIRST_NAME","LAST_NAME","EMAIL","PHONE_NUMBER","H
IRE_DATE","JOB_ID","SALARY","COMMISSION_PCT","MANAGER_ID","DEPAR
TMENT_ID" FROM "HR"."EMPLOYEES" "EMPLOYEES" WHERE ((mail =
sys_context ('USERENV', 'SESSION_USER'))
ORA-00907: missing right parenthesis
-------------------------------------------------------------
$
4. Rewrite the function adding the missing right parenthesis in the d_predicate :=
'(mail = sys_context (''USERENV'', ''SESSION_USER''))'; .
$ sqlplus sec
Enter password: ********
Connected.
SQL> create or replace function fun
(object_schema varchar2, object_name varchar2)
return varchar2
IS
d_predicate varchar2(2000);
BEGIN
d_predicate := '(mail = sys_context (''USERENV'',
''SESSION_USER''))';
RETURN d_predicate;
END fun;
/
2 3 4 5 6 7 8 9 10
Function created.

SQL>
5. Connect as SKING to retest the policy.
SQL> conn sking
Enter password: ********
Connected.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 20
SQL> SELECT mail FROM hr.employees;
SELECT mail FROM hr.employees
*
ERROR at line 1:
ORA-28113: policy predicate has error

SQL>
6. There is still an error. Proceed as in the previous steps.
a. Trace your session and reexecute the statement.
SQL> ALTER SESSION SET EVENTS '10730 TRACE NAME CONTEXT FOREVER,
LEVEL 1';

Session altered.
SQL> SELECT mail FROM hr.employees;
SELECT mail FROM hr.employees
*
ERROR at line 1:
ORA-28113: policy predicate has error

SQL> EXIT
$
b. Analyze the trace file.
$ cd $ORACLE_BASE/diag/rdbms/orcl/orcl/trace
$ ls -ltr *ora*.trc

lines deleted

-rw-r----- 1 oracle oinstall 6345 Apr 25 11:56
orcl_mmon_6671.trc
-rw-r----- 1 oracle oinstall 100 Apr 25 11:59
orcl_ora_22796.trm
-rw-r----- 1 oracle oinstall 3258 Apr 25 11:59
orcl_ora_22796.trc
$ cat orcl_ora_22796.trc
...
*** 2013-04-25 11:59:04.588
-------------------------------------------------------------
-------------------------------------------------------------
Error information for ORA-28113:
Logon user : SKING
Table/View : HR.EMPLOYEES
VPD Policy name : FUN_POLICY

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 21
Policy function: SEC.FUN
RLS view :
SELECT
"EMPLOYEE_ID","FIRST_NAME","LAST_NAME","EMAIL","PHONE_NUMBER","H
IRE_DATE","JOB_ID","SALARY","COMMISSION_PCT","MANAGER_ID","DEPAR
TMENT_ID" FROM "HR"."EMPLOYEES" "EMPLOYEES" WHERE ((mail =
sys_context ('USERENV', 'SESSION_USER')))
ORA-00904: "MAIL": invalid identifier
-------------------------------------------------------------
$
7. Rewrite the function with the right column name: EMAIL.
$ sqlplus sec
Enter password: ********
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> create or replace function fun


(object_schema varchar2, object_name varchar2)
return varchar2
IS
d_predicate varchar2(2000);
BEGIN
d_predicate := '(email = sys_context (''USERENV'',
''SESSION_USER''))';
RETURN d_predicate;
END fun;
/
2 3 4 5 6 7 8 9 10
Function created.

SQL>
8. Connect as SKING to retest the policy.
SQL> conn sking
Enter password: ********
Connected.
SQL> SELECT email FROM hr.employees;

EMAIL
-------------------------
SKING

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 22
Practice 12-4: Cleaning Up VPD Policies
Overview
In this practice, you will drop all VPD policies.

Tasks
1. Find all VPD policies.
SQL> conn sec
Enter password: ******
Connected.
SQL> SELECT policy_name FROM dba_policies;

POLICY_NAME
---------------------------------------------------------
… rows deleted …
FUN_POLICY
… rows deleted …

SQL>
2. Drop each VPD policy listed in step 1.
SQL> exec DBMS_RLS.DROP_POLICY ('HR','EMPLOYEES','FUN_POLICY')

PL/SQL procedure successfully completed.

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 23
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 12: Implementing Virtual Private Database


Chapter 12 - Page 24
Practices for Lesson 13:
Implementing Oracle Label
Security Policies
Chapter 13

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 1
Practice 13-1: Registering and Enabling Oracle Label Security
Overview
In this practice, you register and enable Oracle Label Security (OLS) in the pdb1_1 pluggable
database of cdb1 by using manual procedures. Then you will register and enable OLS in orcl
using DBCA.

Tasks
1. Connect to the pdb1_1 pluggable database and check whether OLS is registered. If it is
registered, check if it is enabled.
a. Connect to the pdb1_1 pluggable database as SYSDBA.
$ . oraenv
ORACLE_SID = [orcl] ? cdb1
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
b. Check whether OLS is registered.
$ sqlplus sys@pdb1_1 as sysdba

Enter password: ******


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options

SQL> SELECT status FROM DBA_OLS_STATUS


WHERE name = 'OLS_CONFIGURE_STATUS';
2
STATU
-----
FALSE

SQL>
c. Register OLS.
SQL> EXEC LBACSYS.CONFIGURE_OLS

PL/SQL procedure successfully completed.

SQL> SELECT status FROM DBA_OLS_STATUS


WHERE name = 'OLS_CONFIGURE_STATUS';
2
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 2
STATU
-----
TRUE

SQL>
d. Check whether OLS is enabled.
SQL> SELECT value FROM V$OPTION
WHERE parameter = 'Oracle Label Security';
2
VALUE
-----
FALSE

SQL>
e. Enable OLS.
SQL> EXEC LBACSYS.OLS_ENFORCEMENT.ENABLE_OLS

PL/SQL procedure successfully completed.

SQL> SELECT value FROM V$OPTION


WHERE parameter = 'Oracle Label Security';
2
VALUE
---------------------------------------------------------------
TRUE

SQL> EXIT
$
Notice that you can register and enable OLS at the PDB level.
2. Connect to the pdb1_2 pluggable database and check whether OLS is registered.
a. Connect to the pdb1_2 pluggable database as SYSDBA.
$ sqlplus sys@pdb1_2 as sysdba

Enter password: ******


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options
SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 3
b. Check whether OLS is registered.
SQL> SELECT status FROM DBA_OLS_STATUS
WHERE name = 'OLS_CONFIGURE_STATUS';
2
STATU
-----
FALSE

SQL>
c. Check whether OLS is enabled.
SQL> SELECT value FROM V$OPTION
WHERE parameter = 'Oracle Label Security';
2
VALUE
-----
FALSE

SQL>
3. What happens if you register and enable OLS at the root level? Does it cascade to all
PDBs?
a. Connect to root as SYSDBA.
SQL> conn / as sysdba
Connected.
SQL> SELECT status FROM DBA_OLS_STATUS
WHERE name = 'OLS_CONFIGURE_STATUS';
2
STATU
-----
FALSE

SQL> SELECT value FROM V$OPTION


WHERE parameter = 'Oracle Label Security';
2
VALUE
---------------------------------------------------------------
FALSE

SQL>
b. Register OLS.
SQL> EXEC LBACSYS.CONFIGURE_OLS

PL/SQL procedure successfully completed.


Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 4
SQL> SELECT status FROM DBA_OLS_STATUS
WHERE name = 'OLS_CONFIGURE_STATUS';
2
STATU
-----
TRUE

SQL>
c. Enable OLS.
SQL> EXEC LBACSYS.OLS_ENFORCEMENT.ENABLE_OLS

PL/SQL procedure successfully completed.

SQL> SELECT value FROM V$OPTION


WHERE parameter = 'Oracle Label Security';
2
VALUE
---------------------------------------------------------------
TRUE

SQL>
d. Check whether the operations cascaded to all PDBs.
SQL> CONNECT sys@pdb1_2 as sysdba
Enter password: ******
Connected.
SQL> SELECT status FROM DBA_OLS_STATUS
WHERE name = 'OLS_CONFIGURE_STATUS';
2
STATU
-----
FALSE

SQL> SELECT value FROM V$OPTION


WHERE parameter = 'Oracle Label Security';
2
VALUE
---------------------------------------------------------------
FALSE

SQL> EXIT
$
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 5
It did not cascade to all PDBs. Registration and enabling execute at the container level.
4. Connect to the orcl database and check whether OLS is registered. If it is registered,
check whether it is enabled.
$ . oraenv
ORACLE_SID = [cdb1] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$
a. Check whether OLS is registered.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> SELECT status FROM DBA_OLS_STATUS
WHERE name = 'OLS_CONFIGURE_STATUS';
2
STATU
-----
TRUE

SQL> EXIT
$
Notice that the banner displays “Oracle Label Security.” The option has already been
enabled because in a previous practice, Database Vault was enabled to protect HR objects.
The configuration of Database Vault automatically enables OLS. OLS is a required option
for Oracle Database Vault.
b. If OLS is not enabled because you did not execute practice 3-7, use DBCA to register
and enable OLS only.
1) Start dbca and perform the following steps.
$ dbca

Step Window/Page Description Choices or Values


a. Step 1: Database Operation Select “Configure Database Options.”
Click Next.
b. Step 2: Database List Select “orcl”.
Click Next.
c. Step 3: Database Options Click Next.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 6
Step Window/Page Description Choices or Values
d. Step 4: Database Vault Credentials Deselect “Configure Database Vault” if selected.
Select “Configure Label Security” if not selected.
Click Next.
e. Step 5: Connection Mode Click Next.
f. Step 6: Summary Click Finish.
g. Step 7: Progress Page On the Database Configuration Assistant page,
click OK.
Click Close.
The following screenshot shows step 6.

The following screenshot shows step 7.

c. Check whether OLS is registered and enabled.


$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 7
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> SELECT value FROM V$OPTION


WHERE parameter = 'Oracle Label Security';
2
VALUE
-----
TRUE

SQL> SELECT status FROM DBA_OLS_STATUS


WHERE name = 'OLS_CONFIGURE_STATUS';
2
STATU
-----
TRUE

SQL> EXIT
$
Notice that the banner now displays “Oracle Label Security.”

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 8
Practice 13-2: Implementing Oracle Label Security
Overview
In this practice, you implement a simple label security system in a pluggable database.

Scenario
This practice uses the HR.LOCATIONS and HR.JOB_HISTORY sample schema tables in the
pdb1_1 pluggable database. Oracle Label Security assigns sensitivity labels to data rows in
the LOCATIONS and JOB_HISTORY tables. The data has been analyzed and can be placed in
three sensitivity levels. There are four groups: one for each region and a GLOBAL group. The
three locations in the Asia region are assigned the SENSITIVE::ASIA sensitivity label. One
location in the United States region is assigned the HIGHLY_SENSITIVE::UNITED_STATES
sensitivity label. All remaining locations are assigned the PUBLIC sensitivity label. From this
analysis, the components and labels are displayed in the following table:

Levels for the FACILITY policy


Short Name Long Name Numeric
P PUBLIC 1000
S SENSITIVE 2000
HS HIGHLY_SENSITIVE 3000

Groups for the FACILITY policy


Short Name Long Name Numeric
US United States 101
EU Europe 102
ASIA Asia 103
GLOBAL Global 1000

Active data labels for FACILITY


Label Tag Number
P 1000
S::US 2101
S::ASIA 2103
HS::US 3101
HS::ASIA 3103

Levels for the PRIVACY policy


Short Name Long Name Numeric

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 9
C CONFIDENTIAL 1000
S SENSITIVE 2000

Active data labels for PRIVACY


Label Tag Number
C 101000
S 102000

Data rows in the JOB_HISTORY table with END_DATE greater than seven years are assigned
the SENSITIVE sensitivity label. Data rows with END_DATE less than or equal to five years are
assigned the CONFIDENTIAL sensitivity label.
The HR application owner is authorized to read and write all data rows in both the
JOB_HISTORY and LOCATIONS tables.
The MYCO_MGR application user is authorized to view all data in the LOCATIONS table labeled
SENSITIVE and below, and having the US, ASIA, or EUROPE groups. The MYCO_PLANNING
application user is authorized to view all data in the LOCATIONS table labeled HIGHLY
SENSITIVE and below, and having the GLOBAL group. Note that the ASIA, EUROPE, and US
groups are created as subordinate to the GLOBAL group. MYCO_EMP is allowed access only to
the data labeled PUBLIC.
Two Oracle Label Security policies are created:
• FACILITY: The designated security column is FACLAB.
• PRIVACY: The designated security column is PRIVLAB.
The security columns for both columns are marked HIDDEN at policy-creation time.
For this practice, you must log in as the oracle user. All scripts are found in the
$HOME/labs/OLS directory. In this practice, it is assumed that the sessions are connected
using the database environment variable.
1. Create three users: MYCO_EMP, MYCO_MGR, and MYCO_PLANNING. You also grant them
access to the JOB_HISTORY and LOCATIONS tables in the HR schema. Open a terminal
window. Set the database environment variables. Change the directory to
/home/oracle/labs/OLS. In the SQL*Plus session, execute the
create_OLS_users.sql script.
$ cd /home/oracle/labs/OLS
$ sqlplus system@pdb1_1

Enter password: ******


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL>
SQL> @create_OLS_users.sql
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 10
SQL> ALTER USER hr IDENTIFIED BY oracle_4U ACCOUNT UNLOCK;

User altered.

SQL>
SQL> -- Cleanup from previous runs
SQL>
SQL> DROP USER myco_EMP;

User dropped.

SQL> DROP USER myco_MGR;

User dropped.

SQL> DROP USER myco_PLANNING;

User dropped.

SQL>
SQL> --
****************************************************************
*******
SQL> -- Create Users MYCO_EMP
SQL> -- Create Users MYCO_MGR
SQL> -- Create Users MYCO_PLANNING
SQL> --
****************************************************************
*******
SQL>
SQL> GRANT CREATE SESSION to MYCO_EMP IDENTIFIED BY oracle_4U;

Grant succeeded.

SQL> GRANT CREATE SESSION to MYCO_MGR IDENTIFIED BY oracle_4U;

Grant succeeded.

SQL> GRANT CREATE SESSION to MYCO_PLANNING IDENTIFIED BY


oracle_4U;

Grant succeeded.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 11
SQL>
SQL>
SQL> --
****************************************************************
*******
SQL> -- Connect as User HR and grant select on job_history to
SQL> -- MYCO_MGR, MYCO_EMP and MYCO_PLANNING
SQL> --
SQL> -- Grant select on locations to MYCO_EMP and MYCO_MGR.
SQL> -- Grant select, insert, update, delete on locations to
MYCO_PLANNING
SQL> --
SQL> -- Note - A database role could be used here in place of
direct grants
SQL> --
****************************************************************
*******
SQL>
SQL> CONNECT HR/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL>
SQL> GRANT SELECT ON JOB_HISTORY TO MYCO_EMP;

Grant succeeded.

SQL> GRANT SELECT ON JOB_HISTORY TO MYCO_MGR;

Grant succeeded.

SQL> GRANT SELECT ON JOB_HISTORY TO MYCO_PLANNING;

Grant succeeded.

SQL>
SQL> GRANT SELECT ON LOCATIONS TO MYCO_EMP;

Grant succeeded.

SQL> GRANT SELECT ON LOCATIONS TO MYCO_MGR;

Grant succeeded.

SQL> GRANT SELECT, INSERT, UPDATE, DELETE ON LOCATIONS TO


MYCO_PLANNING;
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 12
Grant succeeded.

SQL>
2. At this point, a policy must be created to hold the label information. Only a user with proper
privileges can create policies. The only user with those privileges is LBACSYS. The
LBACSYS account is locked by the DBCA by default. You can unlock the LBACSYS account
for these practices. If the LBACSYS account is locked, it can be unlocked with the following
command:
ALTER USER lbacsys IDENTIFIED BY oracle_4U ACCOUNT UNLOCK;
SQL> connect system@pdb1_1
Enter password: ******
Connected.
SQL> ALTER USER lbacsys IDENTIFIED BY oracle_4U ACCOUNT UNLOCK;
ALTER USER lbacsys IDENTIFIED BY oracle_4U ACCOUNT UNLOCK
*
ERROR at line 1:
ORA-65066: The specified changes must apply to all containers

SQL>
The LBACSYS account is a common user. Any change must be applied to all containers.
Connect to the root to be able to perform the operation.
SQL> connect system@cdb1
Enter password: ******
Connected.
SQL> ALTER USER lbacsys IDENTIFIED BY oracle_4U ACCOUNT UNLOCK
CONTAINER=ALL;
2
User altered.

SQL>
3. The first step in setting up OLS is to create policies. Create the FACILITY policy in
pdb1_1. Then you create the data labels. In this case, you create three sensitivity levels
and four groups (see the specification in the scenario). Use SQL*Plus and execute the
create_labels.sql script.
SQL> connect lbacsys@pdb1_1
Enter password: ******
Connected.
SQL> @$HOME/labs/OLS/create_labels.sql
SQL> set echo on
SQL> -- ****************************************************
SQL> -- Connected as User LBACSYS in the PDB
SQL> -- ****************************************************
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 13
SQL> -- Dropping FACILITY and PRIVACY policies
SQL> -- in case they exist
SQL> -- ****************************************************
SQL> EXECUTE LBACSYS.SA_SYSDBA.DROP_POLICY('FACILITY',TRUE);
BEGIN LBACSYS.SA_SYSDBA.DROP_POLICY('FACILITY',TRUE); END;

*
ERROR at line 1:
ORA-12416: policy FACILITY not found
ORA-06512: at "LBACSYS.SA_SYSDBA", line 148
ORA-06512: at line 1

SQL> EXECUTE SA_SYSDBA.DROP_POLICY('PRIVACY',TRUE);


BEGIN SA_SYSDBA.DROP_POLICY('PRIVACY',TRUE); END;

*
ERROR at line 1:
ORA-12416: policy PRIVACY not found
ORA-06512: at "LBACSYS.SA_SYSDBA", line 148
ORA-06512: at line 1

SQL> --
SQL> -- ****************************************************
SQL> -- Creating FACILITY Policy
SQL> -- ****************************************************
SQL> BEGIN
2 SA_SYSDBA.CREATE_POLICY('FACILITY','FACLAB',
3 'READ_CONTROL,CHECK_CONTROL,LABEL_DEFAULT,HIDE');
4 END;
5 /

PL/SQL procedure successfully completed.

SQL> --
SQL> -- ****************************************************
SQL> -- Adding sensitivity levels to FACILITY policy:
SQL> -- ****************************************************
SQL> BEGIN
2 SA_COMPONENTS.CREATE_LEVEL('FACILITY',
3 1000,'P','PUBLIC');

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 14
4 SA_COMPONENTS.CREATE_LEVEL('FACILITY',
5 2000,'S','SENSITIVE');
6 SA_COMPONENTS.CREATE_LEVEL('FACILITY',
7 3000,'HS','HIGHLY_SENSITIVE');
8 END;
9 /

PL/SQL procedure successfully completed.

SQL> --
SQL> -- ****************************************************
SQL> -- Adding groups to FACILITY policy:
SQL> -- ****************************************************
SQL> BEGIN
2 SA_COMPONENTS.CREATE_GROUP('FACILITY',
3 1000,'Global','Global');
4 SA_COMPONENTS.CREATE_GROUP('FACILITY',
5 101,'US','United States','GLOBAL');
6 SA_COMPONENTS.CREATE_GROUP('FACILITY',
7 102,'EU','Europe','GLOBAL');
8 SA_COMPONENTS.CREATE_GROUP('FACILITY',
9 103,'Asia','Asia','GLOBAL');
10 END;
11 /

PL/SQL procedure successfully completed.

SQL> --
SQL> -- ****************************************************
SQL> -- Creating Labels for FACILITY policy
SQL> -- ****************************************************
SQL> EXECUTE SA_LABEL_ADMIN.CREATE_LABEL('FACILITY',-
> 1000,'P');

PL/SQL procedure successfully completed.

SQL> EXECUTE SA_LABEL_ADMIN.CREATE_LABEL('FACILITY',-


> 2101,'S::US');

PL/SQL procedure successfully completed.

SQL> EXECUTE SA_LABEL_ADMIN.CREATE_LABEL('FACILITY',-

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 15
> 3101,'HS::US');

PL/SQL procedure successfully completed.

SQL> EXECUTE SA_LABEL_ADMIN.CREATE_LABEL('FACILITY',-


> 2103,'S::ASIA');

PL/SQL procedure successfully completed.

SQL> EXECUTE SA_LABEL_ADMIN.CREATE_LABEL('FACILITY',-


> 3103,'HS::ASIA');

PL/SQL procedure successfully completed.

SQL>
4. Set up the LBACSYS user to use the Enterprise Manager Cloud Control (EM CC) for the
target.
a. If the cdb1 target is not yet configured as a managed target in EM CC, proceed first
with the steps described in Practice 3-2, step 9. To unlock the DBSNMP user, connect to
the root as SYSDBA and use the following statement:
alter user dbsnmp identified by oracle_4U account unlock
container=all;
b. Then log in as LBACSYS as follows:
Page Description Choices or Value
Step 1: Enterprise Summary Click “Targets” and then click “Databases.”
Step 2: Databases Select “cdb1” and click the “cdb1” link. If the cdb1
link does not appear, refresh.
Step 3: Pluggable Databases Click the “cdb1_PDB1_1” link.
(bottom left)
Step 4: cdb1 / PDB1_1 Click “Administration”, click “Security”, and then
click “Oracle Label Security.”

Step 5: Database Login Database: PDB1_1 is displayed.


Username: LBACSYS
Password: oracle_4U
Select: Save As “lbacsys_cred”
Click Login.
You get an error indicating that the application requires more database privileges than you
have currently been granted.
c. Grant the SELECT ANY DICTIONARY system privilege to LBACSYS.
SQL> connect system@pdb1_1

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 16
Enter password: ******
Connected.
SQL> GRANT select any dictionary TO lbacsys;

Grant succeeded.

SQL>
d. Retry the operation that failed in the previous step.
Page Description Choices or Value
Step 5: Database Login Click OK to close the error message.
Database: PDB1_1 is displayed.
Username: LBACSYS
Password: oracle_4U
Select: Save As “lbacsys_cred”
Click Login.
It succeeded. The FACILITY policy is displayed as the single existing OLS policy in
pdb1_1.
5. Create the PRIVACY policy using EM CC. You create two sensitivity levels as described in
the specification presented in the scenario.
Step Page Action
a. Oracle Label Security Click Create.
b. Create Label Security Policy Enter the following details:
Name: PRIVACY
Label Column: PRIVLAB
Select “Hide Label Column.”
c. Create Label Security Policy In the Default Policy Enforcement Options section:
Select Apply Policy Enforcement.
Select “For all queries (READ_CONTROL).”
Select “For update and insert operations so that
modified or new rows are read accessible
(CHECK_CONTROL).”
Click OK.
d. Oracle Label Security Update message:
Label Security Policy PRIVACY has been created
successfully

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 17
a. The creation of the policy displays the following:

b. Click the FACILITY link to view the attributes of the policy.

6. Create the labels for the PRIVACY policy as shown in the preceding specification by using
EM CC. Click the locator link at the top of the page: “Oracle Label Security”
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 18
Step Page Action
a. Oracle Label Select PRIVACY.
Security Click Edit.
b. Edit Label Security Click the Label Components tab.
Policy: PRIVACY In the Levels section, click Add 5 Rows.
c. Edit Label Security Enter the following information.
Policy: PRIVACY Long Name : Short Name: Numeric Tag
CONFIDENTIAL : C : 1000
SENSITIVE : S : 2000
Remove the extra three rows. (Select the empty rows and
click Delete.)
Click Apply.
d. Edit Label Security Update message:
Policy: PRIVACY Label Security Policy PRIVACY has been
modified successfully
Click the locator link at the top of the page: Label Security
Policies.
e. Data Labels: Click Add.
PRIVACY
f. Create Data Label Enter the following details:
Numeric Tag: 101000
Level: C
Note: You can also click the Flashlight icon next to the Level
field and select the value from the page that is displayed.
Click OK.
g. Data Labels: Click Add.
Privacy
h. Create Data Label Enter the following details:
Numeric Tag: 102000
Level: S
Click OK.
i. Data Labels: Update message:
Privacy The object has been created successfully
Click the locator link at the top of the page: Label Security
Policies.
7. Using a terminal window, set the user authorizations for the FACILITY and PRIVACY
policies. Specify the user’s initial session label and an initial default row label when setting
up user authorizations. These authorizations are kept in the OLS data dictionary tables for
each user. Using SQL*Plus, execute users_auth.sql. This sets the user authorization
labels for the three users: MYCO_EMP, MYCO_PLANNING, and MYCO_MGR. Later, data
access rights will be limited by applying the labels to the data.
SQL> set echo on
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 19
SQL> @$HOME/labs/OLS/users_auth.sql
SQL> SET ECHO OFF
SQL>
SQL> -- **************************************************
SQL> -- Setting User Authorizations for users:
SQL> -- MYCO_EMP
SQL> -- MYCO_MGR
SQL> -- MYCO_PLANNING
SQL> -- **************************************************
SQL> CONNECT lbacsys/oracle_4U@localhost:1521/pdb1_1
Enter password: ******
Connected.
SQL> -- **************************************************
SQL> -- Setting MYCO_EMP user label authorizations
SQL> -- Setting MYCO_MGR user label authorizations
SQL> -- Setting MYCO_PLANNING user label authorizations
SQL> -- **************************************************
SQL> BEGIN
2 SA_USER_ADMIN.SET_USER_LABELS ('PRIVACY',
3 'MYCO_MGR','C');
4 SA_USER_ADMIN.SET_USER_LABELS ('FACILITY',
'MYCO_EMP','P');
5 SA_USER_ADMIN.SET_USER_LABELS ('FACILITY',
'MYCO_MGR','S::US,EU,ASIA');
6 SA_USER_ADMIN.SET_USER_LABELS ('FACILITY',
7 'MYCO_PLANNING','HS::GLOBAL');
8 END;
9 /

PL/SQL procedure successfully completed.

SQL>
8. Set the user authorizations for the HR user by using Enterprise Manager Cloud Control. The
HR user needs full read and write access (FULL) to the data and must be able to change
the session labels and session privileges to those of another user (PROFILE_ACCESS) for
both the FACILITY and PRIVACY policies.
Step Page Action
a. Data Labels: PRIVACY Click the Oracle Label Security link.
b. Oracle Label Security Select the FACILITY policy.
Select Authorization from the Actions menu.
Click Go.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 20
c. Authorization: FACILITY Click Add Users.
d. Add Users: Users Click Add.
e. Search and Select: User Select the HR user and click Select.
f. Add Users: Users Click Next.
g. Add Users: Privileges Select “Assume profile of another user through
set_access_profile (PROFILE_ACCESS).”
Select “Bypass all Label Security checks (FULL).”
Click Next.
h. Add Users: Levels, Click Next.
Compartments And
Groups
i. Add Users: Audit Click Next.
j. Add Users: Review Click Finish.
k. Authorization: FACILITY Update message:
User HR added successfully
The authorization setting displays the following for the FACILITY policy:

9. Repeat the procedure to set user authorizations for the HR user for the PRIVACY policy.
Click Label Security Policies to return to the Label Security Policies page. Give the HR
user the PROFILE_ACCESS and FULL privileges on the PRIVACY policy.
The authorization setting displays the following at step g:

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 21
When complete, the authorization setting displays the following for the PRIVACY policy:

10. Apply the FACILITY policy to the LOCATIONS table. You can apply Oracle Label Security
policies to entire application schemes or individual application tables. In a SQL*Plus
session, execute the apply_FAC_locations.sql script.
SQL> @$HOME/labs/OLS/apply_FAC_locations
SQL> set echo on
SQL> --
SQL> -- *************************************************

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 22
SQL> -- Applying FACILITY policy to hr.locations table.
SQL> -- *************************************************
SQL>
SQL> CONNECT lbacsys/oracle_4U@localhost:1521/pdb1_1
Enter password: *****
Connected.
SQL>
SQL> Begin
2 sa_policy_admin.apply_table_policy (
3 POLICY_NAME => 'FACILITY',
4 SCHEMA_NAME => 'HR',
5 TABLE_NAME => 'LOCATIONS',
6 TABLE_OPTIONS => NULL,
7 LABEL_FUNCTION => NULL);
10 END;
11 /

PL/SQL procedure successfully completed.

SQL>
11. Apply the PRIVACY policy to the JOB_HISTORY table. Use Enterprise Manager Cloud
Control to apply the policy.
Step Page Action
a. Authorization: PRIVACY Click the Label Security Policies link.
b. Oracle Label Security Select the PRIVACY policy.
Select Apply from the Actions menu.
Click Go.
c. Apply: PRIVACY Click Create.
d. Add Table Enter HR.JOB_HISTORY in the Table field.
Click OK.
e. Apply: PRIVACY An update message is displayed.
Click the Label Security Policies link to return to the
Label Security Policies page.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 23
The application of the PRIVACY policy on HR.JOB_HISTORY displays the following:

12. View the protection options of the policies that you created.
a. On the Label Security Policies page, click the FACILITY policy.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 24
b. Note how the policy is enforced for the LOCATIONS table. Expand the Tables folder at
the bottom of the page.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 25
c. Click the Label Security Policies link. On the Label Security Policies page, click the
PRIVACY policy.

d. Log out of Enterprise Manager and close the browser.


13. Before you can test the policy, you must add labels to the data. In SQL*Plus, execute the
add_labels.sql script, which adds the labels to the rows of data in the protected tables.
This update is done by the SYS user who has the EXEMPT ACCESS POLICY system
privilege and HR user who has FULL access rights in PRIVACY policy.
Note: The number of rows updated in the JOB_HISTORY table varies depending on the
current date; any row with an END_DATE more than 10 years is given a SENSITIVE label.
SQL> @$HOME/labs/OLS/add_labels.sql
SQL> set echo on
SQL>
SQL> SPOOL ols_add_labels_to_data.log
SQL>
SQL> -- **************************************************
SQL> -- Populating Data - Enter password for HR schema
SQL> -- **************************************************
SQL>
SQL> connect sys/oracle_4U@localhost:1521/pdb1_1 as sysdba
Connected.
SQL>
SQL> -- ****************************************************
SQL> -- SETTING LABELS FOR FACILITY POLICY
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 26
SQL> -- ****************************************************
SQL>
SQL> -- ****************************************************
SQL> -- Update Labels for Sites In ASIA
SQL> -- ****************************************************
SQL>
SQL> update hr.locations
2 set faclab = char_to_label('FACILITY','S::ASIA')
3 where upper(city) in
4 ('BEIJING','TOKYO','SINGAPORE');

3 rows updated.

SQL>
SQL> -- ****************************************************
SQL> -- Update Labels for Sites In US
SQL> -- ****************************************************
SQL>
SQL> update hr.locations
2 set faclab = char_to_label('FACILITY','HS::US')
3 where upper(city) in ('SOUTH SAN FRANCISCO');

1 row updated.

SQL>
SQL> -- ****************************************************
SQL> -- Update Labels for all remaining locations
SQL> -- ****************************************************
SQL>
SQL> update hr.locations
2 set faclab = char_to_label('FACILITY','P')
3 where faclab is NULL;

19 rows updated.

SQL>
SQL> -- ****************************************************
SQL> -- SETTING LABELS FOR PRIVACY POLICY
SQL> -- ****************************************************
SQL> connect hr/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 27
SQL> update hr.job_history
2 set privlab = char_to_label('PRIVACY','S')
3 where ((to_char(sysdate,'YYYY')
4 - to_char(end_date,'YYYY')) > 10);

2 rows updated.

SQL>
SQL> update hr.job_history
2 set privlab = char_to_label('PRIVACY','C')
3 where ((to_char(sysdate,'YYYY')
4 - to_char(end_date,'YYYY')) <= 10);

8 rows updated.

SQL>
SQL> COMMIT;

Commit complete.

SQL>
SQL> Spool off;
SQL>
14. Test the FACILITY policy implementation. After establishing policies to tables and users,
and adding labels to the data, you can now test them. To test the access for each user,
execute the test_loc.sql script.
SQL> @$HOME/labs/OLS/test_loc.sql
SQL> set echo on
SQL>
SQL> spool ols_test_facility.log
SQL>
SQL> set linesize 57
SQL> set pagesize 100
SQL> col "FACILITY LABEL" format a8 heading "FACILITY|LABEL"
SQL> col street_address format a20 word_wrap
SQL> col city format a10 word_wrap
SQL> col state_province format a12 truncate
SQL> col postal_code format a8 truncate
SQL> col location_id format 9999 heading "LOC"
SQL>
SQL> set echo on
SQL> -- ****************************************************

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 28
SQL> -- * Connect to the Oracle pluggable database PDB1_1 as
SQL> -- * Application User myco_emp
SQL> -- *
SQL> -- * select locations.*, label_to_char(faclab)
SQL> -- * "FACILITY LABEL" from hr.locations;
SQL> -- *
SQL> -- ****************************************************
SQL>
SQL>
SQL> Pause Hit Return To Continue
Hit Return To Continue

SQL>
SQL>
SQL> connect myco_emp/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL>
SQL> select locations.*, label_to_char(faclab)
2 "FACILITY LABEL" from hr.locations;

LOC STREET_ADDRESS POSTAL_C CITY


----- -------------------- -------- ----------
FACILITY
STATE_PROVIN CO LABEL
------------ -- --------
1000 1297 Via Cola di Rie 00989 Roma
IT P

1100 93091 Calle della 10934 Venice


Testa
IT P

1300 9450 Kamiya-cho 6823 Hiroshima


JP P

1400 2014 Jabberwocky Rd 26192 Southlake


Texas US P

1600 2007 Zagora St 50090 South


Brunswick
New Jersey US P

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 29
1700 2004 Charade Rd 98199 Seattle
Washington US P

1800 147 Spadina Ave M5V 2L7 Toronto


Ontario CA P

1900 6092 Boxwood St YSW 9T2 Whitehorse


Yukon CA P

2100 1298 Vileparle (E) 490231 Bombay


Maharashtra IN P

2200 12-98 Victoria 2901 Sydney


Street
New South Wa AU P

2400 8204 Arthur St London


UK P

2500 Magdalen Centre, The OX9 9ZB Oxford


Oxford Science Park
Oxford UK P

2600 9702 Chester Road 09629850 Stretford


Manchester UK P

2700 Schwanthalerstr. 80925 Munich


7031
Bavaria DE P

2800 Rua Frei Caneca 1360 01307-00 Sao Paulo

Sao Paulo BR P

2900 20 Rue des 1730 Geneva


Corps-Saints
Geneve CH P

3000 Murtenstrasse 921 3095 Bern


BE CH P

3100 Pieter 3029SK Utrecht

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 30
Breughelstraat 837
Utrecht NL P

3200 Mariano Escobedo 11932 Mexico


9991 City
Distrito Fed MX P

19 rows selected.

SQL>
SQL> Pause Hit Return To Continue
Hit Return To Continue

SQL>
SQL> -- ****************************************************
SQL> -- * Connect to the Oracle pluggable database PDB1_1 as
SQL> -- * Application User myco_mgr
SQL> -- *
SQL> -- * select locations.*, label_to_char(faclab)
SQL> -- * "FACILITY LABEL" from hr.locations;
SQL> -- *
SQL> -- ****************************************************
SQL>
SQL>
SQL> Pause Hit Return To Continue
Hit Return To Continue

SQL>
SQL> connect myco_mgr/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL>
SQL> select locations.*, label_to_char(faclab)
2 "FACILITY LABEL" from hr.locations;

LOC STREET_ADDRESS POSTAL_C CITY


----- -------------------- -------- ----------
FACILITY
STATE_PROVIN CO LABEL
------------ -- --------
1000 1297 Via Cola di Rie 00989 Roma
IT P

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 31
1100 93091 Calle della 10934 Venice
Testa
IT P

1200 2017 Shinjuku-ku 1689 Tokyo


Tokyo Prefec JP S::ASIA

1300 9450 Kamiya-cho 6823 Hiroshima


JP P

1400 2014 Jabberwocky Rd 26192 Southlake


Texas US P

1600 2007 Zagora St 50090 South


Brunswick
New Jersey US P

1700 2004 Charade Rd 98199 Seattle


Washington US P

1800 147 Spadina Ave M5V 2L7 Toronto


Ontario CA P

1900 6092 Boxwood St YSW 9T2 Whitehorse


Yukon CA P

2000 40-5-12 Laogianggen 190518 Beijing


CN S::ASIA

2100 1298 Vileparle (E) 490231 Bombay


Maharashtra IN P

2200 12-98 Victoria 2901 Sydney


Street
New South Wa AU P

2300 198 Clementi North 540198 Singapore


SG S::ASIA

2400 8204 Arthur St London


UK P

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 32
2500 Magdalen Centre, The OX9 9ZB Oxford
Oxford Science Park
Oxford UK P

2600 9702 Chester Road 09629850 Stretford


Manchester UK P

2700 Schwanthalerstr. 80925 Munich


7031
Bavaria DE P

2800 Rua Frei Caneca 1360 01307-00 Sao Paulo

Sao Paulo BR P

2900 20 Rue des 1730 Geneva


Corps-Saints
Geneve CH P

3000 Murtenstrasse 921 3095 Bern


BE CH P

3100 Pieter 3029SK Utrecht


Breughelstraat 837
Utrecht NL P

3200 Mariano Escobedo 11932 Mexico


9991 City
Distrito Fed MX P

22 rows selected.

SQL>
SQL> Pause Hit Return To Continue
Hit Return To Continue

SQL>
SQL> -- ****************************************************
SQL> -- * Connect to the Oracle pluggable database PDB1_1 as
SQL> -- * Application User myco_planning

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 33
SQL> -- *
SQL> -- * select locations.*, label_to_char(faclab)
SQL> -- * "FACILITY LABEL" from hr.locations;
SQL> -- *
SQL> -- ****************************************************
SQL>
SQL> Pause Hit Return To Continue
Hit Return To Continue

SQL>
SQL> connect myco_planning/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL>
SQL> select locations.*, label_to_char(faclab)
2 "FACILITY LABEL" from hr.locations;

LOC STREET_ADDRESS POSTAL_C CITY


----- -------------------- -------- ----------
FACILITY
STATE_PROVIN CO LABEL
------------ -- --------
1000 1297 Via Cola di Rie 00989 Roma
IT P

1100 93091 Calle della 10934 Venice


Testa
IT P

1200 2017 Shinjuku-ku 1689 Tokyo


Tokyo Prefec JP S::ASIA

1300 9450 Kamiya-cho 6823 Hiroshima


JP P

1400 2014 Jabberwocky Rd 26192 Southlake


Texas US P

1500 2011 Interiors Blvd 99236 South San


Francisco
California US HS::US

1600 2007 Zagora St 50090 South

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 34
Brunswick
New Jersey US P

1700 2004 Charade Rd 98199 Seattle


Washington US P

1800 147 Spadina Ave M5V 2L7 Toronto


Ontario CA P

1900 6092 Boxwood St YSW 9T2 Whitehorse


Yukon CA P

2000 40-5-12 Laogianggen 190518 Beijing


CN S::ASIA

2100 1298 Vileparle (E) 490231 Bombay


Maharashtra IN P

2200 12-98 Victoria 2901 Sydney


Street
New South Wa AU P

2300 198 Clementi North 540198 Singapore


SG S::ASIA

2400 8204 Arthur St London


UK P

2500 Magdalen Centre, The OX9 9ZB Oxford


Oxford Science Park
Oxford UK P

2600 9702 Chester Road 09629850 Stretford


Manchester UK P

2700 Schwanthalerstr. 80925 Munich


7031
Bavaria DE P

2800 Rua Frei Caneca 1360 01307-00 Sao Paulo

Sao Paulo BR P

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 35
2900 20 Rue des 1730 Geneva
Corps-Saints
Geneve CH P

3000 Murtenstrasse 921 3095 Bern


BE CH P

3100 Pieter 3029SK Utrecht


Breughelstraat 837
Utrecht NL P

3200 Mariano Escobedo 11932 Mexico


9991 City
Distrito Fed MX P

23 rows selected.

SQL>
SQL> spool off;
SQL>
15. Test the PRIVACY policy implementation. After establishing policies for tables and users,
and adding labels to the data, you can now test them. To test the access for each user,
execute the test_hist.sql script. The number of rows returned for MYCO_EMP and
MYCO_MGR vary based on SYSDATE; rows with END_DATE greater than 10 years will have a
SENSITIVE label.
SQL> @$HOME/labs/OLS/test_hist.sql
SQL> set echo on
SQL>
SQL> set linesize 57
SQL> set pagesize 32
SQL> col "PRIVACY LABEL" format a8 HEADING "PRIVACY|LABEL"
SQL> col org_name format a10
SQL> col org_id format 9999
SQL> col hours format 9999
SQL> col expenses format 99999
SQL>
SQL>
SQL> -- *****************************************************
SQL> -- * Connect to the Oracle pluggable database PDB1_1 as
SQL> -- * Application User myco_emp
SQL> -- *
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 36
SQL> -- * select job_history.*, label_to_char(PRIVLAB)
SQL> -- * "PRIVACY LABEL" from hr.job_history;
SQL> --
SQL> -- ****************************************************
SQL>
SQL> -- Hit Return To Continue
SQL> PAUSE

SQL>
SQL> connect myco_emp/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL>
SQL> select job_history.*, label_to_char(PRIVLAB)
2 "PRIVACY LABEL" from hr.job_history;

no rows selected

SQL>
SQL>
SQL> -- ****************************************************
SQL> -- * Connect to the Oracle pluggable database PDB1_1 as
SQL> -- * Application User myco_mgr
SQL> -- *
SQL> -- * select job_history.*, label_to_char(PRIVLAB)
SQL> -- * "PRIVACY LABEL" from hr.job_history;
SQL> --
SQL> -- ****************************************************
SQL>
SQL> -- Hit Return To Continue
SQL> PAUSE

SQL>
SQL> connect myco_mgr/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL>
SQL> select job_history.*, label_to_char(PRIVLAB)
2 "PRIVACY LABEL" from hr.job_history;

EMPLOYEE_ID START_DAT END_DATE JOB_ID DEPARTMENT_ID


----------- --------- --------- ---------- -------------
PRIVACY
LABEL

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 37
--------
102 13-JAN-93 24-JUL-98 IT_PROG 60
C

101 28-OCT-01 15-MAR-05 AC_MGR 110


C

201 17-FEB-96 19-DEC-99 MK_REP 20


C

114 24-MAR-98 31-DEC-99 ST_CLERK 50


C

122 01-JAN-99 31-DEC-99 ST_CLERK 50


C

176 24-MAR-98 31-DEC-98 SA_REP 80


C

176 01-JAN-99 31-DEC-99 SA_MAN 80


C

200 01-JUL-94 31-DEC-98 AC_ACCOUNT 90


C

8 rows selected.

SQL>
SQL> -- Hit Return To Continue
SQL> PAUSE

SQL>
SQL>
SQL>
SQL> -- ****************************************************
SQL> -- * Connect to the Oracle pluggable database PDB1_1 as
SQL> -- * Application User HR
SQL> -- ****************************************************
SQL>
SQL> connect hr/oracle_4U@localhost:1521/pdb1_1
Connected.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 38
SQL>
SQL> -- ***********************************************
SQL> -- * User HR has Oracle Label Security FULL and
SQL> -- * PROFILE_ACCESS privileges on policies FACILITY
SQL> -- * and PRIVACY
SQL> -- *
SQL> -- * select job_history.*, label_to_char(PRIVLAB)
SQL> -- * "PRIVACY LABEL" from hr.job_history;
SQL> -- *
SQL> -- **********************************************
SQL>
SQL> select job_history.*, label_to_char(PRIVLAB)
2 "PRIVACY LABEL" from hr.job_history;

EMPLOYEE_ID START_DAT END_DATE JOB_ID DEPARTMENT_ID


----------- --------- --------- ---------- -------------
PRIVACY
LABEL
--------
102 13-JAN-93 24-JUL-98 IT_PROG 60
C

101 21-SEP-89 27-OCT-93 AC_ACCOUNT 110


S

101 28-OCT-93 15-MAR-97 AC_MGR 110


C

201 17-FEB-96 19-DEC-99 MK_REP 20


C

114 24-MAR-98 31-DEC-99 ST_CLERK 50


C

122 01-JAN-99 31-DEC-99 ST_CLERK 50


C

200 17-SEP-87 17-JUN-93 AD_ASST 90


S

176 24-MAR-98 31-DEC-98 SA_REP 80


C

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 39
176 01-JAN-99 31-DEC-99 SA_MAN 80
C

200 01-JUL-94 31-DEC-98 AC_ACCOUNT 90


C

10 rows selected.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 40
Practice 13-3: Cleaning Up OLS Policies
Overview
In this practice, you clean up all OLS policies.

Tasks
1. Drop all OLS policies by running the cleanup_OLS.sql cleanup script.
Note: You are prompted first for the SYSTEM user password, and then for the LBACSYS
user password.
SQL> @$HOME/labs/OLS/cleanup_OLS.sql
SQL> SET ECHO ON
SQL> CONNECT system/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL>
SQL> -- Cleanup from previous runs
SQL>
SQL> DROP USER myco_EMP;

User dropped.

SQL> DROP USER myco_MGR;

User dropped.

SQL> DROP USER myco_PLANNING;

User dropped.

SQL>
SQL> CONNECT lbacsys/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL>
SQL> EXECUTE SA_SYSDBA.DROP_POLICY('FACILITY',TRUE);

PL/SQL procedure successfully completed.

SQL> EXECUTE SA_SYSDBA.DROP_POLICY('PRIVACY',TRUE);

PL/SQL procedure successfully completed.

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 41
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 13: Implementing Oracle Label Security Policies


Chapter 13 - Page 42
Practices for Lesson 14:
Oracle Data Redaction
Chapter 14

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 1
Practices for Lesson 14: Overview
Practices Overview
In the practice for this lesson, you use Oracle Data Redaction to redact values of shielded
columns of the HR.EMPLOYEES table.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 2
Practice 14-1: Redacting Protected Column Values with FULL
Redaction
Overview
In this practice you use FULL data redaction to display:
• The employees’ salary from the HR.EMPLOYEES as 0 instead of the real values
• The employees’ last name as blank. Louise is the only exception to be allowed to view
the employees’ last names.

Tasks
1. Display the current values from the HR.EMPLOYEES table before redaction.
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus sec

Enter password: ******


Last Successful login time: Mon Jun 17 2013 23:54:00 +00:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> CREATE USER louise IDENTIFIED BY oracle_4U;

User created.

SQL> GRANT create session TO louise;

Grant succeeded.

SQL> GRANT select ON hr.employees TO louise;

Grant succeeded.

SQL> col first_name format A12


SQL> col last_name format A10
SQL> col salary format 999999
SQL> SELECT employee_id, last_name, salary, commission_pct

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 3
FROM hr.employees
WHERE department_id = 100;
2 3
EMPLOYEE_ID LAST_NAME SALARY COMMISSION_PCT
----------- ---------- ------- --------------
108 Greenberg 12008
109 Faviet 9000
110 Chen 8200
111 Sciarra 7700
112 Urman 7800
113 Popp 6900

6 rows selected.

SQL>
2. Define a redaction policy for the HR.EMPLOYEES table specifying full redacting for the
SALARY column. SALARY is defined as NUMBER(8,2). In this example, by setting
EXPRESSION to 1=1, redaction is always performed because the expression always
evaluates to true.
The policy is enabled by default.
BEGIN
DBMS_REDACT.ADD_POLICY
(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY',
column_name => 'SALARY',
function_type => DBMS_REDACT.FULL,
expression => '1=1');
END;
/
a. The SEC user also needs the privilege to create redaction policies. Grant SEC the
ability to execute the package that creates redaction policies.
SQL> CONNECT / AS SYSDBA

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL>
SQL> GRANT execute ON dbms_redact TO sec;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 4
Grant succeeded.

SQL>
b. Connect as SEC to create the redaction policy.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> BEGIN
DBMS_REDACT.ADD_POLICY
(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY',
column_name => 'SALARY',
function_type => DBMS_REDACT.FULL,
expression => '1=1');
END;
/
2 3 4 5 6 7 8 9 10
PL/SQL procedure successfully completed.

SQL>
3. Query REDACTION_POLICIES to verify that the policy has been created and is enabled.
This view also shows under what condition the redaction will be performed as shown in the
EXPRESSION column.
SQL> COL object_owner FORMAT A12
SQL> COL object_name FORMAT A12
SQL> COL policy_name FORMAT A14
SQL> COL expression FORMAT A12
SQL> COL enable FORMAT A6
SQL> COL policy_description FORMAT A10
SQL> SELECT * FROM redaction_policies;

OBJECT_OWNER OBJECT_NAME POLICY_NAME EXPRESSION ENABLE


------------ ------------ -------------- ------------ ------
POLICY_DES
----------
HR EMPLOYEES EMP_POLICY 1=1 YES

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 5
4. Display which columns will be redacted and what type of redaction will take place.
SQL> COL column_name FORMAT A14
SQL> COL function_type FORMAT A18
SQL> COL function_parameters FORMAT A20
SQL> SELECT object_owner, object_name, column_name,
function_type, function_parameters
FROM redaction_columns;
2 3
OBJECT_OWNER OBJECT_NAME COLUMN_NAME FUNCTION_TYPE
------------ ---------------- -------------- ------------------
FUNCTION_PARAMETERS
--------------------
HR EMPLOYEES SALARY FULL REDACTION

SQL>
5. Now query the HR.EMPLOYEES table again and note that the value of the SALARY column
is 0 for all displayed rows.
a. First grant the SELECT privilege to SH.
SQL> GRANT select ON hr.employees TO sh;

Grant succeeded.

SQL>
b. Connect as SH. If SH is locked, unlock the account.
SQL> ALTER USER sh IDENTIFIED BY oracle_4U ACCOUNT UNLOCK;

User altered.

SQL> CONNECT sh
Enter password: ******
Connected.
SQL>
c. Run the same select as in task 1.
SQL> SELECT employee_id, last_name, salary, commission_pct
FROM hr.employees
WHERE department_id = 100;
2 3
EMPLOYEE_ID LAST_NAME SALARY COMMISSION_PCT
----------- ---------- ------- --------------
108 Greenberg 0
109 Faviet 0

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 6
110 Chen 0
111 Sciarra 0
112 Urman 0
113 Popp 0

6 rows selected.

SQL>
Why the value displayed for the SALARY column is 0?
The default value for all NUMBER data type columns when full redacted is 0.
SQL> SELECT number_value FROM REDACTION_VALUES_FOR_TYPE_FULL;

NUMBER_VALUE
------------
0

SQL>
6. If you query as SYSDBA, the “real” value is displayed, not the redacted value as shown in
this example. Any user who is granted the EXEMPT REDACTION POLICY privilege
bypasses any redaction policy.
a. Connect as SYSDBA.
SQL> CONNECT / AS SYSDBA
Connected.
SQL>
b. Run the same select as in task 1.
SQL> SELECT employee_id, last_name, salary, commission_pct
FROM hr.employees
WHERE department_id = 100;
2 3
EMPLOYEE_ID LAST_NAME SALARY COMMISSION_PCT
----------- ---------- ------- --------------
108 Greenberg 12008
109 Faviet 9000
110 Chen 8200
111 Sciarra 7700
112 Urman 7800
113 Popp 6900

6 rows selected.

SQL> SELECT * FROM session_privs


WHERE privilege like 'EXEMP%';
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 7
2

PRIVILEGE
----------------------------------------
EXEMPT ACCESS POLICY
EXEMPT IDENTITY POLICY
EXEMPT REDACTION POLICY
EXEMPT DML REDACTION POLICY
EXEMPT DDL REDACTION POLICY

SQL>
7. Display the last and first names of all employees.
SQL> CONNECT louise
Enter password: ******
Connected.
SQL> SELECT first_name, last_name FROM hr.employees
WHERE substr(first_name,1,1)= 'L';
2
FIRST_NAME LAST_NAME
------------ ----------
Laura Bissot
Lex De Haan
Louise Doran
Lisa Ozer
Luis Popp
Lindsey Smith

6 rows selected.

SQL>
The LAST_NAME column is not under full redaction yet.
a. Add the LAST_NAME column to the policy for full redaction except for the Louise user.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> BEGIN
DBMS_REDACT.ALTER_POLICY
(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY',
action => DBMS_REDACT.ADD_COLUMN,
column_name => 'LAST_NAME',
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 8
expression =>
'SYS_CONTEXT(''USERENV'',''SESSION_USER'')!=''LOUISE''');
END;
/
2 3 4 5 6 7 8 9 10
PL/SQL procedure successfully completed.

SQL>
b. The REDACTION_COLUMNS view shows masking functions defined on the
HR.EMPLOYEES table.
SQL> SELECT object_owner, object_name, column_name,
function_type
FROM redaction_columns;
2 3
OBJECT_OWNER OBJECT_NAME COLUMN_NAME FUNCTION_TYPE
------------ ------------ -------------- ------------------
HR EMPLOYEES SALARY FULL REDACTION
HR EMPLOYEES LAST_NAME FULL REDACTION

SQL>
c. Display the values of the LAST_NAME column. First connect as LOUISE then as SH.
SQL> CONNECT louise
Enter password: ******
Connected.
SQL> SELECT first_name, last_name FROM hr.employees
WHERE substr(first_name,1,1)= 'L'
ORDER BY 1;

FIRST_NAME LAST_NAME
------------ -----------
Laura
Lex
Lindsey
Lisa
Louise
Luis

6 rows selected.

SQL> connect sh
Enter password: ******
Connected.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 9
SQL> /

FIRST_NAME LAST_NAME
------------ ----------
Laura
Lex
Lindsey
Lisa
Louise
Luis

6 rows selected.

SQL>
The result is not fully the expected one. The default value for full redaction applies to the
values of all rows omitting the expression of the policy.
The expression of the redaction policy is still set to 1=1.
d. Modify the expression.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> BEGIN
DBMS_REDACT.ALTER_POLICY
(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY',
action => DBMS_REDACT.MODIFY_EXPRESSION,
expression =>
'SYS_CONTEXT(''USERENV'',''SESSION_USER'')!=''LOUISE''');
END;
/
2 3 4 5 6 7 8 9
PL/SQL procedure successfully completed.

SQL> COL expression format A48


SQL> SELECT policy_name, expression FROM redaction_policies;

POLICY_NAME EXPRESSION
-------------- ------------------------------------------------
EMP_POLICY SYS_CONTEXT('USERENV','SESSION_USER')!='LOUISE'

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 10
e. Retest.
SQL> CONNECT louise
Enter password: ******
Connected.
SQL> SELECT first_name, last_name FROM hr.employees
WHERE substr(first_name,1,1)= 'L'
ORDER BY 1;

FIRST_NAME LAST_NAME
------------ ----------
Laura Bissot
Lex De Haan
Lindsey Smith
Lisa Ozer
Louise Doran
Luis Popp

6 rows selected.

SQL> connect sh
Enter password: ******
Connected.
SQL> /

FIRST_NAME LAST_NAME
------------ ----------
Laura
Lex
Lindsey
Lisa
Louise
Luis

6 rows selected.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 11
Practice 14-2: Redacting Protected Column Values with PARTIAL
Redaction
Overview
In this practice, you use PARTIAL data redaction to display the HIRE_DATE column values from
the HR.EMPLOYEES as a partially redacted value instead of the real values.

Tasks
1. Query the HR.EMPLOYEES table again and display the HIRE_DATE column.
SQL> CONNECT louise
enter password: ******
Connected.
SQL> SELECT employee_id, last_name, hire_date
FROM hr.employees
WHERE department_id = 100;
2 3
EMPLOYEE_ID LAST_NAME HIRE_DATE
----------- ---------- ---------
108 Greenberg 17-AUG-02
109 Faviet 16-AUG-02
110 Chen 28-SEP-05
111 Sciarra 30-SEP-05
112 Urman 07-MAR-06
113 Popp 07-DEC-07

6 rows selected.

SQL>
2. Alter the masking policy to redact the HIRE_DATE column. In this example, partial redaction
is used to mask the actual year of hire.
BEGIN
DBMS_REDACT.ALTER_POLICY
(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY',
action => DBMS_REDACT.ADD_COLUMN,
column_name => 'HIRE_DATE',
function_type => DBMS_REDACT.PARTIAL,
function_parameters => 'MDy2012',
expression => '1=1');
END;
/

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 12
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> BEGIN
DBMS_REDACT.ALTER_POLICY
(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY',
action => DBMS_REDACT.ADD_COLUMN,
column_name => 'HIRE_DATE',
function_type => DBMS_REDACT.PARTIAL,
function_parameters => 'MDy2012',
expression => '1=1');
END;
/
2 3 4 5 6 7 8 9 10 11 12
PL/SQL procedure successfully completed.

SQL>
3. Query REDACTION_COLUMNS view to show both masking functions defined on the
HR.EMPLOYEES table.
SQL> SELECT object_owner, object_name, column_name,
function_type, function_parameters
FROM redaction_columns;
2 3
OBJECT_OWNER OBJECT_NAME COLUMN_NAME FUNCTION_TYPE
FUNCTION_PARAMETERS
------------ ----------- ------------ -----------------
-----------------
HR EMPLOYEES SALARY FULL REDACTION
HR EMPLOYEES HIRE_DATE PARTIAL REDACTION
MDy2012
HR EMPLOYEES LAST_NAME FULL REDACTION

SQL>
4. Query HR.EMPLOYEES again as the SH user. ’12’ is displayed as the hire year for all the
rows selected.
SQL> CONNECT sh
Enter password: ******
Connected.
SQL> select employee_id, last_name, hire_date
from hr.employees
where department_id = 100;
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 13
2 3
EMPLOYEE_ID LAST_NAME HIRE_DATE
----------- ------------- ---------
108 17-AUG-12
109 16-AUG-12
110 28-SEP-12
111 30-SEP-12
112 07-MAR-12
113 07-DEC-12

6 rows selected.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 14
Practice 14-3: Changing the Default Value for FULL Redaction
Overview
In this practice, you use full redaction to redact the returned data to a fixed value.
You will modify the default value for full redaction of:
• Number data to 10 for the commission percentage of all employees
• Date time data to the first of June, 2005 for the hire date of all employees

Tasks
1. Modify the default value to 10 for full redaction of the commission percentage of all
employees.
a. Display the information from the data dictionary view before updating the default value.
SQL> SELECT number_value FROM REDACTION_VALUES_FOR_TYPE_FULL;

NUMBER_VALUE
------------
0

SQL>
b. Modify the default value.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> exec DBMS_REDACT.UPDATE_FULL_REDACTION_VALUES( -
NUMBER_VAL => 10)

PL/SQL procedure successfully completed.

SQL>
c. Display the information from the data dictionary view.
SQL> SELECT number_value FROM REDACTION_VALUES_FOR_TYPE_FULL;

NUMBER_VALUE
------------
10

SQL>
d. Add the COMMISSION_PCT column to the policy for full redaction.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> BEGIN
DBMS_REDACT.ALTER_POLICY
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 15
(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY',
action => DBMS_REDACT.ADD_COLUMN,
column_name => 'COMMISSION_PCT',
expression => '1=1');
END;
/
2 3 4 5 6 7 8 9 10
PL/SQL procedure successfully completed.

SQL>
e. The REDACTION_COLUMNS view shows masking functions defined on the
HR.EMPLOYEES table.
SQL> SELECT object_owner, object_name, column_name,
function_type
FROM redaction_columns;
2 3
OBJECT_OWNER OBJECT_NAME COLUMN_NAME FUNCTION_TYPE
------------ ------------ --------------- ------------------
HR EMPLOYEES COMMISSION_PCT FULL REDACTION
HR EMPLOYEES SALARY FULL REDACTION
HR EMPLOYEES HIRE_DATE PARTIAL REDACTION
HR EMPLOYEES LAST_NAME FULL REDACTION

SQL>
f. Display the values of the COMMISSION_PCT column of all employees.
SQL> CONNECT sh
Enter password: ******
Connected.
SQL> SELECT commission_pct, first_name FROM hr.employees
ORDER BY 1 DESC;
2

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 16
COMMISSION_PCT FIRST_NAME
-------------- --------------------
… rows deleted …
Shelley
William
0 John
0 Allan
0 Patrick
0 Ellen
… rows deleted …
0 Sundar
0 Charles
0 Sundita
0 Amit

83 rows selected.

SQL>
The result still displays the value 0. After you modify a value, you must restart the database
for it to take effect. If you only flush the buffer cache, the real value of the column will be
displayed.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> SHUTDOWN IMMEDIATE
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> STARTUP
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2289968 bytes
Variable Size 264244944 bytes
Database Buffers 226492416 bytes
Redo Buffers 8032256 bytes
Database mounted.
Database opened.
SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 17
g. Display the values of the COMMISSION_PCT column of all employees.
SQL> CONNECT sh
Enter password: ******
Connected.
SQL> SELECT commission_pct, first_name FROM hr.employees
ORDER BY 1 DESC;
2
COMMISSION_PCT FIRST_NAME
-------------- --------------------
… rows deleted …
Shelley
William
10 John
10 Allan
10 Patrick
10 Ellen
… rows deleted …
10 Sundar
10 Charles
10 Sundita
10 Amit

83 rows selected.

SQL>
Notice that the default value is only applied to the values that are not NULL.
Question: When you updated the default value to a single, blank space for full redaction of
the character data type, you did not restart the instance to get the right result.
Answer: The original default value is the same as the one you set. You just activated the
default value for full redaction policies. Whereas, in this current case, the default value for
the number data type is different from the original default value.
2. Modify the default value to a 1st of June 2005 for full redaction of the hire date of all
employees.
a. Modify the default value.
SQL> CONNECT / AS SYSDBA
Connected.

SQL> SELECT date_value FROM REDACTION_VALUES_FOR_TYPE_FULL;

DATE_VALU
---------
01-JAN-01

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 18
SQL> exec DBMS_REDACT.UPDATE_FULL_REDACTION_VALUES( -
DATE_VAL => '01-JUN-05')

PL/SQL procedure successfully completed.

SQL>
b. Display the information from the data dictionary view.
SQL> SELECT date_value FROM REDACTION_VALUES_FOR_TYPE_FULL;

DATE_VALU
---------
01-JUN-05

SQL>
c. Display the first names and hire dates of all employees.
SQL> CONNECT sh
Enter password: ******
Connected.

SQL> SELECT first_name, hire_date FROM hr.employees;

FIRST_NAME HIRE_DATE
------------------- ---------
… rows deleted …
Michael 17-FEB-12
Pat 17-AUG-12
Susan 07-JUN-12
Hermann 07-JUN-12
Shelley 07-JUN-12
William 07-JUN-12

83 rows selected.

SQL>
The result still displays the previous redacted values, and does not use the default
redacting value. The HIRE_DATE column is a column to be partially redacted by the
EMP_POLICY policy. The HIRE_DATE column is not under full redaction yet.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 19
d. Add the HIRE_DATE column to the policy for full redaction.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> BEGIN
DBMS_REDACT.ALTER_POLICY
(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY',
action => DBMS_REDACT.ADD_COLUMN,
column_name => 'HIRE_DATE',
expression => '1=1');
END;
/
2 3 4 5 6 7 8 9 10 BEGIN
*
ERROR at line 1:
ORA-28060: A data redaction policy already exists on this
column.
ORA-06512: at "SYS.DBMS_REDACT_INT", line 69
ORA-06512: at "SYS.DBMS_REDACT", line 172
ORA-06512: at line 2

SQL>
e. Drop the HIRE_DATE column from the policy and add it back for full redaction.
SQL> BEGIN
DBMS_REDACT.ALTER_POLICY
(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY',
action => DBMS_REDACT.DROP_COLUMN,
column_name => 'HIRE_DATE');
END;
/
2 3 4 5 6 7 8 9
PL/SQL procedure successfully completed.

SQL> BEGIN
DBMS_REDACT.ALTER_POLICY
(object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY',
action => DBMS_REDACT.ADD_COLUMN,
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 20
column_name => 'HIRE_DATE',
expression => '1=1');
END;
/
2 3 4 5 6 7 8 9 10
PL/SQL procedure successfully completed.

SQL>
f. Display the first names and hire dates of all employees.
SQL> CONNECT sh
Enter password: ******
Connected.
SQL> SELECT first_name, hire_date FROM hr.employees;

FIRST_NAME HIRE_DATE
------------ ---------
… rows deleted …
Michael 01-JAN-01
Pat 01-JAN-01
Susan 01-JAN-01
Hermann 01-JAN-01
Shelley 01-JAN-01
William 01-JAN-01

83 rows selected.

SQL>
The result uses the original default value but not the updated default value. After you modify
a value, you must restart the database for it to take effect.
g. Restart the instance.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> SHUTDOWN IMMEDIATE
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> STARTUP
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2289968 bytes
Variable Size 264244944 bytes

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 21
Database Buffers 226492416 bytes
Redo Buffers 8032256 bytes
Database mounted.
Database opened.
SQL>
h. View the result.
SQL> CONNECT sh
Enter password: ******
Connected.
SQL> SELECT first_name, hire_date FROM hr.employees;

FIRST_NAME HIRE_DATE
------------ ---------
… rows deleted …
Michael 01-JUN-05
Pat 01-JUN-05
Susan 01-JUN-05
Hermann 01-JUN-05
Shelley 01-JUN-05
William 01-JUN-05

83 rows selected.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 22
Practice 14-4: Cleaning Up Redaction Policies
Overview
In this practice, you clean up the redaction policy applied on the HR.EMPLOYEES table.

Tasks
1. Drop the redaction policy.
BEGIN
DBMS_REDACT.DROP_POLICY
( object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY');
END;
/
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> BEGIN
DBMS_REDACT.DROP_POLICY
( object_schema => 'HR',
object_name => 'EMPLOYEES',
policy_name => 'EMP_POLICY');
END;
/
2 3 4 5 6 7
PL/SQL procedure successfully completed.

SQL> SELECT object_owner, object_name, column_name,


function_type
FROM redaction_columns;
2 3
no rows selected

SQL> SELECT * FROM redaction_policies;

no rows selected

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 23
2. Reset the default values of full redaction for the VARCHAR, NUMBER and DATA data types to
the default.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> exec SYS.DBMS_REDACT.UPDATE_FULL_REDACTION_VALUES( -
VARCHAR_VAL => ' ')

PL/SQL procedure successfully completed.

SQL> exec SYS.DBMS_REDACT.UPDATE_FULL_REDACTION_VALUES( -


NUMBER_VAL => 0)

PL/SQL procedure successfully completed.

SQL> exec SYS.DBMS_REDACT.UPDATE_FULL_REDACTION_VALUES( -


DATE_VAL => '01-JAN-01')

PL/SQL procedure successfully completed.

SQL> SELECT varchar_value, number_value, date_value


FROM REDACTION_VALUES_FOR_TYPE_FULL;
2
V NUMBER_VALUE DATE_VALU
- ------------ ---------
0 01-JAN-01

SQL>
3. Question: If you create another full redaction policy, which values are displayed for the full
redacted columns of HR.EMPLOYEES?
Answer: The values displayed for the full redacted columns of HR.EMPLOYEES use the
default values that you had set in the previous practices. They are still in effect until you
restart the instance.
4. Restart the instance.
SQL> SHUTDOWN IMMEDIATE
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> STARTUP
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2289968 bytes
Variable Size 264244944 bytes
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 24
Database Buffers 226492416 bytes
Redo Buffers 8032256 bytes
Database mounted.
Database opened.
SQL>
5. Check that the values for the SALARY and HIRE_DATE columns are displayed without
redaction.
SQL> CONNECT sh
Enter password: ******
Connected.
SQL> SELECT first_name, last_name, salary, commission_pct,
hire_date
FROM hr.employees
WHERE department_id = 100
OR first_name = 'Louise'
ORDER BY 4 DESC;
2 3 4 5 6
FIRST_NAME LAST_NAME SALARY COMMISSION_PCT HIRE_DATE
------------ ---------- ------- -------------- ---------
John Chen 8200 28-SEP-05
Nancy Greenberg 12008 17-AUG-02
Daniel Faviet 9000 16-AUG-02
Luis Popp 6900 07-DEC-07
Ismael Sciarra 7700 30-SEP-05
Jose Manuel Urman 7800 07-MAR-06
Louise Doran 7500 .3 15-DEC-05

7 rows selected.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 25
6. Drop the LOUISE user.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> DROP USER louise;

User dropped.

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 14: Oracle Data Redaction


Chapter 14 - Page 26
Practices for Lesson 15: ADM
and Data Masking
Chapter 15

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: ADM and Data Masking


Chapter 15 - Page 1
Practices for Lesson 15

There is no practice for this lesson.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 15: ADM and Data Masking


Chapter 15 - Page 2
Practices for Lesson 16:
Transparent Sensitive Data
Protection
Chapter 16

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 1
Practices for Lesson 16: Overview
Lesson Overview
In these practices, you will use TSDP to define sensitive column types and configure a TSDP
policy to protect the sensitive column data matching these sensitive column types using a VPD
policy. Then you will use the predefined TSDP REDACT_AUDIT policy to protect other sensitive
columns.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 2
Practice 16-1: Implementing a TSDP Policy
Overview
In this practice, you create a TSDP policy to protect the sensitive column data matching
sensitive column types in the orcl database. Then you will configure the TSDP to protect HR
and OE sensitive columns using a VPD policy.

Tasks
1. Create tables with sensitive columns. Use the $HOME/labs/TSDP/create_tables.sql
script.
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production

SQL> @$HOME/labs/TSDP/create_tables.sql
SQL> drop table oe.customers_info;
drop table oe.customers_info
*
ERROR at line 1:
ORA-00942: table or view does not exist

SQL>
SQL> CREATE TABLE oe.customers_info (
2 CUSTOMER_ID NUMBER(6) NOT NULL,
3 CUST_FIRST_NAME VARCHAR2(20),
4 CUST_LAST_NAME VARCHAR2(20),
5 CCN_TYPE VARCHAR2(6),
6 CCN NUMBER(30),
7 SSN NUMBER(9));

Table created.

SQL>
SQL> INSERT INTO oe.customers_info VALUES (
2 110,
'Adam','X','CARD',5105105105105100,987654320);

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 3
1 row created.

SQL> INSERT INTO oe.customers_info VALUES (


2 109,
'Christian','Y','CARD',6011111111111117,987654321);

1 row created.

SQL> INSERT INTO oe.customers_info VALUES (


2 108, 'Meenakshi','W','AMEX',378282246310005,987654322);

1 row created.

SQL> INSERT INTO oe.customers_info VALUES (


2 107,
'Peter','A','CARD',6011000000000004,987654323);

1 row created.

SQL> INSERT INTO oe.customers_info VALUES (


2 106,
'Peter','B','VISA',4111111111111111,987654324);

1 row created.

SQL> INSERT INTO oe.customers_info VALUES (


2 105,
'Peter','C','MASTER',5105105105105100,987654325);

1 row created.

SQL> INSERT INTO oe.customers_info VALUES (


2 104,
'Harrison','D','VISA',4222222222222,987654326);

1 row created.

SQL> INSERT INTO oe.customers_info VALUES (


2 103,
'Manisha','E','AMEX',343434343434343,987654327);

1 row created.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 4
SQL> INSERT INTO oe.customers_info VALUES (
2 102,
'Harrison','F','CARD',6011000990139424,987654328);

1 row created.

SQL> INSERT INTO oe.customers_info VALUES (


2 101,
'Constantin','G','MASTER',5111111111111118,987654329);

1 row created.

SQL>
SQL> COMMIT;

Commit complete.

SQL>
2. Connect as SYSDBA to grant the SEC user the execute privilege on the
SYS.DBMS_TSDP_MANAGE and SYS.DBMS_TSDP_PROTECT packages.
SQL> grant execute ON DBMS_TSDP_MANAGE to SEC;

Grant succeeded.

SQL> grant execute ON DBMS_TSDP_PROTECT to SEC;

Grant succeeded.

SQL>
3. Because the TSDP policy will be set for VPD, grant the SEC user the execute privilege on
the SYS.DBMS_RLS package if not already done for a previous practice.
SQL> grant execute on DBMS_RLS to SEC;

Grant succeeded.

SQL>
4. Define two sensitive column types. Create the 'Sensitive_Numbers' type. Columns like
CCN (credit card number) or SSN (social security number) of OE.CUSTOMERS_INFO table
will match this sensitive type. Create the 'Income' type. Columns like SALARY or
COMMISSION_PCT of HR.EMPLOYEES table will match this sensitive type.
Remark: Do not use blank spaces in the type name.
SQL> CONNECT sec

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 5
Enter password: ******
Connected.
SQL> exec DBMS_TSDP_MANAGE.DROP_SENSITIVE_TYPE (-
sensitive_type => 'Sensitive_Numbers')
> BEGIN DBMS_TSDP_MANAGE.DROP_SENSITIVE_TYPE ( sensitive_type
=> 'Sensitive_Numbers'); END;

*
ERROR at line 1:
ORA-45610: Sensitive type Sensitive_Numbers does not exist.
ORA-06512: at "SYS.DBMS_TSDP_MANAGE", line 348
ORA-06512: at line 1

SQL> exec DBMS_TSDP_MANAGE.DROP_SENSITIVE_TYPE (-


sensitive_type => 'Income')
> BEGIN DBMS_TSDP_MANAGE.DROP_SENSITIVE_TYPE ( sensitive_type
=> 'Income'); END;

*
ERROR at line 1:
ORA-45610: Sensitive type Income does not exist.
ORA-06512: at "SYS.DBMS_TSDP_MANAGE", line 348
ORA-06512: at line 1

SQL> exec DBMS_TSDP_MANAGE.ADD_SENSITIVE_TYPE (-


sensitive_type => 'Sensitive_Numbers',-
user_comment => 'Type for credit card numbers, -
social security numbers using a number data type' )
> >
PL/SQL procedure successfully completed.

SQL> exec DBMS_TSDP_MANAGE.ADD_SENSITIVE_TYPE (-


sensitive_type => 'Income',-
user_comment => 'Type for salary, commission' )
> >
PL/SQL procedure successfully completed.

SQL>
5. Display the list of sensitive column types.
SQL> COL name FORMAT A18
SQL> COL source_type FORMAT A3
SQL> SELECT name, user_comment, source_type

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 6
FROM dba_sensitive_column_types
WHERE source_type='DB';
2 3
NAME
------------------
USER_COMMENT
---------------------------------------------------------------
SOU
---
Sensitive_Numbers
Type for credit card numbers, social security numbers using a
number data type
DB

Income
Type for salary, commission
DB

SQL>
6. You identified the list of sensitive columns:
• OE.CUSTOMERS_INFO.CCN
• OE.CUSTOMERS_INFO.SSN
• HR.EMPLOYEES.SALARY
• HR.EMPLOYEES.COMMISSION_PCT
Associate OE.CUSTOMERS_INFO.CCN and OE.CUSTOMERS_INFO.SSN columns with the
'Sensitive_Numbers' sensitive type.
Associate HR.EMPLOYEES.SALARY and HR.EMPLOYEES.COMMISSION_PCT columns with
the 'Income' sensitive type.
SQL> exec DBMS_TSDP_MANAGE.ADD_SENSITIVE_COLUMN(-
schema_name => 'OE', -
table_name => 'CUSTOMERS_INFO', -
column_name => 'CCN', -
sensitive_type => 'Sensitive_Numbers')
> > > >

PL/SQL procedure successfully completed.

SQL> exec DBMS_TSDP_MANAGE.ADD_SENSITIVE_COLUMN(-


schema_name => 'OE', -
table_name => 'CUSTOMERS_INFO', -
column_name => 'SSN', -
sensitive_type => 'Sensitive_Numbers')
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 7
> > > >

PL/SQL procedure successfully completed.

SQL> exec DBMS_TSDP_MANAGE.ADD_SENSITIVE_COLUMN(-


schema_name => 'HR', -
table_name => 'EMPLOYEES', -
column_name => 'SALARY', -
sensitive_type => 'Income')
> > > >

PL/SQL procedure successfully completed.

SQL> exec DBMS_TSDP_MANAGE.ADD_SENSITIVE_COLUMN(-


schema_name => 'HR', -
table_name => 'EMPLOYEES', -
column_name => 'COMMISSION_PCT', -
sensitive_type => 'Income')
> > > >

PL/SQL procedure successfully completed.

7. Display the list of identified columns as confidential.


SQL> COL SCHEMA_NAME FORMAT A10
SQL> COL SENSITIVE_TYPE FORMAT A20
SQL> COL TABLE_NAME FORMAT A16
SQL> COL COLUMN_NAME FORMAT A14
SQL> SELECT SCHEMA_NAME, TABLE_NAME,
COLUMN_NAME, SENSITIVE_TYPE
FROM dba_sensitive_data;
2 3
SCHEMA_NAM TABLE_NAME COLUMN_NAME SENSITIVE_TYPE
---------- ---------------- -------------- --------------------
HR EMPLOYEES SALARY Income
HR EMPLOYEES COMMISSION_PCT Income
OE CUSTOMERS_INFO CCN Sensitive_Numbers
OE CUSTOMERS_INFO SSN Sensitive_Numbers

SQL>
8. Create the TSDP policy. You can configure it for the Virtual Private Database or Oracle
Data Redaction settings that you want to use, and then apply these settings to a TSDP
policy.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 8
Because you are using Oracle Virtual Private Database for your policy, a specification of
the VPD settings must be set. You can also specify conditions to test when the policy is
enabled. For example, the data type of the column which should be satisfied before the
policy can be enabled.
a. Create a user that exists in the values of the HR.EMPLOYEES.FIRST_NAME column as
well as in OE.CUSTOMERS_INFO table. And also grant SCOTT the same privileges for
the further tests.
SQL> CREATE USER peter IDENTIFIED BY oracle_4U;

User created.

SQL> GRANT create session TO peter;

Grant succeeded.

SQL> GRANT select ON hr.employees TO peter, scott;

Grant succeeded.

SQL> GRANT select ON oe.customers_info TO peter, scott;

Grant succeeded.

SQL>
b. Create the VPD function that TSDP will associate with the VPD policy that will be
automatically created when you enable the TSDP policy.
SQL> CREATE OR REPLACE FUNCTION vpd_tsdp_function (
v_schema IN VARCHAR2, v_objname IN VARCHAR2)
RETURN VARCHAR2 AS
BEGIN
RETURN 'SYS_CONTEXT(''USERENV'',''SESSION_USER'') =
''PETER''';
END vpd_tsdp_function;
/
2 3 4 5 6 7
Function created.

SQL>
c. Create the TSDP policy. You must at least define the name of the VPD function as one
of the VPD_FEATURE_OPTIONS. All other options have default values.
When the TSDP policy is enabled, the VPD policy that is automatically created will
have its sec_relevant_cols parameter (of DBMS_RLS.ADD_POLICY) set to the
name of the sensitive column on which TSDP enables the VPD policy. If you had not

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 9
set the sec_relevant_cols_opt parameter, then TSDP would not have used the
DBMS_RLS.ADD_POLICY sec_relevant_cols_opt parameter.
SQL> DECLARE
vpd_feature_options SYS.DBMS_TSDP_PROTECT.FEATURE_OPTIONS;
policy_conditions SYS.DBMS_TSDP_PROTECT.POLICY_CONDITIONS;
BEGIN
vpd_feature_options ('policy_function') :=
'vpd_tsdp_function';
vpd_feature_options ('sec_relevant_cols_opt') :=
'DBMS_RLS.ALL_ROWS';
vpd_feature_options ('statement_types') := 'SELECT';
policy_conditions(DBMS_TSDP_PROTECT.DATATYPE) := 'NUMBER';
DBMS_TSDP_PROTECT.ADD_POLICY('tsdp_vpd',
DBMS_TSDP_PROTECT.VPD,
vpd_feature_options,
policy_conditions);
END;
/
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16
PL/SQL procedure successfully completed.

SQL>
d. Display all information related to the new TSDP policy, like parameters, conditions,
features.
SQL> COL POLICY_NAME FORMAT A16
SQL> COL PROPERTY FORMAT A12
SQL> COL VALUE FORMAT A12
SQL> SELECT * FROM DBA_TSDP_POLICY_FEATURE;

POLICY_NAME SECURITY_FEA
---------------- ------------
REDACT_AUDIT REDACT_AUDIT
tsdp_vpd VPD

SQL> SELECT * FROM DBA_TSDP_POLICY_CONDITION;

POLICY_NAME SUB_POLICY PROPERTY VALUE


---------------- ---------- ------------ ------------
tsdp_vpd 1 DATATYPE NUMBER

SQL> col parameter format A24

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 10
SQL> col value format A20
SQL> SELECT policy_name, parameter, value, default_option
FROM DBA_TSDP_POLICY_PARAMETER;
2
POLICY_NAME PARAMETER VALUE DEFAU
------------ -------------------- -------------------- -----
REDACT_AUDIT ORA$TSDP_DEFAULT ORA$TSDP_DEFAULT TRUE
tsdp_vpd policy_function vpd_tsdp_function FALSE
tsdp_vpd sec_relevant_cols_opt DBMS_RLS.ALL_ROWS FALSE
tsdp_vpd statement_types SELECT FALSE

SQL>
9. Associate the TSDP policy with the 'Sensitive_Numbers' and 'Income' sensitive types.
SQL> exec DBMS_TSDP_PROTECT.ASSOCIATE_POLICY( -
policy_name => 'tsdp_vpd', -
sensitive_type => 'Sensitive_Numbers', -
associate => TRUE)
> > >
PL/SQL procedure successfully completed.

SQL> exec DBMS_TSDP_PROTECT.ASSOCIATE_POLICY( -


policy_name => 'tsdp_vpd', -
sensitive_type => 'Income', -
associate => TRUE)
> > >
PL/SQL procedure successfully completed.

SQL> col sensitive_type format A30


SQL> select * from DBA_TSDP_POLICY_TYPE;

POLICY_NAME SENSITIVE_TYPE
---------------- ------------------------------
REDACT_AUDIT Sensitive_Numbers
REDACT_AUDIT Income
tsdp_vpd Sensitive_Numbers
tsdp_vpd Income

SQL>
10. Enable the TSDP policy protections at the sensitive type level.
SQL> exec DBMS_TSDP_PROTECT.ENABLE_PROTECTION_TYPE( -
sensitive_type => 'Sensitive_Numbers')
>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 11
PL/SQL procedure successfully completed.

SQL> exec DBMS_TSDP_PROTECT.ENABLE_PROTECTION_TYPE( -


sensitive_type => 'Income')
>
PL/SQL procedure successfully completed.

SQL>
11. Display the protected columns.
SQL> COL SCHEMA_NAME FORMAT A4
SQL> COL TABLE_NAME FORMAT A14
SQL> COL COLUMN_NAME FORMAT A14
SQL> COL TSDP_POLICY FORMAT A14
SQL> COL SECURITY_FEATURE FORMAT A14
SQL> COL SECURITY_FEATURE_POLICY FORMAT A40
SQL> SELECT schema_name, table_name,
column_name, tsdp_policy,
security_feature, SECURITY_FEATURE_POLICY
FROM DBA_TSDP_POLICY_PROTECTION;
2 3 4 5
SCHE TABLE_NAME COLUMN_NAME TSDP_POLICY SECU
---- -------------- -------------- -------------- -------------
SECURITY_FEATURE_POLICY
---------------------------------------------------------------
OE CUSTOMERS_INFO SSN REDACT_AUDIT REDACT_AUDIT
REDACT_AUDIT_POLICY

HR EMPLOYEES COMMISSION_PCT REDACT_AUDIT REDACT_AUDIT


REDACT_AUDIT_POLICY

OE CUSTOMERS_INFO CCN REDACT_AUDIT REDACT_AUDIT


REDACT_AUDIT_POLICY

HR EMPLOYEES SALARY REDACT_AUDIT REDACT_AUDIT


REDACT_AUDIT_POLICY

HR EMPLOYEES COMMISSION_PCT tsdp_vpd VPD


ORA$VPD_185+uGj0bZ3Q61t4M8VzcA

HR EMPLOYEES SALARY tsdp_vpd VPD


ORA$VPD_OB41Bady5I5jx4iYxsjT6w

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 12
OE CUSTOMERS_INFO SSN tsdp_vpd VPD
ORA$VPD_DeR0fkLChcNgHhUWVV6p/g

OE CUSTOMERS_INFO CCN tsdp_vpd VPD


ORA$VPD_sijJYeNDqu61N4q8RQ3+QA

SQL>
12. Display VPD policies created.
SQL> set pages 100
SQL> COL function FORMAT A18
SQL> COL pf_owner FORMAT A4
SQL> COL package FORMAT A4
SQL> COL policy_group FORMAT A12
SQL> COL policy_name FORMAT A32
SQL> COL object_owner FORMAT A12
SQL> COL object_name FORMAT A20
SQL> select * from dba_policies
where function='VPD_TSDP_FUNCTION';
2
OBJECT_OWNER
---------------------------------------------------------------
OBJECT_NAME
---------------------------------------------------------------
POLICY_GROUP
---------------------------------------------------------------
POLICY_NAME
---------------------------------------------------------------
PF_OWNER
---------------------------------------------------------------
PACKAGE
---------------------------------------------------------------
FUNCTION
---------------------------------------------------------------
SEL INS UPD DEL IDX CHK ENA STA POLICY_TYPE LON
--- --- --- --- --- --- --- --- ------------------------ ---
HR
EMPLOYEES
SYS_DEFAULT
ORA$VPD_185+uGj0bZ3Q61t4M8VzcA
SEC

VPD_TSDP_FUNCTION
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 13
YES NO NO NO NO NO YES NO DYNAMIC NO

HR
EMPLOYEES
SYS_DEFAULT
ORA$VPD_OB41Bady5I5jx4iYxsjT6w
SEC

VPD_TSDP_FUNCTION
YES NO NO NO NO NO YES NO DYNAMIC NO

OE
CUSTOMERS_INFO
SYS_DEFAULT
ORA$VPD_DeR0fkLChcNgHhUWVV6p/g
SEC

VPD_TSDP_FUNCTION
YES NO NO NO NO NO YES NO DYNAMIC NO

OE
CUSTOMERS_INFO
SYS_DEFAULT
ORA$VPD_sijJYeNDqu61N4q8RQ3+QA
SEC

VPD_TSDP_FUNCTION
YES NO NO NO NO NO YES NO DYNAMIC NO

SQL>
13. Test if the VPD and TSDP protect the four columns identified as sensitive.
a. Connect as PETER.
SQL> CONNECT peter
Enter password: ******
Connected.
SQL> COL ssn FORMAT 99999999999
SQL> COL ccn FORMAT 999999999999999999
SQL> SELECT ccn, ssn FROM oe.customers_info;

CCN SSN
------------------- ------------
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 14
5105105105105100 987654320
6011111111111117 987654321
378282246310005 987654322
6011000000000004 987654323
4111111111111111 987654324
5105105105105100 987654325
4222222222222 987654326
343434343434343 987654327
6011000990139424 987654328
5111111111111118 987654329

10 rows selected.

SQL> SELECT last_name, salary, commission_pct


FROM hr.employees;
2
LAST_NAME SALARY COMMISSION_PCT
-------------------------- --------- --------------
… rows deleted …
Bloom 10000 .2
Kumar 6100 .1
Livingston 8400 .2
Taylor 8600
Smith 8000

83 rows selected.

SQL>
Notice that Peter can see all rows and all values of the sensitive type columns, CCN and
SSN columns from OE.CUSTOMERS_INFO and SALARY and COMMISSION_PCT
columns from HR.EMPLOYEES.
b. Connect as SCOTT.
SQL> CONNECT scott
Enter password: ******
Connected.
SQL> SELECT cust_last_name, ccn, ssn FROM oe.customers_info;

CUST_LAST_NAME CCN SSN


-------------------- ------------------- ------------
X
Y
W

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 15
A
B
C
D
E
F
G

10 rows selected.

SQL> SELECT last_name, salary, commission_pct


FROM hr.employees;
2
LAST_NAME SALARY COMMISSION_PCT
------------------------- ---------- --------------
… rows deleted …

Kumar
Livingston
Taylor
Sullivan
Sarchand
Cabrio
Dilly
Perkins
Everett
Walsh

83 rows selected.

SQL>
Notice that Scott cannot see any value of any the sensitive type columns from both
OE.CUSTOMERS_INFO and HR.EMPLOYEES tables.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 16
Practice 16-2: Using REDACT_ AUDIT Policy
Overview
In this practice, you will display or mask the bind variable values used in statements where
sensitive columns are protected by TSPD policy. You will disable and re-enable the predefined
REDACT_AUDIT policy to display or mask the values.

Tasks
1. Audit any SELECT operation on OE.CUSTOMERS_INFO table executed by PETER. The
AUDIT command uses a new syntax that will be covered in the lesson 21 and practice 21-2.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> create audit policy pol_sel actions select on
oe.customers_info;

Audit policy created.

SQL> audit policy pol_sel by peter;

Audit succeeded.

SQL>
2. Verify that there is a REDACT_AUDIT policy associated with the SSN sensitive column.
SQL> SELECT schema_name, table_name,
column_name, tsdp_policy,
security_feature, SECURITY_FEATURE_POLICY
FROM DBA_TSDP_POLICY_PROTECTION
WHERE tsdp_policy <> 'tsdp_vpd';
2 3 4 5
SCHE TABLE_NAME COLUMN_NAME TSDP_POLICY SECU
---- -------------- -------------- -------------- -------------
SECURITY_FEATURE_POLICY
---------------------------------------------------------------
OE CUSTOMERS_INFO SSN REDACT_AUDIT REDACT_AUDIT
REDACT_AUDIT_POLICY

HR EMPLOYEES COMMISSION_PCT REDACT_AUDIT REDACT_AUDIT


REDACT_AUDIT_POLICY

OE CUSTOMERS_INFO CCN REDACT_AUDIT REDACT_AUDIT


REDACT_AUDIT_POLICY

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 17
HR EMPLOYEES SALARY REDACT_AUDIT REDACT_AUDIT
REDACT_AUDIT_POLICY

SQL>
3. The REDACT_AUDIT policy masks bind values of bind variables that are considered to be
sensitive or "associated" with sensitive columns with an ‘*’ value. In comparison conditions,
when a sensitive column and a bind variable appear in the expressions that are being
compared, the bind value is masked. In our case, the bind value of the SSN_VAR bind
variable will be masked by the REDACT_AUDIT policy because SSN_VAR, and SSN appear
as arguments to the equality condition. Connect as PETER, set a bind variable and execute
a SELECT statement on the SSN protected sensitive column.
SQL> connect peter
Enter password: ******
Connected.
SQL> VAR SSN_VAR NUMBER;
SQL> exec :SSN_VAR:=987654323

PL/SQL procedure successfully completed.

SQL> SELECT ccn, ssn FROM oe.customers_info where ssn=:SSN_VAR;

CCN SSN
------------------- ------------
6011000000000004 987654323

SQL>
4. Verify that the audited action does not display the bind value for the SSN_VAR bind variable.
SQL> connect / as sysdba
Connected.
SQL> select SQL_TEXT, SQL_BINDS from unified_audit_trail
where DBUSERNAME='PETER';

SQL_TEXT
---------------------------------------------------------------
SQL_BINDS
---------------------------------------------------------------
… rows deleted

SELECT ccn, ssn FROM oe.customers_info where ssn=:SSN_VAR


#1(1):*

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 18
5. Disable the REDACT_AUDIT policy for the SSN sensitive column.
SQL> exec DBMS_TSDP_PROTECT.DISABLE_PROTECTION_COLUMN -
( schema_name => 'OE', -
table_name => 'CUSTOMERS_INFO', -
column_name => 'SSN', -
policy => 'REDACT_AUDIT')
> > > >
PL/SQL procedure successfully completed.

SQL>
6. Reconnect as PETER, set a bind variable and reexecute a SELECT statement on the SSN
protected sensitive column.
SQL> connect peter
Enter password: ******
Connected.
SQL> VAR SSN_VAR NUMBER;
SQL> exec :SSN_VAR:=987654323

PL/SQL procedure successfully completed.

SQL> SELECT ccn, ssn FROM oe.customers_info where ssn=:SSN_VAR;

CCN SSN
------------------- ------------
6011000000000004 987654323

SQL>
7. Display the bind value for the SSN_VAR bind variable.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> select SQL_TEXT, SQL_BINDS from unified_audit_trail where
DBUSERNAME='PETER';

SQL_TEXT
---------------------------------------------------------------
SQL_BINDS
---------------------------------------------------------------
… rows deleted

SELECT ccn, ssn FROM oe.customers_info where ssn=:SSN_VAR


#1(1):*

SELECT ccn, ssn FROM oe.customers_info where ssn=:SSN_VAR


Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 19
#1(9):987654323

SQL>
8. Drop the audit policy.
SQL> noaudit policy pol_sel by peter;

Noaudit succeeded.

SQL> drop audit policy pol_sel;

Audit Policy dropped.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 20
Practice 16-3: Disabling TSDP Policies
Overview
In this practice, you will disable the TSDP policy created in practice 16-1.

Tasks
1. You can imagine that in a production environment, you need to perform some maintenance
operations and momentarily disable the protection.
Disable the protection at the sensitive type level.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> exec DBMS_TSDP_PROTECT.DISABLE_PROTECTION_TYPE( -
'Sensitive_Numbers')

PL/SQL procedure successfully completed.

SQL> exec DBMS_TSDP_PROTECT.DISABLE_PROTECTION_TYPE( -


'Income')

PL/SQL procedure successfully completed.

SQL>
2. Connect as SCOTT and check that the user can easily view any data.
SQL> CONNECT scott
Enter password: ******
Connected.
SQL> SELECT ccn, ssn FROM oe.customers_info;

CCN SSN
------------------- ------------
5105105105105100 987654320
6011111111111117 987654321
378282246310005 987654322
6011000000000004 987654323
4111111111111111 987654324
5105105105105100 987654325
4222222222222 987654326
343434343434343 987654327
6011000990139424 987654328
5111111111111118 987654329

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 21
10 rows selected.

SQL> SELECT last_name, salary, commission_pct


FROM hr.employees;
2
LAST_NAME SALARY COMMISSION_PCT
-------------------------- --------- --------------
… rows deleted …
Kumar 6300 .1
Livingston 8600 .2
Taylor 3400
Sullivan 2700
Sarchand 4400
Cabrio 3200
Dilly 3800
Perkins 2700
Everett 4100
Walsh 3300

83 rows selected.

SQL>
SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 16: Transparent Sensitive Data Protection


Chapter 16 - Page 22
Practices for Lesson 17:
Encryption Concepts
Chapter 17

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 17: Encryption Concepts


Chapter 17 - Page 1
Practices for Lesson 17

There are no practices for this lesson.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 17: Encryption Concepts


Chapter 17 - Page 2
Practices for Lesson 18:
Using Application-Based
Encryption
Chapter 18

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Using Application-Based Encryption


Chapter 18 - Page 1
Practice 18-1: Using DBMS_CRYPTO for Encryption
Overview
In this practice, you create functions to encrypt and decrypt data, and create a KEYS table.
Then, by using the functions, you encrypt and decrypt column data. You also apply an SHA-1
message digest to the column to verify integrity.

Tasks
1. Review and execute the crypto_random.sql script in the /home/oracle/labs/ENC
directory, which performs the following actions:
a. Adds a credit card column to the CUSTOMERS table
b. Creates the ENCRYPT function for AES encryption
c. Creates the DECRYPT function for AES decryption
d. Creates a KEYS table to hold a 128-bit key value (KEY RAW (16))
e. Inserts a key value generated by DBMS_CRYTPO.RANDOM_BYTES
f. Shows the key value
$ cd ~/labs/ENC
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus /nolog @$HOME/labs/ENC/crypto_random.sql

SQL*Plus: Release 12.1.0.1.0 Production on Tue May 28 08:10:00


2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.

SQL>
SQL> --- Grant Execute on DBMS_CRYPTO TO OE ---
SQL>
SQL> CONNECT / AS SYSDBA
Connected.
SQL>
SQL> GRANT EXECUTE ON DBMS_CRYPTO TO OE;

Grant succeeded.

SQL>
SQL>
SQL> CONNECT oe/oracle_4U
Connected.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Using Application-Based Encryption


Chapter 18 - Page 2
SQL>
SQL> -- Alter the customers table to hold an
SQL> -- encrypted CREDITCARD Number
SQL>
SQL> ALTER TABLE customers DROP column credit_card_num;
ALTER TABLE customers DROP column credit_card_num
*
ERROR at line 1:
ORA-00904: "CREDIT_CARD_NUM": invalid identifier

SQL>
SQL> ALTER TABLE customers ADD credit_card_num RAW(2000);

Table altered.

SQL>
SQL>
SQL> --- Create the encrypt_value and
SQL> -- decrypt_value functions
SQL>
SQL> create or replace function encrypt_value
2 (
3 p_in in varchar2,
4 p_key in raw
5 )
6 return raw is
7 l_enc_val raw (2000);
8 l_mod number := dbms_crypto.ENCRYPT_AES128
9 + dbms_crypto.CHAIN_CBC
10 + dbms_crypto.PAD_PKCS5;
11 begin
12 l_enc_val := dbms_crypto.encrypt
13 (
14 UTL_I18N.STRING_TO_RAW
15 (p_in, 'AL32UTF8'),
16 l_mod,
17 p_key
18 );
19 return l_enc_val;
20 end;
21 /

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Using Application-Based Encryption


Chapter 18 - Page 3
Function created.

SQL>
SQL>
SQL> create or replace function decrypt_value
2 (
3 p_in in raw,
4 p_key in raw
5 )
6 return varchar2
7 is
8 l_ret varchar2 (2000);
9 l_dec_val raw (2000);
10 l_mod number := dbms_crypto.ENCRYPT_AES128
11 + dbms_crypto.CHAIN_CBC
12 + dbms_crypto.PAD_PKCS5;
13 begin
14 l_dec_val := dbms_crypto.decrypt
15 (
16 p_in,
17 l_mod,
18 p_key
19 );
20 l_ret:= UTL_I18N.RAW_TO_CHAR
21 (l_dec_val, 'AL32UTF8');
22 return l_ret;
23 end;
24 /

Function created.

SQL>
SQL>
SQL> -- Create KEYS table
SQL> DROP TABLE KEYS;
DROP TABLE KEYS
*
ERROR at line 1:
ORA-00942: table or view does not exist

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Using Application-Based Encryption


Chapter 18 - Page 4
SQL>
SQL>
SQL> CREATE TABLE KEYS (KEY_VALUE RAW(16));

Table created.

SQL>
SQL> -- get a KEY and store it in KEYS
SQL>
SQL> INSERT INTO KEYS
2 SELECT DBMS_CRYPTO.RANDOMBYTES(16) FROM DUAL;

1 row created.

SQL>
SQL>
SQL> COMMIT;

Commit complete.

SQL>
SQL> SELECT * FROM KEYS;

KEY_VALUE
--------------------------------
AD4C95D0E9D1F31DE5106463F3C103AB

SQL>
2. Update one of the customer’s rows with a credit card number.
SQL> UPDATE customers
SET credit_card_num = '123456789012345678901234'
WHERE customer_id = 101;
2 3
1 row updated.

SQL> COMMIT;

Commit complete.

SQL>
3. Verify the update by selecting the credit card number of the row just updated. Save this
script because you will select this column several times in this practice.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Using Application-Based Encryption


Chapter 18 - Page 5
SQL> SELECT credit_card_num
FROM customers
WHERE customer_id = 101;

CREDIT_CARD_NUM
----------------------------------------------------------
123456789012345678901234

SQL>
4. Encrypt the credit card number by using the function created in step 1.
SQL> DECLARE
l_key RAW(16);
BEGIN
SELECT key_value INTO l_key FROM KEYS;

UPDATE customers
SET credit_card_num
= encrypt_value(credit_card_num, l_key)
WHERE customer_id = 101;

COMMIT;
END;
/
2 3 4 5 6 7 8 9 10 11 12 13
PL/SQL procedure successfully completed.

SQL>
5. Verify the encryption by selecting the credit card number of the row just updated.
SQL> SELECT UTL_I18N.RAW_TO_CHAR(credit_card_num, 'AL32UTF8')
FROM customers
WHERE customer_id = 101;

UTL_I18N.RAW_TO_CHAR(CREDIT_CARD_NUM,'AL32UTF8')
--------------------------------------------------------------
?,C??V<???O)>?P?E????

SQL>
6. Using the function created in step 1, select the decrypted column.
SQL> SELECT decrypt_value(credit_card_num,
(SELECT key_value FROM KEYS))
FROM customers
WHERE customer_id = 101;
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Using Application-Based Encryption


Chapter 18 - Page 6
DECRYPT_VALUE(CREDIT_CARD_NUM,(SELECTKEY_VALUEFROMKEYS))
---------------------------------------------------------
123456789012345678901234

SQL>
7. Update the CUSTOMERS table with the decrypted credit card number.
SQL> UPDATE customers
SET credit_card_num=decrypt_value(credit_card_num,
(SELECT key_value FROM keys))
WHERE customer_id = 101;
2 3 4
1 row updated.

SQL> commit;

Commit complete.

SQL>
8. Verify that the update worked by selecting the credit card number.
SQL> SELECT credit_card_num
FROM customers
WHERE customer_id = 101;

CREDIT_CARD_NUM
---------------------------------------------------------
123456789012345678901234

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Using Application-Based Encryption


Chapter 18 - Page 7
Practice 18-2: Checksumming by Using the HASH Function

Overview
In this practice, you will checksum a credit card number value by using the HASH function of
DBMS_CRYPTO package.

Tasks
1. What happens when you try to produce an SHA-1 checksum on the CREDIT_CARD_NUM
column? Why?
Because the procedures and functions in DBMS_CRYPTO are overloaded, the Oracle
instance cannot determine the correct version of the function to call. To correct this, wrap
the call in a PL/SQL function (as was done with encryption and decryption in the first step of
this practice).
SQL> SELECT DBMS_CRYPTO.HASH(credit_card_num,
DBMS_CRYPTO.HASH_SH1)
FROM customers
WHERE customer_id = 101;
DBMS_CRYPTO.HASH_SH1)
*
ERROR at line 2:
ORA-06553: PLS-221: 'HASH_SH1' is not a procedure or is
undefined

SQL>
2. The hash.sql script creates a function called CHECKSUM that produces an SHA-1 hash of
the input. Review and execute hash.sql.
SQL> @$HOME/labs/ENC/hash.sql
SQL> SET ECHO OFF
SQL>
SQL> CONNECT oe
Enter password: *****
Connected.
SQL>
SQL> CREATE OR REPLACE FUNCTION checksum (
2 p_raw_input RAW)
3 RETURN RAW
4 IS
5 v_checksum RAW(20);
6 BEGIN
7 v_checksum :=
8 DBMS_CRYPTO.HASH(
9 src => p_raw_input,
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Using Application-Based Encryption


Chapter 18 - Page 8
10 typ => DBMS_CRYPTO.HASH_SH1);
11
12 RETURN v_checksum;
13 END;
14 /

Function created.
SQL>
3. Use the function created in the previous step to produce a checksum for the credit card
number.
SQL> SELECT checksum (credit_card_num)
FROM customers
WHERE customer_id = 101;

CHECKSUM(CREDIT_CARD_NUM)
---------------------------------------------------------
196FB5FB06A63A73D0F1D31D6E985C996C3AEFE9

SQL>
4. Change the credit card number in the table.
SQL> UPDATE customers
SET credit_card_num = '123456789A12345678901234'
WHERE customer_id = 101;
2 3
1 row updated.

SQL> COMMIT;

Commit complete.

SQL>
5. Verify that the checksum has changed by using the function created in step 2. Compare the
checksum to the value produced in step 3.
SQL> SELECT checksum (credit_card_num)
FROM customers
WHERE customer_id = 101;

CHECKSUM(CREDIT_CARD_NUM)
---------------------------------------------------------
C2578E5407A57A042B24EC0CFBDF418DB62F526F

SQL> EXIT
$
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Using Application-Based Encryption


Chapter 18 - Page 9
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 18: Using Application-Based Encryption


Chapter 18 - Page 10
Practices for Lesson 19:
Applying Transparent Data
Encryption
Chapter 19

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 1
Practice 19-1: Configuring the Password-Based Keystore for TDE
Overview
In this practice, you will configure a password-based keystore for a non-CDB and a password-
based keystore for a CDB. Then you will set the master key for the non-CDB and the master
key for each PDB of the CDB.
In the sqlnet.ora file, you must set the ENCRYPTION_WALLET_LOCATION parameter to
specify the keystore location. When determining which keystore to use, Oracle Database
searches for the keystore location in the following places, in this order:
1. First, it attempts to use the keystore in the location specified by the parameter
ENCRYPTION_WALLET_LOCATION in the sqlnet.ora file.
2. If the ENCRYPTION_WALLET_LOCATION parameter is not set, then it attempts to use
the keystore in the location that is specified by the parameter WALLET_LOCATION.
3. If the WALLET_LOCATION parameter is also not set, then Oracle Database looks for a
keystore at the default database location, which is
$ORACLE_BASE/admin/DB_UNIQUE_NAME/wallet or
$ORACLE_HOME/admin/DB_UNIQUE_NAME/wallet. (DB_UNIQUE_NAME is the unique
name of the database specified in the initialization parameter file.) When the keystore
location is not set in the sqlnet.ora file, then the V$ENCRYPTION_WALLET view
displays the default location. You can check the location and status of the keystore in the
V$ENCRYPTION_WALLET view.

Task
1. Prepare the orcl database for encryption.
a. Create a directory for the unique Oracle password-based keystore for the database at
$ORACLE_BASE/admin/orcl/wallet if it does not exist.
$ mkdir $ORACLE_BASE/admin/orcl/wallet
$
b. Connect to the orcl database instance as a user who possesses the SYSKM privilege
to create the password-based keystore.
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as syskm

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> ADMINISTER KEY MANAGEMENT CREATE KEYSTORE


Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 2
'/u01/app/oracle/admin/orcl/wallet'
IDENTIFIED BY secret;
2 3
keystore altered.

SQL> EXIT
$
c. Verify that the file is created in the appropriate directory.
$ ls -l /u01/app/oracle/admin/orcl/wallet
total 4
-rw-r--r-- 1 oracle oinstall 2408 Jun 18 06:46 ewallet.p12
$
d. Open the keystore.
$ sqlplus / as syskm

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE OPEN


IDENTIFIED BY secret;
2
keystore altered.

SQL>
e. Generate the master encryption key. The clause WITH BACKUP USING is mandatory
and creates a backup of the keystore before the master key is created and stored in
the keystore.
SQL> ADMINISTER KEY MANAGEMENT SET KEY
IDENTIFIED BY secret
WITH BACKUP
USING 'for_12c';
2 3 4
keystore altered.

SQL>
f. Verify that the keystore has been backed up before the master key generation.
SQL> !ls -l /u01/app/oracle/admin/orcl/wallet
-rw-r--r-- 1 oracle oinstall 2408 Jun 18 06:48
ewallet_2013061806481418_for_12c.p12

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 3
-rw-r--r-- 1 oracle oinstall 4112 Jun 18 06:48 ewallet.p12

SQL>
Notice that if you regenerate the master key, the file grows. All previous master keys are
kept for data which could have used the previous master keys.
SQL> ADMINISTER KEY MANAGEMENT SET KEY
IDENTIFIED BY secret;
2 ADMINISTER KEY MANAGEMENT SET KEY
*
ERROR at line 1:
ORA-46631: keystore needs to be backed up

SQL> ADMINISTER KEY MANAGEMENT SET KEY


IDENTIFIED BY secret
WITH BACKUP;
2 3
keystore altered.

SQL> !ls -l /u01/app/oracle/admin/orcl/wallet

-rw-r--r-- 1 oracle oinstall 2408 Jun 18 06:48


ewallet_2013061806481418_for_12c.p12
-rw-r--r-- 1 oracle oinstall 4112 Jun 18 06:48
ewallet_2013061806485974.p12
-rw-r--r-- 1 oracle oinstall 6312 Jun 18 06:48 ewallet.p12

SQL>
g. Back up the keystore which contains the current master key.
SQL> ADMINISTER KEY MANAGEMENT BACKUP KEYSTORE
IDENTIFIED BY secret;
2
keystore altered.

SQL> !ls -l /u01/app/oracle/admin/orcl/wallet

-rw-r--r-- 1 oracle oinstall 2408 Jun 18 06:48


ewallet_2013061806481418_for_12c.p12
-rw-r--r-- 1 oracle oinstall 4112 Jun 18 06:48
ewallet_2013061806485974.p12
-rw-r--r-- 1 oracle oinstall 6312 Jun 18 06:50
ewallet_2013061806500437.p12
-rw-r--r-- 1 oracle oinstall 6312 Jun 18 06:50 ewallet.p12

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 4
Notice that both the current and the backup files have the same size.
h. View the keystore file location from the view.
SQL> SELECT WRL_PARAMETER, STATUS, WALLET_TYPE, CON_ID
FROM V$ENCRYPTION_WALLET;
2
WRL_PARAMETER STATUS WALLET_TYPE CON_ID
--------------------------------- ------ -------------- ------
/u01/app/oracle/admin/orcl/wallet OPEN PASSWORD 0

SQL> EXIT
$
2. Prepare the cdb1 multitenant container database for encryption.
a. Create a directory for the unique Oracle password-based keystore for the CDB at
$ORACLE_BASE/admin/cdb1/wallet if it does not exist.
$ mkdir $ORACLE_BASE/admin/cdb1/wallet
$
b. Connect to the cdb1 instance as a user who has been granted the SYSKM privilege to
create the password-based keystore.
$ . oraenv
ORACLE_SID = [orcl] ? cdb1
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as syskm

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options

SQL>
c. Display the default keystore location.
SQL> SELECT WRL_PARAMETER, STATUS, WALLET_TYPE
FROM V$ENCRYPTION_WALLET;
2

WRL_PARAMETER STATUS WALLET_TYPE


--------------------------------- -------------- --------------
/u01/app/oracle/admin/cdb1/wallet NOT_AVAILABLE UNKNOWN

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 5
d. Create the keystore.
SQL> ADMINISTER KEY MANAGEMENT CREATE KEYSTORE
'/u01/app/oracle/admin/cdb1/wallet'
IDENTIFIED BY secret_cdb1;
2 3
keystore altered.

SQL> !ls -l /u01/app/oracle/admin/cdb1/wallet

-rw-r--r-- 1 oracle oinstall 2400 Jun 18 06:52 ewallet.p12

SQL> SELECT WRL_PARAMETER, STATUS, WALLET_TYPE, CON_ID


FROM V$ENCRYPTION_WALLET;
2
WRL_PARAMETER STATUS WALLET_TYPE
---------------------------------- ------------- -----------
CON_ID
----------
/u01/app/oracle/admin/cdb1/wallet CLOSED UNKNOWN
0

SQL>
e. Open the keystore for all PDBS.
SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE OPEN
IDENTIFIED BY secret_cdb1
CONTAINER = ALL;
2 3
keystore altered.

SQL>
SQL> SELECT WRL_PARAMETER, STATUS, WALLET_TYPE, CON_ID
FROM V$ENCRYPTION_WALLET;
2

WRL_PARAMETER STATUS WALLET_TYPE


---------------------------------- ------------------ ----------
-
CON_ID
----------
/u01/app/oracle/admin/cdb1/wallet OPEN_NO_MASTER_KEY PASSWORD
0

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 6
Notice that the status explains that the master key has not yet been generated in the
keystore.
f. The application data are stored in the PDBs. Generate a master key for each of the
PDBs in cdb1.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> SELECT name FROM v$pdbs;

NAME
------------------------------
PDB$SEED
PDB1_2
PDB1_1

SQL>
g. Generate a master key for pdb1_1.
1) Grant the SYSKM privilege to the keystore manager of each PDB.
SQL> ALTER USER syskm IDENTIFIED BY oracle_4U ACCOUNT UNLOCK
CONTAINER=ALL;

User altered.

SQL> CREATE USER c##km IDENTIFIED BY oracle_4U;

User created.

SQL> GRANT syskm TO c##km CONTAINER=ALL;

Grant succeeded.

SQL>
2) Connect to the pdb1_1 to generate the master key.
SQL> CONNECT c##km@pdb1_1 AS SYSKM
Enter password: ******
Connected.
SQL>
3) Generate the master key.
SQL> ADMINISTER KEY MANAGEMENT SET KEY
IDENTIFIED BY secret_cdb1
WITH BACKUP
CONTAINER=CURRENT;
2 3 4 ADMINISTER KEY MANAGEMENT SET KEY
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 7
*
ERROR at line 1:
ORA-46671: master key not set in root container

SQL> CONNECT / AS SYSKM


Connected.
SQL> ADMINISTER KEY MANAGEMENT SET KEY
IDENTIFIED BY secret_cdb1
WITH BACKUP;
2 3 ADMINISTER KEY MANAGEMENT SET KEY
*
ERROR at line 1:
ORA-28417: password-based keystore is not open

SQL>
Notice that the keystore was automatically closed.
SQL> SELECT WRL_PARAMETER, STATUS, WALLET_TYPE, CON_ID
FROM V$ENCRYPTION_WALLET;
2
WRL_PARAMETER STATUS WALLET_TYPE CON_ID
---------------------------------- ------ ------------ ---------
-
/u01/app/oracle/admin/cdb1/wallet CLOSED UNKNOWN 0

SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE OPEN


IDENTIFIED BY secret_cdb1
CONTAINER = ALL;
2 3
keystore altered.

SQL>
4) Generate the master key in the root container.
SQL> ADMINISTER KEY MANAGEMENT SET KEY
IDENTIFIED BY secret_cdb1
WITH BACKUP
CONTAINER = ALL;
2 3 4
keystore altered.

SQL> SELECT WRL_PARAMETER, STATUS, WALLET_TYPE, CON_ID


FROM V$ENCRYPTION_WALLET;
2
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 8
WRL_PARAMETER STATUS WALLET_TYPE CON_ID
---------------------------------- ------ ------------ ---------
-
/u01/app/oracle/admin/cdb1/wallet OPEN PASSWORD 0

SQL>
SQL> SELECT KEY_ID, KEYSTORE_TYPE, KEY_USE,
ACTIVATING_DBNAME, ACTIVATING_PDBNAME
FROM V$ENCRYPTION_KEYS;
2 3

AYNanq9p0U8Qv2c7YAeWvUsAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
SOFTWARE KEYSTORE TDE IN PDB cdb1
PDB1_1

AW8zkuYlvE+qv8UXJmOHdAsAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
SOFTWARE KEYSTORE TDE IN PDB cdb1
CDB$ROOT

AVoXTNMhDE8lv3t9ZN08AToAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
SOFTWARE KEYSTORE TDE IN PDB cdb1
PDB1_2

SQL>
Notice that the command generated one master key for each container including the root
container.
5) Generate a master key for pdb1_1.
SQL> CONNECT c##km@pdb1_1 AS SYSKM
Enter password: ******
Connected.
SQL>
SQL> ADMINISTER KEY MANAGEMENT SET KEY
IDENTIFIED BY secret_cdb1
WITH BACKUP
CONTAINER = CURRENT;
2 3 4
keystore altered.

SQL> SELECT KEY_ID, KEYSTORE_TYPE, KEY_USE,


ACTIVATING_DBNAME, ACTIVATING_PDBNAME
FROM V$ENCRYPTION_KEYS;
2 3

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 9
KEY_ID
----------------------------------------------------------------
-
KEYSTORE_TYPE KEY_USE ACTIVATING_DBNAME
----------------- ---------- ------------------------------
ACTIVATING_PDBNAME
------------------------------
AYNanq9p0U8Qv2c7YAeWvUsAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
SOFTWARE KEYSTORE TDE IN PDB cdb1
PDB1_1

AYyDyiRzQE//v2yzAYkINbAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
SOFTWARE KEYSTORE TDE IN PDB cdb1
PDB1_1

SQL>
Notice that the command generated another master key for the pdb1_1 container.
h. Generate a master key for pdb1_2.
SQL> CONNECT c##km@pdb1_2 AS SYSKM
Enter password: ******
Connected.
SQL> ADMINISTER KEY MANAGEMENT SET KEY
IDENTIFIED BY secret_cdb1
WITH BACKUP
CONTAINER = CURRENT;
2 3 4
keystore altered.

SQL> SELECT KEY_ID, KEYSTORE_TYPE, KEY_USE,


ACTIVATING_DBNAME, ACTIVATING_PDBNAME
FROM V$ENCRYPTION_KEYS;
2 3
KEY_ID
----------------------------------------------------------------
--------------
KEYSTORE_TYPE KEY_USE ACTIVATING_DBNAME
----------------- ---------- ------------------------------
ACTIVATING_PDBNAME
------------------------------
AU0iDQnVHk+zv2qpJbKlUvEAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
SOFTWARE KEYSTORE TDE IN PDB cdb1
PDB1_2

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 10
AVoXTNMhDE8lv3t9ZN08AToAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
SOFTWARE KEYSTORE TDE IN PDB cdb1
PDB1_2

SQL> EXIT
$
Notice that the command generated another master key for the pdb1_2 container.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 11
Practice 19-2: Implementing Table Column Encryption
Overview
In this practice, you will create a table that contains an encrypted column. You view the data in
the format that is stored on disk before and after encryption. You create an index on the
encrypted column. You demonstrate that range scans are possible. You grant access to the
column for a particular user, and you demonstrate that any user with proper privileges can view
the unencrypted data.

Tasks
1. When Transparent Data Encryption (TDE) is applied to columns in the database, what does
the application developer do to be sure that the application can handle the encrypted
columns?
a. Increase the size of the fields and the variables holding the values from the encrypted
columns.
b. Add error handling for column overruns.
c. Add error handling for missing keys.
d. Nothing
Answer: d. Nothing
2. Create a table in the OE schema that holds sensitive customer payment information. Use
the create_tables.sql script in the /home/oracle/labs/ENC directory to create and
populate a table named OE.CUST_PAYMENT_INFO.
$ cd ~/labs/ENC
$ . oraenv
ORACLE_SID = [cdb1] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus /nolog @create_tables.sql
SQL> connect oe/oracle_4U@localhost:1521/orcl
Connected.

SQL> drop table cust_payment_info;


drop table cust_payment_info
*
ERROR at line 1:
ORA-00942: table or view does not exist

SQL> create table cust_payment_info


2 (first_name varchar2(11),
3 last_name varchar2(10),
4 order_number number(5),
5 credit_card_number varchar2(20),
6 active_card varchar2(3));

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 12
Table created.

SQL>
SQL> insert into cust_payment_info values
2 ('Jon', 'Oldfield', 10001, 5105105105105100,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Chris', 'White', 10002, 6011111111111117,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Alan', 'Squire', 10003, 378282246310005,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Mike', 'Anderson', 10004, 6011000000000004,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Annie', 'Schmidt', 10005, 4111111111111111,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Elliott', 'Meyer', 10006, 4222222222222,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Celine', 'Smith', 10007, 343434343434343,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Steve', 'Haslam', 10008, 6011000990139424,'YES');

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 13
1 row created.

SQL> insert into cust_payment_info values


2 ('Albert', 'Einstein', 10009, 5111111111111118,'YES');

1 row created.

SQL>
SQL> create index cust_payment_info_idx on
2 cust_payment_info (credit_card_number);

Index created.

SQL>
3. Select the data from the OE.CUST_PAYMENT_INFO table.
SQL> column FIRST_NAME format A8 head 'First'
SQL> column ORDER_NUMBER format 999999 Head "Order#"
SQL> select * from oe.cust_payment_info;

First LAST_NAME Order# CREDIT_CARD_NUMBER ACT


--------- ---------- ------- -------------------- ---
Jon Oldfield 10001 5105105105105100 YES
Chris White 10002 6011111111111117 YES
Alan Squire 10003 378282246310005 YES
Mike Anderson 10004 6011000000000004 YES
Annie Schmidt 10005 4111111111111111 YES
Elliott Meyer 10006 4222222222222 YES
Celine Smith 10007 343434343434343 YES
Steve Haslam 10008 6011000990139424 YES
Albert Einstein 10009 5111111111111118 YES

9 rows selected.

SQL>
4. Dump the data blocks to see the data as it is stored in the file. Do this as the SYS user.
a. Find the database address of the OE.CUST_PAYMENT_INFO table. The
$HOME/labs/ENC/dump_blocks.sql script executes the following:
SELECT file_id FROM dba_data_files
WHERE RELATIVE_FNO =
(SELECT distinct dbms_rowid.ROWID_RELATIVE_FNO(rowid) FILE#
FROM oe.cust_payment_info);

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 14
SELECT distinct dbms_rowid.rowid_block_number(rowid) BLOCK#
FROM oe.cust_payment_info;
Execute the script and determine file# and block# for your table (these numbers vary).
SQL> @dump_blocks.sql
SQL> connect sys/oracle_4U@localhost:1521/orcl as sysdba
Connected.
SQL>
SQL> SELECT file_id FROM dba_data_files
2 WHERE RELATIVE_FNO =
3 (SELECT distinct dbms_rowid.ROWID_RELATIVE_FNO(rowid)
FILE#
4 FROM oe.cust_payment_info);

FILE_ID
----------
2

SQL>
SQL> SELECT distinct dbms_rowid.rowid_block_number(rowid) BLOCK#
2 FROM oe.cust_payment_info;

BLOCK#
----------
41389

SQL>
b. Set the TRACEFILE_IDENTIFIER initialization parameter so that the trace file can be
found more easily by executing the following command:
ALTER SESSION SET TRACEFILE_IDENTIFIER=dp_block;
SQL> ALTER SESSION SET TRACEFILE_IDENTIFIER=dp_block;

Session altered.

SQL>
c. Dump the data block to a trace file. Substituting the file# and block# that you
recorded with the previous command, execute the following command:
ALTER SYSTEM DUMP DATAFILE <file#> BLOCK <block#>;
SQL> ALTER SYSTEM DUMP DATAFILE 2 BLOCK 41389;

System altered.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 15
d. Find the trace file. In this listing, the block dump is in the
orcl_ora_<pid>_DP_BLOCK.trc file.
SQL> show parameter user_dump_dest

NAME TYPE VALUE


------------------- ----------- ------------------------------
user_dump_dest string /u01/app/oracle/diag/rdbms/orc
l/orcl/trace

SQL> EXIT
$
$ cd /u01/app/oracle/diag/rdbms/orcl/orcl/trace
$ ls *DP_BLOCK*
orcl_ora_625_DP_BLOCK.trc orcl_ora_625_DP_BLOCK.trm
$
e. View the dump file. The less utility enables you to scroll up and down the file to find
data of interest. Note that the credit card numbers are clearly visible.
$ less orcl_ora_625_DP_BLOCK.trc
/* Rows deleted */

2C70FE70 02FFFF80 C30407C1 03252C02 024A09C2 [.........,%...J.]
2C70FE80 800102C1 0605012C 65626C41 45087472 [....,...Albert.E]
2C70FE90 74736E69 046E6965 0A0102C3 3031330F [instein......511]
2C70FEA0 33343536 31343530 39383332 53455903
[1111111111118.YES]
2C70FEB0 0505012C 76657453 61480665 6D616C73 [,...Steve.Haslam]
2C70FEC0 0102C304 34330F09 35373930 33303039
[......60110009901]
2C70FED0 35383637 45590338 05012C53 6C654306 [39424.YES,...Cel]
2C70FEE0 05656E69 74696D53 02C30468 340D0801
[ine.Smith......34]
2C70FEF0 38363137 33353839 36333033 53455903
[3434343434343.YES]
2C70FF00 0705012C 696C6C45 0574746F 6579654D [,...Elliott.Meye]
2C70FF10 02C30472 330F0701 36333437 39393536 [r...... 4222222]
2C70FF20 38313137 59033032 012C5345 6E410505 [222222.YES,...An]
2C70FF30 0765696E 6D686353 04746469 060102C3 [nie.Schmidt.....]
2C70FF40 35353410 38383936 32383037 30393633 [.411111111111111]
2C70FF50 45590332 05012C53 6B694D04 6E410865 [1.YES,...Mike.An]
2C70FF60 73726564 C3046E6F 10050102 39323934 [derson......6011]
2C70FF70 35393838 35333637 30303437 53455903 [000000000004.YES]
2C70FF80 0405012C 6E616C41 75715306 04657269 [,...Alan.Squire.]
2C70FF90 040102C3 39353510 38363935 37333439 [.....3782822463]

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 16
2C70FFA0 32393735 45590330 05012C53 72684305 [10005.YES,...Chr]
2C70FFB0 57057369 65746968 0102C304 31351003 [is.White......60]
2C70FFC0 35333232 36343038 35323830 59033036 [11111111111117.Y]
2C70FFD0 012C5345 6F4A0305 6C4F086E 65696664 [ES,...Jon.Oldfie]
2C70FFE0 C304646C 10020102 36343435 37393539 [ld......51051051]
2C70FFF0 31383830 35383932 53455903 49B2060B [05105100.YES...I]
Block header dump: 0x01000198

q – to exit less

$
5. Alter the table to encrypt the credit card numbers with NO SALT.
$ sqlplus oe

SQL*Plus: Release 12.1.0.1.0 Production on Wed Aug 7 03:06:00


2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.

Enter password: ******


Connected.
SQL> desc cust_payment_info
Name Null? Type
----------------------- -------- ------------------------
FIRST_NAME VARCHAR2(11)
LAST_NAME VARCHAR2(10)
ORDER_NUMBER NUMBER(5)
CREDIT_CARD_NUMBER VARCHAR2(20)
ACTIVE_CARD VARCHAR2(3)

SQL> ALTER TABLE cust_payment_info


MODIFY (CREDIT_CARD_NUMBER encrypt no salt);
2
Table altered.

SQL>
6. Dump the data block and find the trace file. Change TRACEFILE_IDENTIFIER to DUMP2.
a. Use the $HOME/labs/ENC/dump_blocks.sql script to find the data block address.
SQL> @$HOME/labs/ENC/dump_blocks.sql
SQL> connect / as sysdba
Connected.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 17
SQL>
SQL> SELECT file_id FROM dba_data_files
2 WHERE RELATIVE_FNO =
3 (SELECT distinct dbms_rowid.ROWID_RELATIVE_FNO(rowid)
FILE#
4 FROM oe.cust_payment_info);

FILE_ID
----------
2

SQL>
SQL> SELECT distinct dbms_rowid.rowid_block_number(rowid) BLOCK#
2 FROM oe.cust_payment_info;

BLOCK#
----------
41389

SQL>
7. Set the TRACEFILE_IDENTIFIER initialization parameter so that the trace file can be
found more easily.
a. Use ALTER SESSION SET TRACEFILE_IDENTIFIER=DUMP2;
SQL> ALTER SESSION SET TRACEFILE_IDENTIFIER=DUMP2;

Session altered.

SQL>
b. As the SYS user, dump the data block to a trace file. Substituting the file# and
block# that you recorded with the previous command, execute the following
command:
ALTER SYSTEM DUMP DATAFILE <file#> BLOCK <block#>;
SQL> ALTER SYSTEM DUMP DATAFILE 2 BLOCK 41389;

System altered.

SQL> EXIT
$
c. Find the trace file.
$ ls *DUMP*.trc
orcl_ora_5358_DUMP2.trc
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 18
d. View the trace file. Note that the unencrypted data remains.
$ less orcl_ora_5358_DUMP2.trc

7AA470 39141603 0301002C 053202C1 6E780700 [...9,.....2...xn]
7AA480 05160302 0605012C 65626C41 45087472 [....,...Albert.E]
7AA490 74736E69 046E6965 0A0102C3 3031330F [instein...... 511]
7AA4A0 33343536 31343530 39383332 53455903 [1111111111118.YES]
7AA4B0 0505012C 76657453 61480665 6D616C73 [,...Steve.Haslam]
7AA4C0 0102C304 34330F09 35373930 33303039 [......60110009901]
7AA4D0 35383637 45590338 05012C53 6C654306 [39424.YES,...Cel]
7AA4E0 05656E69 74696D53 02C30468 340D0801 [ine.Smith......34]
7AA4F0 38363137 33353839 36333033 53455903 [3434343434343.YES]
7AA500 0705012C 696C6C45 0574746F 6579654D [,...Elliott.Meye]
7AA510 02C30472 330F0701 36333437 39393536 [r...... 4222222]
7AA520 38313137 59033032 012C5345 6E410505 [222222.YES,...An]
7AA530 0765696E 6D686353 04746469 060102C3 [nie.Schmidt.....]
7AA540 35353410 38383936 32383037 30393633 [.411111111111111]
7AA550 45590332 05012C53 6B694D04 6E410865 [1.YES,...Mike.An]
7AA560 73726564 C3046E6F 10050102 39323934 [derson...... 6011]
7AA570 35393838 35333637 30303437 53455903 [000000000004.YES]
7AA580 0405012C 6E616C41 75715306 04657269 [,...Alan.Squire.]
7AA590 040102C3 39353510 38363935 37333439 [.....3782822463]
7AA5A0 32393735 45590330 05012C53 72684305 [10005.YES,...Chr]
7AA5B0 57057369 65746968 0102C304 31351003 [is.White......60]
7AA5C0 35333232 36343038 35323830 59033036 [11111111111117.Y]
7AA5D0 012C5345 6F4A0305 6C4F086E 65696664 [ES,...Jon.Oldfie]
7AA5E0 C304646C 10020102 36343435 37393539 [ld...... 51051051]
7AA5F0 31383830 35383932 53455903 50870601 [05105100.YES...P]

q /* to exit less */
$
8. Move the OE.CUST_PAYMENT_INFO table. This causes the valid data to be written to new
blocks. It also makes the index unusable, so you must rebuild the index.
$ sqlplus oe
Enter password: ******
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> alter table oe.cust_payment_info move;

Table altered.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 19
SQL> select index_name, table_name, status
from user_indexes
where table_name ='CUST_PAYMENT_INFO';
2 3
INDEX_NAME TABLE_NAME STATUS
---------------------- ----------------------- --------
CUST_PAYMENT_INFO_IDX CUST_PAYMENT_INFO UNUSABLE

SQL> ALTER INDEX CUST_PAYMENT_INFO_IDX REBUILD;

Index altered.

SQL> select index_name, table_name, status


from user_indexes
where table_name = 'CUST_PAYMENT_INFO';
2 3
INDEX_NAME TABLE_NAME STATUS
--------------------- -------------------------- --------
CUST_PAYMENT_INFO_IDX CUST_PAYMENT_INFO VALID

SQL>
9. Find the new block location. Dump the block and view it. Are the credit card numbers
visible?
SQL> @$HOME/labs/ENC/dump_blocks.sql
SQL> connect sys/oracle_4U@localhost:1521/orcl as sysdba
Connected.
SQL>
SQL> SELECT file_id FROM dba_data_files
2 WHERE RELATIVE_FNO =
3 (SELECT distinct dbms_rowid.ROWID_RELATIVE_FNO(rowid)
FILE#
4 FROM oe.cust_payment_info);

FILE_ID
----------
2

SQL>
SQL> SELECT distinct dbms_rowid.rowid_block_number(rowid) BLOCK#
2 FROM oe.cust_payment_info;

BLOCK#
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 20
----------
41403

SQL> ALTER SESSION SET TRACEFILE_IDENTIFIER=DUMP3;

Session altered.

SQL> ALTER SYSTEM DUMP DATAFILE 2 BLOCK 41403;

System altered.

SQL> EXIT
$
$ ls *DUMP3*
orcl_ora_6495_DUMP3.trc orcl_ora_6495_DUMP3.trm
$ less orcl_ora_6495_DUMP3.trc

B7FBE370 00000000 00000000 002C0000 6C410605 [..........,...Al]
B7FBE380 74726562 6E694508 69657473 02C3046E [bert.Einstein...]
B7FBE390 EF240A01 1D1CFDC1 EFDFBC07 DCC9D8CC [..$.............]
B7FBE3A0 9740148D 6FD843CE 22084248 2560D017 [..@..C.oHB."..`%]
B7FBE3B0 43DB5AFC 0308C8D3 2C534559 53050500 [.Z.C....YES,...S]
B7FBE3C0 65766574 73614806 046D616C 090102C3 [teve.Haslam.....]
B7FBE3D0 A76A7B24 C433FDA7 E55A9A17 435784E7 [${j...3...Z...WC]
B7FBE3E0 534B9E14 3C680588 0F0E50A7 06CDABCC [..KS..h<.P......]
B7FBE3F0 3AF0D07A 45590382 05002C53 6C654306 [z..:..YES,...Cel]
B7FBE400 05656E69 74696D53 02C30468 4E240801 [ine.Smith.....$N]
B7FBE410 BDA6E5BC 908D0883 54413436 0716917E [........64AT~...]
B7FBE420 E858F608 85B70F84 C1610063 1564A265 [..X.....c.a.e.d.]
B7FBE430 0331EC2B 2C534559 45070500 6F696C6C [+.1.YES,...Ellio]
B7FBE440 4D057474 72657965 0102C304 09612407 [tt.Meyer.....$a.]
B7FBE450 B6017970 D4353AC8 2F8FD3B8 BB2568CA [py...:5..../.h%.]
B7FBE460 D85FFBEB B91222F7 5FB559C2 D46D90D9 [.._.."...Y._..m.]
B7FBE470 59031345 002C5345 6E410505 0765696E [E..YES,...Annie.]
B7FBE480 6D686353 04746469 060102C3 16F11234 [Schmidt.....4...]
B7FBE490 04D42CDA 9CFD4B27 417864FF 76918F95 [.,..'K...dxA...v]
B7FBE4A0 6807D5C6 AE87B5A4 C24EEFB6 15BA3F62 [...h......N.b?..]
B7FBE4B0 45490484 3D0C1844 E4BAA4CA FDB117D7 [..IED..=........]
B7FBE4C0 4559039F 05002C53 6B694D04 6E410865 [..YES,...Mike.An]
B7FBE4D0 73726564 C3046E6F 34050102 C48C24C3 [derson.....4.$..]
B7FBE4E0 5CA4D6BB 50C0BFF8 4092C385 E4F9A9F4 [...\...P...@....]
B7FBE4F0 0FE6A0E4 969ACC27 88F92DEC E6180192 [....'....-......]

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 21
B7FBE500 AAA8517D FC23C153 01A08F80 22EC508C [}Q..S.#......P."]
B7FBE510 53455903 0405002C 6E616C41 75715306 [.YES,...Alan.Squ]
B7FBE520 04657269 040102C3 AF0E2734 885468AF [ire.....4'...hT.]
B7FBE530 73D937F7 6D1925EF 2682FC5F A711AC6B [.7.s.%.m_..&k...]
B7FBE540 DD61BDC0 9922B23E 3EDF5EA4 CBEE20FA [..a.>."..^.>. ..]
B7FBE550 C2B7268D CB7EEC1A 14F098B8 45590312 [.&....~.......YE]
B7FBE560 05002C53 72684305 57057369 65746968 [S,...Chris.White]
B7FBE570 0102C304 A1C73403 0E3E6A61 12C64922 [.....4..aj>."I..]
B7FBE580 D0AE9D2C B4235D85 02AC9472 B18F63B3 [,....]#.r....c..]
B7FBE590 B0BD718C 901407AA EE961735 DBCDB4CF [.q......5.......]
B7FBE5A0 BE2E6E65 DC081E9C 5903F5A7 002C5345 [en.........YES,.]
B7FBE5B0 6F4A0305 6C4F086E 65696664 C304646C [..Jon.Oldfield..]
B7FBE5C0 34020102 4DBECDB5 D60B61DE 29A62975 [...4...M.a..u).)]
B7FBE5D0 F5CCBA5F 685E08DF C004E0E5 A2D8BC1E [_.....^h........]
B7FBE5E0 5FEF3520 518764B7 F34C77C9 BFC861DE [ 5._.d.Q.wL..a..]
B7FBE5F0 E56F540C 48B94BF9 53455903 816F0602 [.To..K.H.YES..o.]
Block header dump: 0x010001a4

q /* to exit less */
$
10. Create the LSMITH, LDORAN, and JKING users by using the
/home/oracle/labs/ENC/create_users.sql script. Grant each of them the CREATE
SESSION privilege and grant DBA to LSMITH. Only SYS and SYSTEM have the privileges
required to grant the DBA role.
$ sqlplus /nolog @$HOME/labs/ENC/create_users.sql

SQL*Plus: Release 12.1.0.1.0 Production on Thu May 30 01:39:57


2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.

SQL> connect system/oracle_4U@localhost:1521/orcl


Connected.
SQL>
SQL> grant create session to JKING identified by oracle_4U;

Grant succeeded.

SQL> grant create session, DBA to LSMITH identified by


oracle_4U;

Grant succeeded.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 22
SQL> grant create session to LDORAN identified by oracle_4U;

Grant succeeded.

SQL>
11. Grant privileges to the users on the OE.CUST_PAYMENT_INFO table. Grant the SELECT
privilege to LDORAN and JKING. Grant SELECT and UPDATE privileges to LSMITH. Use the
privs.sql script.
SQL> @$HOME/labs/ENC/privs
SQL> CONNECT OE/oracle_4U@localhost:1521/orcl
Connected.
SQL>
SQL> grant select on oe.CUST_PAYMENT_INFO to LDORAN;

Grant succeeded.

SQL> grant select, update on oe.CUST_PAYMENT_INFO to LSMITH;

Grant succeeded.

SQL> grant select on oe.CUST_PAYMENT_INFO to JKING;

Grant succeeded.

SQL>
12. Is an index range scan possible on an index over an encrypted column? As the LSMITH
user, update a record based on the credit card number. View the explain plan for the
update statement. Use the scan.sql script.
The lab script uses the WHERE clause, where
CREDIT_CARD_NUMBER='6011111111111117' to select the row to update. A range
scan of the index is performed. The credit card number is stored as an encrypted value
in both the column and the index; the literal value is encrypted before it is compared.
The value is found in the index by using a range scan. The range scan is possible only
when an equality predicate is used.
SQL> @$HOME/labs/ENC/scan.sql
SQL> SET ECHO ON
SQL> conn LSMITH/oracle_4U@localhost:1521/orcl
Connected.
SQL> update oe.CUST_PAYMENT_INFO set ACTIVE_CARD='NO'
2 where CREDIT_CARD_NUMBER='6011111111111117';

1 row updated.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 23
SQL>
SQL> PAUSE 'HIT Return to show execution plan'
'HIT Return to show execution plan'

SQL> Set pagesize 100


SQL> Set linesize 70
SQL> select * from table (dbms_xplan.display_cursor);

PLAN_TABLE_OUTPUT
----------------------------------------------------------------
-
SQL_ID 19g90uxc66plt, child number 0
-------------------------------------
update oe.CUST_PAYMENT_INFO set ACTIVE_CARD='NO' where
CREDIT_CARD_NUMBER='6011111111111117'

Plan hash value: 2780468320


----------------------------------------------------------------
-
| Id | Operation | Name | Rows | Bytes | Co
st (%CPU)| Time |
----------------------------------------------------------------
-
| 0 | UPDATE STATEMENT | | | |
2 (100)| |
| 1 | UPDATE | CUST_PAYMENT_INFO | | |
| |
|* 2 | INDEX RANGE SCAN| CUST_PAYMENT_INFO_IDX | 1 | 49
|
1 (0)| 00:00:01 |

Predicate Information (identified by operation id):


---------------------------------------------------

2 - access("CREDIT_CARD_NUMBER"='6011111111111117')

Note
-----
- dynamic statistics used: dynamic sampling (level=2)

24 rows selected.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 24
SQL> EXIT;
$
13. Transparent Data Encryption is not visible to the end user. No changes are required to the
application or SQL syntax. Any user that has been granted privileges to access the table or
column can view the data in its unencrypted form. As the LDORAN user, select the
LAST_NAME and CREDIT_CARD_NUMBER columns from the OE.CUST_PAYMENT_INFO
table.
$ sqlplus ldoran@orcl
Enter password : ******
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> select last_name, credit_card_number


from oe.cust_payment_info;
2
LAST_NAME CREDIT_CARD_NUMBER
---------- --------------------
Oldfield 5105105105105100
White 6011111111111117
Squire 378282246310005
Anderson 6011000000000004
Schmidt 4111111111111111
Meyer 4222222222222
Smith 343434343434343
Haslam 6011000990139424
Einstein 5111111111111118

9 rows selected.

SQL>
14. What should you do when the keystore is not available? Close the keystore.
SQL> CONNECT / as syskm
Connected.

SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE CLOSE


IDENTIFIED BY secret;
2
keystore altered.

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 25
15. Connect as the LSMITH user with the password oracle_4U. Attempt to select all columns
from the OE.CUST_PAYMENT_INFO table. Then, attempt to select only the LAST_NAME
column.
SQL> connect lsmith@orcl
Enter password: ******
Connected.
SQL> select * from oe.cust_payment_info;
select * from oe.cust_payment_info
*
ERROR at line 1:
ORA-28365: wallet is not open

SQL> select last_name from oe.cust_payment_info;

LAST_NAME
----------
Oldfield
White
Squire
Anderson
Schmidt
Meyer
Smith
Haslam
Einstein

9 rows selected.

SQL>
16. As the user who has been granted the SYSKM privilege, open the keystore.
SQL> connect / as syskm
Connected.
SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE OPEN
IDENTIFIED BY secret;
2
keystore altered.

SQL>
17. Connect again as the LSMITH user with the password oracle_4U. Attempt to select all the
columns from the OE.CUST_PAYMENT_INFO table.
SQL> connect lsmith@orcl
Enter password: ******

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 26
Connected.
SQL> select * from oe.cust_payment_info;

FIRST LAST_NAME ORDER_NUMBER CREDIT_CARD_NUMBER ACT


--------- ---------- ------------ -------------------- ---
Jon Oldfield 10001 5105105105105100 YES
Chris White 10002 6011111111111117 NO
Alan Squire 10003 378282246310005 YES
Mike Anderson 10004 6011000000000004 YES
Annie Schmidt 10005 4111111111111111 YES
Elliott Meyer 10006 4222222222222 YES
Celine Smith 10007 343434343434343 YES
Steve Haslam 10008 6011000990139424 YES
Albert Einstein 10009 5111111111111118 YES

9 rows selected.

SQL>
18. Drop the OE.CUST_PAYMENT_INFO table and re-create it with SALT. Then, create an index
on the encrypted column CREDIT_CARD_NUMBER. Use the salt.sql script. What
happens when the create index command is issued?
.Execute the salt.sql script. An index cannot be created on a column with SALT.
SQL> @$HOME/labs/ENC/salt.sql
SQL> connect oe/oracle_4U@localhost:1521/orcl
Connected.
SQL> SQL> drop table cust_payment_info;

Table dropped.

SQL> create table cust_payment_info


2 (first_name varchar2(11),
3 last_name varchar2(10),
4 order_number number(5),
5 credit_card_number varchar2(20) encrypt SALT,
6 active_card varchar2(3));

Table created.

SQL>
SQL> insert into cust_payment_info values
2 ('Jon', 'Oldfield', 10001, 5446959708812985,'YES');

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 27
1 row created.

SQL> insert into cust_payment_info values


2 ('Chris', 'White', 10002, 5122358046082560,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Alan', 'Squire', 10003, 5595968943757920,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Mike', 'Anderson', 10004, 4929889576357400,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Annie', 'Schmidt', 10005, 4556988708236902,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Elliott', 'Meyer', 10006, 374366599711820,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Celine', 'Smith', 10007, 4716898533036,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Steve', 'Haslam', 10008, 340975900376858,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Albert', 'Einstein', 10009, 310654305412389,'YES');

1 row created.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 28
SQL> create index cust_payment_info_idx
2 on cust_payment_info (credit_card_number);
on cust_payment_info (credit_card_number)
*
ERROR at line 2:
ORA-28338: Column(s) cannot be both indexed and encrypted with
salt

SQL> exit
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 29
Practice 19-3: Implementing Tablespace Encryption
Overview
In this practice, you create an encrypted tablespace and move several tables and the
associated indexes to the encrypted tablespace.

Tasks
1. Create an encrypted tablespace named ENCTBS, with a file enctbs01.dbf, in the same
directory with the rest of the data files:
/u01/app/oracle/oradata/orcl/enctbs01.dbf. Use the tablespace.sql script
to create the encrypted tablespace.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> @$HOME/labs/ENC/tablespace.sql
SQL> SET ECHO ON
SQL>
SQL> DROP TABLESPACE "ENCTBS"
2 INCLUDING CONTENTS AND DATAFILES
3 /
DROP TABLESPACE "ENCTBS"
*
ERROR at line 1:
ORA-00959: tablespace 'ENCTBS' does not exist

SQL>
SQL> CREATE TABLESPACE "ENCTBS"
2 DATAFILE '/u01/app/oracle/oradata/orcl/enctbs01.dbf' SIZE
100M
3 EXTENT MANAGEMENT LOCAL
4 SEGMENT SPACE MANAGEMENT AUTO
5 DEFAULT STORAGE (ENCRYPT)
6 ENCRYPTION USING 'AES192'
7 /

Tablespace created.
SQL>
2. Move the HR schema to ENCTBS by using Enterprise Manager Cloud Control.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 30
Step Page Action
a. Browser Enter the following URL:
https://localhost:7802/em
Log in as sysman with password Oracle123
b. Enterprise Summary Click Targets, then click Databases. Select orcl and
click.
b. orcl Click the Schema tab, then click Database Objects,
then click Reorganize Objects.
c. Database Login Click Login.
d. Reorganize Objects: Select Schema Objects.
Type Click Next.
e. Reorganize Objects: Click Add.
Objects
f. Objects: Add Enter HR as the schema.
Click Search.
g. Objects: Add Click Select All.
Click Next 10.
Click Select All.
Click Next 3.
Click Select All.
Click OK.
h. Reorganize Objects: You should see 23 objects (only 10 will be displayed at a
Objects. time).
Click Set Attributes By Type.
i. Objects: Set In the Destination Tablespace for Tables section, select
Attributes By Type “Relocate objects to another tablespace” and enter
ENCTBS.
In the Destination Tablespace for Indexes section, select
“Relocate objects to another tablespace” and enter
ENCTBS.
Click OK.
j. Reorganize Objects: Click Next.
Objects
k. Reorganize Objects: Accept the defaults.
Options Click Next.
l Reorganize Objects: Check the report message.
Impact Report. Click Next.
m Reorganize Objects: Click Named for the host credentials: CREDOS appears.
Schedule Click Next.
n. Reorganize Objects: Click Submit job.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 31
Review
o. Confirmation Click REORGANIZE_*.
p. Job Run: Click the Refresh button of the browser periodically until
REORGANIZE_* all the job steps show a status of Succeeded.
Job Run: Click Log Report to read all commands executed by the
REORGANIZE_* job. Click Done.
q. On the Job Run:… Click Logout.
page Close the browser.
3. Connect as HR, and describe and view the EMPLOYEES table. The encrypted tablespace,
including the indexes, is completely transparent to the applications.
SQL> CONNECT hr@orcl
Enter password: ******
Connected.

SQL> desc employees


Name Null? Type
------------------------------------ -------- ----------
EMPLOYEE_ID NUMBER(6)
FIRST_NAME VARCHAR2(20)
LAST_NAME NOT NULL VARCHAR2(25)
EMAIL NOT NULL VARCHAR2(25)
PHONE_NUMBER VARCHAR2(20)
HIRE_DATE NOT NULL DATE
JOB_ID NOT NULL VARCHAR2(10)
SALARY NUMBER(8,2)
COMMISSION_PCT NUMBER(2,2)
MANAGER_ID NUMBER(6)
DEPARTMENT_ID NUMBER(4)

SQL> SELECT * FROM employees


WHERE employee_id = 106;
2
EMPLOYEE_ID FIRST_NAME LAST_NAME
----------- -------------------- -------------------------
EMAIL PHONE_NUMBER HIRE_DATE JOB_ID
SALARY
------------------------- -------------------- --------- -------
--- ----------
COMMISSION_PCT MANAGER_ID DEPARTMENT_ID
-------------- ---------- -------------
106 Valli Pataballa

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 32
VPATABAL 590.423.4560 05-FEB-98 IT_PROG
4800
103 60

SQL> SELECT tablespace_name FROM user_segments


WHERE segment_name='EMPLOYEES';
2
TABLESPACE_NAME
------------------------------
ENCTBS

SQL> EXIT
$
4. Clean up the environment moving the HR schema back into the EXAMPLE tablespace.
Note: This script was generated by the Reorganize Objects wizard in Enterprise Manager
Cloud Control to move back all HR objects to the EXAMPLE tablespace.
$ $HOME/labs/ENC/back_to_example_tbs.sh
sqlplus sys/oracle_4U@localhost:1521/orcl as sysdba
@$HOME/labs/ENC/back_to_example_tbs.sql

SQL*Plus: Release 12.1.0.1.0 Production on Sun Jul 7 15:18:26


2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics
and Real Application Testing options

Disconnected from Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics
and Real Application Testing options
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 33
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 19: Applying Transparent Data Encryption


Chapter 19 - Page 34
Practices for Lesson 20:
Applying File Encryption
Chapter 20

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 1
Practice 20-1: Using RMAN Backup File Encryption
Overview
Recovery Manager (RMAN) backups to disk can be encrypted.

Task
1. Configure Recovery Manager (RMAN) to use transparent encryption for the orcl
database. Set the configuration to be a permanent configuration in the control file.
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ rman target '"john@orcl AS SYSBACKUP"'

target database Password: ******


connected to target database: ORCL (DBID=1345659572)

RMAN> select user from dual;

using target database control file instead of recovery catalog


USER
------------------------------
SYSBACKUP

RMAN> show all;

RMAN configuration parameters for database with db_unique_name


ORCL are:
CONFIGURE RETENTION POLICY TO REDUNDANCY 1; # default
CONFIGURE BACKUP OPTIMIZATION OFF; # default
CONFIGURE DEFAULT DEVICE TYPE TO DISK; # default
CONFIGURE CONTROLFILE AUTOBACKUP OFF; # default
CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO
'%F'; # default
CONFIGURE DEVICE TYPE DISK PARALLELISM 1 BACKUP TYPE TO
BACKUPSET; # default
CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1; #
default
CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1; #
default
CONFIGURE MAXSETSIZE TO UNLIMITED; # default
CONFIGURE ENCRYPTION FOR DATABASE OFF; # default
CONFIGURE ENCRYPTION ALGORITHM 'AES128'; # default
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 2
CONFIGURE COMPRESSION ALGORITHM 'BASIC' AS OF RELEASE 'DEFAULT'
OPTIMIZE FOR LOAD TRUE ; # default
CONFIGURE RMAN OUTPUT TO KEEP FOR 7 DAYS; # default
CONFIGURE ARCHIVELOG DELETION POLICY TO NONE; # default
CONFIGURE SNAPSHOT CONTROLFILE NAME TO
'/u01/app/oracle/product/12.1.0/dbhome_1/dbs/snapcf_orcl.f'; #
default

RMAN> CONFIGURE ENCRYPTION FOR DATABASE ON;

new RMAN configuration parameters:


CONFIGURE ENCRYPTION FOR DATABASE ON;
new RMAN configuration parameters are successfully stored

RMAN> EXIT
$
2. Back up the EXAMPLE tablespace by using transparent encryption.
Note: The database is in NOARCHIVELOG mode, so an online backup is not possible.
a. Create a directory to hold the backups.
$ mkdir $HOME/backup
$
b. Shut down the database and issue startup mount to perform a cold backup.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> SHUTDOWN IMMEDIATE
database closed
database dismounted
Oracle instance shut down
SQL> STARTUP MOUNT
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2290024 bytes
Variable Size 264244888 bytes
Database Buffers 226492416 bytes
Redo Buffers 8032256 bytes
Database mounted.
SQL> EXIT
$
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 3
c. Use the RMAN BACKUP command to make a backup to
/home/oracle/backup/example001.bck. Set tag = transparent so that it can
be specified in the restore command.
$ rman target '"john@orcl AS SYSBACKUP"'

target database Password: ******


connected to target database: ORCL (DBID=1345659572, not open)

RMAN> backup tablespace example


format '/home/oracle/backup/example001.bck'
tag 'transparent';
2> 3>

Starting backup at 18-JUN-13


using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=12 device type=DISK
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00002
name=/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: starting piece 1 at 18-JUN-13
RMAN-00571:
===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS
RMAN-00571:
===========================================================
RMAN-03009: failure of backup command on ORA_DISK_1 channel at
06/18/2013 07:56:40
ORA-19914: unable to encrypt backup
ORA-28365: wallet is not open

RMAN> EXIT
$
d. Open the keystore.
$ sqlplus / as SYSKM

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE OPEN

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 4
IDENTIFIED BY secret;
2
keystore altered.

SQL> EXIT
$
e. Perform the backup
$ rman target '"john@orcl AS SYSBACKUP"'

target database Password: ******


connected to target database: ORCL (DBID=1345659572, not open)

RMAN> backup tablespace example


format '/home/oracle/backup/example001.bck'
tag 'transparent';
2> 3>

Starting backup at 18-JUN-13


using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=11 device type=DISK
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00002
name=/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: starting piece 1 at 18-JUN-13
channel ORA_DISK_1: finished piece 1 at 18-JUN-13
piece handle=/home/oracle/backup/example001.bck tag=TRANSPARENT
comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:15
Finished backup at 18-JUN-13

RMAN>
f. List the encrypted backups.
RMAN> SELECT tag, encrypted FROM v$backup_piece;

TAG ENC
-------------------------------- ---
TRANSPARENT YES

RMAN>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 5
3. Back up the EXAMPLE tablespace using dual-mode encryption to
/home/oracle/backup/example002.bck. Set tag = dual so that it can be specified
in the restore command. To set encryption mode and password, use the following
command:
SET ENCRYPTION ON IDENTIFIED BY "oracle1";
a. Set encryption mode and password.
RMAN> SET ENCRYPTION ON IDENTIFIED BY "oracle1";

executing command: SET encryption

RMAN>
b. Use the RMAN BACKUP command to make a backup to
/home/oracle/backup/example002.bck.
RMAN> backup tablespace example
format '/home/oracle/backup/example002.bck'
tag 'dual';
2> 3>
Starting backup at 18-JUN-13
using channel ORA_DISK_1

channel ORA_DISK_1: starting full datafile backup set


channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00002
name=/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: starting piece 1 at 18-JUN-13
channel ORA_DISK_1: finished piece 1 at 18-JUN-13
piece handle=/home/oracle/backup/example002.bck tag=DUAL
comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:07
Finished backup at 18-JUN-13

RMAN> SELECT tag, encrypted FROM v$backup_piece;

TAG ENC
-------------------------------- ---
TRANSPARENT YES
DUAL YES

RMAN>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 6
4. Back up the EXAMPLE tablespace using password encryption to
/home/oracle/backup/example003.bck. Set tag = password so that it can be
specified in the restore command. To set encryption mode and password, use the
following command:
SET ENCRYPTION ON IDENTIFIED BY "password1" only;
a. Set the password for encryption.
RMAN> set encryption on identified by "password1" only;

executing command: SET encryption

RMAN>
b. Use the RMAN BACKUP command to make a backup to
/home/oracle/backup/example003.bck.
RMAN> backup tablespace example
format '/home/oracle/backup/example003.bck'
tag 'password';
2> 3>
Starting backup at 18-JUN-13
using channel ORA_DISK_1

channel ORA_DISK_1: starting full datafile backup set


channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00002
name=/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: starting piece 1 at 18-JUN-13
channel ORA_DISK_1: finished piece 1 at 18-JUN-13
piece handle=/home/oracle/backup/example003.bck tag=PASSWORD
comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:07
Finished backup at 18-JUN-13

RMAN> SELECT tag, encrypted FROM v$backup_piece;

TAG ENC
-------------------------------- ---
TRANSPARENT YES
DUAL YES
PASSWORD YES

RMAN> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 7
5. Close the keystore.
$ sqlplus / as SYSKM

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE CLOSE
IDENTIFIED BY secret;
2
keystore altered.

SQL> EXIT
$
6. In another terminal session, remove the EXAMPLE tablespace file.
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / AS SYSDBA

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> SELECT name FROM v$datafile;

NAME
---------------------------------------------------------------
/u01/app/oracle/oradata/orcl/system01.dbf
/u01/app/oracle/oradata/orcl/example01.dbf
/u01/app/oracle/oradata/orcl/sysaux01.dbf
/u01/app/oracle/oradata/orcl/undotbs01.dbf
/u01/app/oracle/oradata/orcl/enctbs01.dbf
/u01/app/oracle/oradata/orcl/users01.dbf

6 rows selected.

SQL> EXIT
$ rm /u01/app/oracle/oradata/orcl/example01.dbf
$
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 8
7. Attempt to restore the example tablespace by using the backup made with transparent
encryption. Why does it fail?
Attempt to restore the backup with the transparent tag. The keystore is closed. As a
result, the encryption key is not available.
$ rman target '"john@orcl AS SYSBACKUP"'

target database Password:


connected to target database: ORCL (DBID=1345659572, not open)

RMAN> restore tablespace example from tag transparent;

Starting restore at 18-JUN-13


using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=12 device type=DISK

channel ORA_DISK_1: starting datafile backup set restore


channel ORA_DISK_1: specifying datafile(s) to restore from
backup set
channel ORA_DISK_1: restoring datafile 00002 to
/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: reading from backup piece
/home/oracle/backup/example001.bck
RMAN-00571:
===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS
RMAN-00571:
===========================================================
RMAN-03002: failure of restore command at 06/18/2013 08:01:28
ORA-19870: error while restoring backup piece
/home/oracle/backup/example001.bck
ORA-19913: unable to decrypt backup
ORA-28365: wallet is not open

RMAN>
8. Restore the example tablespace by using password encryption.
The restore from the password-only backup succeeds because the password is provided
and the keystore is not needed.
RMAN> SET DECRYPTION IDENTIFIED BY "password1";

executing command: SET decryption

RMAN> restore tablespace example from tag "password";

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 9
Starting restore at 18-JUN-13
using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore


channel ORA_DISK_1: specifying datafile(s) to restore from
backup set
channel ORA_DISK_1: restoring datafile 00002 to
/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: reading from backup piece
/home/oracle/backup/example003.bck
channel ORA_DISK_1: piece
handle=/home/oracle/backup/example003.bck tag=PASSWORD
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:16
Finished restore at 18-JUN-13

RMAN>
9. In your second terminal session, once again remove the EXAMPLE tablespace datafile.
$ rm /u01/app/oracle/oradata/orcl/example01.dbf
$
10. Attempt to restore the example tablespace by using dual-mode encryption. Why does it fail?
The restore fails because the keystore is not open and the password is not set.
RMAN> restore tablespace example from tag dual;

Starting restore at 18-JUN-13


using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore


channel ORA_DISK_1: specifying datafile(s) to restore from
backup set
channel ORA_DISK_1: restoring datafile 00002 to
/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: reading from backup piece
/home/oracle/backup/example002.bck
RMAN-00571:
===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS
===============
RMAN-00571:
===========================================================
RMAN-03002: failure of restore command at 06/18/2013 08:19:27
ORA-19870: error while restoring backup piece
/home/oracle/backup/example002.bck
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 10
ORA-19913: unable to decrypt backup
ORA-28365: wallet is not open

RMAN>
11. Set the password for dual-mode backup and restore.
To restore from dual-mode backup, either the password must be provided or the keystore
must be open.
RMAN> SET DECRYPTION IDENTIFIED BY "oracle1";

executing command: SET decryption

RMAN> restore tablespace example from tag dual;

Starting restore at 18-JUN-13


using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore


channel ORA_DISK_1: specifying datafile(s) to restore from
backup set
channel ORA_DISK_1: restoring datafile 00002 to
/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: reading from backup piece
/home/oracle/backup/example002.bck
channel ORA_DISK_1: piece
handle=/home/oracle/backup/example002.bck tag=DUAL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:15
Finished restore at 18-JUN-13

RMAN> exit
$
12. In your second terminal session, again remove the datafile.
$ rm /u01/app/oracle/oradata/orcl/example01.dbf
$
13. Open the encryption keystore.
$ sqlplus / as SYSKM

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE OPEN
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 11
IDENTIFIED BY secret;
2
keystore altered.

SQL> EXIT
$
14. Restore the example tablespace by using transparent encryption.
Transparent mode encryption requires the keystore to be open.
$ rman target '"john@orcl AS SYSBACKUP"'

target database Password:


connected to target database: ORCL (DBID=1345659572, not open)

RMAN> restore tablespace example from tag transparent;

Starting restore at 18-JUN-13


using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=11 device type=DISK

channel ORA_DISK_1: starting datafile backup set restore


channel ORA_DISK_1: specifying datafile(s) to restore from
backup set
channel ORA_DISK_1: restoring datafile 00002 to
/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: reading from backup piece
/home/oracle/backup/example001.bck
channel ORA_DISK_1: piece
handle=/home/oracle/backup/example001.bck tag=TRANSPARENT
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:15
Finished restore at 18-JUN-13

RMAN>
15. In your second terminal session, again remove the datafile and close the terminal window.
$ rm /u01/app/oracle/oradata/orcl/example01.dbf
$ exit

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 12
16. Attempt to restore the example tablespace by using password-encrypted backup without
supplying the password.
The password-encrypted backup must have a password set in the session.
RMAN> restore tablespace example from tag "password";

Starting restore at 18-JUN-13


using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore


channel ORA_DISK_1: specifying datafile(s) to restore from
backup set
channel ORA_DISK_1: restoring datafile 00002 to
/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: reading from backup piece
/home/oracle/backup/example003.bck
RMAN-00571:
===========================================================
RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS
RMAN-00571:
===========================================================
RMAN-03002: failure of restore command at 06/18/2013 08:22:19
ORA-19870: error while restoring backup piece
/home/oracle/backup/example003.bck
ORA-19913: unable to decrypt backup

RMAN>
17. Restore dual-mode backup without a password.
Dual-mode encrypted backup uses either the keystore or the password.
RMAN> restore tablespace example from tag dual;

Starting restore at 18-JUN-13


using channel ORA_DISK_1

channel ORA_DISK_1: starting datafile backup set restore


channel ORA_DISK_1: specifying datafile(s) to restore from
backup set
channel ORA_DISK_1: restoring datafile 00002 to
/u01/app/oracle/oradata/orcl/example01.dbf
channel ORA_DISK_1: reading from backup piece
/home/oracle/backup/example002.bck
channel ORA_DISK_1: piece
handle=/home/oracle/backup/example002.bck tag=DUAL
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:15

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 13
Finished restore at 18-JUN-13

RMAN>
18. Recover the example tablespace, open the database, and then exit Recovery Manager.
RMAN> recover tablespace example;

Starting recover at 18-JUN-13


using channel ORA_DISK_1

starting media recovery


media recovery complete, elapsed time: 00:00:00

Finished recover at 18-JUN-13

RMAN> ALTER DATABASE OPEN;

Statement processed

RMAN> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 14
Practice 20-2: Exporting Encrypted Data
Overview
In this practice, you will perform various Data Pump export operations using the different
parameters for encryption. This will help you understand that you may export data in an
unsecure manner.

Assumptions
The practice 19-1 successfully completed the creation of the password-based keystore in the
cdb1 and the generation of master keys for each PDB in cdb1.

Tasks
1. Execute the $HOME/labs/ENC/create_tables_pdb1_1.sql script to create a table
with an encrypted column in pdb1_1 pluggable database.
$ . oraenv
ORACLE_SID = [orcl] ? cdb1
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> @$HOME/labs/ENC/create_tables_pdb1_1.sql
SQL> SET ECHO ON
SQL>
SQL> connect system/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL> ALTER USER oe IDENTIFIED BY oracle_4U ACCOUNT UNLOCK;

User altered.

SQL> grant create any directory to oe;

Grant succeeded.

SQL>
SQL> connect system/oracle_4U@localhost:1521/pdb1_2
Connected.
SQL> ALTER USER oe IDENTIFIED BY oracle_4U ACCOUNT UNLOCK ;
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 15
User altered.

SQL> grant create any directory to oe;

Grant succeeded.

SQL>
SQL> connect oe/oracle_4U@localhost:1521/pdb1_1
Connected.
SQL> create directory dp as '/tmp';

Directory created.

SQL> connect oe/oracle_4U@localhost:1521/pdb1_2


Connected.
SQL> create directory dp as '/tmp';

Directory created.

SQL> connect oe/oracle_4U@localhost:1521/pdb1_1


Connected.
SQL> drop table cust_payment_info;
drop table cust_payment_info
*
ERROR at line 1:
ORA-00942: table or view does not exist

SQL> create table cust_payment_info


2 (first_name varchar2(11),
3 last_name varchar2(10),
4 order_number number(5),
5 credit_card_number varchar2(20) ENCRYPT,
6 active_card varchar2(3));

Table created.

SQL>
SQL> insert into cust_payment_info values
2 ('Jon', 'Oldfield', 10001, 5105105105105100,'YES');

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 16
1 row created.

SQL> insert into cust_payment_info values


2 ('Chris', 'White', 10002, 6011111111111117,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Alan', 'Squire', 10003, 378282246310005,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Mike', 'Anderson', 10004, 6011000000000004,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Annie', 'Schmidt', 10005, 4111111111111111,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Elliott', 'Meyer', 10006, 4222222222222,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Celine', 'Smith', 10007, 343434343434343,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Steve', 'Haslam', 10008, 6011000990139424,'YES');

1 row created.

SQL> insert into cust_payment_info values


2 ('Albert', 'Einstein', 10009, 5111111111111118,'YES');

1 row created.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 17
SQL>
SQL> COMMIT;

Commit complete.

SQL> exit
$
2. Export the OE.CUST_PAYMENT_INFO table that holds one encrypted column.
$ expdp oe@pdb1_1 tables=cust_payment_info directory=dp
REUSE_DUMPFILES=YES

Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
Starting "OE"."SYS_EXPORT_TABLE_01":
oe/********@localhost:1521/pdb1_1 tables=cust_payment_info
directory=dp REUSE_DUMPFILES=YES
Estimate in progress using BLOCKS method...
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Total estimation using BLOCKS method: 64 KB
Processing object type TABLE_EXPORT/TABLE/TABLE
Processing object type
TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
Processing object type TABLE_EXPORT/TABLE/STATISTICS/MARKER
. . exported "OE"."CUST_PAYMENT_INFO" 7.179
KB 9 rows
ORA-39173: Encrypted data has been stored unencrypted in dump
file set.
Master table "OE"."SYS_EXPORT_TABLE_01" successfully
loaded/unloaded
***************************************************************
Dump file set for OE.SYS_EXPORT_TABLE_01 is:
/tmp/expdat.dmp
Job "OE"."SYS_EXPORT_TABLE_01" completed with 1 error(s) at Thu
May 30 06:15:10 2013 elapsed 0 00:00:16

$
Notice the warning message: ORA-39173: Encrypted data has been stored
unencrypted in dump file set.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 18
This clearly warns you that the data exported from the OE.CUST_PAYMENT_INFO table is
stored in clear text in the export dumpfile. The Data Pump export operation decrypted the
data to export it into the dumpfile.
3. Use the dual encryption mode.
$ expdp oe@pdb1_1 tables=cust_payment_info encryption_mode=dual
directory=dp REUSE_DUMPFILES=YES

Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
ORA-39002: invalid operation
ORA-39050: parameter ENCRYPTION is incompatible with parameter
ENCRYPTION_MODE

$
By default, the ENCRYPTION parameter, when not explicitly defined, sets the scope of
encryption to columns only. This encryption scope is incompatible with dual mode
encryption export.
4. Set the ENCRYPTION parameter explicitly to a compatible value.
$ expdp oe@pdb1_1 tables=cust_payment_info encryption_mode=dual
encryption=data_only directory=dp REUSE_DUMPFILES=YES

Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
ORA-39002: invalid operation
ORA-39174: Encryption password must be supplied.

$
The ENCRYPTION parameter sets the scope of encryption to a value compatible with the
encryption scope, but the dual mode requires the keystore to be opened and a password
explicitly defined. The operation will export data only.
$ expdp oe@pdb1_1 tables=cust_payment_info encryption_mode=dual
encryption=data_only encryption_password="welcome1"
directory=dp dumpfile=reuse

Password: ******

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 19
Connected to: Oracle Database 12c Enterprise Edition Release
12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
Starting "OE"."SYS_EXPORT_TABLE_01":
oe/********@localhost:1521/pdb1_1 tables=cust_payment_info
encryption_mode=dual encryption=data_only
encryption_password=******** directory=dp REUSE_DUMPFILES=YES
Estimate in progress using BLOCKS method...
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Total estimation using BLOCKS method: 64 KB
Processing object type TABLE_EXPORT/TABLE/TABLE
Processing object type
TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
Processing object type TABLE_EXPORT/TABLE/STATISTICS/MARKER
. . exported "OE"."CUST_PAYMENT_INFO" 7.187
KB 9 rows
Master table "OE"."SYS_EXPORT_TABLE_01" successfully
loaded/unloaded
***************************************************************
Dump file set for OE.SYS_EXPORT_TABLE_01 is:
/tmp/expdat.dmp
Job "OE"."SYS_EXPORT_TABLE_01" successfully completed at Thu May
30 06:39:29 2013 elapsed 0 00:00:08

$
5. Use the same parameters to export metadata only.
$ expdp oe@pdb1_1 tables=cust_payment_info encryption_mode=dual
encryption=metadata_only encryption_password="welcome1"
directory=dp REUSE_DUMPFILES=YES

Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
Starting "OE"."SYS_EXPORT_TABLE_01":
oe/********@localhost:1521/pdb1_1 tables=cust_payment_info
encryption_mode=dual encryption=metadata_only
encryption_password=******** directory=dp REUSE_DUMPFILES=YES
Estimate in progress using BLOCKS method...
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Total estimation using BLOCKS method: 64 KB
Processing object type TABLE_EXPORT/TABLE/TABLE

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 20
Processing object type
TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
Processing object type TABLE_EXPORT/TABLE/STATISTICS/MARKER
. . exported "OE"."CUST_PAYMENT_INFO" 7.179
KB 9 rows
ORA-39173: Encrypted data has been stored unencrypted in dump
file set.
Master table "OE"."SYS_EXPORT_TABLE_01" successfully
loaded/unloaded
***************************************************************
Dump file set for OE.SYS_EXPORT_TABLE_01 is:
/tmp/expdat.dmp
Job "OE"."SYS_EXPORT_TABLE_01" completed with 1 error(s) at Thu
May 30 06:48:04 2013 elapsed 0 00:00:06

$
Notice the warning message: ORA-39173: Encrypted data has been stored
unencrypted in dump file set.
This clearly warns you that the data exported from the OE.CUST_PAYMENT_INFO table is
stored in clear text in the export dumpfile. The Data Pump export operation kept encrypted
the metadata only as requested in the command.
6. The SYSKM administrator decides to temporarily close the keystore for an administrative
keystore maintenance task.
$ sqlplus / as SYSKM

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE CLOSE
IDENTIFIED BY secret_cdb1
CONTAINER=ALL;
2 3
keystore altered.

SQL> exit
$
7. Export in dual mode.
$ expdp oe@pdb1_1 tables=cust_payment_info encryption_mode=dual
encryption=data_only encryption_password="welcome1" directory=dp
REUSE_DUMPFILES=YES
Password: ******

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 21
Export: Release 12.1.0.1.0 - Production on Thu May 30 06:54:18
2013

Copyright (c) 1982, 2013, Oracle and/or its affiliates. All


rights reserved.

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
ORA-39002: invalid operation
ORA-39188: unable to encrypt dump file set
ORA-28365: wallet is not open
$
The dual mode requires that the keystore be opened.
8. The keystore is still closed but you need to export in a secure mode.
a. Use the PASSWORD mode.
$ expdp oe@pdb1_1 tables=cust_payment_info
encryption_mode=password encryption_password="welcome1"
encryption_pwd_prompt=YES directory=dp REUSE_DUMPFILES=YES
Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
UDE-00011: parameter encryption_password is incompatible with
parameter encryption_pwd_prompt
$
encryption_password and encryption_pwd_prompt=YES are incompatible.
b. Restart the operation without the password. Enter “welcome1” when prompted for the
password.
$ expdp oe@pdb1_1 tables=cust_payment_info
encryption_mode=password ENCRYPTION_PWD_PROMPT=YES directory=dp
REUSE_DUMPFILES=YES
Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

Encryption Password: ******

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 22
Starting "OE"."SYS_EXPORT_TABLE_01":
oe/********@localhost:1521/pdb1_1 tables=cust_payment_info
encryption_mode=password ENCRYPTION_PWD_PROMPT=YES directory=dp
REUSE_DUMPFILES=YES
Estimate in progress using BLOCKS method...
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Total estimation using BLOCKS method: 64 KB
Processing object type TABLE_EXPORT/TABLE/TABLE
Processing object type
TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
Processing object type TABLE_EXPORT/TABLE/STATISTICS/MARKER
ORA-31693: Table data object "OE"."CUST_PAYMENT_INFO" failed to
load/unload and is being skipped due to error:
ORA-29913: error in executing ODCIEXTTABLEPOPULATE callout
ORA-28365: wallet is not open
Master table "OE"."SYS_EXPORT_TABLE_01" successfully
loaded/unloaded
***************************************************************
Dump file set for OE.SYS_EXPORT_TABLE_01 is:
/tmp/expdat.dmp
Job "OE"."SYS_EXPORT_TABLE_01" completed with 1 error(s) at Thu
May 30 06:59:29 2013 elapsed 0 00:00:10

$
ENCRYPTION_PASSWORD specifies a key for re-encrypting encrypted table columns so that
they are not written as clear text in the dump file set.
Notice that the data has not been exported. The data needs to be decrypted during export
using the keystore before being reencrypted into the dumpfile using the password. This
requires the keystore to be opened.
c. Open the keystore and retry.
$ sqlplus / as SYSKM

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE OPEN
IDENTIFIED BY secret_cdb1
CONTAINER=ALL;
2 3
keystore altered.

SQL> exit
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 23
Enter “welcome1” when prompted for the password.
$ expdp oe@pdb1_1 tables=cust_payment_info
encryption_mode=password ENCRYPTION_PWD_PROMPT=YES directory=dp
REUSE_DUMPFILES=YES

Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

Encryption Password: ******


Starting "OE"."SYS_EXPORT_TABLE_01":
oe/********@localhost:1521/pdb1_1 tables=cust_payment_info
encryption_mode=password ENCRYPTION_PWD_PROMPT=YES directory=dp
REUSE_DUMPFILES=YES
Estimate in progress using BLOCKS method...
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Total estimation using BLOCKS method: 64 KB
Processing object type TABLE_EXPORT/TABLE/TABLE
Processing object type
TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
Processing object type TABLE_EXPORT/TABLE/STATISTICS/MARKER
. . exported "OE"."CUST_PAYMENT_INFO" 7.187
KB 9 rows
Master table "OE"."SYS_EXPORT_TABLE_01" successfully
loaded/unloaded
***************************************************************
Dump file set for OE.SYS_EXPORT_TABLE_01 is:
/tmp/expdat.dmp
Job "OE"."SYS_EXPORT_TABLE_01" successfully completed at Thu May
30 07:18:10 2013 elapsed 0 00:00:09

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 24
Practice 20-3: Importing Encrypted Data
Overview
In this practice, you will import the OE.CUST_PAYMENT_INFO table that holds one encrypted
column into another PDB of cdb1.

Assumptions
The last export operation successfully completed in the practice 20-2.

Tasks
1. The SYSKM administrator decides to temporarily close the keystore for an administrative
keystore maintenance task.
$ sqlplus / as SYSKM

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE CLOSE
IDENTIFIED BY secret_cdb1
CONTAINER=ALL;
2 3
keystore altered.

SQL> exit
$
2. Import the OE.CUST_PAYMENT_INFO table into pdb1_2 of cdb1. The
OE.CUST_PAYMENT_INFO table does not exist in pdb1_2.
If it exists, drop the table.
$ sqlplus system@pdb1_2

Enter password: ******


SQL> drop table oe.cust_payment_info;

Table dropped.

SQL> EXIT
$
a. Use the impdp command.
$ impdp oe@pdb1_2 tables=cust_payment_info directory=dp
Password: ******

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 25
Connected to: Oracle Database 12c Enterprise Edition Release
12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
ORA-39002: invalid operation
ORA-39174: Encryption password must be supplied.
$
b. The export operation used a password to encrypt data in the dumpfile. The import
operation requires the same password to decrypt the data.
$ impdp oe@pdb1_2 tables=cust_payment_info
ENCRYPTION_PWD_PROMPT=YES directory=dp

Password: ******

Import: Release 12.1.0.1.0 - Production on Thu May 30 07:46:26


2013

Copyright (c) 1982, 2013, Oracle and/or its affiliates. All


rights reserved.

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

Encryption Password:
ORA-39002: invalid operation
ORA-39176: Encryption password is incorrect.
$
c. Enter the same password (“welcome1”) used by the export operation. If you use the
wrong password, the import fails.
$ impdp oe@pdb1_2 tables=cust_payment_info
ENCRYPTION_PWD_PROMPT=YES directory=dp

Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

Encryption Password: ******


Master table "OE"."SYS_IMPORT_TABLE_01" successfully
loaded/unloaded

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 26
Starting "OE"."SYS_IMPORT_TABLE_01":
oe/********@localhost:1521/pdb1_2 tables=cust_payment_info
ENCRYPTION_PWD_PROMPT=YES directory=dp
Processing object type TABLE_EXPORT/TABLE/TABLE
ORA-39083: Object type TABLE:"OE"."CUST_PAYMENT_INFO" failed to
create with error:
ORA-28365: wallet is not open
Failing sql is:
CREATE TABLE "OE"."CUST_PAYMENT_INFO" ("FIRST_NAME" VARCHAR2(11
BYTE), "LAST_NAME" VARCHAR2(10 BYTE), "ORDER_NUMBER"
NUMBER(5,0), "CREDIT_CARD_NUMBER" VARCHAR2(20 BYTE) ENCRYPT
USING 'AES192' 'SHA-1', "ACTIVE_CARD" VARCHAR2(3 BYTE)) SEGMENT
CREATION IMMEDIATE PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255
NOCOMPRESS NOLOGGING STORAGE(INITIAL 65536 NEXT 1048576
MINEXTENTS 1 MAXEXTEN
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Processing object type
TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
Processing object type TABLE_EXPORT/TABLE/STATISTICS/MARKER
Job "OE"."SYS_IMPORT_TABLE_01" completed with 1 error(s) at Thu
May 30 07:54:47 2013 elapsed 0 00:00:04

$
The table is created with a CREDIT_CARD_NUMBER column, which holds the ENCRYPT
attribute. The password is required to decrypt the values of the CREDIT_CARD_NUMBER
column stored in the dumpfile and require the keystore to be opened to re-encrypt the
values in the data file where the table segment is stored.
d. Ask the SYSKM administrator to open the keystore.
$ sqlplus / as SYSKM

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE OPEN
IDENTIFIED BY secret_cdb1
CONTAINER=ALL;
2 3
keystore altered.

SQL> exit
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 27
e. Reattempt the import operation.
$ impdp oe@pdb1_2 tables=cust_payment_info
ENCRYPTION_PWD_PROMPT=YES directory=dp

Password: ******
Connected to: Oracle Database 12c Enterprise Edition Release
12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

Encryption Password: ******


Master table "OE"."SYS_IMPORT_TABLE_01" successfully
loaded/unloaded
Starting "OE"."SYS_IMPORT_TABLE_01":
oe/********@localhost:1521/pdb1_2 tables=cust_payment_info
ENCRYPTION_PWD_PROMPT=YES directory=dp
Processing object type TABLE_EXPORT/TABLE/TABLE
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
. . imported "OE"."CUST_PAYMENT_INFO" 7.187
KB 9 rows
Processing object type
TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
Processing object type TABLE_EXPORT/TABLE/STATISTICS/MARKER
Job "OE"."SYS_IMPORT_TABLE_01" successfully completed at Thu May
30 07:50:23 2013 elapsed 0 00:00:10

$
3. Consider that the OE.CUST_PAYMENT_INFO table already existed into pdb1_2 of cdb1
without the ENCRYPT attribute.
a. Drop and re-create the table without the ENCRYPT attribute.
$ sqlplus oe@pdb1_2
Enter password : ******

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 28
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real
Application Testing options

SQL> DROP TABLE OE.CUST_PAYMENT_INFO PURGE;

Table dropped.

SQL> create table cust_payment_info


( first_name varchar2(11),
last_name varchar2(10),
order_number number(5),
credit_card_number varchar2(20),
active_card varchar2(3));
2 3 4 5 6
Table created.

SQL>
b. The SYSKM administrator closes the keystore for maintenance operation.
SQL> CONNECT / as SYSKM
Connected.
SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE CLOSE
IDENTIFIED BY secret_cdb1
CONTAINER=ALL;
2 3
keystore altered.

SQL> exit
$
c. Use the impdp command to import the OE.CUST_PAYMENT_INFO table.
$ impdp oe@pdb1_2 tables=cust_payment_info directory=dp

Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options
ORA-39002: invalid operation
ORA-39174: Encryption password must be supplied.
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 29
d. The export operation used a password to encrypt data in the dumpfile. The import
operation requires the same password to decrypt the data.
$ impdp oe@pdb1_2 tables=cust_payment_info
ENCRYPTION_PWD_PROMPT=YES directory=dp
TABLE_EXISTS_ACTION=truncate
Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

Encryption Password: ******


Master table "OE"."SYS_IMPORT_TABLE_01" successfully
loaded/unloaded
Starting "OE"."SYS_IMPORT_TABLE_01":
oe/********@localhost:1521/pdb1_2 tables=cust_payment_info
ENCRYPTION_PWD_PROMPT=YES directory=dp
TABLE_EXISTS_ACTION=truncate
Processing object type TABLE_EXPORT/TABLE/TABLE
Table "OE"."CUST_PAYMENT_INFO" exists and has been truncated.
Data will be loaded but all dependent metadata will be skipped
due to table_exists_action of truncate
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
. . imported "OE"."CUST_PAYMENT_INFO" 7.187
KB 9 rows
Processing object type
TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
Processing object type TABLE_EXPORT/TABLE/STATISTICS/MARKER
Job "OE"."SYS_IMPORT_TABLE_01" successfully completed at Thu May
30 08:27:12 2013 elapsed 0 00:00:06
$
Notice that even if the keystore is closed, the import operation does not need it. The
password is sufficient to decrypt the data in the dumpfile. The decrypted data is not re-
encrypted because the table does not hold any ENCRYPT column.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 20: Applying File Encryption


Chapter 20 - Page 30
Practices for Lesson 21:
Using Unified Auditing
Chapter 21

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 1
Practices for Lesson 21: Overview
Practices Overview
In the practices for this lesson, you enable unified audit, configure for Data Pump export
auditing, and audit export and RMAN operations. You then view the audited data in the
UNIFIED_AUDIT_TRAIL view.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 2
Practice 21-1: Enabling Unified Auditing
Overview
In this practice, you enable unified auditing.

Tasks
1. Shut down all Oracle processes of all instances.
a. Shut down the listener.
$ . oraenv
ORACLE_SID = [cdb1] ? orcl
The Oracle base remains unchanged with value /u01/app/oracle
$

$ lsnrctl stop

LSNRCTL for Linux: Version 12.1.0.1.0 - Production on 30-MAY-


2013 15:18:54

Copyright (c) 1991, 2013, Oracle. All rights reserved.

Connecting to
(DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
The command completed successfully
$
b. Shut down all instances.
$ pgrep -lf pmon
13266 ora_pmon_cdb1
20655 ora_pmon_em12rep
32139 ora_pmon_orcl
$
1) Shut down the orcl instance.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> shutdown immediate


Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> EXIT
$
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 3
2) Shut down the cdb2 instance.
$ . oraenv
ORACLE_SID = [orcl] ? cdb1
The Oracle base remains unchanged with value /u01/app/oracle
$

$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> shutdown immediate


Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> EXIT
$
3) Shut down the em12rep instance.
a) Stop the OMS.
$ cd /u01/app/oracle/product/middleware/oms
$ export OMS_HOME=/u01/app/oracle/product/middleware/oms
$ $OMS_HOME/bin/emctl stop oms
Oracle Enterprise Manager Cloud Control 12c Release 2
Copyright (c) 1996, 2012 Oracle Corporation. All rights
reserved.
Stopping WebTier...
WebTier Successfully Stopped
Stopping Oracle Management Server...
Oracle Management Server Successfully Stopped
Oracle Management Server is Down
$
b) Shut down the repository database instance em12rep.
$ . oraenv
ORACLE_SID = [cdb1] ? em12rep
The Oracle base remains unchanged with value /u01/app/oracle
$

$ sqlplus / as sysdba

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 4
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> shutdown immediate


Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> EXIT
$
4) Verify that all instances are down.
$ pgrep -lf pmon
$
2. Enable the Unified Audit option. Be cautious to copy the whole make command with the
ORACLE_HOME=$ORACLE_HOME argument.
$ cd $ORACLE_HOME/rdbms/lib
$ make -f ins_rdbms.mk uniaud_on ioracle
ORACLE_HOME=$ORACLE_HOME
/usr/bin/ar d
/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/libknlopt.a
kzanang.o
/usr/bin/ar cr
/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/libknlopt.a
/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/kzaiang.o
chmod 755 /u01/app/oracle/product/12.1.0/dbhome_1/bin

- Linking Oracle
rm -f /u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/oracle
/u01/app/oracle/product/12.1.0/dbhome_1/bin/orald -o
/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/oracle -m64 -z
noexecstack -L/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/
-L/u01/app/oracle/product/12.1.0/dbhome_1/lib/ -
L/u01/app/oracle/product/12.1.0/dbhome_1/lib/stubs/ -Wl,-E
/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/opimai.o
/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/ssoraed.o
/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/ttcsoi.o -Wl,-
-whole-archive -lperfsrv12 -Wl,--no-whole-archive
/u01/app/oracle/product/12.1.0/dbhome_1/lib/nautab.o
/u01/app/oracle/product/12.1.0/dbhome_1/lib/naeet.o
/u01/app/oracle/product/12.1.0/dbhome_1/lib/naect.o
/u01/app/oracle/product/12.1.0/dbhome_1/lib/naedhs.o
/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/config.o -
lserver12 -lodm12 -lcell12 -lnnet12 -lskgxp12 -lsnls12 -lnls12
-lcore12 -lsnls12 -lnls12 -lcore12 -lsnls12 -lnls12 -lxml12 -

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 5
lcore12 -lunls12 -lsnls12 -lnls12 -lcore12 -lnls12 -lclient12 -
lvsn12 -lcommon12 -lgeneric12 -lknlopt `if /usr/bin/ar tv
/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/libknlopt.a |
grep xsyeolap.o > /dev/null 2>&1 ; then echo "-loraolap12" ; fi`
-lskjcx12 -lslax12 -lpls12 -lrt -lplp12 -lserver12 -lclient12
-lvsn12 -lcommon12 -lgeneric12 `if [ -f
/u01/app/oracle/product/12.1.0/dbhome_1/lib/libavserver12.a ] ;
then echo "-lavserver12" ; else echo "-lavstub12"; fi` `if [ -f
/u01/app/oracle/product/12.1.0/dbhome_1/lib/libavclient12.a ] ;
then echo "-lavclient12" ; fi` -lknlopt -lslax12 -lpls12 -lrt -
lplp12 -ljavavm12 -lserver12 -lwwg `cat
/u01/app/oracle/product/12.1.0/dbhome_1/lib/ldflags` -
lncrypt12 -lnsgr12 -lnzjs12 -ln12 -lnl12 -lnro12 `cat
/u01/app/oracle/product/12.1.0/dbhome_1/lib/ldflags` -
lncrypt12 -lnsgr12 -lnzjs12 -ln12 -lnl12 -lnnz12 -lzt12 -lztkg12
-lmm -lsnls12 -lnls12 -lcore12 -lsnls12 -lnls12 -lcore12 -
lsnls12 -lnls12 -lxml12 -lcore12 -lunls12 -lsnls12 -lnls12 -
lcore12 -lnls12 -lztkg12 `cat
/u01/app/oracle/product/12.1.0/dbhome_1/lib/ldflags` -
lncrypt12 -lnsgr12 -lnzjs12 -ln12 -lnl12 -lnro12 `cat
/u01/app/oracle/product/12.1.0/dbhome_1/lib/ldflags` -
lncrypt12 -lnsgr12 -lnzjs12 -ln12 -lnl12 -lnnz12 -lzt12 -lztkg12
-lsnls12 -lnls12 -lcore12 -lsnls12 -lnls12 -lcore12 -lsnls12 -
lnls12 -lxml12 -lcore12 -lunls12 -lsnls12 -lnls12 -lcore12 -
lnls12 `if /usr/bin/ar tv
/u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/libknlopt.a |
grep "kxmnsd.o" > /dev/null 2>&1 ; then echo " " ; else echo "-
lordsdo12"; fi` -
L/u01/app/oracle/product/12.1.0/dbhome_1/ctx/lib/ -lctxc12 -
lctx12 -lzx12 -lgx12 -lctx12 -lzx12 -lgx12 -lordimt12 -lclsra12
-ldbcfg12 -lhasgen12 -lskgxn2 -lnnz12 -lzt12 -lxml12 -locr12 -
locrb12 -locrutl12 -lhasgen12 -lskgxn2 -lnnz12 -lzt12 -lxml12 -
lgeneric12 -loraz -llzopro -lorabz2 -lipp_z -lipp_bz2 -
lippdcemerged -lippsemerged -lippdcmerged -lippsmerged -
lippcore -lippcpemerged -lippcpmerged -lsnls12 -lnls12 -
lcore12 -lsnls12 -lnls12 -lcore12 -lsnls12 -lnls12 -lxml12 -
lcore12 -lunls12 -lsnls12 -lnls12 -lcore12 -lnls12 -lsnls12 -
lunls12 -lsnls12 -lnls12 -lcore12 -lsnls12 -lnls12 -lcore12 -
lsnls12 -lnls12 -lxml12 -lcore12 -lunls12 -lsnls12 -lnls12 -
lcore12 -lnls12 -lasmclnt12 -lcommon12 -lcore12 -laio -lons
`cat /u01/app/oracle/product/12.1.0/dbhome_1/lib/sysliblist` -
Wl,-rpath,/u01/app/oracle/product/12.1.0/dbhome_1/lib -lm
`cat /u01/app/oracle/product/12.1.0/dbhome_1/lib/sysliblist` -
ldl -lm -L/u01/app/oracle/product/12.1.0/dbhome_1/lib
test ! -f /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle ||\
mv -f
/u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle
/u01/app/oracle/product/12.1.0/dbhome_1/bin/oracleO
mv /u01/app/oracle/product/12.1.0/dbhome_1/rdbms/lib/oracle
/u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle
chmod 6751 /u01/app/oracle/product/12.1.0/dbhome_1/bin/oracle
$
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 6
3. Restart the processes.
a. Restart the database orcl only. A later practice requires the database to be in
ARCHIVELOG mode: set the ARCHIVELOG mode now.
$ . oraenv
ORACLE_SID = [em12rep] ? orcl
The Oracle base remains unchanged with value /u01/app/oracle
$

$ sqlplus / as sysdba

SQL*Plus: Release 12.1.0.1.0 Production on Thu May 30 15:27:15


2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.

Connected to an idle instance.

SQL> startup mount


ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2290024 bytes
Variable Size 264244888 bytes
Database Buffers 226492416 bytes
Redo Buffers 8032256 bytes
Database mounted.

SQL> ALTER DATABASE ARCHIVELOG;

Database altered.

SQL> ALTER DATABASE OPEN;

Database altered.

SQL> EXIT
$
b. Verify that unified auditing is enabled. You can see that the Unified Auditing option is
enabled in the SQL*Plus banner.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 7
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Real Application Testing and Unified Auditing options

SQL> COL parameter FORMAT A20


SQL> COL value FORMAT A20
SQL> select parameter , value
from v$option
where PARAMETER = 'Unified Auditing';

PARAMETER VALUE
-------------------- --------------------
Unified Auditing TRUE

SQL>
4. Check the existence of the predefined ORA_SECURECONFIG audit policy.
SQL> COL POLICY_NAME FORMAT A20
SQL> COL AUDIT_OPTION FORMAT A40
SQL> set PAGES 100
SQL> select POLICY_NAME, AUDIT_OPTION
from AUDIT_UNIFIED_POLICIES
where policy_name = 'ORA_SECURECONFIG' order by 2 ;
2 3
POLICY_NAME AUDIT_OPTION
-------------------- ----------------------------------------
ORA_SECURECONFIG ADMINISTER KEY MANAGEMENT
ORA_SECURECONFIG ALTER ANY PROCEDURE
ORA_SECURECONFIG ALTER ANY SQL TRANSLATION PROFILE
ORA_SECURECONFIG ALTER ANY TABLE
ORA_SECURECONFIG ALTER DATABASE
ORA_SECURECONFIG ALTER DATABASE LINK
ORA_SECURECONFIG ALTER PLUGGABLE DATABASE
ORA_SECURECONFIG ALTER PROFILE
ORA_SECURECONFIG ALTER ROLE
ORA_SECURECONFIG ALTER SYSTEM
ORA_SECURECONFIG ALTER USER
ORA_SECURECONFIG AUDIT SYSTEM
ORA_SECURECONFIG CREATE ANY JOB
ORA_SECURECONFIG CREATE ANY LIBRARY
ORA_SECURECONFIG CREATE ANY PROCEDURE
ORA_SECURECONFIG CREATE ANY SQL TRANSLATION PROFILE
ORA_SECURECONFIG CREATE ANY TABLE
ORA_SECURECONFIG CREATE DATABASE LINK

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 8
ORA_SECURECONFIG CREATE DIRECTORY
ORA_SECURECONFIG CREATE EXTERNAL JOB
ORA_SECURECONFIG CREATE PLUGGABLE DATABASE
ORA_SECURECONFIG CREATE PROFILE
ORA_SECURECONFIG CREATE PUBLIC SYNONYM
ORA_SECURECONFIG CREATE ROLE
ORA_SECURECONFIG CREATE SQL TRANSLATION PROFILE
ORA_SECURECONFIG CREATE USER
ORA_SECURECONFIG DROP ANY PROCEDURE
ORA_SECURECONFIG DROP ANY SQL TRANSLATION PROFILE
ORA_SECURECONFIG DROP ANY TABLE
ORA_SECURECONFIG DROP DATABASE LINK
ORA_SECURECONFIG DROP DIRECTORY
ORA_SECURECONFIG DROP PLUGGABLE DATABASE
ORA_SECURECONFIG DROP PROFILE
ORA_SECURECONFIG DROP PUBLIC SYNONYM
ORA_SECURECONFIG DROP ROLE
ORA_SECURECONFIG DROP USER
ORA_SECURECONFIG EXEMPT ACCESS POLICY
ORA_SECURECONFIG EXEMPT REDACTION POLICY
ORA_SECURECONFIG GRANT ANY OBJECT PRIVILEGE
ORA_SECURECONFIG GRANT ANY PRIVILEGE
ORA_SECURECONFIG GRANT ANY ROLE
ORA_SECURECONFIG LOGMINING
ORA_SECURECONFIG LOGOFF
ORA_SECURECONFIG LOGON
ORA_SECURECONFIG PURGE DBA_RECYCLEBIN
ORA_SECURECONFIG SET ROLE
ORA_SECURECONFIG TRANSLATE ANY SQL

47 rows selected.

SQL>
5. Verify that the predefined ORA_SECURECONFIG audit policy is enabled by default.
SQL> select POLICY_NAME
from AUDIT_UNIFIED_ENABLED_POLICIES
where policy_name = 'ORA_SECURECONFIG';
2 3
POLICY_NAME
--------------------
ORA_SECURECONFIG

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 9
6. Are users connections still audited?
SQL> connect hr
Enter password: ******
Connected.
SQL> connect hr
Enter password: ******
Connected.
SQL> connect / as sysdba
Connected.
SQL> col dbusername format A20
SQL> col action_name format A20
SQL> select action_name, dbusername
from unified_audit_trail
where dbusername='HR';
2 3

ACTION_NAME DBUSERNAME
-------------------- --------------------
LOGON HR
LOGON HR
… rows deleted.
LOGOFF HR
LOGOFF HR
… rows deleted.

SQL> exit
$
7. Restart the listener.
$ lsnrctl start

Starting /u01/app/oracle/product/12.1.0/dbhome_1/bin/tnslsnr:
please wait...

TNSLSNR for Linux: Version 12.1.0.1.0 - Production


System parameter file is
/u01/app/oracle/product/12.1.0/dbhome_1/network/admin/listener.o
ra
Log messages written to
/u01/app/oracle/diag/tnslsnr/<YourServer>/listener/alert/log.xml
Listening on:
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))
Listening on:
(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=<YourServer>)(PORT=152
1)))

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 10
Connecting to
(DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC1521)))
STATUS of the LISTENER
------------------------
Alias LISTENER
Version TNSLSNR for Linux: Version 12.1.0.1.0
- Production
Start Date 30-MAY-2013 15:28:59
Uptime 0 days 0 hr. 0 min. 0 sec
Trace Level off
Security ON: Local OS Authentication
SNMP OFF
Listener Parameter File
/u01/app/oracle/product/12.1.0/dbhome_1/network/admin/listener.o
ra
Listener Log File
/u01/app/oracle/diag/tnslsnr/<YourServer>/listener/alert/log.xml
Listening Endpoints Summary...
(DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC1521)))

(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=<YourServer>)(PORT=152
1)))
The listener supports no services
The command completed successfully
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 11
Practice 21-2: Creating and Enabling Audit Policies
Overview
In this practice, the security officer, the SEC user, will create audit policies to audit privileges,
actions and roles under defined conditions.

Tasks
1. Grant the SEC user the AUDIT_ADMIN role to allow him to manage audit policies.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Real Application Testing and Unified Auditing options

SQL> GRANT audit_admin to SEC;

Grant succeeded.

SQL>
2. Connect as SEC to create an audit policy that will audit the OE user using the SELECT ANY
TABLE or CREATE LIBRARY system privileges and this for each statement executed.
a. Grant the SELECT ANY TABLE to the OE and HR users. In case the users are already
granted the SELECT object privilege on the SH.SALES or HR.EMPLOYEES tables,
revoke the object privileges.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> REVOKE select ON sh.sales FROM hr;

REVOKE select ON sh.sales FROM hr


*
ERROR at line 1:
ORA-01927: cannot REVOKE privileges you did not grant

SQL> REVOKE select ON hr.employees FROM oe;

REVOKE select ON hr.employees FROM oe


*
ERROR at line 1:
ORA-01927: cannot REVOKE privileges you did not grant

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 12
SQL> GRANT select any table TO oe, hr;

Grant succeeded.

SQL>
b. Create the audit policy.
SQL> CREATE AUDIT POLICY aud_syspriv_pol
PRIVILEGES select any table, create library
WHEN 'SYS_CONTEXT(''USERENV'',''SESSION_USER'')=''OE'''
EVALUATE PER STATEMENT;
2 3 4
Audit policy created.

SQL>
c. Enable the audit policy.
SQL> AUDIT POLICY aud_syspriv_pol;

Audit succeeded.

SQL>
d. View the audit policy options.
SQL> col audit_option format A17
SQL> col policy_name format A16
SQL> col audit_condition format A42
SQL> SELECT POLICY_NAME, AUDIT_OPTION, AUDIT_CONDITION
FROM AUDIT_UNIFIED_POLICIES
WHERE POLICY_NAME ='AUD_SYSPRIV_POL';
2 3
POLICY_NAME AUDIT_OPTION
---------------- ---------------
AUDIT_CONDITION
------------------------------------------
AUD_SYSPRIV_POL CREATE LIBRARY
SYS_CONTEXT('USERENV','SESSION_USER')='OE'

AUD_SYSPRIV_POL SELECT ANY TABLE


SYS_CONTEXT('USERENV','SESSION_USER')='OE'

SQL>
e. Verify that the audit policy is enabled.
SQL> col user_name format A10
SQL> SELECT POLICY_NAME, ENABLED_OPT, USER_NAME, SUCCESS,
FAILURE
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 13
FROM AUDIT_UNIFIED_ENABLED_POLICIES
WHERE POLICY_NAME ='AUD_SYSPRIV_POL';
2 3
POLICY_NAME ENABLED_ USER_NAME SUC FAI
------------------ -------- ---------- --- ---
AUD_SYSPRIV_POL BY ALL USERS YES YES

SQL>
f. Connect as HR and then as OE and perform actions that require the SELECT ANY
TABLE or CREATE LIBRARY system privileges.
SQL> connect hr
Enter password: ******
Connected.
SQL> select count(*) from sh.sales;

COUNT(*)
----------
918843

SQL> connect oe
Enter password: ******
Connected.
SQL> select last_name from hr.employees;

LAST_NAME
-------------------------
… rows deleted

Urman
Vargas
Vishney
Vollman
Walsh
Weiss
Whalen
Zlotkey

83 rows selected.

SQL>
g. View the resulting audit data.
SQL> connect sec
Enter password: ******
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 14
Connected.
SQL> col action_name format A16
SQL> col policy_name format A18
SQL> col system_privilege_used format A20
SQL> select DBUSERNAME, ACTION_NAME, SYSTEM_PRIVILEGE_USED
from unified_audit_trail
where DBUSERNAME in ('HR','OE')
and action_name not in ('LOGON','LOGOFF');
2 3 4

DBUSERNAME ACTION_NAME SYSTEM_PRIVILEGE_USE


-------------------------- -------------- --------------------
OE SELECT SELECT ANY TABLE

… rows deleted

SQL>
Notice that the action executed by the HR user has not been audited. Only OE was
configured in the audit policy.
3. Create an audit policy that will audit any user performing any SELECT or UPDATE operation
on any object using an object or system privilege, or deleting rows from the HR.CODE table.
a. Create the audit policy.
SQL> CREATE AUDIT POLICY aud_action_pol
ACTIONS select, update, delete ON hr.code;
2
Audit policy created.

SQL>
b. Enable the audit policy for all users except OE.
SQL> AUDIT POLICY aud_action_pol EXCEPT oe;

Audit succeeded.

SQL>
c. View the audit policy options.
SQL> col audit_option format A17
SQL> col policy_name format A16
SQL> col audit_condition format A42
SQL> SELECT POLICY_NAME, AUDIT_OPTION, AUDIT_CONDITION
FROM AUDIT_UNIFIED_POLICIES
WHERE POLICY_NAME ='AUD_ACTION_POL';
2 3
POLICY_NAME AUDIT_OPTION AUDIT_CONDITION

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 15
----------------- ----------------- --------------------------
AUD_ACTION_POL SELECT NONE
AUD_ACTION_POL UPDATE NONE
AUD_ACTION_POL DELETE NONE

SQL>
d. Verify that the audit policy is enabled.
SQL> col user_name format A10
SQL> SELECT POLICY_NAME, ENABLED_OPT, USER_NAME, SUCCESS,
FAILURE
FROM AUDIT_UNIFIED_ENABLED_POLICIES
WHERE POLICY_NAME ='AUD_ACTION_POL';
2 3
POLICY_NAME ENABLED_ USER_NAME SUC FAI
------------------ -------- ---------- --- ---
AUD_ACTION_POL EXCEPT OE YES YES

SQL>
e. Perform an audit operation. First create a new user DEV and grant appropriate
privileges to DEV to execute operations.
SQL> CREATE USER dev IDENTIFIED BY oracle_4U;

User created.

SQL> GRANT create session TO dev;

Grant succeeded.

SQL> CONNECT hr
Enter password: ******
Connected.
SQL> GRANT delete on hr.code TO dev;

Grant succeeded.

SQL> CONNECT dev


Enter password: ******
Connected.
SQL> DELETE hr.code WHERE rownum=1;

1 row deleted.

SQL> COMMIT;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 16
Commit complete.

SQL> CONNECT oe
Enter password: ******
Connected.
SQL> SELECT count(*) FROM hr.employees;

COUNT(*)
----------
83

SQL>
f. View the resulting audit data.
SQL> connect sec
Enter password: ******
Connected.
SQL> set pages 100
SQL> col dbusername format A8
SQL> col action_name format A8
SQL> col unified_audit_policies format a40
SQL> SELECT UNIFIED_AUDIT_POLICIES, DBUSERNAME, ACTION_NAME
FROM unified_audit_trail
WHERE dbusername in ('DEV','OE')
AND action_name not in ('LOGON', 'LOGOFF')
AND unified_audit_policies like '%ACTION%';
2 3 4 5
UNIFIED_AUDIT_POLICIES DBUSERNA ACTION_N
---------------------------------------- -------- --------
… rows deleted

AUD_ACTION_POL DEV SELECT


AUD_ACTION_POL, AUD_ACTION_POL DEV SELECT
AUD_ACTION_POL, AUD_ACTION_POL DEV SELECT
AUD_ACTION_POL DEV DELETE

13 rows selected.

SQL>
Notice that OE was excluded from the auditing process.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 17
4. Create an audit policy that will audit all users while using the MGR_ROLE role.
a. Create a new user if the user does not exist yet. Create a new role and grant the new
role to jim.
SQL> DROP USER jim;

User dropped.

SQL> CREATE USER jim IDENTIFIED BY oracle_4U;

User created.

SQL> CREATE ROLE mgr_role;

Role created.

SQL> GRANT create tablespace TO mgr_role;

Grant succeeded.

SQL> GRANT mgr_role, create session TO jim;

Grant succeeded.

SQL>
b. Create the audit policy.
SQL> CREATE AUDIT POLICY aud_role_pol ROLES mgr_role;

Audit policy created.

SQL>
c. Enable the audit policy.
SQL> AUDIT POLICY aud_role_pol WHENEVER SUCCESSFUL;

Audit succeeded.

SQL>
d. Create another audit policy that will audit all users as soon as these users use the DBA
role.
1) Create a DBA_JUNIOR user granted the DBA role.
SQL> CREATE USER dba_junior IDENTIFIED BY oracle_4U;

User created.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 18
SQL> GRANT dba TO dba_junior;

Grant succeeded.

SQL>
2) Create the audit policy.
SQL> CREATE AUDIT POLICY aud_dba_pol ROLES dba;

Audit policy created.

SQL>
3) Enable the audit policy.
SQL> AUDIT POLICY aud_dba_pol WHENEVER SUCCESSFUL;

Audit succeeded.

SQL>
e. View the audit policy options.
SQL> col audit_option format A20
SQL> col policy_name format A18
SQL> SELECT POLICY_NAME, AUDIT_OPTION, CONDITION_EVAL_OPT
FROM AUDIT_UNIFIED_POLICIES
WHERE POLICY_NAME in ('AUD_ROLE_POL','AUD_DBA_POL');
2 3
POLICY_NAME AUDIT_OPTION CONDITION
------------------ -------------------- ---------
AUD_ROLE_POL MGR_ROLE NONE
AUD_DBA_POL DBA NONE

SQL>
f. Verify that the audit policy is enabled.
SQL> col user_name format A10
SQL> SELECT POLICY_NAME, ENABLED_OPT, USER_NAME, SUCCESS,
FAILURE
FROM AUDIT_UNIFIED_ENABLED_POLICIES
WHERE POLICY_NAME in ('AUD_ROLE_POL','AUD_DBA_POL');
2 3
POLICY_NAME ENABLED_ USER_NAME SUC FAI
------------------ -------- ---------- --- ---
AUD_ROLE_POL BY ALL USERS YES NO
AUD_DBA_POL BY ALL USERS YES NO

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 19
g. Perform an audit operation for both role type audited policies.
SQL> CONNECT jim
Enter password: ******
Connected.
SQL> CREATE TABLESPACE test DATAFILE '/tmp/test01.dbf' size 10m;

Tablespace created.

SQL> CONNECT dba_junior


Enter password: ******
Connected.
SQL> ALTER SYSTEM SET job_queue_processes=200;

System altered.

SQL> ALTER SYSTEM SET job_queue_processes=100;

System altered.

SQL>
h. View the resulting audit data.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> col dbusername format A10
SQL> col action_name format A18
SQL> col unified_audit_policies format a30
SQL> SELECT UNIFIED_AUDIT_POLICIES, DBUSERNAME,
ACTION_NAME, SYSTEM_PRIVILEGE_USED
FROM unified_audit_trail
WHERE DBUSERNAME in ('JIM','DBA_JUNIOR')
AND ACTION_NAME not in ('LOGON', 'LOGOFF')
AND (UNIFIED_AUDIT_POLICIES like '%AUD_ROLE_POL%'
OR UNIFIED_AUDIT_POLICIES like '%AUD_DBA_POL%');
2 3 4 5 6 7
UNIFIED_AUDIT_POLICIES DBUSERNAME ACTION_NAME
SYSTEM_PRIVILEGE_U
------------------------------ ---------- ------------------
------------------
rows deleted …

AUD_ROLE_POL, AUD_DBA_POL JIM CREATE TABLESPACE


CREATE TABLESPACE

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 20
ORA_SECURECONFIG, AUD_DBA_POL DBA_JUNIOR ALTER SYSTEM
ALTER SYSTEM

ORA_SECURECONFIG, AUD_DBA_POL DBA_JUNIOR ALTER SYSTEM


ALTER SYSTEM

SQL>
The first row displays AUD_ROLE_POL, AUD_DBA_POL in the UNIFIED_AUDIT_POLICIES.
Both policies track the CREATE TABLESPACE system privilege.
5. (Optional: if you skip this task, then go to practice 21-3) Create an audit policy that will audit
all users while using the STORAGE_ROLE role or performing any action related to tables.
a. Create a new role and grant this new role to DEV and grant DROP ANY TABLE to JIM.
SQL> CREATE ROLE storage_role;

Role created.

SQL> GRANT drop tablespace TO storage_role;

Grant succeeded.

SQL> GRANT storage_role TO dev;

Grant succeeded.

SQL> GRANT drop any table TO jim;

Grant succeeded.

SQL>
b. Create and enable the audit policy.
SQL> CREATE AUDIT POLICY aud_mixed_pol
ACTIONS create table, drop table, truncate table
ROLES storage_role;
2 3
Audit policy created.

SQL> AUDIT POLICY aud_mixed_pol;

Audit succeeded.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 21
c. Verify that the audit policy is enabled.
SQL> SELECT * FROM AUDIT_UNIFIED_ENABLED_POLICIES
WHERE POLICY_NAME like '%MIXED%';
2
USER_NAME POLICY_NAME ENABLED_ SUC FAI
---------- ------------------ -------- --- ---
ALL USERS AUD_MIXED_POL BY YES YES

SQL>
d. Perform operations.
SQL> CONNECT dev
Enter password: ******
Connected.
SQL> DROP TABLESPACE test including contents and datafiles;

Tablespace dropped.

SQL> CONNECT jim


Enter password: ******
Connected.
SQL> DROP TABLE hr.code purge;

Table dropped.

SQL>
e. View the resulting audit data.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> col unified_audit_policies format A44
SQL> SELECT UNIFIED_AUDIT_POLICIES, DBUSERNAME,
ACTION_NAME, SYSTEM_PRIVILEGE_USED
FROM unified_audit_trail
WHERE DBUSERNAME in ('JIM','DEV')
AND UNIFIED_AUDIT_POLICIES like '%AUD_MIXED_POL%'
AND ACTION_NAME not in ('LOGON', 'LOGOFF');
2 3 4 5 6

UNIFIED_AUDIT_POLICIES DBUSERNAME
ACTION_NAME SYSTEM_PRIVILEGE_U
-------------------------------------------- ----------
------------------ ------------------
AUD_MIXED_POL, ORA_SECURECONFIG, AUD_DBA_POL JIM
DROP TABLE DROP ANY TABLE
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 22
AUD_DBA_POL, AUD_MIXED_POL DEV
DROP TABLESPACE DROP TABLESPACE

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 23
Practice 21-3: Cleaning Up Audit Policies and Data
Overview
In this practice, you will drop the audit policies and the audit trail data.

Tasks
1. Drop the audit polices created in the previous practices.
a. Display the list of audit policies.
SQL> col policy_name FORMAT A30
SQL> SELECT distinct policy_name FROM AUDIT_UNIFIED_POLICIES;

POLICY_NAME
------------------------------
AUD_ROLE_POL
AUD_SYSPRIV_POL
ORA_RAS_POLICY_MGMT
ORA_DATABASE_PARAMETER
ORA_RAS_SESSION_MGMT
ORA_ACCOUNT_MGMT
AUD_ACTION_POL
AUD_MIXED_POL
AUD_DBA_POL
ORA_SECURECONFIG

10 rows selected.

SQL>
b. Drop each audit policy.
SQL> DROP AUDIT POLICY aud_role_pol;
DROP AUDIT POLICY aud_role_pol
*
ERROR at line 1:
ORA-46361: Audit policy cannot be dropped as it is currently
enabled.

SQL>
Notice that an enabled audit policy cannot be dropped. First disable it.
SQL> NOAUDIT POLICY aud_role_pol;

Noaudit succeeded.

SQL> DROP AUDIT POLICY aud_role_pol;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 24
Audit Policy dropped.

SQL> NOAUDIT POLICY aud_syspriv_pol;

Noaudit succeeded.

SQL> DROP AUDIT POLICY aud_syspriv_pol;

Audit Policy dropped.

SQL> NOAUDIT POLICY aud_action_pol;

Noaudit succeeded.

SQL> DROP AUDIT POLICY aud_action_pol;

Audit Policy dropped.

SQL> NOAUDIT POLICY aud_mixed_pol;

Noaudit succeeded.

SQL> DROP AUDIT POLICY aud_mixed_pol;

Audit Policy dropped.

SQL> NOAUDIT POLICY aud_dba_pol;

Noaudit succeeded.

SQL> DROP AUDIT POLICY aud_dba_pol;

Audit Policy dropped.

SQL>
2. Clean up the audit trail data.
a. You can perform the cleanup manually.
SQL> SELECT count(*) FROM unified_audit_trail;

COUNT(*)
----------
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 25
21163

SQL> exec DBMS_AUDIT_MGMT.SET_LAST_ARCHIVE_TIMESTAMP ( -


AUDIT_TRAIL_TYPE => DBMS_AUDIT_MGMT.AUDIT_TRAIL_UNIFIED, -
LAST_ARCHIVE_TIME => sysdate)
> >
PL/SQL procedure successfully completed.

SQL> exec DBMS_AUDIT_MGMT.CLEAN_AUDIT_TRAIL( -


AUDIT_TRAIL_TYPE => DBMS_AUDIT_MGMT.AUDIT_TRAIL_UNIFIED, -
USE_LAST_ARCH_TIMESTAMP => TRUE)
> >

The cleanup may last several minutes. If you attempt to connect as the SEC user or even
AS SYSDBA in another session, the session will be hanging until the cleanup process
completes. The audit is locked during the cleanup.
PL/SQL procedure successfully completed.

SQL> SELECT count(*) FROM unified_audit_trail;

COUNT(*)
----------
358

SQL>
b. You can also schedule the cleanup as follows.
SQL> exec DBMS_AUDIT_MGMT.CREATE_PURGE_JOB (-
AUDIT_TRAIL_TYPE=>DBMS_AUDIT_MGMT.AUDIT_TRAIL_UNIFIED, -
AUDIT_TRAIL_PURGE_INTERVAL => 1, -
AUDIT_TRAIL_PURGE_NAME => 'Audit_Trail_PJ', -
USE_LAST_ARCH_TIMESTAMP => TRUE)
> > > >
PL/SQL procedure successfully completed.

SQL>
c. View the cleanup job executions.
SQL> col JOB_NAME format A14
SQL> col STATUS format A12
SQL> col ACTUAL_START_DATE format A40

SQL> SELECT JOB_NAME, STATUS, ACTUAL_START_DATE


FROM dba_scheduler_job_run_details

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 26
WHERE JOB_NAME='AUDIT_TRAIL_PJ'
ORDER BY ACTUAL_START_DATE;
2 3 4
JOB_NAME STATUS ACTUAL_START_DATE
-------------- ------------ -----------------------------------
AUDIT_TRAIL_PJ SUCCEEDED 31-MAY-13 05.18.39.227394 AM ETC/UTC

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 27
Practice 21-4: Auditing SYS User (Optional)
Overview
In this practice, you will audit actions performed by the SYS user in orcl, which are not audited
by the ORA_SECURECONFIG predefined audit policy.

Tasks
1. Create and enable an audit policy that audits any update or select action on the
HR.EMPLOYEES table.
a. Still connected as the security officer, create, enable and display the audit policy that
audits any update action on the HR.EMPLOYEES table.
SQL> CREATE AUDIT POLICY aud_sys_pol
ACTIONS update ON hr.employees,
select ON hr.employees;
2 3
Audit policy created.

SQL> AUDIT POLICY aud_sys_pol BY sys WHENEVER SUCCESSFUL;

Audit succeeded.

SQL> SELECT * FROM AUDIT_UNIFIED_ENABLED_POLICIES


WHERE POLICY_NAME like '%SYS%';
2
USER_NAME POLICY_NAME ENABLED_ SUC FAI
----------- ------------------- -------- --- ---
SYS AUD_SYS_POL BY YES NO

SQL>
b. Connect as SYS and execute an update command and a select command on the
HR.EMPLOYEES table.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> UPDATE hr.employees SET salary=salary+100
WHERE last_name='Me';
2
0 rows updated.

SQL> SELECT max(salary) FROM hr.employees;

MAX(SALARY)
-----------
24000
SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 28
c. Connect as the security officer to display the audited actions.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> col dbusername format A10
SQL> col action_name format A12
SQL> col system_privilege_used FORMAT A30
SQL> col object_name format A10
SQL> SELECT dbusername, action_name, object_name,
system_privilege_used, unified_audit_policies
FROM unified_audit_trail
WHERE UNIFIED_AUDIT_POLICIES like '%AUD_SYS_POL%'
AND ACTION_NAME not in ('LOGON', 'LOGOFF');
2 3 4 5
DBUSERNAME ACTION_NAME OBJECT_NAM SYSTEM_PRIVILEGE_USED
---------- ------------ ---------- -----------------------
UNIFIED_AUDIT_POLICIES
------------------------------
SYS SELECT EMPLOYEES SYSDBA
AUD_SYS_POL

SYS SELECT EMPLOYEES SYSDBA, SELECT ANY TABLE


AUD_SYS_POL

SYS UPDATE EMPLOYEES SYSDBA


AUD_SYS_POL

SQL>
2. Drop the audit policy.
SQL> NOAUDIT POLICY aud_sys_pol BY sys;

Noaudit succeeded.

SQL> DROP AUDIT POLICY aud_sys_pol;

Audit Policy dropped.

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 29
Practice 21-5: Auditing Data Pump Export (Optional)
Overview
In this practice, you create audit policies to audit Data Pump export operations in pdb1_1 and
import operations in pdb1_2. Then you will view the audited data after the exports and imports
completed.

Assumptions
Practice 21-1 successfully enabled unified audit.

Tasks
1. In pdb1_1, create a DP_PDB1_1_POL for the component Data Pump, and more
specifically for export operations.
a. Connect as the security officer in PDB1_1. If the security officer, the C##SEC user does
not exist in the pluggable databases, create the user. Use the following commands.
$ cd $HOME/labs/USERS
$ . oraenv
ORACLE_SID = [orcl] ? cdb1
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as sysdba

Connected to an idle instance.

SQL> STARTUP
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2290024 bytes
Variable Size 268439192 bytes
Database Buffers 222298112 bytes
Redo Buffers 8032256 bytes
Database mounted.
Database opened.
SQL>
SQL> EXIT
$
$ ./create_sec_cdb.sh

SQL*Plus: Release 12.1.0.1.0 Production on Tue Jun 18 11:00:11


2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.


Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 30
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics,
Real Application Testing and Unified Auditing options

SQL> DROP USER c##sec CASCADE;


DROP USER c##sec CASCADE
*
ERROR at line 1:
ORA-01918: user 'C##SEC' does not exist

SQL> CREATE USER c##sec IDENTIFIED BY oracle_4sec


2 DEFAULT TABLESPACE USERS
3 QUOTA UNLIMITED ON USERS CONTAINER=ALL;

User created.

SQL>
SQL> GRANT create session
2 TO c##sec
3 WITH ADMIN OPTION CONTAINER=ALL;

Grant succeeded.

SQL>
SQL> GRANT select_catalog_role, select any table,
2 create any context, drop any context,
3 create user, alter user, drop user,
4 create role, alter any role, drop any role,
5 create table, create procedure,
6 create any trigger, administer database trigger,
7 create any directory, alter profile, create profile,
8 drop profile, audit system, alter system,
9 grant any object privilege, grant any privilege,
10 grant any role
11 TO c##sec
12 CONTAINER=ALL;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 31
Grant succeeded.

SQL>
SQL> GRANT execute on DBMS_SESSION to c##sec CONTAINER=ALL;

Grant succeeded.

SQL> GRANT execute on UTL_FILE to c##sec CONTAINER=ALL;

Grant succeeded.

SQL> GRANT audit_admin TO c##sec CONTAINER=ALL;

Grant succeeded.

SQL> EXIT
$
b. Create the DP_PDB1_1_POL audit policy in pdb1_1, to audit export operations for
the component Data Pump .
$ sqlplus c##sec@pdb1_1

Enter password: ******


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Real Application Testing and Unified Auditing options

SQL> create audit policy DP_PDB1_1_POL actions


COMPONENT=datapump export;

Audit policy created.

SQL>
c. Enable the export audit policy.
SQL> audit policy DP_PDB1_1_POL;

Audit succeeded.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 32
d. Verify that the policy exists.
SQL> col user_name format A10
SQL> col policy_name format A20
SQL> SELECT * FROM AUDIT_UNIFIED_ENABLED_POLICIES
where POLICY_NAME like '%DP%';

USER_NAME POLICY_NAME ENABLED_ SUC FAI


---------- -------------------- -------- --- ---
ALL USERS DP_PDB1_1_POL BY YES YES

SQL>
e. Create a directory for export operations.
SQL> CREATE DIRECTORY exp_dir AS
'/u01/app/oracle/admin/cdb1/dpdump';

Directory created.

SQL> GRANT read, write ON DIRECTORY exp_dir TO system;

Grant succeeded.

SQL> exit
$
f. Perform an export operation. Before exporting, ensure that the dump file does not
exist; else, the export command will fail.
$ expdp system@pdb1_1 dumpfile=HR_tables tables=HR.EMPLOYEES
DIRECTORY=exp_dir REUSE_DUMPFILES=YES

Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Real Application Testing
and Unified Auditing options
Starting "SYSTEM"."SYS_EXPORT_TABLE_01":
system/********@localhost:1521/pdb1_1 dumpfile=HR_tables
tables=HR.EMPLOYEES DIRECTORY=exp_dir REUSE_DUMPFILES=YES
Estimate in progress using BLOCKS method...
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Total estimation using BLOCKS method: 64 KB
Processing object type TABLE_EXPORT/TABLE/TABLE

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 33
Processing object type
TABLE_EXPORT/TABLE/GRANT/OWNER_GRANT/OBJECT_GRANT
Processing object type TABLE_EXPORT/TABLE/COMMENT
Processing object type TABLE_EXPORT/TABLE/INDEX/INDEX
Processing object type TABLE_EXPORT/TABLE/CONSTRAINT/CONSTRAINT
Processing object type
TABLE_EXPORT/TABLE/INDEX/STATISTICS/INDEX_STATISTICS
Processing object type
TABLE_EXPORT/TABLE/CONSTRAINT/REF_CONSTRAINT
Processing object type TABLE_EXPORT/TABLE/TRIGGER
Processing object type
TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
Processing object type TABLE_EXPORT/TABLE/STATISTICS/MARKER
Processing object type
TABLE_EXPORT/TABLE/POST_INSTANCE/PROCACT_INSTANCE
. . exported "HR"."EMPLOYEES" 17.06
KB 107 rows
Master table "SYSTEM"."SYS_EXPORT_TABLE_01" successfully
loaded/unloaded
****************************************************************
**************
Dump file set for SYSTEM.SYS_EXPORT_TABLE_01 is:
/u01/app/oracle/admin/cdb1/dpdump/HR_tables.dmp
Job "SYSTEM"."SYS_EXPORT_TABLE_01" successfully completed at Sat
Jun 1 23:19:14 2013 elapsed 0 00:00:25

$
g. View the resulting audit data.
$ sqlplus c##sec@pdb1_1

Enter password : ******


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Real Application Testing and Unified Auditing options

SQL> set pages 100


SQL> select DBUSERNAME, DP_TEXT_PARAMETERS1,
DP_BOOLEAN_PARAMETERS1, UNIFIED_AUDIT_POLICIES
from UNIFIED_AUDIT_TRAIL
where DP_TEXT_PARAMETERS1 is not null;

DBUSERNAME

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 34
------------------------------
DP_TEXT_PARAMETERS1
---------------------------------------------------------------
DP_BOOLEAN_PARAMETERS1
---------------------------------------------------------------
UNIFIED_AUDIT_POLICIES
---------------------------------------------------------------
SYSTEM
MASTER TABLE: "SYSTEM"."SYS_EXPORT_TABLE_01" , JOB_TYPE:
EXPORT, METADATA_JOB_M
ODE: TABLE_EXPORT, JOB VERSION: 12.1.0.0.0, ACCESS METHOD:
AUTOMATIC, DATA OPTIO
NS: 0, DUMPER DIRECTORY: NULL REMOTE LINK: NULL, TABLE EXISTS:
NULL, PARTITION
OPTIONS: NONE
MASTER_ONLY: FALSE, DATA_ONLY: FALSE, METADATA_ONLY: FALSE,
DUMPFILE_PRESENT: TR
UE, JOB_RESTARTED: FALSE

SQL> exit
$
2. In pdb1_2, create a DP_PDB1_2_POL for the component Data Pump, and more
specifically for import operations.
a. Connect as the security officer in PDB1_2 to create the DP_PDB1_2_POL audit
policy to audit import operations for the component Data Pump .
$ sqlplus c##sec@pdb1_2

Enter password : ******


Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Real Application Testing
and Unified Auditing options

SQL> create audit policy DP_PDB1_2_POL actions


COMPONENT=datapump import;

Audit policy created.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 35
b. Enable the export audit policy.
SQL> audit policy DP_PDB1_2_POL;

Audit succeeded.

SQL>
c. Verify that the policy exists.
SQL> col user_name format A10
SQL> col policy_name format A20
SQL> SELECT * FROM AUDIT_UNIFIED_ENABLED_POLICIES
where POLICY_NAME like '%DP%';
2
USER_NAME POLICY_NAME ENABLED_ SUC FAI
---------- -------------------- -------- --- ---
ALL USERS DP_PDB1_2_POL BY YES YES

SQL>
d. Create a directory for import operations.
SQL> CREATE DIRECTORY imp_dir AS
'/u01/app/oracle/admin/cdb1/dpdump';

Directory created.

SQL> GRANT read, write ON DIRECTORY imp_dir TO system;

Grant succeeded.

SQL> exit
$
e. Perform an import operation. Before importing, ensure that the dump file does not
exist; else, the import command will fail.
$ impdp system@pdb1_2 dumpfile=HR_tables tables=HR.EMPLOYEES
DIRECTORY=imp_dir

Password: ******

Connected to: Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Real Application Testing
and Unified Auditing options
Master table "SYSTEM"."SYS_IMPORT_TABLE_01" successfully
loaded/unloaded
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 36
Starting "SYSTEM"."SYS_IMPORT_TABLE_01":
system/********@localhost:1521/pdb1_2 dumpfile=HR_tables
tables=HR.EMPLOYEES DIRECTORY=imp_dir
Processing object type TABLE_EXPORT/TABLE/TABLE
ORA-39151: Table "HR"."EMPLOYEES" exists. All dependent metadata
and data will be skipped due to table_exists_action of skip
Processing object type TABLE_EXPORT/TABLE/TABLE_DATA
Processing object type
TABLE_EXPORT/TABLE/GRANT/OWNER_GRANT/OBJECT_GRANT
Processing object type TABLE_EXPORT/TABLE/COMMENT
Processing object type TABLE_EXPORT/TABLE/INDEX/INDEX
Processing object type TABLE_EXPORT/TABLE/CONSTRAINT/CONSTRAINT
Processing object type
TABLE_EXPORT/TABLE/INDEX/STATISTICS/INDEX_STATISTICS
Processing object type
TABLE_EXPORT/TABLE/CONSTRAINT/REF_CONSTRAINT
Processing object type TABLE_EXPORT/TABLE/TRIGGER
Processing object type
TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS
Processing object type TABLE_EXPORT/TABLE/STATISTICS/MARKER
Job "SYSTEM"."SYS_IMPORT_TABLE_01" completed with 1 error(s) at
Sat Jun 1 23:30:55 2013 elapsed 0 00:00:06

$
f. View the resulting audit data.
$ sqlplus c##sec@pdb1_2
Enter password : ******
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Real Application Testing and Unified Auditing options

SQL> set pages 100


SQL> select DBUSERNAME, DP_TEXT_PARAMETERS1,
DP_BOOLEAN_PARAMETERS1, UNIFIED_AUDIT_POLICIES
from UNIFIED_AUDIT_TRAIL
where DP_TEXT_PARAMETERS1 is not null;
2 3 4
DBUSERNAME
------------------------------
DP_TEXT_PARAMETERS1
---------------------------------------------------------------
DP_BOOLEAN_PARAMETERS1
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 37
---------------------------------------------------------------
UNIFIED_AUDIT_POLICIES
---------------------------------------------------------------
SYSTEM
MASTER TABLE: "SYSTEM"."SYS_IMPORT_TABLE_01" , JOB_TYPE:
IMPORT, METADATA_JOB_M
ODE: TABLE_EXPORT, JOB VERSION: 12.1.0.0.0, ACCESS METHOD:
AUTOMATIC, DATA OPTIO
NS: 0, DUMPER DIRECTORY: NULL REMOTE LINK: NULL, TABLE EXISTS:
SKIP, PARTITION
OPTIONS: NONE
MASTER_ONLY: FALSE, DATA_ONLY: FALSE, METADATA_ONLY: FALSE,
DUMPFILE_PRESENT: TR
UE, JOB_RESTARTED: FALSE

SQL>
3. View all export and import audited operations performed in cdb1.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> set pages 100
SQL> select DBUSERNAME, DP_TEXT_PARAMETERS1,
DP_BOOLEAN_PARAMETERS1, UNIFIED_AUDIT_POLICIES
from UNIFIED_AUDIT_TRAIL
where DP_TEXT_PARAMETERS1 is not null;
2 3 4

no rows selected

SQL>
Notice that there are no rows displayed. The UNIFIED_AUDIT_TRAIL displays the audited
data for the current container, the root container in this case.
SQL> select DBUSERNAME, DP_TEXT_PARAMETERS1,
DP_BOOLEAN_PARAMETERS1,
UNIFIED_AUDIT_POLICIES, CON_ID
from CDB_UNIFIED_AUDIT_TRAIL
where DP_TEXT_PARAMETERS1 is not null;
2 3 4 5
DBUSERNAME
------------------------------
DP_TEXT_PARAMETERS1
---------------------------------------------------------------
DP_BOOLEAN_PARAMETERS1
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 38
---------------------------------------------------------------
UNIFIED_AUDIT_POLICIES
---------------------------------------------------------------
CON_ID
----------
SYSTEM
MASTER TABLE: "SYSTEM"."SYS_IMPORT_TABLE_01" , JOB_TYPE:
IMPORT, METADATA_JOB_M
ODE: TABLE_EXPORT, JOB VERSION: 12.1.0.0.0, ACCESS METHOD:
AUTOMATIC, DATA OPTIO
NS: 0, DUMPER DIRECTORY: NULL REMOTE LINK: NULL, TABLE EXISTS:
SKIP, PARTITION
OPTIONS: NONE
MASTER_ONLY: FALSE, DATA_ONLY: FALSE, METADATA_ONLY: FALSE,
DUMPFILE_PRESENT: TR
UE, JOB_RESTARTED: FALSE

SYSTEM
MASTER TABLE: "SYSTEM"."SYS_EXPORT_TABLE_01" , JOB_TYPE:
EXPORT, METADATA_JOB_M
ODE: TABLE_EXPORT, JOB VERSION: 12.1.0.0.0, ACCESS METHOD:
AUTOMATIC, DATA OPTIO
NS: 0, DUMPER DIRECTORY: NULL REMOTE LINK: NULL, TABLE EXISTS:
NULL, PARTITION
OPTIONS: NONE
MASTER_ONLY: FALSE, DATA_ONLY: FALSE, METADATA_ONLY: FALSE,
DUMPFILE_PRESENT: TR
UE, JOB_RESTARTED: FALSE

SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 39
Practice 21-6: Auditing RMAN Backups
In this practice, you perform RMAN backups for the orcl database. Then you will view the
audited data after RMAN backups are completed. You do not have to create any audit policy for
RMAN operations. RMAN is by default audited.

Assumptions
Practice 21-1 successfully enabled unified audit.

Tasks
1. Perform a RMAN backup of the USERS tablespace.
a. If the keystore is not opened, you will encounter the following errors ORA-19914:
unable to encrypt backup and ORA-28365: wallet is not open. In this
case, first open the keystore.
$ . oraenv
ORACLE_SID = [cdb1] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus / as syskm

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> ADMINISTER KEY MANAGEMENT SET KEYSTORE OPEN


IDENTIFIED BY secret;
2
keystore altered.

SQL> exit
$
b. Perform the backup.
$ rman target /

connected to target database: ORCL (DBID=1315477536)

RMAN> backup tablespace USERS;

Starting backup at 02-JUN-13


using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 40
channel ORA_DISK_1: SID=366 device type=DISK
channel ORA_DISK_1: starting full datafile backup set
channel ORA_DISK_1: specifying datafile(s) in backup set
input datafile file number=00006
name=/u01/app/oracle/oradata/orcl/users01.dbf
channel ORA_DISK_1: starting piece 1 at 02-JUN-13
channel ORA_DISK_1: finished piece 1 at 02-JUN-13
piece
handle=/u01/app/oracle/fast_recovery_area/ORCL/backupset/2013_06
_02/o1_mf_nnndf_TAG20130602T083703_8tp11jsx_.bkp
tag=TAG20130602T083703 comment=NONE
channel ORA_DISK_1: backup set complete, elapsed time: 00:00:04
Finished backup at 02-JUN-13
RMAN> exit

Recovery Manager complete.


$
2. Perform a restore and recover after removing the USERS tablespace file.
a. Find the data file name of the USERS tablespace and remove the file.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Real Application Testing and Unified Auditing options

SQL> select name from v$datafile;

NAME
--------------------------------------------------------------
/u01/app/oracle/oradata/orcl/system01.dbf
/u01/app/oracle/oradata/orcl/example01.dbf
/u01/app/oracle/oradata/orcl/sysaux01.dbf
/u01/app/oracle/oradata/orcl/undotbs01.dbf
/u01/app/oracle/oradata/orcl/enctbs01.dbf
/u01/app/oracle/oradata/orcl/users01.dbf

6 rows selected.

SQL> !rm /u01/app/oracle/oradata/orcl/users01.dbf

SQL>
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 41
b. Put the tablespace OFFLINE.
SQL> alter tablespace users offline immediate;

Tablespace altered.

SQL> exit
$
c. Restore and recover the data file.
$ rman target /

connected to target database: ORCL (DBID=1315477536)

RMAN> restore tablespace USERS;

Starting restore at 02-JUN-13


using target database control file instead of recovery catalog
allocated channel: ORA_DISK_1
channel ORA_DISK_1: SID=130 device type=DISK

channel ORA_DISK_1: starting datafile backup set restore


channel ORA_DISK_1: specifying datafile(s) to restore from
backup set
channel ORA_DISK_1: restoring datafile 00006 to
/u01/app/oracle/oradata/orcl/users01.dbf
channel ORA_DISK_1: reading from backup piece
/u01/app/oracle/fast_recovery_area/ORCL/backupset/2013_06_02/o1_
mf_nnndf_TAG20130602T083703_8tp11jsx_.bkp
channel ORA_DISK_1: piece
handle=/u01/app/oracle/fast_recovery_area/ORCL/backupset/2013_06
_02/o1_mf_nnndf_TAG20130602T083703_8tp11jsx_.bkp
tag=TAG20130602T083703
channel ORA_DISK_1: restored backup piece 1
channel ORA_DISK_1: restore complete, elapsed time: 00:00:01
Finished restore at 02-JUN-13

RMAN> recover tablespace USERS;

Starting recover at 02-JUN-13


using channel ORA_DISK_1

starting media recovery


media recovery complete, elapsed time: 00:00:01

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 42
Finished recover at 02-JUN-13

RMAN> exit
$
d. Put the tablespace USERS back online.
$ sqlplus system
Enter password: ******

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics, Real Application Testing and Unified Auditing options

SQL> alter tablespace USERS online;

Tablespace altered.

SQL>
3. View the resulting audit data.
SQL> select DBUSERNAME, RMAN_OPERATION
from UNIFIED_AUDIT_TRAIL
where RMAN_OPERATION is not null;
2 3
DBUSERNAME RMAN_OPERATION
------------------------------ --------------------
SYS Recover
SYS Restore
SYS Backup

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 43
Practice 21-7: Auditing Database Vault Violations (Optional)
Overview
In this practice, you will create an audit policy auditing actions using a Database Vault realm
that protects the HR.EMPLOYEES and HR.DEPARTMENTS tables from system privileged users.

Assumptions
Database Vault has been successfully configured in practice 3-7.

Tasks
1. Reenable Database Vault and create the Database Vault “HR Application” realm, to
protect the HR.EMPLOYEES and HR.DEPARTMENTS tables from system privileged users.
a. Use the $HOME/labs/AUDIT/audit_dv.sql script.
SQL> @$HOME/labs/AUDIT/audit_dv.sql
SQL> connect sec_admin/oracle_4U
Connected.
SQL> exec DVSYS.DBMS_MACADM.ENABLE_DV

PL/SQL procedure successfully completed.

SQL> set echo on


SQL> EXEC DVSYS.DBMS_MACADM.DELETE_REALM(realm_name => 'HR
Application')
BEGIN DVSYS.DBMS_MACADM.DELETE_REALM(realm_name => 'HR
Application'); END;

*
ERROR at line 1:
ORA-47241: Realm HR Application not found
ORA-06512: at "DVSYS.DBMS_MACADM", line 1847
ORA-06512: at line 1

SQL> BEGIN
2 DVSYS.DBMS_MACADM.CREATE_REALM(
3 realm_name => 'HR Application',
4 description => 'Realm to protect the HR application',
5 enabled => DBMS_MACUTL.G_YES,
6 audit_options => DBMS_MACUTL.G_REALM_AUDIT_FAIL +
DBMS_MACUTL.G_REALM_AUDIT_SUCCESS,
7 realm_type => 1);
8 END;
9 /

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 44
PL/SQL procedure successfully completed.

SQL>
SQL> BEGIN
2 DVSYS.DBMS_MACADM.ADD_OBJECT_TO_REALM(
3 realm_name => 'HR Application',
4 object_owner => 'HR',
5 object_name => 'EMPLOYEES',
6 object_type => 'TABLE');
7 END;
8 /

PL/SQL procedure successfully completed.

SQL> BEGIN
2 DVSYS.DBMS_MACADM.ADD_OBJECT_TO_REALM(
3 realm_name => 'HR Application',
4 object_owner => 'HR',
5 object_name => 'DEPARTMENTS',
6 object_type => 'TABLE');
7 END;
8 /

PL/SQL procedure successfully completed.

SQL>
b. Restart the database instance.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> SHUTDOWN IMMEDIATE
Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> STARTUP
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2289400 bytes
Variable Size 297795848 bytes
Database Buffers 192937984 bytes
Redo Buffers 8036352 bytes
Database mounted.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 45
Database opened.
SQL>
2. Create and enable an audit policy that audits any violation against the Database Vault “HR
Application” realm created by the $HOME/labs/AUDIT/audit_dv.sql script.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> CREATE AUDIT POLICY aud_DV_pol ACTIONS
COMPONENT = dv realm violation on "HR Application";
2
Audit policy created.

SQL> AUDIT POLICY aud_DV_pol;

Audit succeeded.

SQL>
3. Connect as a privileged user attempting to update rows in the HR.EMPLOYEES table.
SQL> CONNECT system
Enter password: ******
Connected.
SQL> UPDATE hr.employees SET salary=salary+100;
UPDATE hr.employees SET salary=salary+100
*
ERROR at line 1:
ORA-01031: insufficient privileges
SQL>
4. View the audited data related to the realm violation.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> COL dbusername FORMAT A8
SQL> COL DV_ACTION_NAME FORMAT A22
SQL> COL DV_ACTION_OBJECT_NAME FORMAT A16
SQL> select DBUSERNAME, DV_ACTION_NAME, DV_RETURN_CODE,
DV_ACTION_OBJECT_NAME
from UNIFIED_AUDIT_TRAIL
where DV_ACTION_NAME is not null;
DBUSERNA DV_ACTION_NAME DV_RETURN_CODE DV_ACTION_OBJECT
-------- ---------------------- -------------- ----------------
… rows deleted

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 46
SYSTEM Realm Violation Audit 1031 HR Application

… rows deleted

SQL>
5. Disable and drop the audit policy.
SQL> NOAUDIT POLICY aud_DV_pol;

Noaudit succeeded.

SQL> DROP AUDIT POLICY aud_DV_pol;

Audit Policy dropped.

SQL> EXIT
$
6. Run the DV_drop_realm.sh script to remove the Database Vault protection on the
HR.EMPLOYEES and HR.DEPARTMENTS tables.
$ $HOME/labs/DV/DV_drop_realm.sh

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics,
Oracle Database Vault and Real Application Testing options

PL/SQL procedure successfully completed.


$
7. Run the DV_disable.sh script to disable Database Vault in the database.
$ $HOME/labs/DV/DV_disable.sh
SQL*Plus: Release 12.1.0.1.0 Production on Sun Jun 2 12:09:07
2013

Copyright (c) 1982, 2013, Oracle. All rights reserved.

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics,

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 47
Oracle Database Vault, Real Application Testing and Unified
Auditing options

Connected.

PL/SQL procedure successfully completed.

Disconnected from Oracle Database 12c Enterprise Edition Release


12.1.0.1.0 - 64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics,
Oracle Database Vault, Real Application Testing and Unified
Auditing options
$
8. Restart the database instance.
$ sqlplus / as sysdba

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> SHUTDOWN IMMEDIATE


Database closed.
Database dismounted.
ORACLE instance shut down.
SQL> STARTUP
ORACLE instance started.

Total System Global Area 501059584 bytes


Fixed Size 2289400 bytes
Variable Size 264241416 bytes
Database Buffers 226492416 bytes
Redo Buffers 8036352 bytes
Database mounted.
Database opened.
SQL> EXIT
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 21: Using Unified Auditing


Chapter 21 - Page 48
Practices for Lesson 22:
Using Fine-Grained Audit
Chapter 22

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 1
Practice 22-1: Implementing Fine-Grained Auditing
Overview
There is a business requirement that a record must be logged whenever employee salary
information is accessed. The execution of INSERT, UPDATE, and DELETE commands is
recorded in a journal table by the use of triggers. Create a proof of concept solution for SELECT
accesses. Create a user PFAY, and prove that SELECT accesses will be recorded. Execute a
practice script to create a procedure called SEC.LOG_EMPS_SALARY. This procedure inserts a
record in the SEC.TEST_AUDIT_PROC table to demonstrate that additional audit information
can be captured and stored.
Assumptions: This solution depends on step 1 of Practice 4-1. The SEC user must exist and
the password of the SEC user is oracle_4sec and the password of the HR user is oracle_4U
by these previous practices.

Task
1. As the SEC user, create the PFAY user and grant SELECT access to the HR.EMPLOYEES
table to PFAY.
Create the PFAY user with the password oracle_4U.
Grant PFAY the required access.
Because SEC has been granted GRANT ANY OBJECT PRIVILEGE, the SEC user may grant
SELECT on HR.EMPLOYEES.
$ . oraenv
ORACLE_SID = [orcl] ? orcl
The Oracle base for
ORACLE_HOME=/u01/app/oracle/product/12.1.0/dbhome_1 is
/u01/app/oracle
$ sqlplus sec
Enter password: ******

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 -
64bit Production
With the Partitioning, Oracle Label Security, OLAP, Advanced
Analytics and Real Application Testing options

SQL> DROP USER pfay;

User dropped.

SQL> GRANT create session TO pfay IDENTIFIED BY oracle_4U;

Grant succeeded.

SQL> GRANT select ON hr.employees TO pfay;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 2
Grant succeeded.

SQL>
2. Ensure that EXAMPLE is the default tablespace for the SEC user and that SEC has the ability
to create objects in the EXAMPLE tablespace. Because SEC has been granted ALTER USER,
the SEC user may alter his or her own account settings.
Note: Every user may change his or her password.
SQL> ALTER USER sec
DEFAULT TABLESPACE example
QUOTA UNLIMITED ON example;
2 3
User altered.

SQL>
3. Enable the SEC user to execute the DBMS_FGA package. The SEC user cannot grant
privileges on objects owned by SYS.
SQL> CONNECT / AS SYSDBA
Connected.
SQL> GRANT execute ON dbms_fga TO sec;

Grant succeeded.

SQL>
4. As the SEC user, create an FGA policy with the following properties:
Object: HR.EMPLOYEES
Name: AUDIT_EMPS_SALARY
Audits: Any access to the SALARY column
Policy: Enabled
SQL> connect sec
Enter password: ******
Connected.
SQL>
SQL> BEGIN
dbms_fga.add_policy (
object_schema => 'hr',
object_name => 'employees',
policy_name => 'audit_emps_salary',
audit_condition => NULL,
audit_column => 'salary',
enable => TRUE );
END;

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 3
/
2 3 4 5 6 7 8 9 10
PL/SQL procedure successfully completed.

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 4
Practice 22-2: Viewing the FGA Trail
Overview
In this practice, you view the fine-grained audit results.

Tasks
1. As the PFAY user, select SALARY from the HR.EMPLOYEES table. Save this statement as
list.sql because you will execute it again.
SQL> CONNECT pfay
Enter password: ******
Connected.
SQL>
SQL> SELECT salary FROM hr.employees;

SALARY
----------
24000
17000
17000
9000
6000
4800
4800
… Rows deleted …
6500
10000
12000
8300

83 rows selected.

SQL> save /home/oracle/labs/list.sql replace


Wrote file /home/oracle/labs/list.sql
SQL>
2. As the SEC user, display the audit record from the previous SELECT statement. Use
$HOME/labs/FGA/view.sql.
Note: The time stamp that is shown is the time when step 1 was executed.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> @$HOME/labs/FGA/view.sql
SQL> COL timestamp FORMAT A10
SQL> COL db_user FORMAT A7
SQL> COL object_schema FORMAT A15
SQL> COL object_name FORMAT A12

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 5
SQL> COL policy_name FORMAT A20
SQL> COL sql_bind FORMAT A10
SQL> COL sql_text FORMAT A32
SQL> COL dbusername FORMAT A10
SQL> COL fga_policy_name FORMAT A18
SQL>
SQL> SET PAGESIZE 40
SQL> SET LINESIZE 56
SQL>
SQL> SELECT to_char(timestamp, 'YYMMDDHH24MI') AS timestamp,
2 db_user,
3 object_schema,
4 object_name,
5 policy_name,
6 sql_bind,
7 sql_text
8 FROM dba_fga_audit_trail;

no rows selected

SQL>
SQL> SELECT to_char(event_timestamp, 'YYMMDDHH24MI') AS
timestamp,
2 dbusername,
3 fga_policy_name,
4 sql_text
5 FROM unified_audit_trail
6 WHERE fga_policy_name = 'AUDIT_EMPS_SALARY';

TIMESTAMP DBUSERNAME FGA_POLICY_NAME


---------- ---------- ------------------
SQL_TEXT
--------------------------------
1306030211 PFAY AUDIT_EMPS_SALARY
SELECT salary FROM hr.employees

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 6
Practice 22-3: Using an Event Handler
Overview
In this practice, you will create an FGA policy with an event handler triggered to capture
additional information.

Tasks
1. Review and then execute $HOME/labs/FGA/test_audit_proc.sql, which creates a
table to store audit records and creates a procedure to store audit events in that table. The
script creates the TEST_AUDIT_PROC table and the LOG_EMPS_SALARY procedure. The
procedure captures additional information and inserts it into the table. It is important to
capture enough information in the table to be able to relate this record back to a single FGA
audit record.
SQL> @$HOME/labs/FGA/test_audit_proc.sql
SQL> SET ECHO OFF
SQL>
SQL> CONNECT sec/oracle_4sec
Connected.
SQL>
SQL> DROP TABLE sec.test_audit_proc;

DROP TABLE sec.test_audit_proc


*
ERROR at line 1:
ORA-00942: table or view does not exist

SQL>
SQL> CREATE TABLE sec.test_audit_proc (
2 object_schema VARCHAR2(80),
3 object_name VARCHAR2(80),
4 policy_name VARCHAR2(80),
5 session_id NUMBER,
6 timestamp DATE,
7 audit_entry_id NUMBER );

Table created.

SQL>
SQL> DROP PROCEDURE sec.log_emps_salary;

DROP PROCEDURE sec.log_emps_salary


*
ERROR at line 1:
ORA-04043: object LOG_EMPS_SALARY does not exist
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 7
SQL>
SQL> CREATE PROCEDURE sec.log_emps_salary (
2 p_object_schema VARCHAR2,
3 p_object_name VARCHAR2,
4 p_policy_name VARCHAR2 )
5 AS
6 BEGIN
7 INSERT
8 INTO sec.test_audit_proc
9 (object_schema, object_name, policy_name, session_id,
10 timestamp)
11 VALUES (p_object_schema,
12 p_object_name,
13 p_policy_name,
14 SYS_CONTEXT('userenv', 'SESSIONID'),
15 systimestamp);
16 END;
17 /

Procedure created.

SQL>
2. Drop the FGA policy and re-create it so that it calls the procedure created in the previous
step.
SQL> BEGIN
dbms_fga.drop_policy (
object_schema => 'hr',
object_name => 'employees',
policy_name => 'audit_emps_salary' );

dbms_fga.add_policy (
object_schema => 'hr',
object_name => 'employees',
policy_name => 'audit_emps_salary',
audit_condition => NULL,
audit_column => 'salary',
handler_schema => 'sec',
handler_module => 'log_emps_salary',
enable => TRUE );
END;
/

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 8
2 3 4 5 6 7 8 9 10 11 12 13 14
15 16 17
PL/SQL procedure successfully completed.

SQL>
3. As the PFAY user, select SALARY from the HR.EMPLOYEES table.
SQL> CONNECT pfay
Enter password: ******
Connected.
SQL> SELECT salary FROM hr.employees;

SALARY
----------
24000
17000
17000
9000
… Rows deleted …
2600
4400
13000
6000
6500
10000
12000
8300

83 rows selected.

SQL>
4. As the SEC user, display the audit record from the previous SELECT statement. Use the
same script that you used in practice 22-2 step 2, $HOME/labs/FGA/view.sql.
SQL> CONNECT sec
Enter password: ******
Connected.
SQL> @$HOME/labs/FGA/view.sql
SQL>
SQL> COL timestamp FORMAT A10
SQL> COL db_user FORMAT A7
SQL> COL object_schema FORMAT A15
SQL> COL object_name FORMAT A12
SQL> COL policy_name FORMAT A20

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 9
SQL> COL sql_bind FORMAT A10
SQL> COL sql_text FORMAT A32
SQL> COL dbusername FORMAT A10
SQL> COL fga_policy_name FORMAT A18
SQL>
SQL> SET PAGESIZE 40
SQL> SET LINESIZE 56
SQL>
SQL> SELECT to_char(timestamp, 'YYMMDDHH24MI') AS timestamp,
2 db_user,
3 object_schema,
4 object_name,
5 policy_name,
6 sql_bind,
7 sql_text
8 FROM dba_fga_audit_trail;

no rows selected

SQL>
SQL> SELECT to_char(event_timestamp, 'YYMMDDHH24MI') AS
timestamp,
2 dbusername,
3 fga_policy_name,
4 sql_text
5 FROM unified_audit_trail
6 WHERE fga_policy_name = 'AUDIT_EMPS_SALARY';

TIMESTAMP DBUSERNAME FGA_POLICY_NAME


---------- ---------- ------------------
SQL_TEXT
--------------------------------
1306030225 PFAY AUDIT_EMPS_SALARY
SELECT salary FROM hr.employees

1306030211 PFAY AUDIT_EMPS_SALARY


SELECT salary FROM hr.employees

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 10
5. Verify that the audit handler created a row in the TEST_AUDIT_PROC table.
SQL> SELECT object_schema,
object_name,
policy_name
FROM test_audit_proc;

OBJECT_SCHEM OBJECT_NAM POLICY_NAME


------------ ---------- --------------------
HR EMPLOYEES AUDIT_EMPS_SALARY

SQL>
6. As SEC, display the audit policy information from the data dictionary.
SQL> COLUMN pf_schema FORMAT A10
SQL> COLUMN pf_package FORMAT A12
SQL> COLUMN pf_function FORMAT A20
SQL>
SQL> SELECT * FROM dba_audit_policies;

OBJECT_SCHEMA OBJECT_NAM POLICY_OWNER


-------------- ---------- ------------------------------
POLICY_NAME POLICY_TEXT POLICY_COLUMN
-------------------- -------------------- --------------
PF_SCHEMA PF_PACKAGE PF_FUNCTION ENA SEL INS
---------- ------------ -------------------- --- --- ---
UPD DEL AUDIT_TRAIL POLICY_COLU
--- --- ------------ -----------
HR EMPLOYEES SEC
AUDIT_EMPS_SALARY SALARY
SEC LOG_EMPS_SALARY YES YES NO
NO NO DB+EXTENDED ANY_COLUMNS

SQL>

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 11
7. Drop the FGA policy.
SQL> EXEC dbms_fga.drop_policy (-
object_schema => 'hr', -
object_name => 'employees', -
policy_name => 'audit_emps_salary' )
> > >
PL/SQL procedure successfully completed.

SQL> exit
$

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Practices for Lesson 22: Using Fine-Grained Audit


Chapter 22 - Page 12
Appendix E: Source Code
Chapter 23

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix E: Source Code


Chapter 23 - Page 1
Appendix E: Source Code

Source for PROXY_USER


#include <oci.h>
#include <stdio.h>

#define MAXTHREAD 10

static OCIError *errhp;


static OCIEnv *envhp;
static OCICPool *poolhp;

static int employeeNum[MAXTHREAD];

static OraText *poolName;


static sb4 poolNameLen;
static text *database;
static text *username;
static text *password;
static text *nullpassword =(text *)"";
static text *appusername =(text *)"HRAPP";
static text *apppassword =(text *)"HRAPP";

static ub4 conMin = 2;


static ub4 conMax = 5;
static ub4 conIncr = 1;

static void checkerr (OCIError *errhp, sword status);


static void threadFunction (dvoid *arg);

int main (ac, av)


unsigned ac;
char *av[];
{
unsigned ai;
int i = 0;
database = av[1];
username = av[2];

if (ac>3)
password = av[3];
else password = nullpassword;

printf("Database: %s\nUsername: %s\nPassword: %s\n", database,


username, password);

OCIEnvCreate (&envhp, OCI_THREADED, (dvoid *)0,


(dvoid *(*)()) 0,(dvoid * (*)()) 0,
(dvoid (*)()) 0, 0, (dvoid *)0);
...

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix E: Source Code


Chapter 23 - Page 2
Source for PROXY_USER (continued)
...
(void) OCIHandleAlloc((dvoid *) envhp, (dvoid **) &errhp,
OCI_HTYPE_ERROR,(size_t) 0, (dvoid **) 0);

(void) OCIHandleAlloc((dvoid *) envhp, (dvoid **) &poolhp,


OCI_HTYPE_CPOOL,(size_t) 0, (dvoid **) 0);

/* CREATE THE CONNECTION POOL */


checkerr (errhp, OCIConnectionPoolCreate(envhp,
errhp,poolhp, &poolName, &poolNameLen,
database,strlen(database),
conMin, conMax, conIncr,
appusername,strlen(appusername),
apppassword,
strlen(apppassword),OCI_DEFAULT));

printf("Successful connection: Username: %s\n", appusername);


/* Multiple threads using the connection pool */
{
OCIThreadId *thrid[MAXTHREAD];
OCIThreadHandle *thrhp[MAXTHREAD];

OCIThreadProcessInit ();
checkerr (errhp, OCIThreadInit (envhp, errhp));
for (i = 0; i < MAXTHREAD; ++i)
{
checkerr (errhp, OCIThreadIdInit(envhp, errhp,
&thrid[i]));
checkerr (errhp, OCIThreadHndInit(envhp, errhp,
&thrhp[i]));
}
for (i = 0; i < MAXTHREAD; ++i)
{
employeeNum[i]=i;
checkerr (errhp, OCIThreadCreate (envhp, errhp,
threadFunction, (dvoid *) &employeeNum[i], thrid[i],
thrhp[i]));
}
for (i = 0; i < MAXTHREAD; ++i)
...

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix E: Source Code


Chapter 23 - Page 3
Source for PROXY_USER (continued)
...
{
checkerr (errhp, OCIThreadJoin (envhp, errhp, thrhp[i]));
checkerr (errhp, OCIThreadClose (envhp, errhp, thrhp[i]));
checkerr (errhp, OCIThreadIdDestroy (envhp, errhp,
&(thrid[i])));
checkerr (errhp, OCIThreadHndDestroy (envhp, errhp,
&(thrhp[i])));
}
checkerr (errhp, OCIThreadTerm (envhp, errhp));
} /* ALL THE THREADS ARE COMPLETE */
checkerr(errhp, OCIConnectionPoolDestroy(poolhp, errhp,OCI_DEFAULT));
checkerr(errhp, OCIHandleFree((dvoid *)poolhp,
OCI_HTYPE_CPOOL));
checkerr(errhp, OCIHandleFree((dvoid *)errhp,
OCI_HTYPE_ERROR));
}
/* end of main () */

static void threadFunction (dvoid *arg)


{
int i, c;
int empno = *(int *)arg;
OCISvcCtx *svchp = (OCISvcCtx *) arg;
text insertst1[256];
OCIStmt *stmthp = (OCIStmt *)0;

sword status;

status = OCILogon2(envhp, errhp, &svchp,


(CONST OraText *)username, strlen(username),
(CONST OraText *)password, strlen(password),
(CONST OraText *)poolName, poolNameLen, OCI_CPOOL);

if (status == 0)
printf("Successful connection: Username: %s\n", username);
else checkerr(errhp,status);

...

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix E: Source Code


Chapter 23 - Page 4
Source for PROXY_USER (continued)
...
for (i=0; i < 1000; ++i) i=i;
/*
printf("Press any key to continue:");
c = getchar();

checkerr(errhp,OCILogon2(envhp, errhp, &svchp,


(CONST OraText *)username, strlen(username),
(CONST OraText *)password, strlen(password),
(CONST OraText *)poolName, poolNameLen, OCI_CPOOL));

sprintf(insertst1,"SET ROLE hr_emp_clerk");

OCIHandleAlloc(envhp, (dvoid **)&stmthp, OCI_HTYPE_STMT,


(size_t)0,(dvoid **)0);

checkerr(errhp, OCIStmtPrepare (stmthp, errhp,


(text *)insertst1,(ub4)strlen(insertst1),
OCI_NTV_SYNTAX, OCI_DEFAULT));

checkerr(errhp, OCIStmtExecute (svchp, stmthp, errhp, (ub4)1,


(ub4)0,(OCISnapshot *)0, (OCISnapshot *)0,
OCI_DEFAULT ));

checkerr(errhp, OCITransCommit(svchp,errhp,(ub4)0));

checkerr(errhp, OCIHandleFree((dvoid *) stmthp,


OCI_HTYPE_STMT));
*/
checkerr(errhp, OCILogoff((dvoid *) svchp, errhp));
} /* end of threadFunction (dvoid *) */

void checkerr(errhp, status)


OCIError *errhp;
sword status;
{
text errbuf[512];
sb4 errcode = 0;

switch (status)
{
case OCI_SUCCESS:
break;
case OCI_SUCCESS_WITH_INFO:
(void) printf("Error - OCI_SUCCESS_WITH_INFO\n");
break;

...

Source for PROXY_USER (continued)


...

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix E: Source Code


Chapter 23 - Page 5
case OCI_NEED_DATA:
(void) printf("Error - OCI_NEED_DATA\n");
break;
case OCI_NO_DATA:
(void) printf("Error - OCI_NODATA\n");
break;
case OCI_ERROR:
(void) OCIErrorGet((dvoid *)errhp, (ub4) 1, (text *) NULL,
&errcode, errbuf,(ub4) sizeof(errbuf),
OCI_HTYPE_ERROR);
(void) printf("Error - %.*s\n", 512, errbuf);
break;
case OCI_INVALID_HANDLE:
(void) printf("Error - OCI_INVALID_HANDLE\n");
break;

case OCI_STILL_EXECUTING:
(void) printf("Error - OCI_STILL_EXECUTE\n");
break;
case OCI_CONTINUE:
(void) printf("Error - OCI_CONTINUE\n");
break;
default:
break;
}
}

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix E: Source Code


Chapter 23 - Page 6
Source for PROXY_ROLE
#include <oci.h>
#include <stdio.h>

#define MAXTHREAD 10

static OCIError *errhp;


static OCIEnv *envhp;
static OCICPool *poolhp;

static int employeeNum[MAXTHREAD];

static OraText *poolName;


static sb4 poolNameLen;
static text *database;
static text *username;
static text *password;
static text *role;
static text *nullpassword =(text *)"";
static text *appusername =(text *)"HRAPP";
static text *apppassword =(text *)"HRAPP";

static ub4 conMin = 2;


static ub4 conMax = 5;
static ub4 conIncr = 1;

static void checkerr (OCIError *errhp, sword status);


static void threadFunction (dvoid *arg);

int main (ac, av)


unsigned ac;
char *av[];
{
unsigned ai;

int i = 0;
database = av[1];
role = av[2];
username = av[3];

if (ac>4)
password = av[4];
else password = nullpassword;

printf("Database: %s\nRole: %s\nUsername: %s\nPassword: %s\n",


database, role, username, password);

...

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix E: Source Code


Chapter 23 - Page 7
Source for PROXY_ROLE (continued)
...
OCIEnvCreate (&envhp, OCI_THREADED, (dvoid *)0,
(dvoid * (*)()) 0, (dvoid * (*)()) 0,
(dvoid (*)()) 0, 0, (dvoid *)0);

(void) OCIHandleAlloc((dvoid *) envhp, (dvoid **) &errhp,


OCI_HTYPE_ERROR,(size_t) 0, (dvoid **) 0);

(void) OCIHandleAlloc((dvoid *) envhp, (dvoid **) &poolhp,


OCI_HTYPE_CPOOL, (size_t) 0, (dvoid **) 0);

/* CREATE THE CONNECTION POOL */


checkerr (errhp, OCIConnectionPoolCreate(envhp,
errhp,poolhp, &poolName, &poolNameLen,
database,strlen(database),
conMin, conMax, conIncr,
appusername,strlen(appusername),
apppassword,strlen(apppassword),OCI_DEFAULT));

printf("Successful connection: Username: %s\n", appusername);

/* Multiple threads using the connection pool */


{
OCIThreadId *thrid[MAXTHREAD];
OCIThreadHandle *thrhp[MAXTHREAD];

OCIThreadProcessInit ();
checkerr (errhp, OCIThreadInit (envhp, errhp));
for (i = 0; i < MAXTHREAD; ++i)
{
checkerr (errhp, OCIThreadIdInit (envhp, errhp,
&thrid[i]));
checkerr (errhp, OCIThreadHndInit (envhp, errhp,
&thrhp[i]));
}
for (i = 0; i < MAXTHREAD; ++i)
{
checkerr (errhp, OCIThreadJoin (envhp, errhp, thrhp[i]));
checkerr (errhp, OCIThreadClose (envhp, errhp, thrhp[i]));
checkerr (errhp, OCIThreadIdDestroy (envhp, errhp,
&(thrid[i])));
checkerr (errhp, OCIThreadHndDestroy (envhp, errhp,
&(thrhp[i])));
}
checkerr (errhp, OCIThreadTerm (envhp, errhp));
} /* ALL THE THREADS ARE COMPLETE */
...

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix E: Source Code


Chapter 23 - Page 8
Source for PROXY_ROLE (continued)
...
checkerr(errhp, OCIConnectionPoolDestroy(poolhp, errhp,
OCI_DEFAULT));
checkerr(errhp, OCIHandleFree((dvoid *)poolhp,
OCI_HTYPE_CPOOL));
checkerr(errhp, OCIHandleFree((dvoid *)errhp,
OCI_HTYPE_ERROR));
} /* end of main () */

static void threadFunction (dvoid *arg)


{
int i, c;
int empno = *(int *)arg;
OCISvcCtx *svchp = (OCISvcCtx *) arg;
text insertst1[256];
OCIStmt *stmthp = (OCIStmt *)0;

sword status;
status = OCILogon2(envhp, errhp, &svchp,
(CONST OraText *)username, strlen(username),
(CONST OraText *)password, strlen(password),
(CONST OraText *)poolName, poolNameLen,OCI_CPOOL);

if (status == 0)
printf("Successful connection: Username: %s\n", username);
else checkerr(errhp,status);

sprintf(insertst1,"SET ROLE %s", role);

OCIHandleAlloc(envhp, (dvoid **)&stmthp, OCI_HTYPE_STMT,


(size_t)0, (dvoid **)0);

checkerr(errhp, OCIStmtPrepare (stmthp, errhp,


(text *)insertst1, (ub4)strlen(insertst1),
OCI_NTV_SYNTAX, OCI_DEFAULT));

status = OCIStmtExecute (svchp, stmthp, errhp, (ub4)1, (ub4)0,


(OCISnapshot *)0, (OCISnapshot *)0, OCI_DEFAULT );

if (status == 0)
printf("Role successfully enabled: %s\n", role);
else checkerr(errhp,status);

checkerr(errhp, OCITransCommit(svchp,errhp,(ub4)0));

checkerr(errhp, OCIHandleFree((dvoid *) stmthp,


OCI_HTYPE_STMT));
...

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix E: Source Code


Chapter 23 - Page 9
Source for PROXY_ROLE (continued)
...
checkerr(errhp, OCILogoff((dvoid *) svchp, errhp));
} /* end of threadFunction (dvoid *) */

void checkerr(errhp, status)


OCIError *errhp;
sword status;
{
text errbuf[512];
sb4 errcode = 0;

switch (status)
{
case OCI_SUCCESS:
break;
case OCI_SUCCESS_WITH_INFO:
(void) printf("Error - OCI_SUCCESS_WITH_INFO\n");
break;
case OCI_NEED_DATA:
(void) printf("Error - OCI_NEED_DATA\n");
break;
case OCI_NO_DATA:
(void) printf("Error - OCI_NODATA\n");
break;
case OCI_ERROR:
(void) OCIErrorGet((dvoid *)errhp, (ub4) 1, (text *) NULL,
&errcode,errbuf, (ub4) sizeof(errbuf),
OCI_HTYPE_ERROR);
(void) printf("Error - %.*s\n", 512, errbuf);
break;
case OCI_INVALID_HANDLE:
(void) printf("Error - OCI_INVALID_HANDLE\n");
break;
case OCI_STILL_EXECUTING:
(void) printf("Error - OCI_STILL_EXECUTE\n");
break;
case OCI_CONTINUE:
(void) printf("Error - OCI_CONTINUE\n");
break;
default:
break;
}
}

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix E: Source Code


Chapter 23 - Page 10
Appendix F: USERENV and
SYS_SESSION_ROLES
Contexts
Chapter 24

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix F: USERENV and SYS_SESSION_ROLES Contexts


Chapter 24 - Page 1
Practices for Appendix F: Overview

Predefined Parameters of the USERENV Namespace


Parameter Return Value
ACTION Identifies the position in the module (application name)
and is set through the DBMS_APPLICATION_INFO
package or OCI
AUDITED_CURSORID Returns the cursor ID of the SQL that triggered the audit.
This parameter is not valid in a fine-grained auditing
environment. If you specify it in such an environment, the
Oracle database always returns NULL.
AUTHENTICATED_IDENTITY Returns the identity used in authentication. In the list that
follows, the type of user is followed by the value returned:
• Kerberos-authenticated enterprise user: Kerberos
principal name
• Kerberos-authenticated external user: Kerberos
principal name; same as the schema name
• SSL-authenticated enterprise user: The DN in the
user’s PKI certificate
• SSL-authenticated external user: The DN in the
user’s PKI certificate
• Password-authenticated enterprise user:
Nickname; same as the login name
• Password-authenticated database user: The
database username; same as the schema name
• OS-authenticated external user: The external
operating system username
• RADIUS/DCE-authenticated external user: The
schema proxy with DN: Oracle Internet Directory
DN of the client
• Proxy with certificate: Certificate DN of the client
• Proxy with username: Database username if client
is a local database user; nickname if client is an
enterprise user
• SYSDBA/SYSOPER using Password File: Login
name
• SYSDBA/SYSOPER using OS authentication:
Operating system username
AUTHENTICATION_DATA Is the data being used to authenticate the login user. For
X.503 certificate–authenticated sessions, this field returns
the context of the certificate in HEX2 format.
Note: You can change the return value of the
AUTHENTICATION_DATA attribute by using the
length parameter of the syntax. Values up to 4,000 are
accepted. This is the only attribute of USERENV for which
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix F: USERENV and SYS_SESSION_ROLES Contexts


Chapter 24 - Page 2
the Oracle database implements such a change.
AUTHENTICATION_METHOD Returns the method of authentication. In the list that
follows, the type of user is followed by the method
returned:
• Password-authenticated enterprise user, local
database user, or SYSDBA/SYSOPER using
Password file; proxy with username using
password: PASSWORD
• Kerberos-authenticated enterprise or external user:
KERBEROS
• SSL-authenticated enterprise or external user: SSL
• RADIUS-authenticated external user: RADIUS
• OS-authenticated external user or
SYSDBA/SYSOPER: OS
• DCE-authenticated external user: DCE
• Proxy with certificate, DN, or username without
using password: NONE
• Background process (job queue slave process):
JOB
You can use IDENTIFICATION_TYPE to distinguish
between external and enterprise users when the
authentication method is Password, Kerberos, or SSL.
BG_JOB_ID Is the Job ID of the current session if it is established by
an Oracle database background process; null, if the
session is not established by a background process
CDB_NAME If queried while connected to a multitenant container
database (CDB), returns the name of the CDB. Otherwise,
returns NULL.
CLIENT_IDENTIFIER Returns an identifier that is set by the application through
the DBMS_SESSION.SET_IDENTIFIER procedure,
the OCI_ATTR_CLIENT_IDENTIFIER OCI attribute,
or the
Oracle.jdbc.OracleConnection.setClientI
dentifier Java class. This attribute is used by various
database components to identify lightweight application
users who authenticate as the same database user.
CLIENT_INFO Returns up to 64 bytes of user session information that
can be stored by an application by using the
DBMS_APPLICATION_INFO package
C LIENT_PROGRAM_NAME The name of the program used for the database session
CON_ID If queried while connected to a CDB, returns the current
container ID. Otherwise, returns 0.
CON_NAME If queried while connected to a CDB, returns the current
container name. Otherwise, returns the name of the
database as specified in the DB_NAME initialization
parameter.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix F: USERENV and SYS_SESSION_ROLES Contexts


Chapter 24 - Page 3
CURRENT_BIND The bind variables for fine-grained auditing
CURRENT_EDITION_ID The identifier of the current edition
CURRENT_EDITION_NAME The name of the current edition
CURRENT_SCHEMA Name of the default schema being used in the current
schema. This value can be changed during the session
with an ALTER SESSION SET CURRENT_SCHEMA
statement.
CURRENT_SCHEMAID Is the identifier of the default schema being used in the
current session
CURRENT_SQL CURRENT_SQL returns the first 4 KB of the current SQL
that triggered the fine-grained auditing event. The
CURRENT_SQLn CURRENT_SQLn attributes return subsequent 4 KB
increments, where n can be an integer from 1 through 7,
inclusive. CURRENT_SQL1 returns bytes 4 KB to 8 KB;
CURRENT_SQL2 returns bytes 8 KB to 12 KB, and so
on. You can specify these attributes only inside the event
handler for the fine-grained auditing feature.
CURRENT_SQL_LENGTH Is the length of the current SQL statement that triggers
fine-grained audit or row-level security (RLS) policy
functions or event handlers; valid only inside the function
or event handler
CURRENT_USER The name of the database user whose privileges are
currently active. This may change during the duration of a
session to reflect the owner of any active definer's rights
object. When no definer's rights object is active,
CURRENT_USER returns the same value as
SESSION_USER. When used directly in the body of a
view definition, this returns the user that is executing the
cursor that is using the view; it does not respect views
used in the cursor as being definer's rights.
CURRENT_USERID The identifier of the database user whose privileges are
currently active
DATABASE_ROLE The database role using the SYS_CONTEXT function with
the USERENV namespace.
The role is one of the following: PRIMARY, PHYSICAL
STANDBY, LOGICAL STANDBY, SNAPSHOT STANDBY.
DB_DOMAIN Is the domain of the database as specified in the
DB_DOMAIN initialization parameter
DB_NAME Is the name of the database as specified in the DB_NAME
initialization parameter
DB_SUPPLEMENTAL_LOG_LEV If supplemental logging is enabled, returns a string
EL containing the list of enabled supplemental logging levels.
Possible values are: ALL_COLUMN, FOREIGN_KEY,
MINIMAL, PRIMARY_KEY, PROCEDURAL, and
UNIQUE_INDEX. If supplemental logging is not
enabled, returns NULL.
Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix F: USERENV and SYS_SESSION_ROLES Contexts


Chapter 24 - Page 4
DB_UNIQUE_NAME Is the name of the database as specified in the
DB_UNIQUE_NAME initialization parameter
DBLINK_INFO Returns the source of a database link session. Specifically,
it returns a string of the form:
SOURCE_GLOBAL_NAME=dblink_src_global_name,
DBLINK_NAME=dblink_name,
SOURCE_AUDIT_SESSIONID=dblink_src_audit_sessio
nid where:
dblink_src_global_name is the unique global name of the
source database
dblink_name is the name of the database link on the
source database
dblink_src_audit_sessionid is the audit session ID of the
session on the source database that initiated the
connection to the remote database using dblink_name
ENTRYID Is the current audit entry number. The audit entryid
sequence is shared between fine-grained audit records and
regular audit records. You cannot use this attribute in
distributed SQL statements.
ENTERPRISE_IDENTITY Returns the user’s enterprisewide identity:
• For enterprise users: The Oracle Internet Directory
DN
• For external users: The external identity (Kerberos
principal name, RADIUS and DCE schema
names, OS username, Certificate DN)
• For local users and SYSDBA/SYSOPER logins:
NULL

The value of the attribute differs by proxy method:


• For a proxy with DN: The Oracle Internet
Directory DN of the client
• For a proxy with certificate: The certificate DN of
the client for external users; the Oracle Internet
Directory DN for global users
• For a proxy with username: The Oracle Internet
Directory DN if the client is an enterprise user;
NULL if the client is a local database user
FG_JOB_ID Is the job ID of the current session if it is established by a
client foreground process; Null, if the session is not
established by a foreground process.
GLOBAL_CONTEXT_MEMORY Returns the number being used in the system global area
by the globally accessed context
GLOBAL_UID Returns the global user ID from Oracle Internet Directory

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix F: USERENV and SYS_SESSION_ROLES Contexts


Chapter 24 - Page 5
for Enterprise User Security (EUS) logins; returns null for
all other logins
HOST Is the name of the host machine from which the client has
connected
IDENTIFICATION_TYPE Returns the way the user’s schema was created in the
database. Specifically, it reflects the IDENTIFIED
clause in the CREATE/ALTER USER syntax. In the list
that follows, the syntax used during schema creation is
followed by the identification type returned:
• IDENTIFIED BY password: LOCAL
• IDENTIFIED EXTERNALLY: EXTERNAL
• IDENTIFIED GLOBALLY: GLOBAL SHARED
• IDENTIFIED GLOBALLY AS DN: GLOBAL
PRIVATE
INSTANCE Is the instance identification number of the current
instance
INSTANCE_NAME Is the name of the instance
IP_ADDRESS Is the IP address of the machine from which the client is
connected. If the user does not connect through the
listener, this attribute is NULL.
IS_APPLY_SERVER Returns TRUE if queried from within a SQL Apply server
in a logical standby database. Otherwise, returns FALSE.
IS_DG_ROLLING_UPGRADE Returns TRUE if a rolling upgrade of the database
software in a Data Guard configuration, initiated by way
of the DBMS_ROLLING package, is active. Otherwise,
returns FALSE.
ISDBA Returns TRUE if the user has been authenticated as having
DBA privileges either through the operating system or
through a password file
LANG Is the ISO abbreviation for the language name; a shorter
form than the existing LANGUAGE parameter
LANGUAGE Is the language and territory currently used by your
session, along with the database character set. In this
form: language_territory.characterset

MODULE Is the application name (module) set through the


DBMS_APPLICATION_INFO package or OCI
NETWORK_PROTOCOL Is the network protocol being used for communication, as
specified in the 'PROTOCOL=protocol' portion of
the connect string
NLS_CALENDAR Is the current calendar of the current session
NLS_CURRENCY Is the currency of the current session
NLS_DATE_FORMAT Is the date format for the session
NLS_DATE_LANGUAGE Is the language used for expressing dates
NLS_SORT Is BINARY or the linguistic sort basis

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix F: USERENV and SYS_SESSION_ROLES Contexts


Chapter 24 - Page 6
NLS_TERRITORY Is the territory of the current session
ORACLE_HOME The full path name for the Oracle home directory.
OS_USER Is the operating system username of the client process that
initiated the database session
PLATFORM_SLASH The slash character that is used as the file path delimiter
for your platform.
POLICY_INVOKER Is the invoker of row-level security (RLS) policy
functions
PROXY_ENTERPRISE_IDENTI Returns the Oracle Internet Directory DN when the proxy
TY user is an enterprise user
PROXY_USER Is the name of the database user who opened the current
session on behalf of SESSION_USER
PROXY_USERID Is the identifier of the database user who opened the
current session on behalf of SESSION_USER
SCHEDULER_JOB Returns Y if the current session belongs to a foreground
job or background job. Otherwise, returns N.
SERVER_HOST Is the host name of the machine on which the instance is
running
SERVICE_NAME Is the name of the service to which a given session is
connected
SESSION_EDITION_ID The identifier of the session edition
SESSION_EDITION_NAME The name of the session edition
SESSION_USER Is the database username by which the current user is
authenticated. This value remains the same throughout the
duration of the session.
SESSION_USERID Is the identifier of the database username by which the
current user is authenticated
SESSIONID Is the auditing session identifier. You cannot use this
attribute in distributed SQL statements.
SID Is the session number (different from the session ID)
STATEMENTID Is the auditing statement identifier. STATEMENTID
represents the number of SQL statements audited in a
given session.

TERMINAL Is the operating system identifier for the client of the


current session. In distributed SQL statements, this
attribute returns the identifier for your local session. In a
distributed environment, this is supported only for remote
SELECT statements, not for remote INSERT, UPDATE,
or DELETE operations. (The return length of this
parameter may vary by operating system.)

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix F: USERENV and SYS_SESSION_ROLES Contexts


Chapter 24 - Page 7
Predefined Parameters of the SYS_SESSION_ROLES Namespace
Parameter Return Value
role_name Shows whether the role is currently enabled for the
session or not. Returns FALSE when the role is not
enabled.

Copyright © 2015, Oracle and/or its affiliates. All rights reserved.

Appendix F: USERENV and SYS_SESSION_ROLES Contexts


Chapter 24 - Page 8

S-ar putea să vă placă și