auth.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. # mautrix-signal - A Matrix-Signal puppeting bridge
  2. # Copyright (C) 2020 Tulir Asokan
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU Affero General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU Affero General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU Affero General Public License
  15. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. from typing import Union
  17. import io
  18. from mausignald.errors import (
  19. AuthorizationFailedError,
  20. CaptchaRequiredError,
  21. ScanTimeoutError,
  22. TimeoutException,
  23. UnexpectedResponse,
  24. )
  25. from mautrix.appservice import IntentAPI
  26. from mautrix.bridge.commands import HelpSection, command_handler
  27. from mautrix.types import EventID, ImageInfo, MediaMessageEventContent, MessageType, UserID
  28. from .. import puppet as pu
  29. from ..util import normalize_number
  30. from .typehint import CommandEvent
  31. try:
  32. import PIL as _
  33. import qrcode
  34. except ImportError:
  35. qrcode = None
  36. SECTION_AUTH = HelpSection("Authentication", 10, "")
  37. async def make_qr(
  38. intent: IntentAPI, data: Union[str, bytes], body: str = None
  39. ) -> MediaMessageEventContent:
  40. # TODO always encrypt QR codes?
  41. buffer = io.BytesIO()
  42. image = qrcode.make(data)
  43. size = image.pixel_size
  44. image.save(buffer, "PNG")
  45. qr = buffer.getvalue()
  46. mxc = await intent.upload_media(qr, "image/png", "qr.png", len(qr))
  47. return MediaMessageEventContent(
  48. body=body or data,
  49. url=mxc,
  50. msgtype=MessageType.IMAGE,
  51. info=ImageInfo(mimetype="image/png", size=len(qr), width=size, height=size),
  52. )
  53. @command_handler(
  54. needs_auth=False,
  55. management_only=True,
  56. needs_admin=True,
  57. help_section=SECTION_AUTH,
  58. help_text="Connect to an existing account on signald",
  59. help_args="[mxid] <phone number>",
  60. )
  61. async def connect_existing(evt: CommandEvent) -> EventID:
  62. if len(evt.args) == 0:
  63. return await evt.reply("**Usage:** `$cmdprefix+sp connect-existing [mxid] <phone number>`")
  64. if evt.args[0].startswith("@"):
  65. evt.sender = await evt.bridge.get_user(UserID(evt.args[0]))
  66. evt.args = evt.args[1:]
  67. if await evt.sender.is_logged_in():
  68. return await evt.reply(
  69. "You're already logged in. "
  70. "If you want to relink, log out with `$cmdprefix+sp logout` first."
  71. )
  72. try:
  73. account_id = normalize_number("".join(evt.args))
  74. except Exception:
  75. return await evt.reply("Please enter the phone number in international format (E.164)")
  76. accounts = await evt.bridge.signal.list_accounts()
  77. for account in accounts:
  78. if account.account_id == account_id:
  79. await evt.sender.on_signin(account)
  80. return await evt.reply(
  81. f"Successfully logged in as {pu.Puppet.fmt_phone(evt.sender.username)} "
  82. f"(device #{account.device_id})"
  83. )
  84. return await evt.reply(f"Account with ID {account_id} not found in signald")
  85. @command_handler(
  86. needs_auth=False,
  87. management_only=True,
  88. help_section=SECTION_AUTH,
  89. help_text="Link the bridge as a secondary device",
  90. help_args="[device name]",
  91. aliases=["login"],
  92. )
  93. async def link(evt: CommandEvent) -> None:
  94. if qrcode is None:
  95. await evt.reply("Can't generate QR code: qrcode and/or PIL not installed")
  96. return
  97. if await evt.sender.is_logged_in():
  98. await evt.reply(
  99. "You're already logged in. "
  100. "If you want to relink, log out with `$cmdprefix+sp logout` first."
  101. )
  102. return
  103. # TODO make default device name configurable
  104. device_name = " ".join(evt.args) or "Mautrix-Signal bridge"
  105. sess = await evt.bridge.signal.start_link()
  106. content = await make_qr(evt.az.intent, sess.uri)
  107. event_id = await evt.az.intent.send_message(evt.room_id, content)
  108. try:
  109. account = await evt.bridge.signal.finish_link(
  110. session_id=sess.session_id, overwrite=True, device_name=device_name
  111. )
  112. except (TimeoutException, ScanTimeoutError):
  113. await evt.reply("Linking timed out, please try again.")
  114. except Exception:
  115. evt.log.exception("Fatal error while waiting for linking to finish")
  116. await evt.reply(
  117. "Fatal error while waiting for linking to finish (see logs for more details)"
  118. )
  119. else:
  120. await evt.sender.on_signin(account)
  121. await evt.reply(
  122. f"Successfully logged in as {pu.Puppet.fmt_phone(evt.sender.username)} "
  123. f"(device #{account.device_id})"
  124. )
  125. finally:
  126. await evt.main_intent.redact(evt.room_id, event_id)
  127. @command_handler(
  128. needs_auth=False,
  129. management_only=True,
  130. help_section=SECTION_AUTH,
  131. is_enabled_for=lambda evt: evt.config["signal.registration_enabled"],
  132. help_text="Sign into Signal as the primary device",
  133. help_args="<phone>",
  134. )
  135. async def register(evt: CommandEvent) -> None:
  136. if len(evt.args) == 0:
  137. await evt.reply("**Usage**: $cmdprefix+sp register [--voice] [--captcha <token>] <phone>")
  138. return
  139. if await evt.sender.is_logged_in():
  140. await evt.reply(
  141. "You're already logged in. "
  142. "If you want to re-register, log out with `$cmdprefix+sp logout` first."
  143. )
  144. return
  145. voice = False
  146. captcha = None
  147. while True:
  148. flag = evt.args[0].lower()
  149. if flag == "--voice" or flag == "-v":
  150. voice = True
  151. evt.args = evt.args[1:]
  152. elif flag == "--captcha" or flag == "-c":
  153. if "=" in evt.args[0]:
  154. captcha = evt.args[0].split("=", 1)[1]
  155. evt.args = evt.args[1:]
  156. else:
  157. captcha = evt.args[1]
  158. evt.args = evt.args[2:]
  159. else:
  160. break
  161. try:
  162. phone = normalize_number(evt.args[0])
  163. except Exception:
  164. await evt.reply("Please enter the phone number in international format (E.164)")
  165. return
  166. try:
  167. username = await evt.bridge.signal.register(phone, voice=voice, captcha=captcha)
  168. evt.sender.command_status = {
  169. "action": "Register",
  170. "room_id": evt.room_id,
  171. "next": enter_register_code,
  172. "username": username,
  173. }
  174. await evt.reply("Register SMS requested, please enter the code here.")
  175. except CaptchaRequiredError:
  176. await evt.reply(
  177. "Captcha required. Please follow the instructions at https://signald.org/articles/captcha/ "
  178. "to obtain a captcha token and paste it here."
  179. )
  180. evt.sender.command_status = {
  181. "action": "Register",
  182. "room_id": evt.room_id,
  183. "next": enter_captcha_token,
  184. "voice": voice,
  185. "phone": phone,
  186. }
  187. async def enter_captcha_token(evt: CommandEvent) -> None:
  188. captcha = evt.args[0]
  189. phone = evt.sender.command_status["phone"]
  190. voice = evt.sender.command_status["voice"]
  191. username = await evt.bridge.signal.register(phone, voice=voice, captcha=captcha)
  192. evt.sender.command_status = {
  193. "action": "Register",
  194. "room_id": evt.room_id,
  195. "next": enter_register_code,
  196. "username": username,
  197. }
  198. await evt.reply("Register SMS requested, please enter the code here.")
  199. async def enter_register_code(evt: CommandEvent) -> None:
  200. try:
  201. username = evt.sender.command_status["username"]
  202. account = await evt.bridge.signal.verify(username, code=evt.args[0])
  203. except UnexpectedResponse as e:
  204. if e.resp_type == "error":
  205. await evt.reply(e.data)
  206. else:
  207. raise
  208. else:
  209. await evt.sender.on_signin(account)
  210. await evt.reply(
  211. f"Successfully logged in as {pu.Puppet.fmt_phone(evt.sender.username)}."
  212. f"\n\n**N.B.** You must set a Signal profile name with `$cmdprefix+sp "
  213. f"set-profile-name <name>` before you can participate in new groups."
  214. )
  215. @command_handler(
  216. needs_auth=True,
  217. management_only=True,
  218. help_section=SECTION_AUTH,
  219. help_text="Remove all local data about your Signal link",
  220. )
  221. async def logout(evt: CommandEvent) -> None:
  222. if not evt.sender.username:
  223. await evt.reply("You're not logged in")
  224. return
  225. await evt.sender.logout()
  226. await evt.reply("Successfully logged out")
  227. @command_handler(
  228. needs_auth=False,
  229. management_only=True,
  230. needs_admin=True,
  231. help_section=SECTION_AUTH,
  232. help_text="Remove all local data about a user's Signal link",
  233. help_args="<mxid>",
  234. )
  235. async def logout_user(evt: CommandEvent) -> None:
  236. if len(evt.args) == 0:
  237. await evt.reply("**Usage**: $cmdprefix+sp logout-user <mxid>")
  238. user = await evt.bridge.get_user(UserID(evt.args[0]))
  239. if not await user.is_logged_in():
  240. await evt.reply("This user is not logged in")
  241. return
  242. await user.logout()
  243. await evt.reply("Successfully logged out")
  244. @command_handler(
  245. needs_auth=True,
  246. management_only=True,
  247. help_section=SECTION_AUTH,
  248. help_text="List devices linked to your Signal account",
  249. )
  250. async def list_devices(evt: CommandEvent) -> None:
  251. devices = await evt.bridge.signal.get_linked_devices(evt.sender.username)
  252. await evt.reply(
  253. "\n".join(
  254. f"* #{dev.id}: {dev.name_with_default} (created {dev.created_fmt}, last seen "
  255. f"{dev.last_seen_fmt})"
  256. for dev in devices
  257. )
  258. )
  259. @command_handler(
  260. needs_auth=True,
  261. management_only=True,
  262. help_section=SECTION_AUTH,
  263. help_text="Add a device with a `sgnl://linkdevice?...` URI from a QR code",
  264. )
  265. async def add_linked_device(evt: CommandEvent) -> EventID:
  266. if len(evt.args) == 0:
  267. return await evt.reply("**Usage:** `$cmdprefix+sp add-linked-device <URI from QR code>`")
  268. try:
  269. await evt.bridge.signal.add_linked_device(evt.sender.username, evt.args[0])
  270. except AuthorizationFailedError as e:
  271. return await evt.reply(f"{e} Only the primary device can add linked devices.")
  272. else:
  273. return await evt.reply("Device linked successfully")
  274. @command_handler(
  275. needs_auth=True,
  276. management_only=True,
  277. help_section=SECTION_AUTH,
  278. help_text="Remove a linked device",
  279. )
  280. async def remove_linked_device(evt: CommandEvent) -> EventID:
  281. if len(evt.args) == 0:
  282. return await evt.reply("**Usage:** `$cmdprefix+sp remove-linked-device <device ID>`")
  283. device_id = int(evt.args[0])
  284. try:
  285. await evt.bridge.signal.remove_linked_device(evt.sender.username, device_id)
  286. except AuthorizationFailedError as e:
  287. return await evt.reply(f"{e} Only the primary device can remove linked devices.")
  288. return await evt.reply("Device removed")