Implement and integrate the verification token handler.

This CL implements a background task handler which for now, runs
a thread to retrieve verification tokens. This CL also integrates
this handler with the enforcement module, in order to allow operations
to receive verification tokens.

Bug: 171503362, 171503128
Test: TBD
Change-Id: I2ed0742043095dafb3b5cb7581ca3a2a70929ecc
diff --git a/keystore2/src/background_task_handler.rs b/keystore2/src/background_task_handler.rs
new file mode 100644
index 0000000..fbb6778
--- /dev/null
+++ b/keystore2/src/background_task_handler.rs
@@ -0,0 +1,144 @@
+// Copyright 2020, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! This module implements the handling of background tasks such as obtaining timestamp tokens from
+//! the timestamp service (or TEE KeyMint in legacy devices), via a separate thread.
+
+use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
+    HardwareAuthToken::HardwareAuthToken, IKeyMintDevice::IKeyMintDevice,
+    SecurityLevel::SecurityLevel, VerificationToken::VerificationToken,
+};
+use android_system_keystore2::aidl::android::system::keystore2::OperationChallenge::OperationChallenge;
+use anyhow::Result;
+use log::error;
+use std::sync::mpsc::{Receiver, Sender};
+use std::sync::Mutex;
+use std::thread::{spawn, JoinHandle};
+/// This is the struct encapsulating the thread which handles background tasks such as
+/// obtaining verification tokens.
+pub struct BackgroundTaskHandler {
+    task_handler: Mutex<Option<JoinHandle<()>>>,
+}
+/// This enum defines the two variants of a message that can be passed down to the
+/// BackgroundTaskHandler via the channel.
+pub enum Message {
+    ///This variant represents a message sent down the channel when requesting a timestamp token.
+    Inputs((HardwareAuthToken, OperationChallenge, Sender<(HardwareAuthToken, VerificationToken)>)),
+    ///This variant represents a message sent down the channel when signalling the thread to stop.
+    Shutdown,
+}
+
+impl BackgroundTaskHandler {
+    /// Initialize the BackgroundTaskHandler with the task_handler field set to None.
+    /// The thread is not started during initialization, as it needs the receiver end of a channel
+    /// to function.
+    pub fn new() -> Self {
+        BackgroundTaskHandler { task_handler: Mutex::new(None) }
+    }
+
+    /// Start the background task handler (bth) by passing in the receiver end of a channel, through
+    /// which the enforcement module can send messages to the bth thread.
+    pub fn start_bth(&self, receiver: Receiver<Message>) -> Result<()> {
+        let task_handler = Self::start_thread(receiver)?;
+        // it is ok to unwrap here because there is no way that this lock can get poisoned.
+        let mut thread_guard = self.task_handler.lock().unwrap();
+        *thread_guard = Some(task_handler);
+        Ok(())
+    }
+
+    fn start_thread(receiver: Receiver<Message>) -> Result<JoinHandle<()>> {
+        // TODO: initialize timestamp service/keymint instances.
+        // First lookup timestamp token service, if this is not a legacy device.
+        // Otherwise, lookup keymaster 4.1 or 4.0 (previous ones are not relevant, because strongbox
+        // was introduced with keymaster 4.0).
+        // If either a timestamp service or a keymint instance is expected to be found and neither
+        // is found, an error is returned.
+        // If neither is expected to be found, make timestamp_service field None, and in the thread,
+        // send a default verification token down the channel to the operation.
+        // Until timestamp service is available and proper probing of legacy keymaster devices are
+        // done, the keymint service is initialized here as it is done in security_level module.
+        Ok(spawn(move || {
+            while let Message::Inputs((auth_token, op_challenge, op_sender)) = receiver
+                .recv()
+                .expect(
+                "In background task handler thread. Failed to receive message over the channel.",
+            ) {
+                // TODO: call the timestamp service/old TEE keymaster to get
+                // timestamp/verification tokens and pass it down the sender that is
+                // coupled with a particular operation's receiver.
+                // If none of the services are available, pass the authtoken and a default
+                // verification token down the channel.
+                let km_dev: Box<dyn IKeyMintDevice> =
+                    crate::globals::get_keymint_device(SecurityLevel::TRUSTED_ENVIRONMENT)
+                        .expect("A TEE Keymint must be present.")
+                        .get_interface()
+                        .expect("Fatal: The keymint device does not implement IKeyMintDevice.");
+                let result = km_dev.verifyAuthorization(op_challenge.challenge, &auth_token);
+                match result {
+                    Ok(verification_token) => {
+                        // this can fail if the operation is dropped and hence the channel
+                        // is hung up.
+                        op_sender.send((auth_token, verification_token)).unwrap_or_else(|e| {
+                            error!(
+                                "In background task handler thread. Failed to send
+                                         verification token to operation {} due to error {:?}.",
+                                op_challenge.challenge, e
+                            )
+                        });
+                    }
+                    Err(e) => {
+                        // log error
+                        error!(
+                            "In background task handler thread. Failed to receive
+                                     verification token for operation {} due to error {:?}.",
+                            op_challenge.challenge, e
+                        );
+                        // send default verification token
+                        // this can fail if the operation is dropped and the channel is
+                        // hung up.
+                        op_sender.send((auth_token, VerificationToken::default())).unwrap_or_else(
+                            |e| {
+                                error!(
+                                    "In background task handler thread. Failed to send default
+                                         verification token to operation {} due to error {:?}.",
+                                    op_challenge.challenge, e
+                                )
+                            },
+                        );
+                    }
+                }
+            }
+        }))
+    }
+}
+
+impl Default for BackgroundTaskHandler {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+// TODO: Verify if we want the thread to finish the requests they are working on, during drop.
+impl Drop for BackgroundTaskHandler {
+    fn drop(&mut self) {
+        // it is ok to unwrap here as there is no way this lock can get poisoned.
+        let mut thread_guard = self.task_handler.lock().unwrap();
+        if let Some(thread) = (*thread_guard).take() {
+            // TODO: Verify how best to handle the error in this case.
+            thread.join().unwrap_or_else(|e| {
+                panic!("Failed to join the background task handling thread because of {:?}.", e);
+            });
+        }
+    }
+}
diff --git a/keystore2/src/enforcements.rs b/keystore2/src/enforcements.rs
index 41a4e48..ae41432 100644
--- a/keystore2/src/enforcements.rs
+++ b/keystore2/src/enforcements.rs
@@ -15,6 +15,7 @@
 //! This is the Keystore 2.0 Enforcements module.
 // TODO: more description to follow.
 use crate::auth_token_handler::AuthTokenHandler;
+use crate::background_task_handler::Message;
 use crate::database::AuthTokenEntry;
 use crate::error::Error as KeystoreError;
 use crate::globals::DB;
@@ -23,10 +24,12 @@
     Algorithm::Algorithm, ErrorCode::ErrorCode as Ec, HardwareAuthToken::HardwareAuthToken,
     HardwareAuthenticatorType::HardwareAuthenticatorType, KeyPurpose::KeyPurpose,
     SecurityLevel::SecurityLevel, Tag::Tag, Timestamp::Timestamp,
+    VerificationToken::VerificationToken,
 };
 use android_system_keystore2::aidl::android::system::keystore2::OperationChallenge::OperationChallenge;
 use anyhow::{Context, Result};
 use std::collections::{HashMap, HashSet};
