Properly do a deep copy of the ioctls capability array for fget_cap().
authorjhb <jhb@FreeBSD.org>
Tue, 17 Apr 2018 18:07:40 +0000 (18:07 +0000)
committerjhb <jhb@FreeBSD.org>
Tue, 17 Apr 2018 18:07:40 +0000 (18:07 +0000)
commit6d687d59193e83dfb04dbbbd5b50ee74e906d857
treeb75cba04ad1da1ee5c6fd565cc5e203713988fa5
parentc35e9275fc8c33900d745812422d45f6fbd7e630
Properly do a deep copy of the ioctls capability array for fget_cap().

fget_cap() tries to do a cheaper snapshot of a file descriptor without
holding the file descriptor lock.  This snapshot does not do a deep
copy of the ioctls capability array, but instead uses a different
return value to inform the caller to retry the copy with the lock
held.  However, filecaps_copy() was returning 1 to indicate that a
retry was required, and fget_cap() was checking for 0 (actually
'!filecaps_copy()').  As a result, fget_cap() did not do a deep copy
of the ioctls array and just reused the original pointer.  This cause
multiple file descriptor entries to think they owned the same pointer
and eventually resulted in duplicate frees.

The only code path that I'm aware of that triggers this is to create a
listen socket that has a restricted list of ioctls and then call
accept() which calls fget_cap() with a valid filecaps structure from
getsock_cap().

To fix, change the return value of filecaps_copy() to return true if
it succeeds in copying the caps and false if it fails because the lock
is required.  I find this more intuitive than fixing the caller in
this case.  While here, change the return type from 'int' to 'bool'.

Finally, make filecaps_copy() more robust in the failure case by not
copying any of the source filecaps structure over.  This avoids the
possibility of leaking a pointer into a structure if a similar future
caller doesn't properly handle the return value from filecaps_copy()
at the expense of one more branch.

I also added a test case that panics before this change and now passes.

Reviewed by: kib
Discussed with: mjg (not a fan of the extra branch)
MFC after: 1 week
Differential Revision: https://reviews.freebsd.org/D15047
etc/mtree/BSD.tests.dist
sys/kern/kern_descrip.c
sys/sys/filedesc.h
tests/sys/Makefile
tests/sys/capsicum/Makefile [new file with mode: 0644]
tests/sys/capsicum/ioctls_test.c [new file with mode: 0644]