Execute Immediate within a stored procedure keeps giving insufficient priviliges error - sql

Here is the definition of the stored procedure:
CREATE OR REPLACE PROCEDURE usp_dropTable(schema VARCHAR, tblToDrop VARCHAR) IS
BEGIN
DECLARE v_cnt NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_cnt
FROM all_tables
WHERE owner = schema
AND table_name = tblToDrop;
IF v_cnt > 0 THEN
EXECUTE IMMEDIATE('DROP TABLE someschema.some_table PURGE');
END IF;
END;
END;
Here is the call:
CALL usp_dropTable('SOMESCHEMA', 'SOME_TABLE');
For some reason, I keep getting insufficient privileges error for the EXECUTE IMMEDIATE command. I looked online and found out that the insufficient privileges error usually means the oracle user account does not have privileges for the command used in the query that is passes, which in this case is DROP. However, I have drop privileges. I am really confused and I can't seem to find a solution that works for me.
Thanks to you in advance.
SOLUTION:
As Steve mentioned below, Oracle security model is weird in that it needs to know explicitly somewhere in the procedure what kind of privileges to use. The way to let Oracle know that is to use AUTHID keyword in the CREATE OR REPLACE statement. If you want the same level of privileges as the creator of the procedure, you use AUTHID DEFINER. If you want Oracle to use the privileges of the user currently running the stored procedure, you want to use AUTHID CURRENT_USER. The procedure declaration looks as follows:
CREATE OR REPLACE PROCEDURE usp_dropTable(schema VARCHAR, tblToDrop VARCHAR)
AUTHID CURRENT_USER IS
BEGIN
DECLARE v_cnt NUMBER;
BEGIN
SELECT COUNT(*)
INTO v_cnt
FROM all_tables
WHERE owner = schema
AND table_name = tblToDrop;
IF v_cnt > 0 THEN
EXECUTE IMMEDIATE('DROP TABLE someschema.some_table PURGE');
END IF;
END;
END;
Thank you everyone for responding. This was definitely very annoying problem to get to the solution.

Oracle's security model is such that when executing dynamic SQL using Execute Immediate (inside the context of a PL/SQL block or procedure), the user does not have privileges to objects or commands that are granted via role membership. Your user likely has "DBA" role or something similar. You must explicitly grant "drop table" permissions to this user. The same would apply if you were trying to select from tables in another schema (such as sys or system) - you would need to grant explicit SELECT privileges on that table to this user.

You should use this example with AUTHID CURRENT_USER :
CREATE OR REPLACE PROCEDURE Create_sequence_for_tab (VAR_TAB_NAME IN VARCHAR2)
AUTHID CURRENT_USER
IS
SEQ_NAME VARCHAR2 (100);
FINAL_QUERY VARCHAR2 (100);
COUNT_NUMBER NUMBER := 0;
cur_id NUMBER;
BEGIN
SEQ_NAME := 'SEQ_' || VAR_TAB_NAME;
SELECT COUNT (*)
INTO COUNT_NUMBER
FROM USER_SEQUENCES
WHERE SEQUENCE_NAME = SEQ_NAME;
DBMS_OUTPUT.PUT_LINE (SEQ_NAME || '>' || COUNT_NUMBER);
IF COUNT_NUMBER = 0
THEN
--DBMS_OUTPUT.PUT_LINE('DROP SEQUENCE ' || SEQ_NAME);
-- EXECUTE IMMEDIATE 'DROP SEQUENCE ' || SEQ_NAME;
-- ELSE
SELECT 'CREATE SEQUENCE COMPTABILITE.' || SEQ_NAME || ' START WITH ' || ROUND (DBMS_RANDOM.VALUE (100000000000, 999999999999), 0) || ' INCREMENT BY 1'
INTO FINAL_QUERY
FROM DUAL;
DBMS_OUTPUT.PUT_LINE (FINAL_QUERY);
cur_id := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.parse (cur_id, FINAL_QUERY, DBMS_SQL.v7);
DBMS_SQL.CLOSE_CURSOR (cur_id);
-- EXECUTE IMMEDIATE FINAL_QUERY;
END IF;
COMMIT;
END;
/

you could use "AUTHID CURRENT_USER" in body of your procedure definition for your requirements.

Alternatively you can grant the user DROP_ANY_TABLE privilege if need be and the procedure will run as is without the need for any alteration. Dangerous maybe but depends what you're doing :)

