1 /*
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
21 use anyhow::{ensure, Context, Result};
22 use clap::arg;
23 use dm::{crypt::CipherType, util};
24 use log::info;
25 use std::ffi::CString;
26 use std::fs::{create_dir_all, OpenOptions};
27 use std::io::{Error, Read, Write};
28 use std::os::unix::ffi::OsStrExt;
29 use std::os::unix::fs::FileTypeExt;
30 use std::path::{Path, PathBuf};
31 use std::process::Command;
32
33 const MK2FS_BIN: &str = "/system/bin/mke2fs";
34 const UNFORMATTED_STORAGE_MAGIC: &str = "UNFORMATTED-STORAGE";
35
main() -> Result<()>36 fn 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
44 let matches = clap_command().get_matches();
45
46 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());
49 // Note this error context is used in MicrodroidTests.
50 encryptedstore_init(blkdevice, key, mountpoint).context(format!(
51 "Unable to initialize encryptedstore on {:?} & mount at {:?}",
52 blkdevice, mountpoint
53 ))?;
54 Ok(())
55 }
56
clap_command() -> clap::Command57 fn 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
encryptedstore_init(blkdevice: &Path, key: &str, mountpoint: &Path) -> Result<()>65 fn encryptedstore_init(blkdevice: &Path, key: &str, mountpoint: &Path) -> Result<()> {
66 ensure!(
67 std::fs::metadata(blkdevice)
68 .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
75 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))?;
86 Ok(())
87 }
88
enable_crypt(data_device: &Path, key: &str, name: &str) -> Result<PathBuf>89 fn enable_crypt(data_device: &Path, key: &str, name: &str) -> Result<PathBuf> {
90 let dev_size = util::blkgetsize64(data_device)?;
91 let key = hex::decode(key).context("Unable to decode hex key")?;
92
93 // Create the dm-crypt spec
94 let target = dm::crypt::DmCryptTargetBuilder::default()
95 .data_device(data_device, dev_size)
96 .cipher(CipherType::AES256HCTR2)
97 .key(&key)
98 .opt_param("sector_size:4096")
99 .opt_param("iv_large_sectors")
100 .build()
101 .context("Couldn't build the DMCrypt target")?;
102 let dm = dm::DeviceMapper::new()?;
103 dm.create_crypt_device(name, &target).context("Failed to create dm-crypt device")
104 }
105
106 // 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.
needs_formatting(data_device: &Path) -> Result<bool>108 fn 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
format_ext4(device: &Path) -> Result<()>126 fn format_ext4(device: &Path) -> Result<()> {
127 let mkfs_options = [
128 "-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
135 ];
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);
143 Ok(())
144 }
145
mount(source: &Path, mountpoint: &Path) -> Result<()>146 fn mount(source: &Path, mountpoint: &Path) -> Result<()> {
147 create_dir_all(mountpoint).context(format!("Failed to create {:?}", &mountpoint))?;
148 let mount_options = CString::new(
149 "fscontext=u:object_r:encryptedstore_fs:s0,context=u:object_r:encryptedstore_file:s0",
150 )
151 .unwrap();
152 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
156 let ret = unsafe {
157 libc::mount(
158 source.as_ptr(),
159 mountpoint.as_ptr(),
160 fstype.as_ptr(),
161 libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC,
162 mount_options.as_ptr() as *const std::ffi::c_void,
163 )
164 };
165 if ret < 0 {
166 Err(Error::last_os_error()).context("mount failed")
167 } else {
168 Ok(())
169 }
170 }
171
172 #[cfg(test)]
173 mod tests {
174 use super::*;
175
176 #[test]
verify_command()177 fn verify_command() {
178 // Check that the command parsing has been configured in a valid way.
179 clap_command().debug_assert();
180 }
181 }
182