TCP server security – LINQ and C#
I’m currently working on a TCP client/server system, and I wanted to prevent clients from DoSing the server.
One way to do that is by restricting clients to a certain number of connections in a given time period. Since the code is designed to prevent a DoS condition, it must be extremely fast and efficient because it may be run thousands of times per minute (during a DoS attack for example).
I designed the connection limit system around a collection of connection records, a prune timer, and a test when the server accepts a client connection.
Since I needed to check two variables (timestamp and ip) in each connection record to determine the connection count for a given IP address in a given time period, I decided to use LINQ, which worked nicely:
// Get this client's connection count
int connCount = (from conn in _connectionList
where conn.Ip == clientIp &&
conn.Timestamp >
DateTime.Now.AddMinutes(-howFarBackInMinutesToCheck)
select conn.Ip).Count();
The other query I needed was for pruning the connection list:
// Get the connections to prune
var connQuery = from conn in _connections
where conn.Timestamp <
DateTime.Now.AddMinutes(-howFarBackInMinutesToCheck)
select conn;
After checking the number of records to prune was greater than zero (connQuery.Count()), I pruned them by iterating through the query (LINQ queries implement IEnumerable).