summaryrefslogtreecommitdiff
path: root/trusty_gatekeeper.cpp
blob: e20258d0b183856b80666fa9ede49c189e353ebf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
/*
 * Copyright 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "trusty_gatekeeper.h"

#include <inttypes.h>
#include <trusty/time.h>
#include <uapi/err.h>

#include <lib/hwkey/hwkey.h>
#include <lib/keymaster/keymaster.h>
#include <lib/rng/trusty_rng.h>
#include <lib/storage/storage.h>

#include <openssl/hmac.h>

#define CALLS_BETWEEN_RNG_RESEEDS 32
#define RNG_RESEED_SIZE 64

#define HMAC_SHA_256_KEY_SIZE 32

#define GATEKEEPER_PREFIX "gatekeeper."

#define STORAGE_ID_LENGTH_MAX 64

#define MAX_FAILURE_RECORDS 10

namespace gatekeeper {

static const uint8_t DERIVATION_DATA[HMAC_SHA_256_KEY_SIZE] =
        "TrustyGateKeeperDerivationData0";

TrustyGateKeeper::TrustyGateKeeper() : GateKeeper(),
    cached_auth_token_key_len_(0) {
    rng_initialized_ = false;
    calls_since_reseed_ = 0;
    num_mem_records_ = 0;

    SeedRngIfNeeded();
}

long TrustyGateKeeper::OpenSession() {
    if (!SeedRngIfNeeded()) {
        return ERR_NOT_READY;
    }

    return DerivePasswordKey();
}

void TrustyGateKeeper::CloseSession() {
    ClearPasswordKey();
}

bool TrustyGateKeeper::SeedRngIfNeeded() {
    if (ShouldReseedRng())
        rng_initialized_ = ReseedRng();
    return rng_initialized_;
}

bool TrustyGateKeeper::ShouldReseedRng() {
    if (!rng_initialized_) {
        return true;
    }

    if (++calls_since_reseed_ % CALLS_BETWEEN_RNG_RESEEDS == 0) {
        return true;
    }
    return false;
}

bool TrustyGateKeeper::ReseedRng() {
    UniquePtr<uint8_t[]> rand_seed(new uint8_t[RNG_RESEED_SIZE]);
    memset(rand_seed.get(), 0, RNG_RESEED_SIZE);
    if (trusty_rng_secure_rand(rand_seed.get(), RNG_RESEED_SIZE) != NO_ERROR) {
        return false;
    }

    trusty_rng_add_entropy(rand_seed.get(), RNG_RESEED_SIZE);
    return true;
}

long TrustyGateKeeper::DerivePasswordKey() {
    long rc = hwkey_open();
    if (rc < 0) {
        return rc;
    }

    hwkey_session_t session = (hwkey_session_t)rc;

    password_key_.reset(new uint8_t[HMAC_SHA_256_KEY_SIZE]);

    uint32_t kdf_version = HWKEY_KDF_VERSION_1;
    rc = hwkey_derive(session, &kdf_version, DERIVATION_DATA,
                      password_key_.get(), HMAC_SHA_256_KEY_SIZE);

    hwkey_close(session);
    return rc;
}

void TrustyGateKeeper::ClearPasswordKey() {
    memset_s(password_key_.get(), 0, HMAC_SHA_256_KEY_SIZE);
    password_key_.reset();
}

/*
 * While the GetAuthTokenKey header file says this value cannot be cached,
 * after consulting with the GK/KM team this is incorrect - this is a per-boot
 * key, and so in-memory caching is acceptable.
 */
