keyring-util: Use reported key size to resize buf
authorAdrian Vovk <adrianvovk@gmail.com>
Thu, 1 Feb 2024 22:53:01 +0000 (17:53 -0500)
committerLuca Boccassi <luca.boccassi@gmail.com>
Thu, 15 Feb 2024 11:13:34 +0000 (11:13 +0000)
commitd0aef638ac43ad64df920d8b3f6c2d835db7643c
treeb9762934bc7f31f572eed07da5f07a17e47e0285
parent614d09a37dc468d126df40ae649092f927196863
keyring-util: Use reported key size to resize buf

According to keyctl(2), the return value for KEYCTL_READ is:

    The amount of data that is available in the key,
    irrespective of the provided buffer size

So, we could pass in a NULL buffer to query the size, then allocate the
exact right amount of space, then call keyctl again to get the key data.
However, we must still keep the for loop to avoid TOCTOU issues: the key
might have been replaced with something bigger while we're busy
allocating the buffer to store it.

Thus, we can actually save a syscall by picking some reasonable default
buffer size and skipping the NULL call to keyctl. If our default is big
enough, we're done and have saved a syscall! If not, then the first call
behaves essentially the same as the NULL call, and we use the size it
returns to reallocate the buffer appropriately.
src/shared/keyring-util.c