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
// 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.
#[cfg(test)]
mod tests;
use nuts_bytes::{FromBytes, ToBytes};
use openssl::cipher as ossl_cipher;
use openssl::cipher_ctx::CipherCtx;
use openssl::error::ErrorStack;
use std::str::FromStr;
use std::{cmp, fmt};
use thiserror::Error;
use crate::svec::SecureVec;
/// [`Cipher`] related error codes.
#[derive(Debug, Error)]
pub enum CipherError {
/// The cipher key is invalid/too short.
#[error("invalid key")]
InvalidKey,
/// The cipher iv is invalid/too short.
#[error("invalid iv")]
InvalidIv,
/// The size of the block to be encrypted/decrypted is invalid and must be
/// aligned at the [block size](Cipher::block_size) of the cipher.
#[error("invalid block-size")]
InvalidBlockSize,
/// A cipher-text is not trustworthy.
///
/// If an authenticated decryption is performed, and the tag mismatches,
/// this error is raised.
#[error("the plaintext is not trustworthy")]
NotTrustworthy,
/// An error in the OpenSSL library occured.
#[error(transparent)]
OpenSSL(#[from] ErrorStack),
}
/// Supported cipher algorithms.
#[derive(Clone, Copy, Debug, FromBytes, PartialEq, ToBytes)]
pub enum Cipher {
/// No encryption.
None,
/// AES with a 128-bit key in CTR mode
Aes128Ctr,
/// AES with a 128-bit key in GCM mode
Aes128Gcm,
}
impl Cipher {
/// Returns the block size of the cipher.
pub fn block_size(&self) -> usize {
match self.to_openssl() {
None => 1,
Some(c) => c.block_size(),
}
}
/// Returns the key size of the cipher.
pub fn key_len(&self) -> usize {
match self.to_openssl() {
None => 0,
Some(c) => c.key_length(),
}
}
/// Returns the IV size of the cipher.
pub fn iv_len(&self) -> usize {
match self.to_openssl() {
None => 0,
Some(c) => c.iv_length(),
}
}
/// Returns the tag size of the cipher.
///
/// An AE-cipher results into a
///
/// 1. ciphertext
/// 2. tag
///
/// Ciphertext and tag are both stored in a block of the container. Use
/// this method to get the size of the tag. For a non-AE-cipher the
/// tag-size is `0`.
pub fn tag_size(&self) -> u32 {
match self {
Cipher::None => 0,
Cipher::Aes128Ctr => 0,
Cipher::Aes128Gcm => 16,
}
}
fn to_openssl(self) -> Option<&'static ossl_cipher::CipherRef> {
match self {
Cipher::None => None,
Cipher::Aes128Ctr => Some(ossl_cipher::Cipher::aes_128_ctr()),
Cipher::Aes128Gcm => Some(ossl_cipher::Cipher::aes_128_gcm()),
}
}
}
impl fmt::Display for Cipher {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let s = match self {
Cipher::None => "none",
Cipher::Aes128Ctr => "aes128-ctr",
Cipher::Aes128Gcm => "aes128-gcm",
};
fmt.write_str(s)
}
}
impl FromStr for Cipher {
type Err = ();
fn from_str(str: &str) -> Result<Self, ()> {
match str {
"none" => Ok(Cipher::None),
"aes128-ctr" => Ok(Cipher::Aes128Ctr),
"aes128-gcm" => Ok(Cipher::Aes128Gcm),
_ => Err(()),
}
}
}
#[derive(Debug)]
pub(super) struct CipherContext {
cipher: Cipher,
inp: SecureVec,
outp: SecureVec,
}
impl CipherContext {
pub(super) fn new(cipher: Cipher) -> CipherContext {
CipherContext {
cipher,
inp: vec![].into(),
outp: vec![].into(),
}
}
pub fn copy_from_slice(&mut self, buf_size: usize, buf: &[u8]) -> usize {
let len = cmp::min(buf_size, buf.len());
self.inp.resize(buf_size, 0);
self.inp[..len].copy_from_slice(&buf[..len]);
self.inp[len..].iter_mut().for_each(|n| *n = 0);
len
}
pub fn inp_mut(&mut self, buf_size: usize) -> &mut [u8] {
self.copy_from_slice(buf_size, &[]); // whiteout
&mut self.inp
}
pub fn encrypt(&mut self, key: &[u8], iv: &[u8]) -> Result<&[u8], CipherError> {
match self.cipher {
Cipher::None => self.make_none(),
_ => self.encrypt_aad(None, key, iv).map(|_| ())?,
};
Ok(self.outp.as_slice())
}
fn encrypt_aad(
&mut self,
aad: Option<&[u8]>,
key: &[u8],
iv: &[u8],
) -> Result<usize, CipherError> {
let key = key
.get(..self.cipher.key_len())
.ok_or(CipherError::InvalidKey)?;
let iv = iv
.get(..self.cipher.iv_len())
.ok_or(CipherError::InvalidIv)?;
// number of plaintext bytes: equals to number of input bytes. There is
// no need to align at block size because blocksize is 1 for all
// ciphers.
let ptext_len = self.inp.len();
// number of ciphertext bytes: equals to plaintext bytes (for now) because
// blocksize is 1 for all ciphers.
let ctext_len = ptext_len;
if ptext_len == 0 {
return Ok(0);
}
if ptext_len % self.cipher.block_size() != 0 {
return Err(CipherError::InvalidBlockSize);
}
let mut ctx = CipherCtx::new()?;
ctx.encrypt_init(self.cipher.to_openssl(), Some(key), Some(iv))?;
ctx.set_padding(false);
if let Some(buf) = aad {
ctx.cipher_update(buf, None)?;
}
self.outp
.resize(ctext_len + self.cipher.tag_size() as usize, 0);
ctx.cipher_update(&self.inp[..ptext_len], Some(&mut self.outp[..ctext_len]))?;
if self.cipher.tag_size() > 0 {
ctx.cipher_final(&mut [])?;
ctx.tag(&mut self.outp[ctext_len..])?;
}
Ok(ctext_len)
}
pub fn decrypt(&mut self, key: &[u8], iv: &[u8]) -> Result<&[u8], CipherError> {
match self.cipher {
Cipher::None => self.make_none(),
_ => self.decrypt_aad(None, key, iv).map(|_| ())?,
}
Ok(self.outp.as_slice())
}
fn decrypt_aad(
&mut self,
aad: Option<&[u8]>,
key: &[u8],
iv: &[u8],
) -> Result<usize, CipherError> {
let key = key
.get(..self.cipher.key_len())
.ok_or(CipherError::InvalidKey)?;
let iv = iv
.get(..self.cipher.iv_len())
.ok_or(CipherError::InvalidIv)?;
// number of ciphertext bytes: remove tag from the input.
let ctext_bytes = self
.inp
.len()
.checked_sub(self.cipher.tag_size() as usize)
.unwrap_or(0);
// number of plaintext bytes: equals to ciphertext bytes (for now) because
// blocksize is 1 for all ciphers.
let ptext_bytes = ctext_bytes;
if ctext_bytes == 0 {
return Ok(0);
}
if ctext_bytes % self.cipher.block_size() != 0 {
return Err(CipherError::InvalidBlockSize);
}
let mut ctx = CipherCtx::new()?;
ctx.decrypt_init(self.cipher.to_openssl(), Some(key), Some(iv))?;
ctx.set_padding(false);
if let Some(buf) = aad {
ctx.cipher_update(buf, None)?;
}
self.outp.resize(ptext_bytes, 0);
ctx.cipher_update(
&self.inp[..ctext_bytes],
Some(&mut self.outp[..ptext_bytes]),
)?;
if self.cipher.tag_size() > 0 {
ctx.set_tag(&self.inp[ctext_bytes..])?;
ctx.cipher_final(&mut [])
.map_err(|_| CipherError::NotTrustworthy)?;
}
Ok(ctext_bytes)
}
fn make_none(&mut self) {
self.outp.clear();
self.outp.extend_from_slice(&self.inp);
}
}