13.8. Guarding Against Creating Too Many Network Sockets
Problem
You need to limit the number of network sockets that your program can create.
Solution
Limiting the number of sockets that can be created in an application
is a good way to mitigate potential denial of service attacks by
preventing an attacker from creating too many open sockets for your
program to be able to handle. Imposing a limit on sockets is a simple
matter of maintaining a count of the number of sockets that have been
created so far. To do this, you will need to appropriately wrap three
socket functions. The first two functions that need to be wrapped,
socket( )
and accept( )
, are
used to obtain new socket descriptors, and they should be modified to
increment the number of sockets when they’re
successful. The third function, close( )
(closesocket( )
on Windows), is used to dispose of
an existing socket descriptor, and it should be modified to decrement
the number of sockets when it’s successful.
Discussion
To limit the number of sockets that can be created, the first step is
to call spc_socketpool_init(
)
to initialize the socket pool code. On Unix,
this does nothing, but it is required on Windows to initialize two
synchronization objects. Once the socket pool code is initialized,
the next step is to call spc_socketpool_setlimit(
)
with the maximum number of sockets to allow. In our implementation, any limit less than or equal to zero disables limiting sockets but causes them still to be counted. We have written ...
Get Secure Programming Cookbook for C and C++ now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.