blob: 9b715a55a48a044e12ceba7db57c79674744d0d2 [file] [log] [blame]
Shikha Panwar27cb7e72022-10-13 20:34:45 +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/// `crypt` module implements the "crypt" target in the device mapper framework. Specifically,
18/// it provides `DmCryptTargetBuilder` struct which is used to construct a `DmCryptTarget` struct
19/// which is then given to `DeviceMapper` to create a mapper device.
20use crate::util::*;
21use crate::DmTargetSpec;
22
23use anyhow::{bail, Context, Result};
24use data_model::DataInit;
25use std::io::Write;
26use std::mem::size_of;
27use std::path::Path;
28
29const SECTOR_SIZE: u64 = 512;
30
31// The UAPI for the crypt target is at:
32// Documentation/admin-guide/device-mapper/dm-crypt.rst
33
34/// Supported ciphers
35pub enum CipherType {
36 // TODO(b/253394457) Include ciphers with authenticated modes as well
37 AES256XTS,
38}
39
40pub struct DmCryptTarget(Box<[u8]>);
41
42impl DmCryptTarget {
43 /// Flatten into slice
44 pub fn as_slice(&self) -> &[u8] {
45 self.0.as_ref()
46 }
47}
48
49pub struct DmCryptTargetBuilder<'a> {
50 cipher: CipherType,
51 key: Option<&'a [u8]>,
52 iv_offset: u64,
53 device_path: Option<&'a Path>,
54 offset: u64,
55 device_size: u64,
56 // TODO(b/238179332) Extend this to include opt_params, in particular 'integrity'
57}
58
59impl<'a> Default for DmCryptTargetBuilder<'a> {
60 fn default() -> Self {
61 DmCryptTargetBuilder {
62 cipher: CipherType::AES256XTS,
63 key: None,
64 iv_offset: 0,
65 device_path: None,
66 offset: 0,
67 device_size: 0,
68 }
69 }
70}
71
72impl<'a> DmCryptTargetBuilder<'a> {
73 /// Sets the device that will be used as the data device (i.e. providing actual data).
74 pub fn data_device(&mut self, p: &'a Path, size: u64) -> &mut Self {
75 self.device_path = Some(p);
76 self.device_size = size;
77 self
78 }
79
80 /// Sets the encryption cipher.
81 pub fn cipher(&mut self, cipher: CipherType) -> &mut Self {
82 self.cipher = cipher;
83 self
84 }
85
86 /// Sets the key used for encryption. Input is byte array.
87 pub fn key(&mut self, key: &'a [u8]) -> &mut Self {
88 self.key = Some(key);
89 self
90 }
91
92 /// The IV offset is a sector count that is added to the sector number before creating the IV.
93 pub fn iv_offset(&mut self, iv_offset: u64) -> &mut Self {
94 self.iv_offset = iv_offset;
95 self
96 }
97
98 /// Starting sector within the device where the encrypted data begins
99 pub fn offset(&mut self, offset: u64) -> &mut Self {
100 self.offset = offset;
101 self
102 }
103
104 /// Constructs a `DmCryptTarget`.
105 pub fn build(&self) -> Result<DmCryptTarget> {
106 // The `DmCryptTarget` struct actually is a flattened data consisting of a header and
107 // body. The format of the header is `dm_target_spec` as defined in
108 // include/uapi/linux/dm-ioctl.h.
109 let device_path = self
110 .device_path
111 .context("data device is not set")?
112 .to_str()
113 .context("data device path is not encoded in utf8")?;
114
115 let key =
116 if let Some(key) = self.key { hexstring_from(key) } else { bail!("key is not set") };
117
118 // Step2: serialize the information according to the spec, which is ...
119 // DmTargetSpec{...}
120 // <cipher> <key> <iv_offset> <device path> \
121 // <offset> [<#opt_params> <opt_params>]
122 let mut body = String::new();
123 use std::fmt::Write;
124 write!(&mut body, "{} ", get_kernel_crypto_name(&self.cipher))?;
125 write!(&mut body, "{} ", key)?;
126 write!(&mut body, "{} ", self.iv_offset)?;
127 write!(&mut body, "{} ", device_path)?;
128 write!(&mut body, "{} ", self.offset)?;
129 write!(&mut body, "\0")?; // null terminator
130
131 let size = size_of::<DmTargetSpec>() + body.len();
132 let aligned_size = (size + 7) & !7; // align to 8 byte boundaries
133 let padding = aligned_size - size;
134
135 let mut header = DmTargetSpec::new("crypt")?;
136 header.sector_start = 0;
137 header.length = self.device_size / SECTOR_SIZE; // number of 512-byte sectors
138 header.next = aligned_size as u32;
139
140 let mut buf = Vec::with_capacity(aligned_size);
141 buf.write_all(header.as_slice())?;
142 buf.write_all(body.as_bytes())?;
143 buf.write_all(vec![0; padding].as_slice())?;
144
145 Ok(DmCryptTarget(buf.into_boxed_slice()))
146 }
147}
148
149fn get_kernel_crypto_name(cipher: &CipherType) -> &str {
150 match cipher {
151 CipherType::AES256XTS => "aes-xts-plain64",
152 }
153}