• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2012 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 
17 #include "keymaster_ipc.h"
18 
19 #include <lib/system_state/system_state.h>
20 #include <lk/macros.h>
21 #include <stddef.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <trusty_ipc.h>
26 #include <uapi/err.h>
27 
28 #include <interface/keymaster/keymaster.h>
29 
30 #include <keymaster/UniquePtr.h>
31 
32 #include <openssl/crypto.h>
33 
34 #include "trusty_keymaster.h"
35 #include "trusty_logger.h"
36 
37 using namespace keymaster;
38 
39 typedef void (*event_handler_proc_t)(const uevent_t* ev, void* ctx);
40 struct tipc_event_handler {
41     event_handler_proc_t proc;
42     void* priv;
43 };
44 
45 struct keymaster_chan_ctx {
46     struct tipc_event_handler handler;
47     uuid_t uuid;
48     handle_t chan;
49     long (*dispatch)(keymaster_chan_ctx*,
50                      keymaster_message*,
51                      uint32_t,
52                      keymaster::UniquePtr<uint8_t[]>*,
53                      uint32_t*);
54 };
55 
56 struct keymaster_srv_ctx {
57     handle_t port_secure;
58     handle_t port_non_secure;
59 };
60 
61 static void keymaster_port_handler_secure(const uevent_t* ev, void* priv);
62 static void keymaster_port_handler_non_secure(const uevent_t* ev, void* priv);
63 
64 static tipc_event_handler keymaster_port_evt_handler_secure = {
65         .proc = keymaster_port_handler_secure,
66         .priv = NULL,
67 };
68 
69 static tipc_event_handler keymaster_port_evt_handler_non_secure = {
70         .proc = keymaster_port_handler_non_secure,
71         .priv = NULL,
72 };
73 
74 static void keymaster_chan_handler(const uevent_t* ev, void* priv);
75 
76 TrustyKeymaster* device;
77 
handle_port_errors(const uevent_t * ev)78 static long handle_port_errors(const uevent_t* ev) {
79     if ((ev->event & IPC_HANDLE_POLL_ERROR) ||
80         (ev->event & IPC_HANDLE_POLL_HUP) ||
81         (ev->event & IPC_HANDLE_POLL_MSG) ||
82         (ev->event & IPC_HANDLE_POLL_SEND_UNBLOCKED)) {
83         /* should never happen with port handles */
84         LOG_E("error event (0x%x) for port (%d)", ev->event, ev->handle);
85         return ERR_BAD_STATE;
86     }
87 
88     return NO_ERROR;
89 }
90 
wait_to_send(handle_t session,struct ipc_msg * msg)91 static int wait_to_send(handle_t session, struct ipc_msg* msg) {
92     int rc;
93     struct uevent ev = UEVENT_INITIAL_VALUE(ev);
94 
95     rc = wait(session, &ev, INFINITE_TIME);
96     if (rc < 0) {
97         LOG_E("failed to wait for outgoing queue to free up");
98         return rc;
99     }
100 
101     if (ev.event & IPC_HANDLE_POLL_SEND_UNBLOCKED) {
102         return send_msg(session, msg);
103     }
104 
105     if (ev.event & IPC_HANDLE_POLL_MSG) {
106         return ERR_BUSY;
107     }
108 
109     if (ev.event & IPC_HANDLE_POLL_HUP) {
110         return ERR_CHANNEL_CLOSED;
111     }
112 
113     return rc;
114 }
115 
send_response(handle_t chan,uint32_t cmd,uint8_t * out_buf,uint32_t out_buf_size)116 static long send_response(handle_t chan,
117                           uint32_t cmd,
118                           uint8_t* out_buf,
119                           uint32_t out_buf_size) {
120     struct keymaster_message km_msg;
121     km_msg.cmd = cmd | KEYMASTER_RESP_BIT;
122     struct iovec iov[2] = {{&km_msg, sizeof(km_msg)}, {nullptr, 0}};
123     ipc_msg_t msg = {2, iov, 0, NULL};
124     uint32_t msg_size;
125     uint32_t bytes_remaining = out_buf_size;
126     uint32_t bytes_sent = 0;
127     uint32_t max_msg_size = KEYMASTER_MAX_BUFFER_LENGTH - 64;
128 
129     do {
130         msg_size = MIN(max_msg_size, bytes_remaining);
131         if (msg_size == bytes_remaining) {
132             km_msg.cmd = km_msg.cmd | KEYMASTER_STOP_BIT;
133         }
134         iov[1] = {out_buf + bytes_sent, msg_size};
135 
136         long rc = send_msg(chan, &msg);
137         if (rc == ERR_NOT_ENOUGH_BUFFER) {
138             rc = wait_to_send(chan, &msg);
139         }
140 
141         // fatal error
142         if (rc < 0) {
143             LOG_E("failed (%ld) to send_msg for chan (%d)", rc, chan);
144             return rc;
145         }
146         bytes_remaining -= msg_size;
147         bytes_sent += msg_size;
148     } while (bytes_remaining);
149 
150     return NO_ERROR;
151 }
152 
send_error_response(handle_t chan,uint32_t cmd,keymaster_error_t err)153 static long send_error_response(handle_t chan,
154                                 uint32_t cmd,
155                                 keymaster_error_t err) {
156     return send_response(chan, cmd, reinterpret_cast<uint8_t*>(&err),
157                          sizeof(err));
158 }
159 
160 /*
161  * deseralize_request and serialize_request are used by the different
162  * overloads of the do_dispatch template to handle the new API signatures
163  * that keymaster is migrating to.
164  */
165 template <typename Request>
deserialize_request(struct keymaster_message * msg,uint32_t payload_size,Request & req)166 static long deserialize_request(struct keymaster_message* msg,
167                                 uint32_t payload_size,
168                                 Request& req) {
169     const uint8_t* payload = msg->payload;
170     if (!req.Deserialize(&payload, msg->payload + payload_size))
171         return ERR_NOT_VALID;
172 
173     return NO_ERROR;
174 }
175 
176 template <typename Response>
serialize_response(Response & rsp,keymaster::UniquePtr<uint8_t[]> * out,uint32_t * out_size)177 static long serialize_response(Response& rsp,
178                                keymaster::UniquePtr<uint8_t[]>* out,
179                                uint32_t* out_size) {
180     *out_size = rsp.SerializedSize();
181 
182     out->reset(new (std::nothrow) uint8_t[*out_size]);
183     if (out->get() == NULL) {
184         *out_size = 0;
185         return ERR_NO_MEMORY;
186     }
187 
188     rsp.Serialize(out->get(), out->get() + *out_size);
189 
190     return NO_ERROR;
191 }
192 
193 template <typename Keymaster, typename Request, typename Response>
do_dispatch(void (Keymaster::* operation)(const Request &,Response *),struct keymaster_message * msg,uint32_t payload_size,keymaster::UniquePtr<uint8_t[]> * out,uint32_t * out_size)194 static long do_dispatch(void (Keymaster::*operation)(const Request&, Response*),
195                         struct keymaster_message* msg,
196                         uint32_t payload_size,
197                         keymaster::UniquePtr<uint8_t[]>* out,
198                         uint32_t* out_size) {
199     long err;
200     Request req(device->message_version());
201 
202     err = deserialize_request(msg, payload_size, req);
203     if (err != NO_ERROR)
204         return err;
205 
206     Response rsp(device->message_version());
207     (device->*operation)(req, &rsp);
208     LOG_D("do_dispatch #1 err: %d", rsp.error);
209 
210     if (msg->cmd == KM_CONFIGURE) {
211         device->set_configure_error(rsp.error);
212     }
213 
214     err = serialize_response(rsp, out, out_size);
215     LOG_D("do_dispatch #1: serialized response, %d bytes", *out_size);
216     if (err != NO_ERROR) {
217         LOG_E("Error serializing response: %ld", err);
218     }
219 
220     return err;
221 }
222 
223 /*
224  * Keymaster is migrating to new API signatures.
225  * This overloaded dispatch is used for methods that accept one Request argument
226  * and return a Response (e.g. COMPUTE_SHARED_HMAC_RESPONSE)
227  */
228 template <typename Keymaster, typename Request, typename Response>
do_dispatch(Response (Keymaster::* operation)(const Request &),struct keymaster_message * msg,uint32_t payload_size,keymaster::UniquePtr<uint8_t[]> * out,uint32_t * out_size)229 static long do_dispatch(Response (Keymaster::*operation)(const Request&),
230                         struct keymaster_message* msg,
231                         uint32_t payload_size,
232                         keymaster::UniquePtr<uint8_t[]>* out,
233                         uint32_t* out_size) {
234     long err;
235     Request req(device->message_version());
236 
237     err = deserialize_request(msg, payload_size, req);
238     if (err != NO_ERROR)
239         return err;
240 
241     Response rsp = ((device->*operation)(req));
242     LOG_D("do_dispatch #2 err: %d", rsp.error);
243 
244     if (msg->cmd == KM_CONFIGURE) {
245         device->set_configure_error(rsp.error);
246     }
247 
248     err = serialize_response(rsp, out, out_size);
249     LOG_D("do_dispatch #2: serialized response, %d bytes", *out_size);
250     if (err != NO_ERROR) {
251         LOG_E("Error serializing response: %ld", err);
252     }
253 
254     return err;
255 }
256 
257 /* Keymaster is migrating to new API signatures.
258  * This overloaded dispatch is used for methods that do not have arguments
259  * and return a Response (e.g. GET_HMAC_SHARING_PARAMETERS)
260  * */
261 template <typename Keymaster, typename Response>
do_dispatch(Response (Keymaster::* operation)(),struct keymaster_message * msg,uint32_t payload_size,keymaster::UniquePtr<uint8_t[]> * out,uint32_t * out_size)262 static long do_dispatch(Response (Keymaster::*operation)(),
263                         struct keymaster_message* msg,
264                         uint32_t payload_size,
265                         keymaster::UniquePtr<uint8_t[]>* out,
266                         uint32_t* out_size) {
267     long err;
268     Response rsp = ((device->*operation)());
269     LOG_D("do_dispatch #3 err: %d", rsp.error);
270 
271     if (msg->cmd == KM_CONFIGURE) {
272         device->set_configure_error(rsp.error);
273     }
274 
275     err = serialize_response(rsp, out, out_size);
276     LOG_D("do_dispatch #3: serialized response, %d bytes", *out_size);
277     if (err != NO_ERROR) {
278         LOG_E("Error serializing response: %ld", err);
279     }
280 
281     return err;
282 }
283 
get_auth_token_key(keymaster::UniquePtr<uint8_t[]> * key_buf,uint32_t * key_size)284 static long get_auth_token_key(keymaster::UniquePtr<uint8_t[]>* key_buf,
285                                uint32_t* key_size) {
286     keymaster_key_blob_t key;
287     long rc = device->GetAuthTokenKey(&key);
288 
289     if (rc != NO_ERROR) {
290         return rc;
291     }
292 
293     if (key.key_material_size > KEYMASTER_MAX_BUFFER_LENGTH) {
294         return ERR_NOT_ENOUGH_BUFFER;
295     }
296 
297     key_buf->reset(new (std::nothrow) uint8_t[key.key_material_size]);
298     if (key_buf->get() == NULL) {
299         return ERR_NO_MEMORY;
300     }
301 
302     *key_size = key.key_material_size;
303 
304     memcpy(key_buf->get(), key.key_material, key.key_material_size);
305     return NO_ERROR;
306 }
307 
get_device_info(keymaster::UniquePtr<uint8_t[]> * ids_buf,uint32_t * buf_size)308 static long get_device_info(keymaster::UniquePtr<uint8_t[]>* ids_buf,
309                             uint32_t* buf_size) {
310     auto ids = device->GetDeviceInfo();
311 
312     if (ids->encodedSize() > KEYMASTER_MAX_BUFFER_LENGTH) {
313         return ERR_NOT_ENOUGH_BUFFER;
314     }
315 
316     ids_buf->reset(new (std::nothrow) uint8_t[ids->encodedSize()]);
317     if (ids_buf->get() == NULL) {
318         return ERR_NO_MEMORY;
319     }
320 
321     *buf_size = ids->encodedSize();
322     ids->encode(ids_buf->get(), ids_buf->get() + ids->encodedSize());
323     return NO_ERROR;
324 }
325 
keymaster_dispatch_secure(keymaster_chan_ctx * ctx,keymaster_message * msg,uint32_t payload_size,keymaster::UniquePtr<uint8_t[]> * out,uint32_t * out_size)326 static long keymaster_dispatch_secure(keymaster_chan_ctx* ctx,
327                                       keymaster_message* msg,
328                                       uint32_t payload_size,
329                                       keymaster::UniquePtr<uint8_t[]>* out,
330                                       uint32_t* out_size) {
331     if (msg->cmd == KM_SET_ATTESTATION_IDS_SECURE &&
332         !keymaster_check_secure_target_access_policy_provisioning(&ctx->uuid)) {
333         LOG_E("Command %d by this UUID is not allowed\n", msg->cmd);
334         return ERR_ACCESS_DENIED;
335     }
336 
337     switch (msg->cmd) {
338     case KM_GET_AUTH_TOKEN_KEY:
339         return get_auth_token_key(out, out_size);
340     case KM_GET_DEVICE_INFO:
341         return get_device_info(out, out_size);
342     case KM_SET_ATTESTATION_IDS_SECURE:
343         LOG_D("Dispatching SET_ATTESTATION_IDS_SECURE, size %d", payload_size);
344         return do_dispatch(&TrustyKeymaster::SetAttestationIds, msg,
345                            payload_size, out, out_size);
346     default:
347         return ERR_NOT_IMPLEMENTED;
348     }
349 }
350 
system_state_provisioning_allowed_at_boot(void)351 static bool system_state_provisioning_allowed_at_boot(void) {
352     uint64_t value = system_state_get_flag_default(
353             SYSTEM_STATE_FLAG_PROVISIONING_ALLOWED,
354             SYSTEM_STATE_FLAG_PROVISIONING_ALLOWED_VALUE_NOT_ALLOWED);
355     return value == SYSTEM_STATE_FLAG_PROVISIONING_ALLOWED_VALUE_ALLOWED ||
356            value ==
357                    SYSTEM_STATE_FLAG_PROVISIONING_ALLOWED_VALUE_ALLOWED_AT_BOOT;
358 }
359 
provisioning_allowed(void)360 static bool provisioning_allowed(void) {
361     if (device->ConfigureCalled()) {
362         return system_state_provisioning_allowed();
363     } else {
364         return system_state_provisioning_allowed_at_boot();
365     }
366 }
367 
368 // Returns true if |cmd| is only allowed in provisioning mode
cmd_is_provisioning(uint32_t cmd)369 static bool cmd_is_provisioning(uint32_t cmd) {
370     return (cmd == KM_SET_ATTESTATION_KEY || cmd == KM_SET_ATTESTATION_IDS ||
371             cmd == KM_SET_ATTESTATION_IDS_KM3 ||
372             cmd == KM_APPEND_ATTESTATION_CERT_CHAIN ||
373             cmd == KM_CLEAR_ATTESTATION_CERT_CHAIN ||
374             cmd == KM_SET_WRAPPED_ATTESTATION_KEY);
375 }
376 
377 // Returns true if |cmd| is called from the bootloader
cmd_is_from_bootloader(uint32_t cmd)378 static bool cmd_is_from_bootloader(uint32_t cmd) {
379     return (cmd == KM_SET_BOOT_PARAMS || cmd == KM_ATAP_GET_CA_REQUEST ||
380             cmd == KM_ATAP_SET_CA_RESPONSE_BEGIN ||
381             cmd == KM_ATAP_SET_CA_RESPONSE_UPDATE ||
382             cmd == KM_ATAP_SET_CA_RESPONSE_FINISH || cmd == KM_ATAP_READ_UUID ||
383             cmd == KM_SET_PRODUCT_ID || cmd == KM_CONFIGURE_BOOT_PATCHLEVEL);
384 }
385 
386 // Returns true if |cmd| can be used before the configure command
cmd_allowed_before_configure(uint32_t cmd)387 static bool cmd_allowed_before_configure(uint32_t cmd) {
388     return cmd == KM_CONFIGURE || cmd == KM_GET_VERSION ||
389            cmd_is_from_bootloader(cmd) || cmd_is_provisioning(cmd);
390 }
391 
keymaster_dispatch_non_secure(keymaster_chan_ctx * ctx,keymaster_message * msg,uint32_t payload_size,keymaster::UniquePtr<uint8_t[]> * out,uint32_t * out_size)392 static long keymaster_dispatch_non_secure(keymaster_chan_ctx* ctx,
393                                           keymaster_message* msg,
394                                           uint32_t payload_size,
395                                           keymaster::UniquePtr<uint8_t[]>* out,
396                                           uint32_t* out_size) {
397     if (msg->cmd == KM_GET_VERSION || msg->cmd == KM_GET_VERSION_2) {
398         // KM_GET_VERSION and KM_GET_VERSION_2 commands are always allowed
399     } else if (!device->ConfigureCalled()) {
400         if (!cmd_allowed_before_configure(msg->cmd)) {
401             LOG_E("Command %d not allowed before configure command\n",
402                   msg->cmd);
403             return ERR_NOT_CONFIGURED;
404         }
405     } else if (device->ConfigureCalled()) {
406         if (device->get_configure_error() != KM_ERROR_OK) {
407             LOG_E("Previous configure command failed\n");
408             return ERR_NOT_CONFIGURED;
409         } else if (cmd_is_from_bootloader(msg->cmd)) {
410             LOG_E("Bootloader command %d not allowed after configure command\n",
411                   msg->cmd);
412             return ERR_NOT_IMPLEMENTED;
413         }
414     }
415 
416     if (cmd_is_provisioning(msg->cmd) && !provisioning_allowed()) {
417         LOG_E("Provisioning command %d not allowed\n", msg->cmd);
418         return ERR_NOT_IMPLEMENTED;
419     }
420 
421     switch (static_cast<keymaster_command>(msg->cmd)) {
422     case KM_GENERATE_KEY:
423         LOG_D("Dispatching GENERATE_KEY, size: %d", payload_size);
424         return do_dispatch(&TrustyKeymaster::GenerateKey, msg, payload_size,
425                            out, out_size);
426 
427     case KM_BEGIN_OPERATION:
428         LOG_D("Dispatching BEGIN_OPERATION, size: %d", payload_size);
429         return do_dispatch(&TrustyKeymaster::BeginOperation, msg, payload_size,
430                            out, out_size);
431 
432     case KM_UPDATE_OPERATION:
433         LOG_D("Dispatching UPDATE_OPERATION, size: %d", payload_size);
434         return do_dispatch(&TrustyKeymaster::UpdateOperation, msg, payload_size,
435                            out, out_size);
436 
437     case KM_FINISH_OPERATION:
438         LOG_D("Dispatching FINISH_OPERATION, size: %d", payload_size);
439         return do_dispatch(&TrustyKeymaster::FinishOperation, msg, payload_size,
440                            out, out_size);
441 
442     case KM_IMPORT_KEY:
443         LOG_D("Dispatching IMPORT_KEY, size: %d", payload_size);
444         return do_dispatch(&TrustyKeymaster::ImportKey, msg, payload_size, out,
445                            out_size);
446 
447     case KM_EXPORT_KEY:
448         LOG_D("Dispatching EXPORT_KEY, size: %d", payload_size);
449         return do_dispatch(&TrustyKeymaster::ExportKey, msg, payload_size, out,
450                            out_size);
451 
452     case KM_GET_VERSION:
453         LOG_I("Dispatching GET_VERSION, size: %d", payload_size);
454         return do_dispatch(&TrustyKeymaster::GetVersion, msg, payload_size, out,
455                            out_size);
456 
457     case KM_GET_VERSION_2:
458         LOG_I("Dispatching GET_VERSION_2, size: %d", payload_size);
459         return do_dispatch(&TrustyKeymaster::GetVersion2, msg, payload_size,
460                            out, out_size);
461 
462     case KM_ADD_RNG_ENTROPY:
463         LOG_D("Dispatching ADD_RNG_ENTROPY, size: %d", payload_size);
464         return do_dispatch(&TrustyKeymaster::AddRngEntropy, msg, payload_size,
465                            out, out_size);
466 
467     case KM_GET_SUPPORTED_ALGORITHMS:
468         LOG_D("Dispatching GET_SUPPORTED_ALGORITHMS, size: %d", payload_size);
469         return do_dispatch(&TrustyKeymaster::SupportedAlgorithms, msg,
470                            payload_size, out, out_size);
471 
472     case KM_GET_SUPPORTED_BLOCK_MODES:
473         LOG_D("Dispatching GET_SUPPORTED_BLOCK_MODES, size: %d", payload_size);
474         return do_dispatch(&TrustyKeymaster::SupportedBlockModes, msg,
475                            payload_size, out, out_size);
476 
477     case KM_GET_SUPPORTED_PADDING_MODES:
478         LOG_D("Dispatching GET_SUPPORTED_PADDING_MODES, size: %d",
479               payload_size);
480         return do_dispatch(&TrustyKeymaster::SupportedPaddingModes, msg,
481                            payload_size, out, out_size);
482 
483     case KM_GET_SUPPORTED_DIGESTS:
484         LOG_D("Dispatching GET_SUPPORTED_DIGESTS, size: %d", payload_size);
485         return do_dispatch(&TrustyKeymaster::SupportedDigests, msg,
486                            payload_size, out, out_size);
487 
488     case KM_GET_SUPPORTED_IMPORT_FORMATS:
489         LOG_D("Dispatching GET_SUPPORTED_IMPORT_FORMATS, size: %d",
490               payload_size);
491         return do_dispatch(&TrustyKeymaster::SupportedImportFormats, msg,
492                            payload_size, out, out_size);
493 
494     case KM_GET_SUPPORTED_EXPORT_FORMATS:
495         LOG_D("Dispatching GET_SUPPORTED_EXPORT_FORMATS, size: %d",
496               payload_size);
497         return do_dispatch(&TrustyKeymaster::SupportedExportFormats, msg,
498                            payload_size, out, out_size);
499 
500     case KM_GET_KEY_CHARACTERISTICS:
501         LOG_D("Dispatching GET_KEY_CHARACTERISTICS, size: %d", payload_size);
502         return do_dispatch(&TrustyKeymaster::GetKeyCharacteristics, msg,
503                            payload_size, out, out_size);
504 
505     case KM_ABORT_OPERATION:
506         LOG_D("Dispatching ABORT_OPERATION, size %d", payload_size);
507         return do_dispatch(&TrustyKeymaster::AbortOperation, msg, payload_size,
508                            out, out_size);
509 
510     case KM_ATTEST_KEY:
511         LOG_D("Dispatching ATTEST_KEY, size %d", payload_size);
512         return do_dispatch(&TrustyKeymaster::AttestKey, msg, payload_size, out,
513                            out_size);
514 
515     case KM_UPGRADE_KEY:
516         LOG_D("Dispatching UPGRADE_KEY, size %d", payload_size);
517         return do_dispatch(&TrustyKeymaster::UpgradeKey, msg, payload_size, out,
518                            out_size);
519 
520     case KM_CONFIGURE:
521         LOG_D("Dispatching CONFIGURE, size %d", payload_size);
522         return do_dispatch(&TrustyKeymaster::Configure, msg, payload_size, out,
523                            out_size);
524 
525     case KM_GET_HMAC_SHARING_PARAMETERS:
526         LOG_D("Dispatching GET_HMAC_SHARING_PARAMETERS, size %d", payload_size);
527         return do_dispatch(&TrustyKeymaster::GetHmacSharingParameters, msg,
528                            payload_size, out, out_size);
529 
530     case KM_COMPUTE_SHARED_HMAC:
531         LOG_D("Dispatching COMPUTE_SHARED_HMAC, size %d", payload_size);
532         return do_dispatch(&TrustyKeymaster::ComputeSharedHmac, msg,
533                            payload_size, out, out_size);
534 
535     case KM_VERIFY_AUTHORIZATION:
536         LOG_D("Dispatching VERIFY_AUTHORIZATION, size %d", payload_size);
537         return do_dispatch(&TrustyKeymaster::VerifyAuthorization, msg,
538                            payload_size, out, out_size);
539 
540     case KM_IMPORT_WRAPPED_KEY:
541         LOG_D("Dispatching IMPORT_WRAPPED_KEY, size %d", payload_size);
542         return do_dispatch(&TrustyKeymaster::ImportWrappedKey, msg,
543                            payload_size, out, out_size);
544 
545     case KM_DELETE_KEY:
546         LOG_D("Dispatching DELETE_KEY, size %d", payload_size);
547         return do_dispatch(&TrustyKeymaster::DeleteKey, msg, payload_size, out,
548                            out_size);
549 
550     case KM_DELETE_ALL_KEYS:
551         LOG_D("Dispatching DELETE_ALL_KEYS, size %d", payload_size);
552         return do_dispatch(&TrustyKeymaster::DeleteAllKeys, msg, payload_size,
553                            out, out_size);
554 
555     case KM_SET_BOOT_PARAMS:
556         LOG_D("Dispatching SET_BOOT_PARAMS, size %d", payload_size);
557         return do_dispatch(&TrustyKeymaster::SetBootParams, msg, payload_size,
558                            out, out_size);
559 
560     case KM_SET_ATTESTATION_KEY:
561         LOG_D("Dispatching SET_ATTESTION_KEY, size %d", payload_size);
562         return do_dispatch(&TrustyKeymaster::SetAttestationKey, msg,
563                            payload_size, out, out_size);
564 
565     case KM_SET_ATTESTATION_IDS:
566         LOG_D("Dispatching SET_ATTESTATION_IDS, size %d", payload_size);
567         return do_dispatch(&TrustyKeymaster::SetAttestationIds, msg,
568                            payload_size, out, out_size);
569 
570     case KM_SET_ATTESTATION_IDS_KM3:
571         LOG_D("Dispatching SET_ATTESTATION_IDS_KM3, size %d", payload_size);
572         return do_dispatch(&TrustyKeymaster::SetAttestationIdsKM3, msg,
573                            payload_size, out, out_size);
574 
575     case KM_APPEND_ATTESTATION_CERT_CHAIN:
576         LOG_D("Dispatching SET_ATTESTATION_CERT_CHAIN, size %d", payload_size);
577         return do_dispatch(&TrustyKeymaster::AppendAttestationCertChain, msg,
578                            payload_size, out, out_size);
579 
580     case KM_ATAP_GET_CA_REQUEST:
581         LOG_D("Dispatching KM_ATAP_GET_CA_REQUEST, size %d", payload_size);
582         return do_dispatch(&TrustyKeymaster::AtapGetCaRequest, msg,
583                            payload_size, out, out_size);
584 
585     case KM_ATAP_SET_CA_RESPONSE_BEGIN:
586         LOG_D("Dispatching KM_ATAP_SET_CA_RESPONSE_BEGIN, size %d",
587               payload_size);
588         return do_dispatch(&TrustyKeymaster::AtapSetCaResponseBegin, msg,
589                            payload_size, out, out_size);
590 
591     case KM_ATAP_SET_CA_RESPONSE_UPDATE:
592         LOG_D("Dispatching KM_ATAP_SET_CA_RESPONSE_UPDATE, size %d",
593               payload_size);
594         return do_dispatch(&TrustyKeymaster::AtapSetCaResponseUpdate, msg,
595                            payload_size, out, out_size);
596 
597     case KM_ATAP_SET_CA_RESPONSE_FINISH:
598         LOG_D("Dispatching KM_ATAP_SET_CA_RESPONSE_FINISH, size %d",
599               payload_size);
600         return do_dispatch(&TrustyKeymaster::AtapSetCaResponseFinish, msg,
601                            payload_size, out, out_size);
602 
603     case KM_ATAP_READ_UUID:
604         LOG_D("Dispatching KM_ATAP_READ_UUID, size %d", payload_size);
605         return do_dispatch(&TrustyKeymaster::AtapReadUuid, msg, payload_size,
606                            out, out_size);
607 
608     case KM_SET_PRODUCT_ID:
609         LOG_D("Dispatching KM_SET_PRODUCT_ID, size %d", payload_size);
610         return do_dispatch(&TrustyKeymaster::AtapSetProductId, msg,
611                            payload_size, out, out_size);
612 
613     case KM_CLEAR_ATTESTATION_CERT_CHAIN:
614         LOG_D("Dispatching KM_CLEAR_ATTESTATION_CERT_CHAIN, size %d",
615               payload_size);
616         return do_dispatch(&TrustyKeymaster::ClearAttestationCertChain, msg,
617                            payload_size, out, out_size);
618 
619     case KM_SET_WRAPPED_ATTESTATION_KEY:
620         LOG_D("Dispatching KM_SET_WRAPPED_ATTESTATION_KEY, size %d",
621               payload_size);
622         return do_dispatch(&TrustyKeymaster::SetWrappedAttestationKey, msg,
623                            payload_size, out, out_size);
624 
625     case KM_DESTROY_ATTESTATION_IDS:
626         LOG_E("Dispatching destroy attestation IDs, size %d", payload_size);
627         return do_dispatch(&TrustyKeymaster::DestroyAttestationIds, msg,
628                            payload_size, out, out_size);
629 
630     case KM_EARLY_BOOT_ENDED:
631         LOG_D("Dispatching KM_EARLY_BOOT_ENDED, size %d", payload_size);
632         return do_dispatch(&TrustyKeymaster::EarlyBootEnded, msg, payload_size,
633                            out, out_size);
634 
635     case KM_DEVICE_LOCKED:
636         LOG_D("Dispatching KM_DEVICE_LOCKED, size %d", payload_size);
637         return do_dispatch(&TrustyKeymaster::DeviceLocked, msg, payload_size,
638                            out, out_size);
639 
640     case KM_GENERATE_RKP_KEY:
641         LOG_D("Dispatching KM_GENERATE_RKP_KEY, size %d", payload_size);
642         return do_dispatch(&TrustyKeymaster::GenerateRkpKey, msg, payload_size,
643                            out, out_size);
644 
645     case KM_GENERATE_CSR:
646         LOG_D("Dispatching KM_GENERATE_CSR, size %d", payload_size);
647         return do_dispatch(&TrustyKeymaster::GenerateCsr, msg, payload_size,
648                            out, out_size);
649 
650     case KM_GENERATE_CSR_V2:
651         LOG_D("Dispatching KM_GENERATE_CSR_V2, size %d", payload_size);
652         return do_dispatch(&TrustyKeymaster::GenerateCsrV2, msg, payload_size,
653                            out, out_size);
654 
655     case KM_CONFIGURE_VENDOR_PATCHLEVEL:
656         LOG_D("Dispatching KM_CONFIGURE_VENDOR_PATCHLEVEL, size %d",
657               payload_size);
658         return do_dispatch(&TrustyKeymaster::ConfigureVendorPatchlevel, msg,
659                            payload_size, out, out_size);
660 
661     case KM_CONFIGURE_BOOT_PATCHLEVEL:
662         LOG_D("Dispatching KM_CONFIGURE_BOOT_PATCHLEVEL, size %d",
663               payload_size);
664         return do_dispatch(&TrustyKeymaster::ConfigureBootPatchlevel, msg,
665                            payload_size, out, out_size);
666 
667     case KM_GET_ROOT_OF_TRUST:
668         LOG_D("Dispatching KM_GET_ROOT_OF_TRUST, size %d", payload_size);
669         return do_dispatch(&TrustyKeymaster::GetRootOfTrust, msg, payload_size,
670                            out, out_size);
671 
672     case KM_GET_HW_INFO:
673         LOG_D("Dispatching KM_GET_HW_INFO, size %d", payload_size);
674         return do_dispatch(&TrustyKeymaster::GetHwInfo, msg, payload_size, out,
675                            out_size);
676     }
677 
678     LOG_E("Cannot dispatch unknown command %d", msg->cmd);
679     return ERR_NOT_IMPLEMENTED;
680 }
681 
keymaster_port_accessible(uuid_t * uuid,bool secure)682 static bool keymaster_port_accessible(uuid_t* uuid, bool secure) {
683     return !secure || keymaster_check_target_access_policy(uuid);
684 }
685 
keymaster_ctx_open(handle_t chan,uuid_t * uuid,bool secure)686 static keymaster_chan_ctx* keymaster_ctx_open(handle_t chan,
687                                               uuid_t* uuid,
688                                               bool secure) {
689     if (!keymaster_port_accessible(uuid, secure)) {
690         LOG_E("access denied for client uuid");
691         return NULL;
692     }
693 
694     keymaster_chan_ctx* ctx = new (std::nothrow) keymaster_chan_ctx;
695     if (ctx == NULL) {
696         return ctx;
697     }
698 
699     ctx->handler.proc = &keymaster_chan_handler;
700     ctx->handler.priv = ctx;
701     ctx->uuid = *uuid;
702     ctx->chan = chan;
703     ctx->dispatch = secure ? &keymaster_dispatch_secure
704                            : &keymaster_dispatch_non_secure;
705     return ctx;
706 }
707 
keymaster_ctx_close(keymaster_chan_ctx * ctx)708 static void keymaster_ctx_close(keymaster_chan_ctx* ctx) {
709     close(ctx->chan);
710     delete ctx;
711 }
712 
handle_msg(keymaster_chan_ctx * ctx)713 static long handle_msg(keymaster_chan_ctx* ctx) {
714     handle_t chan = ctx->chan;
715 
716     /* get message info */
717     ipc_msg_info_t msg_inf;
718     int rc = get_msg(chan, &msg_inf);
719     if (rc == ERR_NO_MSG)
720         return NO_ERROR; /* no new messages */
721 
722     // fatal error
723     if (rc != NO_ERROR) {
724         LOG_E("failed (%d) to get_msg for chan (%d), closing connection", rc,
725               chan);
726         return rc;
727     }
728 
729     // allocate msg_buf, with one extra byte for null-terminator
730     keymaster::UniquePtr<uint8_t[]> msg_buf(new (std::nothrow)
731                                                     uint8_t[msg_inf.len + 1]);
732     if (msg_buf.get() == nullptr) {
733         return ERR_NO_MEMORY;
734     }
735     msg_buf[msg_inf.len] = 0;
736 
737     /* read msg content */
738     struct iovec iov = {msg_buf.get(), msg_inf.len};
739     ipc_msg_t msg = {1, &iov, 0, NULL};
740 
741     rc = read_msg(chan, msg_inf.id, 0, &msg);
742 
743     // retire the message (note msg_inf.id becomes invalid after put_msg)
744     put_msg(chan, msg_inf.id);
745 
746     // fatal error
747     if (rc < 0) {
748         LOG_E("failed to read msg (%d)", rc);
749         return rc;
750     }
751     LOG_D("Read %d-byte message", rc);
752 
753     if (((unsigned long)rc) < sizeof(keymaster_message)) {
754         LOG_E("invalid message of size (%d)", rc);
755         return ERR_NOT_VALID;
756     }
757 
758     keymaster::UniquePtr<uint8_t[]> out_buf;
759     uint32_t out_buf_size = 0;
760     keymaster_message* in_msg =
761             reinterpret_cast<keymaster_message*>(msg_buf.get());
762 
763     rc = ctx->dispatch(ctx, in_msg, msg_inf.len - sizeof(*in_msg), &out_buf,
764                        &out_buf_size);
765     if (rc == ERR_NOT_CONFIGURED) {
766         LOG_E("configure error (%d)", rc);
767         return send_error_response(chan, in_msg->cmd,
768                                    device->get_configure_error());
769     } else if (rc < 0) {
770         LOG_E("error handling message (%d)", rc);
771         return send_error_response(chan, in_msg->cmd, KM_ERROR_UNKNOWN_ERROR);
772     }
773 
774     LOG_D("Sending %d-byte response", out_buf_size);
775     return send_response(chan, in_msg->cmd, out_buf.get(), out_buf_size);
776 }
777 
keymaster_chan_handler(const uevent_t * ev,void * priv)778 static void keymaster_chan_handler(const uevent_t* ev, void* priv) {
779     keymaster_chan_ctx* ctx = reinterpret_cast<keymaster_chan_ctx*>(priv);
780     if (ctx == NULL) {
781         LOG_E("error: no context on channel %d", ev->handle);
782         close(ev->handle);
783         return;
784     }
785 
786     if ((ev->event & IPC_HANDLE_POLL_ERROR) ||
787         (ev->event & IPC_HANDLE_POLL_READY)) {
788         /* close it as it is in an error state */
789         LOG_E("error event (0x%x) for chan (%d)", ev->event, ev->handle);
790         close(ev->handle);
791         return;
792     }
793 
794     if (ev->event & IPC_HANDLE_POLL_MSG) {
795         long rc = handle_msg(ctx);
796         if (rc != NO_ERROR) {
797             /* report an error and close channel */
798             LOG_E("failed (%ld) to handle event on channel %d", rc, ev->handle);
799             keymaster_ctx_close(ctx);
800             return;
801         }
802     }
803 
804     if (ev->event & IPC_HANDLE_POLL_HUP) {
805         /* closed by peer. */
806         keymaster_ctx_close(ctx);
807         return;
808     }
809 }
810 
keymaster_port_handler(const uevent_t * ev,void * priv,bool secure)811 static void keymaster_port_handler(const uevent_t* ev,
812                                    void* priv,
813                                    bool secure) {
814     long rc = handle_port_errors(ev);
815     if (rc != NO_ERROR) {
816         abort();
817     }
818 
819     uuid_t peer_uuid;
820     if (ev->event & IPC_HANDLE_POLL_READY) {
821         /* incoming connection: accept it */
822         int rc = accept(ev->handle, &peer_uuid);
823         if (rc < 0) {
824             LOG_E("failed (%d) to accept on port %d", rc, ev->handle);
825             return;
826         }
827 
828         handle_t chan = (handle_t)rc;
829         keymaster_chan_ctx* ctx = keymaster_ctx_open(chan, &peer_uuid, secure);
830         if (ctx == NULL) {
831             LOG_E("failed to allocate context on chan %d", chan);
832             close(chan);
833             return;
834         }
835 
836         rc = set_cookie(chan, ctx);
837         if (rc < 0) {
838             LOG_E("failed (%d) to set_cookie on chan %d", rc, chan);
839             keymaster_ctx_close(ctx);
840             return;
841         }
842     }
843 }
844 
keymaster_port_handler_secure(const uevent_t * ev,void * priv)845 static void keymaster_port_handler_secure(const uevent_t* ev, void* priv) {
846     keymaster_port_handler(ev, priv, true);
847 }
848 
keymaster_port_handler_non_secure(const uevent_t * ev,void * priv)849 static void keymaster_port_handler_non_secure(const uevent_t* ev, void* priv) {
850     keymaster_port_handler(ev, priv, false);
851 }
852 
dispatch_event(const uevent_t * ev)853 static void dispatch_event(const uevent_t* ev) {
854     if (ev == NULL)
855         return;
856 
857     if (ev->event == IPC_HANDLE_POLL_NONE) {
858         /* not really an event, do nothing */
859         LOG_E("got an empty event");
860         return;
861     }
862 
863     /* check if we have handler */
864     tipc_event_handler* handler =
865             reinterpret_cast<tipc_event_handler*>(ev->cookie);
866     if (handler && handler->proc) {
867         /* invoke it */
868         handler->proc(ev, handler->priv);
869         return;
870     }
871 
872     /* no handler? close it */
873     LOG_E("no handler for event (0x%x) with handle %d", ev->event, ev->handle);
874 
875     close(ev->handle);
876 
877     return;
878 }
879 
keymaster_ipc_init(keymaster_srv_ctx * ctx)880 static long keymaster_ipc_init(keymaster_srv_ctx* ctx) {
881     int rc;
882 
883     /* Initialize secure-side service */
884     rc = port_create(KEYMASTER_SECURE_PORT, 1, KEYMASTER_MAX_BUFFER_LENGTH,
885                      IPC_PORT_ALLOW_TA_CONNECT);
886     if (rc < 0) {
887         LOG_E("Failed (%d) to create port %s", rc, KEYMASTER_SECURE_PORT);
888         return rc;
889     }
890 
891     ctx->port_secure = (handle_t)rc;
892 
893     rc = set_cookie(ctx->port_secure, &keymaster_port_evt_handler_secure);
894     if (rc) {
895         LOG_E("failed (%d) to set_cookie on port %d", rc, ctx->port_secure);
896         close(ctx->port_secure);
897         return rc;
898     }
899 
900     /* initialize non-secure side service */
901     rc = port_create(KEYMASTER_PORT, 1, KEYMASTER_MAX_BUFFER_LENGTH,
902                      IPC_PORT_ALLOW_NS_CONNECT);
903     if (rc < 0) {
904         LOG_E("Failed (%d) to create port %s", rc, KEYMASTER_PORT);
905         return rc;
906     }
907 
908     ctx->port_non_secure = (handle_t)rc;
909 
910     rc = set_cookie(ctx->port_non_secure,
911                     &keymaster_port_evt_handler_non_secure);
912     if (rc) {
913         LOG_E("failed (%d) to set_cookie on port %d", rc, ctx->port_non_secure);
914         close(ctx->port_non_secure);
915         return rc;
916     }
917 
918     return NO_ERROR;
919 }
920 
main(void)921 int main(void) {
922     long rc;
923     uevent_t event;
924 
925     device = new (std::nothrow)
926             TrustyKeymaster(new (std::nothrow) TrustyKeymasterContext, 16);
927 
928     TrustyLogger::initialize();
929 
930     LOG_I("Initializing");
931 
932     // Run the BoringSSL self-tests
933     if (!BORINGSSL_self_test()) {
934         LOG_E("BoringSSL self-test: FAILED");
935         return ERR_GENERIC;
936     } else {
937         LOG_I("BoringSSL self-test: PASSED");
938     }
939 
940     keymaster_srv_ctx ctx;
941     rc = keymaster_ipc_init(&ctx);
942     if (rc < 0) {
943         LOG_E("failed (%ld) to initialize keymaster", rc);
944         return rc;
945     }
946 
947     /* enter main event loop */
948     while (true) {
949         event.handle = INVALID_IPC_HANDLE;
950         event.event = 0;
951         event.cookie = NULL;
952 
953         rc = wait_any(&event, INFINITE_TIME);
954         if (rc < 0) {
955             LOG_E("wait_any failed (%ld)", rc);
956             break;
957         }
958 
959         if (rc == NO_ERROR) { /* got an event */
960             dispatch_event(&event);
961         }
962     }
963 
964     return 0;
965 }
966