0

I have an example of a server that gets commands and returns answers in python:

import socket
import time
import random

CommandDict = {"TIME" : time.strftime("%d-%m-%Y"),"NAME": "Ori","RANDOM": str(random.randint(0,10))}
server_socket = socket.socket()
server_socket.bind(('127.0.0.1',8820))
server_socket.listen(5)

while True:
    print "Waiting for commands"
    (client_socket, client_address) = server_socket.accept()
    client_data = client_socket.recv(1024)
    print "GOT COMMAND FROM " + client_address[0] + " : " + client_data
    try:
        client_socket.send(CommandDict[client_data])
    except Exception:
        client_socket.send("ERROR!")

    client_socket.close()

server_socket.close()

i tried a syn flood attack on it and it crashed. i want to defend it from syn flood attacks, how could i do it? i'm new to socket programming so i would be happy to get some advices ^_^

Chad Nouis
  • 6,861
  • 1
  • 27
  • 28
oridamari
  • 561
  • 7
  • 12
  • 24
  • 3
    How exactly does it crash? – Kevin Panko Dec 12 '14 at 18:03
  • 1
    For one, you don't close client sockets when you are done with them. – Nikolai Fetissov Dec 12 '14 at 18:04
  • before the attack i run the server in the cmd and it prints waiting for commands and after i run the attack it raises an exception: Waiting for commands Traceback (most recent call last): File "C:\Servers\CommandServer\Server.py", line 12, in client_data = client_socket.recv(1024) socket.error: [Errno 10054] ■■τΘßσ° ≈ΘΘφ ≡±Γ° ßδ⌠ΘΣ ≥∞- – oridamari Dec 12 '14 at 18:12
  • 1
    As far as I know, SYN flood attacks have to be dealt with at the OS level. – Russell Borogove Dec 12 '14 at 18:17
  • @RussellBorogove is correct. A "syn flood" means the attacker sends a whole bunch of SYNs (possibly with spoofed source addresses) and never finishes the three-way handshake. The application never sees a connection, because no connections are actually established. – nobody Dec 12 '14 at 18:22

1 Answers1

1

First of all you need a better server. As @Nikolai N Fetlissov pointed out, you are leaking file descriptors since you never closing the client connections.

Look at this example to see how to avoid this leak:

http://ilab.cs.byu.edu/python/socket/echoserver.html

In particular, note where the client.close() call is made and at what indentation level it is.

Next, you code only processes one command from the client. Have a look here:

http://code.activestate.com/recipes/578247-basic-threaded-python-tcp-server/

for a discussion on writing a threaded server which can handle multiple connections and multiple commands from each connection.

Finally, a user-space, socket-based program (more so, written in an interpreted language) is too slow to handle a real SYN flood in just any way. The standard approach is to use firewall software (and, after a certain margin, hardware) for that.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
ErikR
  • 51,541
  • 9
  • 73
  • 124