ORACLE - Why does a dynamic SQL statement using DBMS_RANDOM fail when called from a stored procedure but not from an anonymous block - sql

EDIT (8/25)
Thanks to #Alex Poole for providing the answer below but I wanted to share additional detail on these role limitations around PL/SQL objects as it helps explain not only how Oracle is managing things under the hood but why it handles permissions this way.
Now knowing where I was going wrong, I was able to identify this question which discusses the issue at length. This answer describes how the Oracle data structures store the permissions for evaluation.
In addition, someone linked an explanation from Tom Kyte which explains why this behavior was coded intentionally. Long story short: PL/SQL Definer's Rights do not respect role based permissions due to how the Oracle engine compiles these objects. If role based permissions were allowed then any REVOKE statements could have the ability of invalidating large swaths of PL/SQL objects, requiring a costly full database recompile.
Original Question
Could someone help me understand why I can call a dynamic sql script containing a reference to a DBMS_RANDOM procedure when the logic is called from an anonymous block, however, when I take that same logic and drop it into my own stored procedure, the previously runnable script fails to execute with a ORA-00904: "DBMS_RANDOM"."STRING": invalid identifier error?
I feel confident that my privileges are correct. I can run the script that is being passed as a variable directly without issue and run this logic as an anonymous PL/SQL block. Do I need to change my syntax with the stored proc or is it possible that this practice is prevented for security reasons?
Any explanation would be great but if you can point me to the Oracle documentation, I would be ecstatic. I have looked extensively, especially around Oracle's Dynamic SQL documentation but I haven't seen a description of this behavior. I am using Oracle 11g.
To recreate the behavior I am seeing:
Test Data Creation:
SPOOL ON;
SET SERVEROUTPUT ON SIZE UNLIMITED;
--Create Test Table
CREATE TABLE TEST_DYNAMIC_TBL (
ID NUMBER PRIMARY KEY,
MY_COL VARCHAR2(50));
--INSERT a line of data and confirm
INSERT INTO TEST_DYNAMIC_TBL VALUES(1, 'SOME TEXT');
COMMIT;
SELECT MY_COL FROM TEST_DYNAMIC_TBL;
MY_COL
SOME TEXT
PL/SQL Anonymous Block (Successful Example)
DECLARE
l_script VARCHAR2 (32767);
BEGIN
l_script := 'UPDATE TEST_DYNAMIC_TBL SET MY_COL = DBMS_RANDOM.STRING(''U'',5)';
DBMS_OUTPUT.put_line ('Script sent to Exec Immediate: ' || l_script);
EXECUTE IMMEDIATE l_script;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.put_line (' ERROR: ' || SUBSTR (SQLERRM, 1, 64));
ROLLBACK;
END;
/
--Check value (This results in a successful update)
SELECT MY_COL FROM TEST_DYNAMIC_TBL;
Script sent to Exec Immediate: UPDATE TEST_DYNAMIC_TBL SET MY_COL = DBMS_RANDOM.STRING('U',5)
PL/SQL procedure successfully completed.
MY_COL
XFTKV
Your query value will vary depending on the seed that DBMS_RANDOM picked
Stored Procedure Example (Failure Example)
--Procedure created with identical logic
CREATE OR REPLACE PROCEDURE TEST_DYNAMIC
AS
l_script VARCHAR2 (32767);
BEGIN
l_script := 'UPDATE TEST_DYNAMIC_TBL SET MY_COL = DBMS_RANDOM.STRING(''U'',5)';
DBMS_OUTPUT.put_line ('Script sent to Exec Immediate: ' || l_script); -- This string will execute successfully if run directly
EXECUTE IMMEDIATE l_script;
COMMIT;
EXCEPTION
WHEN OTHERS
THEN
DBMS_OUTPUT.put_line (' ERROR: ' || SUBSTR (SQLERRM, 1, 64));
ROLLBACK;
END;
/
--Reset and verify Data
UPDATE TEST_DYNAMIC_TBL SET MY_COL = 'SOME TEXT';
COMMIT;
SELECT MY_COL FROM TEST_DYNAMIC_TBL;
--Execute through Procedure (Will throw error)
EXECUTE TEST_DYNAMIC;
--Check Value of Table
SELECT MY_COL FROM TEST_DYNAMIC_TBL;
Stored Procedure Results:
MY_COL
SOME TEXT
Script sent to Exec Immediate: UPDATE TEST_DYNAMIC_TBL SET MY_COL = DBMS_RANDOM.STRING('U',5)
ERROR: ORA-00904: DBMS_RANDOM: invalid identifier
PL/SQL procedure successfully completed.
MY_COL
SOME TEXT