bool TrustyGateKeeper::GetAuthTokenKey(const uint8_t** auth_token_key,
                                       uint32_t* length) const {
    *length = 0;
    *auth_token_key = nullptr;

    if (!cached_auth_token_key_) {
        long rc = keymaster_open();
        if (rc < 0) {
            return false;
        }

        keymaster_session_t session = (keymaster_session_t)rc;

        uint8_t* key = nullptr;
        uint32_t local_length = 0;

        rc = keymaster_get_auth_token_key(session, &key, &local_length);
        keymaster_close(session);

        if (rc == NO_ERROR) {
            cached_auth_token_key_.reset(key);
            cached_auth_token_key_len_ = local_length;
        } else {
            return false;
        }
    }

    *auth_token_key = cached_auth_token_key_.get();
    *length = cached_auth_token_key_len_;

    return true;
}

void TrustyGateKeeper::GetPasswordKey(const uint8_t** password_key,
                                      uint32_t* length) {
    *password_key = const_cast<const uint8_t*>(password_key_.get());
    *length = HMAC_SHA_256_KEY_SIZE;
}

void TrustyGateKeeper::ComputePasswordSignature(uint8_t* signature,
                                                uint32_t signature_length,
                                                const uint8_t* key,
                                                uint32_t key_length,
                                                const uint8_t* password,
                                                uint32_t password_length,
                                                salt_t salt) const {
    // todo: heap allocate
    uint8_t salted_password[password_length + sizeof(salt)];
    memcpy(salted_password, &salt, sizeof(salt));
    memcpy(salted_password + sizeof(salt), password, password_length);
    ComputeSignature(signature, signature_length, key, key_length,
                     salted_password, password_length + sizeof(salt));
}

void TrustyGateKeeper::GetRandom(void* random, uint32_t requested_size) const {
    if (random == NULL)
        return;
    trusty_rng_secure_rand(reinterpret_cast<uint8_t*>(random), requested_size);
}

void TrustyGateKeeper::ComputeSignature(uint8_t* signature,
                                        uint32_t signature_length,
                                        const uint8_t* key,
                                        uint32_t key_length,
                                        const uint8_t* message,
                                        const uint32_t length) const {
    uint8_t buf[HMAC_SHA_256_KEY_SIZE];
    unsigned int buf_len;

    HMAC(EVP_sha256(), key, key_length, message, length, buf, &buf_len);
    size_t to_write = buf_len;
    if (buf_len > signature_length)
        to_write = signature_length;
    memset(signature, 0, signature_length);
    memcpy(signature, buf, to_write);
}

uint64_t TrustyGateKeeper::GetMillisecondsSinceBoot() const {
    int rc;
    int64_t secure_time_ns = 0;
    rc = trusty_gettime(0, &secure_time_ns);
    if (rc != NO_ERROR) {
        secure_time_ns = 0;
        TLOGE("%s Error:[0x%x].\n", __func__, rc);
    }
    return secure_time_ns / 1000 / 1000;
}

bool TrustyGateKeeper::GetSecureFailureRecord(uint32_t uid,
                                              secure_id_t user_id,
                                              failure_record_t* record) {
    storage_session_t session;
    int rc = storage_open_session(&session, GATEKEEPER_STORAGE_PORT);
    if (rc < 0) {
        TLOGE("Error: [%d] opening storage session\n", rc);
        return false;
    }

    char id[STORAGE_ID_LENGTH_MAX];
    memset(id, 0, sizeof(id));

    file_handle_t handle;
    snprintf(id, STORAGE_ID_LENGTH_MAX, GATEKEEPER_PREFIX "%u", uid);
    rc = storage_open_file(session, &handle, id, 0, 0);
    if (rc < 0) {
        TLOGE("Error:[%d] opening storage object.\n", rc);
        storage_close_session(session);
        return false;
    }

    failure_record_t owner_record;
    rc = storage_read(handle, 0, &owner_record, sizeof(owner_record));
    storage_close_file(handle);
    storage_close_session(session);

    if (rc < 0) {
        TLOGE("Error:[%d] reading storage object.\n", rc);
        return false;
    }

    if ((size_t)rc < sizeof(owner_record)) {
        TLOGE("Error: invalid object size [%d].\n", rc);
        return false;
    }

    if (owner_record.secure_user_id != user_id) {
        TLOGE("Error:[%" PRIu64 " != %" PRIu64 "] secure storage corrupt.\n",
              owner_record.secure_user_id, user_id);
        return false;
    }

    *record = owner_record;
    return true;
}