Related

Oracle: grant to role if role exists

How to execute
GRANT SELECT ON <ownschema>.<sometable> TO <somerole>;
but backing off gracefully if somerole does not exist. The user executing the statement is a standard user (think SCOTT) without any special privileges.
Version: Oracle Database 19 or later
I don't think you can.
If you're running it at SQL level, then Oracle will raise an error if role doesn't exist.
If you want to check whether it exists, you'll need some kind of a PL/SQL procedure (which is not a problem), but - DBA should grant you select privilege on dba_roles so that you could check it. Then, if it exists, you'd grant that privilege; otherwise, return some kind of an information (dbms_output.put_line in my example is pretty much stupid; it wouldn't be visible out of SQL*Plus, SQL Developer, TOAD and similar), but you got the idea, I hope.
Something like this:
create or replace procedure p_grant_to_role (par_role in varchar2) is
l_cnt number;
begin
select count(*)
into l_cnt
from dba_roles
where role_name = par_role;
if l_cnt > 0 then
execute immediate 'grant select on emp to ' || par_role;
else
dbms_output.put_line('Role does not exist');
end if;
end;
/
It all depends on the tool, but you can do something like this (very crude as usually you should have better exception handling):
begin
execute immediate 'grant .....';
exception
when others then null;
end;

How to listed all the tables of a User in a database? n

Hi so i have the following plan :
i want to Write a script, which calls another script. A parameter V_USERNAME should be passed from the 1st script to the 2nd script.( Using the keyword DEFINE)
My code look like :
##C:\Users\pe.k\Documents\script2.sql &p_v_username
set serveroutput on
define p_v_username = "user";
In the 2nd script all tables of the user should be output. (Using the key word EXECUTE IMMEDIATE and a cursor).
The output control is to be done via a parameter in the script or when calling the script.
Example call:
SQL> #start_script1 MML
declare
&p_v_username varchar2(100);
v_result varchar2(100);
cursor cp_username (&p_v_username varchar2)
is
select owner, table_name
from all_tables
where owner = &p_v_username
order by owner, table_name;
begin
dbms_output.put_line('Alle Tabellen der User'); --l_username);
open cp_username(&p_v_username);
--loop
--fetch cp_username into v_result;
-- dbms_output.put_line(v_result);
--end loop;
close cp_username;
end;
/
And i have the errors and i am lost. I dont know how to do it
Your second procedure should be something like this:
BEGIN
DBMS_OUTPUT.PUT_LINE('Alle Tabellen der User'); --l_username);
FOR TABS IN (
SELECT OWNER, TABLE_NAME
FROM ALL_TABLES
WHERE OWNER = '&P_V_USERNAME'
ORDER BY OWNER, TABLE_NAME
) LOOP
DBMS_OUTPUT.PUT_LINE(TABS.TABLE_NAME);
END LOOP;
END;
/
In order to print the output generated by the DBMS_OUTPUT package from PL/SQL, make sure to set serveroutput on

Oracle - Why is EXECUTE IMMEDIATE allowed in stored procedures?

