You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

319 lines
12 KiB

  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"]
  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. code_verifier: str
  86. """The random string used in the RFC7636 code challenge ("" if PKCE is not being used)."""
  87. class MacaroonGenerator:
  88. def __init__(self, clock: Clock, location: str, secret_key: bytes):
  89. self._clock = clock
  90. self._location = location
  91. self._secret_key = secret_key
  92. def generate_guest_access_token(self, user_id: str) -> str:
  93. """Generate a guest access token for the given user ID
  94. Args:
  95. user_id: The user ID for which the guest token should be generated.
  96. Returns:
  97. A signed access token for that guest user.
  98. """
  99. nonce = stringutils.random_string_with_symbols(16)
  100. macaroon = self._generate_base_macaroon("access")
  101. macaroon.add_first_party_caveat(f"user_id = {user_id}")
  102. macaroon.add_first_party_caveat(f"nonce = {nonce}")
  103. macaroon.add_first_party_caveat("guest = true")
  104. return macaroon.serialize()
  105. def generate_delete_pusher_token(
  106. self, user_id: str, app_id: str, pushkey: str
  107. ) -> str:
  108. """Generate a signed token used for unsubscribing from email notifications
  109. Args:
  110. user_id: The user for which this token will be valid.
  111. app_id: The app_id for this pusher.
  112. pushkey: The unique identifier of this pusher.
  113. Returns:
  114. A signed token which can be used in unsubscribe links.
  115. """
  116. macaroon = self._generate_base_macaroon("delete_pusher")
  117. macaroon.add_first_party_caveat(f"user_id = {user_id}")
  118. macaroon.add_first_party_caveat(f"app_id = {app_id}")
  119. macaroon.add_first_party_caveat(f"pushkey = {pushkey}")
  120. return macaroon.serialize()
  121. def generate_oidc_session_token(
  122. self,
  123. state: str,
  124. session_data: OidcSessionData,
  125. duration_in_ms: int = (60 * 60 * 1000),
  126. ) -> str:
  127. """Generates a signed token storing data about an OIDC session.
  128. When Synapse initiates an authorization flow, it creates a random state
  129. and a random nonce. Those parameters are given to the provider and
  130. should be verified when the client comes back from the provider.
  131. It is also used to store the client_redirect_url, which is used to
  132. complete the SSO login flow.
  133. Args:
  134. state: The ``state`` parameter passed to the OIDC provider.
  135. session_data: data to include in the session token.
  136. duration_in_ms: An optional duration for the token in milliseconds.
  137. Defaults to an hour.
  138. Returns:
  139. A signed macaroon token with the session information.
  140. """
  141. now = self._clock.time_msec()
  142. expiry = now + duration_in_ms
  143. macaroon = self._generate_base_macaroon("session")
  144. macaroon.add_first_party_caveat(f"state = {state}")
  145. macaroon.add_first_party_caveat(f"idp_id = {session_data.idp_id}")
  146. macaroon.add_first_party_caveat(f"nonce = {session_data.nonce}")
  147. macaroon.add_first_party_caveat(
  148. f"client_redirect_url = {session_data.client_redirect_url}"
  149. )
  150. macaroon.add_first_party_caveat(
  151. f"ui_auth_session_id = {session_data.ui_auth_session_id}"
  152. )
  153. macaroon.add_first_party_caveat(f"code_verifier = {session_data.code_verifier}")
  154. macaroon.add_first_party_caveat(f"time < {expiry}")
  155. return macaroon.serialize()
  156. def verify_guest_token(self, token: str) -> str:
  157. """Verify a guest access token macaroon
  158. Checks that the given token is a valid, unexpired guest access token
  159. minted by this server.
  160. Args:
  161. token: The access token to verify.
  162. Returns:
  163. The ``user_id`` that this token is valid for.
  164. Raises:
  165. MacaroonVerificationFailedException if the verification failed
  166. """
  167. macaroon = pymacaroons.Macaroon.deserialize(token)
  168. user_id = get_value_from_macaroon(macaroon, "user_id")
  169. # At some point, Synapse would generate macaroons without the "guest"
  170. # caveat for regular users. Because of how macaroon verification works,
  171. # to avoid validating those as guest tokens, we explicitely verify if
  172. # the macaroon includes the "guest = true" caveat.
  173. is_guest = any(
  174. caveat.caveat_id == "guest = true" for caveat in macaroon.caveats
  175. )
  176. if not is_guest:
  177. raise MacaroonVerificationFailedException("Macaroon is not a guest token")
  178. v = self._base_verifier("access")
  179. v.satisfy_exact("guest = true")
  180. v.satisfy_general(lambda c: c.startswith("user_id = "))
  181. v.satisfy_general(lambda c: c.startswith("nonce = "))
  182. satisfy_expiry(v, self._clock.time_msec)
  183. v.verify(macaroon, self._secret_key)
  184. return user_id
  185. def verify_delete_pusher_token(self, token: str, app_id: str, pushkey: str) -> str:
  186. """Verify a token from an email unsubscribe link
  187. Args:
  188. token: The token to verify.
  189. app_id: The app_id of the pusher to delete.
  190. pushkey: The unique identifier of the pusher to delete.
  191. Return:
  192. The ``user_id`` for which this token is valid.
  193. Raises:
  194. MacaroonVerificationFailedException if the verification failed
  195. """
  196. macaroon = pymacaroons.Macaroon.deserialize(token)
  197. user_id = get_value_from_macaroon(macaroon, "user_id")
  198. v = self._base_verifier("delete_pusher")
  199. v.satisfy_exact(f"app_id = {app_id}")
  200. v.satisfy_exact(f"pushkey = {pushkey}")
  201. v.satisfy_general(lambda c: c.startswith("user_id = "))
  202. v.verify(macaroon, self._secret_key)
  203. return user_id
  204. def verify_oidc_session_token(self, session: bytes, state: str) -> OidcSessionData:
  205. """Verifies and extract an OIDC session token.
  206. This verifies that a given session token was issued by this homeserver
  207. and extract the nonce and client_redirect_url caveats.
  208. Args:
  209. session: The session token to verify
  210. state: The state the OIDC provider gave back
  211. Returns:
  212. The data extracted from the session cookie
  213. Raises:
  214. KeyError if an expected caveat is missing from the macaroon.
  215. """
  216. macaroon = pymacaroons.Macaroon.deserialize(session)
  217. v = self._base_verifier("session")
  218. v.satisfy_exact(f"state = {state}")
  219. v.satisfy_general(lambda c: c.startswith("nonce = "))
  220. v.satisfy_general(lambda c: c.startswith("idp_id = "))
  221. v.satisfy_general(lambda c: c.startswith("client_redirect_url = "))
  222. v.satisfy_general(lambda c: c.startswith("ui_auth_session_id = "))
  223. v.satisfy_general(lambda c: c.startswith("code_verifier = "))
  224. satisfy_expiry(v, self._clock.time_msec)
  225. v.verify(macaroon, self._secret_key)
  226. # Extract the session data from the token.
  227. nonce = get_value_from_macaroon(macaroon, "nonce")
  228. idp_id = get_value_from_macaroon(macaroon, "idp_id")
  229. client_redirect_url = get_value_from_macaroon(macaroon, "client_redirect_url")
  230. ui_auth_session_id = get_value_from_macaroon(macaroon, "ui_auth_session_id")
  231. code_verifier = get_value_from_macaroon(macaroon, "code_verifier")
  232. return OidcSessionData(
  233. nonce=nonce,
  234. idp_id=idp_id,
  235. client_redirect_url=client_redirect_url,
  236. ui_auth_session_id=ui_auth_session_id,
  237. code_verifier=code_verifier,
  238. )
  239. def _generate_base_macaroon(self, type: MacaroonType) -> pymacaroons.Macaroon:
  240. macaroon = pymacaroons.Macaroon(
  241. location=self._location,
  242. identifier="key",
  243. key=self._secret_key,
  244. )
  245. macaroon.add_first_party_caveat("gen = 1")
  246. macaroon.add_first_party_caveat(f"type = {type}")
  247. return macaroon
  248. def _base_verifier(self, type: MacaroonType) -> pymacaroons.Verifier:
  249. v = pymacaroons.Verifier()
  250. v.satisfy_exact("gen = 1")
  251. v.satisfy_exact(f"type = {type}")
  252. return v