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 <UniquePtr.h>
17 #include <gatekeeper/gatekeeper.h>
18 
19 #include <endian.h>
20 
21 #define DAY_IN_MS (1000 * 60 * 60 * 24)
22 
23 namespace gatekeeper {
24 
Enroll(const EnrollRequest & request,EnrollResponse * response)25 void GateKeeper::Enroll(const EnrollRequest &request, EnrollResponse *response) {
26     if (response == NULL) return;
27 
28     if (!request.provided_password.buffer.get()) {
29         response->error = ERROR_INVALID;
30         return;
31     }
32 
33     secure_id_t user_id = 0;// todo: rename to policy
34     uint32_t uid = request.user_id;
35 
36     if (request.password_handle.buffer.get() == NULL) {
37         // Password handle does not match what is stored, generate new SecureID
38         GetRandom(&user_id, sizeof(secure_id_t));
39     } else {
40         password_handle_t *pw_handle =
41             reinterpret_cast<password_handle_t *>(request.password_handle.buffer.get());
42 
43         if (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.buffer.get(),
96             request.provided_password.length)) {
97         response->error = ERROR_INVALID;
98         return;
99     }
100 
101     response->SetEnrolledPasswordHandle(&password_handle);
102 }
103 
Verify(const VerifyRequest & request,VerifyResponse * response)104 void GateKeeper::Verify(const VerifyRequest &request, VerifyResponse *response) {
105     if (response == NULL) return;
106 
107     if (!request.provided_password.buffer.get() || !request.password_handle.buffer.get()) {
108         response->error = ERROR_INVALID;
109         return;
110     }
111 
112     password_handle_t *password_handle = reinterpret_cast<password_handle_t *>(
113             request.password_handle.buffer.get());
114 
115     if (password_handle->version > HANDLE_VERSION) {
116         response->error = ERROR_INVALID;
117         return;
118     }
119 
120     secure_id_t user_id = password_handle->user_id;
121     secure_id_t authenticator_id = 0;
122     uint32_t uid = request.user_id;
123 
124     uint64_t timestamp = GetMillisecondsSinceBoot();
125 
126     uint32_t timeout = 0;
127     bool throttle = (password_handle->version >= HANDLE_VERSION_THROTTLE);
128     bool throttle_secure = password_handle->flags & HANDLE_FLAG_THROTTLE_SECURE;
129     if (throttle) {
130         failure_record_t record;
131         if (!GetFailureRecord(uid, user_id, &record, throttle_secure)) {
132             response->error = ERROR_UNKNOWN;
133             return;
134         }
135 
136         if (ThrottleRequest(uid, timestamp, &record, throttle_secure, response)) return;
137 
138         if (!IncrementFailureRecord(uid, user_id, timestamp, &record, throttle_secure)) {
139             response->error = ERROR_UNKNOWN;
140             return;
141         }
142 
143         timeout = ComputeRetryTimeout(&record);
144     } else {
145         response->request_reenroll = true;
146     }
147 
148     if (DoVerify(password_handle, request.provided_password)) {
149         // Signature matches
150         UniquePtr<uint8_t> auth_token_buffer;
151         uint32_t auth_token_len;
152         MintAuthToken(&auth_token_buffer, &auth_token_len, timestamp,
153                 user_id, authenticator_id, request.challenge);
154 
155         SizedBuffer auth_token(auth_token_len);
156         memcpy(auth_token.buffer.get(), auth_token_buffer.get(), auth_token_len);
157         response->SetVerificationToken(&auth_token);
158         if (throttle) ClearFailureRecord(uid, user_id, throttle_secure);
159     } else {
160         // compute the new timeout given the incremented record
161         if (throttle && timeout > 0) {
162             response->SetRetryTimeout(timeout);
163         } else {
164             response->error = ERROR_INVALID;
165         }
166     }
167 }
168 
CreatePasswordHandle(SizedBuffer * password_handle_buffer,salt_t salt,secure_id_t user_id,uint64_t flags,uint8_t handle_version,const uint8_t * password,uint32_t password_length)169 bool GateKeeper::CreatePasswordHandle(SizedBuffer *password_handle_buffer, salt_t salt,
170         secure_id_t user_id, uint64_t flags, uint8_t handle_version, const uint8_t *password,
171         uint32_t password_length) {
172     password_handle_buffer->buffer.reset(new uint8_t[sizeof(password_handle_t)]);
173     password_handle_buffer->length = sizeof(password_handle_t);
174 
175     password_handle_t *password_handle = reinterpret_cast<password_handle_t *>(
176             password_handle_buffer->buffer.get());
177     password_handle->version = handle_version;
178     password_handle->salt = salt;
179     password_handle->user_id = user_id;
180     password_handle->flags = flags;
181     password_handle->hardware_backed = IsHardwareBacked();
182 
183     uint32_t metadata_length = sizeof(user_id) + sizeof(flags) + sizeof(HANDLE_VERSION);
184     const size_t to_sign_size = password_length + metadata_length;
185     UniquePtr<uint8_t> to_sign(new uint8_t[to_sign_size]);
186 
187     if (to_sign.get() == nullptr) {
188         return false;
189     }
190 
191     memcpy(to_sign.get(), password_handle, metadata_length);
192     memcpy(to_sign.get() + metadata_length, password, password_length);
193 
194     const uint8_t *password_key = NULL;
195     uint32_t password_key_length = 0;
196     GetPasswordKey(&password_key, &password_key_length);
197 
198     if (!password_key || password_key_length == 0) {
199         return false;
200     }
201 
202     ComputePasswordSignature(password_handle->signature, sizeof(password_handle->signature),
203             password_key, password_key_length, to_sign.get(), to_sign_size, salt);
204     return true;
205 }
206 
DoVerify(const password_handle_t * expected_handle,const SizedBuffer & password)207 bool GateKeeper::DoVerify(const password_handle_t *expected_handle, const SizedBuffer &password) {
208     if (!password.buffer.get()) return false;
209 
210     SizedBuffer provided_handle;
211     if (!CreatePasswordHandle(&provided_handle, expected_handle->salt, expected_handle->user_id,
212             expected_handle->flags, expected_handle->version,
213             password.buffer.get(), password.length)) {
214         return false;
215     }
216 
217     password_handle_t *generated_handle =
218             reinterpret_cast<password_handle_t *>(provided_handle.buffer.get());
219     return memcmp_s(generated_handle->signature, expected_handle->signature,
220             sizeof(expected_handle->signature)) == 0;
221 }
222 
MintAuthToken(UniquePtr<uint8_t> * auth_token,uint32_t * length,uint64_t timestamp,secure_id_t user_id,secure_id_t authenticator_id,uint64_t challenge)223 void GateKeeper::MintAuthToken(UniquePtr<uint8_t> *auth_token, uint32_t *length,
224         uint64_t timestamp, secure_id_t user_id, secure_id_t authenticator_id,
225         uint64_t challenge) {
226     if (auth_token == NULL) return;
227 
228     hw_auth_token_t *token = new hw_auth_token_t;
229     SizedBuffer serialized_auth_token;
230 
231     token->version = HW_AUTH_TOKEN_VERSION;
232     token->challenge = challenge;
233     token->user_id = user_id;
234     token->authenticator_id = authenticator_id;
235     token->authenticator_type = htonl(HW_AUTH_PASSWORD);
236     token->timestamp = htobe64(timestamp);
237 
238     const uint8_t *auth_token_key = NULL;
239     uint32_t key_len = 0;
240     if (GetAuthTokenKey(&auth_token_key, &key_len)) {
241         uint32_t hash_len = (uint32_t)((uint8_t *)&token->hmac - (uint8_t *)token);
242         ComputeSignature(token->hmac, sizeof(token->hmac), auth_token_key, key_len,
243                 reinterpret_cast<uint8_t *>(token), hash_len);
244         delete[] auth_token_key;
245     } else {
246         memset(token->hmac, 0, sizeof(token->hmac));
247     }
248 
249     if (length != NULL) *length = sizeof(*token);
250     auth_token->reset(reinterpret_cast<uint8_t *>(token));
251 }
252 
253 /*
254  * Calculates the timeout in milliseconds as a function of the failure
255  * counter 'x' as follows:
256  *
257  * [0. 5) -> 0
258  * 5 -> 30
259  * [6, 10) -> 0
260  * [11, 30) -> 30
261  * [30, 140) -> 30 * (2^((x - 30)/10))
262  * [140, inf) -> 1 day
263  *
264  */
ComputeRetryTimeout(const failure_record_t * record)265 uint32_t GateKeeper::ComputeRetryTimeout(const failure_record_t *record) {
266     static const int failure_timeout_ms = 30000;
267     if (record->failure_counter == 0) return 0;
268 
269     if (record->failure_counter > 0 && record->failure_counter <= 10) {
270         if (record->failure_counter % 5 == 0) {
271             return failure_timeout_ms;
272         }  else {
273             return 0;
274         }
275     } else if (record->failure_counter < 30) {
276         return failure_timeout_ms;
277     } else if (record->failure_counter < 140) {
278         return failure_timeout_ms << ((record->failure_counter - 30) / 10);
279     }
280 
281     return DAY_IN_MS;
282 }
283 
ThrottleRequest(uint32_t uid,uint64_t timestamp,failure_record_t * record,bool secure,GateKeeperMessage * response)284 bool GateKeeper::ThrottleRequest(uint32_t uid, uint64_t timestamp,
285         failure_record_t *record, bool secure, GateKeeperMessage *response) {
286 
287     uint64_t last_checked = record->last_checked_timestamp;
288     uint32_t timeout = ComputeRetryTimeout(record);
289 
290     if (timeout > 0) {
291         // we have a pending timeout
292         if (timestamp < last_checked + timeout && timestamp > last_checked) {
293             // attempt before timeout expired, return remaining time
294             response->SetRetryTimeout(timeout - (timestamp - last_checked));
295             return true;
296         } else if (timestamp <= last_checked) {
297             // device was rebooted or timer reset, don't count as new failure but
298             // reset timeout
299             record->last_checked_timestamp = timestamp;
300             if (!WriteFailureRecord(uid, record, secure)) {
301                 response->error = ERROR_UNKNOWN;
302                 return true;
303             }
304             response->SetRetryTimeout(timeout);
305             return true;
306         }
307     }
308 
309     return false;
310 }
311 
IncrementFailureRecord(uint32_t uid,secure_id_t user_id,uint64_t timestamp,failure_record_t * record,bool secure)312 bool GateKeeper::IncrementFailureRecord(uint32_t uid, secure_id_t user_id, uint64_t timestamp,
313             failure_record_t *record, bool secure) {
314     record->secure_user_id = user_id;
315     record->failure_counter++;
316     record->last_checked_timestamp = timestamp;
317 
318     return WriteFailureRecord(uid, record, secure);
319 }
320 } // namespace gatekeeper
321 
322