Re: plpython: NULL pointer dereference on broken sequence objects

From: Ayush Tiwari <ayushtiwari(dot)slg01(at)gmail(dot)com>
To: Richard Guo <guofenglinux(at)gmail(dot)com>
Cc: Pg Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: Re: plpython: NULL pointer dereference on broken sequence objects
Date: 2026-06-25 13:05:01
Message-ID: CAJTYsWUBacKf_+GyLEdhFQOxrE3cs+RReUizts5D8zCYq_BBzQ@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

On Thu, 25 Jun 2026 at 14:19, Richard Guo <guofenglinux(at)gmail(dot)com> wrote:

> While looking into the recent plperl NULL pointer dereference issue,
> which ended up as 4015abe14, I found a similar issue in plpython, with
> the help of an LLM tool (Claude 4.8).
>
> There are 6 callers of PySequence_GetItem() in plpython, and none of
> them checks the returned result before using it. PySequence_GetItem()
> can return NULL whenever an element cannot be fetched, so an object
> that claims a length it cannot actually deliver is enough to crash the
> backend.
>
> For example:
>
> CREATE FUNCTION test() RETURNS int[] AS $$
> class C:
> def __len__(self):
> return 2
> def __getitem__(self, i):
> raise ValueError('boom')
> return C()
> $$ LANGUAGE plpython3u;
>
> SELECT test(); -- crashes
>
>
> The attached patch checks the result of PySequence_GetItem() in each
> place and errors out if it is NULL.
>

Thanks for the patch and detailed repro.

I applied the patch and it works well, changes too, LGTM.

I think there's a similar problem on the mapping side that v1 doesn't
cover. PLyMapping_ToJsonbValue and the hstore equivalent fetch items with
PyMapping_Items() and PyList_GetItem() without checking for NULL, and a
mapping whose items() raises still would crash the backend.

Regards,
Ayush

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message Amit Kapila 2026-06-25 13:07:06 Re: Proposal: Conflict log history table for Logical Replication
Previous Message Dilip Kumar 2026-06-25 13:00:16 Re: Proposal: Conflict log history table for Logical Replication