ircfuz/start.py

299 lines
10 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 = "a"*512
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 = False
self.cap_req = []
self.cap_302 = False
self.cap_req_count = 0
self.long_pong = False
self.pong_colon = False
self.terminal_pong = False
self.user = False
self.nick_first = False
self.user_hostname = None
self.user_hostname_rfc1459 = False
self.user_servername = None
self.user_servername_rfc1459 = False
self.sent_433 = False
self.retry_nick = ""
self.sasl_attempt = 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):
bytes_sent = self._socket.send(self._write_buffer)
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 _detect(client):
if not client.cap_req:
if (not client.user_hostname_rfc1459 and
not client.user_servername_rfc1459):
if client.long_pong:
if client.pong_colon:
return "weechat"
else:
return "limechat"
elif client.user_hostname == "8":
return "polari"
elif client.user_hostname == "*" and client.user_servername == "*":
return "burd"
elif (client.user_hostname == "127.0.0.1" and
client.user_servername == "127.0.0.1"):
return "mibbit"
elif (client.user_hostname == "*" and
client.user_servername_rfc1459):
return "pidgin"
elif client.user_hostname == "+iw" and not client.pong_colon:
return "bitchx"
else:
if client.cap_302:
if "bitbot.dev/multiline" in client.cap_req:
return "bitbot"
elif client.user_hostname == "8":
return "quassel"
elif client.retry_nick.startswith("nickecho"):
return "thelounge"
elif client.user_servername_rfc1459 and client.pong_colon:
return "hexchat"
elif client.user_hostname == "*" and client.user_servername == "*":
return "mutter"
elif client.cap_req_count > 1:
if client.pong_colon:
return "mirc"
else:
return "textual"
elif "batch" in client.cap_req and not "chghost" in client.cap_req:
if "znc.in/self-message" in client.cap_req:
return "kiwi"
else:
return "revolution"
elif "draft/message-tags" in client.cap_req:
return "palaver"
elif client.long_pong:
if client.retry_nick.endswith("_"):
return "irccloud"
else:
return "weechat"
else:
return "igloo"
else:
if client.user_hostname_rfc1459:
if client.cap_req_count > 1:
return "znc"
else:
return "irssi"
elif client.user_hostname == "8":
return "konversation"
def _end(client):
print("long pong:", client.long_pong)
print("pong colon:", client.pong_colon)
print("nick first:", client.nick_first)
print("retry nick:", client.retry_nick)
print("hostname servername:", client.user_hostname, client.user_servername)
print("ircv3:", client.cap)
if client.cap:
print("cap req 302:", client.cap_302)
print("caps:", ", ".join(sorted(client.cap_req)))
print("cap req count:", client.cap_req_count)
detection = _detect(client)
if not detection == None:
print("detected:", detection)
client.send(":ircfuz NOTICE * :yr %s innit" % detection)
else:
print("detection failed")
client.send(":ircfuz NOTICE * :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 rsock in rsocks:
if rsock == 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.send(":ircfuz NOTICE * :\x0303%s" % line)
new_client.send(":ircfuz NOTICE * :detectin yr client lmao")
new_client.send("PING :%s" % LONG_PING)
else:
lines = rsock.recv()
if not lines:
client.connected = False
continue
for raw_line in lines:
if verbose:
print("recv:", raw_line)
if not raw_line.strip():
continue
line = _irc_tokenize(raw_line)
if line.command == "NICK":
if not client.sent_433:
client.sent_433 = True
client.nick_first = not client.user
client.send(":ircfuz 433 * nickecho :nah lol")
else:
client.retry_nick = line.args[0]
elif line.command == "USER":
client.user = True
client.user_hostname = line.args[1]
if not line.args[1].isdigit():
client.user_hostname_rfc1459 = True
client.user_servername = line.args[2]
if not line.args[2] == "*":
client.user_servername_rfc1459 = True
if not client.cap:
client.terminal_pong = True
elif line.command == "PONG":
client.pong_colon = " :" in raw_line
client.long_pong = line.args[0] == LONG_PING
if client.terminal_pong:
_end(client)
break
elif line.command == "CAP":
client.cap = True
if line.args[0] == "LS":
if len(line.args) > 1 and line.args[1] == "302":
client.cap_302 = True
client.send(":ircfuz CAP * LS :%s" % " ".join(CAPS))
elif line.args[0] == "REQ":
client.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] == "END":
_end(client)
break
elif line.command == "AUTHENTICATE":
client.sasl_attempt = True
client.send(":ircfuz 904 * :no sasl buddy")
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)