1 // Copyright 2020, The Android Open Source Project
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 //! This crate implements the Keystore 2.0 service entry point.
16
17 use keystore2::entropy;
18 use keystore2::globals::ENFORCEMENTS;
19 use keystore2::maintenance::Maintenance;
20 use keystore2::metrics::Metrics;
21 use keystore2::metrics_store;
22 use keystore2::service::KeystoreService;
23 use keystore2::{apc::ApcManager, shared_secret_negotiation};
24 use keystore2::{authorization::AuthorizationManager, id_rotation::IdRotationState};
25 use legacykeystore::LegacyKeystore;
26 use log::{error, info};
27 use rusqlite::trace as sqlite_trace;
28 use std::{os::raw::c_int, panic, path::Path, sync::mpsc::channel};
29
30 static KS2_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
31 static APC_SERVICE_NAME: &str = "android.security.apc";
32 static AUTHORIZATION_SERVICE_NAME: &str = "android.security.authorization";
33 static METRICS_SERVICE_NAME: &str = "android.security.metrics";
34 static USER_MANAGER_SERVICE_NAME: &str = "android.security.maintenance";
35 static LEGACY_KEYSTORE_SERVICE_NAME: &str = "android.security.legacykeystore";
36
37 /// Keystore 2.0 takes one argument which is a path indicating its designated working directory.
main()38 fn main() {
39 // Initialize android logging.
40 android_logger::init_once(
41 android_logger::Config::default()
42 .with_tag("keystore2")
43 .with_min_level(log::Level::Debug)
44 .with_log_id(android_logger::LogId::System)
45 .format(|buf, record| {
46 writeln!(
47 buf,
48 "{}:{} - {}",
49 record.file().unwrap_or("unknown"),
50 record.line().unwrap_or(0),
51 record.args()
52 )
53 }),
54 );
55 // Redirect panic messages to logcat.
56 panic::set_hook(Box::new(|panic_info| {
57 error!("{}", panic_info);
58 }));
59
60 // Saying hi.
61 info!("Keystore2 is starting.");
62
63 let mut args = std::env::args();
64 args.next().expect("That's odd. How is there not even a first argument?");
65
66 // This must happen early before any other sqlite operations.
67 log::info!("Setting up sqlite logging for keystore2");
68 fn sqlite_log_handler(err: c_int, message: &str) {
69 log::error!("[SQLITE3] {}: {}", err, message);
70 }
71 unsafe { sqlite_trace::config_log(Some(sqlite_log_handler)) }
72 .expect("Error setting sqlite log callback.");
73
74 // Write/update keystore.crash_count system property.
75 metrics_store::update_keystore_crash_sysprop();
76
77 // Keystore 2.0 cannot change to the database directory (typically /data/misc/keystore) on
78 // startup as Keystore 1.0 did because Keystore 2.0 is intended to run much earlier than
79 // Keystore 1.0. Instead we set a global variable to the database path.
80 // For the ground truth check the service startup rule for init (typically in keystore2.rc).
81 let id_rotation_state = if let Some(dir) = args.next() {
82 let db_path = Path::new(&dir);
83 *keystore2::globals::DB_PATH.write().expect("Could not lock DB_PATH.") =
84 db_path.to_path_buf();
85 IdRotationState::new(db_path)
86 } else {
87 panic!("Must specify a database directory.");
88 };
89
90 let (confirmation_token_sender, confirmation_token_receiver) = channel();
91
92 ENFORCEMENTS.install_confirmation_token_receiver(confirmation_token_receiver);
93
94 entropy::register_feeder();
95 shared_secret_negotiation::perform_shared_secret_negotiation();
96
97 info!("Starting thread pool now.");
98 binder::ProcessState::start_thread_pool();
99
100 let ks_service = KeystoreService::new_native_binder(id_rotation_state).unwrap_or_else(|e| {
101 panic!("Failed to create service {} because of {:?}.", KS2_SERVICE_NAME, e);
102 });
103 binder::add_service(KS2_SERVICE_NAME, ks_service.as_binder()).unwrap_or_else(|e| {
104 panic!("Failed to register service {} because of {:?}.", KS2_SERVICE_NAME, e);
105 });
106
107 let apc_service =
108 ApcManager::new_native_binder(confirmation_token_sender).unwrap_or_else(|e| {
109 panic!("Failed to create service {} because of {:?}.", APC_SERVICE_NAME, e);
110 });
111 binder::add_service(APC_SERVICE_NAME, apc_service.as_binder()).unwrap_or_else(|e| {
112 panic!("Failed to register service {} because of {:?}.", APC_SERVICE_NAME, e);
113 });
114
115 let authorization_service = AuthorizationManager::new_native_binder().unwrap_or_else(|e| {
116 panic!("Failed to create service {} because of {:?}.", AUTHORIZATION_SERVICE_NAME, e);
117 });
118 binder::add_service(AUTHORIZATION_SERVICE_NAME, authorization_service.as_binder())
119 .unwrap_or_else(|e| {
120 panic!("Failed to register service {} because of {:?}.", AUTHORIZATION_SERVICE_NAME, e);
121 });
122
123 let (delete_listener, legacykeystore) = LegacyKeystore::new_native_binder(
124 &keystore2::globals::DB_PATH.read().expect("Could not get DB_PATH."),
125 );
126
127 let maintenance_service = Maintenance::new_native_binder(delete_listener).unwrap_or_else(|e| {
128 panic!("Failed to create service {} because of {:?}.", USER_MANAGER_SERVICE_NAME, e);
129 });
130 binder::add_service(USER_MANAGER_SERVICE_NAME, maintenance_service.as_binder()).unwrap_or_else(
131 |e| {
132 panic!("Failed to register service {} because of {:?}.", USER_MANAGER_SERVICE_NAME, e);
133 },
134 );
135
136 let metrics_service = Metrics::new_native_binder().unwrap_or_else(|e| {
137 panic!("Failed to create service {} because of {:?}.", METRICS_SERVICE_NAME, e);
138 });
139 binder::add_service(METRICS_SERVICE_NAME, metrics_service.as_binder()).unwrap_or_else(|e| {
140 panic!("Failed to register service {} because of {:?}.", METRICS_SERVICE_NAME, e);
141 });
142
143 binder::add_service(LEGACY_KEYSTORE_SERVICE_NAME, legacykeystore.as_binder()).unwrap_or_else(
144 |e| {
145 panic!(
146 "Failed to register service {} because of {:?}.",
147 LEGACY_KEYSTORE_SERVICE_NAME, e
148 );
149 },
150 );
151
152 info!("Successfully registered Keystore 2.0 service.");
153
154 info!("Joining thread pool now.");
155 binder::ProcessState::join_thread_pool();
156 }
157