bool TrustyGateKeeper::GetFailureRecord(uint32_t uid,
                                        secure_id_t user_id,
                                        failure_record_t* record,
                                        bool secure) {
    if (secure) {
        return GetSecureFailureRecord(uid, user_id, record);
    } else {
        return GetMemoryRecord(uid, user_id, record);
    }
}

bool TrustyGateKeeper::ClearFailureRecord(uint32_t uid,
                                          secure_id_t user_id,
                                          bool secure) {
    failure_record_t record;
    record.secure_user_id = user_id;
    record.last_checked_timestamp = 0;
    record.failure_counter = 0;
    return WriteFailureRecord(uid, &record, secure);
}

bool TrustyGateKeeper::WriteSecureFailureRecord(uint32_t uid,
                                                failure_record_t* record) {
    storage_session_t session;
    int rc = storage_open_session(&session, GATEKEEPER_STORAGE_PORT);
    if (rc < 0) {
        TLOGE("Error: [%d] failed to open storage session\n", rc);
        return false;
    }

    char id[STORAGE_ID_LENGTH_MAX];
    memset(id, 0, sizeof(id));
    snprintf(id, STORAGE_ID_LENGTH_MAX, GATEKEEPER_PREFIX "%u", uid);

    file_handle_t handle;
    rc = storage_open_file(session, &handle, id, STORAGE_FILE_OPEN_CREATE, 0);
    if (rc < 0) {
        TLOGE("Error: [%d] failed to open storage object %s\n", rc, id);
        storage_close_session(session);
        return false;
    }

    rc = storage_write(handle, 0, record, sizeof(*record), STORAGE_OP_COMPLETE);
    storage_close_file(handle);
    storage_close_session(session);

    if (rc < 0) {
        TLOGE("Error:[%d] writing storage object.\n", rc);
        return false;
    }

    if ((size_t)rc < sizeof(*record)) {
        TLOGE("Error: invalid object size [%d].\n", rc);
        return false;
    }

    return true;
}

bool TrustyGateKeeper::WriteFailureRecord(uint32_t uid,
                                          failure_record_t* record,
                                          bool secure) {
    if (secure) {
        return WriteSecureFailureRecord(uid, record);
    } else {
        return WriteMemoryRecord(uid, record);
    }
}

bool TrustyGateKeeper::IsHardwareBacked() const {
    return true;
}

void TrustyGateKeeper::InitMemoryRecords() {
    if (!mem_records_.get()) {
        mem_failure_record_t* mem_recs = new mem_failure_record_t[MAX_FAILURE_RECORDS];
        memset(mem_recs, 0, sizeof(*mem_recs));
        mem_records_.reset(mem_recs);
        num_mem_records_ = 0;
    }
}

bool TrustyGateKeeper::GetMemoryRecord(uint32_t uid, secure_id_t user_id,
                                       failure_record_t* record) {
    InitMemoryRecords();

    for (int i = 0; i < num_mem_records_; i++) {
        if (mem_records_[i].uid == uid) {
            if (mem_records_[i].failure_record.secure_user_id == user_id) {
                *record = mem_records_[i].failure_record;
                return true;
            }
            TLOGE("Error:[%" PRIu64 " != %" PRIu64 "] mismatched SID for uid %u.\n",
                  mem_records_[i].failure_record.secure_user_id, user_id, uid);
            return false;
        }
    }

    return false;
}

