Re: plperl & sort - Mailing list pgsql-bugs

From nathan wagner
Subject Re: plperl & sort
Date
Msg-id 4910D972.8070509@hydaspes.if.org
Whole thread Raw
In response to Re: plperl & sort  (Tom Lane <tgl@sss.pgh.pa.us>)
List pgsql-bugs
Tom Lane wrote:
> Jeff <threshar@threshar.is-a-geek.com> writes:
>> I've ran into this interesting problem.
>> It seems that while you can call sort() in a trusted plperl func you
>> cannot access $a & $b which effectively makes it useless.
>
>> I've tested this on 8.2.11, 8.3.5, and the nov 4 snapshot on ftp.postgresql.org
>> In all cases its on a mac with perl 5.8.8.
>
> I can confirm this behavior with perl 5.10 on Fedora 9.  I suppose the
> Safe module is somehow blocking the variable accesses, but if so why
> doesn't it throw an outright error?  Is this a Safe bug, or are we
> failing to enable something we should, or perhaps it's actually
> necessary to block this for security reasons??  Requires more perl-fu
> than I have, unfortunately.

Completely untested speculation based on my knowledge of perl and
a bit of reading:

The reason you can't see $a and $b is that sort internally sets
these variables in the main package.  That is, sort is setting
$main::a and $main::b, and when you run the plperl code in the
safe compartment, main:: isn't visible any more.

The reason you don't get an error is that unadorned $a and $b
which you reference in the sort routine is relative to the
namespace you give to Safe.  That is, your sort sub is trying
to access $PLPerl::a and $PLPerl::b which isn't what is
set by sort.

It looks like there are two fixes that should work, one sort based
and one Safe based.

sort based: use a subroutine with a prototype.  From perldoc -f sort:

     If the subroutine’s prototype is "($$)", the elements to be
     compared are passed by reference in @_, as for a normal
     subroutine.

Safe based: share the $a and $b variables with the compartment.

$compartment->share_from('main', '$a', '$b');

I'm not sure how postgres embeds perl.  Depending on how the
interpreters are set up, it is conceivable that the contents
of $a and $b could be leaked to other "threads" or similar that
are using the same interpreter.  In any case, using the
share_from() method of Safe would have to be changed at
the postgres level rather than the untrusted language
function writer's level.

I can do some testing if anyone needs something more than
the above suggestions.

--
nw

pgsql-bugs by date:

Previous
From: "Alex Hunsaker"
Date:
Subject: Re: plperl & sort
Next
From: Peter Eisentraut
Date:
Subject: Re: BUG #4509: array_cat's null behaviour is inconsistent