Avoiding Denial of Service attack
when I use recv from windows sockets does using recv can lead t开发者_高级运维o denial of service attack ? If it waits for data forever? So what is the best way for solving this (alarms ?)
Thanks & Regards,
Mousey.
You seem to mis-understand what denial of service means. An example would be a large number of HTTP requests to a single web-server arriving at such a rate that the web-server software becomes so busy it cannot accept new TCP connections. Wikipedia has a decent article on DoS, read it.
recv(2)
is just an API. Misuse of it, as any other bug, can lead to issues, including DoS. But that does not mean you should avoid it. If your problem is blocking other sockets while waiting on a read, look into non-blocking sockets and I/O multiplexing as in select(2)
, poll(2)
, and epoll(4)
.
Yes, recv()
can block indefinitely. You need to implement some sort of time out.
I would recommend using the boost asio library. It includes things like timers that work seamlessly with socket connections and receive events. Just setup an asynchronous socket, add a timer, and break if the time runs out.
This still doesn't make you immune to DoS attacks, as a flood of requests could still come in during the timeout window. But if might help if you set the timeout quite low.
If you are using Blocking sockets look into adjusting the send() and recv() timeouts with the SO_SNDTIMEO and SO_RCVTIMEO setsockopt() options.
There are lots of little complexities in creating a proper server, I would look into acquiring by begging, borrowing or stealing this one. Here is a sample multithreaded socket server.
Also if you have control over both sides (The client and server socket software) I would create a protocol that has the length of the message to be passed in as the first 2 or 4 bytes of the message, that way you just have to block for that decode the number and keep reading until the number of bytes as elapsed. Do that for both the client and the server and it will make your code a lot simpler.
精彩评论