-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathchallenges.py
More file actions
326 lines (274 loc) · 12.1 KB
/
Copy pathchallenges.py
File metadata and controls
326 lines (274 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Challenges for reauthentication.
"""
import abc
import base64
import getpass
import hashlib
import json
import sys
from google.auth import _helpers
from google.auth import exceptions
from google.oauth2 import webauthn_handler_factory
from google.oauth2.webauthn_types import (
AuthenticationExtensionsClientInputs,
GetRequest,
PublicKeyCredentialDescriptor,
)
REAUTH_ORIGIN = "https://accounts.google.com"
SAML_CHALLENGE_MESSAGE = (
"Please run `gcloud auth login` to complete reauthentication with SAML."
)
WEBAUTHN_TIMEOUT_MS = 120000 # Two minute timeout
U2F_AUTHENTICATION_TYPE = "navigator.id.getAssertion"
def get_user_password(text):
"""Get password from user.
Override this function with a different logic if you are using this library
outside a CLI.
Args:
text (str): message for the password prompt.
Returns:
str: password string.
"""
return getpass.getpass(text)
class ReauthChallenge(metaclass=abc.ABCMeta):
"""Base class for reauth challenges."""
@property
@abc.abstractmethod
def name(self): # pragma: NO COVER
"""Returns the name of the challenge."""
raise NotImplementedError("name property must be implemented")
@property
@abc.abstractmethod
def is_locally_eligible(self): # pragma: NO COVER
"""Returns true if a challenge is supported locally on this machine."""
raise NotImplementedError("is_locally_eligible property must be implemented")
@abc.abstractmethod
def obtain_challenge_input(self, metadata): # pragma: NO COVER
"""Performs logic required to obtain credentials and returns it.
Args:
metadata (Mapping): challenge metadata returned in the 'challenges' field in
the initial reauth request. Includes the 'challengeType' field
and other challenge-specific fields.
Returns:
response that will be send to the reauth service as the content of
the 'proposalResponse' field in the request body. Usually a dict
with the keys specific to the challenge. For example,
``{'credential': password}`` for password challenge.
"""
raise NotImplementedError("obtain_challenge_input method must be implemented")
class PasswordChallenge(ReauthChallenge):
"""Challenge that asks for user's password."""
@property
def name(self):
return "PASSWORD"
@property
def is_locally_eligible(self):
return True
@_helpers.copy_docstring(ReauthChallenge)
def obtain_challenge_input(self, unused_metadata):
passwd = get_user_password("Please enter your password:")
if not passwd:
passwd = " " # avoid the server crashing in case of no password :D
return {"credential": passwd}
class SecurityKeyChallenge(ReauthChallenge):
"""Challenge that asks for user's security key touch."""
@property
def name(self):
return "SECURITY_KEY"
@property
def is_locally_eligible(self):
return True
@_helpers.copy_docstring(ReauthChallenge)
def obtain_challenge_input(self, metadata):
# Check if there is an available Webauthn Handler, if not use fido2.
try:
factory = webauthn_handler_factory.WebauthnHandlerFactory()
webauthn_handler = factory.get_handler()
if webauthn_handler is not None:
sys.stderr.write("Please insert and touch your security key\n")
return self._obtain_challenge_input_webauthn(metadata, webauthn_handler)
except Exception:
# Attempt fido2 if exception in webauthn flow.
pass
return self._obtain_challenge_input_fido2(metadata)
def _get_fido2_classes(self):
try:
from fido2.ctap import CtapError # type: ignore
from fido2.ctap1 import (
APDU, # type: ignore
ApduError, # type: ignore
Ctap1, # type: ignore
)
from fido2.hid import CtapHidDevice # type: ignore
except ImportError as caught_exc:
raise exceptions.ReauthFailError(
"fido2 dependency is required to use Security key reauth feature. "
"It can be installed via `pip install fido2` or `pip install google-auth[reauth]`."
) from caught_exc
return CtapHidDevice, Ctap1, APDU, ApduError, CtapError
def _obtain_challenge_input_fido2(self, metadata):
CtapHidDevice, Ctap1, APDU, ApduError, CtapError = self._get_fido2_classes()
devices = list(CtapHidDevice.list_devices())
if not devices:
sys.stderr.write("No security key found.\n")
return None
sk = metadata["securityKey"]
challenges = sk["challenges"]
# Read both 'applicationId' and 'relyingPartyId', if they are the same, use
# applicationId, if they are different, use relyingPartyId first and retry
# with applicationId
application_id = sk["applicationId"]
relying_party_id = sk["relyingPartyId"]
if application_id != relying_party_id:
application_parameters = [relying_party_id, application_id]
else:
application_parameters = [application_id]
sys.stderr.write("Please touch your security key.\n")
for app_id in application_parameters:
app_param = hashlib.sha256(app_id.encode("utf-8")).digest()
for challenge in challenges:
key_handle = self._urlsafe_b64decode(challenge["keyHandle"])
challenge_bytes = self._urlsafe_b64decode(challenge["challenge"])
client_data = self._create_u2f_client_data(challenge_bytes)
client_param = hashlib.sha256(client_data).digest()
for device in devices:
try:
signature = Ctap1(device).authenticate(
client_param, app_param, key_handle
)
except ApduError as caught_exc:
if caught_exc.code == APDU.WRONG_DATA:
continue
if caught_exc.code == APDU.USE_NOT_SATISFIED:
sys.stderr.write(
"Timed out while waiting for security key touch.\n"
)
return None
raise
except CtapError as caught_exc:
if caught_exc.code in (
CtapError.ERR.TIMEOUT,
CtapError.ERR.ACTION_TIMEOUT,
CtapError.ERR.KEEPALIVE_CANCEL,
CtapError.ERR.OPERATION_DENIED,
):
sys.stderr.write(
"Timed out while waiting for security key touch.\n"
)
return None
raise
else:
return {
"securityKey": {
"clientData": self._unpadded_urlsafe_b64encode(
client_data
),
"signatureData": self._unpadded_urlsafe_b64encode(
bytes(signature)
),
"applicationId": app_id,
"keyHandle": self._unpadded_urlsafe_b64encode(
key_handle
),
}
}
sys.stderr.write("Ineligible security key.\n")
return None
def _obtain_challenge_input_webauthn(self, metadata, webauthn_handler):
sk = metadata.get("securityKey")
if sk is None:
raise exceptions.InvalidValue("securityKey is None")
challenges = sk.get("challenges")
application_id = sk.get("applicationId")
relying_party_id = sk.get("relyingPartyId")
if challenges is None or len(challenges) < 1:
raise exceptions.InvalidValue("challenges is None or empty")
if application_id is None:
raise exceptions.InvalidValue("application_id is None")
if relying_party_id is None:
raise exceptions.InvalidValue("relying_party_id is None")
allow_credentials = []
for challenge in challenges:
kh = challenge.get("keyHandle")
if kh is None:
raise exceptions.InvalidValue("keyHandle is None")
key_handle = self._unpadded_urlsafe_b64recode(kh)
allow_credentials.append(PublicKeyCredentialDescriptor(id=key_handle))
extension = AuthenticationExtensionsClientInputs(appid=application_id)
challenge = challenges[0].get("challenge")
if challenge is None:
raise exceptions.InvalidValue("challenge is None")
get_request = GetRequest(
origin=REAUTH_ORIGIN,
rpid=relying_party_id,
challenge=self._unpadded_urlsafe_b64recode(challenge),
timeout_ms=WEBAUTHN_TIMEOUT_MS,
allow_credentials=allow_credentials,
user_verification="preferred",
extensions=extension,
)
try:
get_response = webauthn_handler.get(get_request)
except Exception as e:
sys.stderr.write("Webauthn Error: {}.\n".format(e))
raise e
response = {
"clientData": get_response.response.client_data_json,
"authenticatorData": get_response.response.authenticator_data,
"signatureData": get_response.response.signature,
"applicationId": application_id,
"keyHandle": get_response.id,
"securityKeyReplyType": 2,
}
return {"securityKey": response}
def _unpadded_urlsafe_b64recode(self, s):
"""Converts standard b64 encoded string to url safe b64 encoded string
with no padding."""
return self._unpadded_urlsafe_b64encode(self._urlsafe_b64decode(s))
def _create_u2f_client_data(self, challenge):
return json.dumps(
{
"challenge": self._unpadded_urlsafe_b64encode(challenge),
"origin": REAUTH_ORIGIN,
"typ": U2F_AUTHENTICATION_TYPE,
},
sort_keys=True,
).encode()
def _unpadded_urlsafe_b64encode(self, data):
return base64.urlsafe_b64encode(data).decode().rstrip("=")
def _urlsafe_b64decode(self, data):
return base64.urlsafe_b64decode(data + "=" * (-len(data) % 4))
class SamlChallenge(ReauthChallenge):
"""Challenge that asks the users to browse to their ID Providers.
Currently SAML challenge is not supported. When obtaining the challenge
input, exception will be raised to instruct the users to run
`gcloud auth login` for reauthentication.
"""
@property
def name(self):
return "SAML"
@property
def is_locally_eligible(self):
return True
def obtain_challenge_input(self, metadata):
# Magic Arch has not fully supported returning a proper dedirect URL
# for programmatic SAML users today. So we error our here and request
# users to use gcloud to complete a login.
raise exceptions.ReauthSamlChallengeFailError(SAML_CHALLENGE_MESSAGE)
AVAILABLE_CHALLENGES = {
challenge.name: challenge
for challenge in [SecurityKeyChallenge(), PasswordChallenge(), SamlChallenge()]
}