ircfuz/start.py

392 lines
14 KiB
Python
Executable File

#!/usr/bin/env python3
import argparse, select, socket, typing
CAPS = ["multi-prefix", "Chghost", "chghost", "batch", "account-notify", "extended-join", "echo-message", "invite-notify", "draft/labeled-response-0.2", "draft/message-tags", "cap-notify", "bitbot.dev/multiline", "znc.in/self-message", "sasl"]
LONG_PING = "longpong" + ("a"*504)
HENLO = """
dP dP
88 88
88d888b. .d8888b. 88d888b. 88 .d8888b.
88' `88 88ooood8 88' `88 88 88' `88
88 88 88. ... 88 88 88 88. .88
dP dP `88888P' dP dP dP `88888P'
""".split("\n")
class IRCLine(object):
def __init__(self, command: str, args: typing.List[str]):
self.command = command
self.args = args
def __str__(self):
parts = []
parts.append(self.command)
if self.args:
parts.extend(self.args[:-1])
if " " in self.args[-1] or self.args[-1][0] == ":":
parts.append(":%s" % self.args[-1])
else:
parts.append(self.args[-1])
return " ".join(parts)
def _irc_tokenize(line):
tags = None
if line[0] == "@" and " " in line:
tags, line = line.split(" ", 1)
trailing = None
if " :" in line:
line, trailing = line.split(" :", 1)
command, sep, line = line.partition(" ")
command = command.upper()
args = []
if sep:
args = line.split(" ")
if not trailing == None:
args.append(trailing)
return IRCLine(command, args)
class Client(object):
def __init__(self, sock, verbose):
self._socket = sock
self._verbose = verbose
self._read_buffer = b""
self._write_buffer = b""
self.kill_on_write = False
self.connected = True
self.cap_req = []
self.criteria = {
"cap": False,
"cap_302": False,
"cap_req_count": 0,
"cap_list": False,
"sasl_attempt": False,
"pong_colon": False,
"longpong": False,
"longpong_overflow": False,
"spacepong": False,
"lowerpong": False,
"twopong": False,
"twopong_cut": False,
"user_hostname": "",
"user_servername": "",
"nick_first": False,
"protoctl": False
}
self.terminal_pong = False
self.user = False
def fileno(self):
return self._socket.fileno()
def recv(self):
data = self._read_buffer+self._socket.recv(1024)
if not data:
return []
lines = [line.strip(b"\r") for line in data.split(b"\n")]
self._read_buffer = lines.pop(-1)
try:
return [line.decode("utf8") for line in lines]
except:
return []
def send(self, line: str):
if self._verbose:
print("send:", line)
self._write_buffer += ("%s\r\n" % line).encode("utf8")
def _send(self):
try:
bytes_sent = self._socket.send(self._write_buffer)
except:
self.disconnect()
return
self._write_buffer = self._write_buffer[bytes_sent:]
if not self._write_buffer and self.kill_on_write:
self.disconnect()
def write_waiting(self):
return bool(self._write_buffer)
def disconnect(self):
self.connected = False
self._socket.close()
def snotice(self, s: str):
self.send(":ircfuz NOTICE * :%s" % s)
def _detect(client):
if not client.criteria["cap"]:
if (client.criteria["user_hostname"].isdigit() and
client.criteria["user_servername"] == "*"):
if client.criteria["longpong"] or not client.criteria["spacepong"]:
if client.criteria["pong_colon"]:
if client.criteria["lowerpong"]:
return "weechat"
else:
return "erc"
else:
return "limechat"
elif client.criteria["user_hostname"] == "8":
return "polari"
elif (client.criteria["user_hostname"] == "*" and
client.criteria["user_servername"] == "*"):
return "burd"
elif (client.criteria["user_hostname"] == "127.0.0.1" and
client.criteria["user_servername"] == "127.0.0.1"):
return "mibbit"
elif (client.criteria["user_hostname"] == "*" and
not client.criteria["user_servername"] == "*"):
return "pidgin"
elif (client.criteria["user_hostname"] == "+iw" and
not client.criteria["pong_colon"]):
return "bitchx"
elif (client.criteria["longpong"] and
not client.criteria["spacepong"] and
client.criteria["user_hostname"] == "localhost"):
if client.criteria["twopong_cut"]:
return "sic"
else:
return "androirc"
elif client.criteria["user_hostname"].startswith("/"):
return "aicia"
elif client.criteria["longpong_overflow"]:
return "ii"
elif client.criteria["twopong_cut"]:
return "irssi"
elif (not client.criteria["lowerpong"] and
client.criteria["user_servername"] == "0"):
return "turboirc"
else:
if client.criteria["cap_302"]:
if "bitbot.dev/multiline" in client.cap_req:
return "bitbot"
elif client.criteria["user_hostname"] == "8":
return "quassel"
elif client.criteria["twopong"]:
return "irccloud"
elif client.criteria["twopong_cut"]:
if "echo-message" in client.cap_req:
return "thelounge"
else:
return "kiwi"
elif (not client.criteria["user_servername"] == "*" and
client.criteria["pong_colon"]):
if not client.criteria["spacepong"]:
return "icechat"
else:
return "hexchat"
elif (client.criteria["user_hostname"] == "*" and
client.criteria["user_servername"] == "*"):
return "mutter"
elif client.criteria["cap_req_count"] > 1:
if client.criteria["pong_colon"]:
return "mirc"
else:
return "textual"
elif "batch" in client.cap_req and not "chghost" in client.cap_req:
return "revolution"
elif "draft/message-tags" in client.cap_req:
return "palaver"
elif client.criteria["longpong"]:
return "weechat"
else:
return "igloo"
else:
if not client.criteria["user_hostname"].isdigit():
if client.criteria["cap_req_count"] > 1:
return "znc"
elif client.criteria["cap_req_count"] == 1:
return "irssi"
else:
return "qicr"
elif client.criteria["user_hostname"] == "8":
return "konversation"
def _color(irc, value, expected):
if value == expected:
# good
return ("\x0303%s" if irc else "\033[32m%s"
) % value
else:
# bad
return ("\x0304%s" if irc else "\033[31m%s"
) % value
def _result(client, key, expected=None):
value = client.criteria[key]
irc_value = value
print_value = value
if not expected == None:
irc_value = _color(True, value, expected)
print_value = _color(False, value, expected)
print("* %s: %s\033[0m" % (key, print_value))
client.snotice("* %s: %s" % (key, irc_value))
def _end(client):
_result(client, "pong_colon", False)
_result(client, "longpong", False)
_result(client, "longpong_overflow", False)
_result(client, "spacepong", True)
_result(client, "lowerpong", True)
_result(client, "twopong", False)
_result(client, "twopong_cut", False)
_result(client, "cap")
if client.criteria["cap"]:
_result(client, "cap_302")
_result(client, "cap_req_count", 1)
_result(client, "cap_list", False)
_result(client, "sasl_attempt", False)
_result(client, "protoctl")
_result(client, "user_hostname", "0")
_result(client, "user_servername", "*")
_result(client, "nick_first")
detection = _detect(client)
if not detection == None:
print("detected:", detection)
client.snotice("yr %s innit" % detection)
else:
print("detection failed")
client.snotice("idk who u r :(")
client.kill_on_write = True
print("")
def listen(port: int, verbose: bool):
server_socket = socket.socket()
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
server_socket.bind(("", port))
server_socket.listen(1)
clients = {}
while True:
write_waiting = []
dead = []
for fd, client in clients.items():
if not client.connected:
dead.append(fd)
if client.write_waiting():
write_waiting.append(client)
for fd in dead:
del clients[fd]
read_waiting = [server_socket]+list(clients.values())
rsocks, wsocks, esocks = select.select(read_waiting, write_waiting, [])
for client in rsocks:
if client == server_socket:
client, addr = server_socket.accept()
print("new client")
new_client = Client(client, verbose)
clients[client.fileno()] = new_client
for line in HENLO:
new_client.snotice("\x0303%s" % line)
new_client.snotice("detectin yr client lmao")
new_client.send(
":ircfuz 005 * NAMESX :are supported by this server")
new_client.send("PING :cleanping")
new_client.send("PING :%s" % LONG_PING)
new_client.send("PING a :twoping")
new_client.send("ping :lower")
new_client.send("PING :spacepong a")
new_client.send("PING :endpong")
else:
lines = client.recv()
if not lines:
client.connected = False
continue
for raw_line in lines:
if verbose:
print("recv:", raw_line.strip("\r"))
if not raw_line.strip():
continue
line = _irc_tokenize(raw_line)
if line.command == "NICK":
client.criteria["nick_first"] = not client.user
elif line.command == "USER":
client.user = True
client.criteria["user_hostname"] = line.args[1]
client.criteria["user_servername"] = line.args[2]
if not client.criteria["cap"]:
client.terminal_pong = True
elif line.command == "PONG" and line.args:
if "longpong" in line.args[0]:
client.criteria["longpong"] = line.args[0] == LONG_PING
if "\r" in line.args[0]:
client.criteria["longpong_overflow"] = True
client.criteria["pong_colon"] = " :" in raw_line
if line.args[0] == "a twoping":
client.criteria["twopong"] = True
if line.args[0] == "twoping":
client.criteria["twopong_cut"] = True
if line.args[0] == "lower":
client.criteria["lowerpong"] = True
if "spacepong" in line.args[0]:
client.criteria["spacepong"] = " " in line.args[0]
if line.args[0] == "endpong" and client.terminal_pong:
_end(client)
break
elif line.command == "CAP":
client.criteria["cap"] = True
if line.args[0] == "LS":
if len(line.args) > 1 and line.args[1] == "302":
client.criteria["cap_302"] = True
client.send(":ircfuz CAP * LS :%s" % " ".join(CAPS))
elif line.args[0] == "REQ":
client.criteria["cap_req_count"] += 1
caps = line.args[1].split(" ")
client.cap_req.extend(caps)
client.send(":ircfuz CAP * ACK :%s" % line.args[1])
elif line.args[0] == "LIST":
client.criteria["cap_list"] = True
elif line.args[0] == "END":
_end(client)
break
elif line.command == "AUTHENTICATE":
client.criteria["sasl_attempt"] = True
client.send(":ircfuz 904 * :no sasl buddy")
elif line.command == "PROTOCTL":
client.criteria["protoctl"] = True
else:
client.disconnect()
for wsock in wsocks:
wsock._send()
if __name__ == "__main__":
parser = argparse.ArgumentParser("detect IRC clients by handshake behavior")
parser.add_argument("-p", "--port", type=int, default=6661)
parser.add_argument("-V", "--verbose", action="store_true")
args = parser.parse_args()
listen(args.port, args.verbose)