1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
// MIT License
//
// Copyright (c) 2022-2024 Robin Doer
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//! # The basic container
//!
//! This module contains types for the basic container handling. A
//! [`Container`] acts like an encrypted block device, where you can read and
//! write encrypted blocks of data. See the [`Container`] documentation for
//! details.
//!
//! The [`Container`] has no knowlege about the storage layer. Every type that
//! implements the [`Backend`] trait can act as the storage layer for the
//! [`Container`]. The [`Container`] receives (possibly) encrypted data from
//! the backend and pushes (possibly) encrypted data back to the backend.
//! See the [`backend` crate](nuts_backend) documentation for details.
//!
//! ## Create a container
//!
//! The [`Container::create()`] method is used to create a new container. It
//! expects an instance of a type that implements the [`Create`] trait, which
//! acts as a builder for the related [`Backend`].
//!
//! Example:
//!
//! ```rust
//! use nuts_container::*;
//! use nuts_memory::MemoryBackend;
//!
//! // Create a container with a memory backend.
//! let backend = MemoryBackend::new();
//!
//! // Let's create an encrypted container (with aes128-ctr).
//! // Because you are encrypting the container, you need to assign a
//! // password callback.
//! let kdf = Kdf::pbkdf2(Digest::Sha1, 65536, b"123");
//! let options = CreateOptionsBuilder::new(Cipher::Aes128Ctr)
//! .with_password_callback(|| Ok(b"abc".to_vec()))
//! .with_kdf(kdf.clone())
//! .build::<MemoryBackend>()
//! .unwrap();
//!
//! // Create the container and fetch information.
//! // Here you can directly pass the backend instance to the create() method
//! // because MemoryBackend implements the Backend::CreateOptions trait.
//! let container = Container::<MemoryBackend>::create(backend, options).unwrap();
//! let info = container.info().unwrap();
//!
//! assert_eq!(info.cipher, Cipher::Aes128Ctr);
//! assert_eq!(info.kdf, kdf);
//! ```
//!
//! ## Open a container
//!
//! The [`Container::open()`] method is used to open a container. It expects an
//! instance of a type that implements the [`Open`] trait, which acts as a
//! builder for the related [`Backend`].
//!
//! Example:
//!
//! ```rust
//! use nuts_container::*;
//! use nuts_memory::MemoryBackend;
//!
//! let (backend, kdf) = {
//! // In this example you create a container in a separate block.
//! // So, the created container is closed again when leaving the scope.
//! let backend = MemoryBackend::new();
//! let kdf = Kdf::pbkdf2(Digest::Sha1, 65536, b"123");
//! let options = CreateOptionsBuilder::new(Cipher::Aes128Ctr)
//! .with_password_callback(|| Ok(b"abc".to_vec()))
//! .with_kdf(kdf.clone())
//! .build::<MemoryBackend>()
//! .unwrap();
//!
//! // Create the container.
//! let container = Container::<MemoryBackend>::create(backend, options).unwrap();
//! let backend = container.into_backend();
//!
//! (backend, kdf)
//! };
//!
//! // Open the container and fetch information.
//! // Here you can directly pass the backend instance to the open() method
//! // because MemoryBackend implements the Backend::OpenOptions trait.
//! let options = OpenOptionsBuilder::new()
//! .with_password_callback(|| Ok(b"abc".to_vec()))
//! .build::<MemoryBackend>()
//! .unwrap();
//! let container = Container::<MemoryBackend>::open(backend, options).unwrap();
//! let info = container.info().unwrap();
//!
//! assert_eq!(info.cipher, Cipher::Aes128Ctr);
//! assert_eq!(info.kdf, kdf);
//! ```
//!
//! ## Read from a container
//!
//! ```rust
//! use nuts_container::*;
//! use nuts_memory::MemoryBackend;
//!
//! // Create a container with a memory backend.
//! let mut backend = MemoryBackend::new();
//!
//! // Insert a block into the backend.
//! // Note that the insert() method is a part of the MemoryBackend and directly
//! // inserts a block into the backend (bypassing the crypto capabilities of the
//! // container).
//! let id = backend.insert().unwrap();
//!
//! // Create the container.
//! let options = CreateOptionsBuilder::new(Cipher::None)
//! .build::<MemoryBackend>()
//! .unwrap();
//! let mut container = Container::<MemoryBackend>::create(backend, options).unwrap();
//!
//! // Read full block.
//! let mut buf = [b'x'; 512];
//! assert_eq!(container.read(&id, &mut buf).unwrap(), 512);
//! assert_eq!(buf, [0; 512]);
//!
//! // Read block into a buffer which is smaller than the block-size.
//! // The buffer is filled with the first 400 bytes from the block.
//! let mut buf = [b'x'; 400];
//! assert_eq!(container.read(&id, &mut buf).unwrap(), 400);
//! assert_eq!(buf, [0; 400]);
//!
//! // Read block into a buffer which is bigger than the block-size.
//! // The first 512 bytes are filled with the content of the block,
//! // the remaining 8 bytes are not touched.
//! let mut buf = [b'x'; 520];
//! assert_eq!(container.read(&id, &mut buf).unwrap(), 512);
//! assert_eq!(buf[..512], [0; 512]);
//! assert_eq!(buf[512..], [b'x'; 8]);
//! ```
//!
//! ## Write into a container
//!
//! ```rust
//! use nuts_container::*;
//! use nuts_memory::MemoryBackend;
//!
//! // In this example you create a container in a separate block.
//! // So, the created container is closed again when leaving the scope.
//! let mut backend = MemoryBackend::new();
//!
//! // Insert a block into the backend.
//! // Note that the insert() method is a part of the MemoryBackend and directly
//! // inserts a block into the backend (bypassing the crypto capabilities of the
//! // container).
//! let id = backend.insert().unwrap();
//!
//! // Create the container.
//! let options = CreateOptionsBuilder::new(Cipher::None)
//! .build::<MemoryBackend>()
//! .unwrap();
//! let mut container = Container::<MemoryBackend>::create(backend, options).unwrap();
//!
//! // Write a full block. The whole block is filled with 'x'.
//! assert_eq!(container.write(&id, &[b'x'; 512]).unwrap(), 512);
//!
//! let mut buf = [0; 512];
//! assert_eq!(container.read(&id, &mut buf).unwrap(), 512);
//! assert_eq!(buf, [b'x'; 512]);
//!
//! // Write a block from a buffer which is smaller than the block-size.
//! // The first bytes of the block are filled with the data from the buffer,
//! // the remaining space is padded with '0'.
//! assert_eq!(container.write(&id, &[b'x'; 400]).unwrap(), 400);
//!
//! let mut buf = [0; 512];
//! assert_eq!(container.read(&id, &mut buf).unwrap(), 512);
//! assert_eq!(buf[..400], [b'x'; 400]);
//! assert_eq!(buf[400..], [0; 112]);
//!
//! // Write a block from a buffer which is bigger than the block-size.
//! // The block is filled with the first data from the buffer.
//! assert_eq!(container.write(&id, &[b'x'; 520]).unwrap(), 512);
//!
//! let mut buf = [0; 512];
//! assert_eq!(container.read(&id, &mut buf).unwrap(), 512);
//! assert_eq!(buf, [b'x'; 512]);
//! ```
//!
//! ## The header of a container
//!
//! The header of the container stores all data necessary to open the container
//! again. There are:
//!
//! * The [`Cipher`]: The cipher defines the cipher used for encryption and
//! decryption of the individual blocks of the container.
//!
//! If the cipher is set to [`Cipher::None`], then encryption is disabled and
//! all the data are stored unencrypted in the container.
//!
//! If encryption is enabled (with a cipher which is not [`Cipher::None`]),
//! then the blocks of the container are encrypted with a master-key stored
//! and secured in the header of the container. This part of the header
//! (other sensible data are also stored there) is called _secret_ and is
//! encrypted with the wrapping-key derivited by the key derivation function
//! ([`Kdf`]). So, with a user supplied passphrase you are derivating the
//! wrapping-key, which decrypts the _secret_ part of the header, where the
//! master-key (used for en-/decryption of the data blocks) is stored.
//!
//! * The key derivation function ([`Kdf`]) defines a way to create a key from
//! a user supplied passphrase. In the next step this key is used to encrypt resp.
//! decrypt the _secret_ part of the header.
//!
//! * The _secret_ is the encrypted part of the header and contains sensible
//! data of the container. The secret is encrypted with a wrapping-key, which
//! is the output of the [`Kdf`]. The _secret_ contains:
//!
//! * _master-key_: The master-key is used for encryption of the blocks of
//! the container.
//!
//! * _userdata_: Any service running on top of the container can store
//! individual, arbitrary data in the header. Usually the data are used for
//! bootstrapping the service.
//!
//! * _settings of the backend_: The backend of the container stores its
//! runtime information in the secret. It gets it back when opening the
//! backend again. See [`Backend::Settings`] for more information.
mod buffer;
mod cipher;
mod digest;
mod error;
mod header;
mod info;
mod kdf;
mod options;
mod ossl;
mod password;
mod svec;
#[cfg(test)]
mod tests;
use log::debug;
use nuts_backend::{Backend, Create, Open, ReceiveHeader, HEADER_MAX_SIZE};
use std::{any, cmp};
use crate::cipher::CipherContext;
use crate::header::Header;
use crate::password::PasswordStore;
pub use buffer::BufferError;
pub use cipher::{Cipher, CipherError};
pub use digest::Digest;
pub use error::{ContainerResult, Error};
pub use header::HeaderError;
pub use info::Info;
pub use kdf::{Kdf, KdfError};
pub use options::{CreateOptions, CreateOptionsBuilder, OpenOptions, OpenOptionsBuilder};
pub use password::PasswordError;
macro_rules! map_err {
($result:expr) => {
$result.map_err(|cause| Error::Backend(cause))
};
}
/// The Container type.
///
/// A `Container` acts like an encrypted block device, where you can read and
/// write encrypted blocks of data.
///
/// To create a new container use the [`Container::create`] method. You can
/// open an existing container with the [`Container::open`] method. With the
/// [`Container::read`] and [`Container::write`] methods you can read data from
/// the container resp. write data into the container.
#[derive(Debug)]
pub struct Container<B: Backend> {
backend: B,
store: PasswordStore,
header: Header,
ctx: CipherContext,
}
impl<B: Backend> Container<B> {
/// Creates a new container.
///
/// This method expects two arguments:
///
/// 1. `backend_options`, which is a type that implements the
/// [`Create`] trait. It acts as a builder for a concrete [`Backend`]
/// instance.
/// 2. `options`, which is a builder of this `Container`. A
/// [`CreateOptions`] instance can be created with the
/// [`CreateOptionsBuilder`] utility.
///
/// If encryption is turned on, you will be asked for a password over the
/// [password callback](CreateOptionsBuilder::with_password_callback). The
/// returned password is then used for encryption of the secure part of the
/// header.
///
/// The header with the (possibly encrypted) secret is created and passed
/// to the [`Backend`]. The header contains all information you need to
/// open the container again.
///
/// # Errors
///
/// Errors are listed in the [`Error`] type.
pub fn create<C: Create<B>>(
backend_options: C,
options: CreateOptions,
) -> ContainerResult<Container<B>, B> {
let mut header_bytes = [0; HEADER_MAX_SIZE];
let header = Header::create(&options)?;
let settings = backend_options.settings();
let callback = options.callback.clone();
let mut store = PasswordStore::new(callback);
header.write::<B>(settings, &mut header_bytes, &mut store)?;
let backend = map_err!(backend_options.build(header_bytes, options.overwrite))?;
debug!(
"Container created, backend: {}, header: {:?}",
any::type_name::<B>(),
header
);
let ctx = CipherContext::new(header.cipher);
Ok(Container {
backend,
store,
header,
ctx,
})
}
/// Opens an existing container.
///
/// This method expects two arguments:
///
/// 1. `backend_options`, which is a type that implements the [`Open`]
/// trait. It acts as a builder for a concrete [`Backend`] instance.
/// 2. `options`, which is a builder of this `Container`. A
/// [`OpenOptions`] instance can be created with the
/// [`OpenOptionsBuilder`] utility.
///
/// If encryption is turned on for the container, you will be asked for a
/// password over the
/// [password callback](OpenOptionsBuilder::with_password_callback). The
/// returned password is then used to decrypt the secure part of the header.
///
/// # Errors
///
/// Errors are listed in the [`Error`] type.
pub fn open<O: Open<B>>(
mut backend_options: O,
options: OpenOptions,
) -> ContainerResult<Container<B>, B> {
let callback = options.callback.clone();
let mut store = PasswordStore::new(callback);
let (header, settings) = Self::read_header(&mut backend_options, &mut store)?;
let backend = map_err!(backend_options.build(settings))?;
debug!(
"Container opened, backend: {}, header: {:?}",
any::type_name::<B>(),
header
);
let ctx = CipherContext::new(header.cipher);
Ok(Container {
backend,
store,
header,
ctx,
})
}
/// Returns the backend of this container.
pub fn backend(&self) -> &B {
&self.backend
}
/// Consumes this container, returning the inner backend.
pub fn into_backend(self) -> B {
self.backend
}
/// Returns information from the container.
///
/// # Errors
///
/// Errors are listed in the [`Error`] type.
pub fn info(&self) -> ContainerResult<Info<B>, B> {
let backend = map_err!(self.backend.info())?;
Ok(Info {
backend,
cipher: self.header.cipher,
kdf: self.header.kdf.clone(),
bsize_gross: self.backend.block_size(),
bsize_net: self.block_size(),
})
}
/// Returns userdata assigned to the container.
///
/// Userdata are arbitrary data stored in the (encrypted) header of the
/// container. It can be used by a service running on top of a _nuts_
/// container to store information about the service itself.
pub fn userdata(&self) -> &[u8] {
&self.header.userdata
}
/// Updates the userdata.
///
/// Assigns a new set of new userdata to the container; any previous
/// userdata are overwritten.
///
/// # Errors
///
/// Errors are listed in the [`Error`] type.
pub fn update_userdata(&mut self, userdata: &[u8]) -> ContainerResult<(), B> {
let (mut header, settings) = Self::read_header(&mut self.backend, &mut self.store)?;
let mut header_bytes = [0; HEADER_MAX_SIZE];
header.userdata.clear();
header.userdata.extend_from_slice(userdata);
header.write::<B>(settings, &mut header_bytes, &mut self.store)?;
map_err!(self.backend.write_header(&header_bytes))?;
self.header = header;
Ok(())
}
/// The (net) block size specifies the number of userdata bytes you can
/// store in a block. It can be less than the gross block size specified by
/// the [backend](Backend::block_size)!
///
/// Depending on the selected cipher, you need to store additional data in
/// a block. I.e. an AE-cipher results into a tag, which needs to be stored
/// additionally. Such data must be substracted from the gross block size
/// and results into the net block size.
pub fn block_size(&self) -> u32 {
self.backend
.block_size()
.saturating_sub(self.header.cipher.tag_size())
}
/// Aquires a new block in the backend.
///
/// Once aquired you should be able to [read](Container::read) and
/// [write](Container::write) from/to it.
///
/// By default an aquired block, which is not written yet, returns an
/// all-zero buffer.
///
/// Returns the [id](Backend::Id) of the block.
///
/// # Errors
///
/// Errors are listed in the [`Error`] type.
pub fn aquire(&mut self) -> ContainerResult<B::Id, B> {
let key = &self.header.key;
let iv = &self.header.iv;
self.ctx.copy_from_slice(self.block_size() as usize, &[]);
let ctext = self.ctx.encrypt(key, iv)?;
map_err!(self.backend.aquire(ctext))
}
/// Releases a block again.
///
/// A released block cannot be [read](Container::read) and
/// [written](Container::write), the [id](Backend::Id) cannot be used
/// afterwards.
///
/// # Errors
///
/// Errors are listed in the [`Error`] type.
pub fn release(&mut self, id: B::Id) -> ContainerResult<(), B> {
map_err!(self.backend.release(id))
}
/// Reads a block from the container.
///
/// Reads the block with the given `id` and places the decrypted data in
/// `buf`.
///
/// You cannot read not more data than [block-size](Backend::block_size)
/// bytes. If `buf` is larger, than not the whole buffer is filled. In the
/// other direction, if `buf` is not large enough to store the whole block,
/// `buf` is filled with the first `buf.len()` bytes.
///
/// The methods returns the number of bytes actually read, which cannot be
/// greater than the [block-size](Backend::block_size).
///
/// # Errors
///
/// Errors are listed in the [`Error`] type.
pub fn read(&mut self, id: &B::Id, buf: &mut [u8]) -> ContainerResult<usize, B> {
let ctext = self.ctx.inp_mut(self.backend.block_size() as usize);
map_err!(self.backend.read(id, ctext))?;
let key = &self.header.key;
let iv = &self.header.iv;
let ptext = self.ctx.decrypt(key, iv)?;
let n = cmp::min(ptext.len(), buf.len());
buf[..n].copy_from_slice(&ptext[..n]);
Ok(n)
}
/// Writes a block into the container.
///
/// Encrypts the plain data from `buf` and writes the encrypted data into
/// the block with the given `id`.
///
/// Writes up to `buf.len()` bytes from the unencrypted `buf` buffer into
/// the container.
///
/// If `buf` is not large enough to fill the whole block, the destination
/// block is automatically padded with all zeros.
///
/// If `buf` holds more data than the block-size, then the first
/// [block-size](Backend::block_size) bytes are copied into the block.
///
/// The method returns the number of bytes actually written.
///
/// # Errors
///
/// Errors are listed in the [`Error`] type.
pub fn write(&mut self, id: &B::Id, buf: &[u8]) -> ContainerResult<usize, B> {
let len = self.ctx.copy_from_slice(self.block_size() as usize, buf);
let key = &self.header.key;
let iv = &self.header.iv;
let ctext = self.ctx.encrypt(key, iv)?;
map_err!(self.backend.write(id, ctext)).map(|_| len)
}
fn read_header<H: ReceiveHeader<B>>(
reader: &mut H,
store: &mut PasswordStore,
) -> ContainerResult<(Header, B::Settings), B> {
let mut buf = [0; HEADER_MAX_SIZE];
match reader.get_header_bytes(&mut buf) {
Ok(_) => {
debug!("got {} header bytes", buf.len());
Ok(Header::read::<B>(&buf, store)?)
}
Err(cause) => Err(Error::Backend(cause)),
}
}
/// Deletes the entire container and all traces.
///
/// The method must not fail!
pub fn delete(self) {
self.backend.delete()
}
}