macaroons.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. # Copyright 2020 Quentin Gliech
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Utilities for manipulating macaroons"""
  16. from typing import Callable, Optional
  17. import attr
  18. import pymacaroons
  19. from pymacaroons.exceptions import MacaroonVerificationFailedException
  20. from typing_extensions import Literal
  21. from synapse.util import Clock, stringutils
  22. MacaroonType = Literal["access", "delete_pusher", "session", "login"]
  23. def get_value_from_macaroon(macaroon: pymacaroons.Macaroon, key: str) -> str:
  24. """Extracts a caveat value from a macaroon token.
  25. Checks that there is exactly one caveat of the form "key = <val>" in the macaroon,
  26. and returns the extracted value.
  27. Args:
  28. macaroon: the token
  29. key: the key of the caveat to extract
  30. Returns:
  31. The extracted value
  32. Raises:
  33. MacaroonVerificationFailedException: if there are conflicting values for the
  34. caveat in the macaroon, or if the caveat was not found in the macaroon.
  35. """
  36. prefix = key + " = "
  37. result: Optional[str] = None
  38. for caveat in macaroon.caveats:
  39. if not caveat.caveat_id.startswith(prefix):
  40. continue
  41. val = caveat.caveat_id[len(prefix) :]
  42. if result is None:
  43. # first time we found this caveat: record the value
  44. result = val
  45. elif val != result:
  46. # on subsequent occurrences, raise if the value is different.
  47. raise MacaroonVerificationFailedException(
  48. "Conflicting values for caveat " + key
  49. )
  50. if result is not None:
  51. return result
  52. # If the caveat is not there, we raise a MacaroonVerificationFailedException.
  53. # Note that it is insecure to generate a macaroon without all the caveats you
  54. # might need (because there is nothing stopping people from adding extra caveats),
  55. # so if the caveat isn't there, something odd must be going on.
  56. raise MacaroonVerificationFailedException("No %s caveat in macaroon" % (key,))
  57. def satisfy_expiry(v: pymacaroons.Verifier, get_time_ms: Callable[[], int]) -> None:
  58. """Make a macaroon verifier which accepts 'time' caveats
  59. Builds a caveat verifier which will accept unexpired 'time' caveats, and adds it to
  60. the given macaroon verifier.
  61. Args:
  62. v: the macaroon verifier
  63. get_time_ms: a callable which will return the timestamp after which the caveat
  64. should be considered expired. Normally the current time.
  65. """
  66. def verify_expiry_caveat(caveat: str) -> bool:
  67. time_msec = get_time_ms()
  68. prefix = "time < "
  69. if not caveat.startswith(prefix):
  70. return False
  71. expiry = int(caveat[len(prefix) :])
  72. return time_msec < expiry
  73. v.satisfy_general(verify_expiry_caveat)
  74. @attr.s(frozen=True, slots=True, auto_attribs=True)
  75. class OidcSessionData:
  76. """The attributes which are stored in a OIDC session cookie"""
  77. idp_id: str
  78. """The Identity Provider being used"""
  79. nonce: str
  80. """The `nonce` parameter passed to the OIDC provider."""
  81. client_redirect_url: str
  82. """The URL the client gave when it initiated the flow. ("" if this is a UI Auth)"""
  83. ui_auth_session_id: str
  84. """The session ID of the ongoing UI Auth ("" if this is a login)"""
  85. @attr.s(slots=True, frozen=True, auto_attribs=True)
  86. class LoginTokenAttributes:
  87. """Data we store in a short-term login token"""
  88. user_id: str
  89. auth_provider_id: str
  90. """The SSO Identity Provider that the user authenticated with, to get this token."""
  91. auth_provider_session_id: Optional[str]
  92. """The session ID advertised by the SSO Identity Provider."""
  93. class MacaroonGenerator:
  94. def __init__(self, clock: Clock, location: str, secret_key: bytes):
  95. self._clock = clock
  96. self._location = location
  97. self._secret_key = secret_key
  98. def generate_guest_access_token(self, user_id: str) -> str:
  99. """Generate a guest access token for the given user ID
  100. Args:
  101. user_id: The user ID for which the guest token should be generated.
  102. Returns:
  103. A signed access token for that guest user.
  104. """
  105. nonce = stringutils.random_string_with_symbols(16)
  106. macaroon = self._generate_base_macaroon("access")
  107. macaroon.add_first_party_caveat(f"user_id = {user_id}")
  108. macaroon.add_first_party_caveat(f"nonce = {nonce}")
  109. macaroon.add_first_party_caveat("guest = true")
  110. return macaroon.serialize()
  111. def generate_delete_pusher_token(
  112. self, user_id: str, app_id: str, pushkey: str
  113. ) -> str:
  114. """Generate a signed token used for unsubscribing from email notifications
  115. Args:
  116. user_id: The user for which this token will be valid.
  117. app_id: The app_id for this pusher.
  118. pushkey: The unique identifier of this pusher.
  119. Returns:
  120. A signed token which can be used in unsubscribe links.
  121. """
  122. macaroon = self._generate_base_macaroon("delete_pusher")
  123. macaroon.add_first_party_caveat(f"user_id = {user_id}")
  124. macaroon.add_first_party_caveat(f"app_id = {app_id}")
  125. macaroon.add_first_party_caveat(f"pushkey = {pushkey}")
  126. return macaroon.serialize()
  127. def generate_short_term_login_token(
  128. self,
  129. user_id: str,
  130. auth_provider_id: str,
  131. auth_provider_session_id: Optional[str] = None,
  132. duration_in_ms: int = (2 * 60 * 1000),
  133. ) -> str:
  134. """Generate a short-term login token used during SSO logins
  135. Args:
  136. user_id: The user for which the token is valid.
  137. auth_provider_id: The SSO IdP the user used.
  138. auth_provider_session_id: The session ID got during login from the SSO IdP.
  139. Returns:
  140. A signed token valid for using as a ``m.login.token`` token.
  141. """
  142. now = self._clock.time_msec()
  143. expiry = now + duration_in_ms
  144. macaroon = self._generate_base_macaroon("login")
  145. macaroon.add_first_party_caveat(f"user_id = {user_id}")
  146. macaroon.add_first_party_caveat(f"time < {expiry}")
  147. macaroon.add_first_party_caveat(f"auth_provider_id = {auth_provider_id}")
  148. if auth_provider_session_id is not None:
  149. macaroon.add_first_party_caveat(
  150. f"auth_provider_session_id = {auth_provider_session_id}"
  151. )
  152. return macaroon.serialize()
  153. def generate_oidc_session_token(
  154. self,
  155. state: str,
  156. session_data: OidcSessionData,
  157. duration_in_ms: int = (60 * 60 * 1000),
  158. ) -> str:
  159. """Generates a signed token storing data about an OIDC session.
  160. When Synapse initiates an authorization flow, it creates a random state
  161. and a random nonce. Those parameters are given to the provider and
  162. should be verified when the client comes back from the provider.
  163. It is also used to store the client_redirect_url, which is used to
  164. complete the SSO login flow.
  165. Args:
  166. state: The ``state`` parameter passed to the OIDC provider.
  167. session_data: data to include in the session token.
  168. duration_in_ms: An optional duration for the token in milliseconds.
  169. Defaults to an hour.
  170. Returns:
  171. A signed macaroon token with the session information.
  172. """
  173. now = self._clock.time_msec()
  174. expiry = now + duration_in_ms
  175. macaroon = self._generate_base_macaroon("session")
  176. macaroon.add_first_party_caveat(f"state = {state}")
  177. macaroon.add_first_party_caveat(f"idp_id = {session_data.idp_id}")
  178. macaroon.add_first_party_caveat(f"nonce = {session_data.nonce}")
  179. macaroon.add_first_party_caveat(
  180. f"client_redirect_url = {session_data.client_redirect_url}"
  181. )
  182. macaroon.add_first_party_caveat(
  183. f"ui_auth_session_id = {session_data.ui_auth_session_id}"
  184. )
  185. macaroon.add_first_party_caveat(f"time < {expiry}")
  186. return macaroon.serialize()
  187. def verify_short_term_login_token(self, token: str) -> LoginTokenAttributes:
  188. """Verify a short-term-login macaroon
  189. Checks that the given token is a valid, unexpired short-term-login token
  190. minted by this server.
  191. Args:
  192. token: The login token to verify.
  193. Returns:
  194. A set of attributes carried by this token, including the
  195. ``user_id`` and informations about the SSO IDP used during that
  196. login.
  197. Raises:
  198. MacaroonVerificationFailedException if the verification failed
  199. """
  200. macaroon = pymacaroons.Macaroon.deserialize(token)
  201. v = self._base_verifier("login")
  202. v.satisfy_general(lambda c: c.startswith("user_id = "))
  203. v.satisfy_general(lambda c: c.startswith("auth_provider_id = "))
  204. v.satisfy_general(lambda c: c.startswith("auth_provider_session_id = "))
  205. satisfy_expiry(v, self._clock.time_msec)
  206. v.verify(macaroon, self._secret_key)
  207. user_id = get_value_from_macaroon(macaroon, "user_id")
  208. auth_provider_id = get_value_from_macaroon(macaroon, "auth_provider_id")
  209. auth_provider_session_id: Optional[str] = None
  210. try:
  211. auth_provider_session_id = get_value_from_macaroon(
  212. macaroon, "auth_provider_session_id"
  213. )
  214. except MacaroonVerificationFailedException:
  215. pass
  216. return LoginTokenAttributes(
  217. user_id=user_id,
  218. auth_provider_id=auth_provider_id,
  219. auth_provider_session_id=auth_provider_session_id,
  220. )
  221. def verify_guest_token(self, token: str) -> str:
  222. """Verify a guest access token macaroon
  223. Checks that the given token is a valid, unexpired guest access token
  224. minted by this server.
  225. Args:
  226. token: The access token to verify.
  227. Returns:
  228. The ``user_id`` that this token is valid for.
  229. Raises:
  230. MacaroonVerificationFailedException if the verification failed
  231. """
  232. macaroon = pymacaroons.Macaroon.deserialize(token)
  233. user_id = get_value_from_macaroon(macaroon, "user_id")
  234. # At some point, Synapse would generate macaroons without the "guest"
  235. # caveat for regular users. Because of how macaroon verification works,
  236. # to avoid validating those as guest tokens, we explicitely verify if
  237. # the macaroon includes the "guest = true" caveat.
  238. is_guest = any(
  239. (caveat.caveat_id == "guest = true" for caveat in macaroon.caveats)
  240. )
  241. if not is_guest:
  242. raise MacaroonVerificationFailedException("Macaroon is not a guest token")
  243. v = self._base_verifier("access")
  244. v.satisfy_exact("guest = true")
  245. v.satisfy_general(lambda c: c.startswith("user_id = "))
  246. v.satisfy_general(lambda c: c.startswith("nonce = "))
  247. satisfy_expiry(v, self._clock.time_msec)
  248. v.verify(macaroon, self._secret_key)
  249. return user_id
  250. def verify_delete_pusher_token(self, token: str, app_id: str, pushkey: str) -> str:
  251. """Verify a token from an email unsubscribe link
  252. Args:
  253. token: The token to verify.
  254. app_id: The app_id of the pusher to delete.
  255. pushkey: The unique identifier of the pusher to delete.
  256. Return:
  257. The ``user_id`` for which this token is valid.
  258. Raises:
  259. MacaroonVerificationFailedException if the verification failed
  260. """
  261. macaroon = pymacaroons.Macaroon.deserialize(token)
  262. user_id = get_value_from_macaroon(macaroon, "user_id")
  263. v = self._base_verifier("delete_pusher")
  264. v.satisfy_exact(f"app_id = {app_id}")
  265. v.satisfy_exact(f"pushkey = {pushkey}")
  266. v.satisfy_general(lambda c: c.startswith("user_id = "))
  267. v.verify(macaroon, self._secret_key)
  268. return user_id
  269. def verify_oidc_session_token(self, session: bytes, state: str) -> OidcSessionData:
  270. """Verifies and extract an OIDC session token.
  271. This verifies that a given session token was issued by this homeserver
  272. and extract the nonce and client_redirect_url caveats.
  273. Args:
  274. session: The session token to verify
  275. state: The state the OIDC provider gave back
  276. Returns:
  277. The data extracted from the session cookie
  278. Raises:
  279. KeyError if an expected caveat is missing from the macaroon.
  280. """
  281. macaroon = pymacaroons.Macaroon.deserialize(session)
  282. v = self._base_verifier("session")
  283. v.satisfy_exact(f"state = {state}")
  284. v.satisfy_general(lambda c: c.startswith("nonce = "))
  285. v.satisfy_general(lambda c: c.startswith("idp_id = "))
  286. v.satisfy_general(lambda c: c.startswith("client_redirect_url = "))
  287. v.satisfy_general(lambda c: c.startswith("ui_auth_session_id = "))
  288. satisfy_expiry(v, self._clock.time_msec)
  289. v.verify(macaroon, self._secret_key)
  290. # Extract the session data from the token.
  291. nonce = get_value_from_macaroon(macaroon, "nonce")
  292. idp_id = get_value_from_macaroon(macaroon, "idp_id")
  293. client_redirect_url = get_value_from_macaroon(macaroon, "client_redirect_url")
  294. ui_auth_session_id = get_value_from_macaroon(macaroon, "ui_auth_session_id")
  295. return OidcSessionData(
  296. nonce=nonce,
  297. idp_id=idp_id,
  298. client_redirect_url=client_redirect_url,
  299. ui_auth_session_id=ui_auth_session_id,
  300. )
  301. def _generate_base_macaroon(self, type: MacaroonType) -> pymacaroons.Macaroon:
  302. macaroon = pymacaroons.Macaroon(
  303. location=self._location,
  304. identifier="key",
  305. key=self._secret_key,
  306. )
  307. macaroon.add_first_party_caveat("gen = 1")
  308. macaroon.add_first_party_caveat(f"type = {type}")
  309. return macaroon
  310. def _base_verifier(self, type: MacaroonType) -> pymacaroons.Verifier:
  311. v = pymacaroons.Verifier()
  312. v.satisfy_exact("gen = 1")
  313. v.satisfy_exact(f"type = {type}")
  314. return v