1 /*
2  * Copyright 2015 The Android Open Source Project
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  */
16 #include <gatekeeper/UniquePtr.h>
17 #include <gatekeeper/gatekeeper.h>
18 
19 #ifdef _WIN32
20 #include <winsock2.h>
21 #define htobe32 htonl
22 #define htobe64 htonll_gk
23 #else
24 #include <endian.h>
25 #endif
26 
27 #include <stddef.h>
28 
29 #define DAY_IN_MS (1000 * 60 * 60 * 24)
30 
31 #ifdef _WIN32
htonll_gk(uint64_t value)32 __forceinline uint64_t htonll_gk(uint64_t value) {
33     return (((uint64_t)htonl(value & 0xFFFFFFFFUL)) << 32) | htonl((uint32_t)(value >> 32));
34 }
35 #endif
36 
37 namespace gatekeeper {
38 
Enroll(const EnrollRequest & request,EnrollResponse * response)39 void GateKeeper::Enroll(const EnrollRequest &request, EnrollResponse *response) {
40     if (response == nullptr) return;
41 
42     if (!request.provided_password) {
43         response->error = ERROR_INVALID;
44         return;
45     }
46 
47     secure_id_t user_id = 0;// todo: rename to policy
48     uint32_t uid = request.user_id;
49 
50     if (!request.password_handle) {
51         // Password handle does not match what is stored, generate new SecureID
52         GetRandom(&user_id, sizeof(secure_id_t));
53     } else {
54         const password_handle_t *pw_handle = request.password_handle.Data<password_handle_t>();
55 
56         if (!pw_handle || pw_handle->version > HANDLE_VERSION) {
57             response->error = ERROR_INVALID;
58             return;
59         }
60 
61         user_id = pw_handle->user_id;
62 
63         uint64_t timestamp = GetMillisecondsSinceBoot();
64 
65         uint32_t timeout = 0;
66         bool throttle = (pw_handle->version >= HANDLE_VERSION_THROTTLE);
67         if (throttle) {
68             bool throttle_secure = pw_handle->flags & HANDLE_FLAG_THROTTLE_SECURE;
69             failure_record_t record;
70             if (!GetFailureRecord(uid, user_id, &record, throttle_secure)) {
71                 response->error = ERROR_UNKNOWN;
72                 return;
73             }
74 
75             if (ThrottleRequest(uid, timestamp, &record, throttle_secure, response)) return;
76 
77             if (!IncrementFailureRecord(uid, user_id, timestamp, &record, throttle_secure)) {
78                 response->error = ERROR_UNKNOWN;
79                 return;
80             }
81 
82             timeout = ComputeRetryTimeout(&record);
83         }
84 
85         if (!DoVerify(pw_handle, request.enrolled_password)) {
86             // incorrect old password
87             if (throttle && timeout > 0) {
88                 response->SetRetryTimeout(timeout);
89             } else {
90                 response->error = ERROR_INVALID;
91             }
92             return;
93         }
94     }
95 
96     uint64_t flags = 0;
97     if (ClearFailureRecord(uid, user_id, true)) {
98         flags |= HANDLE_FLAG_THROTTLE_SECURE;
99     } else {
100         ClearFailureRecord(uid, user_id, false);
101     }
102 
103     salt_t salt;
104     GetRandom(&salt, sizeof(salt));
105 
106     SizedBuffer password_handle;
107     if (!CreatePasswordHandle(&password_handle,
108             salt, user_id, flags, HANDLE_VERSION, request.provided_password)) {
109         response->error = ERROR_INVALID;
110         return;
111     }
112 
113     response->SetEnrolledPasswordHandle(move(password_handle));
114 }
115 
Verify(const VerifyRequest & request,VerifyResponse * response)116 void GateKeeper::Verify(const VerifyRequest &request, VerifyResponse *response) {
117     if (response == nullptr) return;
118 
119     if (!request.provided_password || !request.password_handle) {
120         response->error = ERROR_INVALID;
121         return;
122     }
123 
124     const password_handle_t *password_handle = request.password_handle.Data<password_handle_t>();
125 
126     if (!password_handle || password_handle->version > HANDLE_VERSION) {
127         response->error = ERROR_INVALID;
128         return;
129     }
130 
131     secure_id_t user_id = password_handle->user_id;
132     secure_id_t authenticator_id = 0;
133     uint32_t uid = request.user_id;
134 
135     uint64_t timestamp = GetMillisecondsSinceBoot();
136 
137     uint32_t timeout = 0;
138     bool throttle = (password_handle->version >= HANDLE_VERSION_THROTTLE);
139     bool throttle_secure = password_handle->flags & HANDLE_FLAG_THROTTLE_SECURE;
140     if (throttle) {
141         failure_record_t record;
142         if (!GetFailureRecord(uid, user_id, &record, throttle_secure)) {
143             response->error = ERROR_UNKNOWN;
144             return;
145         }
146 
147         if (ThrottleRequest(uid, timestamp, &record, throttle_secure, response)) return;
148 
149         if (!IncrementFailureRecord(uid, user_id, timestamp, &record, throttle_secure)) {
150             response->error = ERROR_UNKNOWN;
151             return;
152         }
153 
154         timeout = ComputeRetryTimeout(&record);
155     } else {
156         response->request_reenroll = true;
157     }
158 
159     if (DoVerify(password_handle, request.provided_password)) {
160         // Signature matches
161         SizedBuffer auth_token;
162         response->error = MintAuthToken(&auth_token, timestamp,
163                 user_id, authenticator_id, request.challenge);
164 
165         if (response->error != ERROR_NONE) return;
166 
167         response->SetVerificationToken(move(auth_token));
168         if (throttle) ClearFailureRecord(uid, user_id, throttle_secure);
169     } else {
170         // compute the new timeout given the incremented record
171         if (throttle && timeout > 0) {
172             response->SetRetryTimeout(timeout);
173         } else {
174             response->error = ERROR_INVALID;
175         }
176     }
177 }
178 
DeleteUser(const DeleteUserRequest & request,DeleteUserResponse * response)179 void GateKeeper::DeleteUser(const DeleteUserRequest &request, DeleteUserResponse *response) {
180     if (response == nullptr) return;
181 
182     uint32_t uid = request.user_id;
183     response->error = RemoveUser(uid);
184 }
185 
DeleteAllUsers(const DeleteAllUsersRequest &,DeleteAllUsersResponse * response)186 void GateKeeper::DeleteAllUsers(const DeleteAllUsersRequest &/*request*/,
187         DeleteAllUsersResponse *response) {
188     if (response == nullptr) return;
189 
190     response->error = RemoveAllUsers();
191 }
192 
CreatePasswordHandle(SizedBuffer * password_handle_buffer,salt_t salt,secure_id_t user_id,uint64_t flags,uint8_t handle_version,const SizedBuffer & password)193 bool GateKeeper::CreatePasswordHandle(SizedBuffer *password_handle_buffer, salt_t salt,
194         secure_id_t user_id, uint64_t flags, uint8_t handle_version, const SizedBuffer & password) {
195     if (password_handle_buffer == nullptr) return false;
196 
197     password_handle_t password_handle;
198 
199     password_handle.version = handle_version;
200     password_handle.salt = salt;
201     password_handle.user_id = user_id;
202     password_handle.flags = flags;
203     password_handle.hardware_backed = IsHardwareBacked();
204 
205     constexpr uint32_t metadata_length = sizeof(password_handle.version) +
206                                          sizeof(password_handle.user_id) +
207                                          sizeof(password_handle.flags);
208     static_assert(offsetof(password_handle_t, salt) == metadata_length,
209             "password_handle_t does not appear to be packed");
210 
211     const size_t to_sign_size = password.size() + metadata_length;
212 
213     UniquePtr<uint8_t[]> to_sign(new(std::nothrow) uint8_t[to_sign_size]);
214     if (!to_sign) return false;
215 
216     memcpy(to_sign.get(), &password_handle, metadata_length);
217     memcpy(to_sign.get() + metadata_length, password.Data<uint8_t>(), password.size());
218 
219     const uint8_t *password_key = nullptr;
220     uint32_t password_key_length = 0;
221     GetPasswordKey(&password_key, &password_key_length);
222 
223     if (!password_key || password_key_length == 0) {
224         return false;
225     }
226 
227     ComputePasswordSignature(password_handle.signature, sizeof(password_handle.signature),
228             password_key, password_key_length, to_sign.get(), to_sign_size, salt);
229 
230     uint8_t *ph_buffer = new(std::nothrow) uint8_t[sizeof(password_handle_t)];
231     if (ph_buffer == nullptr) return false;
232 
233     *password_handle_buffer = { ph_buffer, sizeof(password_handle_t) };
234     memcpy(ph_buffer, &password_handle, sizeof(password_handle_t));
235 
236     return true;
237 }
238 
DoVerify(const password_handle_t * expected_handle,const SizedBuffer & password)239 bool GateKeeper::DoVerify(const password_handle_t *expected_handle, const SizedBuffer &password) {
240     if (!password) return false;
241 
242     SizedBuffer provided_handle;
243     if (!CreatePasswordHandle(&provided_handle, expected_handle->salt, expected_handle->user_id,
244             expected_handle->flags, expected_handle->version, password)) {
245         return false;
246     }
247 
248     const password_handle_t *generated_handle = provided_handle.Data<password_handle_t>();
249     return memcmp_s(generated_handle->signature, expected_handle->signature,
250             sizeof(expected_handle->signature)) == 0;
251 }
252 
MintAuthToken(SizedBuffer * auth_token,uint64_t timestamp,secure_id_t user_id,secure_id_t authenticator_id,uint64_t challenge)253 gatekeeper_error_t GateKeeper::MintAuthToken(SizedBuffer *auth_token,
254         uint64_t timestamp, secure_id_t user_id, secure_id_t authenticator_id,
255         uint64_t challenge) {
256     if (auth_token == nullptr) return ERROR_INVALID;
257 
258     hw_auth_token_t token;
259 
260     token.version = HW_AUTH_TOKEN_VERSION;
261     token.challenge = challenge;
262     token.user_id = user_id;
263     token.authenticator_id = authenticator_id;
264     token.authenticator_type = htobe32(HW_AUTH_PASSWORD);
265     token.timestamp = htobe64(timestamp);
266 
267     constexpr uint32_t hashable_length = sizeof(token.version) +
268                                          sizeof(token.challenge) +
269                                          sizeof(token.user_id) +
270                                          sizeof(token.authenticator_id) +
271                                          sizeof(token.authenticator_type) +
272                                          sizeof(token.timestamp);
273 
274     static_assert(offsetof(hw_auth_token_t, hmac) == hashable_length,
275             "hw_auth_token_t does not appear to be packed");
276 
277     const uint8_t *auth_token_key = nullptr;
278     uint32_t key_len = 0;
279     if (GetAuthTokenKey(&auth_token_key, &key_len)) {
280         ComputeSignature(token.hmac, sizeof(token.hmac), auth_token_key, key_len,
281                 reinterpret_cast<uint8_t *>(&token), hashable_length);
282     } else {
283         memset(token.hmac, 0, sizeof(token.hmac));
284     }
285 
286     uint8_t *token_buffer = new(std::nothrow) uint8_t[sizeof(hw_auth_token_t)];
287     if (token_buffer == nullptr) return ERROR_MEMORY_ALLOCATION_FAILED;
288 
289     *reinterpret_cast<hw_auth_token_t*>(token_buffer) = token;
290 
291     *auth_token = { token_buffer, sizeof(hw_auth_token_t) };
292     return ERROR_NONE;
293 }
294 
295 /*
296  * Calculates the timeout in milliseconds as a function of the failure
297  * counter 'x' as follows:
298  *
299  * [0, 4] -> 0
300  * 5 -> 30
301  * [6, 10] -> 0
302  * [11, 29] -> 30
303  * [30, 139] -> 30 * (2^((x - 30)/10))
304  * [140, inf) -> 1 day
305  *
306  */
ComputeRetryTimeout(const failure_record_t * record)307 uint32_t GateKeeper::ComputeRetryTimeout(const failure_record_t *record) {
308     static const int failure_timeout_ms = 30000;
309     if (record->failure_counter == 0) return 0;
310 
311     if (record->failure_counter > 0 && record->failure_counter <= 10) {
312         if (record->failure_counter % 5 == 0) {
313             return failure_timeout_ms;
314         }  else {
315             return 0;
316         }
317     } else if (record->failure_counter < 30) {
318         return failure_timeout_ms;
319     } else if (record->failure_counter < 140) {
320         return failure_timeout_ms << ((record->failure_counter - 30) / 10);
321     }
322 
323     return DAY_IN_MS;
324 }
325 
ThrottleRequest(uint32_t uid,uint64_t timestamp,failure_record_t * record,bool secure,GateKeeperMessage * response)326 bool GateKeeper::ThrottleRequest(uint32_t uid, uint64_t timestamp,
327         failure_record_t *record, bool secure, GateKeeperMessage *response) {
328 
329     uint64_t last_checked = record->last_checked_timestamp;
330     uint32_t timeout = ComputeRetryTimeout(record);
331 
332     if (timeout > 0) {
333         // we have a pending timeout
334         if (timestamp < last_checked + timeout && timestamp > last_checked) {
335             // attempt before timeout expired, return remaining time
336             response->SetRetryTimeout(timeout - (timestamp - last_checked));
337             return true;
338         } else if (timestamp <= last_checked) {
339             // device was rebooted or timer reset, don't count as new failure but
340             // reset timeout
341             record->last_checked_timestamp = timestamp;
342             if (!WriteFailureRecord(uid, record, secure)) {
343                 response->error = ERROR_UNKNOWN;
344                 return true;
345             }
346             response->SetRetryTimeout(timeout);
347             return true;
348         }
349     }
350 
351     return false;
352 }
353 
IncrementFailureRecord(uint32_t uid,secure_id_t user_id,uint64_t timestamp,failure_record_t * record,bool secure)354 bool GateKeeper::IncrementFailureRecord(uint32_t uid, secure_id_t user_id, uint64_t timestamp,
355             failure_record_t *record, bool secure) {
356     record->secure_user_id = user_id;
357     record->failure_counter++;
358     record->last_checked_timestamp = timestamp;
359 
360     return WriteFailureRecord(uid, record, secure);
361 }
362 } // namespace gatekeeper
363 
364