+use std::sync::mpsc::{channel, Sender};
 use std::sync::Mutex;
 use std::time::SystemTime;
 
@@ -38,17 +41,29 @@
     // This maps the operation challenge to an optional auth token, to maintain op-auth tokens
     // in-memory, until they are picked up and given to the operation by authorise_update_finish().
     op_auth_map: Mutex<HashMap<i64, Option<HardwareAuthToken>>>,
+    // sender end of the channel via which the enforcement module communicates with the
+    // background task handler (bth). This is of type Mutex in an Option because it is initialized
+    // after the global enforcement object is created.
+    sender_to_bth: Mutex<Option<Sender<Message>>>,
 }
 
 impl Enforcements {
-    /// Creates an enforcement object with the two data structures it holds.
+    /// Creates an enforcement object with the two data structures it holds and the sender as None.
     pub fn new() -> Self {
         Enforcements {
             device_unlocked_set: Mutex::new(HashSet::new()),
             op_auth_map: Mutex::new(HashMap::new()),
+            sender_to_bth: Mutex::new(None),
         }
     }
 
+    /// Initialize the sender_to_bth field, using the given sender end of a channel.
+    pub fn set_sender_to_bth(&self, sender: Sender<Message>) {
+        // It is ok to unwrap here because there is no chance of poisoning this mutex.
+        let mut sender_guard = self.sender_to_bth.lock().unwrap();
+        *sender_guard = Some(sender);
+    }
+
     /// Checks if update or finish calls are authorized. If the operation is based on per-op key,
     /// try to receive the auth token from the op_auth_map. We assume that by the time update/finish
     /// is called, the auth token has been delivered to keystore. Therefore, we do not wait for it
@@ -415,6 +430,34 @@
         let mut op_auth_map_guard = self.op_auth_map.lock().unwrap();
         op_auth_map_guard.insert(op_challenge, None);
     }
