chore: checkpoint before Python removal

This commit is contained in:
2026-03-26 22:33:59 +00:00
parent 683cec9307
commit e568ddf82a
29972 changed files with 11269302 additions and 2 deletions

View File

@@ -0,0 +1 @@
{"files":{".cargo_vcs_info.json":"fe2b604c914802839ddd017fb940712f9481b8f04b9d2fb2efb78f810077df9c","CHANGELOG.md":"00076d3471973ada2ae351cafa44babfe4a08babdb7929a6df1686afeb362d20","Cargo.toml":"0856a9702dcb53062d8d9632583b0d41b8f533c344fed27e4d728152141f93a7","Cargo.toml.orig":"ff8acef700e97bf93da37733957d69d4b1eda8882f20f3ca04b2b2c75bf02039","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"df5a6e5866476bcef44f2b2e1712d123ea26e350cc0b54df253beb4333bf0aec","README.md":"63c965e419f2689293b010b843d3ba9c802309a2883090300d1dd25eb28b7ada","src/chacha20poly1305.rs":"02dca087550cb3c3217a593234847097daeeb6bd021b32dc918614486e17adb0","src/error.rs":"2bd2e625c3acc829d0cc9e86ea731b0d039ed702db5da06286f89aacea28a77a","src/lib.rs":"0e433b9b02482596f6ca3902b362bdcca74fe8a84751897b47d7159050f5aeba"},"package":"caac132742f0d33c3af65bfcde7f6aa8f62f0e991d80db99149eb9d44708784f"}

View File

@@ -0,0 +1,6 @@
{
"git": {
"sha1": "65d6c00c0455b9dbb03471a337922076d123fe40"
},
"path_in_vcs": "ssh-cipher"
}

11
vendor/ssh-cipher/CHANGELOG.md vendored Normal file
View File

@@ -0,0 +1,11 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## 0.2.0 (2023-08-11)
- Initial release
## 0.1.0
- Skipped to synchronize versions with `ssh-encoding`

115
vendor/ssh-cipher/Cargo.toml vendored Normal file
View File

@@ -0,0 +1,115 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2021"
rust-version = "1.60"
name = "ssh-cipher"
version = "0.2.0"
authors = ["RustCrypto Developers"]
description = """
Pure Rust implementation of SSH symmetric encryption including support for the
modern aes128-gcm@openssh.com/aes256-gcm@openssh.com and
chacha20-poly1305@openssh.com algorithms as well as legacy support for older
ciphers. Built on the pure Rust cryptography implementations maintained by the
RustCrypto organization.
"""
readme = "README.md"
keywords = [
"crypto",
"encryption",
"openssh",
"ssh",
]
categories = [
"cryptography",
"no-std",
]
license = "Apache-2.0 OR MIT"
repository = "https://github.com/RustCrypto/SSH/tree/master/ssh-cipher"
[package.metadata.docs.rs]
all-features = true
rustdoc-args = [
"--cfg",
"docsrs",
]
[dependencies.aes]
version = "0.8"
optional = true
default-features = false
[dependencies.aes-gcm]
version = "0.10"
features = ["aes"]
optional = true
default-features = false
[dependencies.cbc]
version = "0.1"
optional = true
[dependencies.chacha20]
version = "0.9"
optional = true
default-features = false
[dependencies.cipher]
version = "0.4"
[dependencies.ctr]
version = "0.9"
optional = true
default-features = false
[dependencies.des]
version = "0.8"
optional = true
default-features = false
[dependencies.encoding]
version = "0.2"
package = "ssh-encoding"
[dependencies.poly1305]
version = "0.8"
optional = true
default-features = false
[dependencies.subtle]
version = "2"
optional = true
default-features = false
[features]
aes-cbc = [
"dep:aes",
"dep:cbc",
]
aes-ctr = [
"dep:aes",
"dep:ctr",
]
aes-gcm = [
"dep:aes",
"dep:aes-gcm",
]
chacha20poly1305 = [
"dep:chacha20",
"dep:poly1305",
"dep:subtle",
]
std = []
tdes = [
"dep:des",
"dep:cbc",
]

201
vendor/ssh-cipher/LICENSE-APACHE vendored Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

25
vendor/ssh-cipher/LICENSE-MIT vendored Normal file
View File

@@ -0,0 +1,25 @@
Copyright (c) 2023 The RustCrypto Project Developers
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.

60
vendor/ssh-cipher/README.md vendored Normal file
View File

@@ -0,0 +1,60 @@
# [RustCrypto]: SSH Symmetric Ciphers
[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
[![Build Status][build-image]][build-link]
![Apache2/MIT licensed][license-image]
![Rust Version][rustc-image]
[![Project Chat][chat-image]][chat-link]
[Documentation][docs-link]
## About
Pure Rust implementation of SSH symmetric encryption including support for the
modern `aes128-gcm@openssh.com`/`aes256-gcm@openssh.com` and
`chacha20-poly1305@openssh.com` algorithms as well as legacy support for older
ciphers.
Built on the pure Rust cryptography implementations maintained by the
[RustCrypto] organization.
## Minimum Supported Rust Version
This crate requires **Rust 1.60** at a minimum.
We may change the MSRV in the future, but it will be accompanied by a minor
version bump.
## License
Licensed under either of:
* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
* [MIT license](http://opensource.org/licenses/MIT)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.
[//]: # (badges)
[crate-image]: https://buildstats.info/crate/ssh-cipher
[crate-link]: https://crates.io/crates/ssh-cipher
[docs-image]: https://docs.rs/ssh-cipher/badge.svg
[docs-link]: https://docs.rs/ssh-cipher/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
[rustc-image]: https://img.shields.io/badge/rustc-1.60+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/346919-SSH
[build-image]: https://github.com/RustCrypto/SSH/actions/workflows/ssh-cipher.yml/badge.svg
[build-link]: https://github.com/RustCrypto/SSH/actions/workflows/ssh-cipher.yml
[//]: # (links)
[RustCrypto]: https://github.com/rustcrypto
[RFC4251]: https://datatracker.ietf.org/doc/html/rfc4251

View File

@@ -0,0 +1,87 @@
//! OpenSSH variant of ChaCha20Poly1305: `chacha20-poly1305@openssh.com`
//!
//! Differences from ChaCha20Poly1305 as described in RFC8439:
//!
//! - Construction uses two separately keyed instances of ChaCha20: one for data, one for lengths
//! - The input of Poly1305 is not padded
//! - The lengths of ciphertext and AAD are not authenticated using Poly1305
//!
//! [PROTOCOL.chacha20poly1305]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.chacha20poly1305?annotate=HEAD
use crate::{Error, Nonce, Result, Tag};
use chacha20::{ChaCha20, Key};
use cipher::{KeyInit, KeyIvInit, StreamCipher, StreamCipherSeek};
use poly1305::Poly1305;
use subtle::ConstantTimeEq;
const KEY_SIZE: usize = 32;
pub(crate) struct ChaCha20Poly1305 {
cipher: ChaCha20,
mac: Poly1305,
}
impl ChaCha20Poly1305 {
/// Create a new [`ChaCha20Poly1305`] instance with a 64-byte key.
/// From [PROTOCOL.chacha20poly1305]:
///
/// > The chacha20-poly1305@openssh.com cipher requires 512 bits of key
/// > material as output from the SSH key exchange. This forms two 256 bit
/// > keys (K_1 and K_2), used by two separate instances of chacha20.
/// > The first 256 bits constitute K_2 and the second 256 bits become
/// > K_1.
/// >
/// > The instance keyed by K_1 is a stream cipher that is used only
/// > to encrypt the 4 byte packet length field. The second instance,
/// > keyed by K_2, is used in conjunction with poly1305 to build an AEAD
/// > (Authenticated Encryption with Associated Data) that is used to encrypt
/// > and authenticate the entire packet.
///
/// [PROTOCOL.chacha20poly1305]: https://cvsweb.openbsd.org/src/usr.bin/ssh/PROTOCOL.chacha20poly1305?annotate=HEAD
pub fn new(key: &[u8], nonce: &[u8]) -> Result<Self> {
#[allow(clippy::arithmetic_side_effects)]
if key.len() != KEY_SIZE * 2 {
return Err(Error::KeySize);
}
// TODO(tarcieri): support for using both keys
let (k_2, _k_1) = key.split_at(KEY_SIZE);
let key = Key::from_slice(k_2);
let nonce = if nonce.is_empty() {
// For key encryption
Nonce::default()
} else {
Nonce::try_from(nonce).map_err(|_| Error::IvSize)?
};
let mut cipher = ChaCha20::new(key, &nonce.into());
let mut poly1305_key = poly1305::Key::default();
cipher.apply_keystream(&mut poly1305_key);
let mac = Poly1305::new(&poly1305_key);
// Seek to block 1
cipher.seek(64);
Ok(Self { cipher, mac })
}
#[inline]
pub fn encrypt(mut self, buffer: &mut [u8]) -> Tag {
self.cipher.apply_keystream(buffer);
self.mac.compute_unpadded(buffer).into()
}
#[inline]
pub fn decrypt(mut self, buffer: &mut [u8], tag: Tag) -> Result<()> {
let expected_tag = self.mac.compute_unpadded(buffer);
if expected_tag.ct_eq(&tag).into() {
self.cipher.apply_keystream(buffer);
Ok(())
} else {
Err(Error::Crypto)
}
}
}

42
vendor/ssh-cipher/src/error.rs vendored Normal file
View File

@@ -0,0 +1,42 @@
//! Error types.
use crate::Cipher;
use core::fmt;
/// Result type with `ssh-cipher` crate's [`Error`] as the error type.
pub type Result<T> = core::result::Result<T, Error>;
/// Error type.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Error {
/// Cryptographic errors.
Crypto,
/// Invalid key size.
KeySize,
/// Invalid initialization vector / nonce size.
IvSize,
/// Invalid AEAD tag size.
TagSize,
/// Unsupported cipher.
UnsupportedCipher(Cipher),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Crypto => write!(f, "cryptographic error"),
Error::KeySize => write!(f, "invalid key size"),
Error::IvSize => write!(f, "invalid initialization vector size"),
Error::TagSize => write!(f, "invalid AEAD tag size"),
Error::UnsupportedCipher(cipher) => write!(f, "unsupported cipher: {}", cipher),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}

460
vendor/ssh-cipher/src/lib.rs vendored Normal file
View File

@@ -0,0 +1,460 @@
#![no_std]
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]
#![forbid(unsafe_code)]
#![warn(
clippy::arithmetic_side_effects,
clippy::panic,
clippy::panic_in_result_fn,
clippy::unwrap_used,
missing_docs,
rust_2018_idioms,
unused_lifetimes,
unused_qualifications
)]
#[cfg(feature = "std")]
extern crate std;
mod error;
#[cfg(feature = "chacha20poly1305")]
mod chacha20poly1305;
pub use crate::error::{Error, Result};
use core::{fmt, str};
use encoding::{Label, LabelError};
#[cfg(feature = "aes-ctr")]
use cipher::StreamCipherCore;
#[cfg(feature = "aes-gcm")]
use aes_gcm::{aead::AeadInPlace, Aes128Gcm, Aes256Gcm};
#[cfg(feature = "chacha20poly1305")]
use crate::chacha20poly1305::ChaCha20Poly1305;
#[cfg(any(feature = "aes-cbc", feature = "aes-ctr"))]
use aes::{Aes128, Aes192, Aes256};
#[cfg(any(feature = "aes-cbc", feature = "tdes"))]
use {
cbc::{Decryptor, Encryptor},
cipher::{block_padding::NoPadding, BlockCipher, BlockDecryptMut, BlockEncryptMut},
};
#[cfg(any(feature = "aes-cbc", feature = "aes-gcm", feature = "tdes"))]
use cipher::KeyInit;
#[cfg(any(feature = "aes-cbc", feature = "aes-ctr", feature = "tdes"))]
use cipher::KeyIvInit;
#[cfg(feature = "tdes")]
use des::TdesEde3;
/// AES-128 in block chaining (CBC) mode
const AES128_CBC: &str = "aes128-cbc";
/// AES-192 in block chaining (CBC) mode
const AES192_CBC: &str = "aes192-cbc";
/// AES-256 in block chaining (CBC) mode
const AES256_CBC: &str = "aes256-cbc";
/// AES-128 in counter (CTR) mode
const AES128_CTR: &str = "aes128-ctr";
/// AES-192 in counter (CTR) mode
const AES192_CTR: &str = "aes192-ctr";
/// AES-256 in counter (CTR) mode
const AES256_CTR: &str = "aes256-ctr";
/// AES-128 in Galois/Counter Mode (GCM).
const AES128_GCM: &str = "aes128-gcm@openssh.com";
/// AES-256 in Galois/Counter Mode (GCM).
const AES256_GCM: &str = "aes256-gcm@openssh.com";
/// ChaCha20-Poly1305
const CHACHA20_POLY1305: &str = "chacha20-poly1305@openssh.com";
/// Triple-DES in block chaining (CBC) mode
const TDES_CBC: &str = "3des-cbc";
/// Nonce for AEAD modes.
///
/// This is used by e.g. `aes128-gcm@openssh.com`/`aes256-gcm@openssh.com` and
/// `chacha20-poly1305@openssh.com`.
pub type Nonce = [u8; 12];
/// Authentication tag for ciphertext data.
///
/// This is used by e.g. `aes128-gcm@openssh.com`/`aes256-gcm@openssh.com` and
/// `chacha20-poly1305@openssh.com`.
pub type Tag = [u8; 16];
/// Counter mode with a 32-bit big endian counter.
#[cfg(feature = "aes-ctr")]
type Ctr128BE<Cipher> = ctr::CtrCore<Cipher, ctr::flavors::Ctr128BE>;
/// Cipher algorithms.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Cipher {
/// No cipher.
None,
/// AES-128 in cipher block chaining (CBC) mode.
Aes128Cbc,
/// AES-192 in cipher block chaining (CBC) mode.
Aes192Cbc,
/// AES-256 in cipher block chaining (CBC) mode.
Aes256Cbc,
/// AES-128 in counter (CTR) mode.
Aes128Ctr,
/// AES-192 in counter (CTR) mode.
Aes192Ctr,
/// AES-256 in counter (CTR) mode.
Aes256Ctr,
/// AES-128 in Galois/Counter Mode (GCM).
Aes128Gcm,
/// AES-256 in Galois/Counter Mode (GCM).
Aes256Gcm,
/// ChaCha20-Poly1305
ChaCha20Poly1305,
/// TripleDES in block chaining (CBC) mode
TDesCbc,
}
impl Cipher {
/// Decode cipher algorithm from the given `ciphername`.
///
/// # Supported cipher names
/// - `aes256-ctr`
pub fn new(ciphername: &str) -> core::result::Result<Self, LabelError> {
ciphername.parse()
}
/// Get the string identifier which corresponds to this algorithm.
pub fn as_str(self) -> &'static str {
match self {
Self::None => "none",
Self::Aes128Cbc => AES128_CBC,
Self::Aes192Cbc => AES192_CBC,
Self::Aes256Cbc => AES256_CBC,
Self::Aes128Ctr => AES128_CTR,
Self::Aes192Ctr => AES192_CTR,
Self::Aes256Ctr => AES256_CTR,
Self::Aes128Gcm => AES128_GCM,
Self::Aes256Gcm => AES256_GCM,
Self::ChaCha20Poly1305 => CHACHA20_POLY1305,
Self::TDesCbc => TDES_CBC,
}
}
/// Get the key and IV size for this cipher in bytes.
pub fn key_and_iv_size(self) -> Option<(usize, usize)> {
match self {
Self::None => None,
Self::Aes128Cbc => Some((16, 16)),
Self::Aes192Cbc => Some((24, 16)),
Self::Aes256Cbc => Some((32, 16)),
Self::Aes128Ctr => Some((16, 16)),
Self::Aes192Ctr => Some((24, 16)),
Self::Aes256Ctr => Some((32, 16)),
Self::Aes128Gcm => Some((16, 12)),
Self::Aes256Gcm => Some((32, 12)),
Self::ChaCha20Poly1305 => Some((64, 0)),
Self::TDesCbc => Some((24, 8)),
}
}
/// Get the block size for this cipher in bytes.
pub fn block_size(self) -> usize {
match self {
Self::None | Self::ChaCha20Poly1305 | Self::TDesCbc => 8,
Self::Aes128Cbc
| Self::Aes192Cbc
| Self::Aes256Cbc
| Self::Aes128Ctr
| Self::Aes192Ctr
| Self::Aes256Ctr
| Self::Aes128Gcm
| Self::Aes256Gcm => 16,
}
}
/// Compute the length of padding necessary to pad the given input to
/// the block size.
#[allow(clippy::arithmetic_side_effects)]
pub fn padding_len(self, input_size: usize) -> usize {
match input_size % self.block_size() {
0 => 0,
input_rem => self.block_size() - input_rem,
}
}
/// Does this cipher have an authentication tag? (i.e. is it an AEAD mode?)
pub fn has_tag(self) -> bool {
matches!(
self,
Self::Aes128Gcm | Self::Aes256Gcm | Self::ChaCha20Poly1305
)
}
/// Is this cipher `none`?
pub fn is_none(self) -> bool {
self == Self::None
}
/// Is the cipher anything other than `none`?
pub fn is_some(self) -> bool {
!self.is_none()
}
/// Decrypt the ciphertext in the `buffer` in-place using this cipher.
pub fn decrypt(self, key: &[u8], iv: &[u8], buffer: &mut [u8], tag: Option<Tag>) -> Result<()> {
match self {
#[cfg(feature = "aes-cbc")]
Self::Aes128Cbc => {
if tag.is_some() {
return Err(Error::TagSize);
}
cbc_decrypt::<Aes128>(key, iv, buffer)
}
#[cfg(feature = "aes-cbc")]
Self::Aes192Cbc => {
if tag.is_some() {
return Err(Error::TagSize);
}
cbc_decrypt::<Aes192>(key, iv, buffer)
}
#[cfg(feature = "aes-cbc")]
Self::Aes256Cbc => {
if tag.is_some() {
return Err(Error::TagSize);
}
cbc_decrypt::<Aes256>(key, iv, buffer)
}
#[cfg(feature = "aes-ctr")]
Self::Aes128Ctr | Self::Aes192Ctr | Self::Aes256Ctr => {
if tag.is_some() {
return Err(Error::TagSize);
}
// Counter mode encryption and decryption are the same operation
self.encrypt(key, iv, buffer)?;
Ok(())
}
#[cfg(feature = "aes-gcm")]
Self::Aes128Gcm => {
let cipher = Aes128Gcm::new_from_slice(key).map_err(|_| Error::KeySize)?;
let nonce = Nonce::try_from(iv).map_err(|_| Error::IvSize)?;
let tag = tag.ok_or(Error::TagSize)?;
cipher
.decrypt_in_place_detached(&nonce.into(), &[], buffer, &tag.into())
.map_err(|_| Error::Crypto)?;
Ok(())
}
#[cfg(feature = "aes-gcm")]
Self::Aes256Gcm => {
let cipher = Aes256Gcm::new_from_slice(key).map_err(|_| Error::KeySize)?;
let nonce = Nonce::try_from(iv).map_err(|_| Error::IvSize)?;
let tag = tag.ok_or(Error::TagSize)?;
cipher
.decrypt_in_place_detached(&nonce.into(), &[], buffer, &tag.into())
.map_err(|_| Error::Crypto)?;
Ok(())
}
#[cfg(feature = "chacha20poly1305")]
Self::ChaCha20Poly1305 => {
let tag = tag.ok_or(Error::TagSize)?;
ChaCha20Poly1305::new(key, iv)?.decrypt(buffer, tag)
}
#[cfg(feature = "tdes")]
Self::TDesCbc => {
if tag.is_some() {
return Err(Error::TagSize);
}
cbc_decrypt::<TdesEde3>(key, iv, buffer)
}
_ => {
// Suppress unused variable warnings.
let (_, _, _, _) = (key, iv, buffer, tag);
Err(self.unsupported())
}
}
}
/// Encrypt the ciphertext in the `buffer` in-place using this cipher.
pub fn encrypt(self, key: &[u8], iv: &[u8], buffer: &mut [u8]) -> Result<Option<Tag>> {
match self {
#[cfg(feature = "aes-cbc")]
Self::Aes128Cbc => {
cbc_encrypt::<Aes128>(key, iv, buffer)?;
Ok(None)
}
#[cfg(feature = "aes-cbc")]
Self::Aes192Cbc => {
cbc_encrypt::<Aes192>(key, iv, buffer)?;
Ok(None)
}
#[cfg(feature = "aes-cbc")]
Self::Aes256Cbc => {
cbc_encrypt::<Aes256>(key, iv, buffer)?;
Ok(None)
}
#[cfg(feature = "aes-ctr")]
Self::Aes128Ctr => {
ctr_encrypt::<Ctr128BE<Aes128>>(key, iv, buffer)?;
Ok(None)
}
#[cfg(feature = "aes-ctr")]
Self::Aes192Ctr => {
ctr_encrypt::<Ctr128BE<Aes192>>(key, iv, buffer)?;
Ok(None)
}
#[cfg(feature = "aes-ctr")]
Self::Aes256Ctr => {
ctr_encrypt::<Ctr128BE<Aes256>>(key, iv, buffer)?;
Ok(None)
}
#[cfg(feature = "aes-gcm")]
Self::Aes128Gcm => {
let cipher = Aes128Gcm::new_from_slice(key).map_err(|_| Error::KeySize)?;
let nonce = Nonce::try_from(iv).map_err(|_| Error::IvSize)?;
let tag = cipher
.encrypt_in_place_detached(&nonce.into(), &[], buffer)
.map_err(|_| Error::Crypto)?;
Ok(Some(tag.into()))
}
#[cfg(feature = "aes-gcm")]
Self::Aes256Gcm => {
let cipher = Aes256Gcm::new_from_slice(key).map_err(|_| Error::KeySize)?;
let nonce = Nonce::try_from(iv).map_err(|_| Error::IvSize)?;
let tag = cipher
.encrypt_in_place_detached(&nonce.into(), &[], buffer)
.map_err(|_| Error::Crypto)?;
Ok(Some(tag.into()))
}
#[cfg(feature = "chacha20poly1305")]
Self::ChaCha20Poly1305 => {
let tag = ChaCha20Poly1305::new(key, iv)?.encrypt(buffer);
Ok(Some(tag))
}
#[cfg(feature = "tdes")]
Self::TDesCbc => {
cbc_encrypt::<TdesEde3>(key, iv, buffer)?;
Ok(None)
}
_ => {
// Suppress unused variable warnings.
let (_, _, _) = (key, iv, buffer);
Err(self.unsupported())
}
}
}
/// Create an unsupported cipher error.
fn unsupported(self) -> Error {
Error::UnsupportedCipher(self)
}
}
impl AsRef<str> for Cipher {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl Label for Cipher {}
impl fmt::Display for Cipher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl str::FromStr for Cipher {
type Err = LabelError;
fn from_str(ciphername: &str) -> core::result::Result<Self, LabelError> {
match ciphername {
"none" => Ok(Self::None),
AES128_CBC => Ok(Self::Aes128Cbc),
AES192_CBC => Ok(Self::Aes192Cbc),
AES256_CBC => Ok(Self::Aes256Cbc),
AES128_CTR => Ok(Self::Aes128Ctr),
AES192_CTR => Ok(Self::Aes192Ctr),
AES256_CTR => Ok(Self::Aes256Ctr),
AES128_GCM => Ok(Self::Aes128Gcm),
AES256_GCM => Ok(Self::Aes256Gcm),
CHACHA20_POLY1305 => Ok(Self::ChaCha20Poly1305),
TDES_CBC => Ok(Self::TDesCbc),
_ => Err(LabelError::new(ciphername)),
}
}
}
#[cfg(any(feature = "aes-cbc", feature = "tdes"))]
fn cbc_encrypt<C>(key: &[u8], iv: &[u8], buffer: &mut [u8]) -> Result<()>
where
C: BlockEncryptMut + BlockCipher + KeyInit,
{
let cipher = Encryptor::<C>::new_from_slices(key, iv).map_err(|_| Error::KeySize)?;
// Since the passed in buffer is already padded, using NoPadding here
cipher
.encrypt_padded_mut::<NoPadding>(buffer, buffer.len())
.map_err(|_| Error::Crypto)?;
Ok(())
}
#[cfg(any(feature = "aes-cbc", feature = "tdes"))]
fn cbc_decrypt<C>(key: &[u8], iv: &[u8], buffer: &mut [u8]) -> Result<()>
where
C: BlockDecryptMut + BlockCipher + KeyInit,
{
let cipher = Decryptor::<C>::new_from_slices(key, iv).map_err(|_| Error::KeySize)?;
// Since the passed in buffer is already padded, using NoPadding here
cipher
.decrypt_padded_mut::<NoPadding>(buffer)
.map_err(|_| Error::Crypto)?;
Ok(())
}
#[cfg(feature = "aes-ctr")]
fn ctr_encrypt<C>(key: &[u8], iv: &[u8], buffer: &mut [u8]) -> Result<()>
where
C: StreamCipherCore + KeyIvInit,
{
let cipher = C::new_from_slices(key, iv).map_err(|_| Error::KeySize)?;
cipher
.try_apply_keystream_partial(buffer.into())
.map_err(|_| Error::Crypto)?;
Ok(())
}

Binary file not shown.

View File

@@ -0,0 +1 @@
{"name":"ssh-cipher","vers":"0.2.0","deps":[{"name":"aes","req":"^0.8","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"aes-gcm","req":"^0.10","features":["aes"],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"cbc","req":"^0.1","features":[],"optional":true,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"chacha20","req":"^0.9","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"cipher","req":"^0.4","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"ctr","req":"^0.9","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"des","req":"^0.8","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"encoding","req":"^0.2","features":[],"optional":false,"default_features":true,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":"ssh-encoding","public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"poly1305","req":"^0.8","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false},{"name":"subtle","req":"^2","features":[],"optional":true,"default_features":false,"target":null,"kind":"normal","registry":"https://github.com/rust-lang/crates.io-index","package":null,"public":null,"artifact":null,"bindep_target":null,"lib":false}],"features":{"aes-cbc":["dep:aes","dep:cbc"],"aes-ctr":["dep:aes","dep:ctr"],"aes-gcm":["dep:aes","dep:aes-gcm"],"chacha20poly1305":["dep:chacha20","dep:poly1305","dep:subtle"],"std":[],"tdes":["dep:des","dep:cbc"]},"features2":null,"cksum":"3e638ec57b0cbe73847f321d2ceb99b8fadabbe891d10cace22270fb995c4296","yanked":null,"links":null,"rust_version":null,"v":2}