• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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::remote_provisioning::{
23     RemoteProvisioningService, RemotelyProvisionedKeyPoolService,
24 };
25 use keystore2::service::KeystoreService;
26 use keystore2::{apc::ApcManager, shared_secret_negotiation};
27 use keystore2::{authorization::AuthorizationManager, id_rotation::IdRotationState};
28 use legacykeystore::LegacyKeystore;
29 use log::{error, info};
30 use rusqlite::trace as sqlite_trace;
31 use std::{os::raw::c_int, panic, path::Path, sync::mpsc::channel};
32 
33 static KS2_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
34 static APC_SERVICE_NAME: &str = "android.security.apc";
35 static AUTHORIZATION_SERVICE_NAME: &str = "android.security.authorization";
36 static METRICS_SERVICE_NAME: &str = "android.security.metrics";
37 static REMOTE_PROVISIONING_SERVICE_NAME: &str = "android.security.remoteprovisioning";
38 static REMOTELY_PROVISIONED_KEY_POOL_SERVICE_NAME: &str =
39     "android.security.remoteprovisioning.IRemotelyProvisionedKeyPool";
40 static USER_MANAGER_SERVICE_NAME: &str = "android.security.maintenance";
41 static LEGACY_KEYSTORE_SERVICE_NAME: &str = "android.security.legacykeystore";
42 
43 /// Keystore 2.0 takes one argument which is a path indicating its designated working directory.
main()44 fn main() {
45     // Initialize android logging.
46     android_logger::init_once(
47         android_logger::Config::default()
48             .with_tag("keystore2")
49             .with_min_level(log::Level::Debug)
50             .with_log_id(android_logger::LogId::System),
51     );
52     // Redirect panic messages to logcat.
53     panic::set_hook(Box::new(|panic_info| {
54         error!("{}", panic_info);
55     }));
56 
57     // Saying hi.
58     info!("Keystore2 is starting.");
59 
60     let mut args = std::env::args();
61     args.next().expect("That's odd. How is there not even a first argument?");
62 
63     // This must happen early before any other sqlite operations.
64     log::info!("Setting up sqlite logging for keystore2");
65     fn sqlite_log_handler(err: c_int, message: &str) {
66         log::error!("[SQLITE3] {}: {}", err, message);
67     }
68     unsafe { sqlite_trace::config_log(Some(sqlite_log_handler)) }
69         .expect("Error setting sqlite log callback.");
70 
71     // Write/update keystore.crash_count system property.
72     metrics_store::update_keystore_crash_sysprop();
73 
74     // Keystore 2.0 cannot change to the database directory (typically /data/misc/keystore) on
75     // startup as Keystore 1.0 did because Keystore 2.0 is intended to run much earlier than
76     // Keystore 1.0. Instead we set a global variable to the database path.
77     // For the ground truth check the service startup rule for init (typically in keystore2.rc).
78     let id_rotation_state = if let Some(dir) = args.next() {
79         let db_path = Path::new(&dir);
80         *keystore2::globals::DB_PATH.write().expect("Could not lock DB_PATH.") =
81             db_path.to_path_buf();
82         IdRotationState::new(db_path)
83     } else {
84         panic!("Must specify a database directory.");
85     };
86 
87     let (confirmation_token_sender, confirmation_token_receiver) = channel();
88 
89     ENFORCEMENTS.install_confirmation_token_receiver(confirmation_token_receiver);
90 
91     entropy::register_feeder();
92     shared_secret_negotiation::perform_shared_secret_negotiation();
93 
94     info!("Starting thread pool now.");
95     binder::ProcessState::start_thread_pool();
96 
97     let ks_service = KeystoreService::new_native_binder(id_rotation_state).unwrap_or_else(|e| {
98         panic!("Failed to create service {} because of {:?}.", KS2_SERVICE_NAME, e);
99     });
100     binder::add_service(KS2_SERVICE_NAME, ks_service.as_binder()).unwrap_or_else(|e| {
101         panic!("Failed to register service {} because of {:?}.", KS2_SERVICE_NAME, e);
102     });
103 
104     let apc_service =
105         ApcManager::new_native_binder(confirmation_token_sender).unwrap_or_else(|e| {
106             panic!("Failed to create service {} because of {:?}.", APC_SERVICE_NAME, e);
107         });
108     binder::add_service(APC_SERVICE_NAME, apc_service.as_binder()).unwrap_or_else(|e| {
109         panic!("Failed to register service {} because of {:?}.", APC_SERVICE_NAME, e);
110     });
111 
112     let authorization_service = AuthorizationManager::new_native_binder().unwrap_or_else(|e| {
113         panic!("Failed to create service {} because of {:?}.", AUTHORIZATION_SERVICE_NAME, e);
114     });
115     binder::add_service(AUTHORIZATION_SERVICE_NAME, authorization_service.as_binder())
116         .unwrap_or_else(|e| {
117             panic!("Failed to register service {} because of {:?}.", AUTHORIZATION_SERVICE_NAME, e);
118         });
119 
120     let (delete_listener, legacykeystore) = LegacyKeystore::new_native_binder(
121         &keystore2::globals::DB_PATH.read().expect("Could not get DB_PATH."),
122     );
123 
124     let maintenance_service = Maintenance::new_native_binder(delete_listener).unwrap_or_else(|e| {
125         panic!("Failed to create service {} because of {:?}.", USER_MANAGER_SERVICE_NAME, e);
126     });
127     binder::add_service(USER_MANAGER_SERVICE_NAME, maintenance_service.as_binder()).unwrap_or_else(
128         |e| {
129             panic!("Failed to register service {} because of {:?}.", USER_MANAGER_SERVICE_NAME, e);
130         },
131     );
132 
133     let metrics_service = Metrics::new_native_binder().unwrap_or_else(|e| {
134         panic!("Failed to create service {} because of {:?}.", METRICS_SERVICE_NAME, e);
135     });
136     binder::add_service(METRICS_SERVICE_NAME, metrics_service.as_binder()).unwrap_or_else(|e| {
137         panic!("Failed to register service {} because of {:?}.", METRICS_SERVICE_NAME, e);
138     });
139 
140     // Devices with KS2 and KM 1.0 may not have any IRemotelyProvisionedComponent HALs at all. Do
141     // not panic if new_native_binder returns failure because it could not find the TEE HAL.
142     if let Ok(remote_provisioning_service) = RemoteProvisioningService::new_native_binder() {
143         binder::add_service(
144             REMOTE_PROVISIONING_SERVICE_NAME,
145             remote_provisioning_service.as_binder(),
146         )
147         .unwrap_or_else(|e| {
148             panic!(
149                 "Failed to register service {} because of {:?}.",
150                 REMOTE_PROVISIONING_SERVICE_NAME, e
151             );
152         });
153     }
154 
155     // Even if the IRemotelyProvisionedComponent HAL is implemented, it doesn't mean that the keys
156     // may be fetched via the key pool. The HAL must be a new version that exports a unique id. If
157     // none of the HALs support this, then the key pool service is not published.
158     match RemotelyProvisionedKeyPoolService::new_native_binder() {
159         Ok(key_pool_service) => {
160             binder::add_service(
161                 REMOTELY_PROVISIONED_KEY_POOL_SERVICE_NAME,
162                 key_pool_service.as_binder(),
163             )
164             .unwrap_or_else(|e| {
165                 panic!(
166                     "Failed to register service {} because of {:?}.",
167                     REMOTELY_PROVISIONED_KEY_POOL_SERVICE_NAME, e
168                 );
169             });
170         }
171         Err(e) => log::info!("Not publishing IRemotelyProvisionedKeyPool service: {:?}", e),
172     }
173 
174     binder::add_service(LEGACY_KEYSTORE_SERVICE_NAME, legacykeystore.as_binder()).unwrap_or_else(
175         |e| {
176             panic!(
177                 "Failed to register service {} because of {:?}.",
178                 LEGACY_KEYSTORE_SERVICE_NAME, e
179             );
180         },
181     );
182 
183     info!("Successfully registered Keystore 2.0 service.");
184 
185     info!("Joining thread pool now.");
186     binder::ProcessState::join_thread_pool();
187 }
188