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