We often see examples of using SocketServer.TCPServer
to set up a TCP server in python.
SocketServer.Example using TCP Server
import SocketServer
HOST, PORT = "", 12345
class SampleHandler(SocketServer.BaseRequestHandler):
def handle(self):
client = self.request
address = self.client_address[0]
client.send("May I ask your name? ")
name = client.recv(80).strip()
self.request.send("Welcome %s from %s\n" % (name, address))
if __name__ == "__main__":
server = SocketServer.TCPServer((HOST, PORT), SampleHandler)
server.serve_forever()
However, with this, only one connection can be processed at one time, and if a new connection request comes during processing, it will wait until the previous processing is completed.
Simply change this SocketServer.TCPServer
to
SocketServer.ThreadingTCPServer` and you will be able to handle multiple connections at the same time.
py:SocketServer.TCP Server Socket Server.Change to Threading TCP Server(Main part only)
if __name__ == "__main__":
server = SocketServer.ThreadingTCPServer((HOST, PORT), SampleHandler)
server.serve_forever()
However, since the number of sockets used will increase, it is advisable to take measures such as setting the upper limit of the number of connections with iptables and shortening the TIME_WAIT time with sysctl. Please adjust the upper limit and time according to the service.
Limit 15 connections from one IP address with iptables settings
-A INPUT -p tcp -m tcp --dport 12345 --tcp-flags FIN,SYN,RST,ACK SYN -m connlimit --connlimit-above 15 --connlimit-mask 32 --connlimit-saddr -j REJECT --reject-with tcp-reset
/etc/sysctl.TIME in conf_WAIT time reduced to 15 seconds(60 seconds when not set)
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 15
Also, if restarting the script causes an error while using the address, it is a good idea to set the address reuse setting on the script side as follows.
import SocketServer
import socket
HOST, PORT = "", 12345
class SampleHandler(SocketServer.BaseRequestHandler, object):
def handle(self):
client = self.request
address = self.client_address[0]
client.send("May I ask your name? ")
name = client.recv(80).strip()
self.request.send("Welcome %s from %s\n" % (name, address))
class SampleServer(SocketServer.ThreadingTCPServer, object):
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
if __name__ == "__main__":
server = SampleServer((HOST, PORT), SampleHandler)
server.serve_forever()
I tried to operate about two CTF problem servers using ThreadingTCPServer.
SECCON CTF 2014 winter online qualifications Choose the number : https://github.com/shiracamus/seccon2014/blob/master/number/number.py Let's disassemble : https://github.com/shiracamus/seccon2014/blob/master/disassemble/disassemble.py
Recommended Posts