blob: 1a16f49bfa897eb1fc9ffc01b6d253154dbddaac [file] [log] [blame]
Shikha Panwar566c9672022-11-15 14:39:58 +00001/*
2 * Copyright (C) 2022 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//! `encryptedstore` is a program that (as the name indicates) provides encrypted storage
18//! solution in a VM. This is based on dm-crypt & requires the (64 bytes') key & the backing device.
19//! It uses dm_rust lib.
20
21use anyhow::{ensure, Context, Result};
Andrew Walbranaa1efc42022-08-10 13:33:57 +000022use clap::arg;
23use dm::{crypt::CipherType, util};
Shikha Panwar566c9672022-11-15 14:39:58 +000024use log::info;
Shikha Panwar9fd198f2022-11-18 17:43:43 +000025use std::ffi::CString;
26use std::fs::{create_dir_all, OpenOptions};
27use std::io::{Error, Read, Write};
28use std::os::unix::ffi::OsStrExt;
Shikha Panwar566c9672022-11-15 14:39:58 +000029use std::os::unix::fs::FileTypeExt;
Shikha Panwar9fd198f2022-11-18 17:43:43 +000030use std::path::{Path, PathBuf};
31use std::process::Command;
32
33const MK2FS_BIN: &str = "/system/bin/mke2fs";
34const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
Shikha Panwar566c9672022-11-15 14:39:58 +000035
36fn main() -> Result<()> {
37 android_logger::init_once(
38 android_logger::Config::default()
39 .with_tag("encryptedstore")
40 .with_min_level(log::Level::Info),
41 );
42 info!("Starting encryptedstore binary");
43
Andrew Walbranaa1efc42022-08-10 13:33:57 +000044 let matches = clap_command().get_matches();
Shikha Panwar566c9672022-11-15 14:39:58 +000045
Andrew Walbranaa1efc42022-08-10 13:33:57 +000046 let blkdevice = Path::new(matches.get_one::<String>("blkdevice").unwrap());
47 let key = matches.get_one::<String>("key").unwrap();
48 let mountpoint = Path::new(matches.get_one::<String>("mountpoint").unwrap());
Shikha Panwar405aa692023-02-07 20:52:47 +000049 // Note this error context is used in MicrodroidTests.
Shikha Panwar9fd198f2022-11-18 17:43:43 +000050 encryptedstore_init(blkdevice, key, mountpoint).context(format!(
51 "Unable to initialize encryptedstore on {:?} & mount at {:?}",
52 blkdevice, mountpoint
53 ))?;
54 Ok(())
55}
56
Andrew Walbranaa1efc42022-08-10 13:33:57 +000057fn clap_command() -> clap::Command {
58 clap::Command::new("encryptedstore").args(&[
59 arg!(--blkdevice <FILE> "the block device backing the encrypted storage").required(true),
60 arg!(--key <KEY> "key (in hex) equivalent to 32 bytes)").required(true),
61 arg!(--mountpoint <MOUNTPOINT> "mount point for the storage").required(true),
62 ])
63}
64
Shikha Panwar9fd198f2022-11-18 17:43:43 +000065fn encryptedstore_init(blkdevice: &Path, key: &str, mountpoint: &Path) -> Result<()> {
Shikha Panwar566c9672022-11-15 14:39:58 +000066 ensure!(
Andrew Walbran48294fb2023-01-16 12:01:53 +000067 std::fs::metadata(blkdevice)
Shikha Panwar566c9672022-11-15 14:39:58 +000068 .context(format!("Failed to get metadata of {:?}", blkdevice))?
69 .file_type()
70 .is_block_device(),
71 "The path:{:?} is not of a block device",
72 blkdevice
73 );
74
Shikha Panwar9fd198f2022-11-18 17:43:43 +000075 let needs_formatting =
76 needs_formatting(blkdevice).context("Unable to check if formatting is required")?;
77 let crypt_device =
78 enable_crypt(blkdevice, key, "cryptdev").context("Unable to map crypt device")?;
79
80 // We might need to format it with filesystem if this is a "seen-for-the-first-time" device.
81 if needs_formatting {
82 info!("Freshly formatting the crypt device");
83 format_ext4(&crypt_device)?;
84 }
85 mount(&crypt_device, mountpoint).context(format!("Unable to mount {:?}", crypt_device))?;
Shikha Panwar566c9672022-11-15 14:39:58 +000086 Ok(())
87}
88
Shikha Panwar9fd198f2022-11-18 17:43:43 +000089fn enable_crypt(data_device: &Path, key: &str, name: &str) -> Result<PathBuf> {
Shikha Panwar566c9672022-11-15 14:39:58 +000090 let dev_size = util::blkgetsize64(data_device)?;
91 let key = hex::decode(key).context("Unable to decode hex key")?;
Shikha Panwar566c9672022-11-15 14:39:58 +000092
93 // Create the dm-crypt spec
94 let target = dm::crypt::DmCryptTargetBuilder::default()
95 .data_device(data_device, dev_size)
Shikha Panwar195f89c2022-11-23 16:20:34 +000096 .cipher(CipherType::AES256HCTR2)
Shikha Panwar566c9672022-11-15 14:39:58 +000097 .key(&key)
Shikha Panwar6337d5b2023-02-09 13:02:33 +000098 .opt_param("sector_size:4096")
99 .opt_param("iv_large_sectors")
Shikha Panwar566c9672022-11-15 14:39:58 +0000100 .build()
101 .context("Couldn't build the DMCrypt target")?;
102 let dm = dm::DeviceMapper::new()?;
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000103 dm.create_crypt_device(name, &target).context("Failed to create dm-crypt device")
104}
Shikha Panwar566c9672022-11-15 14:39:58 +0000105
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000106// The disk contains UNFORMATTED_STORAGE_MAGIC to indicate we need to format the crypt device.
107// This function looks for it, zeroing it, if present.
108fn needs_formatting(data_device: &Path) -> Result<bool> {
109 let mut file = OpenOptions::new()
110 .read(true)
111 .write(true)
112 .open(data_device)
113 .with_context(|| format!("Failed to open {:?}", data_device))?;
114
115 let mut buf = [0; UNFORMATTED_STORAGE_MAGIC.len()];
116 file.read_exact(&mut buf)?;
117
118 if buf == UNFORMATTED_STORAGE_MAGIC.as_bytes() {
119 buf.fill(0);
120 file.write_all(&buf)?;
121 return Ok(true);
122 }
123 Ok(false)
124}
125
126fn format_ext4(device: &Path) -> Result<()> {
127 let mkfs_options = [
Shikha Panwarab8591a2023-03-27 18:46:48 +0000128 "-j", // Create appropriate sized journal
129 /* metadata_csum: enabled for filesystem integrity
130 * extents: Not enabling extents reduces the coverage of metadata checksumming.
131 * 64bit: larger fields afforded by this feature enable full-strength checksumming.
132 */
133 "-O metadata_csum, extents, 64bit",
134 "-b 4096", // block size in the filesystem
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000135 ];
136 let mut cmd = Command::new(MK2FS_BIN);
137 let status = cmd
138 .args(mkfs_options)
139 .arg(device)
140 .status()
141 .context(format!("failed to execute {}", MK2FS_BIN))?;
142 ensure!(status.success(), "mkfs failed with {:?}", status);
Shikha Panwar566c9672022-11-15 14:39:58 +0000143 Ok(())
144}
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000145
146fn mount(source: &Path, mountpoint: &Path) -> Result<()> {
147 create_dir_all(mountpoint).context(format!("Failed to create {:?}", &mountpoint))?;
Shikha Panward4ce1c02022-12-08 18:05:21 +0000148 let mount_options = CString::new(
149 "fscontext=u:object_r:encryptedstore_fs:s0,context=u:object_r:encryptedstore_file:s0",
150 )
151 .unwrap();
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000152 let source = CString::new(source.as_os_str().as_bytes())?;
153 let mountpoint = CString::new(mountpoint.as_os_str().as_bytes())?;
154 let fstype = CString::new("ext4").unwrap();
155
Andrew Walbranae3350d2023-07-21 19:01:18 +0100156 // SAFETY: The source, target and filesystemtype are valid C strings. For ext4, data is expected
157 // to be a C string as well, which it is. None of these pointers are retained after mount
158 // returns.
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000159 let ret = unsafe {
160 libc::mount(
161 source.as_ptr(),
162 mountpoint.as_ptr(),
163 fstype.as_ptr(),
164 libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC,
165 mount_options.as_ptr() as *const std::ffi::c_void,
166 )
167 };
168 if ret < 0 {
169 Err(Error::last_os_error()).context("mount failed")
170 } else {
171 Ok(())
172 }
173}
Andrew Walbranaa1efc42022-08-10 13:33:57 +0000174
175#[cfg(test)]
176mod tests {
177 use super::*;
178
179 #[test]
180 fn verify_command() {
181 // Check that the command parsing has been configured in a valid way.
182 clap_command().debug_assert();
183 }
184}