challenges.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. # Copyright 2021 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """ Challenges for reauthentication.
  15. """
  16. import abc
  17. import base64
  18. import getpass
  19. import sys
  20. from google.auth import _helpers
  21. from google.auth import exceptions
  22. from google.oauth2 import webauthn_handler_factory
  23. from google.oauth2.webauthn_types import (
  24. AuthenticationExtensionsClientInputs,
  25. GetRequest,
  26. PublicKeyCredentialDescriptor,
  27. )
  28. REAUTH_ORIGIN = "https://accounts.google.com"
  29. SAML_CHALLENGE_MESSAGE = (
  30. "Please run `gcloud auth login` to complete reauthentication with SAML."
  31. )
  32. WEBAUTHN_TIMEOUT_MS = 120000 # Two minute timeout
  33. def get_user_password(text):
  34. """Get password from user.
  35. Override this function with a different logic if you are using this library
  36. outside a CLI.
  37. Args:
  38. text (str): message for the password prompt.
  39. Returns:
  40. str: password string.
  41. """
  42. return getpass.getpass(text)
  43. class ReauthChallenge(metaclass=abc.ABCMeta):
  44. """Base class for reauth challenges."""
  45. @property
  46. @abc.abstractmethod
  47. def name(self): # pragma: NO COVER
  48. """Returns the name of the challenge."""
  49. raise NotImplementedError("name property must be implemented")
  50. @property
  51. @abc.abstractmethod
  52. def is_locally_eligible(self): # pragma: NO COVER
  53. """Returns true if a challenge is supported locally on this machine."""
  54. raise NotImplementedError("is_locally_eligible property must be implemented")
  55. @abc.abstractmethod
  56. def obtain_challenge_input(self, metadata): # pragma: NO COVER
  57. """Performs logic required to obtain credentials and returns it.
  58. Args:
  59. metadata (Mapping): challenge metadata returned in the 'challenges' field in
  60. the initial reauth request. Includes the 'challengeType' field
  61. and other challenge-specific fields.
  62. Returns:
  63. response that will be send to the reauth service as the content of
  64. the 'proposalResponse' field in the request body. Usually a dict
  65. with the keys specific to the challenge. For example,
  66. ``{'credential': password}`` for password challenge.
  67. """
  68. raise NotImplementedError("obtain_challenge_input method must be implemented")
  69. class PasswordChallenge(ReauthChallenge):
  70. """Challenge that asks for user's password."""
  71. @property
  72. def name(self):
  73. return "PASSWORD"
  74. @property
  75. def is_locally_eligible(self):
  76. return True
  77. @_helpers.copy_docstring(ReauthChallenge)
  78. def obtain_challenge_input(self, unused_metadata):
  79. passwd = get_user_password("Please enter your password:")
  80. if not passwd:
  81. passwd = " " # avoid the server crashing in case of no password :D
  82. return {"credential": passwd}
  83. class SecurityKeyChallenge(ReauthChallenge):
  84. """Challenge that asks for user's security key touch."""
  85. @property
  86. def name(self):
  87. return "SECURITY_KEY"
  88. @property
  89. def is_locally_eligible(self):
  90. return True
  91. @_helpers.copy_docstring(ReauthChallenge)
  92. def obtain_challenge_input(self, metadata):
  93. # Check if there is an available Webauthn Handler, if not use pyu2f
  94. try:
  95. factory = webauthn_handler_factory.WebauthnHandlerFactory()
  96. webauthn_handler = factory.get_handler()
  97. if webauthn_handler is not None:
  98. sys.stderr.write("Please insert and touch your security key\n")
  99. return self._obtain_challenge_input_webauthn(metadata, webauthn_handler)
  100. except Exception:
  101. # Attempt pyu2f if exception in webauthn flow
  102. pass
  103. try:
  104. import pyu2f.convenience.authenticator # type: ignore
  105. import pyu2f.errors # type: ignore
  106. import pyu2f.model # type: ignore
  107. except ImportError:
  108. raise exceptions.ReauthFailError(
  109. "pyu2f dependency is required to use Security key reauth feature. "
  110. "It can be installed via `pip install pyu2f` or `pip install google-auth[reauth]`."
  111. )
  112. sk = metadata["securityKey"]
  113. challenges = sk["challenges"]
  114. # Read both 'applicationId' and 'relyingPartyId', if they are the same, use
  115. # applicationId, if they are different, use relyingPartyId first and retry
  116. # with applicationId
  117. application_id = sk["applicationId"]
  118. relying_party_id = sk["relyingPartyId"]
  119. if application_id != relying_party_id:
  120. application_parameters = [relying_party_id, application_id]
  121. else:
  122. application_parameters = [application_id]
  123. challenge_data = []
  124. for c in challenges:
  125. kh = c["keyHandle"].encode("ascii")
  126. key = pyu2f.model.RegisteredKey(bytearray(base64.urlsafe_b64decode(kh)))
  127. challenge = c["challenge"].encode("ascii")
  128. challenge = base64.urlsafe_b64decode(challenge)
  129. challenge_data.append({"key": key, "challenge": challenge})
  130. # Track number of tries to suppress error message until all application_parameters
  131. # are tried.
  132. tries = 0
  133. for app_id in application_parameters:
  134. try:
  135. tries += 1
  136. api = pyu2f.convenience.authenticator.CreateCompositeAuthenticator(
  137. REAUTH_ORIGIN
  138. )
  139. response = api.Authenticate(
  140. app_id, challenge_data, print_callback=sys.stderr.write
  141. )
  142. return {"securityKey": response}
  143. except pyu2f.errors.U2FError as e:
  144. if e.code == pyu2f.errors.U2FError.DEVICE_INELIGIBLE:
  145. # Only show error if all app_ids have been tried
  146. if tries == len(application_parameters):
  147. sys.stderr.write("Ineligible security key.\n")
  148. return None
  149. continue
  150. if e.code == pyu2f.errors.U2FError.TIMEOUT:
  151. sys.stderr.write(
  152. "Timed out while waiting for security key touch.\n"
  153. )
  154. else:
  155. raise e
  156. except pyu2f.errors.PluginError as e:
  157. sys.stderr.write("Plugin error: {}.\n".format(e))
  158. continue
  159. except pyu2f.errors.NoDeviceFoundError:
  160. sys.stderr.write("No security key found.\n")
  161. return None
  162. def _obtain_challenge_input_webauthn(self, metadata, webauthn_handler):
  163. sk = metadata.get("securityKey")
  164. if sk is None:
  165. raise exceptions.InvalidValue("securityKey is None")
  166. challenges = sk.get("challenges")
  167. application_id = sk.get("applicationId")
  168. relying_party_id = sk.get("relyingPartyId")
  169. if challenges is None or len(challenges) < 1:
  170. raise exceptions.InvalidValue("challenges is None or empty")
  171. if application_id is None:
  172. raise exceptions.InvalidValue("application_id is None")
  173. if relying_party_id is None:
  174. raise exceptions.InvalidValue("relying_party_id is None")
  175. allow_credentials = []
  176. for challenge in challenges:
  177. kh = challenge.get("keyHandle")
  178. if kh is None:
  179. raise exceptions.InvalidValue("keyHandle is None")
  180. key_handle = self._unpadded_urlsafe_b64recode(kh)
  181. allow_credentials.append(PublicKeyCredentialDescriptor(id=key_handle))
  182. extension = AuthenticationExtensionsClientInputs(appid=application_id)
  183. challenge = challenges[0].get("challenge")
  184. if challenge is None:
  185. raise exceptions.InvalidValue("challenge is None")
  186. get_request = GetRequest(
  187. origin=REAUTH_ORIGIN,
  188. rpid=relying_party_id,
  189. challenge=self._unpadded_urlsafe_b64recode(challenge),
  190. timeout_ms=WEBAUTHN_TIMEOUT_MS,
  191. allow_credentials=allow_credentials,
  192. user_verification="required",
  193. extensions=extension,
  194. )
  195. try:
  196. get_response = webauthn_handler.get(get_request)
  197. except Exception as e:
  198. sys.stderr.write("Webauthn Error: {}.\n".format(e))
  199. raise e
  200. response = {
  201. "clientData": get_response.response.client_data_json,
  202. "authenticatorData": get_response.response.authenticator_data,
  203. "signatureData": get_response.response.signature,
  204. "applicationId": application_id,
  205. "keyHandle": get_response.id,
  206. "securityKeyReplyType": 2,
  207. }
  208. return {"securityKey": response}
  209. def _unpadded_urlsafe_b64recode(self, s):
  210. """Converts standard b64 encoded string to url safe b64 encoded string
  211. with no padding."""
  212. b = base64.urlsafe_b64decode(s)
  213. return base64.urlsafe_b64encode(b).decode().rstrip("=")
  214. class SamlChallenge(ReauthChallenge):
  215. """Challenge that asks the users to browse to their ID Providers.
  216. Currently SAML challenge is not supported. When obtaining the challenge
  217. input, exception will be raised to instruct the users to run
  218. `gcloud auth login` for reauthentication.
  219. """
  220. @property
  221. def name(self):
  222. return "SAML"
  223. @property
  224. def is_locally_eligible(self):
  225. return True
  226. def obtain_challenge_input(self, metadata):
  227. # Magic Arch has not fully supported returning a proper dedirect URL
  228. # for programmatic SAML users today. So we error our here and request
  229. # users to use gcloud to complete a login.
  230. raise exceptions.ReauthSamlChallengeFailError(SAML_CHALLENGE_MESSAGE)
  231. AVAILABLE_CHALLENGES = {
  232. challenge.name: challenge
  233. for challenge in [SecurityKeyChallenge(), PasswordChallenge(), SamlChallenge()]
  234. }