fetch_blocks.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. from reqto import get
  2. from reqto import post
  3. from hashlib import sha256
  4. import sqlite3
  5. from bs4 import BeautifulSoup
  6. from json import dumps
  7. from json import loads
  8. import re
  9. from time import time
  10. import itertools
  11. with open("config.json") as f:
  12. config = loads(f.read())
  13. headers = {
  14. "user-agent": config["useragent"]
  15. }
  16. def send_bot_post(instance: str, blocks: dict):
  17. message = instance + " has blocked the following instances:\n\n"
  18. truncated = False
  19. if len(blocks) > 20:
  20. truncated = True
  21. blocks = blocks[0 : 19]
  22. for block in blocks:
  23. if block["reason"] == None or block["reason"] == '':
  24. message = message + block["blocked"] + " with unspecified reason\n"
  25. else:
  26. if len(block["reason"]) > 420:
  27. block["reason"] = block["reason"][0:419] + "[…]"
  28. message = message + block["blocked"] + ' for "' + block["reason"].replace("@", "@\u200b") + '"\n'
  29. if truncated:
  30. message = message + "(the list has been truncated to the first 20 entries)"
  31. botheaders = {**headers, **{"Authorization": "Bearer " + config["bot_token"]}}
  32. req = post(f"{config['bot_instance']}/api/v1/statuses",
  33. data={"status":message, "visibility":config['bot_visibility'], "content_type":"text/plain"},
  34. headers=botheaders, timeout=10).json()
  35. return True
  36. def get_mastodon_blocks(domain: str) -> dict:
  37. blocks = {
  38. "Suspended servers": [],
  39. "Filtered media": [],
  40. "Limited servers": [],
  41. "Silenced servers": [],
  42. }
  43. translations = {
  44. "Silenced instances": "Silenced servers",
  45. "Suspended instances": "Suspended servers",
  46. "Gesperrte Server": "Suspended servers",
  47. "Gefilterte Medien": "Filtered media",
  48. "Stummgeschaltete Server": "Silenced servers",
  49. "停止済みのサーバー": "Suspended servers",
  50. "メディアを拒否しているサーバー": "Filtered media",
  51. "サイレンス済みのサーバー": "Silenced servers",
  52. "שרתים מושעים": "Suspended servers",
  53. "מדיה מסוננת": "Filtered media",
  54. "שרתים מוגבלים": "Silenced servers",
  55. "Serveurs suspendus": "Suspended servers",
  56. "Médias filtrés": "Filtered media",
  57. "Serveurs limités": "Silenced servers",
  58. }
  59. try:
  60. doc = BeautifulSoup(
  61. get(f"https://{domain}/about/more", headers=headers, timeout=5, allow_redirects=False).text,
  62. "html.parser",
  63. )
  64. except:
  65. return {}
  66. for header in doc.find_all("h3"):
  67. header_text = header.text
  68. if header_text in translations:
  69. header_text = translations[header_text]
  70. if header_text in blocks:
  71. # replaced find_next_siblings with find_all_next to account for instances that e.g. hide lists in dropdown menu
  72. for line in header.find_all_next("table")[0].find_all("tr")[1:]:
  73. blocks[header_text].append(
  74. {
  75. "domain": line.find("span").text,
  76. "hash": line.find("span")["title"][9:],
  77. "reason": line.find_all("td")[1].text.strip(),
  78. }
  79. )
  80. return {
  81. "reject": blocks["Suspended servers"],
  82. "media_removal": blocks["Filtered media"],
  83. "followers_only": blocks["Limited servers"]
  84. + blocks["Silenced servers"],
  85. }
  86. def get_friendica_blocks(domain: str) -> dict:
  87. blocks = []
  88. try:
  89. doc = BeautifulSoup(
  90. get(f"https://{domain}/friendica", headers=headers, timeout=5, allow_redirects=False).text,
  91. "html.parser",
  92. )
  93. except:
  94. return {}
  95. blocklist = doc.find(id="about_blocklist")
  96. for line in blocklist.find("table").find_all("tr")[1:]:
  97. blocks.append(
  98. {
  99. "domain": line.find_all("td")[0].text.strip(),
  100. "reason": line.find_all("td")[1].text.strip()
  101. }
  102. )
  103. return {
  104. "reject": blocks
  105. }
  106. def get_pisskey_blocks(domain: str) -> dict:
  107. blocks = {
  108. "suspended": [],
  109. "blocked": []
  110. }
  111. try:
  112. counter = 0
  113. step = 99
  114. while True:
  115. # iterating through all "suspended" (follow-only in its terminology) instances page-by-page, since that troonware doesn't support sending them all at once
  116. try:
  117. if counter == 0:
  118. doc = post(f"https://{domain}/api/federation/instances", data=dumps({"sort":"+caughtAt","host":None,"suspended":True,"limit":step}), headers={**headers, **{"Content-Type": "application/json"}}, timeout=5, allow_redirects=False).json()
  119. if doc == []: raise
  120. else:
  121. doc = post(f"https://{domain}/api/federation/instances", data=dumps({"sort":"+caughtAt","host":None,"suspended":True,"limit":step,"offset":counter-1}), headers={**headers, **{"Content-Type": "application/json"}}, timeout=5, allow_redirects=False).json()
  122. if doc == []: raise
  123. for instance in doc:
  124. # just in case
  125. if instance["isSuspended"]:
  126. blocks["suspended"].append(
  127. {
  128. "domain": instance["host"],
  129. # no reason field, nothing
  130. "reason": ""
  131. }
  132. )
  133. counter = counter + step
  134. # for now I'll assume no one in their right mind would block more than 2500 instances
  135. # greetings to abstroonztaube
  136. if counter > 2500:
  137. break
  138. except:
  139. counter = 0
  140. break
  141. while True:
  142. # same shit, different asshole ("blocked" aka full suspend)
  143. try:
  144. if counter == 0:
  145. doc = post(f"https://{domain}/api/federation/instances", data=dumps({"sort":"+caughtAt","host":None,"blocked":True,"limit":step}), headers={**headers, **{"Content-Type": "application/json"}}, timeout=5, allow_redirects=False).json()
  146. if doc == []: raise
  147. else:
  148. doc = post(f"https://{domain}/api/federation/instances", data=dumps({"sort":"+caughtAt","host":None,"blocked":True,"limit":step,"offset":counter-1}), headers={**headers, **{"Content-Type": "application/json"}}, timeout=5, allow_redirects=False).json()
  149. if doc == []: raise
  150. for instance in doc:
  151. if instance["isBlocked"]:
  152. blocks["blocked"].append(
  153. {
  154. "domain": instance["host"],
  155. "reason": ""
  156. }
  157. )
  158. counter = counter + step
  159. if counter > 2500:
  160. break
  161. except:
  162. counter = 0
  163. break
  164. return {
  165. "reject": blocks["blocked"],
  166. "followers_only": blocks["suspended"]
  167. }
  168. except:
  169. return {}
  170. def get_hash(domain: str) -> str:
  171. return sha256(domain.encode("utf-8")).hexdigest()
  172. def get_type(domain: str) -> str:
  173. try:
  174. res = get(f"https://{domain}/nodeinfo/2.1.json", headers=headers, timeout=5, allow_redirects=False)
  175. if res.status_code == 404:
  176. res = get(f"https://{domain}/nodeinfo/2.0", headers=headers, timeout=5, allow_redirects=False)
  177. if res.status_code == 404:
  178. res = get(f"https://{domain}/nodeinfo/2.0.json", headers=headers, timeout=5, allow_redirects=False)
  179. if res.ok and "text/html" in res.headers["content-type"]:
  180. res = get(f"https://{domain}/nodeinfo/2.1", headers=headers, timeout=5, allow_redirects=False)
  181. if res.ok:
  182. if res.json()["software"]["name"] in ["akkoma", "rebased", "incestoma"]:
  183. return "pleroma"
  184. elif res.json()["software"]["name"] in ["hometown", "ecko"]:
  185. return "mastodon"
  186. elif res.json()["software"]["name"] in ["calckey", "groundpolis", "foundkey", "cherrypick", "firefish", "iceshrimp", "sharkey", "catodon"]:
  187. return "misskey"
  188. else:
  189. return res.json()["software"]["name"]
  190. elif res.status_code == 404:
  191. res = get(f"https://{domain}/api/v1/instance", headers=headers, timeout=5, allow_redirects=False)
  192. if res.ok:
  193. return "mastodon"
  194. except:
  195. return None
  196. def tidyup(domain: str) -> str:
  197. # some retards put their blocks in variable case
  198. domain = domain.lower()
  199. # other retards put the port
  200. domain = re.sub("\:\d+$", "", domain)
  201. # bigger retards put the schema in their blocklist, sometimes even without slashes
  202. domain = re.sub("^https?\:(\/*)", "", domain)
  203. # and trailing slash
  204. domain = re.sub("\/$", "", domain)
  205. # and the @
  206. domain = re.sub("^\@", "", domain)
  207. # the biggest retards of them all try to block individual users
  208. domain = re.sub("(.+)\@", "", domain)
  209. # some retards also started putting a single asterisk without dot for subdomain blocks
  210. if domain.count("*") <= 1 and domain.startswith("*"):
  211. domain = re.sub("^\*", "*.", domain)
  212. domain = re.sub("^\*\.\.", "*.", domain)
  213. # and a dot before the domain
  214. domain = re.sub("^\.", "", domain)
  215. # and whitespaces in the beginning/end
  216. domain = re.sub("^\ ", "", domain)
  217. domain = re.sub("\ $", "", domain)
  218. return domain
  219. conn = sqlite3.connect("blocks.db")
  220. c = conn.cursor()
  221. c.execute(
  222. # lemmy's broken at the moment
  223. "select domain, software from instances where software in ('pleroma', 'mastodon', 'friendica', 'misskey', 'gotosocial')"
  224. )
  225. for blocker, software in c.fetchall():
  226. blockdict = []
  227. blocker = tidyup(blocker)
  228. if software == "pleroma":
  229. print(blocker)
  230. try:
  231. # Blocks
  232. federation = get(
  233. f"https://{blocker}/nodeinfo/2.1.json", headers=headers, timeout=5, allow_redirects=False
  234. ).json()["metadata"]["federation"]
  235. if "mrf_simple" in federation:
  236. for block_level, blocks in (
  237. {**federation["mrf_simple"],
  238. **{"quarantined_instances": federation["quarantined_instances"]}}
  239. ).items():
  240. for blocked in blocks:
  241. blocked = tidyup(blocked)
  242. if blocked == "":
  243. continue
  244. if blocked.count("*") > 1:
  245. # -ACK!-oma also started obscuring domains without hash
  246. c.execute(
  247. "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
  248. )
  249. searchres = c.fetchone()
  250. if searchres != None:
  251. blocked = searchres[0]
  252. c.execute(
  253. "select domain from instances where domain = ?", (blocked,)
  254. )
  255. if c.fetchone() == None:
  256. c.execute(
  257. "insert into instances select ?, ?, ?",
  258. (blocked, get_hash(blocked), get_type(blocked)),
  259. )
  260. timestamp = int(time())
  261. c.execute(
  262. "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
  263. (blocker, blocked, block_level),
  264. )
  265. if c.fetchone() == None:
  266. c.execute(
  267. "insert into blocks select ?, ?, '', ?, ?, ?",
  268. (blocker, blocked, block_level, timestamp, timestamp),
  269. )
  270. if block_level == "reject":
  271. blockdict.append(
  272. {
  273. "blocked": blocked,
  274. "reason": None
  275. })
  276. else:
  277. c.execute(
  278. "update blocks set last_seen = ? where blocker = ? and blocked = ? and block_level = ?",
  279. (timestamp, blocker, blocked, block_level)
  280. )
  281. conn.commit()
  282. # Reasons
  283. if "mrf_simple_info" in federation:
  284. for block_level, info in (
  285. {**federation["mrf_simple_info"],
  286. **(federation["quarantined_instances_info"]
  287. if "quarantined_instances_info" in federation
  288. else {})}
  289. ).items():
  290. for blocked, reason in info.items():
  291. blocked = tidyup(blocked)
  292. if blocked == "":
  293. continue
  294. if blocked.count("*") > 1:
  295. # same domain guess as above, but for reasons field
  296. c.execute(
  297. "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
  298. )
  299. searchres = c.fetchone()
  300. if searchres != None:
  301. blocked = searchres[0]
  302. c.execute(
  303. "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ? and reason = ''",
  304. (reason["reason"], blocker, blocked, block_level),
  305. )
  306. for entry in blockdict:
  307. if entry["blocked"] == blocked:
  308. entry["reason"] = reason["reason"]
  309. conn.commit()
  310. except Exception as e:
  311. print("error:", e, blocker)
  312. elif software == "mastodon":
  313. print(blocker)
  314. try:
  315. # json endpoint for newer mastodongs
  316. try:
  317. json = {
  318. "reject": [],
  319. "media_removal": [],
  320. "followers_only": [],
  321. "report_removal": []
  322. }
  323. # handling CSRF, I've saw at least one server requiring it to access the endpoint
  324. meta = BeautifulSoup(
  325. get(f"https://{blocker}/about", headers=headers, timeout=5, allow_redirects=False).text,
  326. "html.parser",
  327. )
  328. try:
  329. csrf = meta.find("meta", attrs={"name": "csrf-token"})["content"]
  330. reqheaders = {**headers, **{"x-csrf-token": csrf}}
  331. except:
  332. reqheaders = headers
  333. blocks = get(
  334. f"https://{blocker}/api/v1/instance/domain_blocks", headers=reqheaders, timeout=5, allow_redirects=False
  335. ).json()
  336. for block in blocks:
  337. entry = {'domain': block['domain'], 'hash': block['digest'], 'reason': block['comment']}
  338. if block['severity'] == 'suspend':
  339. json['reject'].append(entry)
  340. elif block['severity'] == 'silence':
  341. json['followers_only'].append(entry)
  342. elif block['severity'] == 'reject_media':
  343. json['media_removal'].append(entry)
  344. elif block['severity'] == 'reject_reports':
  345. json['report_removal'].append(entry)
  346. except:
  347. json = get_mastodon_blocks(blocker)
  348. for block_level, blocks in json.items():
  349. for instance in blocks:
  350. blocked, blocked_hash, reason = instance.values()
  351. blocked = tidyup(blocked)
  352. if blocked.count("*") <= 1 and blocked.startswith("*"):
  353. c.execute(
  354. "select hash from instances where hash = ?", (blocked_hash,)
  355. )
  356. if c.fetchone() == None:
  357. c.execute(
  358. "insert into instances select ?, ?, ?",
  359. (blocked, get_hash(blocked), get_type(blocked)),
  360. )
  361. else:
  362. # Doing the hash search for instance names as well to tidy up DB
  363. c.execute(
  364. "select domain from instances where hash = ?", (blocked_hash,)
  365. )
  366. searchres = c.fetchone()
  367. if searchres != None:
  368. blocked = searchres[0]
  369. else:
  370. # Apparently, some instances return incorrect hashes for whatever reason
  371. # I've tested one of them, and those hashes correspond to the already obscured domain
  372. # That doesn't make any sense unless someone obscured the domain themselves and put it into the blocklist, but whatever
  373. c.execute(
  374. "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
  375. )
  376. searchres = c.fetchone()
  377. if searchres != None:
  378. blocked = searchres[0]
  379. timestamp = int(time())
  380. c.execute(
  381. "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
  382. (blocker, blocked if blocked.count("*") <= 1 else blocked_hash, block_level),
  383. )
  384. if c.fetchone() == None:
  385. c.execute(
  386. "insert into blocks select ?, ?, ?, ?, ?, ?",
  387. (
  388. blocker,
  389. blocked if blocked.count("*") <= 1 else blocked_hash,
  390. reason,
  391. block_level,
  392. timestamp,
  393. timestamp,
  394. ),
  395. )
  396. if block_level == "reject":
  397. blockdict.append(
  398. {
  399. "blocked": blocked,
  400. "reason": reason
  401. })
  402. else:
  403. c.execute(
  404. "update blocks set last_seen = ? where blocker = ? and blocked = ? and block_level = ?",
  405. (timestamp, blocker, blocked if blocked.count("*") <= 1 else blocked_hash, block_level),
  406. )
  407. if reason != '':
  408. c.execute(
  409. "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ? and reason = ''",
  410. (reason, blocker, blocked if blocked.count("*") <= 1 else blocked_hash, block_level),
  411. )
  412. conn.commit()
  413. except Exception as e:
  414. print("error:", e, blocker)
  415. elif software == "friendica" or software == "misskey":
  416. print(blocker)
  417. try:
  418. if software == "friendica":
  419. json = get_friendica_blocks(blocker)
  420. elif software == "misskey":
  421. json = get_pisskey_blocks(blocker)
  422. for block_level, blocks in json.items():
  423. for instance in blocks:
  424. blocked, reason = instance.values()
  425. blocked = tidyup(blocked)
  426. if blocked.count("*") > 0:
  427. # Some friendica servers also obscure domains without hash
  428. c.execute(
  429. "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
  430. )
  431. searchres = c.fetchone()
  432. if searchres != None:
  433. blocked = searchres[0]
  434. if blocked.count("?") > 0:
  435. # Some obscure them with question marks, not sure if that's dependent on version or not
  436. c.execute(
  437. "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("?", "_"),)
  438. )
  439. searchres = c.fetchone()
  440. if searchres != None:
  441. blocked = searchres[0]
  442. timestamp = int(time())
  443. c.execute(
  444. "select * from blocks where blocker = ? and blocked = ?",
  445. (blocker, blocked),
  446. )
  447. if c.fetchone() == None:
  448. c.execute(
  449. "insert into blocks select ?, ?, ?, ?, ?, ?",
  450. (
  451. blocker,
  452. blocked,
  453. reason,
  454. block_level,
  455. timestamp,
  456. timestamp
  457. ),
  458. )
  459. if block_level == "reject":
  460. blockdict.append(
  461. {
  462. "blocked": blocked,
  463. "reason": reason
  464. })
  465. else:
  466. c.execute(
  467. "update blocks set last_seen = ? where blocker = ? and blocked = ? and block_level = ?",
  468. (timestamp, blocker, blocked, block_level),
  469. )
  470. if reason != '':
  471. c.execute(
  472. "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ? and reason = ''",
  473. (reason, blocker, blocked, block_level),
  474. )
  475. conn.commit()
  476. except Exception as e:
  477. print("error:", e, blocker)
  478. elif software == "gotosocial":
  479. print(blocker)
  480. try:
  481. # Blocks
  482. federation = get(
  483. f"https://{blocker}/api/v1/instance/peers?filter=suspended", headers=headers, timeout=5, allow_redirects=False
  484. ).json()
  485. for peer in federation:
  486. blocked = peer["domain"].lower()
  487. if blocked.count("*") > 0:
  488. # GTS does not have hashes for obscured domains, so we have to guess it
  489. c.execute(
  490. "select domain from instances where domain like ? order by rowid limit 1", (blocked.replace("*", "_"),)
  491. )
  492. searchres = c.fetchone()
  493. if searchres != None:
  494. blocked = searchres[0]
  495. c.execute(
  496. "select domain from instances where domain = ?", (blocked,)
  497. )
  498. if c.fetchone() == None:
  499. c.execute(
  500. "insert into instances select ?, ?, ?",
  501. (blocked, get_hash(blocked), get_type(blocked)),
  502. )
  503. c.execute(
  504. "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
  505. (blocker, blocked, "reject"),
  506. )
  507. timestamp = int(time())
  508. if c.fetchone() == None:
  509. c.execute(
  510. "insert into blocks select ?, ?, ?, ?, ?, ?",
  511. (blocker, blocked, "", "reject", timestamp, timestamp),
  512. )
  513. blockdict.append(
  514. {
  515. "blocked": blocked,
  516. "reason": None
  517. })
  518. else:
  519. c.execute(
  520. "update blocks set last_seen = ? where blocker = ? and blocked = ? and block_level = ?",
  521. (timestamp, blocker, blocked, "reject"),
  522. )
  523. if "public_comment" in peer:
  524. reason = peer["public_comment"]
  525. c.execute(
  526. "update blocks set reason = ? where blocker = ? and blocked = ? and block_level = ? and reason = ''",
  527. (reason, blocker, blocked, "reject"),
  528. )
  529. for entry in blockdict:
  530. if entry["blocked"] == blocked:
  531. entry["reason"] = reason
  532. conn.commit()
  533. except Exception as e:
  534. print("error:", e, blocker)
  535. elif software == "lemmy":
  536. # looks like there's no reason field or obscured domain names yet
  537. print(blocker)
  538. try:
  539. # Blocks
  540. federation = get(
  541. f"https://{blocker}/api/v3/site", headers=headers, timeout=5, allow_redirects=False
  542. ).json()
  543. blocks = federation['federated_instances']['blocked']
  544. for blocked in blocks:
  545. blocked = tidyup(blocked)
  546. c.execute(
  547. "select domain from instances where domain = ?", (blocked,)
  548. )
  549. if c.fetchone() == None:
  550. c.execute(
  551. "insert into instances select ?, ?, ?",
  552. (blocked, get_hash(blocked), get_type(blocked)),
  553. )
  554. c.execute(
  555. "select * from blocks where blocker = ? and blocked = ? and block_level = ?",
  556. (blocker, blocked, "reject"),
  557. )
  558. timestamp = int(time())
  559. if c.fetchone() == None:
  560. c.execute(
  561. "insert into blocks select ?, ?, ?, ?, ?, ?",
  562. (blocker, blocked, "", "reject", timestamp, timestamp),
  563. )
  564. blockdict.append(
  565. {
  566. "blocked": blocked,
  567. "reason": None
  568. })
  569. else:
  570. c.execute(
  571. "update blocks set last_seen = ? where blocker = ? and blocked = ? and block_level = ?",
  572. (timestamp, blocker, blocked, "reject"),
  573. )
  574. conn.commit()
  575. except Exception as e:
  576. print("error:", e, blocker)
  577. if config["bot_enabled"] and len(blockdict) > 0:
  578. send_bot_post(blocker, blockdict)
  579. blockdict = []
  580. conn.close()