bool TrustyGateKeeper::WriteMemoryRecord(uint32_t uid, failure_record_t* record) {
    InitMemoryRecords();

    int idx = 0;
    int min_idx = 0;
    uint64_t min_timestamp = ~0ULL;
    for (idx = 0; idx < num_mem_records_; idx++) {
        if (mem_records_[idx].uid == uid) {
            break;
        }

        if (mem_records_[idx].failure_record.last_checked_timestamp <= min_timestamp) {
            min_timestamp = mem_records_[idx].failure_record.last_checked_timestamp;
            min_idx = idx;
        }
    }

    if (idx >= MAX_FAILURE_RECORDS) {
        // replace oldest element
        idx = min_idx;
    } else if (idx == num_mem_records_) {
        num_mem_records_++;
    }

    mem_records_[idx].uid = uid;
    mem_records_[idx].failure_record = *record;
    return true;
}

gatekeeper_error_t TrustyGateKeeper::RemoveUser(uint32_t uid) {
    bool deleted = false;

    // Remove from the in-memory record
    if (mem_records_.get()) {
        int idx = 0;
        for (idx = 0; idx < num_mem_records_; idx++) {
            if (mem_records_[idx].uid == uid) {
                memset(&mem_records_[idx], 0, sizeof(mem_failure_record_t));
                deleted = true;
            }
        }
    }

    storage_session_t session;
    int rc = storage_open_session(&session, GATEKEEPER_STORAGE_PORT);
    if (rc < 0) {
        TLOGE("Error: [%d] opening storage session\n", rc);
        return ERROR_UNKNOWN;
    }

    char id[STORAGE_ID_LENGTH_MAX];
    memset(id, 0, sizeof(id));
    snprintf(id, STORAGE_ID_LENGTH_MAX, GATEKEEPER_PREFIX "%u", uid);

    rc = storage_delete_file(session, id, STORAGE_OP_COMPLETE);
    if (rc < 0) {
        // if the user's record was added to memory, there may not be a
        // record in storage, so only report failures if we haven't already
        // deleted a record from memory.
        storage_close_session(session);
        return deleted ? ERROR_NONE : ERROR_UNKNOWN;
    }
    storage_close_session(session);

    return ERROR_NONE;
}

gatekeeper_error_t TrustyGateKeeper::RemoveAllUsers() {

    storage_session_t session;
    int rc = storage_open_session(&session, GATEKEEPER_STORAGE_PORT);
    if (rc < 0) {
        TLOGE("Error: [%d] opening storage session\n", rc);
        return ERROR_UNKNOWN;
    }

    storage_open_dir_state *state;
    rc = storage_open_dir(session, "", &state);
    if (rc < 0) {
        TLOGE("Error:[%d] opening storage dir.\n", rc);
        storage_close_session(session);
        return ERROR_UNKNOWN;
    }
    while (true) {
        uint8_t dir_flags = 0;
        char name[STORAGE_ID_LENGTH_MAX];
        rc = storage_read_dir(session, state, &dir_flags, name, STORAGE_ID_LENGTH_MAX);
        if (rc < 0) {
            TLOGE("Error:[%d] reading storage dir.\n", rc);
            storage_close_session(session);
            return ERROR_UNKNOWN;
        }
        if ((dir_flags & STORAGE_FILE_LIST_STATE_MASK) == STORAGE_FILE_LIST_END) {
            break;
        }
        if (!strncmp(name, GATEKEEPER_PREFIX, strlen(GATEKEEPER_PREFIX))) {
            rc = storage_delete_file(session, name, 0);
            if (rc < 0) {
                TLOGE("Error:[%d] deleting storage object.\n", rc);
                storage_close_session(session);
                return ERROR_UNKNOWN;
            }
        }
    }
    storage_close_dir(session, state);
    rc = storage_end_transaction(session, true);
    if (rc < 0) {
        TLOGE("Error:[%d] ending storage transaction.\n", rc);
        storage_close_session(session);
        return ERROR_UNKNOWN;
    }
    storage_close_session(session);

    num_mem_records_ = 0;

    return ERROR_NONE;
}

}  // namespace gatekeeper