xref: /aosp_15_r20/external/tink/cc/keyset_handle.h (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1 // Copyright 2017 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 //
15 ////////////////////////////////////////////////////////////////////////////////
16 
17 #ifndef TINK_KEYSET_HANDLE_H_
18 #define TINK_KEYSET_HANDLE_H_
19 
20 #include <cstdint>
21 #include <memory>
22 #include <string>
23 #include <utility>
24 #include <vector>
25 
26 #include "absl/base/attributes.h"
27 #include "absl/container/flat_hash_map.h"
28 #include "absl/memory/memory.h"
29 #include "absl/status/status.h"
30 #include "tink/aead.h"
31 #include "tink/configuration.h"
32 #include "tink/internal/configuration_impl.h"
33 #include "tink/internal/key_info.h"
34 #include "tink/key.h"
35 #include "tink/key_gen_configuration.h"
36 #include "tink/key_manager.h"
37 #include "tink/key_status.h"
38 #include "tink/keyset_reader.h"
39 #include "tink/keyset_writer.h"
40 #include "tink/primitive_set.h"
41 #include "tink/registry.h"
42 #include "tink/util/statusor.h"
43 #include "proto/tink.pb.h"
44 
45 namespace crypto {
46 namespace tink {
47 
48 // KeysetHandle provides abstracted access to Keysets, to limit
49 // the exposure of actual protocol buffers that hold sensitive
50 // key material.
51 class KeysetHandle {
52  public:
53   // Represents a single entry in a `KeysetHandle`. Some current behavior will
54   // be changed in the future.
55   class Entry {
56    public:
57     // May return an internal class in case there is no implementation of the
58     // corresponding key class yet.  Returned value only valid for lifetime
59     // of entry object.
GetKey()60     std::shared_ptr<const Key> GetKey() const { return key_; }
61 
62     // Status indicates whether or not a key should still be used.
GetStatus()63     KeyStatus GetStatus() const { return status_; }
64 
65     // ID should be unique (though currently Tink still accepts keysets with
66     // repeated IDs).
GetId()67     int GetId() const { return id_; }
68 
69     // Should return true for exactly one entry (though currently Tink still
70     // accepts keysets which have no entry marked as primary).
IsPrimary()71     bool IsPrimary() const { return is_primary_; }
72 
73    private:
74     friend class KeysetHandle;
75     friend class KeysetHandleBuilder;
76 
Entry(std::shared_ptr<const Key> key,KeyStatus status,int id,bool is_primary)77     Entry(std::shared_ptr<const Key> key, KeyStatus status, int id,
78           bool is_primary)
79         : key_(std::move(key)),
80           status_(status),
81           id_(id),
82           is_primary_(is_primary) {}
83 
84     std::shared_ptr<const Key> key_;
85     KeyStatus status_;
86     int id_;
87     bool is_primary_;
88   };
89 
90   // Returns the number of entries in this keyset.
size()91   int size() const { return keyset_.key_size(); }
92   // Validates single `KeysetHandle::Entry` at `index` by making sure that the
93   // key entry's type URL is printable and that it has a valid key status.
94   crypto::tink::util::Status ValidateAt(int index) const;
95   // Validates each individual `KeysetHandle::Entry` in keyset handle by calling
96   // `ValidateAt()`.  Also, checks that there is a single enabled primary key.
97   crypto::tink::util::Status Validate() const;
98   // Returns entry for primary key in this keyset. Crashes if `Validate()`
99   // does not return an OK status.  Call `Validate()` prior to calling this
100   // method to avoid potentially crashing your program.
101   Entry GetPrimary() const;
102   // Returns the `KeysetHandle::Entry` at `index`.  Crashes if
103   // `ValidateAt(index)` does not return an OK status.  Call `ValidateAt(index)`
104   // prior to calling this method to avoid potentially crashing your program.
105   Entry operator[](int index) const;
106 
107   // Creates a KeysetHandle from an encrypted keyset obtained via `reader`
108   // using `master_key_aead` to decrypt the keyset, with monitoring annotations
109   // `monitoring_annotations`; by default, `monitoring_annotations` is empty.
110   static crypto::tink::util::StatusOr<std::unique_ptr<KeysetHandle>> Read(
111       std::unique_ptr<KeysetReader> reader, const Aead& master_key_aead,
112       const absl::flat_hash_map<std::string, std::string>&
113           monitoring_annotations = {});
114 
115   // Creates a KeysetHandle from an encrypted keyset obtained via `reader`
116   // using `master_key_aead` to decrypt the keyset, expecting `associated_data`.
117   // The keyset is annotated for monitoring with `monitoring_annotations`; by
118   // default, `monitoring_annotations` is empty.
119   static crypto::tink::util::StatusOr<std::unique_ptr<KeysetHandle>>
120   ReadWithAssociatedData(std::unique_ptr<KeysetReader> reader,
121                          const Aead& master_key_aead,
122                          absl::string_view associated_data,
123                          const absl::flat_hash_map<std::string, std::string>&
124                              monitoring_annotations = {});
125 
126   // Creates a KeysetHandle from a serialized keyset `serialized_keyset` which
127   // contains no secret key material, and annotates it with
128   // `monitoring_annotations` for monitoring; by default,
129   // `monitoring_annotations` is empty. This can be used to load public keysets
130   // or envelope encryption keysets.
131   static crypto::tink::util::StatusOr<std::unique_ptr<KeysetHandle>>
132   ReadNoSecret(const std::string& serialized_keyset,
133                const absl::flat_hash_map<std::string, std::string>&
134                    monitoring_annotations = {});
135 
136   // Returns a KeysetHandle containing a single new key generated according to
137   // `key_template` and using `config`. The keyset is annotated for monitoring
138   // with `monitoring_annotations`, which is empty by default.
139   static crypto::tink::util::StatusOr<std::unique_ptr<KeysetHandle>>
140   GenerateNew(const google::crypto::tink::KeyTemplate& key_template,
141               const crypto::tink::KeyGenConfiguration& config,
142               const absl::flat_hash_map<std::string, std::string>&
143                   monitoring_annotations = {});
144 
145   // TODO(b/265865177): Deprecate.
146   // Returns a KeysetHandle containing a single new key generated according to
147   // `key_template`. The keyset is annotated for monitoring with
148   // `monitoring_annotations`, which is empty by default.
149   static crypto::tink::util::StatusOr<std::unique_ptr<KeysetHandle>>
150   GenerateNew(const google::crypto::tink::KeyTemplate& key_template,
151               const absl::flat_hash_map<std::string, std::string>&
152                   monitoring_annotations = {});
153 
154   // Encrypts the underlying keyset with the provided `master_key_aead`
155   // and writes the resulting EncryptedKeyset to the given `writer`,
156   // which must be non-null.
157   crypto::tink::util::Status Write(KeysetWriter* writer,
158                                    const Aead& master_key_aead) const;
159 
160   // Encrypts the underlying keyset with the provided `master_key_aead`, using
161   // `associated_data`. and writes the resulting EncryptedKeyset to the given
162   // `writer`, which must be non-null.
163   crypto::tink::util::Status WriteWithAssociatedData(
164       KeysetWriter* writer, const Aead& master_key_aead,
165       absl::string_view associated_data) const;
166 
167   // Returns KeysetInfo, a "safe" Keyset that doesn't contain any actual
168   // key material, thus can be used for logging or monitoring.
169   google::crypto::tink::KeysetInfo GetKeysetInfo() const;
170 
171   // Writes the underlying keyset to `writer` only if the keyset does not
172   // contain any secret key material.
173   // This can be used to persist public keysets or envelope encryption keysets.
174   // Users that need to persist cleartext keysets can use
175   // `CleartextKeysetHandle`.
176   crypto::tink::util::Status WriteNoSecret(KeysetWriter* writer) const;
177 
178   // Returns a new KeysetHandle containing public keys corresponding to the
179   // private keys in this handle. Relies on key type managers stored in `config`
180   // to do so. Returns an error if this handle contains keys that are not
181   // private keys.
182   crypto::tink::util::StatusOr<std::unique_ptr<KeysetHandle>>
183   GetPublicKeysetHandle(const KeyGenConfiguration& config) const;
184 
185   // Returns a new KeysetHandle containing public keys corresponding to the
186   // private keys in this handle. Relies on key type managers stored in the
187   // global registry to do so. Returns an error if this handle contains keys
188   // that are not private keys.
189   crypto::tink::util::StatusOr<std::unique_ptr<KeysetHandle>>
190   GetPublicKeysetHandle() const;
191 
192   // Creates a wrapped primitive using this keyset handle and config, which
193   // stores necessary primitive wrappers and key type managers.
194   template <class P>
195   crypto::tink::util::StatusOr<std::unique_ptr<P>> GetPrimitive(
196       const Configuration& config) const;
197 
198   // Creates a wrapped primitive using this keyset handle and the global
199   // registry, which stores necessary primitive wrappers and key type managers.
200   template <class P>
201   crypto::tink::util::StatusOr<std::unique_ptr<P>> GetPrimitive() const;
202 
203   // Creates a wrapped primitive corresponding to this keyset. Uses the given
204   // KeyManager, as well as the KeyManager and PrimitiveWrapper objects in the
205   // global registry to create the primitive. The given KeyManager is used for
206   // keys supported by it. For those, the registry is ignored.
207   template <class P>
208   ABSL_DEPRECATED("Register the keymanager and use GetPrimitive")
209   crypto::tink::util::StatusOr<std::unique_ptr<P>> GetPrimitive(
210       const KeyManager<P>* custom_manager) const;
211 
212  private:
213   // The classes below need access to get_keyset();
214   friend class CleartextKeysetHandle;
215   friend class KeysetManager;
216 
217   // TestKeysetHandle::GetKeyset() provides access to get_keyset().
218   friend class TestKeysetHandle;
219 
220   // KeysetHandleBuilder::Build() needs access to KeysetHandle(Keyset).
221   friend class KeysetHandleBuilder;
222 
223   // Creates a handle that contains the given keyset.
KeysetHandle(google::crypto::tink::Keyset keyset)224   explicit KeysetHandle(google::crypto::tink::Keyset keyset)
225       : keyset_(std::move(keyset)) {}
KeysetHandle(std::unique_ptr<google::crypto::tink::Keyset> keyset)226   explicit KeysetHandle(std::unique_ptr<google::crypto::tink::Keyset> keyset)
227       : keyset_(std::move(*keyset)) {}
228   // Creates a handle that contains the given `keyset` and `entries`.
KeysetHandle(google::crypto::tink::Keyset keyset,const std::vector<std::shared_ptr<const Entry>> & entries)229   explicit KeysetHandle(
230       google::crypto::tink::Keyset keyset,
231       const std::vector<std::shared_ptr<const Entry>>& entries)
232       : keyset_(std::move(keyset)), entries_(entries) {}
KeysetHandle(std::unique_ptr<google::crypto::tink::Keyset> keyset,const std::vector<std::shared_ptr<const Entry>> & entries)233   explicit KeysetHandle(
234       std::unique_ptr<google::crypto::tink::Keyset> keyset,
235       const std::vector<std::shared_ptr<const Entry>>& entries)
236       : keyset_(std::move(*keyset)), entries_(entries) {}
237   // Creates a handle that contains the given `keyset` and
238   // `monitoring_annotations`.
KeysetHandle(google::crypto::tink::Keyset keyset,const absl::flat_hash_map<std::string,std::string> & monitoring_annotations)239   KeysetHandle(google::crypto::tink::Keyset keyset,
240                const absl::flat_hash_map<std::string, std::string>&
241                    monitoring_annotations)
242       : keyset_(std::move(keyset)),
243         monitoring_annotations_(monitoring_annotations) {}
KeysetHandle(std::unique_ptr<google::crypto::tink::Keyset> keyset,const absl::flat_hash_map<std::string,std::string> & monitoring_annotations)244   KeysetHandle(std::unique_ptr<google::crypto::tink::Keyset> keyset,
245                const absl::flat_hash_map<std::string, std::string>&
246                    monitoring_annotations)
247       : keyset_(std::move(*keyset)),
248         monitoring_annotations_(monitoring_annotations) {}
249   // Creates a handle that contains the given `keyset`, `entries`, and
250   // `monitoring_annotations`.
KeysetHandle(google::crypto::tink::Keyset keyset,const std::vector<std::shared_ptr<const Entry>> & entries,const absl::flat_hash_map<std::string,std::string> & monitoring_annotations)251   KeysetHandle(google::crypto::tink::Keyset keyset,
252                const std::vector<std::shared_ptr<const Entry>>& entries,
253                const absl::flat_hash_map<std::string, std::string>&
254                    monitoring_annotations)
255       : keyset_(std::move(keyset)),
256         entries_(entries),
257         monitoring_annotations_(monitoring_annotations) {}
KeysetHandle(std::unique_ptr<google::crypto::tink::Keyset> keyset,const std::vector<std::shared_ptr<const Entry>> & entries,const absl::flat_hash_map<std::string,std::string> & monitoring_annotations)258   KeysetHandle(std::unique_ptr<google::crypto::tink::Keyset> keyset,
259                const std::vector<std::shared_ptr<const Entry>>& entries,
260                const absl::flat_hash_map<std::string, std::string>&
261                    monitoring_annotations)
262       : keyset_(std::move(*keyset)),
263         entries_(entries),
264         monitoring_annotations_(monitoring_annotations) {}
265 
266   // Generates a key from `key_template` and adds it `keyset`.
267   static crypto::tink::util::StatusOr<uint32_t> AddToKeyset(
268       const google::crypto::tink::KeyTemplate& key_template, bool as_primary,
269       const crypto::tink::KeyGenConfiguration& config,
270       google::crypto::tink::Keyset* keyset);
271 
272   // Creates list of KeysetHandle::Entry entries derived from `keyset` in order.
273   static crypto::tink::util::StatusOr<std::vector<std::shared_ptr<const Entry>>>
274   GetEntriesFromKeyset(const google::crypto::tink::Keyset& keyset);
275 
276   // Creates KeysetHandle::Entry for `key`, which will be set to primary if
277   // its key id equals `primary_key_id`.
278   static util::StatusOr<Entry> CreateEntry(
279       const google::crypto::tink::Keyset::Key& key, uint32_t primary_key_id);
280 
281   // Generates a key from `key_template` and adds it to the keyset handle.
282   crypto::tink::util::StatusOr<uint32_t> AddKey(
283       const google::crypto::tink::KeyTemplate& key_template, bool as_primary,
284       const crypto::tink::KeyGenConfiguration& config);
285 
286   // Returns keyset held by this handle.
get_keyset()287   const google::crypto::tink::Keyset& get_keyset() const { return keyset_; }
288 
289   // Creates a set of primitives corresponding to the keys with
290   // (status == ENABLED) in the keyset given in 'keyset_handle',
291   // assuming all the corresponding key managers are present (keys
292   // with (status != ENABLED) are skipped).
293   //
294   // The returned set is usually later "wrapped" into a class that
295   // implements the corresponding Primitive-interface.
296   template <class P>
297   crypto::tink::util::StatusOr<std::unique_ptr<PrimitiveSet<P>>> GetPrimitives(
298       const KeyManager<P>* custom_manager) const;
299 
300   // Creates KeysetHandle::Entry from `keyset_` at `index`.
301   Entry CreateEntryAt(int index) const;
302 
303   google::crypto::tink::Keyset keyset_;
304   // If this keyset handle has been created with a constructor that does not
305   // accept an entries argument, then `entries` will be empty and operator[]
306   // will fall back to creating the key entry on demand from `keyset_`.
307   //
308   // If `entries_` is not empty, then it should contain exactly one key entry
309   // for each key proto in `keyset_`.
310   std::vector<std::shared_ptr<const Entry>> entries_;
311   absl::flat_hash_map<std::string, std::string> monitoring_annotations_;
312 };
313 
314 ///////////////////////////////////////////////////////////////////////////////
315 // Implementation details of templated methods.
316 
317 template <class P>
318 crypto::tink::util::StatusOr<std::unique_ptr<PrimitiveSet<P>>>
GetPrimitives(const KeyManager<P> * custom_manager)319 KeysetHandle::GetPrimitives(const KeyManager<P>* custom_manager) const {
320   crypto::tink::util::Status status = ValidateKeyset(get_keyset());
321   if (!status.ok()) return status;
322   typename PrimitiveSet<P>::Builder primitives_builder;
323   primitives_builder.AddAnnotations(monitoring_annotations_);
324   for (const google::crypto::tink::Keyset::Key& key : get_keyset().key()) {
325     if (key.status() == google::crypto::tink::KeyStatusType::ENABLED) {
326       std::unique_ptr<P> primitive;
327       if (custom_manager != nullptr &&
328           custom_manager->DoesSupport(key.key_data().type_url())) {
329         auto primitive_result = custom_manager->GetPrimitive(key.key_data());
330         if (!primitive_result.ok()) return primitive_result.status();
331         primitive = std::move(primitive_result.value());
332       } else {
333         auto primitive_result = Registry::GetPrimitive<P>(key.key_data());
334         if (!primitive_result.ok()) return primitive_result.status();
335         primitive = std::move(primitive_result.value());
336       }
337       if (key.key_id() == get_keyset().primary_key_id()) {
338         primitives_builder.AddPrimaryPrimitive(std::move(primitive),
339                                                KeyInfoFromKey(key));
340       } else {
341         primitives_builder.AddPrimitive(std::move(primitive),
342                                         KeyInfoFromKey(key));
343       }
344     }
345   }
346   auto primitives = std::move(primitives_builder).Build();
347   if (!primitives.ok()) return primitives.status();
348   return absl::make_unique<PrimitiveSet<P>>(*std::move(primitives));
349 }
350 
351 template <class P>
GetPrimitive(const Configuration & config)352 crypto::tink::util::StatusOr<std::unique_ptr<P>> KeysetHandle::GetPrimitive(
353     const Configuration& config) const {
354   if (crypto::tink::internal::ConfigurationImpl::IsInGlobalRegistryMode(
355           config)) {
356     return crypto::tink::internal::RegistryImpl::GlobalInstance().WrapKeyset<P>(
357         keyset_, monitoring_annotations_);
358   }
359 
360   crypto::tink::util::StatusOr<
361       const crypto::tink::internal::KeysetWrapperStore*>
362       wrapper_store =
363           crypto::tink::internal::ConfigurationImpl::GetKeysetWrapperStore(
364               config);
365   if (!wrapper_store.ok()) {
366     return wrapper_store.status();
367   }
368   crypto::tink::util::StatusOr<const crypto::tink::internal::KeysetWrapper<P>*>
369       wrapper = (*wrapper_store)->Get<P>();
370   if (!wrapper.ok()) {
371     return wrapper.status();
372   }
373   return (*wrapper)->Wrap(keyset_, monitoring_annotations_);
374 }
375 
376 // TODO(b/265865177): Deprecate.
377 template <class P>
GetPrimitive()378 crypto::tink::util::StatusOr<std::unique_ptr<P>> KeysetHandle::GetPrimitive()
379     const {
380   // TODO(b/265705174): Replace with ConfigGlobalRegistry instance.
381   crypto::tink::Configuration config;
382   crypto::tink::util::Status status =
383       crypto::tink::internal::ConfigurationImpl::SetGlobalRegistryMode(config);
384   if (!status.ok()) {
385     return status;
386   }
387   return GetPrimitive<P>(config);
388 }
389 
390 template <class P>
GetPrimitive(const KeyManager<P> * custom_manager)391 crypto::tink::util::StatusOr<std::unique_ptr<P>> KeysetHandle::GetPrimitive(
392     const KeyManager<P>* custom_manager) const {
393   if (custom_manager == nullptr) {
394     return crypto::tink::util::Status(absl::StatusCode::kInvalidArgument,
395                                       "custom_manager must not be null");
396   }
397   auto primitives_result = this->GetPrimitives<P>(custom_manager);
398   if (!primitives_result.ok()) {
399     return primitives_result.status();
400   }
401   return Registry::Wrap<P>(std::move(primitives_result.value()));
402 }
403 
404 }  // namespace tink
405 }  // namespace crypto
406 
407 #endif  // TINK_KEYSET_HANDLE_H_
408