inet/cidr: IPv4 prefix length overflows int and passes the range check

Started by Iliia Khaprov25 days ago4 messageshackers
Jump to latest
#1Iliia Khaprov
i.khaprov@gmail.com

Hi,

SELECT '192.168.0.0/4294967320'::inet; -- 2^32 + 24, accepted as
192.168.0.0/24
SELECT '10.0.0.0/4294967304'::cidr; -- 2^32 + 8, accepted as 10.0.0.0/8

Both should fail. These do:

SELECT '192.168.0.0/33'::inet; -- ERROR, 33 > 32
SELECT '192.168.0.0/2494967320'::inet; -- ERROR, wraps negative
SELECT '::1/4294967320'::inet; -- ERROR, IPv6 checks
inside the loop

There is a check, but it runs after the digit loop and tests the wrapped
value, i.e. the prefix length mod 2^32. Any input whose residue lands in
0..32 is accepted:

SELECT '192.168.0.0/4294967296'::inet; -- 2^32 + 0, accepted as
192.168.0.0/0
SELECT '192.168.0.0/4294967314'::inet; -- 2^32 + 18, accepted as
192.168.0.0/18

The attached patch moves the check into the digit loop.

Regards,
Iliia

Attachments:

t254431_1
0001-Reject-IPv4-prefix-lengths-that-overflow-int.patchapplication/octet-stream; name=0001-Reject-IPv4-prefix-lengths-that-overflow-int.patchDownload+20-5
#2Roman Khapov
rkhapov@yandex-team.ru
In reply to: Iliia Khaprov (#1)
Re: inet/cidr: IPv4 prefix length overflows int and passes the range check

Hi!

Moving the check into the digit loop, as
getbits() already does for IPv6, is the right fix IMO.

One minor comment, not a blocker: the IPv6 path
rejects leading zeros in the prefix length
(getbits() returns 0 for inputs like '::1/024', due to the
"no leading zeros" check); maybe do the same for IPv4?

--
Best regards,
Roman Khapov

#3Iliia Khaprov
i.khaprov@gmail.com
In reply to: Roman Khapov (#2)
Re: inet/cidr: IPv4 prefix length overflows int and passes the range check

Hi Roman,

Thanks for looking into this.
I thought about leading zeros, but abandoned it - maybe somebody
relies on this quirk.

Best regards,
Iliia

Show quoted text

On Sat, Oct 31, 2026 at 7:08 PM Roman Khapov <rkhapov@yandex-team.ru> wrote:

Hi!

Moving the check into the digit loop, as
getbits() already does for IPv6, is the right fix IMO.

One minor comment, not a blocker: the IPv6 path
rejects leading zeros in the prefix length
(getbits() returns 0 for inputs like '::1/024', due to the
"no leading zeros" check); maybe do the same for IPv4?

--
Best regards,
Roman Khapov

#4Andrey Rachitskiy
pl0h0yp1@gmail.com
In reply to: Iliia Khaprov (#3)
Re: inet/cidr: IPv4 prefix length overflows int and passes the range check

вт, 3 нояб. 2026 г. в 02:00, Iliia Khaprov <i.khaprov@gmail.com>:

Hi Roman,

Thanks for looking into this.
I thought about leading zeros, but abandoned it - maybe somebody
relies on this quirk.

Hi Iliia,
I already made a patch as part of bug 19671 - please take a look at my
version. It covers IPv4 & IPv6.

Attachments:

t254431_4
0001-Fix-IPv4-CIDR-prefix-length-overflow-in-inet_net_pto.patchtext/x-patch; charset=US-ASCII; name=0001-Fix-IPv4-CIDR-prefix-length-overflow-in-inet_net_pto.patchDownload+68-62