+
+    /// Requests a verification token from the background task handler which will retrieve it from
+    /// Timestamp Service or TEE KeyMint.
+    /// Once the create_operation receives an operation challenge from KeyMint, if it has
+    /// previously received a VerificationRequired variant of AuthTokenHandler during
+    /// authorize_create_operation, it calls this method to obtain a VerificationToken.
+    pub fn request_verification_token(
+        &self,
+        auth_token: HardwareAuthToken,
+        op_challenge: OperationChallenge,
+    ) -> Result<AuthTokenHandler> {
+        // create a channel for this particular operation
+        let (op_sender, op_receiver) = channel::<(HardwareAuthToken, VerificationToken)>();
+        // it is ok to unwrap here because there is no way this mutex gets poisoned.
+        let sender_guard = self.sender_to_bth.lock().unwrap();
+        if let Some(sender) = &*sender_guard {
+            let sender_cloned = sender.clone();
+            drop(sender_guard);
+            sender_cloned
+                .send(Message::Inputs((auth_token, op_challenge, op_sender)))
+                .map_err(|_| KeystoreError::sys())
+                .context(
+                    "In request_verification_token. Sending a request for a verification token
+             failed.",
+                )?;
+        }
+        Ok(AuthTokenHandler::Channel(op_receiver))
+    }
 }
 
 impl Default for Enforcements {
@@ -423,4 +466,21 @@
     }
 }
 
+impl Drop for Enforcements {
+    fn drop(&mut self) {
+        let sender_guard = self.sender_to_bth.lock().unwrap();
+        if let Some(sender) = &*sender_guard {
+            let sender_cloned = sender.clone();
+            drop(sender_guard);
+            // TODO: Verify how best to handle the error in this case.
+            sender_cloned.send(Message::Shutdown).unwrap_or_else(|e| {
+                panic!(
+                    "Failed to send shutdown message to background task handler because of {:?}.",
+                    e
+                );
+            });
+        }
+    }
+}
+
 // TODO: Add tests to enforcement module (b/175578618).
diff --git a/keystore2/src/globals.rs b/keystore2/src/globals.rs
index 075a801..035dac1 100644
--- a/keystore2/src/globals.rs
+++ b/keystore2/src/globals.rs
@@ -17,6 +17,7 @@
 //! to talk to.
 
 use crate::async_task::AsyncTask;
+use crate::background_task_handler::BackgroundTaskHandler;
 use crate::enforcements::Enforcements;
 use crate::gc::Gc;
 use crate::super_key::SuperKeyManager;
@@ -86,6 +87,10 @@
     /// It is safe for this enforcements object to be called by multiple threads because the two
     /// data structures which maintain its state are protected by mutexes.
     pub static ref ENFORCEMENTS: Enforcements = Enforcements::new();
