]> kaliko git repositories - sid.git/blob - sid/rtbl.py
424a17982f0ea8e665969dd8c9e6560eb5e61bc9
[sid.git] / sid / rtbl.py
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"""
5
6 from hashlib import sha256
7 from typing import Dict, Optional
8
9 from slixmpp import JID
10 from slixmpp.exceptions import XMPPError
11 from slixmpp.xmlstream import tostring
12
13 from .plugin import Plugin, botcmd
14
15
16 def jid_to_sha256(jid: JID) -> str:
17     """Convert Bare JID to sha256 hexdigest"""
18     return sha256(jid.bare.encode('utf-8')).hexdigest()
19
20
21 class BL:
22     """Plain object to keep track of block list items.
23     Only used in RTBL plugin."""
24     #: Initial seed to ease testing
25     init = {}
26
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)
31
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
36
37     def retract_item(self, item):
38         """remove bl item"""
39         self.sha256_jids.pop(item[id], None)
40
41     def insert_item(self, item):
42         """insert bl item"""
43         text = None
44         for i in item['payload']:
45             try:
46                 text = i.text
47                 break
48             except AttributeError:
49                 continue
50         self.sha256_jids[item['id']] = text
51
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         return self.sha256_jids[jidhash]
56
57     def __len__(self):
58         """Implement the built-in function len(), use for boolean evaluation"""
59         return len(self.sha256_jids)
60
61
62 class RTBL(Plugin):
63     """Spam guard plugin for MUC.
64     """
65     #: Pubsub server
66     pubsub_server = 'example.org'
67     #: Pubsub server node to subscribe to
68     node = 'muc_bans_sha256'
69
70     def __init__(self, bot):
71         Plugin.__init__(self, bot)
72         bot.register_plugin('xep_0059')  # Result Set Management
73         bot.register_plugin('xep_0060')  # Publish-Subscribe
74         self.handlers = [
75                 ('session_start', self._subscribe),
76                 ('pubsub_retract', self._retract),
77                 ('pubsub_publish', self._publish),
78                 (f'muc::{self.bot.room}::presence', self.got_presence),
79                 (f'muc::{self.bot.room}::got_online', self.got_online)
80         ]
81         self.add_handlers()
82         self.bot = bot
83         self.moderator = False
84         self.blocklist: BL = None
85         self.hits = 0
86         self.presences = bot.muc_presences
87
88     def _exit(self):
89         self.rm_handlers()
90         self.bot.unregister_bot_plugin(self)
91
92     async def _subscribe(self, *args):
93         try:
94             nodes = await self.bot['xep_0060'].get_nodes(self.pubsub_server)
95             nodes_av = [_.get('node') for _ in nodes['disco_items']]
96             self.log.debug(f'nodes available: {nodes_av}')
97             if self.node not in nodes_av:
98                 self.log.error(f'{self.node} node not available on {self.pubsub_server}')
99                 await self._create()
100             iq = await self.bot['xep_0060'].subscribe(self.pubsub_server, self.node)
101             subscription = iq['pubsub']['subscription']
102             self.log.info('Subscribed %s to node %s', subscription['jid'], subscription['node'])
103         except XMPPError as error:
104             self.log.error('Could not subscribe %s to node %s: %s',
105                            self.bot.boundjid.full, self.node, error.format())
106             self._exit()
107             return
108         node_blocklist = await self.bot['xep_0060'].get_items(self.pubsub_server, self.node)
109         self.blocklist = BL(node_blocklist['pubsub']['items'])
110         mess = f'Got {len(self.blocklist)} items in block list'
111         self.log.info(mess)
112         # Are current participants in the block list
113         for jid in [pres['muc']['jid'] for pres in self.presences.values()]:
114             await self.rtbl_ban(jid)
115
116     async def _create(self):
117         """Try to create node"""
118         try:
119             await self.bot['xep_0060'].create_node(self.pubsub_server, self.node)
120             self.log.info('Created node %s', self.node)
121         except XMPPError as err:
122             self.log.error('Could not create node %s: %s', self.node, err.format())
123             raise XMPPError(f'Could not create node {self.node}') from err
124
125     def _retract(self, msg):
126         """Handler receiving a retract item event."""
127         self.log.debug('Retracted item %s from %s' % (
128             msg['pubsub_event']['items']['retract']['id'],
129             msg['pubsub_event']['items']['node']))
130         self.blocklist.retract_item(msg['pubsub_event']['items']['retract'])
131
132     async def _publish(self, msg):
133         """Handler receiving a publish item event."""
134         self.log.debug('Published item %s to %s:' % (
135               msg['pubsub_event']['items']['item']['id'],
136               msg['pubsub_event']['items']['node']))
137         data = msg['pubsub_event']['items']['item']['payload']
138         if data is not None:
139             self.log.debug(tostring(data))
140         else:
141             self.log.debug('No item content')
142             return
143         self.blocklist.insert_item(msg['pubsub_event']['items']['item'])
144         # Are current participants in the block list
145         for jid in [pres['muc']['jid'] for pres in self.presences.values()]:
146             await self.rtbl_ban(jid)
147
148     async def rtbl_ban(self, jid: JID):
149         """Ban jid in RTBL"""
150         if not self.moderator or not jid.bare:
151             return
152         if self.blocklist is None:
153             self.log.info('Not checking %s, block list not populated yet', jid)
154             return
155         if self.blocklist.check(jid):
156             self.log.debug(f'About to ban {jid}')
157             reason = self.blocklist.get_reason(jid)
158             if reason is not None:
159                 reason = f'rtbl {reason}'
160             await self.ban(jid.bare, reason=reason)
161             self.hits += 1
162             self.log.info(f'{jid} banned!')
163
164     def got_presence(self, pres):
165         """Does bot have required permissions"""
166         if 110 in pres['muc']['status_codes']:
167             if pres['muc']['role'] != 'moderator':
168                 self.log.error(
169                     'Please give the bot moderator permissions. Will only log actions.'
170                 )
171                 self.moderator = False
172                 return
173             else:
174                 self.log.info('Got moderator permissions.')
175                 self.moderator = True
176                 #TODO: purge presences cache sid.MUCBot.muc_presences?
177
178     async def got_online(self, pres):
179         """Handler method for new MUC participants"""
180         fjid = pres['muc']['jid']
181         await self.rtbl_ban(fjid)
182
183     @botcmd(name="rtbl-info")
184     def rtbl_info(self, rcv, _):
185         """Show RTBL info"""
186         if self.blocklist is None:
187             msg = 'Block list not populated yet'
188             self.log.warning(msg)
189             self.reply(rcv, msg)
190             return
191         msg = f'Got {len(self.blocklist)} items in {RTBL.pubsub_server}/{RTBL.node}'
192         if self.hits > 0:
193             msg+=f' (hits {self.hits})'
194         if not self.moderator:
195             msg+='\nBot has no moderator permissions!'
196         self.reply(rcv, msg)
197
198
199 if __name__ == '__main__':
200     from .cli.rtbl import main
201     main()
202
203 # VIM MODLINE
204 # vim: ai ts=4 sw=4 sts=4 expandtab