Janis Danisevskis | 77d7204 | 2021-01-20 15:36:30 -0800 | [diff] [blame^] | 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 | //! Implements the android.security.vpnprofilestore interface. |
| 16 | |
| 17 | use android_security_vpnprofilestore::aidl::android::security::vpnprofilestore::{ |
| 18 | IVpnProfileStore::BnVpnProfileStore, IVpnProfileStore::IVpnProfileStore, |
| 19 | IVpnProfileStore::ERROR_PROFILE_NOT_FOUND, IVpnProfileStore::ERROR_SYSTEM_ERROR, |
| 20 | }; |
| 21 | use android_security_vpnprofilestore::binder::{Result as BinderResult, Status as BinderStatus}; |
| 22 | use anyhow::{Context, Result}; |
| 23 | use binder::{ExceptionCode, Strong, ThreadState}; |
| 24 | use rusqlite::{ |
| 25 | params, Connection, OptionalExtension, Transaction, TransactionBehavior, NO_PARAMS, |
| 26 | }; |
| 27 | use std::path::{Path, PathBuf}; |
| 28 | |
| 29 | struct DB { |
| 30 | conn: Connection, |
| 31 | } |
| 32 | |
| 33 | impl DB { |
| 34 | fn new(db_file: &Path) -> Result<Self> { |
| 35 | let mut db = Self { |
| 36 | conn: Connection::open(db_file).context("Failed to initialize SQLite connection.")?, |
| 37 | }; |
| 38 | db.init_tables().context("Trying to initialize vpnstore db.")?; |
| 39 | Ok(db) |
| 40 | } |
| 41 | |
| 42 | fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T> |
| 43 | where |
| 44 | F: Fn(&Transaction) -> Result<T>, |
| 45 | { |
| 46 | loop { |
| 47 | match self |
| 48 | .conn |
| 49 | .transaction_with_behavior(behavior) |
| 50 | .context("In with_transaction.") |
| 51 | .and_then(|tx| f(&tx).map(|result| (result, tx))) |
| 52 | .and_then(|(result, tx)| { |
| 53 | tx.commit().context("In with_transaction: Failed to commit transaction.")?; |
| 54 | Ok(result) |
| 55 | }) { |
| 56 | Ok(result) => break Ok(result), |
| 57 | Err(e) => { |
| 58 | if Self::is_locked_error(&e) { |
| 59 | std::thread::sleep(std::time::Duration::from_micros(500)); |
| 60 | continue; |
| 61 | } else { |
| 62 | return Err(e).context("In with_transaction."); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | fn is_locked_error(e: &anyhow::Error) -> bool { |
| 70 | matches!(e.root_cause().downcast_ref::<rusqlite::ffi::Error>(), |
| 71 | Some(rusqlite::ffi::Error { |
| 72 | code: rusqlite::ErrorCode::DatabaseBusy, |
| 73 | .. |
| 74 | }) |
| 75 | | Some(rusqlite::ffi::Error { |
| 76 | code: rusqlite::ErrorCode::DatabaseLocked, |
| 77 | .. |
| 78 | })) |
| 79 | } |
| 80 | |
| 81 | fn init_tables(&mut self) -> Result<()> { |
| 82 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 83 | tx.execute( |
| 84 | "CREATE TABLE IF NOT EXISTS profiles ( |
| 85 | owner INTEGER, |
| 86 | alias BLOB, |
| 87 | profile BLOB, |
| 88 | UNIQUE(owner, alias));", |
| 89 | NO_PARAMS, |
| 90 | ) |
| 91 | .context("Failed to initialize \"profiles\" table.")?; |
| 92 | Ok(()) |
| 93 | }) |
| 94 | } |
| 95 | |
| 96 | fn list(&mut self, caller_uid: u32) -> Result<Vec<String>> { |
| 97 | self.with_transaction(TransactionBehavior::Deferred, |tx| { |
| 98 | let mut stmt = tx |
| 99 | .prepare("SELECT alias FROM profiles WHERE owner = ? ORDER BY alias ASC;") |
| 100 | .context("In list: Failed to prepare statement.")?; |
| 101 | |
| 102 | let aliases = stmt |
| 103 | .query_map(params![caller_uid], |row| row.get(0))? |
| 104 | .collect::<rusqlite::Result<Vec<String>>>() |
| 105 | .context("In list: query_map failed."); |
| 106 | aliases |
| 107 | }) |
| 108 | } |
| 109 | |
| 110 | fn put(&mut self, caller_uid: u32, alias: &str, profile: &[u8]) -> Result<()> { |
| 111 | self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 112 | tx.execute( |
| 113 | "INSERT OR REPLACE INTO profiles (owner, alias, profile) values (?, ?, ?)", |
| 114 | params![caller_uid, alias, profile,], |
| 115 | ) |
| 116 | .context("In put: Failed to insert or replace.")?; |
| 117 | Ok(()) |
| 118 | }) |
| 119 | } |
| 120 | |
| 121 | fn get(&mut self, caller_uid: u32, alias: &str) -> Result<Option<Vec<u8>>> { |
| 122 | self.with_transaction(TransactionBehavior::Deferred, |tx| { |
| 123 | tx.query_row( |
| 124 | "SELECT profile FROM profiles WHERE owner = ? AND alias = ?;", |
| 125 | params![caller_uid, alias], |
| 126 | |row| row.get(0), |
| 127 | ) |
| 128 | .optional() |
| 129 | .context("In get: failed loading profile.") |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | fn remove(&mut self, caller_uid: u32, alias: &str) -> Result<bool> { |
| 134 | let removed = self.with_transaction(TransactionBehavior::Immediate, |tx| { |
| 135 | tx.execute( |
| 136 | "DELETE FROM profiles WHERE owner = ? AND alias = ?;", |
| 137 | params![caller_uid, alias], |
| 138 | ) |
| 139 | .context("In remove: Failed to delete row.") |
| 140 | })?; |
| 141 | Ok(removed == 1) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | /// This is the main VpnProfileStore error type, it wraps binder exceptions and the |
| 146 | /// VnpStore errors. |
| 147 | #[derive(Debug, thiserror::Error, PartialEq)] |
| 148 | pub enum Error { |
| 149 | /// Wraps a VpnProfileStore error code. |
| 150 | #[error("Error::Error({0:?})")] |
| 151 | Error(i32), |
| 152 | /// Wraps a Binder exception code other than a service specific exception. |
| 153 | #[error("Binder exception code {0:?}, {1:?}")] |
| 154 | Binder(ExceptionCode, i32), |
| 155 | } |
| 156 | |
| 157 | impl Error { |
| 158 | /// Short hand for `Error::Error(ERROR_SYSTEM_ERROR)` |
| 159 | pub fn sys() -> Self { |
| 160 | Error::Error(ERROR_SYSTEM_ERROR) |
| 161 | } |
| 162 | |
| 163 | /// Short hand for `Error::Error(ERROR_PROFILE_NOT_FOUND)` |
| 164 | pub fn not_found() -> Self { |
| 165 | Error::Error(ERROR_PROFILE_NOT_FOUND) |
| 166 | } |
| 167 | } |
| 168 | |
| 169 | /// This function should be used by vpnprofilestore service calls to translate error conditions |
| 170 | /// into service specific exceptions. |
| 171 | /// |
| 172 | /// All error conditions get logged by this function. |
| 173 | /// |
| 174 | /// `Error::Error(x)` variants get mapped onto a service specific error code of `x`. |
| 175 | /// |
| 176 | /// All non `Error` error conditions get mapped onto `ERROR_SYSTEM_ERROR`. |
| 177 | /// |
| 178 | /// `handle_ok` will be called if `result` is `Ok(value)` where `value` will be passed |
| 179 | /// as argument to `handle_ok`. `handle_ok` must generate a `BinderResult<T>`, but it |
| 180 | /// typically returns Ok(value). |
| 181 | fn map_or_log_err<T, U, F>(result: Result<U>, handle_ok: F) -> BinderResult<T> |
| 182 | where |
| 183 | F: FnOnce(U) -> BinderResult<T>, |
| 184 | { |
| 185 | result.map_or_else( |
| 186 | |e| { |
| 187 | log::error!("{:#?}", e); |
| 188 | let root_cause = e.root_cause(); |
| 189 | let rc = match root_cause.downcast_ref::<Error>() { |
| 190 | Some(Error::Error(e)) => *e, |
| 191 | Some(Error::Binder(_, _)) | None => ERROR_SYSTEM_ERROR, |
| 192 | }; |
| 193 | Err(BinderStatus::new_service_specific_error(rc, None)) |
| 194 | }, |
| 195 | handle_ok, |
| 196 | ) |
| 197 | } |
| 198 | |
| 199 | // TODO make sure that ALIASES have a prefix of VPN_ PLATFORM_VPN_ or |
| 200 | // is equal to LOCKDOWN_VPN. |
| 201 | |
| 202 | /// Implements IVpnProfileStore AIDL interface. |
| 203 | pub struct VpnProfileStore { |
| 204 | db_path: PathBuf, |
| 205 | } |
| 206 | |
| 207 | impl VpnProfileStore { |
| 208 | /// Creates a new VpnProfileStore instance. |
| 209 | pub fn new_native_binder(db_path: &Path) -> Strong<dyn IVpnProfileStore> { |
| 210 | let mut db_path = path.to_path_buf(); |
| 211 | db_path.push("vpnprofilestore.sqlite"); |
| 212 | BnVpnProfileStore::new_binder(Self { db_path }) |
| 213 | } |
| 214 | |
| 215 | fn open_db(&self) -> Result<DB> { |
| 216 | DB::new(&self.db_path).context("In open_db: Failed to open db.") |
| 217 | } |
| 218 | |
| 219 | fn get(&self, alias: &str) -> Result<Vec<u8>> { |
| 220 | let mut db = self.open_db().context("In get.")?; |
| 221 | let calling_uid = ThreadState::get_calling_uid(); |
| 222 | db.get(calling_uid, alias) |
| 223 | .context("In get: Trying to load profile from DB.")? |
| 224 | .ok_or_else(Error::not_found) |
| 225 | .context("In get: No such profile.") |
| 226 | } |
| 227 | |
| 228 | fn put(&self, alias: &str, profile: &[u8]) -> Result<()> { |
| 229 | let mut db = self.open_db().context("In put.")?; |
| 230 | let calling_uid = ThreadState::get_calling_uid(); |
| 231 | db.put(calling_uid, alias, profile).context("In put: Trying to insert profile into DB.") |
| 232 | } |
| 233 | |
| 234 | fn remove(&self, alias: &str) -> Result<()> { |
| 235 | let mut db = self.open_db().context("In remove.")?; |
| 236 | let calling_uid = ThreadState::get_calling_uid(); |
| 237 | let removed = db |
| 238 | .remove(calling_uid, alias) |
| 239 | .context("In remove: Trying to remove profile from DB.")?; |
| 240 | if removed { |
| 241 | Ok(()) |
| 242 | } else { |
| 243 | Err(Error::not_found()).context("In remove: No such profile.") |
| 244 | } |
| 245 | } |
| 246 | |
| 247 | fn list(&self, prefix: &str) -> Result<Vec<String>> { |
| 248 | let mut db = self.open_db().context("In list.")?; |
| 249 | let calling_uid = ThreadState::get_calling_uid(); |
| 250 | Ok(db |
| 251 | .list(calling_uid) |
| 252 | .context("In list: Trying to get list of profiles.")? |
| 253 | .into_iter() |
| 254 | .filter(|s| s.starts_with(prefix)) |
| 255 | .collect()) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | impl binder::Interface for VpnProfileStore {} |
| 260 | |
| 261 | impl IVpnProfileStore for VpnProfileStore { |
| 262 | fn get(&self, alias: &str) -> BinderResult<Vec<u8>> { |
| 263 | map_or_log_err(self.get(alias), Ok) |
| 264 | } |
| 265 | fn put(&self, alias: &str, profile: &[u8]) -> BinderResult<()> { |
| 266 | map_or_log_err(self.put(alias, profile), Ok) |
| 267 | } |
| 268 | fn remove(&self, alias: &str) -> BinderResult<()> { |
| 269 | map_or_log_err(self.remove(alias), Ok) |
| 270 | } |
| 271 | fn list(&self, prefix: &str) -> BinderResult<Vec<String>> { |
| 272 | map_or_log_err(self.list(prefix), Ok) |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | #[cfg(test)] |
| 277 | mod db_test { |
| 278 | use super::*; |
| 279 | use keystore2_test_utils::TempDir; |
| 280 | |
| 281 | static TEST_BLOB1: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]; |
| 282 | static TEST_BLOB2: &[u8] = &[2, 2, 3, 4, 5, 6, 7, 8, 9, 0]; |
| 283 | static TEST_BLOB3: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0]; |
| 284 | static TEST_BLOB4: &[u8] = &[3, 2, 3, 4, 5, 6, 7, 8, 9, 0]; |
| 285 | |
| 286 | #[test] |
| 287 | fn test_profile_db() { |
| 288 | let test_dir = TempDir::new("profiledb_test_").expect("Failed to create temp dir."); |
| 289 | let mut db = |
| 290 | DB::new(&test_dir.build().push("vpnprofile.sqlite")).expect("Failed to open database."); |
| 291 | |
| 292 | // Insert three profiles for owner 2. |
| 293 | db.put(2, "test1", TEST_BLOB1).expect("Failed to insert test1."); |
| 294 | db.put(2, "test2", TEST_BLOB2).expect("Failed to insert test2."); |
| 295 | db.put(2, "test3", TEST_BLOB3).expect("Failed to insert test3."); |
| 296 | |
| 297 | // Check list returns all inserted aliases. |
| 298 | assert_eq!( |
| 299 | vec!["test1".to_string(), "test2".to_string(), "test3".to_string(),], |
| 300 | db.list(2).expect("Failed to list profiles.") |
| 301 | ); |
| 302 | |
| 303 | // There should be no profiles for owner 1. |
| 304 | assert_eq!(Vec::<String>::new(), db.list(1).expect("Failed to list profiles.")); |
| 305 | |
| 306 | // Check the content of the three entries. |
| 307 | assert_eq!( |
| 308 | Some(TEST_BLOB1), |
| 309 | db.get(2, "test1").expect("Failed to get profile.").as_deref() |
| 310 | ); |
| 311 | assert_eq!( |
| 312 | Some(TEST_BLOB2), |
| 313 | db.get(2, "test2").expect("Failed to get profile.").as_deref() |
| 314 | ); |
| 315 | assert_eq!( |
| 316 | Some(TEST_BLOB3), |
| 317 | db.get(2, "test3").expect("Failed to get profile.").as_deref() |
| 318 | ); |
| 319 | |
| 320 | // Remove test2 and check and check that it is no longer retrievable. |
| 321 | assert!(db.remove(2, "test2").expect("Failed to remove profile.")); |
| 322 | assert!(db.get(2, "test2").expect("Failed to get profile.").is_none()); |
| 323 | |
| 324 | // test2 should now no longer be in the list. |
| 325 | assert_eq!( |
| 326 | vec!["test1".to_string(), "test3".to_string(),], |
| 327 | db.list(2).expect("Failed to list profiles.") |
| 328 | ); |
| 329 | |
| 330 | // Put on existing alias replaces it. |
| 331 | // Verify test1 is TEST_BLOB1. |
| 332 | assert_eq!( |
| 333 | Some(TEST_BLOB1), |
| 334 | db.get(2, "test1").expect("Failed to get profile.").as_deref() |
| 335 | ); |
| 336 | db.put(2, "test1", TEST_BLOB4).expect("Failed to replace test1."); |
| 337 | // Verify test1 is TEST_BLOB4. |
| 338 | assert_eq!( |
| 339 | Some(TEST_BLOB4), |
| 340 | db.get(2, "test1").expect("Failed to get profile.").as_deref() |
| 341 | ); |
| 342 | } |
| 343 | } |