+    /// Background task handler is initialized and exists globally.
+    /// The other modules (e.g. enforcements) communicate with it via a channel initialized during
+    /// keystore startup.
+    pub static ref BACKGROUND_TASK_HANDLER: BackgroundTaskHandler = BackgroundTaskHandler::new();
 }
 
 static KEYMINT_SERVICE_NAME: &str = "android.hardware.security.keymint.IKeyMintDevice";
diff --git a/keystore2/src/keystore2_main.rs b/keystore2/src/keystore2_main.rs
index 7391f37..8607eef 100644
--- a/keystore2/src/keystore2_main.rs
+++ b/keystore2/src/keystore2_main.rs
@@ -16,9 +16,12 @@
 
 use binder::Interface;
 use keystore2::apc::ApcManager;
+use keystore2::background_task_handler::Message;
+use keystore2::globals::{BACKGROUND_TASK_HANDLER, ENFORCEMENTS};
 use keystore2::service::KeystoreService;
 use log::{error, info};
 use std::panic;
+use std::sync::mpsc::channel;
 
 static KS2_SERVICE_NAME: &str = "android.system.keystore2";
 static APC_SERVICE_NAME: &str = "android.security.apc";
@@ -50,6 +53,14 @@
         panic!("Must specify a working directory.");
     }
 
+    // initialize the channel via which the enforcement module and background task handler module
+    // communicate, and hand over the sender and receiver ends to the respective objects.
+    let (sender, receiver) = channel::<Message>();
+    ENFORCEMENTS.set_sender_to_bth(sender);
+    BACKGROUND_TASK_HANDLER.start_bth(receiver).unwrap_or_else(|e| {
+        panic!("Failed to start background task handler because of {:?}.", e);
+    });
+
     info!("Starting thread pool now.");
     binder::ProcessState::start_thread_pool();
 
diff --git a/keystore2/src/lib.rs b/keystore2/src/lib.rs
index 29b3992..f73cd59 100644
--- a/keystore2/src/lib.rs
+++ b/keystore2/src/lib.rs
@@ -17,6 +17,7 @@
 
 pub mod apc;
 pub mod auth_token_handler;
+pub mod background_task_handler;
 pub mod database;
 pub mod enforcements;
 pub mod error;
diff --git a/keystore2/src/security_level.rs b/keystore2/src/security_level.rs
index c5b5da0..079e92a 100644
--- a/keystore2/src/security_level.rs
+++ b/keystore2/src/security_level.rs
@@ -21,7 +21,6 @@
     HardwareAuthenticatorType::HardwareAuthenticatorType, IKeyMintDevice::IKeyMintDevice,
     KeyCreationResult::KeyCreationResult, KeyFormat::KeyFormat, KeyParameter::KeyParameter,
     KeyParameterValue::KeyParameterValue, SecurityLevel::SecurityLevel, Tag::Tag,
-    VerificationToken::VerificationToken,
 };
 use android_system_keystore2::aidl::android::system::keystore2::{
     AuthenticatorSpec::AuthenticatorSpec, CreateOperationResponse::CreateOperationResponse,
@@ -51,7 +50,6 @@
 };
 use anyhow::{Context, Result};
 use binder::{IBinder, Interface, ThreadState};
-use std::sync::mpsc::channel;
 
 /// Implementation of the IKeystoreSecurityLevel Interface.
 pub struct KeystoreSecurityLevel {
@@ -284,9 +282,13 @@
                 ENFORCEMENTS.insert_to_op_auth_map(begin_result.challenge);
             }
             AuthTokenHandler::VerificationRequired(auth_token) => {
-                let (_sender, receiver) = channel::<(HardwareAuthToken, VerificationToken)>();
-                //TODO: call the worker thread and hand over the sender, auth token and challenge
-                auth_token_handler = AuthTokenHandler::Channel(receiver);
+                //request a verification token, given the auth token and the challenge
+                auth_token_handler = ENFORCEMENTS
+                    .request_verification_token(
+                        auth_token,
+                        OperationChallenge { challenge: begin_result.challenge },
+                    )
+                    .context("In create_operation.")?;
             }
             _ => {}
         }