Repository navigation
Expand file tree
/
Copy pathclient.py
More file actions
451 lines (310 loc) · 14.3 KB
/
Copy pathclient.py
File metadata and controls
451 lines (310 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
#!/usr/bin/env python3
# Phaedra - vHost Management & Request Approval Bot
#
# Copyright (C) 2020-2025 Aaron M. D. Jones <aaron@alphachat.net>
#
# This bot matches vHost requests against the Public Suffix List
# (https://publicsuffix.org/learn/). It can automatically reject them
# (when the request matches and the user's control over the domain
# cannot be established) or activate them (when control is established).
# It can also advise staff to activate requests that don't match the
# list.
#
# This program will not function as-is without a custom module loaded
# into Atheme IRC Services. The module's sourcecode is located along-
# side this file in the source repository. The module is necessary to
# perform some up-front request validation (namely, that the vHost
# request must be DNS-legal) and forward the request to the bot,
# denying the request if the bot is not currently online.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import aiodns
import aiohttp
import argparse
import asyncio
import base64
import binascii
import email.utils
import hashlib
import hmac
import os
import re
import signal
import sys
from AlphaChat.ConfigPydle import ConfigPydleClient
from datetime import datetime, timezone
from publicsuffix2 import PublicSuffixList
class PhaedraClient(ConfigPydleClient):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.request_expr = re.compile(r'^VHOSTREQ ([^ ]+) ([^ ]+) ([^ ]+) ([^ ]+)$')
self.resolver = aiodns.DNSResolver(timeout=1, tries=3, domains=[], rotate=True)
self.http_client = None
self.suffix_list = None
self.suffix_lock = asyncio.Lock()
self.acchannels.add(self.acconfig['log_channel'])
self.acchannels.add(self.acconfig['oper_channel'])
def emu_httptime_to_timestamp(self, htime):
return email.utils.parsedate_to_datetime(htime).timestamp()
def emu_timestamp_to_httptime(self, stamp):
return email.utils.formatdate(timeval=stamp, localtime=False, usegmt=True)
def compute_challenge_token(self, secret, netname, entity, account, suffix):
# Entirely arbitrary derivation mechanics
pk = f'netname={netname},entity={entity},account={account},suffix={suffix}'
dk = hashlib.pbkdf2_hmac('sha256', secret.encode('utf-8'), pk.encode('utf-8'), 1000)
tk = base64.b64encode(dk).decode('utf-8')
return (netname + '-dcv.' + suffix, tk)
def load_suffix_list(self, path):
with open(path, 'r') as f:
suffix_list_candidate = PublicSuffixList(psl_file=f, idna=True)
if suffix_list_candidate.get_sld('foo.bar.baz.example.net', strict=True) != 'example.net':
raise Exception('Public Suffix List testcase failed')
self.suffix_list = suffix_list_candidate
async def log_message(self, message):
await self.message(self.acconfig['log_channel'], message)
async def oper_message(self, message):
await self.notice(self.acconfig['oper_channel'], message)
async def update_suffix_list(self):
headers = {}
pslpath = self.acconfig['public_suffix_path']
tmppath = pslpath + '.tmp'
try:
mtime = os.path.getmtime(pslpath)
htime = self.emu_timestamp_to_httptime(mtime)
headers['If-Modified-Since'] = htime
except:
pass
try:
async with self.http_client.get(self.acconfig['update_uri'], headers=headers) as resp:
if resp.status == 304:
if self.suffix_list is None:
self.load_suffix_list(pslpath)
return
if resp.status != 200:
raise Exception(f'Received HTTP response with status code ' \
f'{resp.status}; expected status codes 200 or 304')
if not 'Last-Modified' in resp.headers:
raise Exception(f'Received HTTP response without a Last-Modified header')
with open(tmppath, 'wb') as f:
while True:
chunk = await resp.content.read(4096)
if chunk:
f.write(chunk)
else:
break
f.flush()
os.fsync(f.fileno())
f.close()
htime = resp.headers['Last-Modified']
mtime = self.emu_httptime_to_timestamp(htime)
os.utime(tmppath, (mtime, mtime))
self.load_suffix_list(tmppath)
os.replace(tmppath, pslpath)
suffixcnt = len(self.suffix_list.tlds)
await self.log_message(f'\x0303Updated Public Suffix List ' \
f'(Last-Modified: {htime}) (Suffix Count: {suffixcnt})\x03')
except asyncio.CancelledError:
return
except Exception as e:
await self.log_message(f'\x0304Exception {type(e)} while updating the ' \
f'Public Suffix List: {str(e)}\x03')
async def update_suffix_list_task(self):
try:
while await asyncio.sleep(1, result=True):
current_ts = int(datetime.now(tz=timezone.utc).timestamp())
update_interval = self.acconfig['update_interval']
await asyncio.sleep(update_interval - (current_ts % update_interval))
async with self.suffix_lock:
await self.update_suffix_list()
except asyncio.CancelledError:
return
async def wmessage_header(self, nickname):
await self.wmessage(nickname, f'[Automatic Message] Hello, {nickname}! You are receiving this ' \
f'message because you just requested a vHost that matches the ' \
f'Public Suffix List (https://publicsuffix.org/learn/). ' \
f'Unfortunately, requests for vHosts on this network that match ' \
f'the Public Suffix List (i.e. that could, either now, or in the ' \
f'future, be a registered domain name) must pass domain control ' \
f'validation.')
async def wmessage_footer(self, nickname):
await self.message(nickname, f'Please do not reply; messages to this service are not monitored.')
await self.message(nickname, f'----------------------------------------------------------------')
await self.raw(f'ACCEPT -{nickname}\r\n')
async def approve_request(self, nickname, account, vhost, suffix):
await self.message('HostServ', f'REJECT {account} SILENT')
await self.message('NickServ', f'VHOST {account} ON {vhost} FORCE')
await self.wmessage(nickname, f'Domain control validation for "{suffix}" was successful, ' \
f'and your request for "{vhost}" has been approved.')
await self.wmessage_footer(nickname)
await self.oper_message(f'\x0303The request \x02{vhost}\x02 matches the Public Suffix List, and ' \
f'domain control validation for \x02{account}\x02 succeeded! It has been ' \
f'activated.\x03')
async def reject_no_nameservers(self, nickname, account, vhost, suffix):
await self.message('HostServ', f'REJECT {account} SILENT')
await self.wmessage_header(nickname)
await self.wmessage(nickname, f'However, I failed to validate your control over the ' \
f'suffix "{suffix}", because I am unable to look up its ' \
f'name servers, indicating that it probably does not yet ' \
f'exist as a registered domain name. Therefore, domain ' \
f'control validation cannot proceed, and so your request ' \
f'has been rejected.')
await self.wmessage_footer(nickname)
await self.oper_message(f'\x0304The request \x02{vhost}\x02 matches the Public Suffix ' \
f'List, and domain control validation for \x02{account}\x02 ' \
f'failed! It has been rejected.\x03')
async def reject_record_notfound(self, nickname, account, vhost, suffix, rrname, token):
await self.message('HostServ', f'REJECT {account} SILENT')
await self.wmessage_header(nickname)
await self.wmessage(nickname, f'However, I failed to validate your control over the suffix ' \
f'"{suffix}", because the expected DNS TXT record under it is ' \
f'missing or invalid. Therefore, your request has been rejected. ' \
f'If you do own or control this domain name, and you still wish ' \
f'to request a vHost containing it, please create the following ' \
f'DNS TXT record, wait a few minutes for your DNS provider to ' \
f'put it into place, and then re-submit your request:')
await self.message(nickname, f'Name: {rrname}')
await self.message(nickname, f'Data: {token}')
await self.message(nickname, None)
await self.wmessage_footer(nickname)
await self.oper_message(f'\x0304The request \x02{vhost}\x02 matches the Public Suffix ' \
f'List, and domain control validation for \x02{account}\x02 ' \
f'failed! It has been rejected.\x03')
async def reject_exception(self, nickname, account, vhost, suffix):
await self.message('HostServ', f'REJECT {account} SILENT')
await self.wmessage_header(nickname)
await self.message(nickname, f'However, I failed to validate your control over the suffix ' \
f'"{suffix}", because of an internal error. Therefore, your ' \
f'request has been rejected. The network staff have been ' \
f'notified; please be patient, and do not re-submit your ' \
f'request until told to do so.')
await self.wmessage_footer(nickname)
async def on_autoperform_done(self):
async with self.suffix_lock:
if self.http_client is None:
self.http_client = aiohttp.ClientSession(proxy=self.acconfig['proxy_url'])
try:
await self.update_suffix_list()
except:
pass
await self.add_ev_task(self.update_suffix_list_task())
async def on_disconnect(self, expected):
await super().on_disconnect(expected)
async with self.suffix_lock:
if self.http_client is not None:
await self.http_client.close()
await asyncio.sleep(1)
self.http_client = None
async def on_private_message(self, target, source, message):
await super().on_private_message(target, source, message)
if source != 'HostServ':
return
matches = self.request_expr.fullmatch(message)
if not matches:
return
entity = matches.group(1)
account = matches.group(2)
nickname = matches.group(3)
vhost = matches.group(4)
suffix = None
await self.oper_message(f'The user \x02{nickname}\x02 (account \x02{account}\x02) has ' \
f'requested the vHost \x02{vhost}\x02.')
if self.suffix_list is None:
await self.oper_message(f'\x0304I am unable to match this request against the Public ' \
f'Suffix List because I have failed to parse the list in the ' \
f'past. \x02Please review the request manually.\x02\x03')
return
try:
suffix = self.suffix_list.get_sld(vhost, strict=True)
if suffix is None:
await self.oper_message(f'\x0308It does not match the Public Suffix List; ' \
f'please consider activating it.\x03')
return
except Exception as e:
await self.oper_message(f'\x0304Exception while matching \x02{vhost}\x02 against the ' \
f'Public Suffix List: {str(e)}\x03')
return
try:
candidates = []
try:
results = await self.resolver.query(suffix, 'NS')
if not isinstance(results, list):
results = [results]
for result in results:
candidates.append(result.host)
except aiodns.error.DNSError:
await self.reject_no_nameservers(nickname, account, vhost, suffix)
return
nameservers = []
candidates = list(set(candidates))
for candidate in candidates:
try:
results = await self.resolver.query(candidate, 'AAAA')
if not isinstance(results, list):
results = [results]
for result in results:
nameservers.append(result.host)
except aiodns.error.DNSError:
pass
try:
results = await self.resolver.query(candidate, 'A')
if not isinstance(results, list):
results = [results]
for result in results:
nameservers.append(result.host)
except aiodns.error.DNSError:
pass
nameservers = list(set(nameservers))
if not len(nameservers):
await self.reject_no_nameservers(nickname, account, vhost, suffix)
return
rrname, token = self.compute_challenge_token(self.acconfig['validator_secret'],
self.acconfig['validator_netname'],
entity, account, suffix)
txt_resolver = aiodns.DNSResolver(timeout=1, tries=3, nameservers=nameservers, domains=[],
rotate=True)
try:
results = await txt_resolver.query(rrname, 'TXT')
if not isinstance(results, list):
results = [results]
for result in results:
if result.text == token:
await self.approve_request(nickname, account, vhost, suffix)
return
except aiodns.error.DNSError:
pass
await self.reject_record_notfound(nickname, account, vhost, suffix, rrname, token)
except Exception as e:
await self.reject_exception(nickname, account, vhost, suffix)
await self.oper_message(f'\x0304Exception while handling request for ' \
f'\x02{account}\x02 (\x02{vhost}\x02): {str(e)}\x03')
return
if __name__ == '__main__':
default_config_keys = {
'update_interval': '7200',
'update_uri': 'https://publicsuffix.org/list/public_suffix_list.dat',
'public_suffix_path': 'public_suffix_list.dat',
'proxy_url': None,
}
required_config_keys = [
'log_channel',
'oper_channel',
'validator_netname',
'validator_secret',
]
parser = argparse.ArgumentParser()
parser.add_argument('--config', default='client.yaml')
args = parser.parse_args()
client = PhaedraClient(args.config, default_config_keys, required_config_keys)
client.run()
sys.exit(1)