Check the fd number against FD_SETSIZE in PQsocketPoll

Started by Roman Khapov26 days ago2 messageshackers
Jump to latest
#1Roman Khapov
rkhapov@yandex-team.ru

Hi hackers!

While digging into the pgbench client fd handling discussed in [0]/messages/by-id/5EF180BD-3951-4E8C-903D-D91EF54A338D@yandex-team.ru
(the FD_SETSIZE cap on select(2)-based platforms), I also looked
at the client-side library itself and noticed that libpq
has the same latent problem.

PQsocketPoll() uses poll(2) when available, but its fallback path calls
select(2) with FD_SET(sock, ...) on a socket descriptor without any check.
If the application happens to hold a thousand or so open files before connecting, socket(2) can return an fd >= FD_SETSIZE, and FD_SET() then silently writes beyond the fd_set - i.e. stack corruption.

Patch attached: fail cleanly with EINVAL instead of corrupting the stack. This only affects platforms without poll(2) (essentially Windows and ancient Unixes?), and the branch is not even compiled on modern systems... but I think defending here is cheap and worthwhile.

[0]: /messages/by-id/5EF180BD-3951-4E8C-903D-D91EF54A338D@yandex-team.ru

--
Best regards,
Roman Khapov

Attachments:

t254443_1
0001-libpq-guard-select-fallback-against-fds-FD_SETSIZE.patchapplication/octet-stream; name=0001-libpq-guard-select-fallback-against-fds-FD_SETSIZE.patch; x-unix-mode=0644Download+10-1
#2Roman Khapov
rkhapov@yandex-team.ru
In reply to: Roman Khapov (#1)
Re: Check the fd number against FD_SETSIZE in PQsocketPoll

Patch attached: fail cleanly with EINVAL instead of corrupting the stack. This only affects platforms without poll(2) (essentially Windows and ancient Unixes?), and the

Well, testing on Windows showed that assumption was incorrect, and the
check is not needed on Windows. So now patch fixes only
the Unix without poll(2), what sounds mostly theoretical...

Anyway, attached the v2.

--
Best regards,
Roman Khapov

Attachments:

t254443_2
v2-0001-libpq-guard-select-fallback-against-fds-FD_SETSIZ.patchapplication/octet-stream; name=v2-0001-libpq-guard-select-fallback-against-fds-FD_SETSIZ.patch; x-unix-mode=0644Download+14-1