It isn't about it being dynamic, it's about the privileges and how they were granted. You would see the same thing if you had a static insert using dbms_random (and in your example anyway there is no need for it to be dynamic).
It appears that you have execute privilege on dbms_random granted through a role, not directly to the package owner. From the documentation (emphasis added):
If the procedure owner grants to another user the right to use the procedure, then the privileges of the procedure owner (on the objects the procedure references) apply to the grantee's exercise of the procedure. The privileges of the procedure's definer must be granted directly to the procedure owner, not granted through roles. These are called definer's rights.
The user of a procedure who is not its owner is called the invoker. Additional privileges on referenced objects are required for an invoker's rights procedure, but not for a definer's rights procedure.
That only applies to stored PL/SQL - i.e. procedures, functions, packages, triggers etc. - not to anonymous blocks.
You can either get the privilege on dbms_random granted directly to the package owner, or change your procedure to use invoker's rights:
CREATE OR REPLACE PROCEDURE TEST_DYNAMIC
AUTHID CURRENT_USER
AS
...
In the latter case, anyone calling your procedure will then need the privilege on dbms_random - but they can have it through a role.
As access to that package is sometimes locked down, a direct grant to the owner might be preferable, but it depends on your security constraints.
The reason it requires a direct grant, I believe, is that roles can be enabled and disabled, and be default or not, and can be nested. If a direct grant is revoked then it's fairly straightforward to figure out that should invalidate the procedure. And that's possibly true if a role is revoked, but quite a lot more complicated.
But what role-derived privileges should be taken into consideration when the procedure is created - only those that are enabled in that session? Only default roles? Or all roles? (And remember there can be a chain of roles to think about to determine privileges, and you can get the same privilege from multiple roles.)
However you do it will confuse or upset someone - if only enabled then the owner logging in a future session might not be able to perform the actions the procedure does, and what if they want to recompile it? If only default then those defaults can change, with the same issues - or should that invalidate the procedure? If all roles then including disabled ones will be confusing and could have security implications.
And for any of those, role revocation would still have to figure out which privileges that removes - which aren't also granted directly or via another role! - and only once it's really sure which privileges have actually gone, see which objects that affects. Which could be a lot of work - think how many individual privileges could be affected by revoking DBA.
It's much simpler for the invoker - you only need to look at the active privileges from the enabled roles at the moment then call the procedure.
So while at first glance it seems odd that privileges granted through roles aren't included for stored PL/SQL, once you look at the implications and complications - both as it's created, but more what happens afterwards - it seems like a sensible restriction.

Related

unable to execute sql procedure on oracle live sql

