1 /*
2  * Copyright 2017 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 #ifndef TRUSTY_APP_KEYMASTER_ACCESS_STORAGE_H_
18 #define TRUSTY_APP_KEYMASTER_ACCESS_STORAGE_H_
19 
20 #include <keymaster/UniquePtr.h>
21 #include <keymaster/android_keymaster_utils.h>
22 #include <lib/storage/storage.h>
23 
24 extern "C" {
25 #include <hardware/keymaster_defs.h>
26 }
27 #include "keymaster_attributes.pb.h"
28 #include "trusty_keymaster_messages.h"
29 
30 namespace keymaster {
31 
32 /* The uuid size matches, by design, ATAP_HEX_UUID_LEN in
33  * system/iot/attestation/atap. */
34 static const size_t kAttestationUuidSize = 32;
35 /* ATAP_PRODUCT_ID_LEN in system/iot/attestation/atap. */
36 static const size_t kProductIdSize = 16;
37 
38 static const int kMaxCertChainLength = 3;
39 
40 // RSA and ECDSA are set to be the same as keymaster_algorithm_t.
41 enum class AttestationKeySlot {
42     kInvalid = 0,
43     kRsa = 1,
44     kEcdsa = 3,
45     kEddsa = 4,
46     kEpid = 5,
47     // 'Claimable slots are for use with the claim_key HAL method.
48     kClaimable0 = 128,
49     // 'Som' slots are for Android Things SoM keys. These are generic, that is
50     // they are not associated with a particular model or product.
51     kSomRsa = 257,
52     kSomEcdsa = 259,
53     kSomEddsa = 260,
54     kSomEpid = 261,
55 };
56 
57 struct Certificate {
58     uint32_t cert_size;
59     UniquePtr<uint8_t[]> cert_data;
60 };
61 
62 class SecureStorageManager {
63 public:
64     /**
65      * Get a SecureStorageManager instance. The instance returned is shared with
66      * all other callers, so it is not safe to call any api that does not commit
67      * the transaction and then let other clients use the api. get_instance will
68      * also discard any previous transaction to detect if the session is still
69      * alive, and to make the starting state more predictable.
70      */
71     static SecureStorageManager* get_instance(bool translate_format = true);
72 
73     /**
74      * These functions implement key and certificate chain storage on top
75      * Trusty's secure storage service. All data is stored in the RPMB
76      * filesystem.
77      */
78 
79     /**
80      * Writes |key_size| bytes at |key| to key/cert file associated with
81      * |key_slot|.
82      */
83     keymaster_error_t WriteKeyToStorage(AttestationKeySlot key_slot,
84                                         const uint8_t* key,
85                                         uint32_t key_size);
86 
87     /**
88      * Reads key associated with |key_slot|.
89      */
90     KeymasterKeyBlob ReadKeyFromStorage(AttestationKeySlot key_slot,
91                                         keymaster_error_t* error);
92 
93     /**
94      * Checks if |key_slot| attestation key exists in RPMB. On success, writes
95      * to |exists|.
96      */
97     keymaster_error_t AttestationKeyExists(AttestationKeySlot key_slot,
98                                            bool* exists);
99 
100     /**
101      * Writes |cert_size| bytes at |cert| to key/cert file associated with
102      * |key_slot| and |index|. The caller can either write to an exising
103      * certificate entry, or one past the end of the chain to extend the chain
104      * length by 1 (|index| = chain length). Fails when |index| > chain length.
105      */
106     keymaster_error_t WriteCertToStorage(AttestationKeySlot key_slot,
107                                          const uint8_t* cert,
108                                          uint32_t cert_size,
109                                          uint32_t index);
110 
111     /**
112      * Reads cert chain associated with |key_slot|. Stores certificate chain in
113      * |cert_chain| and caller takes ownership of all allocated memory.
114      */
115     keymaster_error_t ReadCertChainFromStorage(
116             AttestationKeySlot key_slot,
117             keymaster_cert_chain_t* cert_chain);
118 
119     /**
120      * Delete cert chain associated with |key_slot|.
121      */
122     keymaster_error_t DeleteCertChainFromStorage(AttestationKeySlot key_slot);
123 
124     /*
125      * Writes the new length of the stored |key_slot| attestation certificate
126      * chain. If less than the existing certificate chain length, the chain is
127      * truncated. Input cannot be larger than the current certificate chain
128      * length + 1.
129      */
130     keymaster_error_t WriteCertChainLength(AttestationKeySlot key_slot,
131                                            uint32_t cert_chain_length);
132 
133     /**
134      * Reads the current length of the stored |key_slot| attestation certificate
135      * chain. On success, writes the length to |cert_chain_length|.
136      */
137     keymaster_error_t ReadCertChainLength(AttestationKeySlot key_slot,
138                                           uint32_t* cert_chain_length);
139 
140     /**
141      * Writes the |attestation_uuid|.
142      */
143     keymaster_error_t WriteAttestationUuid(
144             const uint8_t attestation_uuid[kAttestationUuidSize]);
145 
146     /**
147      * Reads the |attestation_uuid|. If none exists, sets the uuid to all ascii
148      * zeros.
149      */
150     keymaster_error_t ReadAttestationUuid(
151             uint8_t attestation_uuid[kAttestationUuidSize]);
152 
153     /**
154      * Delete the |attestation_uuid|. This function is for test only.
155      */
156     keymaster_error_t DeleteAttestationUuid();
157 
158     /**
159      * Read the |product_id|. If none exists, sets it to all zeros.
160      */
161     keymaster_error_t ReadProductId(uint8_t product_id[kProductIdSize]);
162 
163     /**
164      * Set the |product_id|.
165      */
166     keymaster_error_t SetProductId(const uint8_t product_id[kProductIdSize]);
167 
168     /**
169      * Clear all attestation IDs for the device.
170      */
171     keymaster_error_t ClearAttestationIds();
172 
173     /**
174      * Set the attestation IDs for the device. This function can only be used
175      * once unless Keymaster is in debug mode.
176      */
177     keymaster_error_t SetAttestationIds(
178             const SetAttestationIdsRequest& request);
179 
180     /**
181      * Reads the attestations IDs for the device.
182      */
183     keymaster_error_t ReadAttestationIds(AttestationIds* attestation_ids_p);
184 
185     /* Sets the KeyMint3 Attestation IDs for the device. This function can only
186      * be used once unless Keymaster is in debug mode.
187      */
188     keymaster_error_t SetAttestationIdsKM3(
189             const SetAttestationIdsKM3Request& request);
190 
191     /**
192      * Delete the |product_id|.
193      */
194     keymaster_error_t DeleteProductId();
195 
196     /**
197      * Deletes |key_slot| attestation key and associated cert chain from RPMB.
198      */
199     keymaster_error_t DeleteKey(AttestationKeySlot key_slot, bool commit);
200 
201     /**
202      * Delete all attestation keys and certificate chains from RPMB.
203      */
204     keymaster_error_t DeleteAllAttestationData();
205 
206 #ifdef KEYMASTER_LEGACY_FORMAT
207 
208     /**
209      * Deprecated, for unit tests only.
210      */
211     keymaster_error_t LegacyWriteKeyToStorage(AttestationKeySlot key_slot,
212                                               const uint8_t* key,
213                                               uint32_t key_size);
214     /**
215      * Deprecated, for unit tests only.
216      */
217     keymaster_error_t LegacyWriteCertToStorage(AttestationKeySlot key_slot,
218                                                const uint8_t* cert,
219                                                uint32_t cert_size,
220                                                uint32_t index);
221     /**
222      * Deprecated, for unit tests only.
223      */
224     keymaster_error_t LegacyWriteAttestationUuid(
225             const uint8_t attestation_uuid[kAttestationUuidSize]);
226     /**
227      * Deprecated, for unit tests only.
228      */
229     keymaster_error_t LegacySetProductId(
230             const uint8_t product_id[kProductIdSize]);
231 #endif  // #define KEYMASTER_LEGACY_FORMAT
232 
233 private:
234     bool SecureStorageGetFileSize(const char* filename, uint64_t* size);
235     bool SecureStorageDeleteFile(const char* filename);
236     keymaster_error_t ReadKeymasterAttributes(
237             KeymasterAttributes** km_attributes_p);
238     keymaster_error_t WriteKeymasterAttributes(
239             const KeymasterAttributes* km_attributes,
240             bool commit);
241     keymaster_error_t WriteAttestationIds(const AttestationIds* attestation_ids,
242                                           bool commit);
243     keymaster_error_t ReadAttestationKey(AttestationKeySlot key_slot,
244                                          AttestationKey** attestation_key_p);
245     keymaster_error_t WriteAttestationKey(AttestationKeySlot key_slot,
246                                           const AttestationKey* attestation_key,
247                                           bool commit);
248     keymaster_error_t EncodeToFile(const pb_field_t fields[],
249                                    const void* dest_struct,
250                                    const char filename[],
251                                    bool commit);
252     keymaster_error_t DecodeFromFile(const pb_field_t fields[],
253                                      void* dest_struct,
254                                      const char filename[]);
255     /**
256      * Translate file format from key/cert per file to new protobuf format.
257      */
258     keymaster_error_t TranslateLegacyFormat();
259 
260     int StorageOpenSession(const char* type);
261     void CloseSession();
262 
263     SecureStorageManager();
264     ~SecureStorageManager();
265     storage_session_t session_handle_;
266 
267 #ifdef KEYMASTER_LEGACY_FORMAT
268     keymaster_error_t LegacySecureStorageRead(const char* filename,
269                                               void* data,
270                                               uint32_t* size,
271                                               uint32_t max_size);
272     keymaster_error_t LegacySecureStorageWrite(const char* filename,
273                                                const uint8_t* data,
274                                                uint32_t data_size);
275     bool legacy_format = true;
276 #endif  // #define KEYMASTER_LEGACY_FORMAT
277 };
278 
279 }  // namespace keymaster
280 
281 #endif  // TRUSTY_APP_KEYMASTER_SECURE_STORAGE_H_
282