From c11d8d383d50b3c2743b0c71b3d7a4486ce62b61 Mon Sep 17 00:00:00 2001 From: Bill Yi Date: Fri, 9 Oct 2015 16:03:11 -0700 Subject: Initial TrustyGateKeeper --- LICENSE | 201 ++++++++++++++++++++++++++++ ipc/gatekeeper_ipc.cpp | 329 +++++++++++++++++++++++++++++++++++++++++++++ ipc/gatekeeper_ipc.h | 38 ++++++ ipc/rules.mk | 22 +++ manifest.c | 35 +++++ rules.mk | 42 ++++++ trusty_gatekeeper.cpp | 354 +++++++++++++++++++++++++++++++++++++++++++++++++ trusty_gatekeeper.h | 93 +++++++++++++ 8 files changed, 1114 insertions(+) create mode 100644 LICENSE create mode 100644 ipc/gatekeeper_ipc.cpp create mode 100644 ipc/gatekeeper_ipc.h create mode 100644 ipc/rules.mk create mode 100644 manifest.c create mode 100644 rules.mk create mode 100644 trusty_gatekeeper.cpp create mode 100644 trusty_gatekeeper.h diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/ipc/gatekeeper_ipc.cpp b/ipc/gatekeeper_ipc.cpp new file mode 100644 index 0000000..267a629 --- /dev/null +++ b/ipc/gatekeeper_ipc.cpp @@ -0,0 +1,329 @@ +/* + * Copyright (C) 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. + */ + +// TODO: add guard in header +extern "C" { +#include +} + +#include +#include + +#include +#include + +#include + +#include "trusty_gatekeeper.h" +#include "gatekeeper_ipc.h" + +using namespace gatekeeper; +TrustyGateKeeper *device; + +class SessionManager { + public: + SessionManager(long* err) { + *err = device->OpenSession(); + } + ~SessionManager() { + device->CloseSession(); + } +}; + +class MessageDeleter { +public: + explicit MessageDeleter(handle_t chan, int id) { + chan_ = chan; + id_ = id; + } + + ~MessageDeleter() { + put_msg(chan_, id_); + } + +private: + handle_t chan_; + int id_; +}; + + +static gatekeeper_error_t tipc_err_to_gatekeeper_err(long tipc_err) { + switch (tipc_err) { + case NO_ERROR: + return ERROR_NONE; + case ERR_BAD_LEN: + case ERR_NOT_VALID: + case ERR_NOT_IMPLEMENTED: + case ERR_NOT_SUPPORTED: + return ERROR_INVALID; + default: + return ERROR_UNKNOWN; + } +} + +template +static gatekeeper_error_t exec_cmd(void (GateKeeper::*operation)(const Request&, Response*), + uint8_t *in_buf, uint32_t in_size, + UniquePtr *out_buf, uint32_t *out_size) { + long rc; + SessionManager sm(&rc); + if (rc != NO_ERROR) + return tipc_err_to_gatekeeper_err(rc); + + Request req; + gatekeeper_error_t err = req.Deserialize(in_buf, in_buf + in_size); + if (err != ERROR_NONE) { + TLOGE("error (%d) deserializing request\n", err); + return ERROR_INVALID; + } + + Response rsp; + (device->*operation)(req, &rsp); + + *out_size = rsp.GetSerializedSize(); + if (*out_size > GATEKEEPER_MAX_BUFFER_LENGTH) { + *out_size = 0; + TLOGE("response size too large (%d)\n", *out_size); + return ERROR_UNKNOWN; + } + + out_buf->reset(new uint8_t[*out_size]); + if (out_buf->get() == NULL) { + *out_size = 0; + return ERROR_UNKNOWN; + } + + if(rsp.Serialize(out_buf->get(), out_buf->get() + *out_size) != *out_size) { + TLOGE("error serializing response message\n"); + return ERROR_UNKNOWN; + } + + return ERROR_NONE; +} + +static gatekeeper_error_t handle_request(uint32_t cmd, uint8_t *in_buf, uint32_t in_buf_size, + UniquePtr *out_buf, uint32_t *out_buf_size) { + switch (cmd) { + case GK_ENROLL: + return exec_cmd(&GateKeeper::Enroll, in_buf, in_buf_size, + out_buf, out_buf_size); + case GK_VERIFY: + return exec_cmd(&GateKeeper::Verify, in_buf, in_buf_size, + out_buf, out_buf_size); + default: + return ERROR_INVALID; + } +} + + +static gatekeeper_error_t send_response(handle_t chan, + uint32_t cmd, uint8_t *out_buf, uint32_t out_buf_size) { + struct gatekeeper_message gk_msg = { cmd | GK_RESP_BIT }; + iovec_t iov[2] = { + { &gk_msg, sizeof(gk_msg) }, + { out_buf, out_buf_size }, + }; + ipc_msg_t msg = { 2, iov, 0, NULL }; + + /* send message back to the caller */ + long rc = send_msg(chan, &msg); + + // fatal error + if (rc < 0) { + TLOGE("failed (%d) to send_msg for chan (%d)\n", rc, chan); + return tipc_err_to_gatekeeper_err(rc); + } + + return ERROR_NONE; +} + +static gatekeeper_error_t send_error_response(handle_t chan, uint32_t cmd, gatekeeper_error_t err) { + GateKeeperMessage msg(err); + size_t serialized_size = msg.GetSerializedSize(); + uint8_t *out_buf = new uint8_t[serialized_size]; + if (out_buf == NULL) { + return ERROR_UNKNOWN; + } + + msg.Serialize(out_buf, out_buf + serialized_size); + gatekeeper_error_t rc = send_response(chan, cmd, out_buf, serialized_size); + + delete[] out_buf; + return rc; +} + + +static long handle_msg(handle_t chan) { + /* get message info */ + ipc_msg_info_t msg_inf; + + long rc = get_msg(chan, &msg_inf); + if (rc == ERR_NO_MSG) + return ERROR_NONE; /* no new messages */ + + // fatal error + if (rc != NO_ERROR) { + TLOGE("failed (%d) to get_msg for chan (%d), closing connection\n", + rc, chan); + return rc; + } + + MessageDeleter md(chan, msg_inf.id); + + UniquePtr msg_buf(new uint8_t[msg_inf.len]); + + /* read msg content */ + iovec_t iov = { msg_buf.get(), msg_inf.len }; + ipc_msg_t msg = { 1, &iov, 0, NULL} ; + + rc = read_msg(chan, msg_inf.id, 0, &msg); + + if (rc < 0) { + TLOGE("failed to read msg (%d)\n", rc, chan); + return rc; + } + + if(((unsigned long) rc) < sizeof(gatekeeper_message)) { + TLOGE("invalid message of size (%d)\n", rc, chan); + return ERROR_INVALID; + } + + /* get request command */ + gatekeeper_message *gk_msg = + reinterpret_cast(msg_buf.get()); + + UniquePtr out_buf; + uint32_t out_buf_size = 0; + rc = handle_request(gk_msg->cmd, gk_msg->payload, + msg_inf.len - sizeof(gatekeeper_message), &out_buf, &out_buf_size); + + if (rc < 0) { + TLOGE("unable (%d) to handle request", rc); + return send_error_response(chan, gk_msg->cmd, tipc_err_to_gatekeeper_err(rc)); + } + + rc = send_response(chan, gk_msg->cmd, out_buf.get(), out_buf_size); + + if (rc < 0) { + TLOGE("unable (%d) to send response", rc); + } + + return rc; +} + +static void gatekeeper_handle_port(uevent_t *ev) { + if ((ev->event & IPC_HANDLE_POLL_ERROR) || + (ev->event & IPC_HANDLE_POLL_HUP) || + (ev->event & IPC_HANDLE_POLL_MSG) || + (ev->event & IPC_HANDLE_POLL_SEND_UNBLOCKED)) { + /* should never happen with port handles */ + TLOGE("error event (0x%x) for port (%d)\n", + ev->event, ev->handle); + abort(); + } + + uuid_t peer_uuid; + if (ev->event & IPC_HANDLE_POLL_READY) { + /* incoming connection: accept it */ + int rc = accept(ev->handle, &peer_uuid); + if (rc < 0) { + TLOGE("failed (%d) to accept on port %d\n", + rc, ev->handle); + return; + } + } +} + +static void gatekeeper_handle_channel(uevent_t *ev) { + if ((ev->event & IPC_HANDLE_POLL_ERROR) || + (ev->event & IPC_HANDLE_POLL_READY)) { + /* close it as it is in an error state */ + TLOGE("error event (0x%x) for chan (%d)\n", + ev->event, ev->handle); + abort(); + } + + handle_t chan = ev->handle; + + if (ev->event & IPC_HANDLE_POLL_MSG) { + long rc = handle_msg(chan); + if (rc != NO_ERROR) { + /* report an error and close channel */ + TLOGE("failed (%d) to handle event on channel %d\n", rc, ev->handle); + close(chan); + } + } + + if (ev->event & IPC_HANDLE_POLL_HUP) { + /* closed by peer. */ + close(chan); + return; + } + +} + +static long gatekeeper_ipc_init(void) { + int rc; + + /* Initialize service */ + rc = port_create(GATEKEEPER_PORT, 1, GATEKEEPER_MAX_BUFFER_LENGTH, + IPC_PORT_ALLOW_NS_CONNECT); + if (rc < 0) { + TLOGE("Failed (%d) to create port %s\n", rc, GATEKEEPER_PORT); + } + + return rc; +} + +int main(void) { + long rc; + uevent_t event; + + TLOGI("Initializing\n"); + + device = new TrustyGateKeeper(); + + rc = gatekeeper_ipc_init(); + if (rc < 0) { + TLOGE("failed (%d) to initialize gatekeeper", rc); + return rc; + } + + handle_t port = (handle_t) rc; + + /* enter main event loop */ + while (true) { + event.handle = INVALID_IPC_HANDLE; + event.event = 0; + event.cookie = NULL; + + rc = wait_any(&event, -1); + if (rc < 0) { + TLOGE("wait_any failed (%d)\n", rc); + break; + } + + if (rc == NO_ERROR) { /* got an event */ + if (event.handle == port) { + gatekeeper_handle_port(&event); + } else { + gatekeeper_handle_channel(&event); + } + } + } + + return 0; +} diff --git a/ipc/gatekeeper_ipc.h b/ipc/gatekeeper_ipc.h new file mode 100644 index 0000000..ed86419 --- /dev/null +++ b/ipc/gatekeeper_ipc.h @@ -0,0 +1,38 @@ +/* + * Copyright (C) 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. + */ + +#define GATEKEEPER_PORT "com.android.trusty.gatekeeper" +#define GATEKEEPER_MAX_BUFFER_LENGTH 1024 + +enum gatekeeper_command { + GK_REQ_SHIFT = 1, + GK_RESP_BIT = 1, + + GK_ENROLL = (0 << GK_REQ_SHIFT), + GK_VERIFY = (1 << GK_REQ_SHIFT), +}; + +/** + * gatekeeper_message - Serial header for communicating with GK server + * @cmd: the command, one of ENROLL, VERIFY. Payload must be a serialized + * buffer of the corresponding request object. + * @payload: start of the serialized command specific payload + */ +struct gatekeeper_message { + uint32_t cmd; + uint8_t payload[0]; +}; + diff --git a/ipc/rules.mk b/ipc/rules.mk new file mode 100644 index 0000000..fdfdcdb --- /dev/null +++ b/ipc/rules.mk @@ -0,0 +1,22 @@ +# Copyright (C) 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. +# + +CUR_DIR := $(GET_LOCAL_DIR) + +MODULE_SRCS += \ + $(CUR_DIR)/gatekeeper_ipc.cpp + +CUR_DIR = + diff --git a/manifest.c b/manifest.c new file mode 100644 index 0000000..fa80047 --- /dev/null +++ b/manifest.c @@ -0,0 +1,35 @@ +/* + * Copyright (C) 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 +#include + +// TODO: generate my own UUID +trusty_app_manifest_t TRUSTY_APP_MANIFEST_ATTRS trusty_app_manifest = +{ + + /* UUID : {38ba0cdc-df0e-11e4-9869-233fb6ae4795} */ + { 0x38ba0cdc, 0xdf0e, 0x11e4, + { 0x98, 0x69, 0x23, 0x3f, 0xb6, 0xae, 0x47, 0x95 } }, + + /* optional configuration options here */ + { + /* openssl need a larger heap */ + TRUSTY_APP_CONFIG_MIN_HEAP_SIZE(2 * 4096), + + /* openssl need a larger stack */ + TRUSTY_APP_CONFIG_MIN_STACK_SIZE(1 * 4096), + }, +}; diff --git a/rules.mk b/rules.mk new file mode 100644 index 0000000..15aec82 --- /dev/null +++ b/rules.mk @@ -0,0 +1,42 @@ +# Copyright (C) 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. +# + +LOCAL_DIR := $(GET_LOCAL_DIR) + +MODULE := $(LOCAL_DIR) + +MODULE_SRCS += \ + $(LOCAL_DIR)/manifest.c \ + $(LOCAL_DIR)/trusty_gatekeeper.cpp \ + +IPC := ipc + +MODULE_DEPS += \ + app/trusty \ + lib/libc-trusty \ + lib/libstdc++-trusty \ + lib/rng \ + lib/hwkey \ + lib/storage \ + lib/keymaster \ + system/gatekeeper \ + +MODULE_INCLUDES += \ + $(LOCAL_DIR) + +include $(LOCAL_DIR)/$(IPC)/rules.mk + +include make/module.mk + diff --git a/trusty_gatekeeper.cpp b/trusty_gatekeeper.cpp new file mode 100644 index 0000000..26a8a3a --- /dev/null +++ b/trusty_gatekeeper.cpp @@ -0,0 +1,354 @@ +/* + * 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 +#include + +extern "C" { +#include +#include +#include +#include + +#include +} + +#include "trusty_gatekeeper.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() { + rng_initialized_ = false; + calls_since_reseed_ = 0; + num_mem_records_ = 0; + + SeedRngIfNeeded(); +} + +long TrustyGateKeeper::OpenSession() { + if (!SeedRngIfNeeded()) { + return ERR_NOT_READY; + } + + return DeriveMasterKey(); +} + +void TrustyGateKeeper::CloseSession() { + ClearMasterKey(); +} + +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 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::DeriveMasterKey() { + long rc = hwkey_open(); + if (rc < 0) { + return rc; + } + + hwkey_session_t session = (hwkey_session_t) rc; + + master_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, master_key_.get(), + HMAC_SHA_256_KEY_SIZE); + + hwkey_close(session); + return rc; +} + +void TrustyGateKeeper::ClearMasterKey() { + memset_s(master_key_.get(), 0, HMAC_SHA_256_KEY_SIZE); + master_key_.reset(); +} + +bool TrustyGateKeeper::GetAuthTokenKey(const uint8_t **auth_token_key, + size_t *length) const { + *length = 0; + *auth_token_key = NULL; + + long rc = keymaster_open(); + if (rc < 0) { + return false; + } + + keymaster_session_t session = (keymaster_session_t) rc; + + uint8_t *key = NULL; + uint32_t local_length = 0; + + rc = keymaster_get_auth_token_key(session, &key, &local_length); + keymaster_close(session); + + if (rc == NO_ERROR) { + *auth_token_key = key; + *length = local_length; + return true; + } else { + return false; + } +} + +void TrustyGateKeeper::GetPasswordKey(const uint8_t **password_key, size_t *length) { + *password_key = const_cast(master_key_.get()); + *length = HMAC_SHA_256_KEY_SIZE; +} + +void TrustyGateKeeper::ComputePasswordSignature(uint8_t *signature, size_t signature_length, + const uint8_t *key, size_t key_length, const uint8_t *password, + size_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, size_t requested_size) const { + if (random == NULL) return; + trusty_rng_secure_rand(reinterpret_cast(random), requested_size); +} + +void TrustyGateKeeper::ComputeSignature(uint8_t *signature, size_t signature_length, + const uint8_t *key, size_t key_length, const uint8_t *message, + const size_t length) const { + uint8_t buf[HMAC_SHA_256_KEY_SIZE]; + size_t 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 { + status_t rc; + int64_t secure_time_ns = 0; + rc = gettime(0, 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); + 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); + if (rc < 0) { + TLOGE("Error:[%d] opening storage object.\n", rc); + return false; + } + + failure_record_t owner_record; + rc = storage_read(session, handle, 0, &owner_record, sizeof(owner_record)); + storage_close_file(session, 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:[%llu != %llu] 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(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; + long rc = storage_open_session(&session); + 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_OPEN_CREATE); + if (rc < 0) { + TLOGE("Error: [%d] failed to open storage object %s\n", rc, id); + return false; + } + + rc = storage_write(session, handle, 0, record, sizeof(*record)); + storage_close_file(session, 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(record); + } +} + +bool TrustyGateKeeper::IsHardwareBacked() const { + return true; +} + +void TrustyGateKeeper::InitMemoryRecords() { + if (!mem_records_.get()) { + failure_record_t *mem_recs = new 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(secure_id_t user_id, failure_record_t *record) { + InitMemoryRecords(); + + for (int i = 0; i < num_mem_records_; i++) { + if (mem_records_[i].secure_user_id == user_id) { + *record = mem_records_[i]; + return true; + } + } + + record->secure_user_id = user_id; + record->failure_counter = 0; + record->last_checked_timestamp = 0; + + return true; +} + +bool TrustyGateKeeper::WriteMemoryRecord(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].secure_user_id == record->secure_user_id) { + break; + } + + if (mem_records_[idx].last_checked_timestamp <= min_timestamp) { + min_timestamp = mem_records_[idx].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] = *record; + return true; +} + +} diff --git a/trusty_gatekeeper.h b/trusty_gatekeeper.h new file mode 100644 index 0000000..1235feb --- /dev/null +++ b/trusty_gatekeeper.h @@ -0,0 +1,93 @@ +/* + * 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. + */ + +#ifndef TRUSTY_GATEKEEPER_H_ +#define TRUSTY_GATEKEEPER_H_ + +#include +#include + +#include + +#define LOG_TAG "trusty_gatekeeper" +#define TLOGE(fmt, ...) \ + fprintf(stderr, "%s: %d: " fmt, LOG_TAG, __LINE__, ## __VA_ARGS__) + +#if LOCAL_TRACE +#define TLOGI(fmt, ...) \ + fprintf(stderr, "%s: %d: " fmt, LOG_TAG, __LINE__, ## __VA_ARGS__) +#else +#define TLOGI(fmt, ...) +#endif + +namespace gatekeeper { + +class TrustyGateKeeper : public GateKeeper { +public: + TrustyGateKeeper(); + + long OpenSession(); + void CloseSession(); +protected: + // See gatekeeper/gatekeeper.h for documentation + + virtual bool GetAuthTokenKey(const uint8_t **auth_token_key, size_t *length) const; + + virtual void GetPasswordKey(const uint8_t **password_key, size_t *length); + + virtual void ComputePasswordSignature(uint8_t *signature, size_t signature_length, + const uint8_t *key, size_t key_length, const uint8_t *password, + size_t password_length, salt_t salt) const; + + virtual void GetRandom(void *random, size_t requested_size) const; + virtual void ComputeSignature(uint8_t *signature, size_t signature_length, + const uint8_t *key, size_t key_length, const uint8_t *message, + const size_t length) const; + virtual uint64_t GetMillisecondsSinceBoot() const; + + virtual bool GetFailureRecord(uint32_t uid, secure_id_t user_id, failure_record_t *record, + bool secure); + virtual bool WriteFailureRecord(uint32_t uid, failure_record_t *record, bool secure); + virtual bool ClearFailureRecord(uint32_t uid, secure_id_t user_id, bool secure); + + virtual bool IsHardwareBacked() const; + +private: + bool SeedRngIfNeeded(); + bool ShouldReseedRng(); + bool ReseedRng(); + + long DeriveMasterKey(); + void ClearMasterKey(); + + void InitMemoryRecords(); + bool GetMemoryRecord(secure_id_t user_id, failure_record_t *record); + bool WriteMemoryRecord(failure_record_t *record); + bool GetSecureFailureRecord(uint32_t uid, secure_id_t user_id, + failure_record_t *record); + bool WriteSecureFailureRecord(uint32_t uid, failure_record_t *record); + + UniquePtr master_key_; + bool rng_initialized_; + int calls_since_reseed_; + + int num_mem_records_; + UniquePtr mem_records_; +}; + +} + +#endif // TRUSTY_GATEKEEPER_H_ -- cgit v1.2.3