1 # -*- coding: utf-8 -*-
2 # SPDX-FileCopyrightText: 2023 kaliko <kaliko@azylum.org>
3 # SPDX-License-Identifier: GPL-3.0-or-later
4 """A Real Time Block List plugin"""
6 from hashlib import sha256
7 from typing import Dict, Optional
9 from slixmpp import JID
10 from slixmpp.exceptions import XMPPError
11 from slixmpp.xmlstream import tostring
13 from .plugin import Plugin
16 def jid_to_sha256(jid: JID) -> str:
17 """Convert Bare JID to sha256 hexdigest"""
18 return sha256(jid.bare.encode('utf-8')).hexdigest()
22 """Plain object to keep track of block list items.
23 Only used in RTBL plugin."""
24 #: Initial seed to ease testing
27 def __init__(self, initial_bl):
28 self.sha256_jids: Dict[str, Optional[str]] = dict(BL.init)
29 for item in initial_bl:
30 self.insert_item(item)
32 def check(self, jid: JID) -> bool:
33 """Check the presence of the JID in the blocklist"""
34 jidhash = jid_to_sha256(jid)
35 return jidhash in self.sha256_jids
37 def retract_item(self, item):
39 self.sha256_jids.pop(item[id], None)
41 def insert_item(self, item):
44 for i in item['payload']:
48 except AttributeError:
50 self.sha256_jids[item['id']] = text
52 def get_reason(self, jid: JID) -> Optional[str]:
53 """Check the presence of the JID in the blocklist"""
54 jidhash = jid_to_sha256(jid)
55 # Raises if item does not exist
56 return self.sha256_jids[jidhash]
59 """Implement the built-in function len(), use for boolean evaluation"""
60 return len(self.sha256_jids)
64 """Spam guard plugin for MUC.
67 pubsub_server = 'example.org'
68 #: Pubsub server node to subscribe to
69 node = 'muc_bans_sha256'
71 def __init__(self, bot):
72 Plugin.__init__(self, bot)
73 bot.register_plugin('xep_0059') # Result Set Management
74 bot.register_plugin('xep_0060') # Publish-Subscribe
76 ('session_start', self._subscribe),
77 ('pubsub_retract', self._retract),
78 ('pubsub_publish', self._publish),
79 (f'muc::{self.bot.room}::presence', self.got_presence),
80 (f'muc::{self.bot.room}::got_offline', self.got_offline),
81 (f'muc::{self.bot.room}::got_online', self.got_online)
85 self.participants = set()
86 self.moderator = False
87 self.blocklist: BL = None
91 self.bot.unregister_bot_plugin(self)
93 async def _subscribe(self, *args):
95 nodes = await self.bot['xep_0060'].get_nodes(self.pubsub_server)
96 nodes_av = [_.get('node') for _ in nodes['disco_items']]
97 self.log.debug(f'nodes available: {nodes_av}')
98 if self.node not in nodes_av:
99 self.log.error(f'{self.node} node not available on {self.pubsub_server}')
101 iq = await self.bot['xep_0060'].subscribe(self.pubsub_server, self.node)
102 subscription = iq['pubsub']['subscription']
103 self.log.info('Subscribed %s to node %s', subscription['jid'], subscription['node'])
104 except XMPPError as error:
105 self.log.error('Could not subscribe %s to node %s: %s',
106 self.bot.boundjid.full, self.node, error.format())
109 node_blocklist = await self.bot['xep_0060'].get_items(self.pubsub_server, self.node)
110 self.blocklist = BL(node_blocklist['pubsub']['items'])
111 mess = f'Got {len(self.blocklist)} items in block list'
113 # Are current participants in the block list
114 for jid in list(self.participants):
115 await self.rtbl_ban(jid)
117 async def _create(self):
118 """Try to create node"""
120 await self.bot['xep_0060'].create_node(self.pubsub_server, self.node)
121 self.log.info('Created node %s', self.node)
122 except XMPPError as err:
123 self.log.error('Could not create node %s: %s', self.node, err.format())
124 raise XMPPError(f'Could not create node {self.node}') from err
126 def _retract(self, msg):
127 """Handler receiving a retract item event."""
128 self.log.debug('Retracted item %s from %s' % (
129 msg['pubsub_event']['items']['retract']['id'],
130 msg['pubsub_event']['items']['node']))
131 self.blocklist.retract_item(msg['pubsub_event']['items']['retract'])
133 async def _publish(self, msg):
134 """Handler receiving a publish item event."""
135 self.log.debug('Published item %s to %s:' % (
136 msg['pubsub_event']['items']['item']['id'],
137 msg['pubsub_event']['items']['node']))
138 data = msg['pubsub_event']['items']['item']['payload']
140 self.log.debug(tostring(data))
142 self.log.debug('No item content')
144 self.blocklist.insert_item(msg['pubsub_event']['items']['item'])
145 # Are current participants in the block list
146 for jid in list(self.participants):
147 await self.rtbl_ban(jid)
149 async def rtbl_ban(self, jid):
150 """Ban jid in RTBL"""
151 if not self.moderator:
153 if not self.blocklist:
154 self.log.debug("block list not populated yet")
156 if self.blocklist.check(jid):
157 self.log.debug(f'About to ban {jid}')
158 reason = self.blocklist.get_reason(jid)
159 if reason is not None:
160 reason = f'rtbl {reason}'
161 await self.ban(jid.bare, reason=reason)
163 def got_offline(self, pres):
164 """Handler method for leaving MUC participants"""
165 fjid = pres['muc']['jid']
166 user = fjid if fjid.full else pres['muc']['nick']
168 self.participants.remove(user)
170 self.log.error('KeyError removing participant: "%s"', user)
171 self.log.debug(f'participants: -{user} (len:{len(self.participants)})')
173 def got_presence(self, pres):
174 """Does bot have required permissions"""
175 if 110 in pres['muc']['status_codes']:
176 if pres['muc']['role'] != 'moderator':
178 'Please give the bot moderator permissions. Will only log actions.'
180 self.moderator = False
183 self.log.info('Got moderator permissions.')
184 self.moderator = True
186 async def got_online(self, pres):
187 """Handler method for new MUC participants"""
188 fjid = pres['muc']['jid']
189 user = fjid if fjid.full else pres['muc']['nick']
190 self.participants.add(user)
191 self.log.debug(f'participants: +{user} (len:{len(self.participants)})')
192 await self.rtbl_ban(user)
195 # vim: ai ts=4 sw=4 sts=4 expandtab