1 /*
2  * Copyright (C) 2016 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 #pragma once
18 
19 #include <android/hidl/token/1.0/ITokenManager.h>
20 #include <chrono>
21 #include <hidl/MQDescriptor.h>
22 #include <hidl/Status.h>
23 #include <unordered_map>
24 #include <array>
25 
26 namespace android {
27 namespace hidl {
28 namespace token {
29 namespace V1_0 {
30 namespace implementation {
31 
32 using ::android::hidl::base::V1_0::IBase;
33 using ::android::hidl::token::V1_0::ITokenManager;
34 using ::android::hardware::hidl_array;
35 using ::android::hardware::hidl_string;
36 using ::android::hardware::hidl_vec;
37 using ::android::hardware::Return;
38 using ::android::hardware::Void;
39 using ::android::sp;
40 
41 struct TokenManager : public ITokenManager {
42     TokenManager();
43 
44     // Methods from ::android::hidl::token::V1_0::ITokenManager follow.
45     Return<void> createToken(const sp<IBase>& store, createToken_cb hidl_cb) override;
46     Return<bool> unregister(const hidl_vec<uint8_t> &token) override;
47     Return<sp<IBase>> get(const hidl_vec<uint8_t> &token) override;
48 
49 private:
50     static constexpr uint64_t KEY_SIZE = 16;
51 
52     static constexpr uint64_t TOKEN_ID_NONE = 0;
53 
54     static bool constantTimeCompare(const hidl_vec<uint8_t> &t1, const hidl_vec<uint8_t> &t2);
55 
56     static hidl_vec<uint8_t> makeToken(const uint64_t id, const uint8_t *hmac, uint64_t hmacSize);
57     static uint64_t getTokenId(const hidl_vec<uint8_t> &token);
58 
59     std::array<uint8_t, KEY_SIZE> mKey;
60 
61     struct TokenInterface {
62         sp<IBase> interface;
63         uint64_t id;
64         hidl_vec<uint8_t> token; // First eight bytes are tokenId. Remaining bytes are hmac.
65     };
66 
67     TokenInterface generateToken(const sp<IBase> &interface);
68 
69     // verifies token, returns iterator into mMap
70     std::unordered_map<uint64_t, TokenInterface>::const_iterator
71             lookupToken(const hidl_vec<uint8_t> &token);
72 
73     std::unordered_map<uint64_t, TokenInterface> mMap; // map getTokenId(i.token) -> i
74     uint64_t mTokenIndex = TOKEN_ID_NONE; // last token index
75 };
76 
77 }  // namespace implementation
78 }  // namespace V1_0
79 }  // namespace token
80 }  // namespace hidl
81 }  // namespace android
82