blob: 5f27fd79a6705dff4b6fcf6b737cc25d3fcd96c4 [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};
22use clap::{arg, App};
23use dm::{crypt::CipherType, util};
24use 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
44 let matches = App::new("encryptedstore")
45 .args(&[
46 arg!(--blkdevice <FILE> "the block device backing the encrypted storage")
47 .required(true),
Shikha Panwar195f89c2022-11-23 16:20:34 +000048 arg!(--key <KEY> "key (in hex) equivalent to 32 bytes)").required(true),
Shikha Panwar9fd198f2022-11-18 17:43:43 +000049 arg!(--mountpoint <MOUNTPOINT> "mount point for the storage").required(true),
Shikha Panwar566c9672022-11-15 14:39:58 +000050 ])
51 .get_matches();
52
53 let blkdevice = Path::new(matches.value_of("blkdevice").unwrap());
54 let key = matches.value_of("key").unwrap();
Shikha Panwar9fd198f2022-11-18 17:43:43 +000055 let mountpoint = Path::new(matches.value_of("mountpoint").unwrap());
56 encryptedstore_init(blkdevice, key, mountpoint).context(format!(
57 "Unable to initialize encryptedstore on {:?} & mount at {:?}",
58 blkdevice, mountpoint
59 ))?;
60 Ok(())
61}
62
63fn encryptedstore_init(blkdevice: &Path, key: &str, mountpoint: &Path) -> Result<()> {
Shikha Panwar566c9672022-11-15 14:39:58 +000064 ensure!(
65 std::fs::metadata(&blkdevice)
66 .context(format!("Failed to get metadata of {:?}", blkdevice))?
67 .file_type()
68 .is_block_device(),
69 "The path:{:?} is not of a block device",
70 blkdevice
71 );
72
Shikha Panwar9fd198f2022-11-18 17:43:43 +000073 let needs_formatting =
74 needs_formatting(blkdevice).context("Unable to check if formatting is required")?;
75 let crypt_device =
76 enable_crypt(blkdevice, key, "cryptdev").context("Unable to map crypt device")?;
77
78 // We might need to format it with filesystem if this is a "seen-for-the-first-time" device.
79 if needs_formatting {
80 info!("Freshly formatting the crypt device");
81 format_ext4(&crypt_device)?;
82 }
83 mount(&crypt_device, mountpoint).context(format!("Unable to mount {:?}", crypt_device))?;
Shikha Panwar566c9672022-11-15 14:39:58 +000084 Ok(())
85}
86
Shikha Panwar9fd198f2022-11-18 17:43:43 +000087fn enable_crypt(data_device: &Path, key: &str, name: &str) -> Result<PathBuf> {
Shikha Panwar566c9672022-11-15 14:39:58 +000088 let dev_size = util::blkgetsize64(data_device)?;
89 let key = hex::decode(key).context("Unable to decode hex key")?;
Shikha Panwar195f89c2022-11-23 16:20:34 +000090 ensure!(key.len() == 32, "We need 32 bytes' key for aes-hctr2 cipher for block encryption");
Shikha Panwar566c9672022-11-15 14:39:58 +000091
92 // Create the dm-crypt spec
93 let target = dm::crypt::DmCryptTargetBuilder::default()
94 .data_device(data_device, dev_size)
Shikha Panwar195f89c2022-11-23 16:20:34 +000095 .cipher(CipherType::AES256HCTR2)
Shikha Panwar566c9672022-11-15 14:39:58 +000096 .key(&key)
97 .build()
98 .context("Couldn't build the DMCrypt target")?;
99 let dm = dm::DeviceMapper::new()?;
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000100 dm.create_crypt_device(name, &target).context("Failed to create dm-crypt device")
101}
Shikha Panwar566c9672022-11-15 14:39:58 +0000102
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000103// The disk contains UNFORMATTED_STORAGE_MAGIC to indicate we need to format the crypt device.
104// This function looks for it, zeroing it, if present.
105fn needs_formatting(data_device: &Path) -> Result<bool> {
106 let mut file = OpenOptions::new()
107 .read(true)
108 .write(true)
109 .open(data_device)
110 .with_context(|| format!("Failed to open {:?}", data_device))?;
111
112 let mut buf = [0; UNFORMATTED_STORAGE_MAGIC.len()];
113 file.read_exact(&mut buf)?;
114
115 if buf == UNFORMATTED_STORAGE_MAGIC.as_bytes() {
116 buf.fill(0);
117 file.write_all(&buf)?;
118 return Ok(true);
119 }
120 Ok(false)
121}
122
123fn format_ext4(device: &Path) -> Result<()> {
124 let mkfs_options = [
125 "-j", // Create appropriate sized journal
126 "-O metadata_csum", // Metadata checksum for filesystem integrity
127 ];
128 let mut cmd = Command::new(MK2FS_BIN);
129 let status = cmd
130 .args(mkfs_options)
131 .arg(device)
132 .status()
133 .context(format!("failed to execute {}", MK2FS_BIN))?;
134 ensure!(status.success(), "mkfs failed with {:?}", status);
Shikha Panwar566c9672022-11-15 14:39:58 +0000135 Ok(())
136}
Shikha Panwar9fd198f2022-11-18 17:43:43 +0000137
138fn mount(source: &Path, mountpoint: &Path) -> Result<()> {
139 create_dir_all(mountpoint).context(format!("Failed to create {:?}", &mountpoint))?;
140 let mount_options = CString::new("").unwrap();
141 let source = CString::new(source.as_os_str().as_bytes())?;
142 let mountpoint = CString::new(mountpoint.as_os_str().as_bytes())?;
143 let fstype = CString::new("ext4").unwrap();
144
145 let ret = unsafe {
146 libc::mount(
147 source.as_ptr(),
148 mountpoint.as_ptr(),
149 fstype.as_ptr(),
150 libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC,
151 mount_options.as_ptr() as *const std::ffi::c_void,
152 )
153 };
154 if ret < 0 {
155 Err(Error::last_os_error()).context("mount failed")
156 } else {
157 Ok(())
158 }
159}