1//
2// Copyright (C) 2015 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#include "tpm_manager/server/tpm2_status_impl.h"
18
19#include <base/logging.h>
20#include <trunks/error_codes.h>
21#include <trunks/tpm_generated.h>
22#include <trunks/trunks_factory_impl.h>
23
24using trunks::TPM_RC;
25using trunks::TPM_RC_SUCCESS;
26
27namespace tpm_manager {
28
29Tpm2StatusImpl::Tpm2StatusImpl(const trunks::TrunksFactory& factory)
30    : trunks_factory_(factory),
31      trunks_tpm_state_(trunks_factory_.GetTpmState()) {}
32
33bool Tpm2StatusImpl::IsTpmEnabled() {
34  if (!initialized_) {
35    Refresh();
36  }
37  return trunks_tpm_state_->IsEnabled();
38}
39
40bool Tpm2StatusImpl::IsTpmOwned() {
41  if (!is_owned_) {
42    Refresh();
43  }
44  is_owned_ = trunks_tpm_state_->IsOwned();
45  return is_owned_;
46}
47
48bool Tpm2StatusImpl::GetDictionaryAttackInfo(int* counter,
49                                             int* threshold,
50                                             bool* lockout,
51                                             int* seconds_remaining) {
52  if (!Refresh()) {
53    return false;
54  }
55  if (counter) {
56    *counter = trunks_tpm_state_->GetLockoutCounter();
57  }
58  if (threshold) {
59    *threshold = trunks_tpm_state_->GetLockoutThreshold();
60  }
61  if (lockout) {
62    *lockout = trunks_tpm_state_->IsInLockout();
63  }
64  if (seconds_remaining) {
65    *seconds_remaining = trunks_tpm_state_->GetLockoutCounter() *
66                         trunks_tpm_state_->GetLockoutInterval();
67  }
68  return true;
69}
70
71bool Tpm2StatusImpl::Refresh() {
72  TPM_RC result = trunks_tpm_state_->Initialize();
73  if (result != TPM_RC_SUCCESS) {
74    LOG(WARNING) << "Error initializing trunks tpm state: "
75                 << trunks::GetErrorString(result);
76    return false;
77  }
78  initialized_ = true;
79  return true;
80}
81
82}  // namespace tpm_manager
83