• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #ifndef KEYSTORE_KEYSTORE_SERVICE_H_
18 #define KEYSTORE_KEYSTORE_SERVICE_H_
19 
20 #include <keystore/IKeystoreService.h>
21 
22 #include <keymaster/authorization_set.h>
23 
24 #include "auth_token_table.h"
25 #include "keystore.h"
26 #include "keystore_keymaster_enforcement.h"
27 #include "operation.h"
28 #include "permissions.h"
29 
30 namespace android {
31 
32 class KeyStoreService : public BnKeystoreService, public IBinder::DeathRecipient {
33   public:
KeyStoreService(KeyStore * keyStore)34     KeyStoreService(KeyStore* keyStore) : mKeyStore(keyStore), mOperationMap(this) {}
35 
36     void binderDied(const wp<IBinder>& who);
37 
38     int32_t getState(int32_t userId);
39 
40     int32_t get(const String16& name, int32_t uid, uint8_t** item, size_t* itemLength);
41     int32_t insert(const String16& name, const uint8_t* item, size_t itemLength, int targetUid,
42                    int32_t flags);
43     int32_t del(const String16& name, int targetUid);
44     int32_t exist(const String16& name, int targetUid);
45     int32_t list(const String16& prefix, int targetUid, Vector<String16>* matches);
46 
47     int32_t reset();
48 
49     int32_t onUserPasswordChanged(int32_t userId, const String16& password);
50     int32_t onUserAdded(int32_t userId, int32_t parentId);
51     int32_t onUserRemoved(int32_t userId);
52 
53     int32_t lock(int32_t userId);
54     int32_t unlock(int32_t userId, const String16& pw);
55 
56     bool isEmpty(int32_t userId);
57 
58     int32_t generate(const String16& name, int32_t targetUid, int32_t keyType, int32_t keySize,
59                      int32_t flags, Vector<sp<KeystoreArg>>* args);
60     int32_t import(const String16& name, const uint8_t* data, size_t length, int targetUid,
61                    int32_t flags);
62     int32_t sign(const String16& name, const uint8_t* data, size_t length, uint8_t** out,
63                  size_t* outLength);
64     int32_t verify(const String16& name, const uint8_t* data, size_t dataLength,
65                    const uint8_t* signature, size_t signatureLength);
66 
67     /*
68      * TODO: The abstraction between things stored in hardware and regular blobs
69      * of data stored on the filesystem should be moved down to keystore itself.
70      * Unfortunately the Java code that calls this has naming conventions that it
71      * knows about. Ideally keystore shouldn't be used to store random blobs of
72      * data.
73      *
74      * Until that happens, it's necessary to have a separate "get_pubkey" and
75      * "del_key" since the Java code doesn't really communicate what it's
76      * intentions are.
77      */
78     int32_t get_pubkey(const String16& name, uint8_t** pubkey, size_t* pubkeyLength);
79 
80     int32_t grant(const String16& name, int32_t granteeUid);
81     int32_t ungrant(const String16& name, int32_t granteeUid);
82 
83     int64_t getmtime(const String16& name, int32_t uid);
84 
85     int32_t duplicate(const String16& srcKey, int32_t srcUid, const String16& destKey,
86                       int32_t destUid);
87 
88     int32_t is_hardware_backed(const String16& keyType);
89 
90     int32_t clear_uid(int64_t targetUid64);
91 
92     int32_t addRngEntropy(const uint8_t* data, size_t dataLength);
93     int32_t generateKey(const String16& name, const KeymasterArguments& params,
94                         const uint8_t* entropy, size_t entropyLength, int uid, int flags,
95                         KeyCharacteristics* outCharacteristics);
96     int32_t getKeyCharacteristics(const String16& name, const keymaster_blob_t* clientId,
97                                   const keymaster_blob_t* appData, int32_t uid,
98                                   KeyCharacteristics* outCharacteristics);
99     int32_t importKey(const String16& name, const KeymasterArguments& params,
100                       keymaster_key_format_t format, const uint8_t* keyData, size_t keyLength,
101                       int uid, int flags, KeyCharacteristics* outCharacteristics);
102     void exportKey(const String16& name, keymaster_key_format_t format,
103                    const keymaster_blob_t* clientId, const keymaster_blob_t* appData, int32_t uid,
104                    ExportResult* result);
105     void begin(const sp<IBinder>& appToken, const String16& name, keymaster_purpose_t purpose,
106                bool pruneable, const KeymasterArguments& params, const uint8_t* entropy,
107                size_t entropyLength, int32_t uid, OperationResult* result);
108     void update(const sp<IBinder>& token, const KeymasterArguments& params, const uint8_t* data,
109                 size_t dataLength, OperationResult* result);
110     void finish(const sp<IBinder>& token, const KeymasterArguments& params,
111                 const uint8_t* signature, size_t signatureLength, const uint8_t* entropy,
112                 size_t entropyLength, OperationResult* result);
113     int32_t abort(const sp<IBinder>& token);
114 
115     bool isOperationAuthorized(const sp<IBinder>& token);
116 
117     int32_t addAuthToken(const uint8_t* token, size_t length);
118 
119     int32_t attestKey(const String16& name, const KeymasterArguments& params,
120                       KeymasterCertificateChain* outChain) override;
121 
122   private:
123     static const int32_t UID_SELF = -1;
124 
125     /**
126      * Prune the oldest pruneable operation.
127      */
128     bool pruneOperation();
129 
130     /**
131      * Get the effective target uid for a binder operation that takes an
132      * optional uid as the target.
133      */
134     uid_t getEffectiveUid(int32_t targetUid);
135 
136     /**
137      * Check if the caller of the current binder method has the required
138      * permission and if acting on other uids the grants to do so.
139      */
140     bool checkBinderPermission(perm_t permission, int32_t targetUid = UID_SELF);
141 
142     /**
143      * Check if the caller of the current binder method has the required
144      * permission and the target uid is the caller or the caller is system.
145      */
146     bool checkBinderPermissionSelfOrSystem(perm_t permission, int32_t targetUid);
147 
148     /**
149      * Check if the caller of the current binder method has the required
150      * permission or the target of the operation is the caller's uid. This is
151      * for operation where the permission is only for cross-uid activity and all
152      * uids are allowed to act on their own (ie: clearing all entries for a
153      * given uid).
154      */
155     bool checkBinderPermissionOrSelfTarget(perm_t permission, int32_t targetUid);
156 
157     /**
158      * Helper method to check that the caller has the required permission as
159      * well as the keystore is in the unlocked state if checkUnlocked is true.
160      *
161      * Returns NO_ERROR on success, PERMISSION_DENIED on a permission error and
162      * otherwise the state of keystore when not unlocked and checkUnlocked is
163      * true.
164      */
165     int32_t checkBinderPermissionAndKeystoreState(perm_t permission, int32_t targetUid = -1,
166                                                   bool checkUnlocked = true);
167 
168     bool isKeystoreUnlocked(State state);
169 
170     bool isKeyTypeSupported(const keymaster2_device_t* device, keymaster_keypair_t keyType);
171 
172     /**
173      * Check that all keymaster_key_param_t's provided by the application are
174      * allowed. Any parameter that keystore adds itself should be disallowed here.
175      */
176     bool checkAllowedOperationParams(const std::vector<keymaster_key_param_t>& params);
177 
178     keymaster_error_t getOperationCharacteristics(const keymaster_key_blob_t& key,
179                                                   const keymaster2_device_t* dev,
180                                                   const std::vector<keymaster_key_param_t>& params,
181                                                   keymaster_key_characteristics_t* out);
182 
183     /**
184      * Get the auth token for this operation from the auth token table.
185      *
186      * Returns ::NO_ERROR if the auth token was set or none was required.
187      *         ::OP_AUTH_NEEDED if it is a per op authorization, no
188      *         authorization token exists for that operation and
189      *         failOnTokenMissing is false.
190      *         KM_ERROR_KEY_USER_NOT_AUTHENTICATED if there is no valid auth
191      *         token for the operation
192      */
193     int32_t getAuthToken(const keymaster_key_characteristics_t* characteristics,
194                          keymaster_operation_handle_t handle, keymaster_purpose_t purpose,
195                          const hw_auth_token_t** authToken, bool failOnTokenMissing = true);
196 
197     void addAuthToParams(std::vector<keymaster_key_param_t>* params, const hw_auth_token_t* token);
198 
199     /**
200      * Add the auth token for the operation to the param list if the operation
201      * requires authorization. Uses the cached result in the OperationMap if available
202      * otherwise gets the token from the AuthTokenTable and caches the result.
203      *
204      * Returns ::NO_ERROR if the auth token was added or not needed.
205      *         KM_ERROR_KEY_USER_NOT_AUTHENTICATED if the operation is not
206      *         authenticated.
207      *         KM_ERROR_INVALID_OPERATION_HANDLE if token is not a valid
208      *         operation token.
209      */
210     int32_t addOperationAuthTokenIfNeeded(sp<IBinder> token,
211                                           std::vector<keymaster_key_param_t>* params);
212 
213     /**
214      * Translate a result value to a legacy return value. All keystore errors are
215      * preserved and keymaster errors become SYSTEM_ERRORs
216      */
217     int32_t translateResultToLegacyResult(int32_t result);
218 
219     keymaster_key_param_t* getKeyAlgorithm(keymaster_key_characteristics_t* characteristics);
220 
221     void addLegacyBeginParams(const String16& name, std::vector<keymaster_key_param_t>& params);
222 
223     int32_t doLegacySignVerify(const String16& name, const uint8_t* data, size_t length,
224                                uint8_t** out, size_t* outLength, const uint8_t* signature,
225                                size_t signatureLength, keymaster_purpose_t purpose);
226 
227     /**
228      * Upgrade a key blob under alias "name", returning the new blob in "blob".  If "blob"
229      * previously contained data, it will be overwritten.
230      *
231      * Returns ::NO_ERROR if the key was upgraded successfully.
232      *         KM_ERROR_VERSION_MISMATCH if called on a key whose patch level is greater than or
233      *         equal to the current system patch level.
234      */
235     int32_t upgradeKeyBlob(const String16& name, uid_t targetUid,
236                            const keymaster::AuthorizationSet& params, Blob* blob);
237 
238     ::KeyStore* mKeyStore;
239     OperationMap mOperationMap;
240     keymaster::AuthTokenTable mAuthTokenTable;
241     KeystoreKeymasterEnforcement enforcement_policy;
242 };
243 
244 };  // namespace android
245 
246 #endif  // KEYSTORE_KEYSTORE_SERVICE_H_
247