How do I restrict a resource handle I generate to one client from a linux shared library

I have a shared library that hands out an integer handle to a client after a successful connection request. Something like:

int ConnectionRequest(const std::string& authorization_token);

Subsequent actions then need to use that handle to access further operations:

result DoOperation(int handle, const std::string& payload);

It occurred to me that a second client could hijack the connection simply by presenting a plausible handle value to the interface. How do I uniquely link the handle to the client that made the original request? Is there a way to get the process ID from the client and check against it?

Internally I use a std::map to link the handle to a shared_ptr object. All this is in user space.

Coding on linux in C++.

1 answer

  • answered 2020-05-26 20:41 Alex

    Both Linux and Windows have already solved this problem - you can look to their implementations for a working method.

    In short, use multiple tables.

    When referencing handles given out by the kernel, the system needs to ensure that a rogue process can't just steal your file handle and access your data. To do so, the system creates a per-process handle table that contains only the handles relevant to your process. If a rogue process steals one of your handles and tries to use it, they won't be able to access your data - the OS will index their handle table, and find either nothing, or one of their resources.

    You can duplicate this behavior by looking up a handle table via process ID first, then look up the structure with the handle provided. If the process ID doesn't exist in the handle table map, return an error. Otherwise, run the function on the structure referenced by the handle if it exists.