1 /*
2  * Copyright (C) 2014 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 ANDROID_LIBRARY_KEYMASTER_ENFORCEMENT_H
18 #define ANDROID_LIBRARY_KEYMASTER_ENFORCEMENT_H
19 
20 #include <array>
21 
22 #include <stdio.h>
23 
24 #include <keymaster/android_keymaster_messages.h>
25 #include <keymaster/authorization_set.h>
26 #include <keymaster/keymaster_utils.h>
27 
28 namespace keymaster {
29 
30 typedef uint64_t km_id_t;
31 
32 class KeymasterEnforcementContext {
33   public:
~KeymasterEnforcementContext()34     virtual ~KeymasterEnforcementContext() {}
35     /*
36      * Get current time.
37      */
38 };
39 
40 class AccessTimeMap;
41 class AccessCountMap;
42 struct HmacSharingParameters;
43 struct HmacSharingParametersArray;
44 
45 class KeymasterEnforcement {
46   public:
47     /**
48      * Construct a KeymasterEnforcement.
49      */
50     KeymasterEnforcement(uint32_t max_access_time_map_size, uint32_t max_access_count_map_size);
51     virtual ~KeymasterEnforcement();
52 
53     /**
54      * Iterates through the authorization set and returns the corresponding keymaster error. Will
55      * return KM_ERROR_OK if all criteria is met for the given purpose in the authorization set with
56      * the given operation params and handle. Used for encrypt, decrypt sign, and verify.
57      */
58     keymaster_error_t AuthorizeOperation(const keymaster_purpose_t purpose, const km_id_t keyid,
59                                          const AuthProxy& auth_set,
60                                          const AuthorizationSet& operation_params,
61                                          keymaster_operation_handle_t op_handle,
62                                          bool is_begin_operation);
63 
64     /**
65      * Iterates through the authorization set and returns the corresponding keymaster error. Will
66      * return KM_ERROR_OK if all criteria is met for the given purpose in the authorization set with
67      * the given operation params. Used for encrypt, decrypt sign, and verify.
68      */
69     keymaster_error_t AuthorizeBegin(const keymaster_purpose_t purpose, const km_id_t keyid,
70                                      const AuthProxy& auth_set,
71                                      const AuthorizationSet& operation_params);
72 
73     /**
74      * Iterates through the authorization set and returns the corresponding keymaster error. Will
75      * return KM_ERROR_OK if all criteria is met for the given purpose in the authorization set with
76      * the given operation params and handle. Used for encrypt, decrypt sign, and verify.
77      */
AuthorizeUpdate(const AuthProxy & auth_set,const AuthorizationSet & operation_params,keymaster_operation_handle_t op_handle)78     keymaster_error_t AuthorizeUpdate(const AuthProxy& auth_set,
79                                       const AuthorizationSet& operation_params,
80                                       keymaster_operation_handle_t op_handle) {
81         return AuthorizeUpdateOrFinish(auth_set, operation_params, op_handle);
82     }
83 
84     /**
85      * Iterates through the authorization set and returns the corresponding keymaster error. Will
86      * return KM_ERROR_OK if all criteria is met for the given purpose in the authorization set with
87      * the given operation params and handle. Used for encrypt, decrypt sign, and verify.
88      */
AuthorizeFinish(const AuthProxy & auth_set,const AuthorizationSet & operation_params,keymaster_operation_handle_t op_handle)89     keymaster_error_t AuthorizeFinish(const AuthProxy& auth_set,
90                                       const AuthorizationSet& operation_params,
91                                       keymaster_operation_handle_t op_handle) {
92         return AuthorizeUpdateOrFinish(auth_set, operation_params, op_handle);
93     }
94 
95     //
96     // Methods that must be implemented by subclasses
97     //
98     // The time-related methods address the fact that different enforcement contexts may have
99     // different time-related capabilities.  In particular:
100     //
101     // - They may or may not be able to check dates against real-world clocks.
102     //
103     // - They may or may not be able to check timestampls against authentication trustlets (minters
104     //   of hw_auth_token_t structs).
105     //
106     // - They must have some time source for relative times, but may not be able to provide more
107     //   than reliability and monotonicity.
108 
109     /*
110      * Returns true if the specified activation date has passed, or if activation cannot be
111      * enforced.
112      */
113     virtual bool activation_date_valid(uint64_t activation_date) const = 0;
114 
115     /*
116      * Returns true if the specified expiration date has passed.  Returns false if it has not, or if
117      * expiration cannot be enforced.
118      */
119     virtual bool expiration_date_passed(uint64_t expiration_date) const = 0;
120 
121     /*
122      * Returns true if the specified auth_token is older than the specified timeout.
123      */
124     virtual bool auth_token_timed_out(const hw_auth_token_t& token, uint32_t timeout) const = 0;
125 
126     /*
127      * Get current time in milliseconds from some starting point.  This value is used to compute
128      * relative times between events.  It must be monotonically increasing, and must not skip or
129      * lag.  It need not have any relation to any external time standard (other than the duration of
130      * "second").
131      *
132      * On Linux systems, it's recommended to use clock_gettime(CLOCK_BOOTTIME, ...) to implement
133      * this method.  On non-Linux POSIX systems, CLOCK_MONOTONIC is good, assuming the device does
134      * not suspend.
135      */
136     virtual uint64_t get_current_time_ms() const = 0;
137 
138     /*
139      * Get whether or not we're in early boot.  See early_boot_ended() below.
140      */
in_early_boot()141     bool in_early_boot() const { return in_early_boot_; }
142 
143     /*
144      * Get current time in seconds from some starting point.  This value is used to compute relative
145      * times between events.  It must be monotonically increasing, and must not skip or lag.  It
146      * need not have any relation to any external time standard (other than the duration of
147      * "second").
148      */
get_current_time()149     uint32_t get_current_time() const {
150         return static_cast<uint32_t>(get_current_time_ms() / 1000);  // Will wrap every 136 years
151     }
152 
153     /*
154      * Returns the security level of this implementation.
155      */
156     virtual keymaster_security_level_t SecurityLevel() const = 0;
157 
158     /*
159      * Returns true if the specified auth_token has a valid signature, or if signature validation is
160      * not available.
161      */
162     virtual bool ValidateTokenSignature(const hw_auth_token_t& token) const = 0;
163 
164     /**
165      * Get the sharing parameters used to negotiate a shared HMAC key among multiple parties.
166      */
167     virtual keymaster_error_t GetHmacSharingParameters(HmacSharingParameters* params) = 0;
168 
169     /**
170      * Compute an HMAC key shared among multiple parties.
171      */
172     virtual keymaster_error_t ComputeSharedHmac(const HmacSharingParametersArray& params_array,
173                                                 KeymasterBlob* sharingCheck) = 0;
174 
175     /**
176      * Verify authorizations for another Keymaster instance.
177      */
178     virtual VerifyAuthorizationResponse
179     VerifyAuthorization(const VerifyAuthorizationRequest& request) = 0;
180 
181     /**
182      * Generate TimestampToken for secure clock instance.
183      */
184     virtual keymaster_error_t GenerateTimestampToken(TimestampToken* token);
185 
186     /**
187      * Compute an HMAC using the auth token HMAC key.
188      *
189      * Note: Use with caution.  MACed data must contain enough structure that it's unambiguous.
190      */
191     virtual KmErrorOr<std::array<uint8_t, 32>>
ComputeHmac(const std::vector<uint8_t> &)192     ComputeHmac(const std::vector<uint8_t>& /* data_to_mac */) const {
193         return KM_ERROR_UNIMPLEMENTED;
194     }
195 
196     /**
197      * Creates a key ID for use in subsequent calls to AuthorizeOperation.  AndroidKeymaster
198      * uses this method for creating key IDs. The generated id must be stable in that the same
199      * key_blob bits yield the same keyid.
200      *
201      * Returns false if an error in the crypto library prevents creation of an ID.
202      */
203     virtual bool CreateKeyId(const keymaster_key_blob_t& key_blob, km_id_t* keyid) const = 0;
204 
205     /*
206      * Inform the KeymasterEnforcement object that early boot stage has ended.
207      */
early_boot_ended()208     void early_boot_ended() { in_early_boot_ = false; }
209 
210     /*
211      * Inform the KeymasterEnforcement object that the device is locked, so it knows not to permit
212      * UNLOCKED_DEVICE_REQUIRED keys to be used until a fresh (later than "now") auth token is
213      * provided.  If password_only is true, the fresh auth token must additionally be a password
214      * auth token.
215      */
device_locked(bool password_only)216     void device_locked(bool password_only) {
217         device_locked_at_ = get_current_time_ms();
218         password_unlock_only_ = password_only;
219     }
220 
221   private:
222     keymaster_error_t AuthorizeUpdateOrFinish(const AuthProxy& auth_set,
223                                               const AuthorizationSet& operation_params,
224                                               keymaster_operation_handle_t op_handle);
225 
226     bool MinTimeBetweenOpsPassed(uint32_t min_time_between, const km_id_t keyid);
227     bool MaxUsesPerBootNotExceeded(const km_id_t keyid, uint32_t max_uses);
228     bool GetAndValidateAuthToken(const AuthorizationSet& operation_params,
229                                  const hw_auth_token_t** token, uint32_t* token_auth_type) const;
230     bool AuthTokenMatches(const AuthProxy& auth_set, const AuthorizationSet& operation_params,
231                           const uint64_t user_secure_id, const int auth_type_index,
232                           const int auth_timeout_index,
233                           const keymaster_operation_handle_t op_handle,
234                           bool is_begin_operation) const;
235 
236     AccessTimeMap* access_time_map_;
237     AccessCountMap* access_count_map_;
238     bool in_early_boot_ = true;
239     uint64_t device_locked_at_ = 0;
240     bool password_unlock_only_ = false;
241 };
242 
243 }; /* namespace keymaster */
244 
245 #endif  // ANDROID_LIBRARY_KEYMASTER_ENFORCEMENT_H
246