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