1 /*
2  * Copyright (C) 2019 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 <android-base/file.h>
18 #include <android-base/logging.h>
19 #include <android-base/unique_fd.h>
20 
21 #include "HadamardUtils.h"
22 #include "rebootescrow-impl/RebootEscrow.h"
23 
24 namespace aidl {
25 namespace android {
26 namespace hardware {
27 namespace rebootescrow {
28 
29 using ::android::base::unique_fd;
30 
storeKey(const std::vector<uint8_t> & ukek)31 ndk::ScopedAStatus RebootEscrow::storeKey(const std::vector<uint8_t>& ukek) {
32     int rawFd = TEMP_FAILURE_RETRY(::open(devicePath_.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
33     unique_fd fd(rawFd);
34     if (fd.get() < 0) {
35         LOG(WARNING) << "Could not open reboot escrow device";
36         return ndk::ScopedAStatus(AStatus_fromExceptionCode(EX_UNSUPPORTED_OPERATION));
37     }
38 
39     auto encoded = hadamard::EncodeKey(ukek);
40 
41     if (!::android::base::WriteFully(fd, encoded.data(), encoded.size())) {
42         LOG(WARNING) << "Could not write data fully to character device";
43         return ndk::ScopedAStatus(AStatus_fromExceptionCode(EX_UNSUPPORTED_OPERATION));
44     }
45 
46     return ndk::ScopedAStatus::ok();
47 }
48 
retrieveKey(std::vector<uint8_t> * _aidl_return)49 ndk::ScopedAStatus RebootEscrow::retrieveKey(std::vector<uint8_t>* _aidl_return) {
50     int rawFd = TEMP_FAILURE_RETRY(::open(devicePath_.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
51     unique_fd fd(rawFd);
52     if (fd.get() < 0) {
53         LOG(WARNING) << "Could not open reboot escrow device";
54         return ndk::ScopedAStatus(AStatus_fromExceptionCode(EX_UNSUPPORTED_OPERATION));
55     }
56 
57     std::vector<uint8_t> encodedBytes(hadamard::OUTPUT_SIZE_BYTES);
58     if (!::android::base::ReadFully(fd, &encodedBytes[0], encodedBytes.size())) {
59         LOG(WARNING) << "Could not read device";
60         return ndk::ScopedAStatus(AStatus_fromExceptionCode(EX_UNSUPPORTED_OPERATION));
61     }
62 
63     auto keyBytes = hadamard::DecodeKey(encodedBytes);
64 
65     *_aidl_return = keyBytes;
66     return ndk::ScopedAStatus::ok();
67 }
68 
69 }  // namespace rebootescrow
70 }  // namespace hardware
71 }  // namespace android
72 }  // namespace aidl
73