I created a procedure
create or replace procedure dba_role
as
user varchar2(200);
ref varchar2(200);
begin
insert into dba_role_privs(grantee,granted_role) (select user as grantee,granted_role from dba_role_privs where grantee=ref);
end;
The procedure is getting created but I'm not able to execute the procedure. I've tried different methods to execute it by passing parameters but nothing worked.
Can anyone please tell how to execute this procedure in oracle live SQL
the parameters to be passed are both strings(varchars)
for example:
I've tried "Execute dba_role('alex','hunter');
The error is
**ORA-06550: line 1, column 7:
**PLS-00306: wrong number or types of arguments in call to 'DBA_ROLE' **
As well as missing the two parameters that you are trying to pass (parameters should appear in brackets immediately following the procedure name, as explained in d r's answer), you can't insert into a DBA view. For one thing, it's not in your schema (unless you are creating your procedure as SYS, which you should never do because SYS is reserved for Oracle internals) and you haven't been granted INSERT privilege, but also because it is defined with multiple joins and unions etc and is therefore not an updatable view. Even it it were, your procedure only specifies two of its seven columns.
Even if you did have privileges and it was updatable and you supplied all of the values, directly updating internal data dictionary tables is unsupported and could damage your database. If you want to grant a privilege to a role you should use the GRANT command:
grant reports_user to hr;
To revoke the grant,
revoke reports_user from hr;
create or replace procedure
dba_role(p_user IN VarChar2, p_ref IN VarChar2) AS
begin
insert into dba_role_privs(grantee, granted_role) (select p_user as grantee, granted_role from dba_role_privs where grantee = p_ref);
end dba_role;
/
Above is how it should be defined - with two VarChar2 parameters. And below is how to call it:
Begin
dba_role('alex', 'hunter');
End;
/
The problem with your code was that user and ref were declared as variables within the scope of the procedure (not as parameters) so, when the procedure was called with parameters (like I did above) then you tryed to pass two parameters to the procedure not accepting any. On the other side, if you call it without parameters (just as dba_role;) then user and ref were both Null.

Grant permission to role if exists in SAP HANA

I have a HANA database deployment set up using Flyway and the HANA JDBC driver that creates and populates a schema. Something I would also like to do as part of the deployment is grant a particular database role read access to that schema. However, in order to avoid migration errors, I'd first like to verify that this role exists, and I can't get this part of the logic to work.
The closest I've come is
DO
BEGIN
DECLARE I INTEGER;
SELECT COUNT(*) INTO I
FROM roles
WHERE role_name = 'MYROLE';
IF I > 0
THEN
GRANT SELECT ON SCHEMA myschema TO MYROLE;
END IF;
END;
but this fails with
SQL State : HY000
Error Code : 7
Message : SAP DBTech JDBC: [7] (at 140): feature not supported: DDL statements other than CREATE/DROP TABLE is/are not supported in anonymous block: line 9 col 9 (at pos 140)
Location : db/migration/V1.10__my_script.sql (snip)
Line : 1
Statement : DO
I also tried this via trying to create a temporary stored procedure and executing that - same problem with DDL statements not being supported.
The problems:
I need to do an IF-THEN-ELSE based on the result of a select query
HANA doesn't seem to support nesting a SELECT statement inside an IF clause, so I need to save the result in a variable and use that instead
Declaring variables is only supported inside blocks, such as anonymous blocks or the bodies of stored procedures
Blocks also forbid executing most DDL statements - GRANT being one of them.
At this point, I'm not sure if what I'm trying to do is even possible. Pointers would be very much appreciated.
Your code should work with a few modifications like the following:
DO
BEGIN
DECLARE I INTEGER;
SELECT COUNT(*) INTO I
FROM roles
WHERE role_name = 'MYROLE';
IF :I > 0 THEN
exec 'GRANT SELECT ON SCHEMA myschema to MYROLE';
END IF;
END;
To access the I variable value in the IF statement you need to use the : notation.
As you mentioned some DDL statements are not directly supported in SQL Script, but you can use the EXEC command to run them as dynamic SQL commands.
Generally speaking, this approach to handle privileges is rather problematic since the outcome of your procedure, that is what privileges exactly are available to MYROLE, is dependent on
if there already exists a role with the same name
what privileges the security context that runs the procedure is allowed to grant
SAP HANA provides HDI (HANA Deployment Infrastructure) repository object type .hdbrole that allows to bundle privileges into roles and have those deployed fully (or not at all) upon installation time. This approach also allows updating privilege assignments to roles even after the role had been assigned to other roles and users without the need for re-assignment.
Dynamically building roles and assigning privileges makes it much harder to understand when, where and why privileges are assigned to roles/users. That is typically not what you want; instead, you like to have privileges assigned at a well-known place in your application and nowhere else. Therefore the pointer is to actually not use your procedure but to use the HANA tools available for role-definition.
All that is explained in a lot more detail in the SAP HANA documentation.

Execute a stored procedure through a trigger right after a user was created on the database

I would like to write a procedure can grant role permissions to a new created user.
My thoughts were that I first create a procedure like this:
CREATE OR REPLACE PROCEDURE P_CREATE_USER
BEGIN
EXECUTE IMMEDIATE 'GRANT RESOURCE TO'||ora_dict_obj_name;
EXECUTE IMMEDIATE 'GRANT CONNECT TO'||ora_dict_obj_name;
END;
/
Then, I create a trigger, which execute this procedure, after a user is created on the database. Like this:
CREATE OR REPLACE TRIGGER T_CREATE_USER
AFTER CREATE ON DATABASE
WHEN (ora_dict_obj_type = 'USER')
BEGIN
P_CREATE_USER;
END;
/
It did not really work, do you have other suggestions?
I use Oracle as DBMS.
So the problem is this: your trigger throws ORA-30511: invalid DDL operation in system triggers.
The reason is, we cannot commit in triggers. DDL issues implicit commits (before and after the statement). So there is no way your trigger can work, nor could it ever have worked.
The workaround for commits in triggers is pragma AUTONOMOUS TRANSACTION, which causes the trigger to operate in an isolated session. That won't here because the freshly created user won't be visible in the autonomous session.
The best approach you can get to encapsulate the logic would be this:
CREATE OR REPLACE PROCEDURE P_CREATE_USER
(p_user_name in varchar2
, p_password in varchar2)
is
BEGIN
EXECUTE IMMEDIATE ' create user '||p_user_name ||' identified by '||p_password;
EXECUTE IMMEDIATE 'GRANT RESOURCE TO'||p_user_name ;
EXECUTE IMMEDIATE 'GRANT CONNECT TO'||p_user_name ;
END;
/
In SQL server a user, such as you can execute a procedure to grant SQL permission to a newly created user. The condition to make this work is that the user’s account, such as your account need ‘With Grant’ to that SQL permission in order to be able to grant other new user this SQL permission

Error during stored procedure creation in DB2 database

I am struggling with schemas while creating a stored procedure in DB2 database ( 10.5 version ).
My user name is XYZ but I have to create a Stored procedure for schema ABC.
When I am trying to execute the create procedure sql I get error message which looks like Schema related
Create procedure ABC.customInsert(
IN temp INTEGER
)
BEGIN
INSERT INTO ABC.One_Column_table VALUES ( temp );
END
Error Message:
Error:DB2 SQL error:SQLCODE:-551, SQLSTATE: 42501,
SQLERRMC:XYZ;INSERT;ABC.One_Column_table
My current schema was showing XYZ earlier. ( result of select current_Schema from sysibm.sysdummy1).
I have changed it to ABC. ( using SET CURRENT SCHEMA ABC). But still the same problem.
I am able to insert, select, create UDT etc in ABC schema but the problem exists only during stored procedure creation.
Any idea what am I doing wrong ?
Based on your error message, SQLCODE -551 means that the user "XYZ" does not have the "INSERT" privilege on the table "ABC.One_Column_table".
Since you imply that you, when connected as XYZ, can insert into the table by issuing simple INSERT statements, it is possible that you possess the INSERT privilege indirectly, via a group membership. Group privileges are ignored for SQL statements in stored procedures, functions or triggers, as explained in this IBM technote.
You have two options:
Grant the required privileges on ABC.One_Column_table to the user XYZ directly.
Create a role (using the CREATE ROLE statement), grant the table privileges to that role, then grant the role to the user XYZ.
If you are curious, such behaviour is caused by the fact that static SQL statement (e.g. in a stored procedure) authorization is checked only during compilation, and the compiled code can then be executed without additional authorization checks. Groups are maintained outside the DB2 database, by the operating system, and it is possible that group membership changes after the stored procedure is compiled and without the database security administrator's knowledge. If group privileges were effective for static SQL, it would allow users who weren't originally authorized to run particular statements (i.e. were not members of the authorized group at the compilation time) still execute those statements, thus creating a security risk.
Roles, on the other hand, are maintained within the database itself by the database security administrator and thus are part of the same security landscape.

Multi-schema select statement doesn't work in PL/SQL procedure?

I'm trying to create a procedure to run multiple PL/SQL statements, but I haven't gotten very far. The select statement works fine if I run it out of a procedure, but if I try to execute it inside one -- it can't find the shttran table. I'm guessing it might be a schema issue, but I have no idea how-to correct. Ideas?
CREATE OR REPLACE PROCEDURE REGREPORTUSER.findUnsent
IS
BEGIN
INSERT INTO regreportuser.maltran (maltran.maltran_key,
maltran.maltran_sent)
SELECT shttran.shttran_id || shttran.shttran_seq_no AS maltran_key,
'No' AS maltran_sent
FROM saturn.shttran -- This is the table it can't find
WHERE TO_DATE (shttran.shttran_activity_date) > SYSDATE - 14
AND shttran.shttran_user = 'WWW2_USER'
AND shttran.shttran_id || shttran.shttran_seq_no NOT IN
(SELECT maltran.maltran_key FROM regreportuser.maltran);
END findUnsent;
Most likely, the problem is that the user that owns the stored procedure, REGREPORTUSER has access to the table saturn.shttran via a role rather than as a direct grant. A definer's rights stored procedure cannot use privileges that are granted to a definer via a role. It can only use privileges granted directly.
You can verify that this is, in fact, the problem by disabling roles in your SQL*Plus session. If you run the command
SQL> set role none;
and then try to execute the SQL statement, you should get the same error. In order to fix the problem, you need to give the grant directly
GRANT SELECT ON saturn.shttran
TO REGREPORTUSER