1 //
2 // Copyright (C) 2020 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #include "tpm_ffi.h"
17 
18 #include <android-base/logging.h>
19 
20 #include "host/commands/secure_env/tpm_hmac.h"
21 #include "host/commands/secure_env/tpm_resource_manager.h"
22 
23 using cuttlefish::TpmResourceManager;
24 
25 extern "C" {
26 
tpm_hmac(void * trm,const uint8_t * data,uint32_t data_len,uint8_t * tag,uint32_t tag_len)27 uint32_t tpm_hmac(void* trm, const uint8_t* data, uint32_t data_len,
28                   uint8_t* tag, uint32_t tag_len) {
29   if (trm == nullptr) {
30     LOG(ERROR) << "No TPM resource manager provided";
31     return 1;
32   }
33   TpmResourceManager* resource_manager =
34       reinterpret_cast<TpmResourceManager*>(trm);
35   auto hmac =
36       TpmHmacWithContext(*resource_manager, "TpmHmac_context", data, data_len);
37   if (!hmac) {
38     LOG(ERROR) << "Could not calculate HMAC";
39     return 1;
40   } else if (hmac->size != tag_len) {
41     LOG(ERROR) << "HMAC size of " << hmac->size
42                << " different than expected tag len " << tag_len;
43     return 1;
44   }
45   memcpy(tag, hmac->buffer, tag_len);
46   return 0;
47 }
48 
secure_env_log(const char * file,unsigned int line,int severity,const char * tag,const char * msg)49 void secure_env_log(const char* file, unsigned int line, int severity,
50                     const char* tag, const char* msg) {
51   android::base::LogSeverity severity_enum;
52   switch (severity) {
53     case 0:
54       severity_enum = android::base::LogSeverity::VERBOSE;
55       break;
56     case 1:
57       severity_enum = android::base::LogSeverity::DEBUG;
58       break;
59     case 2:
60       severity_enum = android::base::LogSeverity::INFO;
61       break;
62     case 3:
63       severity_enum = android::base::LogSeverity::WARNING;
64       break;
65     default:
66     case 4:
67       severity_enum = android::base::LogSeverity::ERROR;
68       break;
69     case 5:
70       severity_enum = android::base::LogSeverity::FATAL_WITHOUT_ABORT;
71       break;
72     case 6:
73       severity_enum = android::base::LogSeverity::FATAL;
74       break;
75   }
76   android::base::LogMessage::LogLine(file, line, severity_enum, tag, msg);
77 }
78 }
79