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 bool GateKeeper::CreatePasswordHandle(SizedBuffer *password_handle_buffer, salt_t salt,
167         secure_id_t user_id, uint64_t flags, uint8_t handle_version, const SizedBuffer & password) {
168     if (password_handle_buffer == nullptr) return false;
169 
170     password_handle_t password_handle;
171 
172     password_handle.version = handle_version;
173     password_handle.salt = salt;
174     password_handle.user_id = user_id;
175     password_handle.flags = flags;
176     password_handle.hardware_backed = IsHardwareBacked();
177 
178     constexpr uint32_t metadata_length = sizeof(password_handle.version) +
179                                          sizeof(password_handle.user_id) +
180                                          sizeof(password_handle.flags);
181     static_assert(offsetof(password_handle_t, salt) == metadata_length,
182             "password_handle_t does not appear to be packed");
183 
184     const size_t to_sign_size = password.size() + metadata_length;
185 
186     UniquePtr<uint8_t[]> to_sign(new(std::nothrow) uint8_t[to_sign_size]);
187     if (!to_sign) return false;
188 
189     memcpy(to_sign.get(), &password_handle, metadata_length);
190     memcpy(to_sign.get() + metadata_length, password.Data<uint8_t>(), password.size());
191 
192     const uint8_t *password_key = nullptr;
193     uint32_t password_key_length = 0;
194     GetPasswordKey(&password_key, &password_key_length);
195 
196     if (!password_key || password_key_length == 0) {
197         return false;
198     }
199 
200     ComputePasswordSignature(password_handle.signature, sizeof(password_handle.signature),
201             password_key, password_key_length, to_sign.get(), to_sign_size, salt);
202 
203     uint8_t *ph_buffer = new(std::nothrow) uint8_t[sizeof(password_handle_t)];
204     if (ph_buffer == nullptr) return false;
205 
206     *password_handle_buffer = { ph_buffer, sizeof(password_handle_t) };
207     memcpy(ph_buffer, &password_handle, sizeof(password_handle_t));
208 
209     return true;
210 }
211 
212 bool GateKeeper::DoVerify(const password_handle_t *expected_handle, const SizedBuffer &password) {
213     if (!password) return false;
214 
215     SizedBuffer provided_handle;
216     if (!CreatePasswordHandle(&provided_handle, expected_handle->salt, expected_handle->user_id,
217             expected_handle->flags, expected_handle->version, password)) {
218         return false;
219     }
220 
221     const password_handle_t *generated_handle = provided_handle.Data<password_handle_t>();
222     return memcmp_s(generated_handle->signature, expected_handle->signature,
223             sizeof(expected_handle->signature)) == 0;
224 }
225 
226 gatekeeper_error_t GateKeeper::MintAuthToken(SizedBuffer *auth_token,
227         uint64_t timestamp, secure_id_t user_id, secure_id_t authenticator_id,
228         uint64_t challenge) {
229     if (auth_token == nullptr) return ERROR_INVALID;
230 
231     hw_auth_token_t token;
232 
233     token.version = HW_AUTH_TOKEN_VERSION;
234     token.challenge = challenge;
235     token.user_id = user_id;
236     token.authenticator_id = authenticator_id;
237     token.authenticator_type = htobe32(HW_AUTH_PASSWORD);
238     token.timestamp = htobe64(timestamp);
239 
240     constexpr uint32_t hashable_length = sizeof(token.version) +
241                                          sizeof(token.challenge) +
242                                          sizeof(token.user_id) +
243                                          sizeof(token.authenticator_id) +
244                                          sizeof(token.authenticator_type) +
245                                          sizeof(token.timestamp);
246 
247     static_assert(offsetof(hw_auth_token_t, hmac) == hashable_length,
248             "hw_auth_token_t does not appear to be packed");
249 
250     const uint8_t *auth_token_key = nullptr;
251     uint32_t key_len = 0;
252     if (GetAuthTokenKey(&auth_token_key, &key_len)) {
253         ComputeSignature(token.hmac, sizeof(token.hmac), auth_token_key, key_len,
254                 reinterpret_cast<uint8_t *>(&token), hashable_length);
255     } else {
256         memset(token.hmac, 0, sizeof(token.hmac));
257     }
258 
259     uint8_t *token_buffer = new(std::nothrow) uint8_t[sizeof(hw_auth_token_t)];
260     if (token_buffer == nullptr) return ERROR_MEMORY_ALLOCATION_FAILED;
261 
262     *reinterpret_cast<hw_auth_token_t*>(token_buffer) = token;
263 
264     *auth_token = { token_buffer, sizeof(hw_auth_token_t) };
265     return ERROR_NONE;
266 }
267 
268 /*
269  * Calculates the timeout in milliseconds as a function of the failure
270  * counter 'x' as follows:
271  *
272  * [0, 4] -> 0
273  * 5 -> 30
274  * [6, 10] -> 0
275  * [11, 29] -> 30
276  * [30, 139] -> 30 * (2^((x - 30)/10))
277  * [140, inf) -> 1 day
278  *
279  */
280 uint32_t GateKeeper::ComputeRetryTimeout(const failure_record_t *record) {
281     static const int failure_timeout_ms = 30000;
282     if (record->failure_counter == 0) return 0;
283 
284     if (record->failure_counter > 0 && record->failure_counter <= 10) {
285         if (record->failure_counter % 5 == 0) {
286             return failure_timeout_ms;
287         }  else {
288             return 0;
289         }
290     } else if (record->failure_counter < 30) {
291         return failure_timeout_ms;
292     } else if (record->failure_counter < 140) {
293         return failure_timeout_ms << ((record->failure_counter - 30) / 10);
294     }
295 
296     return DAY_IN_MS;
297 }
298 
299 bool GateKeeper::ThrottleRequest(uint32_t uid, uint64_t timestamp,
300         failure_record_t *record, bool secure, GateKeeperMessage *response) {
301 
302     uint64_t last_checked = record->last_checked_timestamp;
303     uint32_t timeout = ComputeRetryTimeout(record);
304 
305     if (timeout > 0) {
306         // we have a pending timeout
307         if (timestamp < last_checked + timeout && timestamp > last_checked) {
308             // attempt before timeout expired, return remaining time
309             response->SetRetryTimeout(timeout - (timestamp - last_checked));
310             return true;
311         } else if (timestamp <= last_checked) {
312             // device was rebooted or timer reset, don't count as new failure but
313             // reset timeout
314             record->last_checked_timestamp = timestamp;
315             if (!WriteFailureRecord(uid, record, secure)) {
316                 response->error = ERROR_UNKNOWN;
317                 return true;
318             }
319             response->SetRetryTimeout(timeout);
320             return true;
321         }
322     }
323 
324     return false;
325 }
326 
327 bool GateKeeper::IncrementFailureRecord(uint32_t uid, secure_id_t user_id, uint64_t timestamp,
328             failure_record_t *record, bool secure) {
329     record->secure_user_id = user_id;
330     record->failure_counter++;
331     record->last_checked_timestamp = timestamp;
332 
333     return WriteFailureRecord(uid, record, secure);
334 }
335 } // namespace gatekeeper
336 
337