Why is EXECUTE IMMEDIATE allowed in stored procedures, if stored procedures are meant to mitigate SQL injection attacks? The accepted answer to the following question refers to them as a step against such attacks:
What is a stored procedure? https://stackoverflow.com/a/459531/3163495
"Stored procedures also have a security benefit in that you can grant
execute rights to a stored procedure but the user will not need to
have read/write permissions on the underlying tables. This is a good
first step against SQL injection."
...unless the stored procedure is using EXECUTE IMMEDIATE.
This PL/SQL code returns a product's description (second parameter).
CREATE OR REPLACE PROCEDURE prodDescr(vname IN VARCHAR2, vresult OUT VARCHAR2) AS
vsql VARCHAR2(4000);
BEGIN
vsql := 'SELECT description FROM products WHERE name=''' || vname || '''';
EXECUTE IMMEDIATE vsql INTO vresult;
END;
Malicious user input.
A' AND 1=2 UNION SELECT password FROM members WHERE username='admin
Generated Query.
SELECT description FROM products WHERE name='A' OR 1=2 UNION SELECT password FROM members WHERE username='admin'
When the query is executed, the attacker gets the administrator’s password.
As you can see, although we used a stored procedure, an attacker can still exploit a vulnerability just as easily as if we were an amateur developer concatenating some SELECT statement in PHP without sanitizing input. To me, it seems it can be very misleading to say to developers that stored procedures will help keep your database safe.
Execute Immediate can still be used in a safe way. It all comes down to the logic of the stored proc. The concat is making the code unsafe not the execute immediate.
vsql := 'SELECT description FROM products WHERE name=''' || vname || '''';
Should be using bind variables or a dbms_assert call.
vsql := 'select count(1) from all_objects where owner = :1'
EXECUTE IMMEDIATE vsql into vresult using vname ;
OR
vsql := 'select count(1) from all_objects where owner ='||DBMS_ASSERT.ENQUOTE_LITERAL(vname);
EXECUTE IMMEDIATE vsql into vresult ;
In a full example below using both methods. The first has bind(s) and the second is wrappered with DBMS_ASSERT.
SQL>declare
v_in varchar2(2000);
ret varchar2(2000);
begin
v_in := 'KLRICE';
EXECUTE IMMEDIATE 'select count(1) from all_objects where owner = :1' into ret using v_in ;
dbms_output.put_line('First Object Count : ' || ret);
EXECUTE IMMEDIATE 'select count(1) from all_objects where owner ='||DBMS_ASSERT.ENQUOTE_LITERAL(v_in) into ret ;
dbms_output.put_line('Second Object Count : ' || ret);
end
SQL> /
First Object Count : 74
Second Object Count : 74
PL/SQL procedure successfully completed.
SQL>
Stored procedures do not keep your database safe. That has never been true.
No language, framework, or API can keep your database safe.
It is the developer's responsibility to write safe code.
If you use EXECUTE IMMEDIATE in an unsafe way, then you have a vulnerability.
The same is true when you don't use stored procedures — if you write dynamic SQL using any application language, you have the same risk of creating SQL injection vulnerabilities.

How to get user of a schema with sql/plsql

I am login with a user abc in a database xyz with Oracle SQL Developer. How can I get the usernames of the schema through which I am logged in?
I believe by usernames you mean operating system usernames. Username in Oracle database (and SQL Developer), is a synonym to the schema name.
So in your case, your schema called abc. Now assume your operating system username is 'John', and you want to know other users who are connected to the schema 'abc', then you can run the query:
SELECT osuser
FROM v$session
WHERE schemaname = 'abc';
Refer to this post for more details
If you just want to know the list of users in the schema you are in, try this:
SELECT * FROM all_users
If you do not change current schema the following code will be fine:
-- In PLSQL
DECLARE
vv_SchemaName VARCHAR2(100);
BEGIN
vv_SchemaName := Sys_Context('USERENV','CURRENT_SCHEMA');
dbms_output.put_line(vv_SchemaName);
END;
-- IN SQL
SELECT Sys_Context('USERENV','CURRENT_SCHEMA') FROM DUAL
Current_schema is a bit different from LOGGED USER see the example:
-- The output will be:
-- Current schema:LOGGED_SCHEMA session user:LOGGED_SCHEMA
-- Current schema:CHANGED_SCHEMA session user:LOGGED_SCHEMA
-- When you are connected to LOGGED_SCHEMA and have CHANGED_SCHEMA.
DECLARE
vv_SchemaName VARCHAR2(100);
vv_SessionUser VARCHAR2(100);
BEGIN
vv_SchemaName := Sys_Context('USERENV','CURRENT_SCHEMA');
vv_SessionUser := Sys_Context('USERENV','SESSION_USER' );
dbms_output.put_line('Current schema:' || vv_SchemaName || ' session user:' || vv_SessionUser);
EXECUTE IMMEDIATE 'ALTER SESSION SET CURRENT_SCHEMA=CHANGED_SCHEMA';
vv_SchemaName := Sys_Context('USERENV','CURRENT_SCHEMA');
vv_SessionUser := Sys_Context('USERENV','SESSION_USER' );
dbms_output.put_line('Current schema:' || vv_SchemaName || ' session user:' || vv_SessionUser);
END;
So If you plan to connect to one user and work on another one than depending on your needs using Sys_Context('USERENV','SESSION_USER' ) may be a better option.

Oracle Procedure with an IF-THEN-ELSE produces error

I have created this procedure in Oracle, to assign a role to a user based on the grade stored in the grade column of the marketing table. However, when I run it I get errors.
Initial Problem
CREATE OR REPLACE PROCEDURE proc_assign_role IS
vn_grade NUMBER(5);
CURSOR cur_user_grade IS
SELECT grade, username
FROM marketing
WHERE grade BETWEEN 1 AND 3;
BEGIN
FOR rec_cur_user_grade IN cur_user_grade
vn_grade:=
IF grade= 1
THEN
GRANT ROLE admin_staff;
ELSIF grade= 2 THEN
GRANT ROLE marketing_staff;
ELSIF grade= 3 THEN
GRANT ROLE event_staff;
END IF;
DBMS_OUTPUT.PUT_LINE(username||'YOU ARE A GRADE '||vn_grade|| 'USER');
END proc_assign_role;
/
This is the error I get:
ERROR at line 11: PLS-00103: Encountered the symbol "VN_GRADE" when expecting one of the following:
. ( * # % & - + / at loop mod remainder range rem ..
|| multiset
1. CREATE OR REPLACE PROCEDURE proc_assign_role IS
2. vn_grade NUMBER(5);
vn_grade:=
You need to assign a value to that line, or get rid of it. You can't assign an IF statement to a number variable. Probably get rid of it, then change your IF statement to look at the grade from the cursor. You also need to end your loop.
Additionally, you can't do a grant directly within a PL/SQL code block. You have to use the execute immediate statement for that. And you have to tell it who you're granting the role to.
FOR rec_cur_user_grade IN cur_user_grade LOOP
IF rec_cur_user_grade.grade= 1 THEN
execute immediate 'GRANT ROLE admin_staff to ' || rec_cur_user_grade.username;
ELSIF rec_cur_user_grade.grade= 2 THEN
execute immediate 'GRANT ROLE marketing_staff to ' || rec_cur_user_grade.username;
ELSIF rec_cur_user_grade.grade= 3 THEN
execute immediate 'GRANT ROLE event_staff to ' || rec_cur_user_grade.username;
END IF;
DBMS_OUTPUT.PUT_LINE(username||'YOU ARE A GRADE '||rec_cur_user_grade.grade|| 'USER');
END LOOP;
I'm seeing a few things that would keep this from working:
After your FOR statement, there's no LOOP statement (which is what the error is complaining about). There's also no END LOOP after your DBMS_OUTPUT.
vn_grade is followed by the := assignment operator, but nothing is being assigned to it.
The GRANT statements are written as bare DDL, which isn't allowed in PL/SQL. They need to be wrapped in EXECUTE IMMEDIATE.
grade and username need to be qualified by the cursor variable (e.g., rec_cur_user_grade.grade and rec_cur_user_grade.username).
Try something like this (which runs as an anonymous block, rather than a procedure, and uses an implicit cursor):
BEGIN
FOR rec_cur_user_grade IN (
SELECT grade, username
FROM marketing
WHERE grade BETWEEN 1 AND 3
)
LOOP
CASE rec_cur_user_grade.grade
WHEN 1 THEN
EXECUTE IMMEDIATE 'GRANT ROLE admin_staff TO ' || rec_cur_user_grade.username;
WHEN 2 THEN
EXECUTE IMMEDIATE 'GRANT ROLE marketing_staff TO ' || rec_cur_user_grade.username;
WHEN 3 THEN
EXECUTE IMMEDIATE 'GRANT ROLE event_staff TO ' || rec_cur_user_grade.username;
END CASE;
DMBS_OUTPUT.PUT_LINE(rec_cur_user_grade.username || ' YOU ARE A GRADE ' || rec_cur_user_grade.grade || ' USER');
END LOOP;
END;
/
grant is DDL and therefore cannot be used in PL/SQL directly. In order to accomplish this, the DDL needs to be executed dynamically, using execute immediately. Additionally, grant always requires you to specify the recipient of the role. The result would be something like this:
execute immediate 'GRANT ROLE admin_staff to ' || rec_cur_user_grade.username;
An ORA-00990: missing or invalid privilege error is fairly self-descriptive: the owner of the procedure does not have the necessary privileges to take the actions being attempted by the procedure.
The most likely culprit here is roles: permissions granted by a role cannot be used in a procedure. The first step you should take is to make sure that the owner of the procedure has been explicitly granted permission to administer the roles involved.