1 /* 2 * Copyright 2021 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 #pragma once 18 19 #include <cppbor.h> 20 #include <cppbor_parse.h> 21 22 #include <keymaster/android_keymaster_utils.h> 23 #include <keymaster/cppcose/cppcose.h> 24 25 namespace keymaster { 26 27 // These are the negations of the actual error codes 28 constexpr keymaster_error_t kStatusFailed = static_cast<keymaster_error_t>(-1); 29 constexpr keymaster_error_t kStatusInvalidMac = static_cast<keymaster_error_t>(-2); 30 constexpr keymaster_error_t kStatusProductionKeyInTestRequest = static_cast<keymaster_error_t>(-3); 31 constexpr keymaster_error_t kStatusTestKeyInProductionRequest = static_cast<keymaster_error_t>(-4); 32 constexpr keymaster_error_t kStatusInvalidEek = static_cast<keymaster_error_t>(-5); 33 34 template <typename T> class StatusOr { 35 public: StatusOr(uint32_t status_code)36 StatusOr(uint32_t status_code) // NOLINT(google-explicit-constructor) 37 : status_code_(status_code) {} StatusOr(T val)38 StatusOr(T val) 39 : status_code_(0), value_(std::move(val)) {} // NOLINT(google-explicit-constructor) 40 isOk()41 bool isOk() { return status_code_ == 0; } 42 43 T* operator->() & { 44 assert(isOk()); 45 return &value_.value(); 46 } 47 T& operator*() & { 48 assert(isOk()); 49 return value_.value(); 50 } 51 T&& operator*() && { 52 assert(isOk()); 53 return std::move(value_).value(); 54 } 55 moveError()56 uint32_t moveError() { 57 assert(!isOk()); 58 return status_code_; 59 } 60 moveValue()61 T moveValue() { return std::move(value_).value(); } 62 63 private: 64 uint32_t status_code_; 65 std::optional<T> value_; 66 }; 67 68 StatusOr<std::pair<std::vector<uint8_t> /* EEK pub */, std::vector<uint8_t> /* EEK ID */>> 69 validateAndExtractEekPubAndId(bool testMode, const KeymasterBlob& endpointEncryptionCertChain); 70 71 StatusOr<std::vector<uint8_t> /* pubkeys */> 72 validateAndExtractPubkeys(bool testMode, uint32_t numKeys, KeymasterBlob* keysToSign, 73 cppcose::HmacSha256Function macFunction); 74 75 cppbor::Array buildCertReqRecipients(const std::vector<uint8_t>& pubkey, 76 const std::vector<uint8_t>& kid); 77 78 } // namespace keymaster 79