auth.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. # mautrix-instagram - A Matrix-Instagram puppeting bridge.
  2. # Copyright (C) 2023 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 __future__ import annotations
  17. import base64
  18. import hashlib
  19. import hmac
  20. import zlib
  21. from mauigpapi.errors import (
  22. IGBad2FACodeError,
  23. IGChallengeError,
  24. IGChallengeWrongCodeError,
  25. IGLoginBadPasswordError,
  26. IGLoginInvalidUserError,
  27. IGLoginTwoFactorRequiredError,
  28. )
  29. from mauigpapi.http import AndroidAPI
  30. from mauigpapi.state import AndroidState
  31. from mauigpapi.types import BaseResponseUser
  32. from mautrix.bridge.commands import HelpSection, command_handler
  33. from mautrix.types import EventID
  34. from .. import user as u
  35. from .typehint import CommandEvent
  36. SECTION_AUTH = HelpSection("Authentication", 10, "")
  37. async def get_login_state(user: u.User, seed: str) -> tuple[AndroidAPI, AndroidState]:
  38. if user.command_status and user.command_status["action"] == "Login":
  39. api: AndroidAPI = user.command_status["api"]
  40. state: AndroidState = user.command_status["state"]
  41. else:
  42. state = AndroidState()
  43. seed = hmac.new(seed.encode("utf-8"), user.mxid.encode("utf-8"), hashlib.sha256).digest()
  44. state.device.generate(seed)
  45. api = AndroidAPI(state, log=user.api_log, proxy_handler=user.proxy_handler)
  46. await api.get_mobile_config()
  47. user.command_status = {
  48. "action": "Login",
  49. "state": state,
  50. "api": api,
  51. }
  52. return api, state
  53. @command_handler(
  54. needs_auth=False,
  55. management_only=True,
  56. help_section=SECTION_AUTH,
  57. help_text="Log into Instagram",
  58. help_args="<_username_> <_password_>",
  59. )
  60. async def login(evt: CommandEvent) -> None:
  61. if await evt.sender.is_logged_in():
  62. await evt.reply("You're already logged in")
  63. return
  64. elif len(evt.args) < 2:
  65. await evt.reply("**Usage:** `$cmdprefix+sp login <username> <password>`")
  66. return
  67. username = evt.args[0]
  68. password = " ".join(evt.args[1:])
  69. await evt.redact()
  70. api, state = await get_login_state(evt.sender, evt.config["instagram.device_seed"])
  71. try:
  72. resp = await api.login(username, password)
  73. except IGLoginTwoFactorRequiredError as e:
  74. tfa_info = e.body.two_factor_info
  75. msg = "Username and password accepted, but you have two-factor authentication enabled.\n"
  76. if tfa_info.totp_two_factor_on:
  77. msg += "Send the code from your authenticator app here."
  78. if tfa_info.sms_two_factor_on:
  79. msg += f" Alternatively, send `resend-sms` to get an SMS code to •••{tfa_info.obfuscated_phone_number}"
  80. elif tfa_info.sms_two_factor_on:
  81. msg += (
  82. f"Send the code sent to •••{tfa_info.obfuscated_phone_number} here."
  83. " You can also send `resend-sms` if you didn't receive the code."
  84. )
  85. else:
  86. msg += (
  87. "Unfortunately, none of your two-factor authentication methods are currently "
  88. "supported by the bridge."
  89. )
  90. return
  91. evt.sender.command_status = {
  92. **evt.sender.command_status,
  93. "next": enter_login_2fa,
  94. "username": tfa_info.username,
  95. "is_totp": tfa_info.totp_two_factor_on,
  96. "has_sms": tfa_info.sms_two_factor_on,
  97. "2fa_identifier": tfa_info.two_factor_identifier,
  98. }
  99. await evt.reply(msg)
  100. except IGChallengeError:
  101. await evt.reply(
  102. "Login challenges aren't currently supported. "
  103. "Please set up real two-factor authentication."
  104. )
  105. await api.challenge_auto()
  106. evt.sender.command_status = {
  107. **evt.sender.command_status,
  108. "next": enter_login_security_code,
  109. }
  110. await evt.reply(
  111. "Username and password accepted, but Instagram wants to verify it's really"
  112. " you. Please confirm the login and enter the security code here."
  113. )
  114. except IGLoginInvalidUserError:
  115. await evt.reply("Invalid username")
  116. except IGLoginBadPasswordError:
  117. await evt.reply("Incorrect password")
  118. except Exception as e:
  119. evt.log.exception("Failed to log in")
  120. await evt.reply(f"Failed to log in: {e}")
  121. else:
  122. await _post_login(evt, state, resp.logged_in_user)
  123. async def enter_login_2fa(evt: CommandEvent) -> None:
  124. api: AndroidAPI = evt.sender.command_status["api"]
  125. state: AndroidState = evt.sender.command_status["state"]
  126. identifier = evt.sender.command_status["2fa_identifier"]
  127. username = evt.sender.command_status["username"]
  128. is_totp = evt.sender.command_status["is_totp"]
  129. has_sms = evt.sender.command_status["has_sms"]
  130. code = "".join(evt.args).lower()
  131. if has_sms and code == "resend-sms":
  132. try:
  133. resp = await api.send_two_factor_login_sms(username, identifier=identifier)
  134. except Exception as e:
  135. evt.log.exception("Failed to re-request SMS code")
  136. await evt.reply(f"Failed to re-request SMS code: {e}")
  137. else:
  138. await evt.reply(
  139. f"Re-requested SMS code to {resp.two_factor_info.obfuscated_phone_number}"
  140. )
  141. evt.sender.command_status[
  142. "2fa_identifier"
  143. ] = resp.two_factor_info.two_factor_identifier
  144. evt.sender.command_status["is_totp"] = False
  145. return
  146. try:
  147. resp = await api.two_factor_login(
  148. username, code=code, identifier=identifier, is_totp=is_totp
  149. )
  150. except IGBad2FACodeError:
  151. await evt.reply(
  152. "Invalid 2-factor authentication code. Please try again "
  153. "or use `$cmdprefix+sp cancel` to cancel."
  154. )
  155. except IGChallengeError:
  156. await api.challenge_auto(reset=True)
  157. evt.sender.command_status = {
  158. **evt.sender.command_status,
  159. "next": enter_login_security_code,
  160. }
  161. await evt.reply(
  162. "2-factor authentication code accepted, but Instagram wants to verify it's"
  163. " really you. Please confirm the login and enter the security code here."
  164. )
  165. except Exception as e:
  166. evt.log.exception("Failed to log in")
  167. await evt.reply(f"Failed to log in: {e}")
  168. evt.sender.command_status = None
  169. else:
  170. evt.sender.command_status = None
  171. await _post_login(evt, state, resp.logged_in_user)
  172. async def enter_login_security_code(evt: CommandEvent) -> None:
  173. api: AndroidAPI = evt.sender.command_status["api"]
  174. state: AndroidState = evt.sender.command_status["state"]
  175. try:
  176. resp = await api.challenge_send_security_code("".join(evt.args))
  177. except IGChallengeWrongCodeError as e:
  178. await evt.reply(f"Incorrect security code: {e}")
  179. except Exception as e:
  180. evt.log.exception("Failed to log in")
  181. await evt.reply(f"Failed to log in: {e}")
  182. evt.sender.command_status = None
  183. else:
  184. if not resp.logged_in_user:
  185. evt.log.error(
  186. f"Didn't get logged_in_user in challenge response "
  187. f"after entering security code: {resp.serialize()}"
  188. )
  189. await evt.reply("An unknown error occurred. Please check the bridge logs.")
  190. return
  191. evt.sender.command_status = None
  192. await _post_login(evt, state, resp.logged_in_user)
  193. async def _post_login(evt: CommandEvent, state: AndroidState, user: BaseResponseUser) -> None:
  194. evt.sender.state = state
  195. pl = state.device.payload
  196. manufacturer, model = pl["manufacturer"], pl["model"]
  197. await evt.reply(
  198. f"Successfully logged in as {user.full_name} ([@{user.username}]"
  199. f"(https://instagram.com/{user.username}), user ID: {user.pk}).\n\n"
  200. f"The bridge will show up on Instagram as {manufacturer} {model}."
  201. )
  202. await evt.sender.try_connect()
  203. @command_handler(
  204. needs_auth=True,
  205. help_section=SECTION_AUTH,
  206. help_text="Disconnect the bridge from your Instagram account",
  207. )
  208. async def logout(evt: CommandEvent) -> None:
  209. await evt.sender.logout()
  210. await evt.reply("Successfully logged out")
  211. @command_handler(
  212. needs_auth=False,
  213. management_only=True,
  214. help_section=SECTION_AUTH,
  215. help_text="Log into Instagram with a pre-generated session blob",
  216. help_args="<_blob_>",
  217. )
  218. async def login_blob(evt: CommandEvent) -> EventID:
  219. if await evt.sender.is_logged_in():
  220. return await evt.reply("You're already logged in")
  221. elif len(evt.args) < 1:
  222. return await evt.reply("**Usage:** `$cmdprefix+sp login-blob <blob>`")
  223. await evt.redact()
  224. try:
  225. state = AndroidState.parse_json(zlib.decompress(base64.b64decode("".join(evt.args))))
  226. except Exception:
  227. evt.log.exception(f"{evt.sender} provided an invalid login blob")
  228. return await evt.reply("Invalid blob")
  229. evt.sender.state = state
  230. await evt.reply("Connecting...")
  231. await evt.sender.try_connect()
  232. await evt.reply("Maybe connected now, try pinging?")