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     uint8_t to_sign[password_length + metadata_length];
185     memcpy(to_sign, password_handle, metadata_length);
186     memcpy(to_sign + metadata_length, password, password_length);
187 
188     const uint8_t *password_key = NULL;
189     uint32_t password_key_length = 0;
190     GetPasswordKey(&password_key, &password_key_length);
191 
192     if (!password_key || password_key_length == 0) {
193         return false;
194     }
195 
196     ComputePasswordSignature(password_handle->signature, sizeof(password_handle->signature),
197             password_key, password_key_length, to_sign, sizeof(to_sign), salt);
198     return true;
199 }
200 
DoVerify(const password_handle_t * expected_handle,const SizedBuffer & password)201 bool GateKeeper::DoVerify(const password_handle_t *expected_handle, const SizedBuffer &password) {
202     if (!password.buffer.get()) return false;
203 
204     SizedBuffer provided_handle;
205     if (!CreatePasswordHandle(&provided_handle, expected_handle->salt, expected_handle->user_id,
206             expected_handle->flags, expected_handle->version,
207             password.buffer.get(), password.length)) {
208         return false;
209     }
210 
211     password_handle_t *generated_handle =
212             reinterpret_cast<password_handle_t *>(provided_handle.buffer.get());
213     return memcmp_s(generated_handle->signature, expected_handle->signature,
214             sizeof(expected_handle->signature)) == 0;
215 }
216 
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)217 void GateKeeper::MintAuthToken(UniquePtr<uint8_t> *auth_token, uint32_t *length,
218         uint64_t timestamp, secure_id_t user_id, secure_id_t authenticator_id,
219         uint64_t challenge) {
220     if (auth_token == NULL) return;
221 
222     hw_auth_token_t *token = new hw_auth_token_t;
223     SizedBuffer serialized_auth_token;
224 
225     token->version = HW_AUTH_TOKEN_VERSION;
226     token->challenge = challenge;
227     token->user_id = user_id;
228     token->authenticator_id = authenticator_id;
229     token->authenticator_type = htonl(HW_AUTH_PASSWORD);
230     token->timestamp = htobe64(timestamp);
231 
232     const uint8_t *auth_token_key = NULL;
233     uint32_t key_len = 0;
234     if (GetAuthTokenKey(&auth_token_key, &key_len)) {
235         uint32_t hash_len = (uint32_t)((uint8_t *)&token->hmac - (uint8_t *)token);
236         ComputeSignature(token->hmac, sizeof(token->hmac), auth_token_key, key_len,
237                 reinterpret_cast<uint8_t *>(token), hash_len);
238         delete[] auth_token_key;
239     } else {
240         memset(token->hmac, 0, sizeof(token->hmac));
241     }
242 
243     if (length != NULL) *length = sizeof(*token);
244     auth_token->reset(reinterpret_cast<uint8_t *>(token));
245 }
246 
247 /*
248  * Calculates the timeout in milliseconds as a function of the failure
249  * counter 'x' as follows:
250  *
251  * [0. 5) -> 0
252  * 5 -> 30
253  * [6, 10) -> 0
254  * [11, 30) -> 30
255  * [30, 140) -> 30 * (2^((x - 30)/10))
256  * [140, inf) -> 1 day
257  *
258  */
ComputeRetryTimeout(const failure_record_t * record)259 uint32_t GateKeeper::ComputeRetryTimeout(const failure_record_t *record) {
260     static const int failure_timeout_ms = 30000;
261     if (record->failure_counter == 0) return 0;
262 
263     if (record->failure_counter > 0 && record->failure_counter <= 10) {
264         if (record->failure_counter % 5 == 0) {
265             return failure_timeout_ms;
266         }  else {
267             return 0;
268         }
269     } else if (record->failure_counter < 30) {
270         return failure_timeout_ms;
271     } else if (record->failure_counter < 140) {
272         return failure_timeout_ms << ((record->failure_counter - 30) / 10);
273     }
274 
275     return DAY_IN_MS;
276 }
277 
ThrottleRequest(uint32_t uid,uint64_t timestamp,failure_record_t * record,bool secure,GateKeeperMessage * response)278 bool GateKeeper::ThrottleRequest(uint32_t uid, uint64_t timestamp,
279         failure_record_t *record, bool secure, GateKeeperMessage *response) {
280 
281     uint64_t last_checked = record->last_checked_timestamp;
282     uint32_t timeout = ComputeRetryTimeout(record);
283 
284     if (timeout > 0) {
285         // we have a pending timeout
286         if (timestamp < last_checked + timeout && timestamp > last_checked) {
287             // attempt before timeout expired, return remaining time
288             response->SetRetryTimeout(timeout - (timestamp - last_checked));
289             return true;
290         } else if (timestamp <= last_checked) {
291             // device was rebooted or timer reset, don't count as new failure but
292             // reset timeout
293             record->last_checked_timestamp = timestamp;
294             if (!WriteFailureRecord(uid, record, secure)) {
295                 response->error = ERROR_UNKNOWN;
296                 return true;
297             }
298             response->SetRetryTimeout(timeout);
299             return true;
300         }
301     }
302 
303     return false;
304 }
305 
IncrementFailureRecord(uint32_t uid,secure_id_t user_id,uint64_t timestamp,failure_record_t * record,bool secure)306 bool GateKeeper::IncrementFailureRecord(uint32_t uid, secure_id_t user_id, uint64_t timestamp,
307             failure_record_t *record, bool secure) {
308     record->secure_user_id = user_id;
309     record->failure_counter++;
310     record->last_checked_timestamp = timestamp;
311 
312     return WriteFailureRecord(uid, record, secure);
313 }
314 } // namespace gatekeeper
315 
316