blob: 9a701ed95b771dcc7bdaff8a7d2abdf0ebf3355b [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;
25use std::os::unix::fs::FileTypeExt;
26use std::path::Path;
27
28fn main() -> Result<()> {
29 android_logger::init_once(
30 android_logger::Config::default()
31 .with_tag("encryptedstore")
32 .with_min_level(log::Level::Info),
33 );
34 info!("Starting encryptedstore binary");
35
36 let matches = App::new("encryptedstore")
37 .args(&[
38 arg!(--blkdevice <FILE> "the block device backing the encrypted storage")
39 .required(true),
40 arg!(--key <KEY> "key (in hex) equivalent to 64 bytes)").required(true),
41 ])
42 .get_matches();
43
44 let blkdevice = Path::new(matches.value_of("blkdevice").unwrap());
45 let key = matches.value_of("key").unwrap();
46 ensure!(
47 std::fs::metadata(&blkdevice)
48 .context(format!("Failed to get metadata of {:?}", blkdevice))?
49 .file_type()
50 .is_block_device(),
51 "The path:{:?} is not of a block device",
52 blkdevice
53 );
54
55 enable_crypt(blkdevice, key, "cryptdev")?;
56 Ok(())
57}
58
59fn enable_crypt(data_device: &Path, key: &str, name: &str) -> Result<()> {
60 let dev_size = util::blkgetsize64(data_device)?;
61 let key = hex::decode(key).context("Unable to decode hex key")?;
62 ensure!(key.len() == 64, "We need 64 bytes' key for aes-xts cipher for block encryption");
63
64 // Create the dm-crypt spec
65 let target = dm::crypt::DmCryptTargetBuilder::default()
66 .data_device(data_device, dev_size)
67 .cipher(CipherType::AES256XTS) // TODO(b/259253336) Move to HCTR2 based encryption.
68 .key(&key)
69 .build()
70 .context("Couldn't build the DMCrypt target")?;
71 let dm = dm::DeviceMapper::new()?;
72 dm.create_crypt_device(name, &target).context("Failed to create dm-crypt device")?;
73
74 Ok(())
75}