mirror of
https://github.com/stalwartlabs/stalwart.git
synced 2026-11-26 23:29:52 +00:00
v1.0.2
This commit is contained in:
parent
23b69755cb
commit
1d66d65daf
229 changed files with 21994 additions and 5325 deletions
58
CHANGELOG.md
58
CHANGELOG.md
|
|
@ -2,6 +2,64 @@
|
|||
|
||||
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [1.0.2] - 2026-11-02
|
||||
|
||||
**Encryption at rest must be re-enabled after upgrading.** The algorithm is now chosen from each user's key, so the per-account cipher choice of earlier versions (AES-128, AES-256, AES-256-GCM, ChaCha20-Poly1305) no longer exists, and accounts that had encryption at rest enabled are set to `Disabled` on upgrade. Until a user (or an administrator) selects their public key again under the account's encryption settings, new messages for that account are stored unencrypted. Registered public keys and messages already encrypted are not affected. The server-wide settings also moved: `Email.encryptAtRest` is replaced by `atRestEnable` in the new `Encryption` settings (enabled by default, so servers that had disabled it must disable it again), and `Email.encryptOnAppend` by the per-account `encryptOnAppend` setting. See the [encryption at rest documentation](https://stalw.art/docs/encryption/at-rest) for details.
|
||||
|
||||
## Added
|
||||
- Encryption:
|
||||
- OpenPGP ([RFC 9580](https://www.rfc-editor.org/rfc/rfc9580)): v4 and v6 keys; RSA (2048 to 8192 bits), ECDH on NIST P-256, P-384 and P-521, legacy Curve25519, X25519 and X448 encryption keys; SEIPD v1 and SEIPD v2 with AES-OCB or AES-GCM, selected from the key's features and preferences.
|
||||
- Post-quantum OpenPGP ([RFC 9980](https://www.rfc-editor.org/rfc/rfc9980)): ML-KEM-768+X25519 and ML-KEM-1024+X448 keys, with AES-256.
|
||||
- S/MIME ([RFC 8551](https://www.rfc-editor.org/rfc/rfc8551)): RSA with PKCS #1 v1.5 or RSA-OAEP, ECDH on NIST P-256, P-384 and P-521, X25519 and X448 ([RFC 8418](https://www.rfc-editor.org/rfc/rfc8418)) and post-quantum ML-KEM-512, ML-KEM-768 and ML-KEM-1024 ([RFC 9936](https://www.rfc-editor.org/rfc/rfc9936)) certificates; CMS EnvelopedData with AES-256-CBC and AuthEnvelopedData with AES-256-GCM ([RFC 5083](https://www.rfc-editor.org/rfc/rfc5083)).
|
||||
- Header protection ([RFC 9788](https://www.rfc-editor.org/rfc/rfc9788)) for encrypted messages, including Subject hiding and legacy display for messages sent through the gateway.
|
||||
- Public keys: per-key `authenticatedEncryption` (AES-GCM with RSA-OAEP) and `strictKeyWrapEncoding` (RFC 5753 encoding instead of the Outlook-compatible one) switches, and server-computed `keyType`, `fingerprints`, `capabilities` and `warnings` (expiring soon, weak RSA, address mismatch, post-quantum only, no known decryptor, unusable).
|
||||
- Encryption gateway: encrypts outgoing messages for remote recipients with their OpenPGP keys or S/MIME certificates, with a per-recipient `gatewayOutbound` policy (`disable`, `opportunistic` or `required`), a minimum key trust level, a separate encrypted copy per recipient with its own DKIM and DKIM2 signatures, and `5.7.5` bounces when encryption is required but not possible.
|
||||
- External public keys: superuser-managed keys of remote recipients, entered manually or kept up to date from Web Key Directory (WKD), keys.openpgp.org (VKS), HKP keyservers or DNSSEC-validated OPENPGPKEY ([RFC 7929](https://www.rfc-editor.org/rfc/rfc7929)) and SMIMEA ([RFC 8162](https://www.rfc-editor.org/rfc/rfc8162)) records, with trust levels, pinning, approval of key changes, blocked keys and revocation handling. No lookups are made for unknown recipients.
|
||||
- Key harvesting: S/MIME certificates (with their advertised capabilities) and Autocrypt keys are learned from DMARC-authenticated incoming mail, controlled by the `harvestKeys` expression.
|
||||
- S/MIME certificate trust: bundled Mozilla email root certificates, custom trust anchors (`SmimeTrustAnchor`), intermediate certificate retrieval through Authority Information Access and daily certificate revocation list checks.
|
||||
- New `encryption.*` telemetry events and metrics, including the `encryption.key-lookup-time` histogram.
|
||||
- DKIM2:
|
||||
- DSNs are signed with a domain that matches a recipient in the `rt=` of the reported message, as required by spec-08 section 16.2. When no hosted domain matches, the DSN is signed with DKIM only.
|
||||
- DSNs about forwarded messages are propagated to the previous hop in the DKIM2 chain, with the forwarding destination removed and the returned headers restored to how the message arrived (spec-08 section 16.3). This applies to inbound DKIM2 DSNs and to DSNs generated for messages Stalwart forwarded, such as failed Sieve redirects.
|
||||
- New `dkim2.dsn-not-aligned` and `dkim2.dsn-propagated` telemetry events.
|
||||
- OAuth: `Application` objects have an `oauthScopes` list of extra scopes that the WebUI requests at sign-in, for external identity providers that release a claim only with a scope of its own.
|
||||
- OIDC directories: superuser-only `trustedProvider` setting lets a tenant-owned directory reach an identity provider on a private network.
|
||||
|
||||
## Changed
|
||||
- DKIM2: The post-quantum composite `ML-DSA-44` and `Ed25519` algorithm with `SHA-512` is replaced by pure `ML-DSA-44` (as per [draft-ietf-dkim-dkim2-spec-08](https://datatracker.ietf.org/doc/html/draft-ietf-dkim-dkim2-spec-08)).
|
||||
- vCard and iCalendar: `QUOTED-PRINTABLE` values without a `CHARSET` parameter are decoded as UTF-8 when valid, otherwise as Windows-1252, instead of ISO-8859-1.
|
||||
|
||||
## Fixed
|
||||
- DKIM: Relaxed body canonicalization ignores whitespace-only lines at the end of the body (RFC 6376, section 3.4.4), which produced a `bh=` that other implementations rejected.
|
||||
- iTIP: A full `REQUEST` with an older `SEQUENCE` no longer removes a newer override from the attendee's copy (RFC 5546, section 2.1.5).
|
||||
- Applications: A cached application bundle that failed the manifest check (such as the WebUI 1.x bundle left by v0.16 in a shared blob store) was never replaced, so `/admin` and `/account` returned 404; it is now downloaded again.
|
||||
- HTTP: Error responses sent before the request body is read (such as a `401`) include `Connection: close`, instead of the connection being closed without notice.
|
||||
- HTTP: A response with an invalid header value, such as a JMAP download whose `accept` parameter contains a line break, returns `500` instead of aborting the connection.
|
||||
- IMAP
|
||||
- `RENAME` refuses to move a mailbox into its own subtree (such as `A` to `A/B/C`) with `NO [CANNOT]`, instead of creating a parent loop.
|
||||
- Single-level mailbox names are checked against `maxMailboxNameLength`, which only applied to names containing `/`.
|
||||
- Client quirks are detected from the `ID` command, and `UIDONLY` is not enabled for Microsoft's sync service (`Microsoft Office 365`), which left the new Outlook without folders or mail.
|
||||
- Mailboxes: IMAP, JMAP and Sieve `fileinto` accept names of up to `maxMailboxNameLength` octets (RFC 8621, section 1.6.1); JMAP `Mailbox/set` rejected names of exactly that length.
|
||||
- JMAP
|
||||
- Messages added with IMAP `APPEND`/`MULTIAPPEND` or `Email/import` send an `EmailPush` with their id, so push subscribers no longer get an empty notification.
|
||||
- `Email/queryChanges` with `collapseThreads` reports the previous representative of a thread as removed when a newer email joins the thread, and adds it back when that email is destroyed.
|
||||
- `Email/set` places inline attachments that have a `cid` (image, audio or video, disposition not `attachment`) in `multipart/related` with the HTML body instead of `multipart/mixed`, so clients display them in the message body and `Email/get` returns them in `attachments`.
|
||||
- `Email/get`, `Email/set`, `Email/copy` and `SearchSnippet/get` return `notFound` for an Email id destroyed by a thread merge instead of resolving it with the stale `threadId`.
|
||||
- The upload endpoint rejects uploads to accounts the caller is not a member of and to account ids that do not exist, as `Blob/upload` already did.
|
||||
- OAuth: Scope values the server does not know, such as the OpenID Connect `email` and `profile` scopes, are ignored at the authorization endpoint instead of failing with `invalid_scope` (OpenID Connect Core, section 3.1.2.1).
|
||||
- OAuth: App passwords and API keys are refused at interactive sign-in (WebUI login and device code approval), which issued a session with the account's full permissions and skipped two-factor authentication.
|
||||
- Milter
|
||||
- `SMFIC_BODY` carries only the message body instead of the whole message, so milters no longer receive the headers twice.
|
||||
- Header names and values that are not valid UTF-8 are sent to the milter as raw bytes instead of empty strings.
|
||||
- Search indexing
|
||||
- An email whose blob is missing is logged and skipped instead of failing its whole index partition and being retried forever.
|
||||
- Tracing spans queued for indexing are discarded when no tracing store is configured (for example after the enterprise license expires) instead of failing with `store.not-configured` forever.
|
||||
- Calendar: events whose owner participant has no calendar address are treated as owned when checking the `mayWriteOwn` right.
|
||||
- vCard: yearless `--MM-DD` dates keep their day when uploaded, and month-only dates are written zero-padded (`--03`).
|
||||
- Spam filter: `MIXED_CHARSET` only compares the scripts of letters, so single-script text containing characters such as U+202F no longer triggers it.
|
||||
- Telemetry: Outbound HTTP errors log their cause, such as a refused non-public address, instead of only `error sending request`.
|
||||
- Accounts: `DestroyAccount` removes the account's spam training samples, whose message bodies otherwise stayed in the blob store for up to `holdSamplesFor`.
|
||||
|
||||
## [1.0.1] - 2026-10-28
|
||||
|
||||
## Added
|
||||
|
|
|
|||
1598
Cargo.lock
generated
1598
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -36,6 +36,7 @@ members = [
|
|||
"crates/sieve",
|
||||
"crates/jmap-tools",
|
||||
"crates/s3",
|
||||
"crates/crypto",
|
||||
]
|
||||
default-members = [
|
||||
"crates/main",
|
||||
|
|
|
|||
11
README.md
11
README.md
|
|
@ -88,8 +88,17 @@ Key features:
|
|||
- Automatic account configuration and discovery with [PACC](https://datatracker.ietf.org/doc/draft-ietf-mailmaint-pacc/), [autoconfig](https://datatracker.ietf.org/doc/draft-ietf-mailmaint-autoconfig/) and [autodiscover](https://learn.microsoft.com/en-us/exchange/architecture/client-access/autodiscover?view=exchserver-2019).
|
||||
- Multi-tenancy support with domain and tenant isolation.
|
||||
- Disk quotas per user and tenant.
|
||||
- **Encryption** with **OpenPGP** and **S/MIME**:
|
||||
- Encryption at rest of each user's mailbox with their own OpenPGP key or S/MIME certificate.
|
||||
- Encryption gateway that encrypts outgoing mail for remote recipients, with opportunistic or required policies and no software needed on the sender's side.
|
||||
- Recipient key discovery from Web Key Directory, keys.openpgp.org, HKP keyservers and DNSSEC-validated OPENPGPKEY and SMIMEA records.
|
||||
- Key harvesting from S/MIME signatures and Autocrypt headers of authenticated incoming mail.
|
||||
- S/MIME certificate validation with bundled root certificates, custom trust anchors and revocation lists.
|
||||
- Post-quantum encryption with ML-KEM for both OpenPGP ([RFC 9980](https://www.rfc-editor.org/rfc/rfc9980)) and S/MIME ([RFC 9936](https://www.rfc-editor.org/rfc/rfc9936)).
|
||||
- OpenPGP v4 and v6 keys with RSA, ECDH (NIST P-256, P-384, P-521, Curve25519), X25519 and X448, and AES-OCB or AES-GCM authenticated encryption ([RFC 9580](https://www.rfc-editor.org/rfc/rfc9580)).
|
||||
- S/MIME with RSA (PKCS #1 v1.5 and RSA-OAEP), ECDH (NIST P-256, P-384, P-521), X25519 and X448 certificates, and AES-CBC or AES-GCM content encryption.
|
||||
- [Header protection](https://www.rfc-editor.org/rfc/rfc9788) with Subject hiding.
|
||||
- **Secure and robust**:
|
||||
- Encryption at rest with **S/MIME** or **OpenPGP**.
|
||||
- Automatic TLS certificate provisioning with [ACME](https://datatracker.ietf.org/doc/html/rfc8555) using `TLS-ALPN-01`, `DNS-01`, `DNS-PERSIST-01` or `HTTP-01` challenges.
|
||||
- Automated blocking of IP addresses that attack, abuse or scan the server for exploits.
|
||||
- SSRF protection for outbound requests.
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
[package]
|
||||
name = "calcard"
|
||||
description = "iCalendar/JSCalendar and vCard/JSContact parsing, building and conversion library"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ use encodify::{
|
|||
use mail_parser::Charset;
|
||||
use std::borrow::Cow;
|
||||
|
||||
const QUOTED_PRINTABLE_CHARSET: &str = "iso-8859-1";
|
||||
const QUOTED_PRINTABLE_CHARSET: Charset = Charset::Windows1252;
|
||||
const QUOTED_PRINTABLE: QuotedPrintable = qp::BODY.strict();
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
|
|
@ -45,16 +45,17 @@ impl ValueDecoder<'_> {
|
|||
if self.binary {
|
||||
return Decoded::Binary(bytes.into_owned());
|
||||
}
|
||||
let default_charset = match self.encoding {
|
||||
Encoding::QuotedPrintable => Some(QUOTED_PRINTABLE_CHARSET),
|
||||
Encoding::Base64 => None,
|
||||
let charset = match (self.charset, self.encoding) {
|
||||
(Some(label), _) => Charset::from_label(label.as_bytes()),
|
||||
(None, Encoding::QuotedPrintable) => {
|
||||
return Decoded::Text(match String::from_utf8(bytes.into_owned()) {
|
||||
Ok(text) => text,
|
||||
Err(err) => QUOTED_PRINTABLE_CHARSET.decode_owned(err.into_bytes()),
|
||||
});
|
||||
}
|
||||
(None, Encoding::Base64) => None,
|
||||
};
|
||||
match self
|
||||
.charset
|
||||
.or(default_charset)
|
||||
.and_then(|charset| Charset::from_label(charset.as_bytes()))
|
||||
.filter(|charset| *charset != Charset::Utf8)
|
||||
{
|
||||
match charset.filter(|charset| *charset != Charset::Utf8) {
|
||||
Some(charset) => Decoded::Text(match bytes {
|
||||
Cow::Borrowed(bytes) => charset.decode(bytes).into_owned(),
|
||||
Cow::Owned(bytes) => charset.decode_owned(bytes),
|
||||
|
|
|
|||
|
|
@ -872,6 +872,9 @@ impl PartialDateTime {
|
|||
parse_small_digits(iter, &mut self.month, 2, true);
|
||||
} else {
|
||||
parse_small_digits(iter, &mut self.month, 2, true);
|
||||
if self.year.is_none() && self.month.is_some() && iter.peek() == Some(&&b'-') {
|
||||
iter.next();
|
||||
}
|
||||
parse_small_digits(iter, &mut self.day, 2, false);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -368,7 +368,7 @@ impl PartialDateTime {
|
|||
}
|
||||
(None, Some(month), None) => {
|
||||
buf.push_ascii(b"--")?;
|
||||
buf.push_u64(month.into())?;
|
||||
buf.push_2_digits(month)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
|
@ -477,7 +477,7 @@ impl PartialDateTime {
|
|||
}
|
||||
(None, Some(month), None) => {
|
||||
buf.push_ascii(b"--")?;
|
||||
buf.push_u64(month.into())?;
|
||||
buf.push_2_digits(month)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "common"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
edition = "2024"
|
||||
build = "build.rs"
|
||||
|
||||
|
|
@ -14,11 +14,12 @@ directory = { path = "../directory" }
|
|||
coordinator = { path = "../coordinator" }
|
||||
types = { path = "../types" }
|
||||
registry = { path = "../registry" }
|
||||
crypto = { path = "../crypto" }
|
||||
jmap_proto = { path = "../jmap-proto" }
|
||||
sieve-rs = { path = "../sieve", features = ["serde"] }
|
||||
mail-parser = { version = "1.0", features = ["full_encoding"] }
|
||||
mail-builder = { version = "2.0" }
|
||||
mail-auth = { version = "0.14", features = ["generate", "arc"] }
|
||||
mail-auth = { version = "0.15.1", features = ["generate", "arc"] }
|
||||
smtp-report = { path = "../smtp-report" }
|
||||
smtp-proto = { path = "../smtp-proto", features = ["rkyv"] }
|
||||
dns-update = { version = "0.6" }
|
||||
|
|
@ -31,7 +32,7 @@ rustls = { version = "0.23.46", default-features = false, features = ["std", "aw
|
|||
rustls-pemfile = "2.2"
|
||||
rustls-pki-types = { version = "1" }
|
||||
aws-lc-rs = { version = "1" }
|
||||
tokio = { version = "1.54", features = ["net", "macros", "sync", "time"] }
|
||||
tokio = { version = "1.54", features = ["net", "macros", "sync", "time", "rt-multi-thread"] }
|
||||
tokio-rustls = { version = "0.26", default-features = false, features = ["aws_lc_rs", "tls12"] }
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
futures = "0.3"
|
||||
|
|
@ -67,15 +68,13 @@ p384 = { version = "0.14", features = ["ecdh"] }
|
|||
hashify = "0.3"
|
||||
rkyv.workspace = true
|
||||
tinyvec = { version = "1.13.3", features = ["alloc"] }
|
||||
smallvec = "1.16"
|
||||
compact_str = { version = "0.10.0", features = ["rkyv", "serde"] }
|
||||
bytes = "1"
|
||||
lz4_flex = { version = "0.14", features = ["frame"], default-features = false }
|
||||
hickory-proto = "0.26.3"
|
||||
nohash-hasher = "0.2.0"
|
||||
quick_cache = "0.7"
|
||||
rasn = "0.29"
|
||||
rasn-pkix = "0.29"
|
||||
sequoia-openpgp = { version = "2.4", default-features = false, features = ["crypto-rust", "allow-experimental-crypto", "allow-variable-time-crypto"] }
|
||||
zxcvbn = "3.1.1"
|
||||
pkcs8 = { version = "0.11.0", features = ["alloc", "std"] }
|
||||
quick-xml = "0.42"
|
||||
|
|
|
|||
|
|
@ -724,6 +724,11 @@ impl AccessToken {
|
|||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn is_secondary_credential(&self) -> bool {
|
||||
self.scope_idx > 0
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn credential_id(&self) -> Option<u32> {
|
||||
self.inner
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use crate::{
|
|||
auth::{active_script::ActiveScriptSlot, oauth::scope::OAuthScopes},
|
||||
expr::if_block::IfBlock,
|
||||
network::limiter::AccountLimits,
|
||||
storage::ObjectQuota,
|
||||
storage::{ObjectQuota, encryption::AccountEncryption},
|
||||
};
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
|
|
@ -115,7 +115,7 @@ pub struct AccountCache {
|
|||
#[derive(Debug, Clone, Default)]
|
||||
pub struct AccountStorage {
|
||||
pub quota_objects: Option<ObjectQuota>,
|
||||
pub encryption_key: Option<EncryptionKeys>,
|
||||
pub encryption: Option<Arc<AccountEncryption>>,
|
||||
}
|
||||
|
||||
const _: () = assert!(size_of::<AccountCache>() <= 112);
|
||||
|
|
@ -123,28 +123,18 @@ const _: () = assert!(size_of::<AccountCache>() <= 112);
|
|||
impl AccountStorage {
|
||||
pub fn boxed(
|
||||
quota_objects: Option<ObjectQuota>,
|
||||
encryption_key: Option<EncryptionKeys>,
|
||||
encryption: Option<Arc<AccountEncryption>>,
|
||||
) -> Option<Box<Self>> {
|
||||
(quota_objects.is_some() || encryption_key.is_some()).then(|| {
|
||||
(quota_objects.is_some() || encryption.is_some()).then(|| {
|
||||
Box::new(AccountStorage {
|
||||
quota_objects,
|
||||
encryption_key,
|
||||
encryption,
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub type EncryptionKeys = Box<[Box<[u8]>]>;
|
||||
|
||||
pub const ACCOUNT_IS_USER: u64 = 1;
|
||||
pub const ACCOUNT_FLAG_ENCRYPT_TRAIN_SPAM_FILTER: u64 = 1 << 1;
|
||||
pub const ACCOUNT_FLAG_ENCRYPT_METHOD_SMIME: u64 = 1 << 2;
|
||||
pub const ACCOUNT_FLAG_ENCRYPT_METHOD_PGP: u64 = 1 << 3;
|
||||
pub const ACCOUNT_FLAG_ENCRYPT_ALGO_AES256: u64 = 1 << 4;
|
||||
pub const ACCOUNT_FLAG_ENCRYPT_ALGO_AES128: u64 = 1 << 5;
|
||||
pub const ACCOUNT_FLAG_ENCRYPT_APPEND: u64 = 1 << 6;
|
||||
pub const ACCOUNT_FLAG_ENCRYPT_ALGO_AES256_GCM: u64 = 1 << 7;
|
||||
pub const ACCOUNT_FLAG_ENCRYPT_ALGO_CHACHA20_POLY1305: u64 = 1 << 8;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RoleCache {
|
||||
|
|
@ -338,11 +328,7 @@ impl CacheItemWeight for AccountCache {
|
|||
impl CacheItemWeight for AccountStorage {
|
||||
fn weight(&self) -> u64 {
|
||||
std::mem::size_of::<AccountStorage>() as u64
|
||||
+ self.encryption_key.as_ref().map_or(0, |keys| {
|
||||
keys.iter()
|
||||
.map(|k| k.len() as u64 + std::mem::size_of::<Box<[u8]>>() as u64)
|
||||
.sum::<u64>()
|
||||
})
|
||||
+ self.encryption.as_ref().map_or(0, |e| e.weight())
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ use store::{
|
|||
};
|
||||
use trc::{AddContext, AuthEvent};
|
||||
use utils::{
|
||||
HttpLimitResponse,
|
||||
HttpLimitResponse, error_chain,
|
||||
http::http_client_builder,
|
||||
outbound::{OutboundClient, OutboundError, OutboundPolicy, Redirects},
|
||||
};
|
||||
|
|
@ -344,7 +344,7 @@ async fn fetch_cimd_document(url: Url) -> Result<(Vec<u8>, u64), CimdError> {
|
|||
trc::event!(
|
||||
Auth(AuthEvent::Error),
|
||||
Url = display_url.clone(),
|
||||
Reason = err.to_string(),
|
||||
Reason = error_chain(&err),
|
||||
Details = "Failed to fetch client metadata document",
|
||||
);
|
||||
CimdError::Fetch
|
||||
|
|
|
|||
33
crates/common/src/cache/invalidate.rs
vendored
33
crates/common/src/cache/invalidate.rs
vendored
|
|
@ -7,6 +7,7 @@
|
|||
use crate::{
|
||||
Inner, Server,
|
||||
auth::{EmailAddressRef, EmailCache},
|
||||
gateway::resolver::KeyCacheKey,
|
||||
ipc::{BroadcastEvent, CacheInvalidation, PushNotification},
|
||||
};
|
||||
use ahash::AHashSet;
|
||||
|
|
@ -231,6 +232,23 @@ impl CacheInvalidationBuilder {
|
|||
}
|
||||
}
|
||||
|
||||
(ObjectInner::PublicKey(current), ObjectInner::PublicKey(new))
|
||||
if current.key != new.key
|
||||
|| current.strict_key_wrap_encoding != new.strict_key_wrap_encoding
|
||||
|| current.authenticated_encryption != new.authenticated_encryption =>
|
||||
{
|
||||
self.invalidate(CacheInvalidation::Account(new.account_id.document_id()));
|
||||
}
|
||||
|
||||
(ObjectInner::ExternalPublicKey(current), ObjectInner::ExternalPublicKey(new)) => {
|
||||
self.invalidate(CacheInvalidation::ExternalPublicKey(
|
||||
KeyCacheKey::address_hash(¤t.email_address),
|
||||
));
|
||||
self.invalidate(CacheInvalidation::ExternalPublicKey(
|
||||
KeyCacheKey::address_hash(&new.email_address),
|
||||
));
|
||||
}
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
|
|
@ -287,6 +305,11 @@ impl CacheInvalidationBuilder {
|
|||
let grant_id = id.id();
|
||||
let id = id.document_id();
|
||||
match &object.inner {
|
||||
ObjectInner::ExternalPublicKey(key) => {
|
||||
self.invalidate(CacheInvalidation::ExternalPublicKey(
|
||||
KeyCacheKey::address_hash(&key.email_address),
|
||||
));
|
||||
}
|
||||
ObjectInner::OAuthGrant(grant) => {
|
||||
self.invalidate(CacheInvalidation::OAuthGrant {
|
||||
account_id: grant.account_id.document_id(),
|
||||
|
|
@ -329,6 +352,11 @@ impl CacheInvalidationBuilder {
|
|||
|
||||
pub fn process_create(&mut self, object: &Object) {
|
||||
match &object.inner {
|
||||
ObjectInner::ExternalPublicKey(key) => {
|
||||
self.invalidate(CacheInvalidation::ExternalPublicKey(
|
||||
KeyCacheKey::address_hash(&key.email_address),
|
||||
));
|
||||
}
|
||||
ObjectInner::Domain(_) => {
|
||||
self.invalidate(CacheInvalidation::DomainNegative);
|
||||
}
|
||||
|
|
@ -627,6 +655,11 @@ impl Server {
|
|||
CacheInvalidation::DomainNegative => {
|
||||
cache.domain_names_negative.clear();
|
||||
}
|
||||
CacheInvalidation::ExternalPublicKey(address_hash) => {
|
||||
cache
|
||||
.external_public_keys
|
||||
.retain(|key| KeyCacheKey::address_hash(&key.address) != *address_hash);
|
||||
}
|
||||
CacheInvalidation::PrivateMetadata(id) => {
|
||||
cache.metadata_viewers.invalidate(*id);
|
||||
}
|
||||
|
|
|
|||
122
crates/common/src/cache/principals.rs
vendored
122
crates/common/src/cache/principals.rs
vendored
|
|
@ -7,13 +7,9 @@
|
|||
use crate::{
|
||||
Server,
|
||||
auth::{
|
||||
ACCOUNT_FLAG_ENCRYPT_ALGO_AES128, ACCOUNT_FLAG_ENCRYPT_ALGO_AES256,
|
||||
ACCOUNT_FLAG_ENCRYPT_ALGO_AES256_GCM, ACCOUNT_FLAG_ENCRYPT_ALGO_CHACHA20_POLY1305,
|
||||
ACCOUNT_FLAG_ENCRYPT_APPEND, ACCOUNT_FLAG_ENCRYPT_METHOD_PGP,
|
||||
ACCOUNT_FLAG_ENCRYPT_METHOD_SMIME, ACCOUNT_FLAG_ENCRYPT_TRAIN_SPAM_FILTER, ACCOUNT_IS_USER,
|
||||
AccountCache, AccountInfo, AccountStorage, ChangedBy, DOMAIN_FLAG_RELAY,
|
||||
ACCOUNT_IS_USER, AccountCache, AccountInfo, AccountStorage, ChangedBy, DOMAIN_FLAG_RELAY,
|
||||
DOMAIN_FLAG_SUB_ADDRESSING, DomainCache, EmailAddress, EmailAddressRef, EmailCache,
|
||||
EncryptionKeys, MailingListCache, PermissionsGroup, RECOVERY_ADMIN_ID, RoleCache,
|
||||
MailingListCache, PermissionsGroup, RECOVERY_ADMIN_ID, RoleCache,
|
||||
permissions::BuildPermissions,
|
||||
},
|
||||
config::smtp::auth::DkimSigners,
|
||||
|
|
@ -21,7 +17,7 @@ use crate::{
|
|||
network::mta::AddressResolver,
|
||||
storage::{
|
||||
ObjectQuota,
|
||||
encryption::{EncryptionMethod, parse_public_key},
|
||||
encryption::{AccountEncryption, EncryptionKeys},
|
||||
},
|
||||
};
|
||||
// SPDX-SnippetBegin
|
||||
|
|
@ -41,8 +37,8 @@ use registry::{
|
|||
enums::{DkimRotationStage, Locale, StorageQuota},
|
||||
prelude::{ObjectType, Property},
|
||||
structs::{
|
||||
Account, DkimSignature, Domain, EncryptionAtRest, MailingList, PublicKey, Role,
|
||||
SubAddressing,
|
||||
Account, DkimSignature, Domain, EncryptionAtRest, EncryptionSettings, MailingList,
|
||||
PublicKey, Role, SubAddressing,
|
||||
},
|
||||
},
|
||||
types::id::ObjectId,
|
||||
|
|
@ -51,7 +47,7 @@ use std::{borrow::Cow, sync::Arc};
|
|||
use store::{
|
||||
U32_LEN,
|
||||
registry::{RegistryQuery, bootstrap::Bootstrap},
|
||||
write::key::KeySerializer,
|
||||
write::{key::KeySerializer, now},
|
||||
};
|
||||
use trc::{AddContext, CacheEvent};
|
||||
use types::id::Id;
|
||||
|
|
@ -62,8 +58,6 @@ use utils::DomainPart;
|
|||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
use registry::schema::structs::MaskedEmail;
|
||||
#[cfg(feature = "enterprise")]
|
||||
use store::write::now;
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
impl Server {
|
||||
|
|
@ -434,73 +428,13 @@ impl Server {
|
|||
}
|
||||
}
|
||||
|
||||
let mut flags = ACCOUNT_IS_USER;
|
||||
let encryption_settings = match account.encryption_at_rest {
|
||||
let encryption = match account.encryption_at_rest {
|
||||
EncryptionAtRest::Disabled => None,
|
||||
EncryptionAtRest::Aes256(settings) => {
|
||||
flags |= ACCOUNT_FLAG_ENCRYPT_ALGO_AES256;
|
||||
settings.into()
|
||||
}
|
||||
EncryptionAtRest::Aes128(settings) => {
|
||||
flags |= ACCOUNT_FLAG_ENCRYPT_ALGO_AES128;
|
||||
settings.into()
|
||||
}
|
||||
EncryptionAtRest::Aes256Gcm(settings) => {
|
||||
flags |= ACCOUNT_FLAG_ENCRYPT_ALGO_AES256_GCM;
|
||||
settings.into()
|
||||
}
|
||||
EncryptionAtRest::ChaCha20Poly1305(settings) => {
|
||||
flags |= ACCOUNT_FLAG_ENCRYPT_ALGO_CHACHA20_POLY1305;
|
||||
settings.into()
|
||||
}
|
||||
};
|
||||
let encryption_key = if let Some(settings) = encryption_settings {
|
||||
if settings.allow_spam_training {
|
||||
flags |= ACCOUNT_FLAG_ENCRYPT_TRAIN_SPAM_FILTER;
|
||||
}
|
||||
if settings.encrypt_on_append {
|
||||
flags |= ACCOUNT_FLAG_ENCRYPT_APPEND;
|
||||
}
|
||||
if let Some(public_key) = self
|
||||
.registry()
|
||||
.object::<PublicKey>(settings.public_key)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
match parse_public_key(&public_key).and_then(|params| {
|
||||
params.ok_or(Cow::Borrowed("No public key found"))
|
||||
}) {
|
||||
Ok(params) => {
|
||||
match params.method {
|
||||
EncryptionMethod::PGP => {
|
||||
flags |= ACCOUNT_FLAG_ENCRYPT_METHOD_PGP
|
||||
}
|
||||
EncryptionMethod::SMIME => {
|
||||
flags |= ACCOUNT_FLAG_ENCRYPT_METHOD_SMIME
|
||||
}
|
||||
}
|
||||
Some(params.certs)
|
||||
}
|
||||
Err(err) => {
|
||||
trc::error!(
|
||||
trc::EventType::Registry(
|
||||
trc::RegistryEvent::ValidationError
|
||||
)
|
||||
.into_err()
|
||||
.details("Invalid public key, encryption disabled")
|
||||
.reason(err)
|
||||
.account_id(account_id)
|
||||
.ctx(trc::Key::Id, settings.public_key.id())
|
||||
.caused_by(trc::location!())
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
EncryptionAtRest::Enabled(settings) => Some(Arc::new(
|
||||
self.build_account_encryption(account_id, settings)
|
||||
.await
|
||||
.caused_by(trc::location!())?,
|
||||
)),
|
||||
};
|
||||
|
||||
AccountCache {
|
||||
|
|
@ -535,9 +469,9 @@ impl Server {
|
|||
.collect(),
|
||||
quota_disk,
|
||||
description: account.description.map(Into::into),
|
||||
storage: AccountStorage::boxed(quota_objects, encryption_key),
|
||||
storage: AccountStorage::boxed(quota_objects, encryption),
|
||||
locale: account.locale,
|
||||
flags,
|
||||
flags: ACCOUNT_IS_USER,
|
||||
active_script: Default::default(),
|
||||
}
|
||||
}
|
||||
|
|
@ -1065,10 +999,10 @@ impl AccountCache {
|
|||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn encryption_key(&self) -> Option<&EncryptionKeys> {
|
||||
pub fn encryption(&self) -> Option<&AccountEncryption> {
|
||||
self.storage
|
||||
.as_ref()
|
||||
.and_then(|storage| storage.encryption_key.as_ref())
|
||||
.and_then(|storage| storage.encryption.as_deref())
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
|
|
@ -1084,3 +1018,27 @@ impl AccountCache {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Server {
|
||||
async fn build_account_encryption(
|
||||
&self,
|
||||
account_id: u32,
|
||||
settings: EncryptionSettings,
|
||||
) -> trc::Result<AccountEncryption> {
|
||||
let public_key = self
|
||||
.registry()
|
||||
.object::<PublicKey>(settings.public_key)
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
let encryption = AccountEncryption::build(&settings, public_key.as_ref(), now());
|
||||
if let EncryptionKeys::Unusable(reason) = &encryption.keys {
|
||||
trc::event!(
|
||||
Encryption(trc::EncryptionEvent::KeyUnusable),
|
||||
AccountId = account_id,
|
||||
Id = settings.public_key.id(),
|
||||
Reason = reason.as_str(),
|
||||
);
|
||||
}
|
||||
Ok(encryption)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ use std::{
|
|||
sync::Arc,
|
||||
};
|
||||
use store::{LookupStores, registry::bootstrap::Bootstrap};
|
||||
use tokio::sync::Semaphore;
|
||||
use types::collection::SyncCollection;
|
||||
use utils::{
|
||||
UnwrapFailure,
|
||||
|
|
@ -51,6 +52,8 @@ use utils::{
|
|||
tls::build_tls_connector,
|
||||
};
|
||||
|
||||
const MAX_HARVEST_TASKS: usize = 8;
|
||||
|
||||
impl Data {
|
||||
pub async fn parse(bp: &mut Bootstrap) -> Self {
|
||||
// Parse certificates
|
||||
|
|
@ -108,6 +111,7 @@ impl Data {
|
|||
logos: Default::default(),
|
||||
smtp_connectors: TlsConnectors::try_new().failed("Failed to build TLS connectors"),
|
||||
memory_budget: Default::default(),
|
||||
harvest_tasks: Arc::new(Semaphore::new(MAX_HARVEST_TASKS)),
|
||||
asn_geo_data: Default::default(),
|
||||
password_verifier: Default::default(),
|
||||
}
|
||||
|
|
@ -245,6 +249,7 @@ impl Caches {
|
|||
(std::mem::size_of::<SpamLookup>() + 255 * 2) as u64,
|
||||
),
|
||||
directory_recipients: CacheWithTtl::new(cache.directory_recipients, 255u64),
|
||||
external_public_keys: CacheWithTtl::new(cache.external_public_keys, 4096u64),
|
||||
directory_recipients_ttl: cache.directory_recipients_ttl.into_inner(),
|
||||
negative_cache_ttl: cache.negative_ttl.into_inner(),
|
||||
swap,
|
||||
|
|
@ -303,6 +308,7 @@ impl Default for Data {
|
|||
logos: Default::default(),
|
||||
smtp_connectors: TlsConnectors::try_new().unwrap(),
|
||||
memory_budget: Default::default(),
|
||||
harvest_tasks: Arc::new(Semaphore::new(MAX_HARVEST_TASKS)),
|
||||
asn_geo_data: Default::default(),
|
||||
password_verifier: Default::default(),
|
||||
lookup_stores: Default::default(),
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
|
||||
use crate::{
|
||||
config::mailstore::limits::{EmailLimits, MAX_HEADER_ENTRIES},
|
||||
gateway::config::GatewayConfig,
|
||||
storage::ObjectQuota,
|
||||
};
|
||||
use ahash::{AHashMap, AHashSet};
|
||||
|
|
@ -18,13 +19,13 @@ use registry::{
|
|||
},
|
||||
prelude::ObjectType,
|
||||
structs::{
|
||||
AddressBook, Authentication, Calendar, DataRetention, Domain, Email, FileStorage, Jmap,
|
||||
Search, SieveUserInterpreter, SystemSettings,
|
||||
AddressBook, Authentication, Calendar, DataRetention, Domain, Email, Encryption,
|
||||
FileStorage, Jmap, Search, SieveUserInterpreter, SystemSettings,
|
||||
},
|
||||
},
|
||||
types::EnumImpl,
|
||||
};
|
||||
use std::time::Duration;
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use store::{
|
||||
registry::bootstrap::Bootstrap,
|
||||
search::{
|
||||
|
|
@ -59,7 +60,7 @@ pub struct EmailConfig {
|
|||
pub shared_folder: String,
|
||||
|
||||
pub encrypt: bool,
|
||||
pub encrypt_append: bool,
|
||||
pub gateway: Option<Arc<GatewayConfig>>,
|
||||
|
||||
pub index_batch_size: usize,
|
||||
pub index_concurrency: usize,
|
||||
|
|
@ -96,8 +97,21 @@ pub struct DefaultFolder {
|
|||
}
|
||||
|
||||
impl EmailConfig {
|
||||
pub fn is_mailbox_name_too_long(&self, name: &str) -> bool {
|
||||
name.len() > self.mailbox_name_max_len
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn gateway_outbound_enabled(&self) -> bool {
|
||||
self.gateway
|
||||
.as_ref()
|
||||
.is_some_and(|gateway| gateway.outbound_enabled)
|
||||
}
|
||||
|
||||
pub async fn parse(bp: &mut Bootstrap) -> Self {
|
||||
let email = bp.setting_infallible::<Email>().await;
|
||||
let encryption = bp.setting_infallible::<Encryption>().await;
|
||||
let gateway = GatewayConfig::parse(bp, &encryption);
|
||||
let dr = bp.setting_infallible::<DataRetention>().await;
|
||||
let sieve = bp.setting_infallible::<SieveUserInterpreter>().await;
|
||||
let search = bp.setting_infallible::<Search>().await;
|
||||
|
|
@ -331,8 +345,8 @@ impl EmailConfig {
|
|||
changes_max_history: dr.max_changes_history.map(|v| v as usize),
|
||||
share_notification_max_history: dr.expunge_share_notify_after.map(|v| v.into_inner()),
|
||||
sieve_max_script_name: sieve.max_script_name_length as usize,
|
||||
encrypt: email.encrypt_at_rest,
|
||||
encrypt_append: email.encrypt_on_append,
|
||||
encrypt: encryption.at_rest_enable,
|
||||
gateway,
|
||||
index_batch_size: std::cmp::max(search.index_batch_size as usize, 1),
|
||||
index_concurrency: std::cmp::max(search.max_concurrent_index_tasks as usize, 1),
|
||||
index_fields,
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ use crate::expr::{
|
|||
use compact_str::ToCompactString;
|
||||
use encodify::{Error as CodecError, base64::LENIENT, pem};
|
||||
use mail_auth::{
|
||||
crypto::{DkimKey, Ed25519Key, HashAlgorithm, MlDsa44Ed25519Key, RsaKey, Sha256, SigningKey},
|
||||
crypto::{DkimKey, Ed25519Key, HashAlgorithm, MlDsa44Key, RsaKey, Sha256, SigningKey},
|
||||
dkim::Canonicalization,
|
||||
dkim2::{Dkim2Hash, Dkim2Signer, Flag},
|
||||
signer::Ready,
|
||||
|
|
@ -174,9 +174,9 @@ impl DkimSigners {
|
|||
})
|
||||
.await?;
|
||||
}
|
||||
DkimSignature::Dkim2MlDsa44Ed25519Sha512(signature) => {
|
||||
DkimSignature::Dkim2MlDsa44(signature) => {
|
||||
self.insert_dkim2(domain, signature, |pem| {
|
||||
mldsa44_ed25519_key_parse(pem).map(DkimKey::from)
|
||||
mldsa44_key_parse(pem).map(DkimKey::from)
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
|
|
@ -258,16 +258,16 @@ fn ed25519_key_parse(pem: &str) -> trc::Result<Ed25519Key> {
|
|||
})
|
||||
}
|
||||
|
||||
fn mldsa44_ed25519_key_parse(pem: &str) -> trc::Result<MlDsa44Ed25519Key> {
|
||||
fn mldsa44_key_parse(pem: &str) -> trc::Result<MlDsa44Key> {
|
||||
let der = pem_or_base64_decode(pem).map_err(|_| {
|
||||
trc::DkimEvent::BuildError
|
||||
.reason("Failed to parse ML-DSA-44/Ed25519 private key PEM")
|
||||
.reason("Failed to parse ML-DSA-44 private key PEM")
|
||||
.details("Invalid PEM format")
|
||||
})?;
|
||||
MlDsa44Ed25519Key::from_pkcs8_der(&der).map_err(|err| {
|
||||
MlDsa44Key::from_pkcs8_der(&der).map_err(|err| {
|
||||
trc::DkimEvent::BuildError
|
||||
.reason(err)
|
||||
.details("Failed to build ML-DSA-44/Ed25519 key")
|
||||
.details("Failed to build ML-DSA-44 key")
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ use std::{
|
|||
time::Duration,
|
||||
};
|
||||
use utils::{
|
||||
HttpLimitResponse,
|
||||
HttpLimitResponse, error_chain,
|
||||
outbound::{OutboundClient, OutboundError, OutboundPolicy, Redirects},
|
||||
};
|
||||
|
||||
|
|
@ -116,7 +116,7 @@ impl From<LogoLoadError> for trc::Error {
|
|||
LogoLoadError::Download(err) => trc::ResourceEvent::DownloadExternal
|
||||
.into_err()
|
||||
.details("Failed to download logo")
|
||||
.reason(err),
|
||||
.reason(error_chain(&err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
246
crates/common/src/gateway/config.rs
Normal file
246
crates/common/src/gateway/config.rs
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::expr::{
|
||||
Constant, ExpressionItem, Variable,
|
||||
if_block::{BootstrapExprExt, IfBlock},
|
||||
};
|
||||
use crypto::{HeaderProtection, KeyKind};
|
||||
use registry::schema::{
|
||||
enums::{
|
||||
ExpressionConstant, HeaderProtection as RegistryHeaderProtection, KeyTrust, PublicKeyKind,
|
||||
},
|
||||
prelude::{ObjectType, Property},
|
||||
structs::Encryption,
|
||||
};
|
||||
use reqwest::Proxy;
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use store::registry::bootstrap::Bootstrap;
|
||||
use utils::{
|
||||
http::http_client_builder,
|
||||
outbound::{OutboundClient, OutboundPolicy, Redirects},
|
||||
};
|
||||
|
||||
const HTTP_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const PKI_FETCH_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
const HTTP_MAX_REDIRECTS: usize = 3;
|
||||
|
||||
pub struct GatewayConfig {
|
||||
pub outbound: IfBlock,
|
||||
pub min_trust: IfBlock,
|
||||
pub outbound_enabled: bool,
|
||||
pub harvest: IfBlock,
|
||||
pub harvest_enabled: bool,
|
||||
pub methods: Box<[KeyKind]>,
|
||||
pub header_protection: HeaderProtection,
|
||||
pub encrypt_signed: bool,
|
||||
pub hkp_servers: Box<[Box<str>]>,
|
||||
pub source_timeout: Duration,
|
||||
pub key_refresh_interval: Duration,
|
||||
pub negative_ttl: Duration,
|
||||
pub use_bundled_roots: bool,
|
||||
pub max_crl_size: usize,
|
||||
pub http: OutboundClient,
|
||||
pub pki_http: OutboundClient,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum GatewayMode {
|
||||
Disable,
|
||||
Opportunistic,
|
||||
Required,
|
||||
}
|
||||
|
||||
pub trait GatewayHeaderProtection {
|
||||
fn to_gateway(self) -> HeaderProtection;
|
||||
}
|
||||
|
||||
pub trait KeyTrustRank {
|
||||
fn rank(self) -> u8;
|
||||
}
|
||||
|
||||
trait ConstantBlock {
|
||||
fn is_constant(&self, constant: ExpressionConstant) -> bool;
|
||||
|
||||
fn is_false(&self) -> bool;
|
||||
}
|
||||
|
||||
impl GatewayConfig {
|
||||
pub fn parse(bp: &mut Bootstrap, encryption: &Encryption) -> Option<Arc<Self>> {
|
||||
if !encryption.gateway_enable {
|
||||
return None;
|
||||
}
|
||||
let id = ObjectType::Encryption.singleton();
|
||||
let mut outbound = bp.compile_expr(id, &encryption.ctx_gateway_outbound());
|
||||
if outbound.is_empty() {
|
||||
bp.invalid_property(
|
||||
id,
|
||||
Property::GatewayOutbound,
|
||||
"Empty outbound policy: recipients are rejected until it is fixed",
|
||||
);
|
||||
outbound = IfBlock::empty(id, Property::GatewayOutbound);
|
||||
}
|
||||
let outbound_enabled = !outbound.is_constant(ExpressionConstant::Disable);
|
||||
let harvest = bp.compile_expr(id, &encryption.ctx_harvest_keys());
|
||||
let harvest_enabled = !harvest.is_false();
|
||||
let proxy = encryption.discovery_proxy.as_deref().map(Proxy::all);
|
||||
let proxy_is_valid = proxy.as_ref().is_none_or(Result::is_ok);
|
||||
if let Some(Err(err)) = &proxy {
|
||||
bp.invalid_property(id, Property::DiscoveryProxy, err.to_string());
|
||||
}
|
||||
let proxy = proxy.and_then(Result::ok);
|
||||
if let Some(server) = encryption
|
||||
.hkp_servers
|
||||
.iter()
|
||||
.find(|url| !url.trim().starts_with("https://") && !url.trim().starts_with("hkps://"))
|
||||
{
|
||||
bp.invalid_property(
|
||||
id,
|
||||
Property::HkpServers,
|
||||
format!("Keyserver {server} must use https or hkps."),
|
||||
);
|
||||
}
|
||||
|
||||
Some(Arc::new(GatewayConfig {
|
||||
min_trust: bp.compile_expr(id, &encryption.ctx_gateway_min_trust()),
|
||||
outbound,
|
||||
outbound_enabled,
|
||||
harvest,
|
||||
harvest_enabled,
|
||||
methods: encryption
|
||||
.gateway_methods
|
||||
.iter()
|
||||
.map(|kind| match kind {
|
||||
PublicKeyKind::OpenPgp => KeyKind::OpenPgp,
|
||||
PublicKeyKind::Smime => KeyKind::Smime,
|
||||
})
|
||||
.collect(),
|
||||
header_protection: encryption.gateway_header_protection.to_gateway(),
|
||||
encrypt_signed: encryption.gateway_encrypt_signed,
|
||||
hkp_servers: encryption
|
||||
.hkp_servers
|
||||
.iter()
|
||||
.map(|url| Box::from(url.trim()))
|
||||
.collect(),
|
||||
source_timeout: encryption.source_timeout.into_inner(),
|
||||
key_refresh_interval: encryption.key_refresh_interval.into_inner(),
|
||||
negative_ttl: encryption.negative_cache_ttl.into_inner(),
|
||||
use_bundled_roots: encryption.use_bundled_roots,
|
||||
max_crl_size: encryption.max_crl_size as usize,
|
||||
http: Self::http_client(
|
||||
encryption.source_timeout.into_inner(),
|
||||
OutboundPolicy::PublicOnly,
|
||||
proxy.as_ref(),
|
||||
proxy_is_valid,
|
||||
),
|
||||
pki_http: Self::http_client(
|
||||
PKI_FETCH_TIMEOUT,
|
||||
OutboundPolicy::PublicSignedData,
|
||||
proxy.as_ref(),
|
||||
proxy_is_valid,
|
||||
),
|
||||
}))
|
||||
}
|
||||
|
||||
fn http_client(
|
||||
timeout: Duration,
|
||||
policy: OutboundPolicy,
|
||||
proxy: Option<&Proxy>,
|
||||
proxy_is_valid: bool,
|
||||
) -> OutboundClient {
|
||||
if !proxy_is_valid {
|
||||
return OutboundClient::default();
|
||||
}
|
||||
let builder = http_client_builder(cfg!(stalwart_tests))
|
||||
.connect_timeout(HTTP_CONNECT_TIMEOUT)
|
||||
.timeout(timeout);
|
||||
let redirects = Redirects::Limited(HTTP_MAX_REDIRECTS);
|
||||
match proxy {
|
||||
Some(proxy) => OutboundClient::with_proxy(builder, policy, redirects, proxy.clone()),
|
||||
None => OutboundClient::new(builder, policy, redirects),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ConstantBlock for IfBlock {
|
||||
fn is_constant(&self, constant: ExpressionConstant) -> bool {
|
||||
self.if_then.is_empty()
|
||||
&& matches!(
|
||||
&*self.default.items,
|
||||
[ExpressionItem::Constant(Constant::Static(value))] if *value == constant
|
||||
)
|
||||
}
|
||||
|
||||
fn is_false(&self) -> bool {
|
||||
self.if_then.is_empty()
|
||||
&& (self.default.items.is_empty()
|
||||
|| matches!(
|
||||
&*self.default.items,
|
||||
[ExpressionItem::Constant(Constant::Integer(0))]
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl GatewayHeaderProtection for RegistryHeaderProtection {
|
||||
fn to_gateway(self) -> HeaderProtection {
|
||||
match self {
|
||||
RegistryHeaderProtection::None => HeaderProtection::None,
|
||||
RegistryHeaderProtection::NoConfidentiality => HeaderProtection::Full,
|
||||
RegistryHeaderProtection::Baseline => HeaderProtection::Baseline,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyTrustRank for KeyTrust {
|
||||
fn rank(self) -> u8 {
|
||||
match self {
|
||||
KeyTrust::Manual => 4,
|
||||
KeyTrust::Verified => 3,
|
||||
KeyTrust::Discovered => 2,
|
||||
KeyTrust::Harvested => 1,
|
||||
KeyTrust::Unverified => 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'x> TryFrom<Variable<'x>> for GatewayMode {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: Variable<'x>) -> Result<Self, ()> {
|
||||
match value {
|
||||
Variable::Constant(ExpressionConstant::Disable) => Ok(GatewayMode::Disable),
|
||||
Variable::Constant(ExpressionConstant::Opportunistic) => Ok(GatewayMode::Opportunistic),
|
||||
Variable::Constant(ExpressionConstant::Required) => Ok(GatewayMode::Required),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'x> TryFrom<Variable<'x>> for GatewayMinTrust {
|
||||
type Error = ();
|
||||
|
||||
fn try_from(value: Variable<'x>) -> Result<Self, ()> {
|
||||
match value {
|
||||
Variable::Constant(ExpressionConstant::Manual) => Ok(GatewayMinTrust(KeyTrust::Manual)),
|
||||
Variable::Constant(ExpressionConstant::Verified) => {
|
||||
Ok(GatewayMinTrust(KeyTrust::Verified))
|
||||
}
|
||||
Variable::Constant(ExpressionConstant::Discovered) => {
|
||||
Ok(GatewayMinTrust(KeyTrust::Discovered))
|
||||
}
|
||||
Variable::Constant(ExpressionConstant::Harvested) => {
|
||||
Ok(GatewayMinTrust(KeyTrust::Harvested))
|
||||
}
|
||||
Variable::Constant(ExpressionConstant::Unverified) => {
|
||||
Ok(GatewayMinTrust(KeyTrust::Unverified))
|
||||
}
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct GatewayMinTrust(pub KeyTrust);
|
||||
279
crates/common/src/gateway/discovery/dns.rs
Normal file
279
crates/common/src/gateway/discovery/dns.rs
Normal file
|
|
@ -0,0 +1,279 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::SourceResult;
|
||||
use crate::{
|
||||
Server,
|
||||
gateway::{
|
||||
discovery::DiscoveryMethod,
|
||||
store::KeyCandidate,
|
||||
trust::{RunTrustAnchors, SmimeTrust},
|
||||
},
|
||||
};
|
||||
use crypto::ChainStatus;
|
||||
use mail_auth::hickory_resolver::{
|
||||
net::{DnsError, NetError},
|
||||
proto::{
|
||||
dnssec::Proof,
|
||||
rr::{
|
||||
Name, RData, RecordType,
|
||||
rdata::tlsa::{CertUsage, Matching, Selector},
|
||||
},
|
||||
},
|
||||
};
|
||||
use registry::schema::enums::KeyDiscoverySource;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{fmt::Write, time::Instant};
|
||||
use store::write::now;
|
||||
|
||||
const OWNER_HASH_LEN: usize = 28;
|
||||
|
||||
pub trait DnssecKeyLookup: Sync + Send {
|
||||
fn lookup_dnssec_keys(
|
||||
&self,
|
||||
address: &str,
|
||||
anchors: &RunTrustAnchors,
|
||||
) -> impl Future<Output = SourceResult> + Send;
|
||||
}
|
||||
|
||||
enum KeyRecords {
|
||||
Found(Vec<KeyRecord>, u64),
|
||||
Missing,
|
||||
Failed,
|
||||
Bogus,
|
||||
}
|
||||
|
||||
struct KeyRecord {
|
||||
data: Vec<u8>,
|
||||
needs_chain: bool,
|
||||
}
|
||||
|
||||
impl DnssecKeyLookup for Server {
|
||||
async fn lookup_dnssec_keys(&self, address: &str, anchors: &RunTrustAnchors) -> SourceResult {
|
||||
let resolvers = &self.core.smtp.resolvers;
|
||||
if !resolvers.dnssec_available {
|
||||
return SourceResult::TemporaryFailure;
|
||||
}
|
||||
let Some((local_part, domain)) = address.rsplit_once('@') else {
|
||||
return SourceResult::NotFound;
|
||||
};
|
||||
let Some(label) = Sha256::digest(local_part.as_bytes())
|
||||
.get(..OWNER_HASH_LEN)
|
||||
.map(|hash| {
|
||||
hash.iter()
|
||||
.fold(String::with_capacity(56), |mut label, byte| {
|
||||
let _ = write!(label, "{byte:02x}");
|
||||
label
|
||||
})
|
||||
})
|
||||
else {
|
||||
return SourceResult::NotFound;
|
||||
};
|
||||
|
||||
let (pgp, smime) = tokio::join!(
|
||||
self.key_records(
|
||||
format!("{label}._openpgpkey.{domain}."),
|
||||
RecordType::OPENPGPKEY
|
||||
),
|
||||
self.key_records(format!("{label}._smimecert.{domain}."), RecordType::SMIMEA),
|
||||
);
|
||||
|
||||
let mut candidates = Vec::new();
|
||||
let mut revoked = Vec::new();
|
||||
let mut failed = false;
|
||||
for (records, is_pgp) in [(pgp, true), (smime, false)] {
|
||||
match records {
|
||||
KeyRecords::Found(records, ttl) => {
|
||||
let time = now();
|
||||
let valid_until = time + ttl;
|
||||
for record in records {
|
||||
if is_pgp {
|
||||
if let SourceResult::Keys {
|
||||
candidates: keys,
|
||||
revoked: fingerprints,
|
||||
} = SourceResult::from_openpgp(
|
||||
&record.data,
|
||||
address,
|
||||
KeyDiscoverySource::Dnssec,
|
||||
Some(valid_until),
|
||||
) {
|
||||
candidates.extend(keys);
|
||||
revoked.extend(fingerprints);
|
||||
}
|
||||
} else if let Ok(parsed) = crypto::parse_public_keys(&record.data, time)
|
||||
&& parsed
|
||||
.addresses
|
||||
.iter()
|
||||
.any(|bound| bound.eq_ignore_ascii_case(address))
|
||||
{
|
||||
if record.needs_chain {
|
||||
match self.pkix_chain_valid(&record.data, anchors, time).await {
|
||||
Some(true) => {}
|
||||
Some(false) => continue,
|
||||
None => {
|
||||
failed = true;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
candidates.push(KeyCandidate {
|
||||
address: address.into(),
|
||||
key: record.data,
|
||||
parsed,
|
||||
source: KeyDiscoverySource::Dnssec.key_source(),
|
||||
trust: KeyDiscoverySource::Dnssec.trust(),
|
||||
valid_until: Some(valid_until),
|
||||
capabilities: None,
|
||||
signed_at: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
KeyRecords::Bogus => return SourceResult::Bogus,
|
||||
KeyRecords::Failed => failed = true,
|
||||
KeyRecords::Missing => {}
|
||||
}
|
||||
}
|
||||
|
||||
if !candidates.is_empty() || !revoked.is_empty() {
|
||||
SourceResult::Keys {
|
||||
candidates,
|
||||
revoked,
|
||||
}
|
||||
} else if failed {
|
||||
SourceResult::TemporaryFailure
|
||||
} else {
|
||||
SourceResult::NotFound
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
trait KeyRecordLookup {
|
||||
fn pkix_chain_valid(
|
||||
&self,
|
||||
certificate: &[u8],
|
||||
anchors: &RunTrustAnchors,
|
||||
now: u64,
|
||||
) -> impl Future<Output = Option<bool>> + Send;
|
||||
|
||||
fn key_records(
|
||||
&self,
|
||||
name: String,
|
||||
record_type: RecordType,
|
||||
) -> impl Future<Output = KeyRecords> + Send;
|
||||
}
|
||||
|
||||
impl KeyRecordLookup for Server {
|
||||
async fn pkix_chain_valid(
|
||||
&self,
|
||||
certificate: &[u8],
|
||||
anchors: &RunTrustAnchors,
|
||||
now: u64,
|
||||
) -> Option<bool> {
|
||||
let anchors = self.run_trust_anchors(anchors).await.ok()?;
|
||||
let verdict = self
|
||||
.verify_certificate_chain(&[certificate.to_vec()], anchors, &[], now)
|
||||
.await?;
|
||||
match verdict.status {
|
||||
ChainStatus::Valid | ChainStatus::RevocationUnknown => Some(true),
|
||||
ChainStatus::Untrusted if !verdict.issuer_urls.is_empty() => None,
|
||||
_ => Some(false),
|
||||
}
|
||||
}
|
||||
|
||||
async fn key_records(&self, name: String, record_type: RecordType) -> KeyRecords {
|
||||
#[cfg(stalwart_tests)]
|
||||
if let Some(records) = test_records(&name) {
|
||||
return records;
|
||||
}
|
||||
|
||||
let Ok(name) = Name::from_str_relaxed(name.as_str()) else {
|
||||
return KeyRecords::Missing;
|
||||
};
|
||||
let lookup = match self
|
||||
.core
|
||||
.smtp
|
||||
.resolvers
|
||||
.dnssec
|
||||
.resolver
|
||||
.lookup(name, record_type)
|
||||
.await
|
||||
{
|
||||
Ok(lookup) => lookup,
|
||||
Err(err) => return KeyRecords::from_error(&err),
|
||||
};
|
||||
|
||||
let ttl = lookup
|
||||
.valid_until()
|
||||
.saturating_duration_since(Instant::now())
|
||||
.as_secs();
|
||||
let mut records = Vec::new();
|
||||
for record in lookup.answers() {
|
||||
let found = match &record.data {
|
||||
RData::OPENPGPKEY(key) => KeyRecord {
|
||||
data: key.public_key.to_vec(),
|
||||
needs_chain: false,
|
||||
},
|
||||
RData::SMIMEA(smimea)
|
||||
if matches!(smimea.cert_usage, CertUsage::PkixEe | CertUsage::DaneEe)
|
||||
&& smimea.selector == Selector::Full
|
||||
&& smimea.matching == Matching::Raw =>
|
||||
{
|
||||
KeyRecord {
|
||||
data: smimea.cert_data.clone(),
|
||||
needs_chain: smimea.cert_usage == CertUsage::PkixEe,
|
||||
}
|
||||
}
|
||||
_ => continue,
|
||||
};
|
||||
match record.proof {
|
||||
Proof::Secure => records.push(found),
|
||||
Proof::Insecure => return KeyRecords::Missing,
|
||||
Proof::Bogus | Proof::Indeterminate => return KeyRecords::Bogus,
|
||||
}
|
||||
}
|
||||
|
||||
if records.is_empty() {
|
||||
KeyRecords::Missing
|
||||
} else {
|
||||
KeyRecords::Found(records, ttl)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyRecords {
|
||||
fn from_error(err: &NetError) -> Self {
|
||||
match err {
|
||||
NetError::Dns(DnsError::NoRecordsFound(no_records)) => {
|
||||
if no_records.authorities.as_deref().is_some_and(|records| {
|
||||
records.iter().any(|record| {
|
||||
matches!(record.proof, Proof::Bogus | Proof::Indeterminate)
|
||||
&& matches!(record.record_type(), RecordType::NSEC | RecordType::NSEC3)
|
||||
})
|
||||
}) {
|
||||
KeyRecords::Bogus
|
||||
} else {
|
||||
KeyRecords::Missing
|
||||
}
|
||||
}
|
||||
NetError::Dns(DnsError::DnssecBogus) => KeyRecords::Bogus,
|
||||
NetError::Dns(DnsError::Nsec {
|
||||
proof: Proof::Bogus | Proof::Indeterminate,
|
||||
..
|
||||
}) => KeyRecords::Bogus,
|
||||
NetError::Dns(DnsError::Nsec { .. }) => KeyRecords::Missing,
|
||||
_ => KeyRecords::Failed,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(stalwart_tests)]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../../stalwart-tests/unit/common/src/gateway/discovery/dns/test_support.rs"]
|
||||
pub mod test_support;
|
||||
|
||||
#[cfg(stalwart_tests)]
|
||||
use test_support::test_records;
|
||||
147
crates/common/src/gateway/discovery/keyserver.rs
Normal file
147
crates/common/src/gateway/discovery/keyserver.rs
Normal file
|
|
@ -0,0 +1,147 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{MAX_KEY_RESPONSE, SourceResult};
|
||||
use crate::{KV_KEY_LOOKUP, Server};
|
||||
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
|
||||
use registry::schema::{enums::KeyDiscoverySource, structs::Rate};
|
||||
use reqwest::{Method, Response, StatusCode, header::RETRY_AFTER};
|
||||
use std::time::Duration;
|
||||
use store::dispatch::lookup::KeyValue;
|
||||
use utils::HttpLimitResponse;
|
||||
|
||||
const VKS_BASE_URL: &str = "https://keys.openpgp.org/vks/v1/by-email/";
|
||||
const VKS_BLOCK_KEY: &[u8] = &[KV_KEY_LOOKUP, 2];
|
||||
const VKS_BURST: u64 = 50;
|
||||
const VKS_WINDOW_SECS: u64 = 60;
|
||||
const VKS_DEFAULT_BACKOFF_SECS: u64 = 300;
|
||||
|
||||
pub trait KeyserverLookup: Sync + Send {
|
||||
fn lookup_vks(&self, address: &str) -> impl Future<Output = SourceResult> + Send;
|
||||
|
||||
fn lookup_hkp(&self, address: &str) -> impl Future<Output = SourceResult> + Send;
|
||||
}
|
||||
|
||||
trait VksRateLimit {
|
||||
fn vks_allowed(&self) -> impl Future<Output = bool> + Send;
|
||||
|
||||
fn vks_backoff(&self, response: &Response) -> impl Future<Output = ()> + Send;
|
||||
}
|
||||
|
||||
impl KeyserverLookup for Server {
|
||||
async fn lookup_vks(&self, address: &str) -> SourceResult {
|
||||
let Some(gateway) = self.core.email.gateway.as_deref() else {
|
||||
return SourceResult::NotFound;
|
||||
};
|
||||
if !self.vks_allowed().await {
|
||||
return SourceResult::TemporaryFailure;
|
||||
}
|
||||
let url = format!(
|
||||
"{VKS_BASE_URL}{}",
|
||||
utf8_percent_encode(address, NON_ALPHANUMERIC)
|
||||
);
|
||||
let Ok(request) = gateway.http.request(Method::GET, &url) else {
|
||||
return SourceResult::TemporaryFailure;
|
||||
};
|
||||
match request.send().await {
|
||||
Ok(response) if response.status() == StatusCode::TOO_MANY_REQUESTS => {
|
||||
self.vks_backoff(&response).await;
|
||||
SourceResult::TemporaryFailure
|
||||
}
|
||||
Ok(response) if response.status() == StatusCode::OK => {
|
||||
match response.bytes_with_limit(MAX_KEY_RESPONSE).await {
|
||||
Ok(Some(body)) => {
|
||||
SourceResult::from_openpgp(&body, address, KeyDiscoverySource::Vks, None)
|
||||
}
|
||||
Ok(None) => SourceResult::TemporaryFailure,
|
||||
Err(_) => SourceResult::TemporaryFailure,
|
||||
}
|
||||
}
|
||||
Ok(response) if response.status().is_server_error() => SourceResult::TemporaryFailure,
|
||||
Ok(_) => SourceResult::NotFound,
|
||||
Err(_) => SourceResult::TemporaryFailure,
|
||||
}
|
||||
}
|
||||
|
||||
async fn lookup_hkp(&self, address: &str) -> SourceResult {
|
||||
let Some(gateway) = self.core.email.gateway.as_deref() else {
|
||||
return SourceResult::NotFound;
|
||||
};
|
||||
let mut result = SourceResult::NotFound;
|
||||
let search = utf8_percent_encode(address, NON_ALPHANUMERIC).to_string();
|
||||
for server in &gateway.hkp_servers {
|
||||
let server = server.trim_end_matches('/');
|
||||
let url = match server.strip_prefix("hkps://") {
|
||||
Some(host) => {
|
||||
format!("https://{host}/pks/lookup?op=get&options=mr&search={search}")
|
||||
}
|
||||
None => format!("{server}/pks/lookup?op=get&options=mr&search={search}"),
|
||||
};
|
||||
let Ok(request) = gateway.http.request(Method::GET, &url) else {
|
||||
result = SourceResult::TemporaryFailure;
|
||||
continue;
|
||||
};
|
||||
match request.send().await {
|
||||
Ok(response) if response.status() == StatusCode::OK => {
|
||||
match response.bytes_with_limit(MAX_KEY_RESPONSE).await {
|
||||
Ok(Some(body)) => {
|
||||
let keys = SourceResult::from_openpgp(
|
||||
&body,
|
||||
address,
|
||||
KeyDiscoverySource::Hkp,
|
||||
None,
|
||||
);
|
||||
if matches!(keys, SourceResult::Keys { .. }) {
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
_ => result = SourceResult::TemporaryFailure,
|
||||
}
|
||||
}
|
||||
Ok(response) if !response.status().is_server_error() => {}
|
||||
_ => result = SourceResult::TemporaryFailure,
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl VksRateLimit for Server {
|
||||
async fn vks_allowed(&self) -> bool {
|
||||
let store = self.in_memory_store();
|
||||
if store.key_exists(VKS_BLOCK_KEY).await.unwrap_or(false) {
|
||||
return false;
|
||||
}
|
||||
store
|
||||
.is_rate_allowed(
|
||||
KV_KEY_LOOKUP,
|
||||
b"vks",
|
||||
&Rate {
|
||||
count: VKS_BURST,
|
||||
period: Duration::from_secs(VKS_BURST * VKS_WINDOW_SECS).into(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map(|retry| retry.is_none())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
async fn vks_backoff(&self, response: &Response) {
|
||||
let backoff = response
|
||||
.headers()
|
||||
.get(RETRY_AFTER)
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
.unwrap_or(VKS_DEFAULT_BACKOFF_SECS);
|
||||
if let Err(err) = self
|
||||
.in_memory_store()
|
||||
.key_set(KeyValue::new(VKS_BLOCK_KEY, Vec::new()).expires(backoff))
|
||||
.await
|
||||
{
|
||||
trc::error!(err.caused_by(trc::location!()));
|
||||
}
|
||||
}
|
||||
}
|
||||
299
crates/common/src/gateway/discovery/mod.rs
Normal file
299
crates/common/src/gateway/discovery/mod.rs
Normal file
|
|
@ -0,0 +1,299 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub mod dns;
|
||||
pub mod keyserver;
|
||||
pub mod wkd;
|
||||
|
||||
use super::{
|
||||
store::{
|
||||
ExternalPublicKeyData, ExternalPublicKeyRow, ExternalPublicKeyStore, KeyCandidate,
|
||||
KeyChange, MAX_STORED_KEY_SIZE, RegistryKeyKind,
|
||||
},
|
||||
trust::RunTrustAnchors,
|
||||
};
|
||||
use crate::Server;
|
||||
use crypto::KeyKind;
|
||||
use dns::DnssecKeyLookup;
|
||||
use futures::{StreamExt, stream::FuturesUnordered};
|
||||
use keyserver::KeyserverLookup;
|
||||
use registry::{
|
||||
schema::{
|
||||
enums::{KeyDiscoverySource, KeyTrust},
|
||||
structs::{ExternalPublicKey, KeySource, KeySourceAutomatic},
|
||||
},
|
||||
types::{EnumImpl, datetime::UTCDateTime},
|
||||
};
|
||||
use std::time::Instant;
|
||||
use store::write::now;
|
||||
use trc::EncryptionEvent;
|
||||
use wkd::WkdLookup;
|
||||
|
||||
pub const MAX_KEY_RESPONSE: usize = 256 * 1024;
|
||||
const MAX_CONCURRENT_FETCHES: usize = 16;
|
||||
const KIND_PREFERENCE: [KeyKind; 2] = [KeyKind::Smime, KeyKind::OpenPgp];
|
||||
|
||||
pub enum SourceResult {
|
||||
Keys {
|
||||
candidates: Vec<KeyCandidate>,
|
||||
revoked: Vec<String>,
|
||||
},
|
||||
NotFound,
|
||||
TemporaryFailure,
|
||||
Bogus,
|
||||
}
|
||||
|
||||
pub trait KeyDiscovery: Sync + Send {
|
||||
fn fetch_external_public_keys(
|
||||
&self,
|
||||
rows: &[ExternalPublicKeyRow],
|
||||
anchors: &RunTrustAnchors,
|
||||
) -> impl Future<Output = ()> + Send;
|
||||
|
||||
fn fetch_external_public_key(
|
||||
&self,
|
||||
row: &ExternalPublicKeyRow,
|
||||
anchors: &RunTrustAnchors,
|
||||
) -> impl Future<Output = trc::Result<()>> + Send;
|
||||
|
||||
fn lookup_key(
|
||||
&self,
|
||||
address: &str,
|
||||
method: KeyDiscoverySource,
|
||||
anchors: &RunTrustAnchors,
|
||||
) -> impl Future<Output = SourceResult> + Send;
|
||||
}
|
||||
|
||||
pub trait DiscoveryMethod {
|
||||
fn trust(self) -> KeyTrust;
|
||||
|
||||
fn key_source(self) -> KeySource;
|
||||
}
|
||||
|
||||
trait CandidateSelection {
|
||||
fn preferred_candidate(
|
||||
&self,
|
||||
candidates: Vec<KeyCandidate>,
|
||||
methods: &[KeyKind],
|
||||
) -> Option<KeyCandidate>;
|
||||
}
|
||||
|
||||
impl KeyDiscovery for Server {
|
||||
async fn fetch_external_public_keys(
|
||||
&self,
|
||||
rows: &[ExternalPublicKeyRow],
|
||||
anchors: &RunTrustAnchors,
|
||||
) {
|
||||
let mut rows = rows.iter();
|
||||
let mut running = FuturesUnordered::new();
|
||||
loop {
|
||||
while running.len() < MAX_CONCURRENT_FETCHES
|
||||
&& let Some(row) = rows.next()
|
||||
{
|
||||
running.push(self.fetch_external_public_key(row, anchors));
|
||||
}
|
||||
match running.next().await {
|
||||
Some(Ok(())) => {}
|
||||
Some(Err(err)) => {
|
||||
trc::error!(err.caused_by(trc::location!()));
|
||||
}
|
||||
None => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn fetch_external_public_key(
|
||||
&self,
|
||||
row: &ExternalPublicKeyRow,
|
||||
anchors: &RunTrustAnchors,
|
||||
) -> trc::Result<()> {
|
||||
let Some(gateway) = self.core.email.gateway.as_deref() else {
|
||||
return Ok(());
|
||||
};
|
||||
let KeySource::Automatic(KeySourceAutomatic { method }) = row.key.source else {
|
||||
return Ok(());
|
||||
};
|
||||
let address = row.key.email_address.as_str();
|
||||
let started = Instant::now();
|
||||
let result = tokio::time::timeout(
|
||||
gateway.source_timeout,
|
||||
self.lookup_key(address, method, anchors),
|
||||
)
|
||||
.await
|
||||
.unwrap_or(SourceResult::TemporaryFailure);
|
||||
trc::event!(
|
||||
Encryption(EncryptionEvent::KeyLookup),
|
||||
Source = method.as_str(),
|
||||
Result = result.as_str(),
|
||||
Elapsed = started.elapsed(),
|
||||
);
|
||||
|
||||
let time = now();
|
||||
let mut updated = row.key.clone();
|
||||
match result {
|
||||
SourceResult::Keys {
|
||||
candidates,
|
||||
revoked,
|
||||
} => {
|
||||
updated.revoke(&revoked);
|
||||
updated.last_checked = Some(UTCDateTime::from_timestamp(time as i64));
|
||||
if let Some(candidate) = updated.preferred_candidate(candidates, &gateway.methods) {
|
||||
let fingerprint = candidate.fingerprint().unwrap_or_default();
|
||||
if updated.fingerprint.as_deref() == Some(fingerprint.as_str()) {
|
||||
if let Some(refreshed) = candidate.refreshed(&updated, time) {
|
||||
updated = refreshed;
|
||||
}
|
||||
} else if updated.accept_candidate(&candidate, fingerprint, time)
|
||||
== KeyChange::PendingApproval
|
||||
{
|
||||
trc::event!(
|
||||
Encryption(EncryptionEvent::KeyChange),
|
||||
To = address.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
updated.schedule_next_check(gateway, time);
|
||||
}
|
||||
SourceResult::NotFound => {
|
||||
updated.last_checked = Some(UTCDateTime::from_timestamp(time as i64));
|
||||
if method == KeyDiscoverySource::Dnssec && !updated.pinned {
|
||||
updated.clear_next_key();
|
||||
updated.clear_key();
|
||||
}
|
||||
updated.schedule_next_check(gateway, time);
|
||||
}
|
||||
SourceResult::Bogus => {
|
||||
trc::event!(
|
||||
Encryption(EncryptionEvent::DnssecBogus),
|
||||
To = address.to_string(),
|
||||
);
|
||||
updated.schedule_retry(gateway, time);
|
||||
}
|
||||
SourceResult::TemporaryFailure => updated.schedule_retry(gateway, time),
|
||||
}
|
||||
self.update_external_public_key(row, updated).await
|
||||
}
|
||||
|
||||
async fn lookup_key(
|
||||
&self,
|
||||
address: &str,
|
||||
method: KeyDiscoverySource,
|
||||
anchors: &RunTrustAnchors,
|
||||
) -> SourceResult {
|
||||
match method {
|
||||
KeyDiscoverySource::Dnssec => self.lookup_dnssec_keys(address, anchors).await,
|
||||
KeyDiscoverySource::Wkd => self.lookup_wkd(address).await,
|
||||
KeyDiscoverySource::Vks => self.lookup_vks(address).await,
|
||||
KeyDiscoverySource::Hkp => self.lookup_hkp(address).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DiscoveryMethod for KeyDiscoverySource {
|
||||
fn trust(self) -> KeyTrust {
|
||||
match self {
|
||||
KeyDiscoverySource::Dnssec => KeyTrust::Verified,
|
||||
KeyDiscoverySource::Wkd | KeyDiscoverySource::Vks => KeyTrust::Discovered,
|
||||
KeyDiscoverySource::Hkp => KeyTrust::Unverified,
|
||||
}
|
||||
}
|
||||
|
||||
fn key_source(self) -> KeySource {
|
||||
KeySource::Automatic(KeySourceAutomatic { method: self })
|
||||
}
|
||||
}
|
||||
|
||||
impl CandidateSelection for ExternalPublicKey {
|
||||
fn preferred_candidate(
|
||||
&self,
|
||||
mut candidates: Vec<KeyCandidate>,
|
||||
methods: &[KeyKind],
|
||||
) -> Option<KeyCandidate> {
|
||||
candidates.retain(|candidate| {
|
||||
candidate.key.len() <= MAX_STORED_KEY_SIZE
|
||||
&& candidate.fingerprint().is_some_and(|fingerprint| {
|
||||
!self
|
||||
.blocked_fingerprints
|
||||
.iter()
|
||||
.any(|blocked| *blocked == fingerprint)
|
||||
})
|
||||
&& self
|
||||
.kind
|
||||
.is_none_or(|kind| kind == candidate.parsed.kind.registry_kind())
|
||||
});
|
||||
let known = [
|
||||
self.fingerprint.as_deref(),
|
||||
self.next_fingerprint.as_deref(),
|
||||
];
|
||||
let idx = known
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find_map(|known| {
|
||||
candidates
|
||||
.iter()
|
||||
.position(|candidate| candidate.fingerprint().as_deref() == Some(known))
|
||||
})
|
||||
.or_else(|| {
|
||||
KIND_PREFERENCE
|
||||
.iter()
|
||||
.filter(|kind| methods.contains(kind))
|
||||
.find_map(|kind| {
|
||||
candidates
|
||||
.iter()
|
||||
.position(|candidate| candidate.parsed.kind == *kind)
|
||||
})
|
||||
})?;
|
||||
Some(candidates.swap_remove(idx))
|
||||
}
|
||||
}
|
||||
|
||||
impl SourceResult {
|
||||
pub fn from_openpgp(
|
||||
input: &[u8],
|
||||
address: &str,
|
||||
method: KeyDiscoverySource,
|
||||
valid_until: Option<u64>,
|
||||
) -> Self {
|
||||
let time = now();
|
||||
let revoked: Vec<String> = crypto::revoked_fingerprints(input, time)
|
||||
.iter()
|
||||
.map(|fingerprint| fingerprint.to_hex())
|
||||
.collect();
|
||||
let candidates: Vec<KeyCandidate> = crypto::parse_public_keys_for(input, address, time)
|
||||
.map(|keys| {
|
||||
keys.into_iter()
|
||||
.map(|key| KeyCandidate {
|
||||
address: address.into(),
|
||||
key: key.key,
|
||||
parsed: key.parsed,
|
||||
source: method.key_source(),
|
||||
trust: method.trust(),
|
||||
valid_until,
|
||||
capabilities: None,
|
||||
signed_at: None,
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if candidates.is_empty() && revoked.is_empty() {
|
||||
SourceResult::NotFound
|
||||
} else {
|
||||
SourceResult::Keys {
|
||||
candidates,
|
||||
revoked,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
SourceResult::Keys { .. } => "found",
|
||||
SourceResult::NotFound => "notFound",
|
||||
SourceResult::TemporaryFailure => "temporaryFailure",
|
||||
SourceResult::Bogus => "bogus",
|
||||
}
|
||||
}
|
||||
}
|
||||
133
crates/common/src/gateway/discovery/wkd.rs
Normal file
133
crates/common/src/gateway/discovery/wkd.rs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{MAX_KEY_RESPONSE, SourceResult};
|
||||
use crate::Server;
|
||||
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
|
||||
use registry::schema::enums::KeyDiscoverySource;
|
||||
use reqwest::{Method, StatusCode};
|
||||
use sha1::{Digest, Sha1};
|
||||
use utils::HttpLimitResponse;
|
||||
|
||||
const ZBASE32: &[u8; 32] = b"ybndrfg8ejkmcpqxot1uwisza345h769";
|
||||
|
||||
pub trait WkdLookup: Sync + Send {
|
||||
fn lookup_wkd(&self, address: &str) -> impl Future<Output = SourceResult> + Send;
|
||||
|
||||
fn wkd_is_advanced(&self, domain: &str) -> impl Future<Output = Option<bool>> + Send;
|
||||
}
|
||||
|
||||
struct WkdUrl {
|
||||
host: String,
|
||||
prefix: String,
|
||||
}
|
||||
|
||||
impl WkdLookup for Server {
|
||||
async fn lookup_wkd(&self, address: &str) -> SourceResult {
|
||||
let Some(gateway) = self.core.email.gateway.as_deref() else {
|
||||
return SourceResult::NotFound;
|
||||
};
|
||||
let Some((local_part, domain)) = address.rsplit_once('@') else {
|
||||
return SourceResult::NotFound;
|
||||
};
|
||||
let Some(advanced) = self.wkd_is_advanced(domain).await else {
|
||||
return SourceResult::TemporaryFailure;
|
||||
};
|
||||
let url = WkdUrl::new(domain, advanced).key_url(local_part);
|
||||
let Ok(request) = gateway.http.request(Method::GET, &url) else {
|
||||
return SourceResult::TemporaryFailure;
|
||||
};
|
||||
match request.send().await {
|
||||
Ok(response) if response.status() == StatusCode::OK => {
|
||||
match response.bytes_with_limit(MAX_KEY_RESPONSE).await {
|
||||
Ok(Some(body)) => {
|
||||
SourceResult::from_openpgp(&body, address, KeyDiscoverySource::Wkd, None)
|
||||
}
|
||||
Ok(None) => SourceResult::TemporaryFailure,
|
||||
Err(_) => SourceResult::TemporaryFailure,
|
||||
}
|
||||
}
|
||||
Ok(response) if response.status().is_server_error() => SourceResult::TemporaryFailure,
|
||||
Ok(_) => SourceResult::NotFound,
|
||||
Err(_) => SourceResult::TemporaryFailure,
|
||||
}
|
||||
}
|
||||
|
||||
async fn wkd_is_advanced(&self, domain: &str) -> Option<bool> {
|
||||
let advanced_host = format!("openpgpkey.{domain}");
|
||||
#[cfg(not(stalwart_tests))]
|
||||
let advanced = match self
|
||||
.core
|
||||
.smtp
|
||||
.resolvers
|
||||
.dns
|
||||
.resolver()
|
||||
.lookup_ip(advanced_host.as_str())
|
||||
.await
|
||||
{
|
||||
Ok(_) => true,
|
||||
Err(err) if err.is_no_records_found() => false,
|
||||
Err(_) => return None,
|
||||
};
|
||||
#[cfg(stalwart_tests)]
|
||||
let advanced = !advanced_host.is_empty() && WkdUrl::test_advanced(domain);
|
||||
|
||||
Some(advanced)
|
||||
}
|
||||
}
|
||||
|
||||
impl WkdUrl {
|
||||
fn new(domain: &str, advanced: bool) -> Self {
|
||||
let domain = domain.to_ascii_lowercase();
|
||||
if advanced {
|
||||
WkdUrl {
|
||||
host: format!("openpgpkey.{domain}"),
|
||||
prefix: format!("/.well-known/openpgpkey/{domain}"),
|
||||
}
|
||||
} else {
|
||||
WkdUrl {
|
||||
host: domain,
|
||||
prefix: "/.well-known/openpgpkey".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn key_url(&self, local_part: &str) -> String {
|
||||
format!(
|
||||
"https://{}{}/hu/{}?l={}",
|
||||
self.host,
|
||||
self.prefix,
|
||||
local_part_hash(local_part),
|
||||
utf8_percent_encode(local_part, NON_ALPHANUMERIC)
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(stalwart_tests)]
|
||||
fn test_advanced(domain: &str) -> bool {
|
||||
domain.starts_with("advanced.")
|
||||
}
|
||||
}
|
||||
|
||||
fn local_part_hash(local_part: &str) -> String {
|
||||
let digest = Sha1::digest(local_part.to_ascii_lowercase().as_bytes());
|
||||
let mut encoded = String::with_capacity(32);
|
||||
let mut buffer = 0u32;
|
||||
let mut bits = 0;
|
||||
for &byte in digest.iter() {
|
||||
buffer = (buffer << 8) | u32::from(byte);
|
||||
bits += 8;
|
||||
while bits >= 5 {
|
||||
bits -= 5;
|
||||
encoded.push(ZBASE32[((buffer >> bits) & 31) as usize] as char);
|
||||
}
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../../stalwart-tests/unit/common/src/gateway/discovery/wkd/tests.rs"]
|
||||
mod tests;
|
||||
211
crates/common/src/gateway/harvest.rs
Normal file
211
crates/common/src/gateway/harvest.rs
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{
|
||||
resolver::{KeyCacheKey, KeyResolver},
|
||||
store::{ExternalPublicKeyStore, KeyCandidate, KeyChange, LAST_SEEN_RESOLUTION},
|
||||
trust::SmimeTrust,
|
||||
};
|
||||
use crate::{
|
||||
Server,
|
||||
expr::{Bump, Variable, functions::ResolveVariable},
|
||||
};
|
||||
use crypto::{ChainStatus, HarvestSource, HarvestedKey};
|
||||
use mail_parser::{HeaderName, Message, MessageParser};
|
||||
use registry::schema::{
|
||||
enums::{ExpressionVariable, KeyTrust},
|
||||
structs::KeySource,
|
||||
};
|
||||
use store::write::now;
|
||||
use trc::EncryptionEvent;
|
||||
|
||||
struct HarvestSender<'x>(&'x str);
|
||||
|
||||
pub trait KeyHarvest: Sync + Send {
|
||||
fn harvest_enabled(&self) -> bool;
|
||||
|
||||
fn harvest_candidate(&self, message: &Message<'_>) -> bool;
|
||||
|
||||
fn spawn_harvest(&self, raw_message: Vec<u8>, session_id: u64);
|
||||
|
||||
fn harvest_message(
|
||||
&self,
|
||||
raw_message: &[u8],
|
||||
session_id: u64,
|
||||
) -> impl Future<Output = ()> + Send;
|
||||
|
||||
fn harvested_candidate(
|
||||
&self,
|
||||
harvested: &HarvestedKey,
|
||||
from: &str,
|
||||
now: u64,
|
||||
) -> impl Future<Output = Option<KeyCandidate>> + Send;
|
||||
}
|
||||
|
||||
impl KeyHarvest for Server {
|
||||
fn harvest_enabled(&self) -> bool {
|
||||
self.core
|
||||
.email
|
||||
.gateway
|
||||
.as_deref()
|
||||
.is_some_and(|gateway| gateway.harvest_enabled)
|
||||
}
|
||||
|
||||
fn harvest_candidate(&self, message: &Message<'_>) -> bool {
|
||||
message.headers().contains(HeaderName::Autocrypt)
|
||||
|| message
|
||||
.root_part()
|
||||
.content_type()
|
||||
.and_then(|content_type| content_type.subtype())
|
||||
.is_some_and(|subtype| {
|
||||
hashify::set_ignore_case!(
|
||||
subtype.as_bytes(),
|
||||
"signed",
|
||||
"pkcs7-mime",
|
||||
"x-pkcs7-mime"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn spawn_harvest(&self, raw_message: Vec<u8>, session_id: u64) {
|
||||
let Ok(permit) = self.inner.data.harvest_tasks.clone().try_acquire_owned() else {
|
||||
return;
|
||||
};
|
||||
let server = self.clone();
|
||||
tokio::spawn(async move {
|
||||
server.harvest_message(&raw_message, session_id).await;
|
||||
drop(permit);
|
||||
});
|
||||
}
|
||||
|
||||
async fn harvest_message(&self, raw_message: &[u8], session_id: u64) {
|
||||
let Some(gateway) = self.core.email.gateway.as_deref() else {
|
||||
return;
|
||||
};
|
||||
let Some(message) = MessageParser::default().parse(raw_message) else {
|
||||
return;
|
||||
};
|
||||
let Some(from) = message
|
||||
.from()
|
||||
.and_then(|from| from.first())
|
||||
.and_then(|from| from.address())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let key = KeyCacheKey::new(from);
|
||||
if !self
|
||||
.eval_if::<bool, _>(
|
||||
&gateway.harvest,
|
||||
&HarvestSender(&key.address),
|
||||
&mut Bump::new(),
|
||||
session_id,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_default()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let time = now();
|
||||
for harvested in crypto::harvest(&message, from, time) {
|
||||
let Some(fingerprint) = crypto::parse_public_keys(&harvested.key, time)
|
||||
.ok()
|
||||
.and_then(|parsed| parsed.fingerprints.first().map(|f| f.to_hex()))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Ok(Some(entry)) = self.key_entry(&key).await
|
||||
&& entry.knows(&fingerprint)
|
||||
&& time.saturating_sub(entry.last_seen) < LAST_SEEN_RESOLUTION
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Some(candidate) = self.harvested_candidate(&harvested, from, time).await else {
|
||||
continue;
|
||||
};
|
||||
match self.store_key_candidate(candidate).await {
|
||||
Ok(KeyChange::Stored | KeyChange::Replaced) => {
|
||||
trc::event!(
|
||||
Encryption(EncryptionEvent::KeyHarvested),
|
||||
SpanId = session_id,
|
||||
From = from.to_string(),
|
||||
Fingerprint = fingerprint.clone(),
|
||||
);
|
||||
}
|
||||
Ok(KeyChange::PendingApproval) => {
|
||||
trc::event!(
|
||||
Encryption(EncryptionEvent::KeyChange),
|
||||
SpanId = session_id,
|
||||
From = from.to_string(),
|
||||
Fingerprint = fingerprint.clone(),
|
||||
);
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
trc::error!(err.span_id(session_id).caused_by(trc::location!()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn harvested_candidate(
|
||||
&self,
|
||||
harvested: &HarvestedKey,
|
||||
from: &str,
|
||||
now: u64,
|
||||
) -> Option<KeyCandidate> {
|
||||
let (key, trust, source) = match harvested.source {
|
||||
HarvestSource::SmimeSignature if !harvested.signature_verified => return None,
|
||||
HarvestSource::SmimeSignature => {
|
||||
let certificates = harvested.chain();
|
||||
let anchors = self.trust_anchors().await.ok()?;
|
||||
let trust = match self
|
||||
.verify_certificate_chain(&certificates, &anchors, &[], now)
|
||||
.await
|
||||
.map(|verdict| verdict.status)
|
||||
{
|
||||
Some(ChainStatus::Valid | ChainStatus::RevocationUnknown) => KeyTrust::Verified,
|
||||
_ => KeyTrust::Unverified,
|
||||
};
|
||||
(certificates.concat(), trust, KeySource::HarvestedSmime)
|
||||
}
|
||||
HarvestSource::Autocrypt if harvested.signature_verified => (
|
||||
harvested.key.to_vec(),
|
||||
KeyTrust::Harvested,
|
||||
KeySource::HarvestedPgp,
|
||||
),
|
||||
HarvestSource::Autocrypt => (
|
||||
harvested.key.to_vec(),
|
||||
KeyTrust::Unverified,
|
||||
KeySource::Autocrypt,
|
||||
),
|
||||
};
|
||||
let parsed = crypto::parse_public_keys(&key, now).ok()?;
|
||||
Some(KeyCandidate {
|
||||
address: from.into(),
|
||||
key,
|
||||
parsed,
|
||||
source,
|
||||
trust,
|
||||
valid_until: None,
|
||||
capabilities: harvested.smime_capabilities.clone(),
|
||||
signed_at: harvested.signing_time,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl ResolveVariable for HarvestSender<'_> {
|
||||
fn resolve_variable<'a>(&'a self, variable: ExpressionVariable, _: &'a Bump) -> Variable<'a> {
|
||||
match variable {
|
||||
ExpressionVariable::Sender => self.0.into(),
|
||||
ExpressionVariable::SenderDomain => self
|
||||
.0
|
||||
.rsplit_once('@')
|
||||
.map_or("", |(_, domain)| domain)
|
||||
.into(),
|
||||
_ => "".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
12
crates/common/src/gateway/mod.rs
Normal file
12
crates/common/src/gateway/mod.rs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub mod config;
|
||||
pub mod discovery;
|
||||
pub mod harvest;
|
||||
pub mod resolver;
|
||||
pub mod store;
|
||||
pub mod trust;
|
||||
221
crates/common/src/gateway/resolver.rs
Normal file
221
crates/common/src/gateway/resolver.rs
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{
|
||||
config::KeyTrustRank,
|
||||
store::{ExternalPublicKeyData, ExternalPublicKeyStore},
|
||||
};
|
||||
use crate::{Server, storage::encryption::PublicKeyParse};
|
||||
use crypto::{KeyKind, ParsedKeys, Profile, RecipientSet};
|
||||
use quick_cache::Equivalent;
|
||||
use registry::schema::{
|
||||
enums::{KeyTrust, SmimeCipher},
|
||||
structs::ExternalPublicKey,
|
||||
};
|
||||
use smallvec::SmallVec;
|
||||
use std::{borrow::Cow, sync::Arc};
|
||||
use store::write::now;
|
||||
use utils::cache::CacheItemWeight;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct KeyCacheKey {
|
||||
pub address: Box<str>,
|
||||
}
|
||||
|
||||
#[derive(Hash)]
|
||||
struct KeyCacheRef<'x>(&'x str);
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ResolvedKey {
|
||||
pub recipients: RecipientSet,
|
||||
pub kind: KeyKind,
|
||||
pub trust: KeyTrust,
|
||||
pub fingerprint: Box<str>,
|
||||
pub expires_at: Option<u64>,
|
||||
pub profile: Profile,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct KeyEntry {
|
||||
pub key: Option<Arc<ResolvedKey>>,
|
||||
pub fingerprints: SmallVec<[Box<str>; 2]>,
|
||||
pub last_seen: u64,
|
||||
}
|
||||
|
||||
pub struct KeyQuery<'x> {
|
||||
pub address: &'x str,
|
||||
pub min_trust: KeyTrust,
|
||||
}
|
||||
|
||||
pub enum Resolution {
|
||||
Found(Arc<ResolvedKey>),
|
||||
NotFound,
|
||||
}
|
||||
|
||||
pub trait KeyResolver: Sync + Send {
|
||||
fn resolve_key(
|
||||
&self,
|
||||
query: &KeyQuery<'_>,
|
||||
) -> impl Future<Output = trc::Result<Resolution>> + Send;
|
||||
|
||||
fn key_entry(
|
||||
&self,
|
||||
key: &KeyCacheKey,
|
||||
) -> impl Future<Output = trc::Result<Option<Arc<KeyEntry>>>> + Send;
|
||||
}
|
||||
|
||||
impl KeyResolver for Server {
|
||||
async fn resolve_key(&self, query: &KeyQuery<'_>) -> trc::Result<Resolution> {
|
||||
let Some(gateway) = self.core.email.gateway.as_deref() else {
|
||||
return Ok(Resolution::NotFound);
|
||||
};
|
||||
let address = KeyCacheKey::normalize(query.address);
|
||||
let entry = match self
|
||||
.inner
|
||||
.cache
|
||||
.external_public_keys
|
||||
.get(&KeyCacheRef(&address))
|
||||
{
|
||||
Some(entry) => entry,
|
||||
None => {
|
||||
self.key_entry(&KeyCacheKey {
|
||||
address: address.into(),
|
||||
})
|
||||
.await?
|
||||
}
|
||||
};
|
||||
Ok(entry
|
||||
.and_then(|entry| {
|
||||
entry
|
||||
.select(query, &gateway.methods, now())
|
||||
.cloned()
|
||||
.map(Resolution::Found)
|
||||
})
|
||||
.unwrap_or(Resolution::NotFound))
|
||||
}
|
||||
|
||||
async fn key_entry(&self, key: &KeyCacheKey) -> trc::Result<Option<Arc<KeyEntry>>> {
|
||||
let Some(gateway) = self.core.email.gateway.as_deref() else {
|
||||
return Ok(None);
|
||||
};
|
||||
match self
|
||||
.inner
|
||||
.cache
|
||||
.external_public_keys
|
||||
.get_value_or_guard_async(key)
|
||||
.await
|
||||
{
|
||||
Ok(entry) => Ok(entry),
|
||||
Err(guard) => {
|
||||
let entry = self.load_key_entry(key).await?.map(Arc::new);
|
||||
let ttl = if entry.is_some() {
|
||||
gateway.key_refresh_interval
|
||||
} else {
|
||||
gateway.negative_ttl
|
||||
};
|
||||
guard.insert(entry.clone(), ttl);
|
||||
Ok(entry)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ResolvedKey {
|
||||
pub fn new(row: &ExternalPublicKey, parsed: ParsedKeys) -> Self {
|
||||
let aead_advertised = row.smime_oaep && row.smime_ciphers.contains(&SmimeCipher::Aes256Gcm);
|
||||
ResolvedKey {
|
||||
profile: parsed
|
||||
.set
|
||||
.inferred_profile(row.authenticated_encryption || aead_advertised),
|
||||
kind: parsed.kind,
|
||||
recipients: parsed.set,
|
||||
trust: row.trust,
|
||||
fingerprint: row.fingerprint.as_deref().unwrap_or_default().into(),
|
||||
expires_at: row.expires_at.map(|at| at.timestamp() as u64),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyEntry {
|
||||
pub fn select(
|
||||
&self,
|
||||
query: &KeyQuery<'_>,
|
||||
methods: &[KeyKind],
|
||||
now: u64,
|
||||
) -> Option<&Arc<ResolvedKey>> {
|
||||
self.key.as_ref().filter(|key| {
|
||||
methods.contains(&key.kind)
|
||||
&& key.trust.rank() >= query.min_trust.rank()
|
||||
&& key.expires_at.is_none_or(|expires_at| expires_at > now)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn knows(&self, fingerprint: &str) -> bool {
|
||||
self.fingerprints
|
||||
.iter()
|
||||
.any(|known| known.as_ref() == fingerprint)
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyCacheKey {
|
||||
pub fn new(address: &str) -> Self {
|
||||
KeyCacheKey {
|
||||
address: Self::normalize(address).into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize(address: &str) -> Cow<'_, str> {
|
||||
if address
|
||||
.bytes()
|
||||
.any(|byte| byte.is_ascii_uppercase() || !byte.is_ascii())
|
||||
{
|
||||
address.to_lowercase().into()
|
||||
} else {
|
||||
address.into()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn address_hash(address: &str) -> u32 {
|
||||
xxhash_rust::xxh3::xxh3_64(address.as_bytes()) as u32
|
||||
}
|
||||
}
|
||||
|
||||
impl Equivalent<KeyCacheKey> for KeyCacheRef<'_> {
|
||||
fn equivalent(&self, key: &KeyCacheKey) -> bool {
|
||||
self.0 == key.address.as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
impl PublicKeyParse for ExternalPublicKey {
|
||||
fn parse_keys(&self, now: u64) -> Result<ParsedKeys, crypto::KeyError> {
|
||||
crate::storage::encryption::parse_key_text(self.key_text(), now)
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheItemWeight for KeyCacheKey {
|
||||
fn weight(&self) -> u64 {
|
||||
(size_of::<KeyCacheKey>() + self.address.len()) as u64
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheItemWeight for KeyEntry {
|
||||
fn weight(&self) -> u64 {
|
||||
(size_of::<KeyEntry>()
|
||||
+ self.key.as_ref().map_or(0, |key| {
|
||||
size_of::<ResolvedKey>() + key.recipients.heap_size() + key.fingerprint.len()
|
||||
})
|
||||
+ self
|
||||
.fingerprints
|
||||
.iter()
|
||||
.map(|fingerprint| fingerprint.len())
|
||||
.sum::<usize>()) as u64
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/common/src/gateway/resolver/tests.rs"]
|
||||
mod tests;
|
||||
729
crates/common/src/gateway/store.rs
Normal file
729
crates/common/src/gateway/store.rs
Normal file
|
|
@ -0,0 +1,729 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{
|
||||
config::{GatewayConfig, KeyTrustRank},
|
||||
resolver::{KeyCacheKey, KeyEntry, ResolvedKey},
|
||||
};
|
||||
use crate::{
|
||||
Server, cache::invalidate::CacheInvalidationBuilder, ipc::CacheInvalidation,
|
||||
storage::encryption::PublicKeyParse,
|
||||
};
|
||||
use crypto::{KeyCapability, KeyKind, ParsedKeys, SmimeCapabilities};
|
||||
use encodify::base64::{LENIENT, STANDARD};
|
||||
use registry::{
|
||||
schema::{
|
||||
enums::{
|
||||
ExternalPublicKeyStatus, KeyTrust, PublicKeyCapability, PublicKeyKind, SmimeCipher,
|
||||
},
|
||||
prelude::{Object, ObjectType, Property},
|
||||
structs::{ExternalPublicKey, KeySource},
|
||||
},
|
||||
types::{datetime::UTCDateTime, id::ObjectId, map::Map},
|
||||
};
|
||||
use std::{sync::Arc, time::Duration};
|
||||
use store::{
|
||||
registry::{
|
||||
RegistryQuery,
|
||||
write::{RegistryWrite, RegistryWriteResult},
|
||||
},
|
||||
write::now,
|
||||
};
|
||||
use trc::AddContext;
|
||||
use types::id::Id;
|
||||
|
||||
pub const LAST_SEEN_RESOLUTION: u64 = 86400;
|
||||
pub const KEY_CHECK_INTERVAL: Duration = Duration::from_secs(300);
|
||||
pub const MAX_KEYS_PER_RUN: usize = 1024;
|
||||
const MAX_DUE_KEYS: usize = 2 * MAX_KEYS_PER_RUN;
|
||||
const MAX_SIGNING_TIME_SKEW: u64 = 86400;
|
||||
const MAX_BLOCKED_FINGERPRINTS: usize = 8;
|
||||
const EXPIRY_MARGIN_SECS: u64 = 2 * KEY_CHECK_INTERVAL.as_secs();
|
||||
pub const MAX_STORED_KEY_SIZE: usize = 64 * 1024;
|
||||
const SMIME_RECHECK_SECS: u64 = 86400;
|
||||
|
||||
pub struct KeyCandidate {
|
||||
pub address: Box<str>,
|
||||
pub key: Vec<u8>,
|
||||
pub parsed: ParsedKeys,
|
||||
pub source: KeySource,
|
||||
pub trust: KeyTrust,
|
||||
pub valid_until: Option<u64>,
|
||||
pub capabilities: Option<SmimeCapabilities>,
|
||||
pub signed_at: Option<u64>,
|
||||
}
|
||||
|
||||
pub struct ExternalPublicKeyRow {
|
||||
pub id: Id,
|
||||
pub revision: u64,
|
||||
pub key: ExternalPublicKey,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum KeyChange {
|
||||
Unchanged,
|
||||
Updated,
|
||||
Stored,
|
||||
Replaced,
|
||||
PendingApproval,
|
||||
}
|
||||
|
||||
pub trait ExternalPublicKeyStore: Sync + Send {
|
||||
fn load_key_entry(
|
||||
&self,
|
||||
key: &KeyCacheKey,
|
||||
) -> impl Future<Output = trc::Result<Option<KeyEntry>>> + Send;
|
||||
|
||||
fn store_key_candidate(
|
||||
&self,
|
||||
candidate: KeyCandidate,
|
||||
) -> impl Future<Output = trc::Result<KeyChange>> + Send;
|
||||
|
||||
fn external_public_key_row(
|
||||
&self,
|
||||
id: Id,
|
||||
) -> impl Future<Output = trc::Result<Option<ExternalPublicKeyRow>>> + Send;
|
||||
|
||||
fn external_public_key_for(
|
||||
&self,
|
||||
address: &str,
|
||||
) -> impl Future<Output = trc::Result<Option<ExternalPublicKeyRow>>> + Send;
|
||||
|
||||
fn due_external_public_keys(
|
||||
&self,
|
||||
now: u64,
|
||||
) -> impl Future<Output = trc::Result<Vec<Id>>> + Send;
|
||||
|
||||
fn has_due_external_public_keys(
|
||||
&self,
|
||||
now: u64,
|
||||
) -> impl Future<Output = trc::Result<bool>> + Send;
|
||||
|
||||
fn update_external_public_key(
|
||||
&self,
|
||||
row: &ExternalPublicKeyRow,
|
||||
new: ExternalPublicKey,
|
||||
) -> impl Future<Output = trc::Result<()>> + Send;
|
||||
|
||||
fn invalidate_external_public_key(
|
||||
&self,
|
||||
address: &str,
|
||||
) -> impl Future<Output = trc::Result<()>> + Send;
|
||||
}
|
||||
|
||||
pub trait ExternalPublicKeyData {
|
||||
fn key_text(&self) -> &str;
|
||||
|
||||
fn key_bytes(&self) -> Vec<u8>;
|
||||
|
||||
fn set_key(&mut self, candidate: &KeyCandidate, fingerprint: String);
|
||||
|
||||
fn set_next_key(&mut self, candidate: &KeyCandidate, fingerprint: String);
|
||||
|
||||
fn clear_key(&mut self);
|
||||
|
||||
fn clear_next_key(&mut self);
|
||||
|
||||
fn promote_next_key(&mut self) -> bool;
|
||||
|
||||
fn replacement_due(&self, now: u64) -> bool;
|
||||
|
||||
fn block_fingerprint(&mut self, fingerprint: &str);
|
||||
|
||||
fn revoke(&mut self, fingerprints: &[String]) -> bool;
|
||||
|
||||
fn accept_candidate(
|
||||
&mut self,
|
||||
candidate: &KeyCandidate,
|
||||
fingerprint: String,
|
||||
now: u64,
|
||||
) -> KeyChange;
|
||||
|
||||
fn schedule_next_check(&mut self, gateway: &GatewayConfig, now: u64);
|
||||
|
||||
fn schedule_retry(&mut self, gateway: &GatewayConfig, now: u64);
|
||||
|
||||
fn differs_when_resolved(&self, other: &ExternalPublicKey) -> bool;
|
||||
}
|
||||
|
||||
pub trait KeySourceKind {
|
||||
fn harvested_kind(&self) -> Option<KeyKind>;
|
||||
|
||||
fn is_automatic(&self) -> bool;
|
||||
}
|
||||
|
||||
pub trait RegistryKeyCapabilities {
|
||||
fn registry_capabilities(&self) -> Map<PublicKeyCapability>;
|
||||
}
|
||||
|
||||
pub trait RegistryKeyKind {
|
||||
fn registry_kind(self) -> PublicKeyKind;
|
||||
}
|
||||
|
||||
impl ExternalPublicKeyStore for Server {
|
||||
async fn load_key_entry(&self, key: &KeyCacheKey) -> trc::Result<Option<KeyEntry>> {
|
||||
let Some(ExternalPublicKeyRow { key: row, .. }) =
|
||||
self.external_public_key_for(&key.address).await?
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
Ok(Some(KeyEntry {
|
||||
key: (row.status != ExternalPublicKeyStatus::Disabled && row.key.is_some())
|
||||
.then(|| row.parse_keys(now()).ok())
|
||||
.flatten()
|
||||
.map(|parsed| Arc::new(ResolvedKey::new(&row, parsed))),
|
||||
fingerprints: row
|
||||
.fingerprint
|
||||
.iter()
|
||||
.chain(row.next_fingerprint.iter())
|
||||
.chain(row.blocked_fingerprints.iter())
|
||||
.map(|fingerprint| Box::from(fingerprint.as_str()))
|
||||
.collect(),
|
||||
last_seen: row.last_seen.timestamp() as u64,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn external_public_key_row(&self, id: Id) -> trc::Result<Option<ExternalPublicKeyRow>> {
|
||||
Ok(self
|
||||
.registry()
|
||||
.get(ObjectId::new(ObjectType::ExternalPublicKey, id))
|
||||
.await?
|
||||
.map(|object| ExternalPublicKeyRow {
|
||||
id,
|
||||
revision: object.revision,
|
||||
key: object.into(),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn external_public_key_for(
|
||||
&self,
|
||||
address: &str,
|
||||
) -> trc::Result<Option<ExternalPublicKeyRow>> {
|
||||
match self
|
||||
.registry()
|
||||
.primary_key(
|
||||
ObjectType::ExternalPublicKey.into(),
|
||||
Property::EmailAddress,
|
||||
address.as_bytes().to_vec(),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())?
|
||||
{
|
||||
Some(id) => self.external_public_key_row(id.id()).await,
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
async fn due_external_public_keys(&self, now: u64) -> trc::Result<Vec<Id>> {
|
||||
self.registry()
|
||||
.query::<Vec<Id>>(
|
||||
RegistryQuery::new(ObjectType::ExternalPublicKey)
|
||||
.less_than_or_equal(Property::NextCheckAt, now)
|
||||
.with_limit(MAX_DUE_KEYS),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())
|
||||
}
|
||||
|
||||
async fn has_due_external_public_keys(&self, now: u64) -> trc::Result<bool> {
|
||||
self.registry()
|
||||
.query::<Vec<Id>>(
|
||||
RegistryQuery::new(ObjectType::ExternalPublicKey)
|
||||
.less_than_or_equal(Property::NextCheckAt, now)
|
||||
.with_limit(1),
|
||||
)
|
||||
.await
|
||||
.caused_by(trc::location!())
|
||||
.map(|due| !due.is_empty())
|
||||
}
|
||||
|
||||
async fn store_key_candidate(&self, mut candidate: KeyCandidate) -> trc::Result<KeyChange> {
|
||||
let time = now();
|
||||
candidate.address = candidate.address.to_lowercase().into_boxed_str();
|
||||
let Some(fingerprint) = candidate
|
||||
.fingerprint()
|
||||
.filter(|_| candidate.key.len() <= MAX_STORED_KEY_SIZE)
|
||||
else {
|
||||
return Ok(KeyChange::Unchanged);
|
||||
};
|
||||
let Some(row) = self.external_public_key_for(&candidate.address).await? else {
|
||||
let address = candidate.address.clone();
|
||||
let mut row = candidate.into_row(fingerprint, time);
|
||||
if let Some(gateway) = self.core.email.gateway.as_deref() {
|
||||
row.schedule_next_check(gateway, time);
|
||||
}
|
||||
let object = Object::new(row.into());
|
||||
let result = match self.registry().write(RegistryWrite::insert(&object)).await {
|
||||
Err(err) if err.is_assertion_failure() => return Ok(KeyChange::Unchanged),
|
||||
result => result.caused_by(trc::location!())?,
|
||||
};
|
||||
if matches!(result, RegistryWriteResult::PrimaryKeyConflict { .. }) {
|
||||
return Ok(KeyChange::Unchanged);
|
||||
}
|
||||
assert_key_written(result)?;
|
||||
self.invalidate_external_public_key(&address).await?;
|
||||
return Ok(KeyChange::Stored);
|
||||
};
|
||||
|
||||
if row.key.fingerprint.as_deref() == Some(fingerprint.as_str()) {
|
||||
return match candidate.refreshed(&row.key, time) {
|
||||
Some(updated) => {
|
||||
self.update_external_public_key(&row, updated).await?;
|
||||
Ok(KeyChange::Updated)
|
||||
}
|
||||
None => Ok(KeyChange::Unchanged),
|
||||
};
|
||||
}
|
||||
if row.key.status == ExternalPublicKeyStatus::Disabled
|
||||
|| (row.key.source.harvested_kind() != Some(candidate.parsed.kind)
|
||||
&& !candidate.outranks_harvested(&row.key))
|
||||
|| row.key.next_fingerprint.as_deref() == Some(fingerprint.as_str())
|
||||
|| row
|
||||
.key
|
||||
.blocked_fingerprints
|
||||
.iter()
|
||||
.any(|blocked| *blocked == fingerprint)
|
||||
{
|
||||
return Ok(KeyChange::Unchanged);
|
||||
}
|
||||
|
||||
let mut updated = row.key.clone();
|
||||
let change = updated.accept_candidate(&candidate, fingerprint, time);
|
||||
if change != KeyChange::Unchanged {
|
||||
if let Some(gateway) = self.core.email.gateway.as_deref() {
|
||||
updated.schedule_next_check(gateway, time);
|
||||
}
|
||||
self.update_external_public_key(&row, updated).await?;
|
||||
}
|
||||
Ok(change)
|
||||
}
|
||||
|
||||
async fn update_external_public_key(
|
||||
&self,
|
||||
row: &ExternalPublicKeyRow,
|
||||
new: ExternalPublicKey,
|
||||
) -> trc::Result<()> {
|
||||
let address = new.email_address.clone();
|
||||
let affects_cache = new.differs_when_resolved(&row.key);
|
||||
let new = Object::new(new.into());
|
||||
let mut current = Object::new(row.key.clone().into());
|
||||
current.revision = row.revision;
|
||||
let result = self
|
||||
.registry()
|
||||
.write(RegistryWrite::update(row.id, &new, ¤t))
|
||||
.await
|
||||
.caused_by(trc::location!())?;
|
||||
assert_key_written(result)?;
|
||||
if affects_cache {
|
||||
self.invalidate_external_public_key(&address).await
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
async fn invalidate_external_public_key(&self, address: &str) -> trc::Result<()> {
|
||||
self.invalidate_caches(CacheInvalidationBuilder::default().with_invalidation(
|
||||
CacheInvalidation::ExternalPublicKey(KeyCacheKey::address_hash(address)),
|
||||
))
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalPublicKeyData for ExternalPublicKey {
|
||||
fn key_text(&self) -> &str {
|
||||
self.key.as_deref().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn key_bytes(&self) -> Vec<u8> {
|
||||
let key = self.key_text().trim_ascii();
|
||||
if key.starts_with("-----") {
|
||||
key.as_bytes().to_vec()
|
||||
} else {
|
||||
LENIENT
|
||||
.decode(key.as_bytes())
|
||||
.unwrap_or_else(|_| key.as_bytes().to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
fn set_key(&mut self, candidate: &KeyCandidate, fingerprint: String) {
|
||||
self.key = Some(STANDARD.encode(&candidate.key));
|
||||
self.kind = Some(candidate.parsed.kind.registry_kind());
|
||||
self.key_type = Some(candidate.parsed.set.key_type());
|
||||
self.fingerprint = Some(fingerprint);
|
||||
self.capabilities = candidate.parsed.registry_capabilities();
|
||||
self.expires_at = candidate.expires_at();
|
||||
self.source = candidate.source.clone();
|
||||
self.trust = candidate.trust;
|
||||
self.smime_ciphers = Map::default();
|
||||
self.smime_oaep = false;
|
||||
self.smime_signed_at = None;
|
||||
candidate.apply_capabilities(self);
|
||||
self.clear_next_key();
|
||||
}
|
||||
|
||||
fn set_next_key(&mut self, candidate: &KeyCandidate, fingerprint: String) {
|
||||
self.next_key = Some(STANDARD.encode(&candidate.key));
|
||||
self.next_key_type = Some(candidate.parsed.set.key_type());
|
||||
self.next_fingerprint = Some(fingerprint);
|
||||
self.next_capabilities = candidate.parsed.registry_capabilities();
|
||||
self.next_expires_at = candidate.expires_at();
|
||||
self.status = ExternalPublicKeyStatus::PendingApproval;
|
||||
}
|
||||
|
||||
fn clear_key(&mut self) {
|
||||
self.key = None;
|
||||
self.kind = None;
|
||||
self.key_type = None;
|
||||
self.fingerprint = None;
|
||||
self.capabilities = Map::default();
|
||||
self.expires_at = None;
|
||||
self.smime_ciphers = Map::default();
|
||||
self.smime_oaep = false;
|
||||
self.smime_signed_at = None;
|
||||
}
|
||||
|
||||
fn clear_next_key(&mut self) {
|
||||
self.next_key = None;
|
||||
self.next_key_type = None;
|
||||
self.next_fingerprint = None;
|
||||
self.next_capabilities = Map::default();
|
||||
self.next_expires_at = None;
|
||||
if self.status == ExternalPublicKeyStatus::PendingApproval {
|
||||
self.status = ExternalPublicKeyStatus::Active;
|
||||
}
|
||||
}
|
||||
|
||||
fn promote_next_key(&mut self) -> bool {
|
||||
if self.next_key.is_none() {
|
||||
return false;
|
||||
}
|
||||
self.key = self.next_key.take();
|
||||
self.key_type = self.next_key_type.take();
|
||||
self.fingerprint = self.next_fingerprint.take();
|
||||
self.capabilities = std::mem::take(&mut self.next_capabilities);
|
||||
self.expires_at = self.next_expires_at.take();
|
||||
self.smime_ciphers = Map::default();
|
||||
self.smime_oaep = false;
|
||||
self.smime_signed_at = None;
|
||||
self.clear_next_key();
|
||||
true
|
||||
}
|
||||
|
||||
fn replacement_due(&self, now: u64) -> bool {
|
||||
self.next_key.is_some()
|
||||
&& !self.pinned
|
||||
&& self
|
||||
.expires_at
|
||||
.is_some_and(|expires_at| expires_at.timestamp() as u64 <= now)
|
||||
}
|
||||
|
||||
fn block_fingerprint(&mut self, fingerprint: &str) {
|
||||
if !self.blocked_fingerprints.iter().any(|b| b == fingerprint) {
|
||||
if self.blocked_fingerprints.len() >= MAX_BLOCKED_FINGERPRINTS {
|
||||
self.blocked_fingerprints.inner_mut().remove(0);
|
||||
}
|
||||
self.blocked_fingerprints.push(fingerprint.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
fn revoke(&mut self, fingerprints: &[String]) -> bool {
|
||||
let mut revoked = false;
|
||||
if let Some(fingerprint) = self
|
||||
.next_fingerprint
|
||||
.clone()
|
||||
.filter(|fingerprint| fingerprints.contains(fingerprint))
|
||||
{
|
||||
self.block_fingerprint(&fingerprint);
|
||||
self.clear_next_key();
|
||||
revoked = true;
|
||||
}
|
||||
if let Some(fingerprint) = self
|
||||
.fingerprint
|
||||
.clone()
|
||||
.filter(|fingerprint| fingerprints.contains(fingerprint))
|
||||
{
|
||||
self.block_fingerprint(&fingerprint);
|
||||
if self.pinned || !self.promote_next_key() {
|
||||
self.clear_key();
|
||||
}
|
||||
revoked = true;
|
||||
}
|
||||
revoked
|
||||
}
|
||||
|
||||
fn accept_candidate(
|
||||
&mut self,
|
||||
candidate: &KeyCandidate,
|
||||
fingerprint: String,
|
||||
now: u64,
|
||||
) -> KeyChange {
|
||||
if self.next_fingerprint.as_deref() == Some(fingerprint.as_str())
|
||||
&& (self.pinned || !self.source.is_automatic())
|
||||
{
|
||||
return KeyChange::Unchanged;
|
||||
}
|
||||
if self.key.is_none() && (!self.pinned || self.blocked_fingerprints.is_empty()) {
|
||||
self.set_key(candidate, fingerprint);
|
||||
self.first_seen = UTCDateTime::from_timestamp(now as i64);
|
||||
self.last_seen = self.first_seen;
|
||||
KeyChange::Stored
|
||||
} else if candidate.may_replace(self, now) {
|
||||
self.set_key(candidate, fingerprint);
|
||||
self.last_seen = UTCDateTime::from_timestamp(now as i64);
|
||||
KeyChange::Replaced
|
||||
} else {
|
||||
self.set_next_key(candidate, fingerprint);
|
||||
KeyChange::PendingApproval
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule_next_check(&mut self, gateway: &GatewayConfig, now: u64) {
|
||||
let expires_at = self
|
||||
.expires_at
|
||||
.map(|at| at.timestamp() as u64)
|
||||
.filter(|_| self.status != ExternalPublicKeyStatus::Disabled);
|
||||
let check_at = match &self.source {
|
||||
_ if self.status == ExternalPublicKeyStatus::Disabled => None,
|
||||
KeySource::Automatic(_) => {
|
||||
let check_at = now + gateway.key_refresh_interval.as_secs();
|
||||
Some(
|
||||
expires_at
|
||||
.filter(|expires_at| *expires_at > now)
|
||||
.map_or(check_at, |expires_at| {
|
||||
check_at.min(expires_at.saturating_sub(EXPIRY_MARGIN_SECS))
|
||||
}),
|
||||
)
|
||||
}
|
||||
KeySource::HarvestedSmime if self.trust != KeyTrust::Manual && self.key.is_some() => {
|
||||
Some(now - (now % SMIME_RECHECK_SECS) + SMIME_RECHECK_SECS)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let promote_at = expires_at.filter(|_| self.next_key.is_some() && !self.pinned);
|
||||
let next_check = match (check_at, promote_at) {
|
||||
(Some(check_at), Some(promote_at)) => Some(check_at.min(promote_at)),
|
||||
(check_at, promote_at) => check_at.or(promote_at),
|
||||
};
|
||||
self.next_check_at = next_check.map(|at| {
|
||||
UTCDateTime::from_timestamp(at.max(now + KEY_CHECK_INTERVAL.as_secs()) as i64)
|
||||
});
|
||||
}
|
||||
|
||||
fn schedule_retry(&mut self, gateway: &GatewayConfig, now: u64) {
|
||||
let confirmed = self
|
||||
.last_checked
|
||||
.unwrap_or(self.first_seen)
|
||||
.timestamp()
|
||||
.max(0) as u64;
|
||||
let delay = now.saturating_sub(confirmed).clamp(
|
||||
KEY_CHECK_INTERVAL.as_secs(),
|
||||
gateway
|
||||
.key_refresh_interval
|
||||
.as_secs()
|
||||
.max(KEY_CHECK_INTERVAL.as_secs()),
|
||||
);
|
||||
let retry_before = self
|
||||
.expires_at
|
||||
.map(|at| at.timestamp() as u64)
|
||||
.filter(|at| *at > now || (self.next_key.is_some() && !self.pinned))
|
||||
.map(|at| at.max(now + KEY_CHECK_INTERVAL.as_secs()));
|
||||
let retry_at = retry_before.map_or(now + delay, |at| at.min(now + delay));
|
||||
self.next_check_at = Some(UTCDateTime::from_timestamp(retry_at as i64));
|
||||
}
|
||||
|
||||
fn differs_when_resolved(&self, other: &ExternalPublicKey) -> bool {
|
||||
self.key != other.key
|
||||
|| self.status != other.status
|
||||
|| self.trust != other.trust
|
||||
|| self.expires_at != other.expires_at
|
||||
|| self.last_seen != other.last_seen
|
||||
|| self.next_fingerprint != other.next_fingerprint
|
||||
|| self.blocked_fingerprints != other.blocked_fingerprints
|
||||
|| self.smime_oaep != other.smime_oaep
|
||||
|| self.smime_ciphers != other.smime_ciphers
|
||||
|| self.authenticated_encryption != other.authenticated_encryption
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_key_written(result: RegistryWriteResult) -> trc::Result<()> {
|
||||
match result {
|
||||
RegistryWriteResult::Success(_) => Ok(()),
|
||||
_ => Err(trc::StoreEvent::UnexpectedError
|
||||
.into_err()
|
||||
.details("External public key was not written.")
|
||||
.caused_by(trc::location!())),
|
||||
}
|
||||
}
|
||||
|
||||
impl KeySourceKind for KeySource {
|
||||
fn harvested_kind(&self) -> Option<KeyKind> {
|
||||
match self {
|
||||
KeySource::HarvestedSmime => Some(KeyKind::Smime),
|
||||
KeySource::HarvestedPgp | KeySource::Autocrypt => Some(KeyKind::OpenPgp),
|
||||
KeySource::Manual | KeySource::Automatic(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_automatic(&self) -> bool {
|
||||
matches!(self, KeySource::Automatic(_))
|
||||
}
|
||||
}
|
||||
|
||||
impl RegistryKeyKind for KeyKind {
|
||||
fn registry_kind(self) -> PublicKeyKind {
|
||||
match self {
|
||||
KeyKind::OpenPgp => PublicKeyKind::OpenPgp,
|
||||
KeyKind::Smime => PublicKeyKind::Smime,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyCandidate {
|
||||
pub fn fingerprint(&self) -> Option<String> {
|
||||
match self.parsed.fingerprints.as_slice() {
|
||||
[fingerprint] => Some(fingerprint.to_hex()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn expires_at(&self) -> Option<UTCDateTime> {
|
||||
match (self.parsed.expires_at, self.valid_until) {
|
||||
(Some(expires_at), Some(valid_until)) => Some(expires_at.min(valid_until)),
|
||||
(expires_at, valid_until) => expires_at.or(valid_until),
|
||||
}
|
||||
.map(|at| UTCDateTime::from_timestamp(at as i64))
|
||||
}
|
||||
|
||||
fn outranks_harvested(&self, current: &ExternalPublicKey) -> bool {
|
||||
!current.pinned
|
||||
&& current.source.harvested_kind().is_some()
|
||||
&& self.trust.rank() > current.trust.rank()
|
||||
}
|
||||
|
||||
fn may_replace(&self, current: &ExternalPublicKey, now: u64) -> bool {
|
||||
!current.pinned
|
||||
&& (current.source.is_automatic()
|
||||
|| (self.trust == KeyTrust::Verified && self.trust.rank() >= current.trust.rank())
|
||||
|| (current.trust == KeyTrust::Unverified
|
||||
&& self.trust.rank() > current.trust.rank())
|
||||
|| current
|
||||
.expires_at
|
||||
.is_some_and(|expires_at| expires_at.timestamp() as u64 <= now)
|
||||
|| (self.parsed.kind == KeyKind::OpenPgp
|
||||
&& crypto::certifies(
|
||||
¤t.key_bytes(),
|
||||
&self.key,
|
||||
¤t.email_address,
|
||||
now,
|
||||
)))
|
||||
}
|
||||
|
||||
pub fn refreshed(&self, row: &ExternalPublicKey, now: u64) -> Option<ExternalPublicKey> {
|
||||
let mut updated = row.clone();
|
||||
let mut changed = false;
|
||||
if now.saturating_sub(row.last_seen.timestamp() as u64) >= LAST_SEEN_RESOLUTION {
|
||||
updated.last_seen = UTCDateTime::from_timestamp(now as i64);
|
||||
changed = true;
|
||||
}
|
||||
let automatic = row.source.is_automatic();
|
||||
let authoritative = automatic && self.source == row.source;
|
||||
if row.source.harvested_kind().is_some() && self.trust.rank() > row.trust.rank() {
|
||||
updated.trust = self.trust;
|
||||
updated.source = self.source.clone();
|
||||
changed = true;
|
||||
}
|
||||
if authoritative && row.expires_at != self.expires_at() {
|
||||
updated.expires_at = self.expires_at();
|
||||
changed = true;
|
||||
}
|
||||
if !row.pinned
|
||||
&& ((!automatic && self.extends_expiry(row))
|
||||
|| (authoritative && self.key != row.key_bytes()))
|
||||
{
|
||||
updated.key = Some(STANDARD.encode(&self.key));
|
||||
updated.key_type = Some(self.parsed.set.key_type());
|
||||
updated.capabilities = self.parsed.registry_capabilities();
|
||||
updated.expires_at = self.expires_at();
|
||||
changed = true;
|
||||
}
|
||||
if self.apply_capabilities(&mut updated) {
|
||||
changed = true;
|
||||
}
|
||||
changed.then_some(updated)
|
||||
}
|
||||
|
||||
fn apply_capabilities(&self, row: &mut ExternalPublicKey) -> bool {
|
||||
if let (Some(capabilities), Some(signed_at)) = (&self.capabilities, self.signed_at)
|
||||
&& signed_at <= now() + MAX_SIGNING_TIME_SKEW
|
||||
&& row
|
||||
.smime_signed_at
|
||||
.is_none_or(|known| (known.timestamp() as u64) < signed_at)
|
||||
{
|
||||
row.smime_ciphers = Self::registry_ciphers(capabilities);
|
||||
row.smime_oaep = capabilities.rsaes_oaep;
|
||||
row.smime_signed_at = Some(UTCDateTime::from_timestamp(signed_at as i64));
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn extends_expiry(&self, row: &ExternalPublicKey) -> bool {
|
||||
match (self.parsed.expires_at, row.expires_at) {
|
||||
(None, Some(_)) => true,
|
||||
(Some(new), Some(known)) => new > known.timestamp() as u64,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn registry_ciphers(capabilities: &SmimeCapabilities) -> Map<SmimeCipher> {
|
||||
let mut ciphers = Map::default();
|
||||
for cipher in &capabilities.ciphers {
|
||||
ciphers.push(match cipher {
|
||||
crypto::SmimeCipher::Aes128Cbc => SmimeCipher::Aes128Cbc,
|
||||
crypto::SmimeCipher::Aes192Cbc => SmimeCipher::Aes192Cbc,
|
||||
crypto::SmimeCipher::Aes256Cbc => SmimeCipher::Aes256Cbc,
|
||||
crypto::SmimeCipher::Aes128Gcm => SmimeCipher::Aes128Gcm,
|
||||
crypto::SmimeCipher::Aes192Gcm => SmimeCipher::Aes192Gcm,
|
||||
crypto::SmimeCipher::Aes256Gcm => SmimeCipher::Aes256Gcm,
|
||||
crypto::SmimeCipher::ChaCha20Poly1305 => SmimeCipher::ChaCha20Poly1305,
|
||||
});
|
||||
}
|
||||
ciphers
|
||||
}
|
||||
|
||||
fn into_row(self, fingerprint: String, now: u64) -> ExternalPublicKey {
|
||||
let time = UTCDateTime::from_timestamp(now as i64);
|
||||
let mut row = ExternalPublicKey {
|
||||
email_address: self.address.to_string(),
|
||||
first_seen: time,
|
||||
last_seen: time,
|
||||
last_checked: Some(time),
|
||||
..Default::default()
|
||||
};
|
||||
row.set_key(&self, fingerprint);
|
||||
row
|
||||
}
|
||||
}
|
||||
|
||||
impl RegistryKeyCapabilities for ParsedKeys {
|
||||
fn registry_capabilities(&self) -> Map<PublicKeyCapability> {
|
||||
let mut capabilities = Map::default();
|
||||
if self.capabilities.contains(KeyCapability::Aead) {
|
||||
capabilities.push(PublicKeyCapability::Aead);
|
||||
}
|
||||
if self.capabilities.contains(KeyCapability::PostQuantum) {
|
||||
capabilities.push(PublicKeyCapability::PostQuantum);
|
||||
}
|
||||
capabilities
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/common/src/gateway/store/tests.rs"]
|
||||
mod tests;
|
||||
128
crates/common/src/gateway/trust.rs
Normal file
128
crates/common/src/gateway/trust.rs
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::Server;
|
||||
use crypto::{ChainStatus, ChainVerdict, Crl, TrustAnchors, TrustContext};
|
||||
use registry::schema::{prelude::ObjectType, structs::SmimeTrustAnchor};
|
||||
use reqwest::Method;
|
||||
use std::time::Duration;
|
||||
use store::registry::RegistryQuery;
|
||||
use tokio::sync::OnceCell;
|
||||
use types::id::Id;
|
||||
use utils::HttpLimitResponse;
|
||||
|
||||
const CHAIN_VERIFY_DEADLINE: Duration = Duration::from_secs(45);
|
||||
const MAX_CHAIN_FETCHES: usize = 4;
|
||||
const MAX_ISSUER_FETCHES: usize = 8;
|
||||
const MAX_INTERMEDIATE_SIZE: usize = 64 * 1024;
|
||||
|
||||
pub type RunTrustAnchors = OnceCell<TrustAnchors>;
|
||||
|
||||
pub trait SmimeTrust: Sync + Send {
|
||||
fn trust_anchors(&self) -> impl Future<Output = trc::Result<TrustAnchors>> + Send;
|
||||
|
||||
fn run_trust_anchors<'x>(
|
||||
&self,
|
||||
anchors: &'x RunTrustAnchors,
|
||||
) -> impl Future<Output = trc::Result<&'x TrustAnchors>> + Send;
|
||||
|
||||
fn verify_certificate_chain(
|
||||
&self,
|
||||
certificates: &[Vec<u8>],
|
||||
anchors: &TrustAnchors,
|
||||
crls: &[Crl],
|
||||
now: u64,
|
||||
) -> impl Future<Output = Option<ChainVerdict>> + Send;
|
||||
}
|
||||
|
||||
impl SmimeTrust for Server {
|
||||
async fn trust_anchors(&self) -> trc::Result<TrustAnchors> {
|
||||
let mut anchors = match self.core.email.gateway.as_deref() {
|
||||
Some(gateway) if gateway.use_bundled_roots => TrustAnchors::embedded(),
|
||||
_ => TrustAnchors::empty(),
|
||||
};
|
||||
let ids = self
|
||||
.registry()
|
||||
.query::<Vec<Id>>(RegistryQuery::new(ObjectType::SmimeTrustAnchor))
|
||||
.await?;
|
||||
for id in ids {
|
||||
if let Some(anchor) = self.registry().object::<SmimeTrustAnchor>(id).await?
|
||||
&& anchor.enable
|
||||
{
|
||||
let _ = anchors.add(anchor.certificate.as_bytes());
|
||||
}
|
||||
}
|
||||
Ok(anchors)
|
||||
}
|
||||
|
||||
async fn run_trust_anchors<'x>(
|
||||
&self,
|
||||
anchors: &'x RunTrustAnchors,
|
||||
) -> trc::Result<&'x TrustAnchors> {
|
||||
anchors.get_or_try_init(|| self.trust_anchors()).await
|
||||
}
|
||||
|
||||
async fn verify_certificate_chain(
|
||||
&self,
|
||||
certificates: &[Vec<u8>],
|
||||
anchors: &TrustAnchors,
|
||||
crls: &[Crl],
|
||||
now: u64,
|
||||
) -> Option<ChainVerdict> {
|
||||
let gateway = self.core.email.gateway.as_deref()?;
|
||||
let (leaf, supplied) = certificates.split_first()?;
|
||||
let mut fetched: Vec<Vec<u8>> = Vec::new();
|
||||
let mut attempted: Vec<Box<str>> = Vec::new();
|
||||
|
||||
tokio::time::timeout(CHAIN_VERIFY_DEADLINE, async {
|
||||
for round in 0..=MAX_CHAIN_FETCHES {
|
||||
let intermediates: Vec<&[u8]> = supplied
|
||||
.iter()
|
||||
.chain(fetched.iter())
|
||||
.map(Vec::as_slice)
|
||||
.collect();
|
||||
let verdict = crypto::verify_smime_chain(
|
||||
leaf,
|
||||
&TrustContext {
|
||||
anchors,
|
||||
intermediates: &intermediates,
|
||||
crls,
|
||||
now,
|
||||
},
|
||||
)
|
||||
.ok()?;
|
||||
if verdict.status != ChainStatus::Untrusted
|
||||
|| verdict.issuer_urls.is_empty()
|
||||
|| round == MAX_CHAIN_FETCHES
|
||||
{
|
||||
return Some(verdict);
|
||||
}
|
||||
let before = fetched.len();
|
||||
for url in &verdict.issuer_urls {
|
||||
if attempted.len() >= MAX_ISSUER_FETCHES || attempted.contains(url) {
|
||||
continue;
|
||||
}
|
||||
attempted.push(url.clone());
|
||||
if let Ok(request) = gateway.pki_http.request(Method::GET, url)
|
||||
&& let Ok(response) = request.send().await
|
||||
&& response.status().is_success()
|
||||
&& let Ok(Some(body)) =
|
||||
response.bytes_with_limit(MAX_INTERMEDIATE_SIZE).await
|
||||
{
|
||||
fetched.push(body);
|
||||
}
|
||||
}
|
||||
if fetched.len() == before {
|
||||
return Some(verdict);
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
}
|
||||
|
|
@ -173,6 +173,7 @@ pub enum CacheInvalidation {
|
|||
grant_id: u64,
|
||||
},
|
||||
ActiveSieveScript(u32),
|
||||
ExternalPublicKey(u32),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
|
|
|||
|
|
@ -54,6 +54,7 @@ use config::{
|
|||
storage::Storage,
|
||||
telemetry::Metrics,
|
||||
};
|
||||
use gateway::resolver::{KeyCacheKey, KeyEntry};
|
||||
use ipc::{BroadcastEvent, PushEvent, QueueEvent, ReportingEvent, subscribers::PushSubscribers};
|
||||
use mail_auth::{Mx, Negative, RecordSet, TxtRecord};
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
|
|
@ -87,6 +88,7 @@ pub mod auth;
|
|||
pub mod cache;
|
||||
pub mod config;
|
||||
pub mod expr;
|
||||
pub mod gateway;
|
||||
pub mod i18n;
|
||||
pub mod ipc;
|
||||
pub mod manager;
|
||||
|
|
@ -161,6 +163,7 @@ pub const KV_LOCK_DAV: u8 = 16;
|
|||
pub const KV_LOCK_SEARCH_INDEX: u8 = 17;
|
||||
pub const KV_OAUTH_CIMD: u8 = 18;
|
||||
pub const KV_RATE_LIMIT_CIMD: u8 = 19;
|
||||
pub const KV_KEY_LOOKUP: u8 = 20;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Server {
|
||||
|
|
@ -199,6 +202,8 @@ pub struct Data {
|
|||
|
||||
pub smtp_connectors: TlsConnectors,
|
||||
pub memory_budget: MemoryBudget,
|
||||
|
||||
pub harvest_tasks: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
|
@ -248,6 +253,7 @@ pub struct Caches {
|
|||
pub lists: Cache<u32, Arc<MailingListCache>>,
|
||||
|
||||
pub dkim_signers: Cache<u32, Arc<DkimSigners>>,
|
||||
pub external_public_keys: CacheWithTtl<KeyCacheKey, Option<Arc<KeyEntry>>>,
|
||||
|
||||
pub dns_txt: CacheWithTtl<Box<str>, TxtRecord>,
|
||||
pub dns_mx: CacheWithTtl<Box<str>, Result<RecordSet<Mx>, Negative>>,
|
||||
|
|
@ -682,59 +688,58 @@ impl MessageUid {
|
|||
}
|
||||
}
|
||||
|
||||
pub const DEFAULT_LOGO_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAMgAAAAnCAMAAAB9lPf7AAABOFBMVEUAAAAAADoAAEkPDkIPDkIQ\r\n\
|
||||
DkIQDkLcLVTYMVTbLVTbLVQPDkLWM2YQDkIPD0IODEHaJlPbLVQWDT8MC0IQDkIQDkIPDkIODkEQ\r\n\
|
||||
D0ITDEAQDkIPDkIODkIPDkIPDkIRDUIQDkIQDUIPDkLcLVQQDkIQDkIQDkIQDULbLVQQDUIPDkIQ\r\n\
|
||||
EEIPDkIPD0EPDkHcLlUPDkLbLFQPDULbLFPbLVQQDkLbLFPcK1TbLVTbLVQQDUIPDkIPDkIPDULc\r\n\
|
||||
LVTcLVQQDkLbLFTcLFTbLFQPDkIQDkIQDULbLVUSEkPcLVTbLVQQDULbLFTcLVTbLVTbLVPbLFQP\r\n\
|
||||
DUHbLVMPDkPbLVTdLFXbLFQNDULcLVTcLlMRD0cQDkIQDkXpMFnrMFrtMFvlL1jjLlfdLVThLlYS\r\n\
|
||||
EErnL1gRD0n0Ml2YjG1wAAAAWnRSTlMABAb59/379wr7/lMF9HgoBvQJF/BtZSQwGu7JNulAO95x\r\n\
|
||||
WD3TsF1M3b6kH5MRiRe5saujyH9oHezk4tjGmn9fwkc1vrVqYA8N19DPqnFQkYh1V0a4LSITmSiJ\r\n\
|
||||
LN30AAAKZUlEQVRYw91ZCVvbRhCVrcuWD7AxYLANtrEx5opDIBCOQBLO5qTQ0uyubyD//x/0za4O\r\n\
|
||||
RIG0/dLvazu0tbTaWc3bOd6sqv2PJen9/LcF9o++fnf58r8OBcb/vNBttzvrc0Ck/VcFMN6+a/fs\r\n\
|
||||
uG23+x9+fcopkUiE/ks/35ew2j8ucMCz3wbteNwZtIcZp2O/jj3mlWjo+t8nHzNdx3ac/sLrTDee\r\n\
|
||||
GXRf7cMpD+OYnF9dO6zvnc/gOuLv93dBRScTkz/KWrwu+mBUfTrrwhHtod1b0J696N/E7T5S5UEo\r\n\
|
||||
xbrBlIidyp90CvCO1cu56you/jFBAP1y2evZdq/z4suwv3CiaXPr7X7Gbg9fbP4xvtKccSNlGEYq\r\n\
|
||||
ZQpWG3GRTM2ki49biUkjgpks8aOAZCcT6ZX7ME4+Izkyw85Pn7T9m+FCjMb2X3UHSJXM62TIKxFt\r\n\
|
||||
lXHdEPAG/jUNnelFQjJVM8T1BK4e98hIiqd+DBCskcgZjE/dW+zlFiVHd+sjXfcICEnsS7wTtwfd\r\n\
|
||||
hZ8DJFBsMNPirLxabSQqTSFMQ5RWyErBDTH/NBCdGz8MyPm1wUtjocXe/NQZZuLtwednMN4FkpSO\r\n\
|
||||
+vqhh1Tp3bx7qwXyXuhcLLsLNHJAwvZg/6TBLRYGEoE8AOTplAqrPx6nR8wQ01N3Fht90evF4+2b\r\n\
|
||||
y1+k7QEQLTkqQfbt+M3wi29NUZgWO8RSJLg1ucVTY6hj5j0geCh//pZHAvX7s+nNtOr4fSCbw0Hc\r\n\
|
||||
cdbd8ElKIIESMf3AsftbSW8nJphusqqWdTMOGQNgVRdINUQvkZWrLP24Ix6Q74qn46kHEtwqIKda\r\n\
|
||||
IJtbDgQ4YpoLxMk89+Xy+W/rAyc+OPOBpBki6wIX7v2s4CZblUBMXjtstgoNLYK/6PxarVQqt8Zh\r\n\
|
||||
zEThEKMKSCPaah4WKporK/Vm6yCP+SqDC61ma0paW10k9SYVpirUq3Jqcw23F8tr0K8wg+sHrSbN\r\n\
|
||||
l/LMadvxwfDyKyKL/vn4DQSipNdG19XtO3G7+8rf6Ap5pKJlPZ9H8/l8ccoFQrXsukIoG2Vcco6R\r\n\
|
||||
UkNrXfPrI83zSA135YhXOm6hseHt8yEe1Wh4puapT89rixjdQF3kGFvKHtA7FskOeow/RbGKCG2n\r\n\
|
||||
7Xw5kdG1+bzXaUvp9uIkjiRGH0iCWSafzitmDUhdATFNpP4RZm0wYRm6EFTKxHxBpMSEC6QKE1I6\r\n\
|
||||
B+NItWWWMsSupmRsmudok7QjqoaGVOdsoiVS7Fw+tfhx4dpI5cSyAoL3cWPyTmvScWx0JC9din+h\r\n\
|
||||
5POH+MBx4rJVCWTKgLrQV4tZt7QADWxSQCAWgCCATcsSorxbKDGMUUELgOQt/KSBltR3hMW5vuRG\r\n\
|
||||
Fowz84glMJUl2PbuLtRNqOssDSA5WJ7CdeAREssDEqNmcQg+7Ldp42PJoCwPHLgq/iWG0WDrl29T\r\n\
|
||||
WJzx7cONxEjUTz9KdpFeQqCNaXm80WKFGWBdmS8JHdABxE/2XWGwA68GcuBgx4CFu0WWYvDOEqw1\r\n\
|
||||
We0C6qeJMtR9ILRVopmeqMxQsvPczCTeB9UACrXvGftGNu8xd6SD0PJHAokc3ILPLcoHxsuL1RUM\r\n\
|
||||
uUC8klRnusXqXryUsekhIGkGnyxBi0JQJycuyiWy20JavMcMizW9TgS8FQJSfaRqPfuEFB+VB6qB\r\n\
|
||||
HVfNu+sjGz3LG8DA0093XBJdRIaZOgmhKW1g0OeRLHEjDBZlTJSGSP+EgOTJdtXN7FJkmWI7S+l3\r\n\
|
||||
IWBoXpvKcZ26haxSh39MH4iOZEFqRh7ikcE7UGGMjrh2x3Gb949bXVx2tl5iGI/mzohHgkI+u1gS\r\n\
|
||||
sqpYhoFYLqxo0YAQI0Q1iJagQi8y/S6QCJoDg61pEQlZ7BSELmaI5pZhW0GT5QSGZz31VWZ5QHRA\r\n\
|
||||
VlXCAxIJPJLpqOYEmF4M2zZS5d16Fz1Lx/l8Iod//TDsnmlhOb3YqO+kBMBYpkFxfRfIHkuJ3NSd\r\n\
|
||||
7iwMJIuAMtSWTyApNiZuU2yV7N4RBhm8qlI+YKogRwwZhA8D2cygXfS3fl12JNTQ954rR8Veo3V0\r\n\
|
||||
FkbvdkBu2V1qrL5HncTy46EW5RDm1QLQ8lEABFPyVPgasL3ODFacFJbYpcTnkBGNHCi2Tz0TI1R2\r\n\
|
||||
fY/IaveYR7po4LuUDKNu827b6j6WdJv5+Dd4JCwemEZJwKhCCMgBgBz4M5UFodBCbKXYsqZdlbjY\r\n\
|
||||
jmo1IclgA2oEqA4gO8GLqAYEQMYfBYIjleuBrzBdNu/tNjX0SSpdOF5RMcPxypVssUgFNjhrFok/\r\n\
|
||||
SlfaiOUDacKiwl3qSYWBRMhmUctqDYHOmWLJYMdIfKhRaqwBSPlOr3la+nNAvENuB9wuoXzd3/dy\r\n\
|
||||
BgfeTMDrpL9kCo5AjfqOgdk6zy3dBbIGM8ungQ5VqRAQFUVFmd3owWYo92kB1CwA2aMFx4LQWjL4\r\n\
|
||||
nwIympSfHRS3K0dIGMnX7uA+BZ3vEbCCKAdNaJQ2kE+PBUAitMMwM+h6j8LJTuM12XXsCF46pTW5\r\n\
|
||||
KMnEL+BGcrZoBMleFeb3gYS5XW1+LBaTvNIhN4V5XUWwicYp6582doCshhxxgeCv4R22ICojrDCQ\r\n\
|
||||
qIymwxGhUxWKkg9EHrROqeyeeOq4UrUFLrceBxINkv1jUkv63N6TTC7v+rbP9JgUC5pGHXVqlq6j\r\n\
|
||||
tEqF9mtZJrvOqpIQT7cFtfowEUJJbPH7QGaJBfdAIChiWFMYYrEMXlJFt0bq85qm1I+Y+Vho5a5k\r\n\
|
||||
BCjZ7C/c5/ZRfKgL8fp+JqP5sssMU5jpK1WQVgU3qWhSJFOkS0lLsG6/soGyFgaimkWTQ6ZX5KFk\r\n\
|
||||
mq5l8dMUoeLhsVI/4vxBIJjExXHoYNXuXXqUobh94VWY19fbnbNk0K8bwtA5m24try63cozrqrhH\r\n\
|
||||
y7SP7+v11h7CDWC5aI03EukaQ3m4D4RYXPaCa3QXkXkWkIR2INUPKonEeUFA/SEgM7Q/VrNeb07g\r\n\
|
||||
joDEbfrwcBJwu90P83q/ZzuvRoMzbDHHcFjgjISncIHAIj6/zYFRmLgFM0xOM90wGROMERuDskNA\r\n\
|
||||
lB2cYlG1vccEhCIroihwG+oW1AWDZr0mjHtAVIeZMjm19Mtq6GSBPgXJ7deSHrcrXh9VTsInoW/v\r\n\
|
||||
7n7AWGoJOjfRNzpYnhpXWzRVuuVwj8Fr5Lb3DCwH0QXbI4aUQAw/tKQDLaqyEBmXpi4K/hvGcAz0\r\n\
|
||||
1NdQX1J+izLu15AqY1DSU2LVHXr22ekPB+1vZ59wI7m815M8j7uXW996g2Evg5Y4EKhdrJWE8sjO\r\n\
|
||||
xpRf79emucAmluWU8RqXE94nNDqr3tJRlwt+W/WOhtecX9e9NZu3uEsH3KEdF6S62DnWaOo1AdGh\r\n\
|
||||
XgnqVKNg4H3c8wjk69zc3Nu3b+ZG3c+Oc3SVJG+9efP2LR5u/vFDxkqxOn5+lMhTwPujK/nZ2dmZ\r\n\
|
||||
vDslX61U5vMS4szsDPY+S0+vvL7lAoNeZ4kZeHQaesNIYvz8uCg7AzUzWpwNNJRWkVZceur/vSUf\r\n\
|
||||
GAtDCZrI0KAvoeG/Lt9Xx5MfIhFiicj9QSmhGd649zg098nPik+rB+/T/k/yO9A7bEvKcQkCAAAA\r\n\
|
||||
AElFTkSuQmCC";
|
||||
pub const DEFAULT_LOGO_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAcIAAABRCAMAAAB2Q1YuAAAAXVBMVEVMaXEbGRYbGRYZFxQUExAb\r\n\
|
||||
GRYbGBUbGRYbGRYaGRTbLFQbGRbbLFMaGBUXFhMbGRbbLFPcK1MbGRXbLFPbLFPcLFPpI0PbLFPd\r\n\
|
||||
KlTbLFPdK1LeJlLbKU/bLVQcGhcLDqwpAAAAHXRSTlMA654uDY1A1oBX8LGEZx3D2z12waFWB3Eq\r\n\
|
||||
+R0PFGz/LiIAAAAJcEhZcwAACxMAAAsTAQCanBgAAAtPSURBVHja7V3pYqM4DA7YHA7BNPTIdKbl\r\n\
|
||||
/R9zk+402NZpSGa3U/SvCQTkz9YtdbfLoOOFdht9Wfrx+H6hxx/bUnxNent6/6Snt205vh69nPbv\r\n\
|
||||
M+1PL9uSfDF6fniP6eF5W5QvqARj2lTi16Ffh9d3jF43lfhFKFKCMW0q8SvQ8eGdo4fNS/yf088n\r\n\
|
||||
oAEfbq8SrTe1sdtq30UJwmN3AIL19fBr8RN83zXF9JuarnJ/FEjTV/Vf7khgSvCAmDf70zL8xmYC\r\n\
|
||||
NIz+j6DnquHyOPdXK8FHVPkdUCdjgUr05URQZ+7N23h9lvtGSvAhhBBx9Z9+5j2gnRgq7yxPq78f\r\n\
|
||||
whdEVO4jCJOA24dKzHAwTDOxVBBLa+v+m0J45tyuiKa9Pp0NlgRC7KCqY251MUlUQu3Vdhfg7beD\r\n\
|
||||
MJ9zoOj+dRsAhIjPqHQw6klBMYbd9fPvBmE+52/U2UIgRIxWjUq0jQbCqQrvab4thLmcMxoOhRBz\r\n\
|
||||
MESVmJqizdBVbdkBYPsNwnzOOTsThxBzMASVaGJ5WQcau4sxrDcIMznnvT0KQgR4XiUO4QFMXEAf\r\n\
|
||||
gdhsEGZxLolEGkJE/DJpqNCWGeBbOVyUbhDKnIOUUooCAyFiBNEqMdCEgwRxs0Go5lzhHrAQZsTc\r\n\
|
||||
AoTwQJrDtOEGocR5cgT3z+QlB31UXDJmOnGBZ+dwgzALQjx7JEIItCl6UT+Jy2cRSbpBmAMhYU/K\r\n\
|
||||
EJ5jbo8ihK0kR2N16TcI8yF85i95OrJ0kCAM4LEKo7UGjLQzwT1Qj+XwkUMuujF0OH+TwSC08w+i\r\n\
|
||||
qcr681s8wj7fjWSUP1+mrWdm05cxn/cHbrAZLx+4mPOK4zyEkDJD9u+5pD1hnCR1AEIifHPhu4qj\r\n\
|
||||
50Vrky1RoqdwvqvND1LWhH3t2+SVS58w16TmW/mZCR9CY0HDOcAHj3PeHkK66GFs050pM2I6JGc1\r\n\
|
||||
2kj/4hBWvJdTsC883zxK+ezKR/YcgPDj6bZK7L1FEOL2zI0grIg4tlojEIxUeKy88eG2wSGsWcFQ\r\n\
|
||||
8y9cYPf2RBbUhN8BCIs0kZoFYerUIV7FQy6Cj0LNw1TYm0HoyeTHBcOBhzCAoWf3XMP5SPMJth2Z\r\n\
|
||||
ya6D3wMQnjeBiVRBFoRInPMIAjCvOQBSwW4hvrYMQi6FfN76hQBhybmq4ZM9Y2CPqooEN6tWCGHt\r\n\
|
||||
Yz7yIIS1FlAl/nhUA0hXYdhpEYYsIz1fxGEmAcJgW/F5lZ6J2XtdRcJ8ziCE/TCtgRAppIA4PCul\r\n\
|
||||
KZf4HWJ7w6+H0Ai540KCkLNYRrCmkd0JhKwVakqaiYYwvTUbQqTuUFMNA48vX5HYg8JRsw7CtAig\r\n\
|
||||
6MpLBrlgijlSCEvaYokPBs3MCFyQ3+zh6WwUwmk9hEicU6yGAQdTqgtGtunFD7daCOuZPFIEMNdn\r\n\
|
||||
m7HQQjhL0oKT+/CQdqkcjTdod2XL90UOhEUznKmNOXcp59pGNLYaBqhHRXU+seuKruppIOkwU1RL\r\n\
|
||||
FaeQfaeEMJCkhn3ZigK4QfZnXElpKyWERdwlsCC0CFTinjRNoJGqKmErOVVBdDnQjDRc5eKohLBE\r\n\
|
||||
HXT4rg0F8AgvB7ZaYugQEJZ+XfkTnjwkVCLIEmvL8gfe+uhcBoT1xLreTgehowI0qfjzBMA+sW7O\r\n\
|
||||
QhSueOz14RCOayvYKHCQ03V8WNwvagfJhmytlpFByD/2KggtEXyveTsidRDCMICVCmhRCMvFmYqT\r\n\
|
||||
2JaW1GHAxkNQLnNSZXvIKlKrYsQIixabiCSEwVWOfc8OR2QEZ9ZIsSkUQiRgpU42AVkJDJXwkEFH\r\n\
|
||||
AhzT8yHlHliL5cCFSqmPYgbZqyB0OEgNcNlwgI0mnJqAjEHYr8oXAhDoOSXyBJOP3K9gmErSVFUK\r\n\
|
||||
PJDuAHYMaQgt+jtX+LsScysaWo56sS0Og7BYmfIF/sALrhLZ8xl6Jju5xZfHsBUZsROf60vOBg1h\r\n\
|
||||
AHSNKNLeIcfLpM9uxLIgrKjE8Wc3L2sPvPI3qPF+HkQl+BkfULVcVY3qHBKMGEUZx04FocPW8Yqr\r\n\
|
||||
tYhb0abP1kRPBg7C+gaFF8AtEEPbQP7Od+g756qBiCwagZFelqPhqjEQWsT3s4Gn0UEROSR3qPZT\r\n\
|
||||
xUFob1I7A4IxbGgbKMHw3GZV+fi6RcKag8BIJYuu8LQwEAaS1ICT2YcyFdpJLYhXa2JTDfnJ2vIn\r\n\
|
||||
kJ94Oey1KaVYe+ZXa5lxAPk1lpGScaiQo8pBCCPW86/70LKBN5j0g0bTFNTwxvCqOlJoXz7pUkrJ\r\n\
|
||||
gV1Uc5dUnQw8I52misOpILTw6BfhB0PqVoDc7cjX4FDpKcdvw4XV3NDLe5TnPgG1uVtGcSjRKyEc\r\n\
|
||||
NU3FHISByrTJgRkjcVynkLdAYDNS3TIQVmsghGbmLz4NtZfjOYfd0nlCDUzvrIHQ6CDs0w/baBuZ\r\n\
|
||||
ZKEd0J2jBsLdvSBE8hMnJg0FU0ow0fhzt5g8DPuKurBafQp9elkTr3XyZwkUX68RpHc7hWh+4kjB\r\n\
|
||||
DOCR772ueVeec+pj75zXhVDL9eaMThcGkrSIIW2Tm3wcKmshhM0yXVit7vI9ibMPjo8XOmafYM5H\r\n\
|
||||
EwIqndKpGDSznngIx1h694mgrCO3omZ8EM6pqO8KIUzZa8YBZbX4Bspr2GmkjQChyrXvlBAmjl6X\r\n\
|
||||
HqkifKUKnjiVaz/eF8K0NUlTAJXZaF9p1jwMVXXrA2yFEsI43GLBwpbhmxdIbFYTYOvuDWHuOKDs\r\n\
|
||||
cRdu0vSFWa0u1IS5zaSFcAxdGQcCl+EnBts6mjB3cX8IoUqkBeOCoTNm0khSo7VINcmmUg2hD09R\r\n\
|
||||
CX43PJctZrkourb66U9ACKuaCPNEnLAg5DydZkwi7xeGV65K+SZP6eYXRRIXTbB1WlzELEr53g5C\r\n\
|
||||
3eyDhQPYKkVbTFjKZ3lG6hsVXqQbwhoufeg9qoKtOAqine4G4eklYw6UcgziSZz9RLVUlLBWhWSk\r\n\
|
||||
uUn5E3g513JJ/L7HPcBuXfmTAKHPrJ1h542C5AXafiHWQRAY9hPXqG3oi0dp6KIE4fyYcsDc12v7\r\n\
|
||||
bYcbUWZiN5QvFkA4KFpqqdoZciaiYiTwD7p2xkujYx2WLxwonKL66VEYmylC2IJypxozWcni74Ht\r\n\
|
||||
oZFKgSt+y7dypgJYI/hkUllR/raH5Aqgj7aDZNEHNGvfEZVtqaSMhI1tp0wIQZNUwX/dcK1sQ4yv\r\n\
|
||||
K6YlEJYk53jtjEIlHqSG4KsIVpSUfbxZ+fmvDaxJytpK1A4oWxd2hwzr22LoDqqS/7riC2Q7N7fF\r\n\
|
||||
NHJbTCXt+IRzvHbmWWw9k9pgZtQzRspeOnlg2UVgEuCDhEdEPl36a5xrs5rT6Npfx39tRN6Gc7PP\r\n\
|
||||
WOqa0yr9COWWSfkClUik7BWdwLqEIFMM7MkmsUj31atbRGlRadn1bCSThXsZJYQ2G0JEJZL/tumB\r\n\
|
||||
78dfOdq5MGI71HibRm26D6bjv67yB4/XTSaEePMCDyGmEvfov00T/BAuFdGJCCbTZj0DIY9hLY5L\r\n\
|
||||
oBfM8Y11Jnv8f8+NS6hkE14JIaISYecopwQ1tTNVznB1qrN0pKy9uDWjy4Cw5uRo8hZEWNbQGI5I\r\n\
|
||||
dFWCEOW8XRAtS9JQTAWwdkQ3dxAHIzkjiR9IqdeP0UFVBoSRqOx4zVRlypgPr8BlQ4gJmVaRuGVV\r\n\
|
||||
IlIBnD8of1dT7b4DHrE2Aw3hGeECG+C1UwzwosVDz3tEdIrSNWS/ncmHEOG8XTib+US4jy+n/bL/\r\n\
|
||||
4HSeGAenCDBzTExZ0C2xNnW9tGP0aEnq2RNRZDVuyWP0uBKulHMiUnM8JARE4dvp/OkJpJSe0xuP\r\n\
|
||||
ef/O5t8BlGffsKzEOTTG9XDI3vXL9nM8SDzM8vN6l86nxKZCziMjsdx7MPrSSfuzvL5MOMxyTH7d\r\n\
|
||||
kOxkcL7RRhtttNFGG2200Ub/If0DrtIVT4+09ukAAAAASUVORK5CYII=";
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ const MAX_APP_SIZE: usize = 100 * 1024 * 1024;
|
|||
const INDEX_PAGE: &str = "index.html";
|
||||
const BASE_HREF: &str = "<base href=\"/\"";
|
||||
const OAUTH_CLIENT_ID: &str = "<meta name=\"oauth-client-id\" content=\"\"";
|
||||
const OAUTH_SCOPES: &str = "<meta name=\"oauth-scopes\" content=\"\"";
|
||||
const APP_MANIFEST: &str = "stalwart-app.json";
|
||||
const MAX_APP_MANIFEST_SIZE: u64 = 4 * 1024;
|
||||
|
||||
|
|
@ -56,7 +57,13 @@ struct AppManifest<'x> {
|
|||
|
||||
enum IndexEdit<'x> {
|
||||
BaseHref(&'x str),
|
||||
OAuthClientId(&'x str),
|
||||
Meta(&'x str),
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
struct IndexMeta {
|
||||
client_id: Option<String>,
|
||||
scopes: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
|
@ -89,6 +96,7 @@ pub struct WebApplicationManager {
|
|||
expiry: u64,
|
||||
blob_key: BlobHash,
|
||||
oauth_client_id: Option<String>,
|
||||
index_meta: IndexMeta,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
|
|
@ -342,6 +350,10 @@ impl WebApplicationManager {
|
|||
url: app.object.resource_url,
|
||||
description: app.object.description,
|
||||
expiry: app.object.auto_update_interval.as_secs(),
|
||||
index_meta: IndexMeta::new(
|
||||
app.object.oauth_client_id.as_deref(),
|
||||
scope_list(app.object.oauth_scopes.iter()).as_deref(),
|
||||
),
|
||||
oauth_client_id: app.object.oauth_client_id,
|
||||
prefixes: app
|
||||
.object
|
||||
|
|
@ -359,7 +371,7 @@ impl WebApplicationManager {
|
|||
force_refresh: bool,
|
||||
sweep_orphans: bool,
|
||||
) -> trc::Result<AppRoutes> {
|
||||
let cached = if force_refresh {
|
||||
let mut cached = if force_refresh {
|
||||
None
|
||||
} else {
|
||||
match server
|
||||
|
|
@ -379,25 +391,24 @@ impl WebApplicationManager {
|
|||
}
|
||||
}
|
||||
};
|
||||
let is_cached = cached.is_some();
|
||||
let bundle = match cached {
|
||||
Some(bundle) => bundle,
|
||||
None => self.fetch().await?,
|
||||
};
|
||||
|
||||
let staging = TempDir::new(self.base_path.join(format!("{:x}-{generation:x}", now())));
|
||||
staging.create().await.map_err(unpack_error)?;
|
||||
|
||||
let url = self.url.clone();
|
||||
let bundle_path = staging.path.clone();
|
||||
let max_prefix_len = self
|
||||
.prefixes
|
||||
.iter()
|
||||
.map(String::len)
|
||||
.max()
|
||||
.unwrap_or_default();
|
||||
let (resources, index, oauth_client, bundle) =
|
||||
tokio::task::spawn_blocking(move || -> trc::Result<_> {
|
||||
let (resources, index, oauth_client, bundle, is_cached) = loop {
|
||||
let is_cached = cached.is_some();
|
||||
let bundle = match cached.take() {
|
||||
Some(bundle) => bundle,
|
||||
None => self.fetch().await?,
|
||||
};
|
||||
let url = self.url.clone();
|
||||
let bundle_path = staging.path.clone();
|
||||
match tokio::task::spawn_blocking(move || -> trc::Result<_> {
|
||||
let mut archive = ZipArchive::new(Cursor::new(bundle)).map_err(|err| {
|
||||
trc::ResourceEvent::Error
|
||||
.caused_by(trc::location!())
|
||||
|
|
@ -495,7 +506,21 @@ impl WebApplicationManager {
|
|||
.caused_by(trc::location!())
|
||||
.reason(err)
|
||||
.details("Bundle unpack task panicked")
|
||||
})??;
|
||||
})? {
|
||||
Ok((resources, index, oauth_client, bundle)) => {
|
||||
break (resources, index, oauth_client, bundle, is_cached);
|
||||
}
|
||||
Err(err) if is_cached => {
|
||||
trc::event!(
|
||||
Resource(trc::ResourceEvent::Error),
|
||||
Reason = err,
|
||||
Url = self.url.clone(),
|
||||
Details = "Cached application bundle is invalid, downloading it again"
|
||||
);
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
};
|
||||
|
||||
if !is_cached && let Err(err) = self.cache(server, &bundle).await {
|
||||
trc::event!(
|
||||
|
|
@ -519,7 +544,7 @@ impl WebApplicationManager {
|
|||
Ok(AppRoutes {
|
||||
resources,
|
||||
index_pages: index
|
||||
.map(|index| index_pages(&index, &self.prefixes, self.oauth_client_id.as_deref()))
|
||||
.map(|index| index_pages(&index, &self.prefixes, &self.index_meta))
|
||||
.unwrap_or_default(),
|
||||
oauth_client,
|
||||
_bundle_dir: staging,
|
||||
|
|
@ -736,18 +761,13 @@ impl Default for WebApplications {
|
|||
}
|
||||
}
|
||||
|
||||
fn index_pages(
|
||||
index: &[u8],
|
||||
prefixes: &[String],
|
||||
oauth_client_id: Option<&str>,
|
||||
) -> AHashMap<String, Bytes> {
|
||||
let client_id_meta = oauth_client_id.map(oauth_client_id_meta);
|
||||
fn index_pages(index: &[u8], prefixes: &[String], meta: &IndexMeta) -> AHashMap<String, Bytes> {
|
||||
let html = std::str::from_utf8(index).ok();
|
||||
prefixes
|
||||
.iter()
|
||||
.map(|prefix| {
|
||||
let page = match html {
|
||||
Some(html) => rewrite_index(html, prefix, client_id_meta.as_deref()),
|
||||
Some(html) => rewrite_index(html, prefix, meta),
|
||||
None => index.to_vec(),
|
||||
};
|
||||
(prefix.clone(), Bytes::from(page))
|
||||
|
|
@ -755,14 +775,12 @@ fn index_pages(
|
|||
.collect()
|
||||
}
|
||||
|
||||
fn rewrite_index(html: &str, prefix: &str, oauth_client_id_meta: Option<&str>) -> Vec<u8> {
|
||||
fn rewrite_index(html: &str, prefix: &str, meta: &IndexMeta) -> Vec<u8> {
|
||||
let mut edits = [
|
||||
html.find(BASE_HREF)
|
||||
.map(|at| (at, BASE_HREF.len(), IndexEdit::BaseHref(prefix))),
|
||||
oauth_client_id_meta.and_then(|meta| {
|
||||
html.find(OAUTH_CLIENT_ID)
|
||||
.map(|at| (at, OAUTH_CLIENT_ID.len(), IndexEdit::OAuthClientId(meta)))
|
||||
}),
|
||||
meta_edit(html, OAUTH_CLIENT_ID, meta.client_id.as_deref()),
|
||||
meta_edit(html, OAUTH_SCOPES, meta.scopes.as_deref()),
|
||||
];
|
||||
|
||||
if edits.iter().all(Option::is_none) {
|
||||
|
|
@ -770,8 +788,7 @@ fn rewrite_index(html: &str, prefix: &str, oauth_client_id_meta: Option<&str>) -
|
|||
}
|
||||
edits.sort_unstable_by_key(|edit| edit.as_ref().map_or(usize::MAX, |(at, _, _)| *at));
|
||||
|
||||
let mut out =
|
||||
String::with_capacity(html.len() + prefix.len() + oauth_client_id_meta.map_or(0, str::len));
|
||||
let mut out = String::with_capacity(html.len() + prefix.len() + meta.len());
|
||||
let mut pos = 0;
|
||||
|
||||
for (at, len, edit) in edits.into_iter().flatten() {
|
||||
|
|
@ -782,7 +799,7 @@ fn rewrite_index(html: &str, prefix: &str, oauth_client_id_meta: Option<&str>) -
|
|||
out.push_str(prefix);
|
||||
out.push_str("/\"");
|
||||
}
|
||||
IndexEdit::OAuthClientId(meta) => out.push_str(meta),
|
||||
IndexEdit::Meta(tag) => out.push_str(tag),
|
||||
}
|
||||
pos = at + len;
|
||||
}
|
||||
|
|
@ -790,10 +807,35 @@ fn rewrite_index(html: &str, prefix: &str, oauth_client_id_meta: Option<&str>) -
|
|||
out.into_bytes()
|
||||
}
|
||||
|
||||
fn oauth_client_id_meta(client_id: &str) -> String {
|
||||
let mut meta = String::with_capacity(OAUTH_CLIENT_ID.len() + client_id.len());
|
||||
meta.push_str("<meta name=\"oauth-client-id\" content=\"");
|
||||
for ch in client_id.chars() {
|
||||
fn meta_edit<'x>(
|
||||
html: &str,
|
||||
placeholder: &'static str,
|
||||
tag: Option<&'x str>,
|
||||
) -> Option<(usize, usize, IndexEdit<'x>)> {
|
||||
tag.and_then(|tag| {
|
||||
html.find(placeholder)
|
||||
.map(|at| (at, placeholder.len(), IndexEdit::Meta(tag)))
|
||||
})
|
||||
}
|
||||
|
||||
impl IndexMeta {
|
||||
fn new(client_id: Option<&str>, scopes: Option<&str>) -> Self {
|
||||
Self {
|
||||
client_id: client_id.map(|client_id| meta_tag(OAUTH_CLIENT_ID, client_id)),
|
||||
scopes: scopes.map(|scopes| meta_tag(OAUTH_SCOPES, scopes)),
|
||||
}
|
||||
}
|
||||
|
||||
fn len(&self) -> usize {
|
||||
self.client_id.as_ref().map_or(0, String::len) + self.scopes.as_ref().map_or(0, String::len)
|
||||
}
|
||||
}
|
||||
|
||||
fn meta_tag(placeholder: &str, content: &str) -> String {
|
||||
let open = placeholder.strip_suffix('"').unwrap_or(placeholder);
|
||||
let mut meta = String::with_capacity(placeholder.len() + content.len());
|
||||
meta.push_str(open);
|
||||
for ch in content.chars() {
|
||||
match ch {
|
||||
'&' => meta.push_str("&"),
|
||||
'"' => meta.push_str("""),
|
||||
|
|
@ -806,6 +848,24 @@ fn oauth_client_id_meta(client_id: &str) -> String {
|
|||
meta
|
||||
}
|
||||
|
||||
fn scope_list<'x>(scopes: impl Iterator<Item = &'x String>) -> Option<String> {
|
||||
let mut list = String::new();
|
||||
for scope in scopes.filter(|scope| is_scope_token(scope)) {
|
||||
if !list.is_empty() {
|
||||
list.push(' ');
|
||||
}
|
||||
list.push_str(scope);
|
||||
}
|
||||
(!list.is_empty()).then_some(list)
|
||||
}
|
||||
|
||||
fn is_scope_token(scope: &str) -> bool {
|
||||
!scope.is_empty()
|
||||
&& scope
|
||||
.bytes()
|
||||
.all(|byte| matches!(byte, 0x21 | 0x23..=0x5B | 0x5D..=0x7E))
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/common/src/manager/application/tests.rs"]
|
||||
|
|
|
|||
|
|
@ -370,32 +370,33 @@ async fn insert_safe_defaults(bp: &mut Bootstrap) -> trc::Result<()> {
|
|||
|
||||
if bp.registry.count_object(ObjectType::Role).await? == 0 {
|
||||
let permissions = DefaultPermissions::default();
|
||||
let mut roles = Vec::with_capacity(4);
|
||||
roles.push(Role {
|
||||
description: "User".into(),
|
||||
enabled_permissions: Map::new(permissions.user),
|
||||
..Default::default()
|
||||
});
|
||||
roles.push(Role {
|
||||
description: "Group".into(),
|
||||
enabled_permissions: Map::new(permissions.group),
|
||||
..Default::default()
|
||||
});
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
roles.push(Role {
|
||||
description: "Tenant Administrator".into(),
|
||||
enabled_permissions: Map::new(permissions.tenant),
|
||||
..Default::default()
|
||||
});
|
||||
// SPDX-SnippetEnd
|
||||
roles.push(Role {
|
||||
description: "System Administrator".into(),
|
||||
enabled_permissions: Map::new(permissions.superuser),
|
||||
..Default::default()
|
||||
});
|
||||
let roles = [
|
||||
Role {
|
||||
description: "User".into(),
|
||||
enabled_permissions: Map::new(permissions.user),
|
||||
..Default::default()
|
||||
},
|
||||
Role {
|
||||
description: "Group".into(),
|
||||
enabled_permissions: Map::new(permissions.group),
|
||||
..Default::default()
|
||||
},
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
Role {
|
||||
description: "Tenant Administrator".into(),
|
||||
enabled_permissions: Map::new(permissions.tenant),
|
||||
..Default::default()
|
||||
},
|
||||
// SPDX-SnippetEnd
|
||||
Role {
|
||||
description: "System Administrator".into(),
|
||||
enabled_permissions: Map::new(permissions.superuser),
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
let num_roles = roles.len();
|
||||
let mut role_ids = Vec::with_capacity(num_roles);
|
||||
|
||||
|
|
|
|||
|
|
@ -23,6 +23,7 @@ use std::{
|
|||
time::Duration,
|
||||
};
|
||||
use store::registry::write::RegistryWriteResult;
|
||||
use utils::error_chain;
|
||||
|
||||
pub type AcmeResult<T> = Result<T, AcmeError>;
|
||||
|
||||
|
|
@ -277,7 +278,7 @@ impl Display for Problem {
|
|||
impl Display for AcmeError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
AcmeError::Http(err) => write!(f, "HTTP error: {}", err),
|
||||
AcmeError::Http(err) => write!(f, "HTTP error: {}", error_chain(err)),
|
||||
AcmeError::HttpStatus(status) => write!(f, "HTTP error: {}", status),
|
||||
AcmeError::Json(err) => write!(f, "JSON error: {}", err),
|
||||
AcmeError::Dns(err) => write!(f, "DNS error: {}", err),
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ use crate::config::smtp::auth::{pem_or_base64_decode, rsa_key_parse};
|
|||
use dns_update::{DnsRecord, NamedDnsRecord};
|
||||
use encodify::{base64::STANDARD, pem};
|
||||
use jiff::{Timestamp, fmt::strtime, tz::TimeZone};
|
||||
use mail_auth::crypto::{Ed25519Key, MlDsa44Ed25519Key};
|
||||
use mail_auth::crypto::{Ed25519Key, MlDsa44Key};
|
||||
use mail_auth::dkim::generate::DkimKeyPair;
|
||||
use registry::schema::enums::DkimSignatureType;
|
||||
use registry::schema::structs::DkimSignature;
|
||||
|
|
@ -26,8 +26,8 @@ pub async fn generate_dkim_private_key(
|
|||
DkimSignatureType::Dkim1Ed25519Sha256 | DkimSignatureType::Dkim2Ed25519Sha256 => {
|
||||
DkimKeyPair::generate_ed25519().map(|key| (key, "PRIVATE KEY"))
|
||||
}
|
||||
DkimSignatureType::Dkim2MlDsa44Ed25519Sha512 => {
|
||||
DkimKeyPair::generate_mldsa44_ed25519().map(|key| (key, "PRIVATE KEY"))
|
||||
DkimSignatureType::Dkim2MlDsa44 => {
|
||||
DkimKeyPair::generate_mldsa44().map(|key| (key, "PRIVATE KEY"))
|
||||
}
|
||||
})
|
||||
.await
|
||||
|
|
@ -70,16 +70,14 @@ pub async fn generate_dkim_public_key(key: &DkimSignature) -> trc::Result<String
|
|||
.reason(err)
|
||||
})
|
||||
}
|
||||
DkimSignature::Dkim2MlDsa44Ed25519Sha512(_) => {
|
||||
MlDsa44Ed25519Key::from_pkcs8_der(&decode_private_key(&pem)?)
|
||||
.and_then(|pk| pk.public_key())
|
||||
.map(|pk| STANDARD.encode(pk))
|
||||
.map_err(|err| {
|
||||
trc::EventType::Dkim(trc::DkimEvent::BuildError)
|
||||
.into_err()
|
||||
.reason(err)
|
||||
})
|
||||
}
|
||||
DkimSignature::Dkim2MlDsa44(_) => MlDsa44Key::from_pkcs8_der(&decode_private_key(&pem)?)
|
||||
.and_then(|pk| pk.public_key())
|
||||
.map(|pk| STANDARD.encode(pk))
|
||||
.map_err(|err| {
|
||||
trc::EventType::Dkim(trc::DkimEvent::BuildError)
|
||||
.into_err()
|
||||
.reason(err)
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -114,9 +112,9 @@ pub async fn generate_dkim_dns_record(
|
|||
&sign.selector,
|
||||
format!("v=DKIM1; k=rsa; h=sha256; p={public_key}"),
|
||||
),
|
||||
DkimSignature::Dkim2MlDsa44Ed25519Sha512(sign) => (
|
||||
DkimSignature::Dkim2MlDsa44(sign) => (
|
||||
&sign.selector,
|
||||
format!("v=DKIM1; k=mldsa44-ed25519-sha512; p={public_key}"),
|
||||
format!("v=DKIM1; k=mldsa44; p={public_key}"),
|
||||
),
|
||||
};
|
||||
|
||||
|
|
@ -133,8 +131,8 @@ pub fn generate_dkim_dns_record_name(key: &DkimSignature, domain: &str) -> Strin
|
|||
/// Generate a DKIM selector from a template string.
|
||||
///
|
||||
/// Supported variables:
|
||||
/// - `{algorithm}`: signing algorithm in lowercase (`rsa`, `ed25519`, `mldsa44-ed25519`)
|
||||
/// - `{hash}`: hash algorithm (`sha256`, `sha512`)
|
||||
/// - `{algorithm}`: signing algorithm in lowercase (`rsa`, `ed25519`, `mldsa44`)
|
||||
/// - `{hash}`: hash algorithm (`sha256`, or `none` for ML-DSA-44)
|
||||
/// - `{version}`: DKIM version number (`1`, `2`)
|
||||
/// - `{date-<fmt>}`: current UTC date formatted with strftime specifiers (e.g. `{date-%Y%m%d}`)
|
||||
/// - `{epoch}`: current UTC unix timestamp
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ impl<T: AsRef<str>> IsMixedCharset for T {
|
|||
let mut set: Option<AugmentedScriptSet> = None;
|
||||
|
||||
for ch in self.as_ref().chars() {
|
||||
if !ch.is_ascii() {
|
||||
if !ch.is_ascii() && ch.is_alphabetic() {
|
||||
set.get_or_insert_default().intersect_with(ch.into());
|
||||
}
|
||||
}
|
||||
|
|
@ -68,3 +68,8 @@ impl<T: AsRef<str>> IsMixedCharset for T {
|
|||
set.is_some_and(|set| set.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/common/src/scripts/tests.rs"]
|
||||
mod tests;
|
||||
|
|
|
|||
|
|
@ -4,199 +4,209 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::auth::EncryptionKeys;
|
||||
use crypto::{
|
||||
EcdhWrapParameters, EncryptError, EncryptOptions, Encrypted, HeaderProtection, KeyError,
|
||||
ParsedKeys, RecipientSet,
|
||||
};
|
||||
use encodify::base64::LENIENT;
|
||||
use registry::schema::structs::PublicKey;
|
||||
use sequoia_openpgp::{Cert, parse::Parse, policy::StandardPolicy, types::KeyFlags};
|
||||
use std::{borrow::Cow, str::SplitInclusive};
|
||||
use mail_parser::Message;
|
||||
use registry::schema::{
|
||||
enums::HeaderProtection as RegistryHeaderProtection,
|
||||
structs::{EncryptionSettings, PublicKey},
|
||||
};
|
||||
use tokio::runtime::{Handle, RuntimeFlavor};
|
||||
use utils::cache::CacheItemWeight;
|
||||
|
||||
const P: StandardPolicy<'static> = StandardPolicy::new();
|
||||
const ENCRYPT_INLINE_MAX: usize = 512 * 1024;
|
||||
|
||||
const ARMOR_BEGIN: &str = "-----BEGIN ";
|
||||
const ARMOR_END: &str = "-----END";
|
||||
const ARMOR_DASHES: &str = "-----";
|
||||
#[derive(Debug)]
|
||||
pub struct AccountEncryption {
|
||||
pub keys: EncryptionKeys,
|
||||
pub options: EncryptOptions,
|
||||
pub train_spam: bool,
|
||||
pub encrypt_on_append: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum EncryptionKeys {
|
||||
Usable {
|
||||
recipients: RecipientSet,
|
||||
expires_at: Option<u64>,
|
||||
},
|
||||
Unusable(UnusableReason),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EncryptionMethod {
|
||||
PGP,
|
||||
SMIME,
|
||||
pub enum UnusableReason {
|
||||
KeyNotFound,
|
||||
Invalid(KeyError),
|
||||
}
|
||||
|
||||
pub struct EncryptionParams {
|
||||
pub certs: EncryptionKeys,
|
||||
pub method: EncryptionMethod,
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SkipReason {
|
||||
Expired,
|
||||
Unusable(UnusableReason),
|
||||
}
|
||||
|
||||
pub fn parse_public_key(pk: &PublicKey) -> Result<Option<EncryptionParams>, Cow<'static, str>> {
|
||||
let mut method = None;
|
||||
let mut certs: Vec<Box<[u8]>> = Vec::new();
|
||||
let mut has_usable_pgp_key = false;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EncryptFailure {
|
||||
Skipped(SkipReason),
|
||||
Error(EncryptError),
|
||||
}
|
||||
|
||||
for block in ArmoredBlocks::new(&pk.key) {
|
||||
let block = block?;
|
||||
if contains_ignore_ascii_case(block.label, "PRIVATE") {
|
||||
return Err("Private keys cannot be used as public keys".into());
|
||||
pub trait RecipientEncrypt {
|
||||
fn encrypt_on_runtime(
|
||||
&self,
|
||||
message: &Message<'_>,
|
||||
options: &EncryptOptions,
|
||||
) -> Result<Encrypted, EncryptError>;
|
||||
}
|
||||
|
||||
pub trait PublicKeyParse {
|
||||
fn parse_keys(&self, now: u64) -> Result<ParsedKeys, KeyError>;
|
||||
}
|
||||
|
||||
pub trait ToCrypto {
|
||||
type Output;
|
||||
|
||||
fn to_crypto(self) -> Self::Output;
|
||||
}
|
||||
|
||||
impl AccountEncryption {
|
||||
pub fn build(settings: &EncryptionSettings, public_key: Option<&PublicKey>, now: u64) -> Self {
|
||||
let mut options = EncryptOptions {
|
||||
header_protection: settings.header_protection.to_crypto(),
|
||||
..Default::default()
|
||||
};
|
||||
let keys = match public_key {
|
||||
Some(public_key) => match public_key.parse_keys(now).map_err(UnusableReason::Invalid) {
|
||||
Ok(parsed) => {
|
||||
options.profile = parsed
|
||||
.set
|
||||
.inferred_profile(public_key.authenticated_encryption);
|
||||
if !public_key.strict_key_wrap_encoding {
|
||||
options.ecdh_wrap_parameters = EcdhWrapParameters::Null;
|
||||
}
|
||||
EncryptionKeys::Usable {
|
||||
recipients: parsed.set,
|
||||
expires_at: parsed.expires_at,
|
||||
}
|
||||
}
|
||||
Err(reason) => EncryptionKeys::Unusable(reason),
|
||||
},
|
||||
None => EncryptionKeys::Unusable(UnusableReason::KeyNotFound),
|
||||
};
|
||||
AccountEncryption {
|
||||
keys,
|
||||
options,
|
||||
train_spam: settings.allow_spam_training,
|
||||
encrypt_on_append: settings.encrypt_on_append,
|
||||
}
|
||||
let block_method = if contains_ignore_ascii_case(block.label, "CERTIFICATE") {
|
||||
EncryptionMethod::SMIME
|
||||
} else if contains_ignore_ascii_case(block.label, "PGP") {
|
||||
EncryptionMethod::PGP
|
||||
}
|
||||
|
||||
pub fn recipients(&self, now: u64) -> Result<&RecipientSet, SkipReason> {
|
||||
match &self.keys {
|
||||
EncryptionKeys::Usable {
|
||||
recipients,
|
||||
expires_at,
|
||||
} => {
|
||||
if expires_at.is_none_or(|expires_at| expires_at > now) {
|
||||
Ok(recipients)
|
||||
} else {
|
||||
Err(SkipReason::Expired)
|
||||
}
|
||||
}
|
||||
EncryptionKeys::Unusable(UnusableReason::Invalid(KeyError::Expired)) => {
|
||||
Err(SkipReason::Expired)
|
||||
}
|
||||
EncryptionKeys::Unusable(reason) => Err(SkipReason::Unusable(*reason)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn encrypt(&self, message: &Message<'_>, now: u64) -> Result<Encrypted, EncryptFailure> {
|
||||
self.recipients(now)
|
||||
.map_err(EncryptFailure::Skipped)?
|
||||
.encrypt_on_runtime(message, &self.options)
|
||||
.map_err(EncryptFailure::Error)
|
||||
}
|
||||
}
|
||||
|
||||
impl RecipientEncrypt for RecipientSet {
|
||||
fn encrypt_on_runtime(
|
||||
&self,
|
||||
message: &Message<'_>,
|
||||
options: &EncryptOptions,
|
||||
) -> Result<Encrypted, EncryptError> {
|
||||
if message.raw().len() >= ENCRYPT_INLINE_MAX
|
||||
&& matches!(
|
||||
Handle::try_current().map(|handle| handle.runtime_flavor()),
|
||||
Ok(RuntimeFlavor::MultiThread)
|
||||
)
|
||||
{
|
||||
tokio::task::block_in_place(|| self.encrypt(message, options))
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
match method {
|
||||
Some(method) if method != block_method => {
|
||||
return Err("Cannot mix OpenPGP and S/MIME certificates".into());
|
||||
}
|
||||
_ => method = Some(block_method),
|
||||
}
|
||||
|
||||
match block_method {
|
||||
EncryptionMethod::PGP => {
|
||||
let cert = Cert::from_bytes(block.armored.as_bytes())
|
||||
.map_err(|err| format!("Failed to decode OpenPGP public key: {err}"))?;
|
||||
if cert.is_tsk() {
|
||||
return Err("Private keys cannot be used as public keys".into());
|
||||
}
|
||||
has_usable_pgp_key |= has_pgp_keys(&cert);
|
||||
certs.push(block.armored.as_bytes().into());
|
||||
}
|
||||
EncryptionMethod::SMIME => {
|
||||
let cert = LENIENT
|
||||
.decode(block.body)
|
||||
.map_err(|_| Cow::from("Failed to decode base64 certificate."))?;
|
||||
let is_complete = rasn::der::decode_with_remainder::<rasn_pkix::Certificate>(&cert)
|
||||
.map_err(|err| format!("Failed to decode X509 certificate: {err}"))?
|
||||
.1
|
||||
.is_empty();
|
||||
if !is_complete {
|
||||
return Err("Unexpected data after X509 certificate".into());
|
||||
}
|
||||
certs.push(cert.into_boxed_slice());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match method {
|
||||
Some(EncryptionMethod::PGP) if !has_usable_pgp_key => {
|
||||
Err("Could not find any suitable keys in OpenPGP public key".into())
|
||||
}
|
||||
Some(method) => Ok(Some(EncryptionParams {
|
||||
method,
|
||||
certs: certs.into_boxed_slice(),
|
||||
})),
|
||||
None if pk.key.trim().is_empty() => Ok(None),
|
||||
None => Err("No OpenPGP public key or X.509 certificate found".into()),
|
||||
}
|
||||
}
|
||||
|
||||
struct ArmoredBlock<'x> {
|
||||
label: &'x str,
|
||||
armored: &'x str,
|
||||
body: &'x str,
|
||||
}
|
||||
|
||||
struct ArmoredBlocks<'x> {
|
||||
text: &'x str,
|
||||
lines: SplitInclusive<'x, char>,
|
||||
offset: usize,
|
||||
}
|
||||
|
||||
impl<'x> ArmoredBlocks<'x> {
|
||||
fn new(text: &'x str) -> Self {
|
||||
ArmoredBlocks {
|
||||
text,
|
||||
lines: text.split_inclusive('\n'),
|
||||
offset: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn next_line(&mut self) -> Option<(usize, &'x str)> {
|
||||
let line = self.lines.next()?;
|
||||
let start = self.offset;
|
||||
self.offset += line.len();
|
||||
Some((start, line))
|
||||
}
|
||||
|
||||
fn fail(
|
||||
&mut self,
|
||||
reason: &'static str,
|
||||
) -> Option<Result<ArmoredBlock<'x>, Cow<'static, str>>> {
|
||||
self.lines = "".split_inclusive('\n');
|
||||
Some(Err(reason.into()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<'x> Iterator for ArmoredBlocks<'x> {
|
||||
type Item = Result<ArmoredBlock<'x>, Cow<'static, str>>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
let (block_start, label) = loop {
|
||||
let (line_start, line) = self.next_line()?;
|
||||
let begin = line.trim();
|
||||
if begin.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(label) = begin
|
||||
.strip_prefix(ARMOR_BEGIN)
|
||||
.and_then(|label| label.strip_suffix(ARMOR_DASHES))
|
||||
.filter(|label| !label.is_empty())
|
||||
else {
|
||||
return self.fail("Unexpected text outside of a PEM or OpenPGP armor block");
|
||||
};
|
||||
break (line_start + line.len() - line.trim_start().len(), label);
|
||||
};
|
||||
let body_start = self.offset;
|
||||
|
||||
loop {
|
||||
let Some((line_start, line)) = self.next_line() else {
|
||||
return self.fail("PEM or OpenPGP armor block is missing its END line");
|
||||
};
|
||||
let line = line.trim();
|
||||
if let Some(end_label) = line.strip_prefix(ARMOR_END) {
|
||||
if end_label
|
||||
.strip_prefix(' ')
|
||||
.and_then(|end_label| end_label.strip_suffix(ARMOR_DASHES))
|
||||
!= Some(label)
|
||||
{
|
||||
return self
|
||||
.fail("PEM or OpenPGP armor END line does not match its BEGIN line");
|
||||
}
|
||||
return match (
|
||||
self.text.get(block_start..self.offset),
|
||||
self.text.get(body_start..line_start),
|
||||
) {
|
||||
(Some(armored), Some(body)) => Some(Ok(ArmoredBlock {
|
||||
label,
|
||||
armored,
|
||||
body,
|
||||
})),
|
||||
_ => self.fail("Invalid PEM or OpenPGP armor block"),
|
||||
};
|
||||
} else if line.starts_with(ARMOR_BEGIN) {
|
||||
return self.fail("PEM or OpenPGP armor block is missing its END line");
|
||||
}
|
||||
self.encrypt(message, options)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
|
||||
haystack
|
||||
.as_bytes()
|
||||
.windows(needle.len())
|
||||
.any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
|
||||
impl UnusableReason {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
UnusableReason::KeyNotFound => "KeyNotFound",
|
||||
UnusableReason::Invalid(err) => err.as_str(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_pgp_keys(cert: &Cert) -> bool {
|
||||
cert.keys()
|
||||
.with_policy(&P, None)
|
||||
.supported()
|
||||
.alive()
|
||||
.revoked(false)
|
||||
.key_flags(KeyFlags::empty().set_transport_encryption())
|
||||
.next()
|
||||
.is_some()
|
||||
impl SkipReason {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
SkipReason::Expired => "Expired",
|
||||
SkipReason::Unusable(reason) => reason.as_str(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CacheItemWeight for AccountEncryption {
|
||||
fn weight(&self) -> u64 {
|
||||
(size_of::<AccountEncryption>()
|
||||
+ match &self.keys {
|
||||
EncryptionKeys::Usable { recipients, .. } => recipients.heap_size(),
|
||||
EncryptionKeys::Unusable(_) => 0,
|
||||
}) as u64
|
||||
}
|
||||
}
|
||||
|
||||
impl PublicKeyParse for PublicKey {
|
||||
fn parse_keys(&self, now: u64) -> Result<ParsedKeys, KeyError> {
|
||||
parse_key_text(&self.key, now)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_key_text(key: &str, now: u64) -> Result<ParsedKeys, KeyError> {
|
||||
let key = key.trim_ascii();
|
||||
if !key.starts_with("-----")
|
||||
&& let Ok(binary) = LENIENT.decode(key.as_bytes())
|
||||
&& !binary.is_empty()
|
||||
{
|
||||
crypto::parse_public_keys(&binary, now)
|
||||
} else {
|
||||
crypto::parse_public_keys(key.as_bytes(), now)
|
||||
}
|
||||
}
|
||||
|
||||
impl ToCrypto for RegistryHeaderProtection {
|
||||
type Output = HeaderProtection;
|
||||
|
||||
fn to_crypto(self) -> HeaderProtection {
|
||||
match self {
|
||||
RegistryHeaderProtection::None => HeaderProtection::None,
|
||||
RegistryHeaderProtection::NoConfidentiality | RegistryHeaderProtection::Baseline => {
|
||||
HeaderProtection::Full
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
|
|
|
|||
|
|
@ -86,6 +86,16 @@ persisted_metrics!(
|
|||
SmtpDkim2Fail,
|
||||
SmtpDmarcPass,
|
||||
SmtpDmarcFail,
|
||||
EncryptionAtRestEncrypted,
|
||||
EncryptionEncryptionSkipped,
|
||||
EncryptionGatewayEncrypted,
|
||||
EncryptionGatewayPlaintext,
|
||||
EncryptionGatewayBounced,
|
||||
EncryptionKeyLookup,
|
||||
EncryptionKeyHarvested,
|
||||
EncryptionKeyChange,
|
||||
EncryptionCrlFetchFailed,
|
||||
EncryptionDnssecBogus,
|
||||
]
|
||||
);
|
||||
|
||||
|
|
@ -115,6 +125,7 @@ persisted_metrics!(
|
|||
DeliveryTotalTime,
|
||||
DeliveryAttemptTime,
|
||||
DnsLookupTime,
|
||||
EncryptionKeyLookupTime,
|
||||
StoreDataReadTime,
|
||||
StoreDataWriteTime,
|
||||
StoreBlobReadTime,
|
||||
|
|
|
|||
|
|
@ -228,6 +228,20 @@ fn counter_rate(metric: MetricType, interval: Interval) -> f64 {
|
|||
MetricType::SmtpDmarcPass => 440.0,
|
||||
MetricType::SmtpDmarcFail if incident => 280.0,
|
||||
MetricType::SmtpDmarcFail => 60.0,
|
||||
MetricType::EncryptionAtRestEncrypted => 180.0,
|
||||
MetricType::EncryptionEncryptionSkipped if incident => 20.0,
|
||||
MetricType::EncryptionEncryptionSkipped => 1.5,
|
||||
MetricType::EncryptionGatewayEncrypted => 95.0,
|
||||
MetricType::EncryptionGatewayPlaintext => 160.0,
|
||||
MetricType::EncryptionGatewayBounced if incident => 12.0,
|
||||
MetricType::EncryptionGatewayBounced => 0.6,
|
||||
MetricType::EncryptionKeyLookup => 70.0,
|
||||
MetricType::EncryptionKeyHarvested => 9.0,
|
||||
MetricType::EncryptionKeyChange => 0.4,
|
||||
MetricType::EncryptionCrlFetchFailed if incident => 6.0,
|
||||
MetricType::EncryptionCrlFetchFailed => 0.2,
|
||||
MetricType::EncryptionDnssecBogus if incident => 4.0,
|
||||
MetricType::EncryptionDnssecBogus => 0.1,
|
||||
_ => 10.0,
|
||||
}
|
||||
}
|
||||
|
|
@ -240,6 +254,7 @@ fn histogram_profile(metric: MetricType, interval: Interval) -> (f64, f64) {
|
|||
MetricType::DeliveryTotalTime => (450.0, 2_400.0 * slowdown),
|
||||
MetricType::DeliveryAttemptTime => (480.0, 750.0 * slowdown),
|
||||
MetricType::DnsLookupTime => (3_000.0, 18.0),
|
||||
MetricType::EncryptionKeyLookupTime => (70.0, 140.0 * slowdown),
|
||||
MetricType::StoreDataReadTime => (90_000.0, 1.6 * slowdown),
|
||||
MetricType::StoreDataWriteTime => (12_000.0, 4.5 * slowdown),
|
||||
MetricType::StoreBlobReadTime => (4_000.0, 6.0 * slowdown),
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "coordinator"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
21
crates/crypto/Cargo.toml
Normal file
21
crates/crypto/Cargo.toml
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
[package]
|
||||
name = "crypto"
|
||||
description = "OpenPGP and S/MIME encryption, key validation and signature verification"
|
||||
version = "1.0.2"
|
||||
edition = "2024"
|
||||
license = "AGPL-3.0-only OR LicenseRef-SEL"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
aes = "0.9.3"
|
||||
aws-lc-rs = "1.18.2"
|
||||
ed448-goldilocks = "0.9"
|
||||
encodify = "1.0"
|
||||
hashify = "0.3"
|
||||
mail-parser = { version = "1.0", features = ["full_encoding"] }
|
||||
memchr = "2"
|
||||
shake = { version = "0.1", default-features = false }
|
||||
zeroize = "1.9"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
BIN
crates/crypto/resources/email-anchors.bin
Normal file
BIN
crates/crypto/resources/email-anchors.bin
Normal file
Binary file not shown.
140
crates/crypto/src/backend/aes.rs
Normal file
140
crates/crypto/src/backend/aes.rs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aes::{
|
||||
Aes128, Aes192, Aes256,
|
||||
cipher::{Array, BlockCipherEncrypt, KeyInit},
|
||||
};
|
||||
use aws_lc_rs::{
|
||||
cipher::{AES_128, AES_192, AES_256, EncryptingKey, EncryptionContext, UnboundCipherKey},
|
||||
iv::FixedLength,
|
||||
};
|
||||
|
||||
use super::PrimitiveError;
|
||||
|
||||
pub(crate) const BLOCK_LEN: usize = 16;
|
||||
pub(crate) const KEY_WRAP_OVERHEAD: usize = 8;
|
||||
const KEY_WRAP_IV: u64 = 0xA6A6_A6A6_A6A6_A6A6;
|
||||
const KEY_WRAP_ROUNDS: u64 = 6;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum AesKeySize {
|
||||
Aes128,
|
||||
Aes192,
|
||||
Aes256,
|
||||
}
|
||||
|
||||
impl AesKeySize {
|
||||
pub const fn key_len(self) -> usize {
|
||||
match self {
|
||||
AesKeySize::Aes128 => 16,
|
||||
AesKeySize::Aes192 => 24,
|
||||
AesKeySize::Aes256 => 32,
|
||||
}
|
||||
}
|
||||
|
||||
fn aws_algorithm(self) -> &'static aws_lc_rs::cipher::Algorithm {
|
||||
match self {
|
||||
AesKeySize::Aes128 => &AES_128,
|
||||
AesKeySize::Aes192 => &AES_192,
|
||||
AesKeySize::Aes256 => &AES_256,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn from_key_len(len: usize) -> Option<Self> {
|
||||
match len {
|
||||
16 => Some(AesKeySize::Aes128),
|
||||
24 => Some(AesKeySize::Aes192),
|
||||
32 => Some(AesKeySize::Aes256),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum AesCipher {
|
||||
Aes128(Aes128),
|
||||
Aes192(Aes192),
|
||||
Aes256(Aes256),
|
||||
}
|
||||
|
||||
macro_rules! with_cipher {
|
||||
($self:expr, $c:ident => $body:expr) => {
|
||||
match $self {
|
||||
AesCipher::Aes128($c) => $body,
|
||||
AesCipher::Aes192($c) => $body,
|
||||
AesCipher::Aes256($c) => $body,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl AesCipher {
|
||||
pub(crate) fn new(key: &[u8]) -> Result<Self, PrimitiveError> {
|
||||
match AesKeySize::from_key_len(key.len()) {
|
||||
Some(AesKeySize::Aes128) => Aes128::new_from_slice(key).map(AesCipher::Aes128),
|
||||
Some(AesKeySize::Aes192) => Aes192::new_from_slice(key).map(AesCipher::Aes192),
|
||||
Some(AesKeySize::Aes256) => Aes256::new_from_slice(key).map(AesCipher::Aes256),
|
||||
None => return Err(PrimitiveError::InvalidKeyLength),
|
||||
}
|
||||
.map_err(|_| PrimitiveError::InvalidKeyLength)
|
||||
}
|
||||
|
||||
pub(crate) fn encrypt_block(&self, block: &mut [u8; BLOCK_LEN]) {
|
||||
with_cipher!(self, c => c.encrypt_block(block.into()))
|
||||
}
|
||||
|
||||
pub(crate) fn encrypt_blocks(&self, data: &mut [u8]) {
|
||||
let (blocks, _) = Array::slice_as_chunks_mut(data);
|
||||
with_cipher!(self, c => c.encrypt_blocks(blocks))
|
||||
}
|
||||
|
||||
pub(crate) fn wrap_len(input_len: usize) -> usize {
|
||||
input_len + KEY_WRAP_OVERHEAD
|
||||
}
|
||||
|
||||
pub(crate) fn wrap(&self, input: &[u8], out: &mut [u8]) -> Result<(), PrimitiveError> {
|
||||
if input.len() < 16
|
||||
|| !input.len().is_multiple_of(8)
|
||||
|| out.len() != Self::wrap_len(input.len())
|
||||
{
|
||||
return Err(PrimitiveError::InvalidLength);
|
||||
}
|
||||
let (a_out, r) = out.split_at_mut(KEY_WRAP_OVERHEAD);
|
||||
r.copy_from_slice(input);
|
||||
let (r, _) = r.as_chunks_mut::<8>();
|
||||
let n = r.len() as u64;
|
||||
let mut a = KEY_WRAP_IV;
|
||||
for j in 0..KEY_WRAP_ROUNDS {
|
||||
for (i, r) in (1..).zip(r.iter_mut()) {
|
||||
let mut block =
|
||||
((u128::from(a) << 64) | u128::from(u64::from_be_bytes(*r))).to_be_bytes();
|
||||
self.encrypt_block(&mut block);
|
||||
let b = u128::from_be_bytes(block);
|
||||
a = ((b >> 64) as u64) ^ (n * j + i);
|
||||
*r = (b as u64).to_be_bytes();
|
||||
}
|
||||
}
|
||||
a_out.copy_from_slice(&a.to_be_bytes());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn unbound_key(key: &[u8]) -> Result<UnboundCipherKey, PrimitiveError> {
|
||||
let size = AesKeySize::from_key_len(key.len()).ok_or(PrimitiveError::InvalidKeyLength)?;
|
||||
UnboundCipherKey::new(size.aws_algorithm(), key).map_err(|_| PrimitiveError::InvalidKeyLength)
|
||||
}
|
||||
|
||||
pub(crate) fn cfb_encrypt_zero_iv(key: &[u8], data: &mut [u8]) -> Result<(), PrimitiveError> {
|
||||
EncryptingKey::cfb128(unbound_key(key)?)
|
||||
.and_then(|key| {
|
||||
key.less_safe_encrypt(
|
||||
data,
|
||||
EncryptionContext::Iv128(FixedLength::from([0u8; BLOCK_LEN])),
|
||||
)
|
||||
})
|
||||
.map(|_| ())
|
||||
.map_err(|_| PrimitiveError::Encryption)
|
||||
}
|
||||
189
crates/crypto/src/backend/agree.rs
Normal file
189
crates/crypto/src/backend/agree.rs
Normal file
|
|
@ -0,0 +1,189 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aws_lc_rs::agreement::{
|
||||
self, ECDH_P256, ECDH_P384, ECDH_P521, ParsedPublicKey, PrivateKey, UnparsedPublicKey, X25519,
|
||||
};
|
||||
use ed448_goldilocks::{Scalar, curve::MontgomeryPoint};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::{PrimitiveError, rng::Rng};
|
||||
|
||||
pub(crate) const MAX_PUBLIC_LEN: usize = 133;
|
||||
pub(crate) const MAX_SHARED_LEN: usize = 66;
|
||||
const X448_LEN: usize = 56;
|
||||
const MAX_SCALAR_ATTEMPTS: usize = 16;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Curve {
|
||||
P256,
|
||||
P384,
|
||||
P521,
|
||||
X25519,
|
||||
X448,
|
||||
}
|
||||
|
||||
impl Curve {
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
Curve::P256 => "P-256",
|
||||
Curve::P384 => "P-384",
|
||||
Curve::P521 => "P-521",
|
||||
Curve::X25519 => "X25519",
|
||||
Curve::X448 => "X448",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Curve {
|
||||
pub const fn shared_len(self) -> usize {
|
||||
match self {
|
||||
Curve::P256 | Curve::X25519 => 32,
|
||||
Curve::P384 => 48,
|
||||
Curve::P521 => 66,
|
||||
Curve::X448 => X448_LEN,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn public_len(self) -> usize {
|
||||
match self {
|
||||
Curve::P256 => 65,
|
||||
Curve::P384 => 97,
|
||||
Curve::P521 => 133,
|
||||
Curve::X25519 => 32,
|
||||
Curve::X448 => X448_LEN,
|
||||
}
|
||||
}
|
||||
|
||||
const fn scalar_len(self) -> usize {
|
||||
match self {
|
||||
Curve::P521 => 66,
|
||||
_ => self.shared_len(),
|
||||
}
|
||||
}
|
||||
|
||||
fn aws_algorithm(self) -> Option<&'static agreement::Algorithm> {
|
||||
match self {
|
||||
Curve::P256 => Some(&ECDH_P256),
|
||||
Curve::P384 => Some(&ECDH_P384),
|
||||
Curve::P521 => Some(&ECDH_P521),
|
||||
Curve::X25519 => Some(&X25519),
|
||||
Curve::X448 => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_public(self, public: &[u8]) -> Result<(), PrimitiveError> {
|
||||
if public.len() != self.public_len() {
|
||||
return Err(PrimitiveError::InvalidPublicKey);
|
||||
}
|
||||
match self.aws_algorithm() {
|
||||
Some(alg) => ParsedPublicKey::try_from(UnparsedPublicKey::new(alg, public))
|
||||
.map(|_| ())
|
||||
.map_err(|_| PrimitiveError::InvalidPublicKey),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn ephemeral_agree(
|
||||
self,
|
||||
peer_public: &[u8],
|
||||
rng: &mut impl Rng,
|
||||
) -> Result<Agreement, PrimitiveError> {
|
||||
let mut agreement = Agreement {
|
||||
curve: self,
|
||||
public: [0u8; MAX_PUBLIC_LEN],
|
||||
shared: Zeroizing::new([0u8; MAX_SHARED_LEN]),
|
||||
};
|
||||
match self.aws_algorithm() {
|
||||
Some(alg) => {
|
||||
let private = self.random_private_key(alg, rng)?;
|
||||
let public = private
|
||||
.compute_public_key()
|
||||
.map_err(|_| PrimitiveError::KeyAgreement)?;
|
||||
agreement
|
||||
.public
|
||||
.get_mut(..self.public_len())
|
||||
.filter(|_| public.as_ref().len() == self.public_len())
|
||||
.ok_or(PrimitiveError::KeyAgreement)?
|
||||
.copy_from_slice(public.as_ref());
|
||||
let shared = agreement
|
||||
.shared
|
||||
.get_mut(..self.shared_len())
|
||||
.ok_or(PrimitiveError::KeyAgreement)?;
|
||||
agreement::agree(
|
||||
&private,
|
||||
UnparsedPublicKey::new(alg, peer_public),
|
||||
PrimitiveError::KeyAgreement,
|
||||
|z| {
|
||||
if z.len() == shared.len() {
|
||||
shared.copy_from_slice(z);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PrimitiveError::KeyAgreement)
|
||||
}
|
||||
},
|
||||
)?;
|
||||
}
|
||||
None => {
|
||||
let peer: [u8; X448_LEN] = peer_public
|
||||
.try_into()
|
||||
.map_err(|_| PrimitiveError::InvalidPublicKey)?;
|
||||
let mut secret = Zeroizing::new([0u8; X448_LEN]);
|
||||
rng.fill(secret.as_mut())?;
|
||||
secret[0] &= 252;
|
||||
secret[X448_LEN - 1] |= 128;
|
||||
let scalar = Scalar::from_bytes(*secret);
|
||||
let public = &MontgomeryPoint::generator() * &scalar;
|
||||
let shared = &MontgomeryPoint(peer) * &scalar;
|
||||
if shared.0.iter().all(|b| *b == 0) {
|
||||
return Err(PrimitiveError::KeyAgreement);
|
||||
}
|
||||
agreement.public[..X448_LEN].copy_from_slice(&public.0);
|
||||
agreement.shared[..X448_LEN].copy_from_slice(&shared.0);
|
||||
}
|
||||
}
|
||||
Ok(agreement)
|
||||
}
|
||||
|
||||
fn random_private_key(
|
||||
self,
|
||||
alg: &'static agreement::Algorithm,
|
||||
rng: &mut impl Rng,
|
||||
) -> Result<PrivateKey, PrimitiveError> {
|
||||
let mut scalar = Zeroizing::new([0u8; MAX_SHARED_LEN]);
|
||||
let scalar = scalar
|
||||
.get_mut(..self.scalar_len())
|
||||
.ok_or(PrimitiveError::KeyAgreement)?;
|
||||
for _ in 0..MAX_SCALAR_ATTEMPTS {
|
||||
rng.fill(scalar)?;
|
||||
if self == Curve::P521
|
||||
&& let Some(first) = scalar.first_mut()
|
||||
{
|
||||
*first &= 0x01;
|
||||
}
|
||||
if let Ok(key) = PrivateKey::from_private_key(alg, scalar) {
|
||||
return Ok(key);
|
||||
}
|
||||
}
|
||||
Err(PrimitiveError::KeyAgreement)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Agreement {
|
||||
curve: Curve,
|
||||
public: [u8; MAX_PUBLIC_LEN],
|
||||
shared: Zeroizing<[u8; MAX_SHARED_LEN]>,
|
||||
}
|
||||
|
||||
impl Agreement {
|
||||
pub(crate) fn public(&self) -> &[u8] {
|
||||
&self.public[..self.curve.public_len()]
|
||||
}
|
||||
|
||||
pub(crate) fn shared(&self) -> &[u8] {
|
||||
&self.shared[..self.curve.shared_len()]
|
||||
}
|
||||
}
|
||||
72
crates/crypto/src/backend/base64.rs
Normal file
72
crates/crypto/src/backend/base64.rs
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use encodify::base64::{Base64, LineEnding, STANDARD};
|
||||
|
||||
use crate::mime::Sink;
|
||||
|
||||
pub(crate) const MIME_LINE_BYTES: usize = 57;
|
||||
pub(crate) const ARMOR: Base64 = STANDARD.wrapped(64, LineEnding::CrLf);
|
||||
pub(crate) const MIME: Base64 = STANDARD.wrapped(76, LineEnding::CrLf);
|
||||
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
const B64_INVALID: u8 = 0xFF;
|
||||
const DECODE_GROUPS: usize = 512;
|
||||
|
||||
static B64_DECODE: [u8; 256] = {
|
||||
let mut table = [B64_INVALID; 256];
|
||||
let mut i = 0;
|
||||
while i < ALPHABET.len() {
|
||||
table[ALPHABET[i] as usize] = i as u8;
|
||||
i += 1;
|
||||
}
|
||||
table
|
||||
};
|
||||
|
||||
pub(crate) fn decoded_base64_len(input: &[u8]) -> usize {
|
||||
let data = memchr::memchr(b'=', input).map_or(input, |end| input.split_at(end).0);
|
||||
let sextets = data
|
||||
.iter()
|
||||
.filter(|b| B64_DECODE[usize::from(**b)] != B64_INVALID)
|
||||
.count();
|
||||
sextets / 4 * 3 + [0, 0, 1, 2][sextets % 4]
|
||||
}
|
||||
|
||||
pub(crate) fn decode_base64<S: Sink>(input: &[u8], out: &mut S) {
|
||||
let mut groups = [[0u8; 3]; DECODE_GROUPS];
|
||||
let mut filled = 0;
|
||||
let mut acc = 0u32;
|
||||
let mut count = 0;
|
||||
for byte in input {
|
||||
if *byte == b'=' {
|
||||
break;
|
||||
}
|
||||
let value = B64_DECODE[usize::from(*byte)];
|
||||
if value == B64_INVALID {
|
||||
continue;
|
||||
}
|
||||
acc = (acc << 6) | u32::from(value);
|
||||
count += 1;
|
||||
if count == 4 {
|
||||
let [_, a, b, c] = acc.to_be_bytes();
|
||||
if let Some(slot) = groups.get_mut(filled) {
|
||||
*slot = [a, b, c];
|
||||
filled += 1;
|
||||
}
|
||||
if filled == DECODE_GROUPS {
|
||||
out.put(groups.as_flattened());
|
||||
filled = 0;
|
||||
}
|
||||
acc = 0;
|
||||
count = 0;
|
||||
}
|
||||
}
|
||||
out.put(groups.get(..filled).unwrap_or_default().as_flattened());
|
||||
match count {
|
||||
2 => out.put(&[(acc >> 4) as u8]),
|
||||
3 => out.put(&[(acc >> 10) as u8, (acc >> 2) as u8]),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
124
crates/crypto/src/backend/crc24.rs
Normal file
124
crates/crypto/src/backend/crc24.rs
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
const GENERATOR: u32 = 0x186_4CFB;
|
||||
const POLY: u32 = 0x86_4CFB << 8;
|
||||
const INIT: u32 = 0xB7_04CE << 8;
|
||||
const DEGREE: u32 = 24;
|
||||
const LANES: usize = 4;
|
||||
const MIN_LANE_LEN: usize = 256;
|
||||
|
||||
static TABLES: [[u32; 256]; 8] = {
|
||||
let mut tables = [[0u32; 256]; 8];
|
||||
let mut byte = 0;
|
||||
while byte < 256 {
|
||||
let mut crc = (byte as u32) << 24;
|
||||
let mut bit = 0;
|
||||
while bit < 8 {
|
||||
crc = if crc & 0x8000_0000 != 0 {
|
||||
(crc << 1) ^ POLY
|
||||
} else {
|
||||
crc << 1
|
||||
};
|
||||
bit += 1;
|
||||
}
|
||||
tables[0][byte] = crc;
|
||||
byte += 1;
|
||||
}
|
||||
let mut slice = 1;
|
||||
while slice < 8 {
|
||||
let mut byte = 0;
|
||||
while byte < 256 {
|
||||
let previous = tables[slice - 1][byte];
|
||||
tables[slice][byte] = (previous << 8) ^ tables[0][(previous >> 24) as usize];
|
||||
byte += 1;
|
||||
}
|
||||
slice += 1;
|
||||
}
|
||||
tables
|
||||
};
|
||||
|
||||
#[inline(always)]
|
||||
fn step(crc: u32, block: &[u8; 8]) -> u32 {
|
||||
let [t0, t1, t2, t3, t4, t5, t6, t7] = &TABLES;
|
||||
let [a0, a1, a2, a3, a4, a5, a6, a7] = *block;
|
||||
let x = crc ^ u32::from_be_bytes([a0, a1, a2, a3]);
|
||||
t7[(x >> 24) as usize]
|
||||
^ t6[((x >> 16) & 0xFF) as usize]
|
||||
^ t5[((x >> 8) & 0xFF) as usize]
|
||||
^ t4[(x & 0xFF) as usize]
|
||||
^ t3[usize::from(a4)]
|
||||
^ t2[usize::from(a5)]
|
||||
^ t1[usize::from(a6)]
|
||||
^ t0[usize::from(a7)]
|
||||
}
|
||||
|
||||
fn update(mut crc: u32, data: &[u8]) -> u32 {
|
||||
let (blocks, tail) = data.as_chunks::<8>();
|
||||
for block in blocks {
|
||||
crc = step(crc, block);
|
||||
}
|
||||
for byte in tail {
|
||||
crc = (crc << 8) ^ TABLES[0][((crc >> 24) ^ u32::from(*byte)) as usize];
|
||||
}
|
||||
crc
|
||||
}
|
||||
|
||||
fn multiply_mod(mut a: u32, b: u32) -> u32 {
|
||||
let mut product = 0;
|
||||
for bit in 0..DEGREE {
|
||||
if b & (1 << bit) != 0 {
|
||||
product ^= a;
|
||||
}
|
||||
a <<= 1;
|
||||
if a & (1 << DEGREE) != 0 {
|
||||
a ^= GENERATOR;
|
||||
}
|
||||
}
|
||||
product
|
||||
}
|
||||
|
||||
fn zero_bytes_factor(mut len: usize) -> u32 {
|
||||
let mut factor = 1;
|
||||
let mut base = 1 << 8;
|
||||
while len > 0 {
|
||||
if len & 1 != 0 {
|
||||
factor = multiply_mod(factor, base);
|
||||
}
|
||||
base = multiply_mod(base, base);
|
||||
len >>= 1;
|
||||
}
|
||||
factor
|
||||
}
|
||||
|
||||
pub(crate) fn crc24(data: &[u8]) -> u32 {
|
||||
let lane_len = data.len() / LANES / 8 * 8;
|
||||
if lane_len < MIN_LANE_LEN {
|
||||
return update(INIT, data) >> 8;
|
||||
}
|
||||
let (striped, rest) = data.split_at(lane_len * LANES);
|
||||
let (lane0, striped) = striped.split_at(lane_len);
|
||||
let (lane1, striped) = striped.split_at(lane_len);
|
||||
let (lane2, lane3) = striped.split_at(lane_len);
|
||||
let mut crcs = [INIT, 0, 0, 0];
|
||||
for (((b0, b1), b2), b3) in lane0
|
||||
.as_chunks::<8>()
|
||||
.0
|
||||
.iter()
|
||||
.zip(lane1.as_chunks::<8>().0)
|
||||
.zip(lane2.as_chunks::<8>().0)
|
||||
.zip(lane3.as_chunks::<8>().0)
|
||||
{
|
||||
let [c0, c1, c2, c3] = crcs;
|
||||
crcs = [step(c0, b0), step(c1, b1), step(c2, b2), step(c3, b3)];
|
||||
}
|
||||
let factor = zero_bytes_factor(lane_len);
|
||||
let [c0, c1, c2, c3] = crcs;
|
||||
let combined = [c1, c2, c3]
|
||||
.into_iter()
|
||||
.fold(c0, |crc, lane| (multiply_mod(crc >> 8, factor) << 8) ^ lane);
|
||||
update(combined, rest) >> 8
|
||||
}
|
||||
62
crates/crypto/src/backend/ed448.rs
Normal file
62
crates/crypto/src/backend/ed448.rs
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use ed448_goldilocks::{
|
||||
Scalar,
|
||||
curve::edwards::{CompressedEdwardsY, ExtendedPoint},
|
||||
};
|
||||
use shake::{ExtendableOutput, Shake256, Update, XofReader};
|
||||
|
||||
use super::PrimitiveError;
|
||||
|
||||
pub(crate) const ED448_PUBLIC_LEN: usize = 57;
|
||||
pub(crate) const ED448_SIGNATURE_LEN: usize = 114;
|
||||
const DOM4_PREFIX: &[u8] = b"SigEd448\x00\x00";
|
||||
const SIGN_BIT_MASK: u8 = 0x7F;
|
||||
|
||||
fn decode_point(bytes: &[u8; ED448_PUBLIC_LEN]) -> Option<ExtendedPoint> {
|
||||
if bytes[ED448_PUBLIC_LEN - 1] & SIGN_BIT_MASK != 0 {
|
||||
return None;
|
||||
}
|
||||
let point = CompressedEdwardsY(*bytes).decompress()?;
|
||||
(point.compress().0 == *bytes).then_some(point)
|
||||
}
|
||||
|
||||
pub(crate) fn verify(
|
||||
public_key: &[u8],
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> Result<(), PrimitiveError> {
|
||||
let public_key: &[u8; ED448_PUBLIC_LEN] = public_key
|
||||
.try_into()
|
||||
.map_err(|_| PrimitiveError::InvalidPublicKey)?;
|
||||
let (r_bytes, s_bytes) = signature
|
||||
.split_first_chunk::<ED448_PUBLIC_LEN>()
|
||||
.ok_or(PrimitiveError::BadSignature)?;
|
||||
let s_bytes: [u8; ED448_PUBLIC_LEN] = s_bytes
|
||||
.try_into()
|
||||
.map_err(|_| PrimitiveError::BadSignature)?;
|
||||
let a = decode_point(public_key).ok_or(PrimitiveError::InvalidPublicKey)?;
|
||||
let r = decode_point(r_bytes).ok_or(PrimitiveError::BadSignature)?;
|
||||
let s = Scalar::from_canonical_bytes(s_bytes).ok_or(PrimitiveError::BadSignature)?;
|
||||
|
||||
let mut shake = Shake256::default();
|
||||
shake.update(DOM4_PREFIX);
|
||||
shake.update(r_bytes);
|
||||
shake.update(public_key);
|
||||
shake.update(message);
|
||||
let mut wide = [0u8; ED448_SIGNATURE_LEN];
|
||||
shake.finalize_xof().read(&mut wide);
|
||||
let k = Scalar::from_bytes_mod_order_wide(&wide);
|
||||
|
||||
let lhs = ExtendedPoint::generator().scalar_mul(&s);
|
||||
let rhs = r.add(&a.scalar_mul(&k));
|
||||
if lhs.add(&rhs.negate()).double().double() == ExtendedPoint::identity() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PrimitiveError::BadSignature)
|
||||
}
|
||||
}
|
||||
73
crates/crypto/src/backend/hash.rs
Normal file
73
crates/crypto/src/backend/hash.rs
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aws_lc_rs::digest::{self, Context, Digest};
|
||||
|
||||
use crate::mime::Sink;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum HashAlgorithm {
|
||||
Sha1,
|
||||
Sha224,
|
||||
Sha256,
|
||||
Sha384,
|
||||
Sha512,
|
||||
Sha3_256,
|
||||
Sha3_512,
|
||||
}
|
||||
|
||||
impl HashAlgorithm {
|
||||
pub(crate) fn algorithm(self) -> &'static digest::Algorithm {
|
||||
match self {
|
||||
HashAlgorithm::Sha1 => &digest::SHA1_FOR_LEGACY_USE_ONLY,
|
||||
HashAlgorithm::Sha224 => &digest::SHA224,
|
||||
HashAlgorithm::Sha256 => &digest::SHA256,
|
||||
HashAlgorithm::Sha384 => &digest::SHA384,
|
||||
HashAlgorithm::Sha512 => &digest::SHA512,
|
||||
HashAlgorithm::Sha3_256 => &digest::SHA3_256,
|
||||
HashAlgorithm::Sha3_512 => &digest::SHA3_512,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn output_len(self) -> usize {
|
||||
match self {
|
||||
HashAlgorithm::Sha1 => 20,
|
||||
HashAlgorithm::Sha224 => 28,
|
||||
HashAlgorithm::Sha256 | HashAlgorithm::Sha3_256 => 32,
|
||||
HashAlgorithm::Sha384 => 48,
|
||||
HashAlgorithm::Sha512 | HashAlgorithm::Sha3_512 => 64,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn digest(self, data: &[u8]) -> Digest {
|
||||
digest::digest(self.algorithm(), data)
|
||||
}
|
||||
|
||||
pub(crate) fn hasher(self) -> Hasher {
|
||||
Hasher(Context::new(self.algorithm()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct Hasher(Context);
|
||||
|
||||
impl Hasher {
|
||||
#[inline]
|
||||
pub(crate) fn update(&mut self, data: &[u8]) {
|
||||
self.0.update(data);
|
||||
}
|
||||
|
||||
pub(crate) fn finish(self) -> Digest {
|
||||
self.0.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink for Hasher {
|
||||
#[inline]
|
||||
fn put(&mut self, data: &[u8]) {
|
||||
self.0.update(data);
|
||||
}
|
||||
}
|
||||
116
crates/crypto/src/backend/kdf.rs
Normal file
116
crates/crypto/src/backend/kdf.rs
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aws_lc_rs::hmac::{self, Context, Key};
|
||||
|
||||
use super::{PrimitiveError, hash::HashAlgorithm};
|
||||
|
||||
const MAX_HASH_LEN: usize = 64;
|
||||
const MAX_HKDF_BLOCKS: usize = 255;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum HkdfHash {
|
||||
Sha256,
|
||||
Sha512,
|
||||
}
|
||||
|
||||
impl HkdfHash {
|
||||
fn algorithm(self) -> hmac::Algorithm {
|
||||
match self {
|
||||
HkdfHash::Sha256 => hmac::HMAC_SHA256,
|
||||
HkdfHash::Sha512 => hmac::HMAC_SHA512,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn derive(
|
||||
self,
|
||||
salt: &[u8],
|
||||
ikm: &[&[u8]],
|
||||
info: &[&[u8]],
|
||||
out: &mut [u8],
|
||||
) -> Result<(), PrimitiveError> {
|
||||
let algorithm = self.algorithm();
|
||||
let hash_len = algorithm.digest_algorithm().output_len();
|
||||
if out.len() > MAX_HKDF_BLOCKS * hash_len {
|
||||
return Err(PrimitiveError::InvalidLength);
|
||||
}
|
||||
let zero_salt = [0u8; MAX_HASH_LEN];
|
||||
let salt = if salt.is_empty() {
|
||||
zero_salt
|
||||
.get(..hash_len)
|
||||
.ok_or(PrimitiveError::InvalidLength)?
|
||||
} else {
|
||||
salt
|
||||
};
|
||||
let mut extract = Context::with_key(&Key::new(algorithm, salt));
|
||||
for part in ikm {
|
||||
extract.update(part);
|
||||
}
|
||||
let prk = Key::new(algorithm, extract.sign().as_ref());
|
||||
let mut previous = None;
|
||||
for (counter, block) in (1u8..).zip(out.chunks_mut(hash_len)) {
|
||||
let mut expand = Context::with_key(&prk);
|
||||
if let Some(previous) = &previous {
|
||||
expand.update(AsRef::<[u8]>::as_ref(previous));
|
||||
}
|
||||
for part in info {
|
||||
expand.update(part);
|
||||
}
|
||||
expand.update(&[counter]);
|
||||
let tag = expand.sign();
|
||||
block.copy_from_slice(
|
||||
tag.as_ref()
|
||||
.get(..block.len())
|
||||
.ok_or(PrimitiveError::InvalidLength)?,
|
||||
);
|
||||
previous = Some(tag);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn x963(
|
||||
hash: HashAlgorithm,
|
||||
z: &[u8],
|
||||
shared_info: &[u8],
|
||||
out: &mut [u8],
|
||||
) -> Result<(), PrimitiveError> {
|
||||
for (counter, block) in (1u32..).zip(out.chunks_mut(hash.output_len())) {
|
||||
let mut hasher = hash.hasher();
|
||||
hasher.update(z);
|
||||
hasher.update(&counter.to_be_bytes());
|
||||
hasher.update(shared_info);
|
||||
let digest = hasher.finish();
|
||||
let digest = digest
|
||||
.as_ref()
|
||||
.get(..block.len())
|
||||
.ok_or(PrimitiveError::InvalidLength)?;
|
||||
block.copy_from_slice(digest);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn openpgp_ecdh(
|
||||
hash: HashAlgorithm,
|
||||
z: &[u8],
|
||||
param: &[&[u8]],
|
||||
out: &mut [u8],
|
||||
) -> Result<(), PrimitiveError> {
|
||||
let mut hasher = hash.hasher();
|
||||
hasher.update(&1u32.to_be_bytes());
|
||||
hasher.update(z);
|
||||
for part in param {
|
||||
hasher.update(part);
|
||||
}
|
||||
let digest = hasher.finish();
|
||||
out.copy_from_slice(
|
||||
digest
|
||||
.as_ref()
|
||||
.get(..out.len())
|
||||
.ok_or(PrimitiveError::InvalidLength)?,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
101
crates/crypto/src/backend/kem.rs
Normal file
101
crates/crypto/src/backend/kem.rs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aws_lc_rs::kem::{Ciphertext, EncapsulationKey, ML_KEM_512, ML_KEM_768, ML_KEM_1024};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use super::PrimitiveError;
|
||||
|
||||
pub(crate) const ML_KEM_SHARED_LEN: usize = 32;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum MlKem {
|
||||
MlKem512,
|
||||
MlKem768,
|
||||
MlKem1024,
|
||||
}
|
||||
|
||||
impl MlKem {
|
||||
pub(crate) fn name(self) -> &'static str {
|
||||
match self {
|
||||
MlKem::MlKem512 => "ML-KEM-512",
|
||||
MlKem::MlKem768 => "ML-KEM-768",
|
||||
MlKem::MlKem1024 => "ML-KEM-1024",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn public_len(self) -> usize {
|
||||
match self {
|
||||
MlKem::MlKem512 => 800,
|
||||
MlKem::MlKem768 => 1184,
|
||||
MlKem::MlKem1024 => 1568,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn ciphertext_len(self) -> usize {
|
||||
match self {
|
||||
MlKem::MlKem512 => 768,
|
||||
MlKem::MlKem768 => 1088,
|
||||
MlKem::MlKem1024 => 1568,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct MlKemPublicKey {
|
||||
kem: MlKem,
|
||||
key: EncapsulationKey,
|
||||
}
|
||||
|
||||
pub(crate) struct Encapsulation {
|
||||
ciphertext: Ciphertext<'static>,
|
||||
shared: Zeroizing<[u8; ML_KEM_SHARED_LEN]>,
|
||||
}
|
||||
|
||||
impl Encapsulation {
|
||||
pub(crate) fn ciphertext(&self) -> &[u8] {
|
||||
self.ciphertext.as_ref()
|
||||
}
|
||||
|
||||
pub(crate) fn shared(&self) -> &[u8; ML_KEM_SHARED_LEN] {
|
||||
&self.shared
|
||||
}
|
||||
}
|
||||
|
||||
impl MlKemPublicKey {
|
||||
pub(crate) fn new(kem: MlKem, bytes: &[u8]) -> Result<Self, PrimitiveError> {
|
||||
let alg = match kem {
|
||||
MlKem::MlKem512 => &ML_KEM_512,
|
||||
MlKem::MlKem768 => &ML_KEM_768,
|
||||
MlKem::MlKem1024 => &ML_KEM_1024,
|
||||
};
|
||||
EncapsulationKey::new(alg, bytes)
|
||||
.map(|key| MlKemPublicKey { kem, key })
|
||||
.map_err(|_| PrimitiveError::InvalidPublicKey)
|
||||
}
|
||||
|
||||
pub(crate) fn kem(&self) -> MlKem {
|
||||
self.kem
|
||||
}
|
||||
|
||||
pub(crate) fn heap_size(&self) -> usize {
|
||||
super::NATIVE_KEY_OVERHEAD + 2 * self.kem.public_len()
|
||||
}
|
||||
|
||||
pub(crate) fn encapsulate(&self) -> Result<Encapsulation, PrimitiveError> {
|
||||
let (ciphertext, secret) = self
|
||||
.key
|
||||
.encapsulate()
|
||||
.map_err(|_| PrimitiveError::Encryption)?;
|
||||
let mut shared = Zeroizing::new([0u8; ML_KEM_SHARED_LEN]);
|
||||
if secret.as_ref().len() != ML_KEM_SHARED_LEN
|
||||
|| ciphertext.as_ref().len() != self.kem.ciphertext_len()
|
||||
{
|
||||
return Err(PrimitiveError::Encryption);
|
||||
}
|
||||
shared.copy_from_slice(secret.as_ref());
|
||||
Ok(Encapsulation { ciphertext, shared })
|
||||
}
|
||||
}
|
||||
33
crates/crypto/src/backend/mod.rs
Normal file
33
crates/crypto/src/backend/mod.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub(crate) mod aes;
|
||||
pub(crate) mod agree;
|
||||
pub(crate) mod base64;
|
||||
pub(crate) mod crc24;
|
||||
pub(crate) mod ed448;
|
||||
pub(crate) mod hash;
|
||||
pub(crate) mod kdf;
|
||||
pub(crate) mod kem;
|
||||
pub(crate) mod ocb;
|
||||
pub(crate) mod rng;
|
||||
pub(crate) mod rsa;
|
||||
pub(crate) mod symmetric;
|
||||
pub(crate) mod verify;
|
||||
|
||||
pub(crate) const NATIVE_KEY_OVERHEAD: usize = 256;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PrimitiveError {
|
||||
Random,
|
||||
InvalidKeyLength,
|
||||
InvalidLength,
|
||||
InvalidPublicKey,
|
||||
KeyAgreement,
|
||||
Encryption,
|
||||
UnsupportedAlgorithm,
|
||||
BadSignature,
|
||||
}
|
||||
144
crates/crypto/src/backend/ocb.rs
Normal file
144
crates/crypto/src/backend/ocb.rs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{
|
||||
PrimitiveError,
|
||||
aes::{AesCipher, BLOCK_LEN},
|
||||
};
|
||||
|
||||
pub(crate) const OCB_TAG_LEN: usize = 16;
|
||||
pub(crate) const OCB_MAX_NONCE_LEN: usize = 15;
|
||||
const L_TABLE_LEN: usize = 32;
|
||||
const PAD_MARKER: u8 = 0x80;
|
||||
|
||||
pub(crate) struct OcbKey {
|
||||
cipher: AesCipher,
|
||||
l_star: u128,
|
||||
l_dollar: u128,
|
||||
l: [u128; L_TABLE_LEN],
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn load(block: &[u8; BLOCK_LEN]) -> u128 {
|
||||
u128::from_ne_bytes(*block)
|
||||
}
|
||||
|
||||
fn double(value: u128) -> u128 {
|
||||
let v = u128::from_be_bytes(value.to_ne_bytes());
|
||||
let doubled = (v << 1) ^ ((v >> 127) * 0x87);
|
||||
u128::from_ne_bytes(doubled.to_be_bytes())
|
||||
}
|
||||
|
||||
impl OcbKey {
|
||||
pub(crate) fn new(key: &[u8]) -> Result<Self, PrimitiveError> {
|
||||
let mut ocb = OcbKey {
|
||||
cipher: AesCipher::new(key)?,
|
||||
l_star: 0,
|
||||
l_dollar: 0,
|
||||
l: [0u128; L_TABLE_LEN],
|
||||
};
|
||||
ocb.l_star = ocb.encipher(0);
|
||||
ocb.l_dollar = double(ocb.l_star);
|
||||
let mut acc = ocb.l_dollar;
|
||||
for entry in ocb.l.iter_mut() {
|
||||
acc = double(acc);
|
||||
*entry = acc;
|
||||
}
|
||||
Ok(ocb)
|
||||
}
|
||||
|
||||
fn encipher(&self, value: u128) -> u128 {
|
||||
let mut block = value.to_ne_bytes();
|
||||
self.cipher.encrypt_block(&mut block);
|
||||
load(&block)
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
fn l_at(&self, index: u64) -> u128 {
|
||||
self.l[index.trailing_zeros() as usize & (L_TABLE_LEN - 1)]
|
||||
}
|
||||
|
||||
fn initial_offset(&self, nonce: &[u8]) -> Result<u128, PrimitiveError> {
|
||||
if nonce.is_empty() || nonce.len() > OCB_MAX_NONCE_LEN {
|
||||
return Err(PrimitiveError::InvalidLength);
|
||||
}
|
||||
let mut block = [0u8; BLOCK_LEN];
|
||||
let (head, tail) = block.split_at_mut(BLOCK_LEN - nonce.len());
|
||||
tail.copy_from_slice(nonce);
|
||||
if let Some(marker) = head.last_mut() {
|
||||
*marker |= 1;
|
||||
}
|
||||
let bottom = u32::from(block[BLOCK_LEN - 1] & 0x3F);
|
||||
block[BLOCK_LEN - 1] &= 0xC0;
|
||||
self.cipher.encrypt_block(&mut block);
|
||||
let ktop = u128::from_be_bytes(block);
|
||||
let stretch = ((ktop >> 64) as u64) ^ ((ktop >> 56) as u64);
|
||||
let offset = if bottom == 0 {
|
||||
ktop
|
||||
} else {
|
||||
(ktop << bottom) | (u128::from(stretch) >> (64 - bottom))
|
||||
};
|
||||
Ok(u128::from_ne_bytes(offset.to_be_bytes()))
|
||||
}
|
||||
|
||||
pub(crate) fn hash(&self, ad: &[u8]) -> u128 {
|
||||
let (blocks, tail) = ad.as_chunks::<BLOCK_LEN>();
|
||||
let mut offset = 0u128;
|
||||
let mut sum = 0u128;
|
||||
for (i, block) in (1u64..).zip(blocks) {
|
||||
offset ^= self.l_at(i);
|
||||
sum ^= self.encipher(load(block) ^ offset);
|
||||
}
|
||||
if !tail.is_empty() {
|
||||
offset ^= self.l_star;
|
||||
sum ^= self.encipher(load(&padded(tail)) ^ offset);
|
||||
}
|
||||
sum
|
||||
}
|
||||
|
||||
pub(crate) fn seal_in_place(
|
||||
&self,
|
||||
nonce: &[u8],
|
||||
ad_hash: u128,
|
||||
data: &mut [u8],
|
||||
) -> Result<[u8; OCB_TAG_LEN], PrimitiveError> {
|
||||
let initial = self.initial_offset(nonce)?;
|
||||
let (blocks, tail) = data.as_chunks_mut::<BLOCK_LEN>();
|
||||
let mut checksum = 0u128;
|
||||
let mut offset = initial;
|
||||
for (i, block) in (1u64..).zip(blocks.iter_mut()) {
|
||||
offset ^= self.l_at(i);
|
||||
let plain = load(block);
|
||||
checksum ^= plain;
|
||||
*block = (plain ^ offset).to_ne_bytes();
|
||||
}
|
||||
self.cipher.encrypt_blocks(blocks.as_flattened_mut());
|
||||
let mut offset = initial;
|
||||
for (i, block) in (1u64..).zip(blocks.iter_mut()) {
|
||||
offset ^= self.l_at(i);
|
||||
*block = (load(block) ^ offset).to_ne_bytes();
|
||||
}
|
||||
if !tail.is_empty() {
|
||||
offset ^= self.l_star;
|
||||
let pad = self.encipher(offset).to_ne_bytes();
|
||||
checksum ^= load(&padded(tail));
|
||||
for (byte, pad) in tail.iter_mut().zip(pad) {
|
||||
*byte ^= pad;
|
||||
}
|
||||
}
|
||||
Ok((self.encipher(checksum ^ offset ^ self.l_dollar) ^ ad_hash).to_ne_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
fn padded(tail: &[u8]) -> [u8; BLOCK_LEN] {
|
||||
let mut block = [0u8; BLOCK_LEN];
|
||||
let (head, rest) = block.split_at_mut(tail.len().min(BLOCK_LEN - 1));
|
||||
head.copy_from_slice(&tail[..head.len()]);
|
||||
if let Some(marker) = rest.first_mut() {
|
||||
*marker = PAD_MARKER;
|
||||
}
|
||||
block
|
||||
}
|
||||
28
crates/crypto/src/backend/rng.rs
Normal file
28
crates/crypto/src/backend/rng.rs
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aws_lc_rs::rand::{SecureRandom, SystemRandom};
|
||||
|
||||
use super::PrimitiveError;
|
||||
|
||||
pub(crate) trait Rng {
|
||||
fn fill(&mut self, dest: &mut [u8]) -> Result<(), PrimitiveError>;
|
||||
}
|
||||
|
||||
pub(crate) struct SystemRng(SystemRandom);
|
||||
|
||||
impl SystemRng {
|
||||
pub(crate) fn new() -> Self {
|
||||
SystemRng(SystemRandom::new())
|
||||
}
|
||||
}
|
||||
|
||||
impl Rng for SystemRng {
|
||||
#[inline]
|
||||
fn fill(&mut self, dest: &mut [u8]) -> Result<(), PrimitiveError> {
|
||||
self.0.fill(dest).map_err(|_| PrimitiveError::Random)
|
||||
}
|
||||
}
|
||||
115
crates/crypto/src/backend/rsa.rs
Normal file
115
crates/crypto/src/backend/rsa.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aws_lc_rs::rsa::{
|
||||
OAEP_SHA1_MGF1SHA1, OAEP_SHA256_MGF1SHA256, OAEP_SHA384_MGF1SHA384, OAEP_SHA512_MGF1SHA512,
|
||||
OaepAlgorithm, OaepPublicEncryptingKey, Pkcs1PublicEncryptingKey, PublicEncryptingKey,
|
||||
};
|
||||
|
||||
use super::PrimitiveError;
|
||||
use crate::der::{
|
||||
oid, tag,
|
||||
writer::{
|
||||
bit_string_len, rsa_public_key_len, tlv_len, write_bit_string_header, write_header,
|
||||
write_rsa_public_key, write_tlv,
|
||||
},
|
||||
};
|
||||
|
||||
pub(crate) const MIN_RSA_BITS: usize = 2048;
|
||||
pub(crate) const MAX_RSA_BITS: usize = 8192;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum OaepHash {
|
||||
Sha1,
|
||||
Sha256,
|
||||
Sha384,
|
||||
Sha512,
|
||||
}
|
||||
|
||||
impl OaepHash {
|
||||
fn algorithm(self) -> &'static OaepAlgorithm {
|
||||
match self {
|
||||
OaepHash::Sha1 => &OAEP_SHA1_MGF1SHA1,
|
||||
OaepHash::Sha256 => &OAEP_SHA256_MGF1SHA256,
|
||||
OaepHash::Sha384 => &OAEP_SHA384_MGF1SHA384,
|
||||
OaepHash::Sha512 => &OAEP_SHA512_MGF1SHA512,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct RsaPublicKey(PublicEncryptingKey);
|
||||
|
||||
impl RsaPublicKey {
|
||||
pub(crate) fn from_spki(spki: &[u8]) -> Result<Self, PrimitiveError> {
|
||||
PublicEncryptingKey::from_der(spki)
|
||||
.map(RsaPublicKey)
|
||||
.map_err(|_| PrimitiveError::InvalidPublicKey)
|
||||
}
|
||||
|
||||
pub(crate) fn from_components(n: &[u8], e: &[u8]) -> Result<Self, PrimitiveError> {
|
||||
let key_len = rsa_public_key_len(n, e);
|
||||
let algorithm_len = tlv_len(tlv_len(oid::RSA_ENCRYPTION.len()) + tlv_len(0));
|
||||
let spki_content_len = algorithm_len + bit_string_len(key_len);
|
||||
let mut spki = Vec::with_capacity(tlv_len(spki_content_len));
|
||||
write_header(&mut spki, tag::SEQUENCE, spki_content_len);
|
||||
write_header(&mut spki, tag::SEQUENCE, algorithm_len - 2);
|
||||
write_tlv(&mut spki, tag::OID, oid::RSA_ENCRYPTION);
|
||||
write_tlv(&mut spki, tag::NULL, &[]);
|
||||
write_bit_string_header(&mut spki, key_len);
|
||||
write_rsa_public_key(&mut spki, n, e);
|
||||
Self::from_spki(&spki)
|
||||
}
|
||||
|
||||
pub(crate) fn bits(&self) -> usize {
|
||||
self.0.key_size_bits()
|
||||
}
|
||||
|
||||
pub(crate) fn ciphertext_len(&self) -> usize {
|
||||
self.0.key_size_bytes()
|
||||
}
|
||||
|
||||
pub(crate) fn heap_size(&self) -> usize {
|
||||
super::NATIVE_KEY_OVERHEAD + 3 * self.0.key_size_bytes()
|
||||
}
|
||||
|
||||
pub(crate) fn encrypt_pkcs1(
|
||||
&self,
|
||||
plaintext: &[u8],
|
||||
out: &mut [u8],
|
||||
) -> Result<(), PrimitiveError> {
|
||||
let key = Pkcs1PublicEncryptingKey::new(self.0.clone())
|
||||
.map_err(|_| PrimitiveError::InvalidPublicKey)?;
|
||||
let written = key
|
||||
.encrypt(plaintext, out)
|
||||
.map_err(|_| PrimitiveError::Encryption)?
|
||||
.len();
|
||||
if written == out.len() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PrimitiveError::Encryption)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn encrypt_oaep(
|
||||
&self,
|
||||
hash: OaepHash,
|
||||
plaintext: &[u8],
|
||||
out: &mut [u8],
|
||||
) -> Result<(), PrimitiveError> {
|
||||
let key = OaepPublicEncryptingKey::new(self.0.clone())
|
||||
.map_err(|_| PrimitiveError::InvalidPublicKey)?;
|
||||
let written = key
|
||||
.encrypt(hash.algorithm(), plaintext, out, None)
|
||||
.map_err(|_| PrimitiveError::Encryption)?
|
||||
.len();
|
||||
if written == out.len() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(PrimitiveError::Encryption)
|
||||
}
|
||||
}
|
||||
}
|
||||
78
crates/crypto/src/backend/symmetric.rs
Normal file
78
crates/crypto/src/backend/symmetric.rs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aws_lc_rs::{
|
||||
aead::{AES_128_GCM, AES_192_GCM, AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey},
|
||||
cipher::{AES_128, AES_192, AES_256, EncryptingKey, EncryptionContext, UnboundCipherKey},
|
||||
iv::FixedLength,
|
||||
};
|
||||
|
||||
use super::{PrimitiveError, aes::BLOCK_LEN};
|
||||
|
||||
pub(crate) const GCM_NONCE_LEN: usize = 12;
|
||||
pub(crate) const GCM_TAG_LEN: usize = 16;
|
||||
|
||||
pub(crate) struct GcmKey(LessSafeKey);
|
||||
|
||||
impl GcmKey {
|
||||
pub(crate) fn new(key: &[u8]) -> Result<Self, PrimitiveError> {
|
||||
let alg = match key.len() {
|
||||
16 => &AES_128_GCM,
|
||||
24 => &AES_192_GCM,
|
||||
32 => &AES_256_GCM,
|
||||
_ => return Err(PrimitiveError::InvalidKeyLength),
|
||||
};
|
||||
UnboundKey::new(alg, key)
|
||||
.map(|key| GcmKey(LessSafeKey::new(key)))
|
||||
.map_err(|_| PrimitiveError::InvalidKeyLength)
|
||||
}
|
||||
|
||||
pub(crate) fn seal_in_place(
|
||||
&self,
|
||||
nonce: [u8; GCM_NONCE_LEN],
|
||||
ad: &[u8],
|
||||
data: &mut [u8],
|
||||
) -> Result<[u8; GCM_TAG_LEN], PrimitiveError> {
|
||||
let tag = self
|
||||
.0
|
||||
.seal_in_place_separate_tag(Nonce::assume_unique_for_key(nonce), Aad::from(ad), data)
|
||||
.map_err(|_| PrimitiveError::Encryption)?;
|
||||
tag.as_ref()
|
||||
.try_into()
|
||||
.map_err(|_| PrimitiveError::Encryption)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn cbc_pkcs7_padded_len(len: usize) -> usize {
|
||||
(len / BLOCK_LEN + 1) * BLOCK_LEN
|
||||
}
|
||||
|
||||
pub(crate) fn write_pkcs7_padding(out: &mut Vec<u8>, plaintext_len: usize) {
|
||||
let pad = cbc_pkcs7_padded_len(plaintext_len) - plaintext_len;
|
||||
out.resize(out.len() + pad, pad as u8);
|
||||
}
|
||||
|
||||
pub(crate) fn cbc_encrypt_padded_in_place(
|
||||
key: &[u8],
|
||||
iv: [u8; BLOCK_LEN],
|
||||
data: &mut [u8],
|
||||
) -> Result<(), PrimitiveError> {
|
||||
let alg = match key.len() {
|
||||
16 => &AES_128,
|
||||
24 => &AES_192,
|
||||
32 => &AES_256,
|
||||
_ => return Err(PrimitiveError::InvalidKeyLength),
|
||||
};
|
||||
if !data.len().is_multiple_of(BLOCK_LEN) {
|
||||
return Err(PrimitiveError::InvalidLength);
|
||||
}
|
||||
let key = UnboundCipherKey::new(alg, key)
|
||||
.and_then(EncryptingKey::cbc)
|
||||
.map_err(|_| PrimitiveError::InvalidKeyLength)?;
|
||||
key.less_safe_encrypt(data, EncryptionContext::Iv128(FixedLength::from(iv)))
|
||||
.map(|_| ())
|
||||
.map_err(|_| PrimitiveError::Encryption)
|
||||
}
|
||||
108
crates/crypto/src/backend/verify.rs
Normal file
108
crates/crypto/src/backend/verify.rs
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aws_lc_rs::{
|
||||
digest::Digest,
|
||||
signature::{
|
||||
ECDSA_P256_SHA1_ASN1, ECDSA_P256_SHA256_ASN1, ECDSA_P256_SHA384_ASN1,
|
||||
ECDSA_P256_SHA512_ASN1, ECDSA_P384_SHA256_ASN1, ECDSA_P384_SHA384_ASN1,
|
||||
ECDSA_P384_SHA512_ASN1, ECDSA_P521_SHA1_ASN1, ECDSA_P521_SHA224_ASN1,
|
||||
ECDSA_P521_SHA256_ASN1, ECDSA_P521_SHA384_ASN1, ECDSA_P521_SHA512_ASN1, ED25519, ML_DSA_44,
|
||||
ML_DSA_65, ML_DSA_87, RSA_PKCS1_2048_8192_SHA1_FOR_LEGACY_USE_ONLY,
|
||||
RSA_PKCS1_2048_8192_SHA256, RSA_PKCS1_2048_8192_SHA384, RSA_PKCS1_2048_8192_SHA512,
|
||||
RSA_PSS_2048_8192_SHA256, RSA_PSS_2048_8192_SHA384, RSA_PSS_2048_8192_SHA512,
|
||||
UnparsedPublicKey, VerificationAlgorithm,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{PrimitiveError, hash::HashAlgorithm};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum EcCurve {
|
||||
P256,
|
||||
P384,
|
||||
P521,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum MlDsa {
|
||||
MlDsa44,
|
||||
MlDsa65,
|
||||
MlDsa87,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum SignatureScheme {
|
||||
RsaPkcs1(HashAlgorithm),
|
||||
RsaPss(HashAlgorithm),
|
||||
Ecdsa(EcCurve, HashAlgorithm),
|
||||
Ed25519,
|
||||
Ed448,
|
||||
MlDsa(MlDsa),
|
||||
}
|
||||
|
||||
impl SignatureScheme {
|
||||
fn algorithm(self) -> Result<&'static dyn VerificationAlgorithm, PrimitiveError> {
|
||||
use EcCurve::*;
|
||||
use HashAlgorithm::*;
|
||||
Ok(match self {
|
||||
SignatureScheme::RsaPkcs1(Sha1) => &RSA_PKCS1_2048_8192_SHA1_FOR_LEGACY_USE_ONLY,
|
||||
SignatureScheme::RsaPkcs1(Sha256) => &RSA_PKCS1_2048_8192_SHA256,
|
||||
SignatureScheme::RsaPkcs1(Sha384) => &RSA_PKCS1_2048_8192_SHA384,
|
||||
SignatureScheme::RsaPkcs1(Sha512) => &RSA_PKCS1_2048_8192_SHA512,
|
||||
SignatureScheme::RsaPss(Sha256) => &RSA_PSS_2048_8192_SHA256,
|
||||
SignatureScheme::RsaPss(Sha384) => &RSA_PSS_2048_8192_SHA384,
|
||||
SignatureScheme::RsaPss(Sha512) => &RSA_PSS_2048_8192_SHA512,
|
||||
SignatureScheme::Ecdsa(P256, Sha1) => &ECDSA_P256_SHA1_ASN1,
|
||||
SignatureScheme::Ecdsa(P256, Sha256) => &ECDSA_P256_SHA256_ASN1,
|
||||
SignatureScheme::Ecdsa(P256, Sha384) => &ECDSA_P256_SHA384_ASN1,
|
||||
SignatureScheme::Ecdsa(P256, Sha512) => &ECDSA_P256_SHA512_ASN1,
|
||||
SignatureScheme::Ecdsa(P384, Sha256) => &ECDSA_P384_SHA256_ASN1,
|
||||
SignatureScheme::Ecdsa(P384, Sha384) => &ECDSA_P384_SHA384_ASN1,
|
||||
SignatureScheme::Ecdsa(P384, Sha512) => &ECDSA_P384_SHA512_ASN1,
|
||||
SignatureScheme::Ecdsa(P521, Sha1) => &ECDSA_P521_SHA1_ASN1,
|
||||
SignatureScheme::Ecdsa(P521, Sha224) => &ECDSA_P521_SHA224_ASN1,
|
||||
SignatureScheme::Ecdsa(P521, Sha256) => &ECDSA_P521_SHA256_ASN1,
|
||||
SignatureScheme::Ecdsa(P521, Sha384) => &ECDSA_P521_SHA384_ASN1,
|
||||
SignatureScheme::Ecdsa(P521, Sha512) => &ECDSA_P521_SHA512_ASN1,
|
||||
SignatureScheme::Ed25519 => &ED25519,
|
||||
SignatureScheme::MlDsa(MlDsa::MlDsa44) => &ML_DSA_44,
|
||||
SignatureScheme::MlDsa(MlDsa::MlDsa65) => &ML_DSA_65,
|
||||
SignatureScheme::MlDsa(MlDsa::MlDsa87) => &ML_DSA_87,
|
||||
_ => return Err(PrimitiveError::UnsupportedAlgorithm),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn verify(
|
||||
self,
|
||||
public_key: &[u8],
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> Result<(), PrimitiveError> {
|
||||
if self == SignatureScheme::Ed448 {
|
||||
return super::ed448::verify(public_key, message, signature);
|
||||
}
|
||||
UnparsedPublicKey::new(self.algorithm()?, public_key)
|
||||
.verify(message, signature)
|
||||
.map_err(|_| PrimitiveError::BadSignature)
|
||||
}
|
||||
|
||||
pub(crate) fn verify_digest(
|
||||
self,
|
||||
public_key: &[u8],
|
||||
digest: &Digest,
|
||||
signature: &[u8],
|
||||
) -> Result<(), PrimitiveError> {
|
||||
match self {
|
||||
SignatureScheme::Ed25519 | SignatureScheme::Ed448 | SignatureScheme::MlDsa(_) => {
|
||||
self.verify(public_key, digest.as_ref(), signature)
|
||||
}
|
||||
_ => UnparsedPublicKey::new(self.algorithm()?, public_key)
|
||||
.verify_digest(digest, signature)
|
||||
.map_err(|_| PrimitiveError::BadSignature),
|
||||
}
|
||||
}
|
||||
}
|
||||
578
crates/crypto/src/cms/envelope.rs
Normal file
578
crates/crypto/src/cms/envelope.rs
Normal file
|
|
@ -0,0 +1,578 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::{
|
||||
backend::{
|
||||
aes::{AesCipher, BLOCK_LEN},
|
||||
agree::Curve,
|
||||
base64::MIME,
|
||||
hash::HashAlgorithm,
|
||||
kdf::{HkdfHash, x963},
|
||||
kem::{MlKem, MlKemPublicKey},
|
||||
rng::Rng,
|
||||
rsa::{OaepHash, RsaPublicKey},
|
||||
symmetric::{
|
||||
GCM_NONCE_LEN, GCM_TAG_LEN, GcmKey, cbc_encrypt_padded_in_place, cbc_pkcs7_padded_len,
|
||||
write_pkcs7_padding,
|
||||
},
|
||||
},
|
||||
der::{
|
||||
oid, tag,
|
||||
writer::{
|
||||
StackBuf, bit_string_len, small_integer_len, tlv_len, write_bit_string_header,
|
||||
write_header, write_small_integer, write_tlv,
|
||||
},
|
||||
},
|
||||
error::{EncryptError, ProfileError},
|
||||
mime::{Sink, entity::Entity},
|
||||
types::{EcdhWrapParameters, EncryptOptions, EncryptWarning, Profile},
|
||||
x509::recipient::{SmimeKey, SmimeRecipient},
|
||||
};
|
||||
|
||||
const CEK_LEN: usize = 32;
|
||||
const UKM_LEN: usize = 64;
|
||||
const WRAPPED_LEN: usize = CEK_LEN + 8;
|
||||
const NULL: &[u8] = &[tag::NULL, 0];
|
||||
const NSS_SIZE_LIMIT: usize = 256 << 20;
|
||||
const MAX_SHARED_INFO: usize = 128;
|
||||
const MAX_KEM_INFO: usize = 32;
|
||||
|
||||
const SMIME_HEADERS_ENVELOPED: &[u8] = b"Content-Type: application/pkcs7-mime; smime-type=enveloped-data;\r\n\tname=\"smime.p7m\"\r\nContent-Disposition: attachment; filename=\"smime.p7m\"\r\nContent-Transfer-Encoding: base64\r\n\r\n";
|
||||
const SMIME_HEADERS_AUTH: &[u8] = b"Content-Type: application/pkcs7-mime; smime-type=authEnveloped-data;\r\n\tname=\"smime.p7m\"\r\nContent-Disposition: attachment; filename=\"smime.p7m\"\r\nContent-Transfer-Encoding: base64\r\n\r\n";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Content {
|
||||
Cbc,
|
||||
Gcm,
|
||||
}
|
||||
|
||||
fn alg_id_len(oid: &[u8], params_len: usize) -> usize {
|
||||
tlv_len(tlv_len(oid.len()) + params_len)
|
||||
}
|
||||
|
||||
fn write_alg_id<S: Sink + ?Sized>(out: &mut S, oid: &[u8], params: &[u8]) {
|
||||
write_header(out, tag::SEQUENCE, tlv_len(oid.len()) + params.len());
|
||||
write_tlv(out, tag::OID, oid);
|
||||
out.put(params);
|
||||
}
|
||||
|
||||
fn hash_oid(hash: OaepHash) -> &'static [u8] {
|
||||
match hash {
|
||||
OaepHash::Sha1 => oid::SHA1,
|
||||
OaepHash::Sha256 => oid::SHA256,
|
||||
OaepHash::Sha384 => oid::SHA384,
|
||||
OaepHash::Sha512 => oid::SHA512,
|
||||
}
|
||||
}
|
||||
|
||||
fn oaep_params_len(hash: OaepHash) -> usize {
|
||||
if hash == OaepHash::Sha1 {
|
||||
return tlv_len(0);
|
||||
}
|
||||
let hash_alg = alg_id_len(hash_oid(hash), 0);
|
||||
tlv_len(tlv_len(hash_alg) + tlv_len(alg_id_len(oid::MGF1, hash_alg)))
|
||||
}
|
||||
|
||||
fn write_oaep_params<S: Sink + ?Sized>(out: &mut S, hash: OaepHash) {
|
||||
if hash == OaepHash::Sha1 {
|
||||
write_header(out, tag::SEQUENCE, 0);
|
||||
return;
|
||||
}
|
||||
let hash_oid = hash_oid(hash);
|
||||
let hash_alg = alg_id_len(hash_oid, 0);
|
||||
let mgf = alg_id_len(oid::MGF1, hash_alg);
|
||||
write_header(out, tag::SEQUENCE, tlv_len(hash_alg) + tlv_len(mgf));
|
||||
write_header(out, tag::context_constructed(0), hash_alg);
|
||||
write_alg_id(out, hash_oid, &[]);
|
||||
write_header(out, tag::context_constructed(1), mgf);
|
||||
write_header(out, tag::SEQUENCE, tlv_len(oid::MGF1.len()) + hash_alg);
|
||||
write_tlv(out, tag::OID, oid::MGF1);
|
||||
write_alg_id(out, hash_oid, &[]);
|
||||
}
|
||||
|
||||
fn rsa_padding(key: &SmimeKey, profile: Profile) -> Option<OaepHash> {
|
||||
match key {
|
||||
SmimeKey::Rsa {
|
||||
oaep: Some(hash), ..
|
||||
} => Some(*hash),
|
||||
SmimeKey::Rsa { oaep: None, .. } if profile != Profile::Compatible => {
|
||||
Some(OaepHash::Sha256)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum KariKdf {
|
||||
X963(HashAlgorithm),
|
||||
Hkdf,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Ukm {
|
||||
Absent,
|
||||
Random,
|
||||
}
|
||||
|
||||
impl Ukm {
|
||||
fn explicit_len(self) -> usize {
|
||||
match self {
|
||||
Ukm::Absent => 0,
|
||||
Ukm::Random => tlv_len(tlv_len(UKM_LEN)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Kari<'r> {
|
||||
curve: Curve,
|
||||
point: &'r [u8],
|
||||
originator_oid: &'static [u8],
|
||||
scheme: &'static [u8],
|
||||
kdf: KariKdf,
|
||||
ukm: Ukm,
|
||||
wrap: &'static [u8],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum RecipientKind<'r> {
|
||||
Ktri {
|
||||
key: &'r RsaPublicKey,
|
||||
padding: Option<OaepHash>,
|
||||
},
|
||||
Kari(Kari<'r>),
|
||||
Kemri(&'r MlKemPublicKey),
|
||||
}
|
||||
|
||||
fn wrap_params(wrap: EcdhWrapParameters) -> &'static [u8] {
|
||||
match wrap {
|
||||
EcdhWrapParameters::Absent => &[],
|
||||
EcdhWrapParameters::Null => NULL,
|
||||
}
|
||||
}
|
||||
|
||||
fn mlkem_wrap(kem: MlKem) -> (&'static [u8], usize) {
|
||||
match kem {
|
||||
MlKem::MlKem512 => (oid::AES128_WRAP, 16),
|
||||
_ => (oid::AES256_WRAP, 32),
|
||||
}
|
||||
}
|
||||
|
||||
fn mlkem_oid(kem: MlKem) -> &'static [u8] {
|
||||
match kem {
|
||||
MlKem::MlKem512 => oid::ML_KEM_512,
|
||||
MlKem::MlKem768 => oid::ML_KEM_768,
|
||||
MlKem::MlKem1024 => oid::ML_KEM_1024,
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> RecipientKind<'r> {
|
||||
fn new(key: &'r SmimeKey, options: &EncryptOptions) -> Self {
|
||||
let hkdf = |curve, point, originator_oid| {
|
||||
RecipientKind::Kari(Kari {
|
||||
curve,
|
||||
point,
|
||||
originator_oid,
|
||||
scheme: oid::ECDH_HKDF_SHA256,
|
||||
kdf: KariKdf::Hkdf,
|
||||
ukm: Ukm::Random,
|
||||
wrap: &[],
|
||||
})
|
||||
};
|
||||
match key {
|
||||
SmimeKey::Rsa { key: rsa, .. } => RecipientKind::Ktri {
|
||||
key: rsa,
|
||||
padding: rsa_padding(key, options.profile),
|
||||
},
|
||||
SmimeKey::Ec { curve, point } => {
|
||||
let (scheme, hash) = match curve {
|
||||
Curve::P256 => (oid::ECDH_SHA256_KDF, HashAlgorithm::Sha256),
|
||||
Curve::P384 => (oid::ECDH_SHA384_KDF, HashAlgorithm::Sha384),
|
||||
_ => (oid::ECDH_SHA512_KDF, HashAlgorithm::Sha512),
|
||||
};
|
||||
RecipientKind::Kari(Kari {
|
||||
curve: *curve,
|
||||
point,
|
||||
originator_oid: oid::EC_PUBLIC_KEY,
|
||||
scheme,
|
||||
kdf: KariKdf::X963(hash),
|
||||
ukm: match options.ecdh_wrap_parameters {
|
||||
EcdhWrapParameters::Absent => Ukm::Absent,
|
||||
EcdhWrapParameters::Null => Ukm::Random,
|
||||
},
|
||||
wrap: wrap_params(options.ecdh_wrap_parameters),
|
||||
})
|
||||
}
|
||||
SmimeKey::X25519(point) => hkdf(Curve::X25519, point.as_slice(), oid::X25519),
|
||||
SmimeKey::X448(point) => hkdf(Curve::X448, point.as_slice(), oid::X448),
|
||||
SmimeKey::MlKem(kem) => RecipientKind::Kemri(kem),
|
||||
}
|
||||
}
|
||||
|
||||
fn ktri_alg_len(padding: Option<OaepHash>) -> usize {
|
||||
match padding {
|
||||
Some(hash) => alg_id_len(oid::RSAES_OAEP, oaep_params_len(hash)),
|
||||
None => alg_id_len(oid::RSA_ENCRYPTION, NULL.len()),
|
||||
}
|
||||
}
|
||||
|
||||
fn kemri_body_len(kem: MlKem, rid: usize) -> usize {
|
||||
let (wrap_oid, kek_len) = mlkem_wrap(kem);
|
||||
small_integer_len(0)
|
||||
+ rid
|
||||
+ alg_id_len(mlkem_oid(kem), 0)
|
||||
+ tlv_len(kem.ciphertext_len())
|
||||
+ alg_id_len(oid::HKDF_SHA256, 0)
|
||||
+ small_integer_len(kek_len as u32)
|
||||
+ alg_id_len(wrap_oid, 0)
|
||||
+ tlv_len(WRAPPED_LEN)
|
||||
}
|
||||
|
||||
fn content_len(&self, rid: usize) -> usize {
|
||||
match self {
|
||||
RecipientKind::Ktri { key, padding } => {
|
||||
small_integer_len(0)
|
||||
+ rid
|
||||
+ Self::ktri_alg_len(*padding)
|
||||
+ tlv_len(key.ciphertext_len())
|
||||
}
|
||||
RecipientKind::Kemri(kem) => {
|
||||
tlv_len(oid::ORI_KEM.len()) + tlv_len(Self::kemri_body_len(kem.kem(), rid))
|
||||
}
|
||||
RecipientKind::Kari(kari) => {
|
||||
small_integer_len(3)
|
||||
+ tlv_len(kari.originator_len())
|
||||
+ kari.ukm.explicit_len()
|
||||
+ alg_id_len(kari.scheme, alg_id_len(oid::AES256_WRAP, kari.wrap.len()))
|
||||
+ tlv_len(tlv_len(rid + tlv_len(WRAPPED_LEN)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn len(&self, rid: usize) -> usize {
|
||||
tlv_len(self.content_len(rid))
|
||||
}
|
||||
}
|
||||
|
||||
impl Kari<'_> {
|
||||
fn originator_len(&self) -> usize {
|
||||
tlv_len(alg_id_len(self.originator_oid, 0) + bit_string_len(self.curve.public_len()))
|
||||
}
|
||||
}
|
||||
|
||||
fn write_explicit_ukm<S: Sink + ?Sized>(out: &mut S, number: u8, ukm: Option<&[u8]>) {
|
||||
if let Some(ukm) = ukm {
|
||||
write_header(out, tag::context_constructed(number), tlv_len(ukm.len()));
|
||||
write_tlv(out, tag::OCTET_STRING, ukm);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_ri(
|
||||
out: &mut Vec<u8>,
|
||||
kind: &RecipientKind<'_>,
|
||||
rid: &[u8],
|
||||
cek: &[u8],
|
||||
rng: &mut impl Rng,
|
||||
) -> Result<(), EncryptError> {
|
||||
match kind {
|
||||
RecipientKind::Ktri { key, padding } => {
|
||||
write_header(out, tag::SEQUENCE, kind.content_len(rid.len()));
|
||||
write_small_integer(out, 0);
|
||||
out.extend_from_slice(rid);
|
||||
match padding {
|
||||
Some(hash) => {
|
||||
write_header(
|
||||
out,
|
||||
tag::SEQUENCE,
|
||||
tlv_len(oid::RSAES_OAEP.len()) + oaep_params_len(*hash),
|
||||
);
|
||||
write_tlv(out, tag::OID, oid::RSAES_OAEP);
|
||||
write_oaep_params(out, *hash);
|
||||
}
|
||||
None => write_alg_id(out, oid::RSA_ENCRYPTION, NULL),
|
||||
}
|
||||
write_header(out, tag::OCTET_STRING, key.ciphertext_len());
|
||||
let start = out.len();
|
||||
out.resize(start + key.ciphertext_len(), 0);
|
||||
let slot = out.get_mut(start..).unwrap_or_default();
|
||||
match padding {
|
||||
Some(hash) => key.encrypt_oaep(*hash, cek, slot)?,
|
||||
None => key.encrypt_pkcs1(cek, slot)?,
|
||||
}
|
||||
}
|
||||
RecipientKind::Kemri(kem) => {
|
||||
let (wrap_oid, kek_len) = mlkem_wrap(kem.kem());
|
||||
let encapsulation = kem.encapsulate()?;
|
||||
let mut info = StackBuf::<MAX_KEM_INFO>::new();
|
||||
write_header(
|
||||
&mut info,
|
||||
tag::SEQUENCE,
|
||||
alg_id_len(wrap_oid, 0) + small_integer_len(kek_len as u32),
|
||||
);
|
||||
write_alg_id(&mut info, wrap_oid, &[]);
|
||||
write_small_integer(&mut info, kek_len as u32);
|
||||
let mut kek = Zeroizing::new([0u8; 32]);
|
||||
let kek = kek.get_mut(..kek_len).unwrap_or_default();
|
||||
HkdfHash::Sha256.derive(
|
||||
&[],
|
||||
&[encapsulation.shared()],
|
||||
&[info.as_slice().ok_or(EncryptError::MalformedMessage)?],
|
||||
kek,
|
||||
)?;
|
||||
write_header(
|
||||
out,
|
||||
tag::context_constructed(4),
|
||||
kind.content_len(rid.len()),
|
||||
);
|
||||
write_tlv(out, tag::OID, oid::ORI_KEM);
|
||||
write_header(
|
||||
out,
|
||||
tag::SEQUENCE,
|
||||
RecipientKind::kemri_body_len(kem.kem(), rid.len()),
|
||||
);
|
||||
write_small_integer(out, 0);
|
||||
out.extend_from_slice(rid);
|
||||
write_alg_id(out, mlkem_oid(kem.kem()), &[]);
|
||||
write_tlv(out, tag::OCTET_STRING, encapsulation.ciphertext());
|
||||
write_alg_id(out, oid::HKDF_SHA256, &[]);
|
||||
write_small_integer(out, kek_len as u32);
|
||||
write_alg_id(out, wrap_oid, &[]);
|
||||
write_header(out, tag::OCTET_STRING, WRAPPED_LEN);
|
||||
let start = out.len();
|
||||
out.resize(start + WRAPPED_LEN, 0);
|
||||
AesCipher::new(kek)?.wrap(cek, out.get_mut(start..).unwrap_or_default())?;
|
||||
}
|
||||
RecipientKind::Kari(kari) => {
|
||||
let agreement = kari.curve.ephemeral_agree(kari.point, rng)?;
|
||||
let mut ukm_bytes = [0u8; UKM_LEN];
|
||||
let ukm = match kari.ukm {
|
||||
Ukm::Absent => None,
|
||||
Ukm::Random => {
|
||||
rng.fill(&mut ukm_bytes)?;
|
||||
Some(ukm_bytes.as_slice())
|
||||
}
|
||||
};
|
||||
|
||||
let wrap_alg = alg_id_len(oid::AES256_WRAP, kari.wrap.len());
|
||||
let mut shared_info = StackBuf::<MAX_SHARED_INFO>::new();
|
||||
write_header(
|
||||
&mut shared_info,
|
||||
tag::SEQUENCE,
|
||||
wrap_alg + kari.ukm.explicit_len() + tlv_len(tlv_len(4)),
|
||||
);
|
||||
write_alg_id(&mut shared_info, oid::AES256_WRAP, kari.wrap);
|
||||
write_explicit_ukm(&mut shared_info, 0, ukm);
|
||||
write_header(&mut shared_info, tag::context_constructed(2), tlv_len(4));
|
||||
write_tlv(
|
||||
&mut shared_info,
|
||||
tag::OCTET_STRING,
|
||||
&((CEK_LEN * 8) as u32).to_be_bytes(),
|
||||
);
|
||||
let shared_info = shared_info
|
||||
.as_slice()
|
||||
.ok_or(EncryptError::MalformedMessage)?;
|
||||
let mut kek = Zeroizing::new([0u8; CEK_LEN]);
|
||||
match kari.kdf {
|
||||
KariKdf::X963(hash) => x963(hash, agreement.shared(), shared_info, kek.as_mut())?,
|
||||
KariKdf::Hkdf => HkdfHash::Sha256.derive(
|
||||
ukm.unwrap_or_default(),
|
||||
&[agreement.shared()],
|
||||
&[shared_info],
|
||||
kek.as_mut(),
|
||||
)?,
|
||||
}
|
||||
|
||||
write_header(
|
||||
out,
|
||||
tag::context_constructed(1),
|
||||
kind.content_len(rid.len()),
|
||||
);
|
||||
write_small_integer(out, 3);
|
||||
write_header(out, tag::context_constructed(0), kari.originator_len());
|
||||
write_header(
|
||||
out,
|
||||
tag::context_constructed(1),
|
||||
alg_id_len(kari.originator_oid, 0) + bit_string_len(kari.curve.public_len()),
|
||||
);
|
||||
write_alg_id(out, kari.originator_oid, &[]);
|
||||
write_bit_string_header(out, kari.curve.public_len());
|
||||
out.extend_from_slice(agreement.public());
|
||||
write_explicit_ukm(out, 1, ukm);
|
||||
write_header(out, tag::SEQUENCE, tlv_len(kari.scheme.len()) + wrap_alg);
|
||||
write_tlv(out, tag::OID, kari.scheme);
|
||||
write_alg_id(out, oid::AES256_WRAP, kari.wrap);
|
||||
write_header(
|
||||
out,
|
||||
tag::SEQUENCE,
|
||||
tlv_len(rid.len() + tlv_len(WRAPPED_LEN)),
|
||||
);
|
||||
write_header(out, tag::SEQUENCE, rid.len() + tlv_len(WRAPPED_LEN));
|
||||
out.extend_from_slice(rid);
|
||||
write_header(out, tag::OCTET_STRING, WRAPPED_LEN);
|
||||
let start = out.len();
|
||||
out.resize(start + WRAPPED_LEN, 0);
|
||||
AesCipher::new(kek.as_ref())?.wrap(cek, out.get_mut(start..).unwrap_or_default())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn check_profile(
|
||||
recipients: &[SmimeRecipient],
|
||||
profile: Profile,
|
||||
) -> Result<(), ProfileError> {
|
||||
if profile == Profile::PostQuantum
|
||||
&& recipients
|
||||
.iter()
|
||||
.any(|r| !matches!(r.key, SmimeKey::MlKem(_)))
|
||||
{
|
||||
return Err(ProfileError::NoPostQuantumKey);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn encrypt(
|
||||
message: &Entity<'_>,
|
||||
recipients: &[SmimeRecipient],
|
||||
options: &EncryptOptions,
|
||||
rng: &mut impl Rng,
|
||||
) -> Result<(Vec<u8>, Option<EncryptWarning>), EncryptError> {
|
||||
if recipients.is_empty() {
|
||||
return Err(EncryptError::NoRecipients);
|
||||
}
|
||||
check_profile(recipients, options.profile)?;
|
||||
let content = if options.profile == Profile::Compatible {
|
||||
Content::Cbc
|
||||
} else {
|
||||
Content::Gcm
|
||||
};
|
||||
let inner_len = message.inner_len();
|
||||
let content_len = match content {
|
||||
Content::Cbc => cbc_pkcs7_padded_len(inner_len),
|
||||
Content::Gcm => inner_len,
|
||||
};
|
||||
let ris: usize = recipients
|
||||
.iter()
|
||||
.map(|r| RecipientKind::new(&r.key, options).len(r.issuer_and_serial.len()))
|
||||
.sum();
|
||||
let version = if content == Content::Gcm {
|
||||
0
|
||||
} else if recipients
|
||||
.iter()
|
||||
.any(|r| matches!(r.key, SmimeKey::MlKem(_)))
|
||||
{
|
||||
3
|
||||
} else if recipients
|
||||
.iter()
|
||||
.any(|r| !matches!(r.key, SmimeKey::Rsa { .. }))
|
||||
{
|
||||
2
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let (content_oid, params_len, type_oid, smime_headers) = match content {
|
||||
Content::Cbc => (
|
||||
oid::AES256_CBC,
|
||||
tlv_len(BLOCK_LEN),
|
||||
oid::ENVELOPED_DATA,
|
||||
SMIME_HEADERS_ENVELOPED,
|
||||
),
|
||||
Content::Gcm => (
|
||||
oid::AES256_GCM,
|
||||
tlv_len(tlv_len(GCM_NONCE_LEN) + small_integer_len(GCM_TAG_LEN as u32)),
|
||||
oid::AUTH_ENVELOPED_DATA,
|
||||
SMIME_HEADERS_AUTH,
|
||||
),
|
||||
};
|
||||
let eci = tlv_len(oid::DATA.len()) + alg_id_len(content_oid, params_len) + tlv_len(content_len);
|
||||
let body = small_integer_len(version)
|
||||
+ tlv_len(ris)
|
||||
+ tlv_len(eci)
|
||||
+ match content {
|
||||
Content::Cbc => 0,
|
||||
Content::Gcm => tlv_len(GCM_TAG_LEN),
|
||||
};
|
||||
let content_info = tlv_len(type_oid.len()) + tlv_len(tlv_len(body));
|
||||
let total = tlv_len(content_info);
|
||||
|
||||
let mut cek = Zeroizing::new([0u8; CEK_LEN]);
|
||||
rng.fill(cek.as_mut())?;
|
||||
let mut iv = [0u8; BLOCK_LEN];
|
||||
let iv = match content {
|
||||
Content::Cbc => &mut iv[..],
|
||||
Content::Gcm => &mut iv[..GCM_NONCE_LEN],
|
||||
};
|
||||
rng.fill(iv)?;
|
||||
|
||||
let mut scratch = Vec::with_capacity(total);
|
||||
write_header(&mut scratch, tag::SEQUENCE, content_info);
|
||||
write_tlv(&mut scratch, tag::OID, type_oid);
|
||||
write_header(&mut scratch, tag::context_constructed(0), tlv_len(body));
|
||||
write_header(&mut scratch, tag::SEQUENCE, body);
|
||||
write_small_integer(&mut scratch, version);
|
||||
write_header(&mut scratch, tag::SET, ris);
|
||||
for recipient in recipients {
|
||||
let start = scratch.len();
|
||||
let kind = RecipientKind::new(&recipient.key, options);
|
||||
let rid = &recipient.issuer_and_serial;
|
||||
write_ri(&mut scratch, &kind, rid, cek.as_ref(), rng)?;
|
||||
if scratch.len() - start != kind.len(rid.len()) {
|
||||
return Err(EncryptError::MalformedMessage);
|
||||
}
|
||||
}
|
||||
write_header(&mut scratch, tag::SEQUENCE, eci);
|
||||
write_tlv(&mut scratch, tag::OID, oid::DATA);
|
||||
write_header(
|
||||
&mut scratch,
|
||||
tag::SEQUENCE,
|
||||
tlv_len(content_oid.len()) + params_len,
|
||||
);
|
||||
write_tlv(&mut scratch, tag::OID, content_oid);
|
||||
match content {
|
||||
Content::Cbc => write_tlv(&mut scratch, tag::OCTET_STRING, iv),
|
||||
Content::Gcm => {
|
||||
write_header(
|
||||
&mut scratch,
|
||||
tag::SEQUENCE,
|
||||
tlv_len(GCM_NONCE_LEN) + small_integer_len(GCM_TAG_LEN as u32),
|
||||
);
|
||||
write_tlv(&mut scratch, tag::OCTET_STRING, iv);
|
||||
write_small_integer(&mut scratch, GCM_TAG_LEN as u32);
|
||||
}
|
||||
}
|
||||
write_header(&mut scratch, tag::context(0), content_len);
|
||||
let start = scratch.len();
|
||||
message.write_inner(&mut scratch);
|
||||
match content {
|
||||
Content::Cbc => {
|
||||
write_pkcs7_padding(&mut scratch, inner_len);
|
||||
let mut cbc_iv = [0u8; BLOCK_LEN];
|
||||
cbc_iv.copy_from_slice(iv);
|
||||
cbc_encrypt_padded_in_place(cek.as_ref(), cbc_iv, &mut scratch[start..])?;
|
||||
}
|
||||
Content::Gcm => {
|
||||
let mut nonce = [0u8; GCM_NONCE_LEN];
|
||||
nonce.copy_from_slice(iv);
|
||||
let mac =
|
||||
GcmKey::new(cek.as_ref())?.seal_in_place(nonce, &[], &mut scratch[start..])?;
|
||||
write_tlv(&mut scratch, tag::OCTET_STRING, &mac);
|
||||
}
|
||||
}
|
||||
if scratch.len() != total {
|
||||
return Err(EncryptError::MalformedMessage);
|
||||
}
|
||||
|
||||
let mut out = Vec::with_capacity(
|
||||
message.outer_len() + smime_headers.len() + MIME.encoded_len(scratch.len()),
|
||||
);
|
||||
message.write_outer(&mut out);
|
||||
out.extend_from_slice(smime_headers);
|
||||
MIME.encode_append(&scratch, &mut out);
|
||||
let warning = (scratch.len() > NSS_SIZE_LIMIT).then_some(EncryptWarning::ExceedsNssLimit);
|
||||
Ok((out, warning))
|
||||
}
|
||||
8
crates/crypto/src/cms/mod.rs
Normal file
8
crates/crypto/src/cms/mod.rs
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub(crate) mod envelope;
|
||||
pub(crate) mod signed;
|
||||
322
crates/crypto/src/cms/signed.rs
Normal file
322
crates/crypto/src/cms/signed.rs
Normal file
|
|
@ -0,0 +1,322 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aws_lc_rs::digest::Digest;
|
||||
|
||||
use crate::{
|
||||
backend::{hash::HashAlgorithm, verify::SignatureScheme},
|
||||
der::{
|
||||
DerError, oid,
|
||||
reader::{Encoding, Reader, Tlv},
|
||||
tag,
|
||||
},
|
||||
error::VerifyError,
|
||||
mime::{Canonical, Sink},
|
||||
x509::{
|
||||
cert::{AlgorithmId, Certificate, digest_oid_hash, signature_scheme},
|
||||
time::parse_time,
|
||||
},
|
||||
};
|
||||
|
||||
const CERTIFICATES: u8 = tag::context_constructed(0);
|
||||
const CRLS: u8 = tag::context_constructed(1);
|
||||
const SIGNED_ATTRS: u8 = tag::context_constructed(0);
|
||||
const UNSIGNED_ATTRS: u8 = tag::context_constructed(1);
|
||||
const SID_KEY_ID: u8 = tag::context(0);
|
||||
const ECONTENT: u8 = tag::context_constructed(0);
|
||||
const CONSTRUCTED_OCTET_STRING: u8 = tag::OCTET_STRING | tag::CONSTRUCTED;
|
||||
const PREF_ISSUER_SERIAL: u8 = tag::context_constructed(0);
|
||||
const PREF_SUBJECT_KEY_ID: u8 = tag::context(2);
|
||||
const MAX_SIGNERS: usize = 8;
|
||||
const MAX_FUTURE_SKEW: u64 = 86_400;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum KeyPreference<'x> {
|
||||
IssuerSerial { issuer: &'x [u8], serial: &'x [u8] },
|
||||
SubjectKeyId(&'x [u8]),
|
||||
}
|
||||
|
||||
impl KeyPreference<'_> {
|
||||
pub(crate) fn matches(&self, cert: &Certificate<'_>) -> bool {
|
||||
match self {
|
||||
KeyPreference::IssuerSerial { issuer, serial } => {
|
||||
cert.issuer == *issuer && cert.serial == *serial
|
||||
}
|
||||
KeyPreference::SubjectKeyId(id) => cert.extensions.ski == Some(*id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct SignedData<'x> {
|
||||
pub certificates: &'x [u8],
|
||||
pub signer: Option<Certificate<'x>>,
|
||||
pub verified: bool,
|
||||
pub signing_time: Option<u64>,
|
||||
pub capabilities: Option<&'x [u8]>,
|
||||
pub preference: Option<KeyPreference<'x>>,
|
||||
}
|
||||
|
||||
fn certificate_set(set: &[u8]) -> impl Iterator<Item = Certificate<'_>> {
|
||||
Reader::new(set)
|
||||
.map_while(Result::ok)
|
||||
.filter(|tlv| tlv.tag == tag::SEQUENCE)
|
||||
.filter_map(|tlv| Certificate::parse_tlv(tlv).ok())
|
||||
}
|
||||
|
||||
impl<'x> SignedData<'x> {
|
||||
pub(crate) fn certificates(&self) -> impl Iterator<Item = Certificate<'x>> + use<'x> {
|
||||
certificate_set(self.certificates)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum Content<'x> {
|
||||
Detached(&'x [u8]),
|
||||
Encapsulated,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Attributes<'x> {
|
||||
content_type: Option<&'x [u8]>,
|
||||
message_digest: Option<&'x [u8]>,
|
||||
signing_time: Option<u64>,
|
||||
capabilities: Option<&'x [u8]>,
|
||||
preference: Option<KeyPreference<'x>>,
|
||||
}
|
||||
|
||||
struct SignerInfo<'x> {
|
||||
sid: Tlv<'x>,
|
||||
digest: HashAlgorithm,
|
||||
signed_attrs: Option<Tlv<'x>>,
|
||||
algorithm: AlgorithmId<'x>,
|
||||
signature: &'x [u8],
|
||||
}
|
||||
|
||||
fn hash_econtent(econtent: Tlv<'_>, hasher: &mut impl Sink) -> Result<(), DerError> {
|
||||
match econtent.tag {
|
||||
tag::OCTET_STRING => {
|
||||
hasher.put(econtent.content);
|
||||
Ok(())
|
||||
}
|
||||
CONSTRUCTED_OCTET_STRING => {
|
||||
for chunk in econtent.reader() {
|
||||
hash_econtent(chunk?, hasher)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(DerError::UnexpectedTag),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_preference(value: Tlv<'_>) -> Option<KeyPreference<'_>> {
|
||||
match value.tag {
|
||||
PREF_ISSUER_SERIAL | tag::SEQUENCE => {
|
||||
let mut reader = value.reader();
|
||||
let issuer = reader.read_tag(tag::SEQUENCE).ok()?.raw;
|
||||
let serial = reader.read_content(tag::INTEGER).ok()?;
|
||||
Some(KeyPreference::IssuerSerial { issuer, serial })
|
||||
}
|
||||
PREF_SUBJECT_KEY_ID => Some(KeyPreference::SubjectKeyId(value.content)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_attributes(signed_attrs: Tlv<'_>) -> Result<Attributes<'_>, DerError> {
|
||||
let mut attrs = Attributes::default();
|
||||
for attribute in signed_attrs.reader() {
|
||||
let mut attribute = attribute?.expect(tag::SEQUENCE)?.reader();
|
||||
let id = attribute.read_content(tag::OID)?;
|
||||
let mut values = attribute.read_tag(tag::SET)?.reader();
|
||||
let value = values.read()?;
|
||||
match id {
|
||||
oid::CONTENT_TYPE => attrs.content_type = Some(value.expect(tag::OID)?.content),
|
||||
oid::MESSAGE_DIGEST => {
|
||||
attrs.message_digest = Some(value.expect(tag::OCTET_STRING)?.content)
|
||||
}
|
||||
oid::SIGNING_TIME => attrs.signing_time = Some(parse_time(value)?),
|
||||
oid::SMIME_CAPABILITIES => {
|
||||
attrs.capabilities = Some(value.expect(tag::SEQUENCE)?.content)
|
||||
}
|
||||
oid::ENCRYPTION_KEY_PREFERENCE => attrs.preference = parse_preference(value),
|
||||
oid::MS_ENCRYPTION_KEY_PREFERENCE => {
|
||||
attrs.preference = attrs.preference.or_else(|| parse_preference(value))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(attrs)
|
||||
}
|
||||
|
||||
fn parse_signer_info(tlv: Tlv<'_>) -> Result<SignerInfo<'_>, VerifyError> {
|
||||
let mut info = tlv.expect(tag::SEQUENCE)?.reader();
|
||||
info.read_small_unsigned()?;
|
||||
let sid = info.read()?;
|
||||
let digest = AlgorithmId::parse(info.read()?)?;
|
||||
let digest = digest_oid_hash(digest.oid)
|
||||
.filter(|hash| {
|
||||
matches!(
|
||||
hash,
|
||||
HashAlgorithm::Sha256 | HashAlgorithm::Sha384 | HashAlgorithm::Sha512
|
||||
)
|
||||
})
|
||||
.ok_or(VerifyError::UnsupportedAlgorithm)?;
|
||||
let signed_attrs = info.read_optional(SIGNED_ATTRS)?;
|
||||
let algorithm = AlgorithmId::parse(info.read()?)?;
|
||||
let signature = info.read_content(tag::OCTET_STRING)?;
|
||||
info.read_optional(UNSIGNED_ATTRS)?;
|
||||
info.finish()?;
|
||||
Ok(SignerInfo {
|
||||
sid,
|
||||
digest,
|
||||
signed_attrs,
|
||||
algorithm,
|
||||
signature,
|
||||
})
|
||||
}
|
||||
|
||||
fn find_signer<'x>(certificates: &'x [u8], sid: &Tlv<'_>) -> Option<Certificate<'x>> {
|
||||
let preference = match sid.tag {
|
||||
tag::SEQUENCE => parse_preference(*sid)?,
|
||||
SID_KEY_ID => KeyPreference::SubjectKeyId(sid.content),
|
||||
_ => return None,
|
||||
};
|
||||
certificate_set(certificates).find(|cert| preference.matches(cert))
|
||||
}
|
||||
|
||||
fn scheme_for(info: &SignerInfo<'_>, signer: &Certificate<'_>) -> Option<SignatureScheme> {
|
||||
let scheme = if info.algorithm.oid == oid::RSA_ENCRYPTION {
|
||||
SignatureScheme::RsaPkcs1(info.digest)
|
||||
} else {
|
||||
signature_scheme(&info.algorithm, &signer.spki)?
|
||||
};
|
||||
match scheme {
|
||||
SignatureScheme::RsaPkcs1(HashAlgorithm::Sha1)
|
||||
| SignatureScheme::Ecdsa(_, HashAlgorithm::Sha1) => None,
|
||||
scheme => Some(scheme),
|
||||
}
|
||||
}
|
||||
|
||||
struct DigestCache {
|
||||
entries: [Option<(HashAlgorithm, Digest)>; 3],
|
||||
}
|
||||
|
||||
impl DigestCache {
|
||||
fn get(
|
||||
&mut self,
|
||||
hash: HashAlgorithm,
|
||||
compute: impl FnOnce(HashAlgorithm) -> Result<Digest, DerError>,
|
||||
) -> Result<Digest, DerError> {
|
||||
if let Some((_, digest)) = self.entries.iter().flatten().find(|(h, _)| *h == hash) {
|
||||
return Ok(*digest);
|
||||
}
|
||||
let digest = compute(hash)?;
|
||||
if let Some(slot) = self.entries.iter_mut().find(|slot| slot.is_none()) {
|
||||
*slot = Some((hash, digest));
|
||||
}
|
||||
Ok(digest)
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_signer(
|
||||
info: &SignerInfo<'_>,
|
||||
signer: &Certificate<'_>,
|
||||
attrs: &Attributes<'_>,
|
||||
econtent_type: &[u8],
|
||||
digest: &Digest,
|
||||
now: u64,
|
||||
) -> bool {
|
||||
let Some(scheme) = scheme_for(info, signer) else {
|
||||
return false;
|
||||
};
|
||||
match info.signed_attrs {
|
||||
Some(signed_attrs) => {
|
||||
if signed_attrs.encoding != Encoding::Definite
|
||||
|| attrs.content_type != Some(econtent_type)
|
||||
|| attrs.message_digest != Some(digest.as_ref())
|
||||
|| attrs
|
||||
.signing_time
|
||||
.is_some_and(|time| time > now + MAX_FUTURE_SKEW)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let mut der = Vec::with_capacity(signed_attrs.raw.len());
|
||||
der.push(tag::SET);
|
||||
der.extend_from_slice(signed_attrs.raw.get(1..).unwrap_or_default());
|
||||
scheme.verify(signer.spki.key, &der, info.signature).is_ok()
|
||||
}
|
||||
None => scheme
|
||||
.verify_digest(signer.spki.key, digest, info.signature)
|
||||
.is_ok(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn verify<'x>(
|
||||
der: &'x [u8],
|
||||
content: Content<'_>,
|
||||
now: u64,
|
||||
) -> Result<SignedData<'x>, VerifyError> {
|
||||
let mut content_info = Reader::new(der).read_sequence()?;
|
||||
if content_info.read_content(tag::OID)? != oid::SIGNED_DATA {
|
||||
return Err(VerifyError::NotSigned);
|
||||
}
|
||||
let mut signed = content_info
|
||||
.read_tag(tag::context_constructed(0))?
|
||||
.reader()
|
||||
.read_sequence()?;
|
||||
signed.read_small_unsigned()?;
|
||||
signed.read_tag(tag::SET)?;
|
||||
let mut encap = signed.read_sequence()?;
|
||||
let econtent_type = encap.read_content(tag::OID)?;
|
||||
let econtent = encap
|
||||
.read_optional(ECONTENT)?
|
||||
.map(|explicit| explicit.reader().read())
|
||||
.transpose()?;
|
||||
let certificates = signed
|
||||
.read_optional(CERTIFICATES)?
|
||||
.map_or(&[][..], |set| set.content);
|
||||
signed.read_optional(CRLS)?;
|
||||
let signer_infos = signed.read_tag(tag::SET)?;
|
||||
|
||||
let mut cache = DigestCache {
|
||||
entries: [None, None, None],
|
||||
};
|
||||
let compute = |hash: HashAlgorithm| -> Result<Digest, DerError> {
|
||||
let mut hasher = hash.hasher();
|
||||
match (&content, econtent) {
|
||||
(Content::Detached(data), None) => Canonical::new(&mut hasher).put(data),
|
||||
(Content::Encapsulated, Some(econtent)) => hash_econtent(econtent, &mut hasher)?,
|
||||
_ => return Err(DerError::UnexpectedTag),
|
||||
}
|
||||
Ok(hasher.finish())
|
||||
};
|
||||
|
||||
let mut first = None;
|
||||
for info in signer_infos.reader().take(MAX_SIGNERS) {
|
||||
let info = parse_signer_info(info?)?;
|
||||
let Some(signer) = find_signer(certificates, &info.sid) else {
|
||||
continue;
|
||||
};
|
||||
let attrs = match info.signed_attrs {
|
||||
Some(signed_attrs) => parse_attributes(signed_attrs)?,
|
||||
None => Attributes::default(),
|
||||
};
|
||||
let digest = cache.get(info.digest, compute)?;
|
||||
let verified = verify_signer(&info, &signer, &attrs, econtent_type, &digest, now);
|
||||
let result = SignedData {
|
||||
certificates,
|
||||
signer: Some(signer),
|
||||
verified,
|
||||
signing_time: attrs.signing_time,
|
||||
capabilities: attrs.capabilities,
|
||||
preference: attrs.preference,
|
||||
};
|
||||
if verified {
|
||||
return Ok(result);
|
||||
}
|
||||
first.get_or_insert(result);
|
||||
}
|
||||
first.ok_or(VerifyError::UnknownSigner)
|
||||
}
|
||||
44
crates/crypto/src/der/mod.rs
Normal file
44
crates/crypto/src/der/mod.rs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub(crate) mod oid;
|
||||
pub(crate) mod reader;
|
||||
pub(crate) mod writer;
|
||||
|
||||
pub(crate) mod tag {
|
||||
pub(crate) const BOOLEAN: u8 = 0x01;
|
||||
pub(crate) const INTEGER: u8 = 0x02;
|
||||
pub(crate) const BIT_STRING: u8 = 0x03;
|
||||
pub(crate) const OCTET_STRING: u8 = 0x04;
|
||||
pub(crate) const NULL: u8 = 0x05;
|
||||
pub(crate) const OID: u8 = 0x06;
|
||||
pub(crate) const UTF8_STRING: u8 = 0x0C;
|
||||
pub(crate) const UTC_TIME: u8 = 0x17;
|
||||
pub(crate) const GENERALIZED_TIME: u8 = 0x18;
|
||||
pub(crate) const SEQUENCE: u8 = 0x30;
|
||||
pub(crate) const SET: u8 = 0x31;
|
||||
pub(crate) const CONSTRUCTED: u8 = 0x20;
|
||||
pub(crate) const CONTEXT: u8 = 0x80;
|
||||
|
||||
pub(crate) const fn context(number: u8) -> u8 {
|
||||
CONTEXT | number
|
||||
}
|
||||
|
||||
pub(crate) const fn context_constructed(number: u8) -> u8 {
|
||||
CONTEXT | CONSTRUCTED | number
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DerError {
|
||||
Truncated,
|
||||
UnexpectedTag,
|
||||
InvalidLength,
|
||||
UnsupportedTag,
|
||||
TooDeep,
|
||||
TrailingData,
|
||||
InvalidValue,
|
||||
}
|
||||
98
crates/crypto/src/der/oid.rs
Normal file
98
crates/crypto/src/der/oid.rs
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
macro_rules! oids {
|
||||
($($name:ident = [$($byte:expr),*];)*) => {
|
||||
$(pub(crate) const $name: &[u8] = &[$($byte),*];)*
|
||||
};
|
||||
}
|
||||
|
||||
oids! {
|
||||
RSA_ENCRYPTION = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01];
|
||||
RSAES_OAEP = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x07];
|
||||
MGF1 = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x08];
|
||||
RSASSA_PSS = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0A];
|
||||
SHA1_WITH_RSA = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05];
|
||||
SHA256_WITH_RSA = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B];
|
||||
SHA384_WITH_RSA = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0C];
|
||||
SHA512_WITH_RSA = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0D];
|
||||
EC_PUBLIC_KEY = [0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01];
|
||||
ECDSA_SHA1 = [0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x01];
|
||||
ECDSA_SHA256 = [0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02];
|
||||
ECDSA_SHA384 = [0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x03];
|
||||
ECDSA_SHA512 = [0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x04];
|
||||
P256 = [0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07];
|
||||
P384 = [0x2B, 0x81, 0x04, 0x00, 0x22];
|
||||
P521 = [0x2B, 0x81, 0x04, 0x00, 0x23];
|
||||
BRAINPOOL_PREFIX = [0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01];
|
||||
X25519 = [0x2B, 0x65, 0x6E];
|
||||
X448 = [0x2B, 0x65, 0x6F];
|
||||
ED25519 = [0x2B, 0x65, 0x70];
|
||||
ED448 = [0x2B, 0x65, 0x71];
|
||||
ML_KEM_512 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, 0x01];
|
||||
ML_KEM_768 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, 0x02];
|
||||
ML_KEM_1024 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, 0x03];
|
||||
ML_DSA_44 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x11];
|
||||
ML_DSA_65 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x12];
|
||||
ML_DSA_87 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x03, 0x13];
|
||||
SHA1 = [0x2B, 0x0E, 0x03, 0x02, 0x1A];
|
||||
SHA224 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04];
|
||||
SHA256 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01];
|
||||
SHA384 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02];
|
||||
SHA512 = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03];
|
||||
AES128_CBC = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x02];
|
||||
AES192_CBC = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x16];
|
||||
AES256_CBC = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2A];
|
||||
AES128_GCM = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x06];
|
||||
AES192_GCM = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x1A];
|
||||
AES256_GCM = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2E];
|
||||
AES128_WRAP = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x05];
|
||||
AES256_WRAP = [0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x2D];
|
||||
CHACHA20_POLY1305 = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x10, 0x03, 0x12];
|
||||
ECDH_SHA256_KDF = [0x2B, 0x81, 0x04, 0x01, 0x0B, 0x01];
|
||||
ECDH_SHA384_KDF = [0x2B, 0x81, 0x04, 0x01, 0x0B, 0x02];
|
||||
ECDH_SHA512_KDF = [0x2B, 0x81, 0x04, 0x01, 0x0B, 0x03];
|
||||
ECDH_HKDF_SHA256 = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x10, 0x03, 0x13];
|
||||
HKDF_SHA256 = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x10, 0x03, 0x1C];
|
||||
ORI_KEM = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x10, 0x0D, 0x03];
|
||||
DATA = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01];
|
||||
SIGNED_DATA = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02];
|
||||
ENVELOPED_DATA = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x03];
|
||||
AUTH_ENVELOPED_DATA = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x10, 0x01, 0x17];
|
||||
COMMON_NAME = [0x55, 0x04, 0x03];
|
||||
ORGANIZATION = [0x55, 0x04, 0x0A];
|
||||
EMAIL_ADDRESS = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x01];
|
||||
CONTENT_TYPE = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x03];
|
||||
MESSAGE_DIGEST = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x04];
|
||||
SIGNING_TIME = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x05];
|
||||
SMIME_CAPABILITIES = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x0F];
|
||||
ENCRYPTION_KEY_PREFERENCE = [0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x10, 0x02, 0x0B];
|
||||
SMTP_UTF8_MAILBOX = [0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x08, 0x09];
|
||||
EMAIL_PROTECTION = [0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x04];
|
||||
ANY_EXTENDED_KEY_USAGE = [0x55, 0x1D, 0x25, 0x00];
|
||||
EXT_SUBJECT_KEY_ID = [0x55, 0x1D, 0x0E];
|
||||
EXT_KEY_USAGE = [0x55, 0x1D, 0x0F];
|
||||
EXT_SUBJECT_ALT_NAME = [0x55, 0x1D, 0x11];
|
||||
EXT_BASIC_CONSTRAINTS = [0x55, 0x1D, 0x13];
|
||||
EXT_CRL_NUMBER = [0x55, 0x1D, 0x14];
|
||||
EXT_REASON_CODE = [0x55, 0x1D, 0x15];
|
||||
EXT_NAME_CONSTRAINTS = [0x55, 0x1D, 0x1E];
|
||||
EXT_CRL_DISTRIBUTION_POINTS = [0x55, 0x1D, 0x1F];
|
||||
EXT_CERTIFICATE_POLICIES = [0x55, 0x1D, 0x20];
|
||||
EXT_AUTHORITY_KEY_ID = [0x55, 0x1D, 0x23];
|
||||
EXT_EXTENDED_KEY_USAGE = [0x55, 0x1D, 0x25];
|
||||
EXT_AUTHORITY_INFO_ACCESS = [0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01];
|
||||
CA_ISSUERS = [0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x02];
|
||||
EXT_ISSUING_DISTRIBUTION_POINT = [0x55, 0x1D, 0x1C];
|
||||
EXT_DELTA_CRL_INDICATOR = [0x55, 0x1D, 0x1B];
|
||||
EXT_FRESHEST_CRL = [0x55, 0x1D, 0x2E];
|
||||
EXT_INVALIDITY_DATE = [0x55, 0x1D, 0x18];
|
||||
EXT_ISSUER_ALT_NAME = [0x55, 0x1D, 0x12];
|
||||
EXT_POLICY_CONSTRAINTS = [0x55, 0x1D, 0x24];
|
||||
EXT_INHIBIT_ANY_POLICY = [0x55, 0x1D, 0x36];
|
||||
EXT_POLICY_MAPPINGS = [0x55, 0x1D, 0x21];
|
||||
MS_ENCRYPTION_KEY_PREFERENCE = [0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x10, 0x04];
|
||||
}
|
||||
198
crates/crypto/src/der/reader.rs
Normal file
198
crates/crypto/src/der/reader.rs
Normal file
|
|
@ -0,0 +1,198 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::{DerError, tag};
|
||||
|
||||
const MAX_DEPTH: usize = 32;
|
||||
const HIGH_TAG_NUMBER: u8 = 0x1F;
|
||||
const INDEFINITE_LENGTH: u8 = 0x80;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Encoding {
|
||||
Definite,
|
||||
Indefinite,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Tlv<'x> {
|
||||
pub tag: u8,
|
||||
pub content: &'x [u8],
|
||||
pub raw: &'x [u8],
|
||||
pub encoding: Encoding,
|
||||
}
|
||||
|
||||
impl<'x> Tlv<'x> {
|
||||
pub(crate) fn reader(&self) -> Reader<'x> {
|
||||
Reader::new(self.content)
|
||||
}
|
||||
|
||||
pub(crate) fn expect(self, tag: u8) -> Result<Self, DerError> {
|
||||
if self.tag == tag {
|
||||
Ok(self)
|
||||
} else {
|
||||
Err(DerError::UnexpectedTag)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Reader<'x> {
|
||||
data: &'x [u8],
|
||||
}
|
||||
|
||||
impl<'x> Reader<'x> {
|
||||
pub(crate) const fn new(data: &'x [u8]) -> Self {
|
||||
Reader { data }
|
||||
}
|
||||
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.data.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn peek_tag(&self) -> Option<u8> {
|
||||
self.data.first().copied()
|
||||
}
|
||||
|
||||
pub(crate) fn finish(&self) -> Result<(), DerError> {
|
||||
if self.data.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(DerError::TrailingData)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn read(&mut self) -> Result<Tlv<'x>, DerError> {
|
||||
let (tlv, rest) = parse_tlv(self.data, 0)?;
|
||||
self.data = rest;
|
||||
Ok(tlv)
|
||||
}
|
||||
|
||||
pub(crate) fn read_tag(&mut self, tag: u8) -> Result<Tlv<'x>, DerError> {
|
||||
self.read()?.expect(tag)
|
||||
}
|
||||
|
||||
pub(crate) fn read_optional(&mut self, tag: u8) -> Result<Option<Tlv<'x>>, DerError> {
|
||||
if self.peek_tag() == Some(tag) {
|
||||
self.read().map(Some)
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn read_sequence(&mut self) -> Result<Reader<'x>, DerError> {
|
||||
self.read_tag(tag::SEQUENCE).map(|tlv| tlv.reader())
|
||||
}
|
||||
|
||||
pub(crate) fn read_content(&mut self, tag: u8) -> Result<&'x [u8], DerError> {
|
||||
self.read_tag(tag).map(|tlv| tlv.content)
|
||||
}
|
||||
|
||||
pub(crate) fn read_small_unsigned(&mut self) -> Result<u32, DerError> {
|
||||
let content = match self.read_content(tag::INTEGER)? {
|
||||
[0, rest @ ..] if !rest.is_empty() => rest,
|
||||
[first, ..] if first & 0x80 != 0 => return Err(DerError::InvalidValue),
|
||||
[] => return Err(DerError::InvalidValue),
|
||||
content => content,
|
||||
};
|
||||
if content.len() > 4 {
|
||||
return Err(DerError::InvalidValue);
|
||||
}
|
||||
Ok(content
|
||||
.iter()
|
||||
.fold(0u32, |acc, b| (acc << 8) | u32::from(*b)))
|
||||
}
|
||||
|
||||
pub(crate) fn read_bool_default_false(&mut self) -> Result<bool, DerError> {
|
||||
match self.read_optional(tag::BOOLEAN)? {
|
||||
Some(tlv) => match tlv.content {
|
||||
[value] => Ok(*value != 0),
|
||||
_ => Err(DerError::InvalidValue),
|
||||
},
|
||||
None => Ok(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'x> Iterator for Reader<'x> {
|
||||
type Item = Result<Tlv<'x>, DerError>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.data.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let result = self.read();
|
||||
if result.is_err() {
|
||||
self.data = &[];
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_tlv(data: &[u8], depth: usize) -> Result<(Tlv<'_>, &[u8]), DerError> {
|
||||
let [tag, len_byte, after_len @ ..] = data else {
|
||||
return Err(DerError::Truncated);
|
||||
};
|
||||
if tag & HIGH_TAG_NUMBER == HIGH_TAG_NUMBER {
|
||||
return Err(DerError::UnsupportedTag);
|
||||
}
|
||||
if *len_byte == INDEFINITE_LENGTH {
|
||||
if tag & tag::CONSTRUCTED == 0 {
|
||||
return Err(DerError::InvalidLength);
|
||||
}
|
||||
if depth >= MAX_DEPTH {
|
||||
return Err(DerError::TooDeep);
|
||||
}
|
||||
let mut rest = after_len;
|
||||
loop {
|
||||
match rest {
|
||||
[0, 0, after_eoc @ ..] => {
|
||||
let content_len = after_len.len() - rest.len();
|
||||
let raw_len = data.len() - after_eoc.len();
|
||||
return Ok((
|
||||
Tlv {
|
||||
tag: *tag,
|
||||
content: &after_len[..content_len],
|
||||
raw: &data[..raw_len],
|
||||
encoding: Encoding::Indefinite,
|
||||
},
|
||||
after_eoc,
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
let (_, next) = parse_tlv(rest, depth + 1)?;
|
||||
rest = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let (len, body) = if len_byte & 0x80 == 0 {
|
||||
(usize::from(*len_byte), after_len)
|
||||
} else {
|
||||
let count = usize::from(len_byte & 0x7F);
|
||||
if count == 0 || count > 4 {
|
||||
return Err(DerError::InvalidLength);
|
||||
}
|
||||
let (len_bytes, body) = after_len
|
||||
.split_at_checked(count)
|
||||
.ok_or(DerError::Truncated)?;
|
||||
let len = len_bytes
|
||||
.iter()
|
||||
.fold(0usize, |acc, b| (acc << 8) | usize::from(*b));
|
||||
(len, body)
|
||||
};
|
||||
let (content, rest) = body.split_at_checked(len).ok_or(DerError::Truncated)?;
|
||||
let raw_len = data.len() - rest.len();
|
||||
Ok((
|
||||
Tlv {
|
||||
tag: *tag,
|
||||
content,
|
||||
raw: &data[..raw_len],
|
||||
encoding: Encoding::Definite,
|
||||
},
|
||||
rest,
|
||||
))
|
||||
}
|
||||
146
crates/crypto/src/der/writer.rs
Normal file
146
crates/crypto/src/der/writer.rs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::tag;
|
||||
use crate::mime::Sink;
|
||||
|
||||
pub(crate) const fn length_len(len: usize) -> usize {
|
||||
if len < 0x80 {
|
||||
1
|
||||
} else if len < 0x100 {
|
||||
2
|
||||
} else if len < 0x1_0000 {
|
||||
3
|
||||
} else if len < 0x100_0000 {
|
||||
4
|
||||
} else {
|
||||
5
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn tlv_len(content_len: usize) -> usize {
|
||||
1 + length_len(content_len) + content_len
|
||||
}
|
||||
|
||||
pub(crate) fn write_header<S: Sink + ?Sized>(out: &mut S, tag: u8, len: usize) {
|
||||
match length_len(len) {
|
||||
1 => out.put(&[tag, len as u8]),
|
||||
n => {
|
||||
let bytes = (len as u64).to_be_bytes();
|
||||
out.put(&[tag, 0x80 | (n - 1) as u8]);
|
||||
out.put(&bytes[bytes.len() - (n - 1)..]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_tlv<S: Sink + ?Sized>(out: &mut S, tag: u8, content: &[u8]) {
|
||||
write_header(out, tag, content.len());
|
||||
out.put(content);
|
||||
}
|
||||
|
||||
fn strip_unsigned(bytes: &[u8]) -> (&[u8], bool) {
|
||||
let first = bytes.iter().position(|b| *b != 0).unwrap_or(bytes.len());
|
||||
let stripped = &bytes[first..];
|
||||
match stripped.first() {
|
||||
Some(b) => (stripped, *b & 0x80 != 0),
|
||||
None => (&[], true),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn unsigned_integer_content_len(bytes: &[u8]) -> usize {
|
||||
let (stripped, pad) = strip_unsigned(bytes);
|
||||
stripped.len() + usize::from(pad)
|
||||
}
|
||||
|
||||
pub(crate) fn unsigned_integer_len(bytes: &[u8]) -> usize {
|
||||
tlv_len(unsigned_integer_content_len(bytes))
|
||||
}
|
||||
|
||||
pub(crate) fn write_unsigned_integer<S: Sink + ?Sized>(out: &mut S, bytes: &[u8]) {
|
||||
let (stripped, pad) = strip_unsigned(bytes);
|
||||
write_header(out, tag::INTEGER, stripped.len() + usize::from(pad));
|
||||
if pad {
|
||||
out.put(&[0]);
|
||||
}
|
||||
out.put(stripped);
|
||||
}
|
||||
|
||||
pub(crate) const fn small_integer_len(value: u32) -> usize {
|
||||
tlv_len(small_integer_content_len(value))
|
||||
}
|
||||
|
||||
const fn small_integer_content_len(value: u32) -> usize {
|
||||
let bits = 32 - value.leading_zeros() as usize;
|
||||
bits / 8 + 1
|
||||
}
|
||||
|
||||
pub(crate) fn write_small_integer<S: Sink + ?Sized>(out: &mut S, value: u32) {
|
||||
let len = small_integer_content_len(value);
|
||||
let bytes = value.to_be_bytes();
|
||||
out.put(&[tag::INTEGER, len as u8]);
|
||||
if len > bytes.len() {
|
||||
out.put(&[0]);
|
||||
out.put(&bytes);
|
||||
} else {
|
||||
out.put(&bytes[bytes.len() - len..]);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn bit_string_len(content_len: usize) -> usize {
|
||||
tlv_len(content_len + 1)
|
||||
}
|
||||
|
||||
pub(crate) fn write_bit_string_header<S: Sink + ?Sized>(out: &mut S, content_len: usize) {
|
||||
write_header(out, tag::BIT_STRING, content_len + 1);
|
||||
out.put(&[0]);
|
||||
}
|
||||
|
||||
pub(crate) fn rsa_public_key_len(n: &[u8], e: &[u8]) -> usize {
|
||||
tlv_len(unsigned_integer_len(n) + unsigned_integer_len(e))
|
||||
}
|
||||
|
||||
pub(crate) fn write_rsa_public_key<S: Sink + ?Sized>(out: &mut S, n: &[u8], e: &[u8]) {
|
||||
write_header(
|
||||
out,
|
||||
tag::SEQUENCE,
|
||||
unsigned_integer_len(n) + unsigned_integer_len(e),
|
||||
);
|
||||
write_unsigned_integer(out, n);
|
||||
write_unsigned_integer(out, e);
|
||||
}
|
||||
|
||||
pub(crate) struct StackBuf<const N: usize> {
|
||||
buf: [u8; N],
|
||||
len: usize,
|
||||
overflow: bool,
|
||||
}
|
||||
|
||||
impl<const N: usize> StackBuf<N> {
|
||||
pub(crate) const fn new() -> Self {
|
||||
StackBuf {
|
||||
buf: [0u8; N],
|
||||
len: 0,
|
||||
overflow: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn as_slice(&self) -> Option<&[u8]> {
|
||||
(!self.overflow).then(|| &self.buf[..self.len])
|
||||
}
|
||||
}
|
||||
|
||||
impl<const N: usize> Sink for StackBuf<N> {
|
||||
fn put(&mut self, data: &[u8]) {
|
||||
let end = self.len + data.len();
|
||||
match self.buf.get_mut(self.len..end) {
|
||||
Some(slot) => {
|
||||
slot.copy_from_slice(data);
|
||||
self.len = end;
|
||||
}
|
||||
None => self.overflow = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
255
crates/crypto/src/error.rs
Normal file
255
crates/crypto/src/error.rs
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use crate::{backend::PrimitiveError, der::DerError};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum KeyError {
|
||||
Empty,
|
||||
MalformedArmor,
|
||||
MalformedPacket,
|
||||
MalformedCertificate,
|
||||
MixedKeyKinds,
|
||||
SecretKey,
|
||||
PrivateKey,
|
||||
Pkcs12,
|
||||
UnsupportedKeyVersion,
|
||||
UnsupportedPrimaryAlgorithm,
|
||||
UnsupportedKeyAlgorithm,
|
||||
Elgamal,
|
||||
Brainpool,
|
||||
WeakRsa,
|
||||
NoValidSelfSignature,
|
||||
Revoked,
|
||||
Expired,
|
||||
NotYetValid,
|
||||
NoEncryptionKey,
|
||||
SignatureOnlyCertificate,
|
||||
EncipherOnlyCertificate,
|
||||
NoEmailProtection,
|
||||
InvalidPublicKey,
|
||||
TooLarge,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ProfileError {
|
||||
NoPostQuantumKey,
|
||||
IncompatibleRecipientVersions,
|
||||
NoAeadSupport,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EncryptError {
|
||||
NoRecipients,
|
||||
Profile(ProfileError),
|
||||
Primitive(PrimitiveError),
|
||||
MessageTooLarge,
|
||||
MalformedMessage,
|
||||
}
|
||||
|
||||
impl From<PrimitiveError> for EncryptError {
|
||||
fn from(err: PrimitiveError) -> Self {
|
||||
EncryptError::Primitive(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProfileError> for EncryptError {
|
||||
fn from(err: ProfileError) -> Self {
|
||||
EncryptError::Profile(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DerError> for KeyError {
|
||||
fn from(_: DerError) -> Self {
|
||||
KeyError::MalformedCertificate
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CrlError {
|
||||
Malformed,
|
||||
TooLarge,
|
||||
DeltaCrl,
|
||||
UnsupportedScope,
|
||||
UnsupportedCriticalExtension,
|
||||
Sha1Signature,
|
||||
}
|
||||
|
||||
impl From<DerError> for CrlError {
|
||||
fn from(_: DerError) -> Self {
|
||||
CrlError::Malformed
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ChainError {
|
||||
MalformedCertificate,
|
||||
UnsupportedCriticalExtension,
|
||||
NoEmailProtection,
|
||||
TooManyAnchors,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum VerifyError {
|
||||
NotSigned,
|
||||
Malformed,
|
||||
UnknownSigner,
|
||||
UnsupportedAlgorithm,
|
||||
BadSignature,
|
||||
InvalidCertificate(KeyError),
|
||||
}
|
||||
|
||||
impl From<DerError> for VerifyError {
|
||||
fn from(_: DerError) -> Self {
|
||||
VerifyError::Malformed
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! unit_variant_names {
|
||||
($ty:ty { $($variant:ident),* $(,)? }) => {
|
||||
impl $ty {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
$(Self::$variant => stringify!($variant),)*
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
unit_variant_names!(KeyError {
|
||||
Empty,
|
||||
MalformedArmor,
|
||||
MalformedPacket,
|
||||
MalformedCertificate,
|
||||
MixedKeyKinds,
|
||||
SecretKey,
|
||||
PrivateKey,
|
||||
Pkcs12,
|
||||
UnsupportedKeyVersion,
|
||||
UnsupportedPrimaryAlgorithm,
|
||||
UnsupportedKeyAlgorithm,
|
||||
Elgamal,
|
||||
Brainpool,
|
||||
WeakRsa,
|
||||
NoValidSelfSignature,
|
||||
Revoked,
|
||||
Expired,
|
||||
NotYetValid,
|
||||
NoEncryptionKey,
|
||||
SignatureOnlyCertificate,
|
||||
EncipherOnlyCertificate,
|
||||
NoEmailProtection,
|
||||
InvalidPublicKey,
|
||||
TooLarge,
|
||||
});
|
||||
|
||||
unit_variant_names!(ProfileError {
|
||||
NoPostQuantumKey,
|
||||
IncompatibleRecipientVersions,
|
||||
NoAeadSupport,
|
||||
});
|
||||
|
||||
unit_variant_names!(PrimitiveError {
|
||||
Random,
|
||||
InvalidKeyLength,
|
||||
InvalidLength,
|
||||
InvalidPublicKey,
|
||||
KeyAgreement,
|
||||
Encryption,
|
||||
UnsupportedAlgorithm,
|
||||
BadSignature,
|
||||
});
|
||||
|
||||
impl EncryptError {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
EncryptError::NoRecipients => "NoRecipients",
|
||||
EncryptError::Profile(err) => err.as_str(),
|
||||
EncryptError::Primitive(err) => err.as_str(),
|
||||
EncryptError::MessageTooLarge => "MessageTooLarge",
|
||||
EncryptError::MalformedMessage => "MalformedMessage",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KeyError {
|
||||
pub fn description(&self) -> &'static str {
|
||||
match self {
|
||||
KeyError::Empty => "No valid public key found.",
|
||||
KeyError::MalformedArmor => "The ASCII armor or PEM encoding is malformed.",
|
||||
KeyError::MalformedPacket => "The OpenPGP key data is malformed.",
|
||||
KeyError::MalformedCertificate => "The X.509 certificate is malformed.",
|
||||
KeyError::MixedKeyKinds => "Cannot mix OpenPGP keys and S/MIME certificates.",
|
||||
KeyError::SecretKey | KeyError::PrivateKey | KeyError::Pkcs12 => {
|
||||
"Secret key material is not accepted, upload the public key only."
|
||||
}
|
||||
KeyError::UnsupportedKeyVersion => {
|
||||
"Unsupported OpenPGP key version, only v4 and v6 keys are supported."
|
||||
}
|
||||
KeyError::UnsupportedPrimaryAlgorithm => "The primary key algorithm is not supported.",
|
||||
KeyError::UnsupportedKeyAlgorithm => "The encryption key algorithm is not supported.",
|
||||
KeyError::Elgamal => "ElGamal keys are not supported.",
|
||||
KeyError::Brainpool => "Brainpool curves are not supported.",
|
||||
KeyError::WeakRsa => "RSA keys must be between 2048 and 8192 bits long.",
|
||||
KeyError::NoValidSelfSignature => "The key has no valid self-signature.",
|
||||
KeyError::Revoked => "The key or certificate has been revoked.",
|
||||
KeyError::Expired => "The key or certificate has expired.",
|
||||
KeyError::NotYetValid => "The certificate is not valid yet.",
|
||||
KeyError::NoEncryptionKey => "The key contains no key usable for encryption.",
|
||||
KeyError::SignatureOnlyCertificate => {
|
||||
"Signature-only certificate cannot be used for encryption."
|
||||
}
|
||||
KeyError::EncipherOnlyCertificate => {
|
||||
"Encipher-only certificates cannot be used for encryption."
|
||||
}
|
||||
KeyError::NoEmailProtection => {
|
||||
"The certificate is not valid for email protection (extended key usage)."
|
||||
}
|
||||
KeyError::InvalidPublicKey => "The public key is invalid.",
|
||||
KeyError::TooLarge => "The key is too large.",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ProfileError {
|
||||
pub fn description(&self) -> &'static str {
|
||||
match self {
|
||||
ProfileError::NoPostQuantumKey => {
|
||||
"The post-quantum profile requires a key with a post-quantum (ML-KEM) encryption key."
|
||||
}
|
||||
ProfileError::IncompatibleRecipientVersions => {
|
||||
"The key mixes OpenPGP key versions that cannot be used together with this profile."
|
||||
}
|
||||
ProfileError::NoAeadSupport => {
|
||||
"The key does not support the authenticated encryption this profile requires."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! display_as_debug {
|
||||
($($ty:ty),*) => {
|
||||
$(impl fmt::Display for $ty {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
fmt::Debug::fmt(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for $ty {})*
|
||||
};
|
||||
}
|
||||
|
||||
display_as_debug!(
|
||||
KeyError,
|
||||
ProfileError,
|
||||
EncryptError,
|
||||
CrlError,
|
||||
ChainError,
|
||||
VerifyError
|
||||
);
|
||||
69
crates/crypto/src/harvest/autocrypt.rs
Normal file
69
crates/crypto/src/harvest/autocrypt.rs
Normal file
|
|
@ -0,0 +1,69 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use encodify::base64::LENIENT;
|
||||
|
||||
pub(crate) const MAX_HEADER_LEN: usize = 10 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Attribute {
|
||||
Addr,
|
||||
PreferEncrypt,
|
||||
Keydata,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AutocryptHeader<'x> {
|
||||
pub addr: &'x [u8],
|
||||
pub prefer_encrypt: bool,
|
||||
pub keydata: Vec<u8>,
|
||||
}
|
||||
|
||||
pub fn parse_autocrypt(value: &[u8]) -> Option<AutocryptHeader<'_>> {
|
||||
if value.len() > MAX_HEADER_LEN {
|
||||
return None;
|
||||
}
|
||||
let mut addr = None;
|
||||
let mut prefer_encrypt = None;
|
||||
let mut keydata = None;
|
||||
for attribute in value.split(|b| *b == b';') {
|
||||
let attribute = attribute.trim_ascii();
|
||||
if attribute.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if keydata.is_some() {
|
||||
return None;
|
||||
}
|
||||
let mut parts = attribute.splitn(2, |b| *b == b'=');
|
||||
let (Some(name), Some(value)) = (parts.next(), parts.next()) else {
|
||||
return None;
|
||||
};
|
||||
let name = name.trim_ascii();
|
||||
let value = value.trim_ascii();
|
||||
let known = hashify::map_ignore_case!(
|
||||
name,
|
||||
Attribute,
|
||||
"addr" => Attribute::Addr,
|
||||
"prefer-encrypt" => Attribute::PreferEncrypt,
|
||||
"keydata" => Attribute::Keydata,
|
||||
);
|
||||
match known {
|
||||
Some(Attribute::Addr) if addr.is_none() => addr = Some(value),
|
||||
Some(Attribute::PreferEncrypt) if prefer_encrypt.is_none() => {
|
||||
prefer_encrypt = Some(value.eq_ignore_ascii_case(b"mutual"))
|
||||
}
|
||||
Some(Attribute::Keydata) => keydata = Some(LENIENT.decode(value).ok()?),
|
||||
None if name.starts_with(b"_") => {}
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
let keydata = keydata.filter(|k| !k.is_empty())?;
|
||||
Some(AutocryptHeader {
|
||||
addr: addr.filter(|a| !a.is_empty())?,
|
||||
prefer_encrypt: prefer_encrypt.unwrap_or(false),
|
||||
keydata,
|
||||
})
|
||||
}
|
||||
218
crates/crypto/src/harvest/mod.rs
Normal file
218
crates/crypto/src/harvest/mod.rs
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub mod autocrypt;
|
||||
|
||||
use mail_parser::{HeaderName, Message};
|
||||
|
||||
use crate::{
|
||||
cms::signed::{Content, verify as verify_signed_data},
|
||||
error::VerifyError,
|
||||
mime::signed::{SignedProtocol, detached_signature, opaque_signed_data},
|
||||
pgp::{
|
||||
armor::dearmor_public_keys,
|
||||
cert::split_certs,
|
||||
verify::{PgpVerified, validate_signers, verify_detached},
|
||||
},
|
||||
types::{Fingerprint, KeyKind, SmimeCapabilities},
|
||||
x509::{cert::Certificate, recipient::parse_capabilities},
|
||||
};
|
||||
|
||||
use autocrypt::parse_autocrypt;
|
||||
|
||||
const MAX_AUTOCRYPT_HEADERS: usize = 8;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum HarvestSource {
|
||||
SmimeSignature,
|
||||
Autocrypt,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct HarvestedKey {
|
||||
pub kind: KeyKind,
|
||||
pub source: HarvestSource,
|
||||
pub key: Box<[u8]>,
|
||||
pub addresses: Vec<Box<str>>,
|
||||
pub signing_time: Option<u64>,
|
||||
pub signature_verified: bool,
|
||||
pub smime_capabilities: Option<SmimeCapabilities>,
|
||||
pub encryption_key_preference: bool,
|
||||
pub certificates: Vec<Box<[u8]>>,
|
||||
pub prefer_encrypt: bool,
|
||||
}
|
||||
|
||||
impl HarvestedKey {
|
||||
pub fn chain(&self) -> Vec<Vec<u8>> {
|
||||
let mut chain = Vec::with_capacity(self.certificates.len() + 1);
|
||||
chain.push(self.key.to_vec());
|
||||
chain.extend(
|
||||
self.certificates
|
||||
.iter()
|
||||
.filter(|der| {
|
||||
der.as_ref() != self.key.as_ref()
|
||||
&& Certificate::parse(der).is_ok_and(|cert| cert.is_ca())
|
||||
})
|
||||
.map(|der| der.to_vec()),
|
||||
);
|
||||
chain
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct SignatureCheck {
|
||||
pub signer: Fingerprint,
|
||||
pub signing_time: u64,
|
||||
}
|
||||
|
||||
fn is_excluded(message: &Message<'_>) -> bool {
|
||||
message
|
||||
.from()
|
||||
.is_none_or(|from| from.mailboxes().nth(1).is_some() || from.first().is_none())
|
||||
|| message.root_part().content_type().is_some_and(|ct| {
|
||||
ct.ctype().eq_ignore_ascii_case("multipart")
|
||||
&& ct
|
||||
.subtype()
|
||||
.is_some_and(|sub| sub.eq_ignore_ascii_case("report"))
|
||||
})
|
||||
}
|
||||
|
||||
pub fn harvest(message: &Message<'_>, from: &str, now: u64) -> Vec<HarvestedKey> {
|
||||
if is_excluded(message) {
|
||||
return Vec::new();
|
||||
}
|
||||
smime_key(message, from, now)
|
||||
.into_iter()
|
||||
.chain(autocrypt_key(message, from, now))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn verify_pgp_signature(
|
||||
message: &Message<'_>,
|
||||
cert: &[u8],
|
||||
now: u64,
|
||||
) -> Result<SignatureCheck, VerifyError> {
|
||||
let detached = detached_signature(message)
|
||||
.filter(|signed| signed.protocol == SignedProtocol::Pgp)
|
||||
.ok_or(VerifyError::NotSigned)?;
|
||||
let binary = dearmor_public_keys(cert).map_err(VerifyError::InvalidCertificate)?;
|
||||
let certs = split_certs(&binary).map_err(VerifyError::InvalidCertificate)?;
|
||||
let PgpVerified { signer, created } = verify_detached(
|
||||
&validate_signers(&certs, now),
|
||||
&detached.signature.decoded(),
|
||||
detached.content,
|
||||
now,
|
||||
)?;
|
||||
Ok(SignatureCheck {
|
||||
signer,
|
||||
signing_time: created,
|
||||
})
|
||||
}
|
||||
|
||||
fn bound_to(cert: &Certificate<'_>, from: &str) -> bool {
|
||||
cert.email_addresses()
|
||||
.any(|address| address.eq_ignore_ascii_case(from))
|
||||
}
|
||||
|
||||
fn smime_key(message: &Message<'_>, from: &str, now: u64) -> Option<HarvestedKey> {
|
||||
let (der, content) = match detached_signature(message) {
|
||||
Some(signed) if signed.protocol == SignedProtocol::Smime => (
|
||||
signed.signature.decoded(),
|
||||
Content::Detached(signed.content),
|
||||
),
|
||||
Some(_) => return None,
|
||||
None => (
|
||||
opaque_signed_data(message)?.decoded(),
|
||||
Content::Encapsulated,
|
||||
),
|
||||
};
|
||||
let signed = verify_signed_data(&der, content, now).ok()?;
|
||||
let signer = signed.signer?;
|
||||
let preferred = signed
|
||||
.preference
|
||||
.and_then(|preference| signed.certificates().find(|cert| preference.matches(cert)))
|
||||
.filter(|cert| bound_to(cert, from));
|
||||
let (cert, is_preferred) = match preferred {
|
||||
Some(cert) => (cert, true),
|
||||
None if bound_to(&signer, from) => (signer, false),
|
||||
None => return None,
|
||||
};
|
||||
let mut addresses: Vec<Box<str>> = Vec::new();
|
||||
for address in cert.email_addresses() {
|
||||
if !addresses
|
||||
.iter()
|
||||
.any(|known| known.eq_ignore_ascii_case(address))
|
||||
{
|
||||
addresses.push(address.into());
|
||||
}
|
||||
}
|
||||
Some(HarvestedKey {
|
||||
kind: KeyKind::Smime,
|
||||
source: HarvestSource::SmimeSignature,
|
||||
key: cert.raw.into(),
|
||||
addresses,
|
||||
signing_time: signed.signing_time,
|
||||
signature_verified: signed.verified,
|
||||
smime_capabilities: signed.capabilities.map(parse_capabilities),
|
||||
encryption_key_preference: is_preferred,
|
||||
certificates: signed.certificates().map(|c| c.raw.into()).collect(),
|
||||
prefer_encrypt: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn autocrypt_key(message: &Message<'_>, from: &str, now: u64) -> Option<HarvestedKey> {
|
||||
let mut found = None;
|
||||
for header in message
|
||||
.root_part()
|
||||
.headers()
|
||||
.iter()
|
||||
.filter(|header| header.name() == HeaderName::Autocrypt)
|
||||
.take(MAX_AUTOCRYPT_HEADERS)
|
||||
{
|
||||
let Some(parsed) = parse_autocrypt(header.raw_value()) else {
|
||||
continue;
|
||||
};
|
||||
if !parsed.addr.eq_ignore_ascii_case(from.as_bytes()) {
|
||||
continue;
|
||||
}
|
||||
if found.is_some() {
|
||||
return None;
|
||||
}
|
||||
found = Some(parsed);
|
||||
}
|
||||
let header = found?;
|
||||
let certs = split_certs(&header.keydata).ok()?;
|
||||
if certs.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
let mut signers = validate_signers(&certs, now);
|
||||
signers.retain(|(_, valid)| {
|
||||
!valid.cert.keys.is_empty()
|
||||
&& valid
|
||||
.addresses
|
||||
.iter()
|
||||
.any(|address| address.eq_ignore_ascii_case(from))
|
||||
});
|
||||
let (_, first) = signers.first()?;
|
||||
let addresses = first.addresses.clone();
|
||||
let verified = detached_signature(message)
|
||||
.filter(|signed| signed.protocol == SignedProtocol::Pgp)
|
||||
.and_then(|signed| {
|
||||
verify_detached(&signers, &signed.signature.decoded(), signed.content, now).ok()
|
||||
});
|
||||
Some(HarvestedKey {
|
||||
kind: KeyKind::OpenPgp,
|
||||
source: HarvestSource::Autocrypt,
|
||||
key: header.keydata.into_boxed_slice(),
|
||||
addresses,
|
||||
signing_time: verified.map(|v| v.created),
|
||||
signature_verified: verified.is_some(),
|
||||
smime_capabilities: None,
|
||||
encryption_key_preference: false,
|
||||
certificates: Vec::new(),
|
||||
prefer_encrypt: header.prefer_encrypt,
|
||||
})
|
||||
}
|
||||
111
crates/crypto/src/lib.rs
Normal file
111
crates/crypto/src/lib.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
#![deny(rust_2018_idioms)]
|
||||
|
||||
pub(crate) mod backend;
|
||||
pub(crate) mod cms;
|
||||
pub(crate) mod der;
|
||||
pub mod error;
|
||||
pub mod harvest;
|
||||
pub mod mime;
|
||||
pub(crate) mod pgp;
|
||||
pub mod types;
|
||||
pub mod x509;
|
||||
|
||||
use mail_parser::Message;
|
||||
|
||||
pub use error::{ChainError, CrlError, EncryptError, KeyError, ProfileError, VerifyError};
|
||||
pub use harvest::{
|
||||
HarvestSource, HarvestedKey, SignatureCheck,
|
||||
autocrypt::{AutocryptHeader, parse_autocrypt},
|
||||
harvest, verify_pgp_signature,
|
||||
};
|
||||
pub use mime::protection::{Protection, is_ciphertext, is_encrypted_media, protection};
|
||||
pub use types::{
|
||||
AddressKey, EcdhWrapParameters, EncryptOptions, EncryptWarning, Encrypted, Fingerprint,
|
||||
HeaderProtection, KeyCapabilities, KeyCapability, KeyKind, KeyWarning, ParsedKeys, Profile,
|
||||
RecipientIds, RecipientSet, SmimeCapabilities, SmimeCipher,
|
||||
};
|
||||
|
||||
pub use pgp::EXPIRES_SOON_SECS;
|
||||
pub use x509::{
|
||||
chain::{ChainStatus, ChainVerdict, TrustContext, verify_smime_chain},
|
||||
crl::{Crl, parse_crl},
|
||||
trust::{TrustAnchor, TrustAnchors},
|
||||
};
|
||||
|
||||
use backend::rng::{Rng, SystemRng};
|
||||
use mime::entity::Entity;
|
||||
use types::Recipients;
|
||||
|
||||
pub fn parse_public_keys(input: &[u8], now: u64) -> Result<ParsedKeys, KeyError> {
|
||||
let trimmed = input.trim_ascii();
|
||||
match trimmed.first() {
|
||||
None => Err(KeyError::Empty),
|
||||
Some(b'-') if !trimmed.starts_with(b"-----BEGIN PGP ") => {
|
||||
x509::recipient::parse_public_keys(input, now)
|
||||
}
|
||||
Some(0x30) => x509::recipient::parse_public_keys(input, now),
|
||||
Some(_) => pgp::parse_public_keys(input, now),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check_profile(set: &RecipientSet, profile: Profile) -> Result<(), ProfileError> {
|
||||
match set.0.as_ref() {
|
||||
Recipients::OpenPgp(certs) => pgp::encrypt::check_profile(certs, profile),
|
||||
Recipients::Smime(recipients) => cms::envelope::check_profile(recipients, profile),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn split_certificates(input: &[u8]) -> Result<Vec<Vec<u8>>, KeyError> {
|
||||
x509::recipient::split_certificates(input)
|
||||
}
|
||||
|
||||
pub fn parse_public_keys_for(
|
||||
input: &[u8],
|
||||
address: &str,
|
||||
now: u64,
|
||||
) -> Result<Vec<AddressKey>, KeyError> {
|
||||
pgp::parse_public_keys_for(input, address, now)
|
||||
}
|
||||
|
||||
pub fn revoked_fingerprints(input: &[u8], now: u64) -> Vec<Fingerprint> {
|
||||
pgp::revoked_fingerprints(input, now)
|
||||
}
|
||||
|
||||
pub fn certifies(old_key: &[u8], new_key: &[u8], address: &str, now: u64) -> bool {
|
||||
pgp::certifies(old_key, new_key, address, now)
|
||||
}
|
||||
|
||||
impl RecipientSet {
|
||||
pub fn encrypt(
|
||||
&self,
|
||||
message: &Message<'_>,
|
||||
options: &EncryptOptions,
|
||||
) -> Result<Encrypted, EncryptError> {
|
||||
encrypt_with(message, self, options, &mut SystemRng::new())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn encrypt_with(
|
||||
message: &Message<'_>,
|
||||
recipients: &RecipientSet,
|
||||
options: &EncryptOptions,
|
||||
rng: &mut impl Rng,
|
||||
) -> Result<Encrypted, EncryptError> {
|
||||
let entity = Entity::new(message, options.header_protection)?;
|
||||
let (message, warning) = match recipients.0.as_ref() {
|
||||
Recipients::OpenPgp(certs) => (pgp::encrypt::encrypt(&entity, certs, options, rng)?, None),
|
||||
Recipients::Smime(recipients) => cms::envelope::encrypt(&entity, recipients, options, rng)?,
|
||||
};
|
||||
Ok(Encrypted { message, warning })
|
||||
}
|
||||
|
||||
#[cfg(stalwart_tests)]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../stalwart-tests/unit/crypto/src/test_support.rs"]
|
||||
pub mod test_support;
|
||||
270
crates/crypto/src/mime/entity.rs
Normal file
270
crates/crypto/src/mime/entity.rs
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use mail_parser::{Header, HeaderName, Headers, Message};
|
||||
|
||||
use super::{
|
||||
CRLF, Canonical, Counter, Sink, has_bare_lf,
|
||||
legacy::{LEGACY_PARAM, LegacyParts},
|
||||
protection::Protection,
|
||||
};
|
||||
use crate::{error::EncryptError, types::HeaderProtection};
|
||||
|
||||
const MIME_VERSION: &[u8] = b"MIME-Version: 1.0\r\n";
|
||||
const OBSCURED_SUBJECT: &[u8] = b"Subject: [...]\r\n";
|
||||
const HP_OUTER: &[u8] = b"HP-Outer: ";
|
||||
const HP_OUTER_SUBJECT: &[u8] = b"HP-Outer: Subject: [...]\r\n";
|
||||
const HP_CIPHER: &[u8] = b"; hp=\"cipher\"";
|
||||
const DEFAULT_CONTENT_TYPE: &[u8] = b"Content-Type: text/plain; charset=us-ascii";
|
||||
const NAME_SEPARATOR: &[u8] = b": ";
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Outer {
|
||||
Keep,
|
||||
Obscure,
|
||||
Remove,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Field {
|
||||
ContentType,
|
||||
Mime,
|
||||
Protected(Outer),
|
||||
Unprotected,
|
||||
}
|
||||
|
||||
impl Field {
|
||||
fn classify(name: &HeaderName<'_>, protection: HeaderProtection) -> Self {
|
||||
let baseline = |outer| {
|
||||
if protection == HeaderProtection::Baseline {
|
||||
outer
|
||||
} else {
|
||||
Outer::Keep
|
||||
}
|
||||
};
|
||||
match name {
|
||||
HeaderName::ContentType => Field::ContentType,
|
||||
name if name.is_mime_header() => Field::Mime,
|
||||
_ if protection == HeaderProtection::None => Field::Unprotected,
|
||||
HeaderName::Subject => Field::Protected(baseline(Outer::Obscure)),
|
||||
HeaderName::Comments | HeaderName::Keywords => {
|
||||
Field::Protected(baseline(Outer::Remove))
|
||||
}
|
||||
HeaderName::From
|
||||
| HeaderName::Sender
|
||||
| HeaderName::ReplyTo
|
||||
| HeaderName::To
|
||||
| HeaderName::Cc
|
||||
| HeaderName::Date
|
||||
| HeaderName::MessageId
|
||||
| HeaderName::InReplyTo
|
||||
| HeaderName::References => Field::Protected(Outer::Keep),
|
||||
_ => Field::Unprotected,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Entity<'x> {
|
||||
raw: &'x [u8],
|
||||
headers: Headers<'x>,
|
||||
body_offset: usize,
|
||||
body_canonical: bool,
|
||||
has_mime_version: bool,
|
||||
has_content_type: bool,
|
||||
protection: HeaderProtection,
|
||||
legacy: LegacyParts<'x>,
|
||||
}
|
||||
|
||||
fn write_field<S: Sink>(out: &mut S, bytes: &[u8]) {
|
||||
out.put(bytes);
|
||||
if !bytes.ends_with(b"\n") {
|
||||
out.put(CRLF);
|
||||
}
|
||||
}
|
||||
|
||||
fn write_with_params<S: Sink>(out: &mut S, field: &[u8], params: &[&[u8]]) {
|
||||
let value = field.trim_ascii_end();
|
||||
out.put(value.strip_suffix(b";").unwrap_or(value).trim_ascii_end());
|
||||
for param in params {
|
||||
out.put(param);
|
||||
}
|
||||
out.put(CRLF);
|
||||
}
|
||||
|
||||
impl<'x> Entity<'x> {
|
||||
pub(crate) fn new(
|
||||
message: &'x Message<'x>,
|
||||
protection: HeaderProtection,
|
||||
) -> Result<Self, EncryptError> {
|
||||
let raw = message.raw();
|
||||
let root = message.root_part();
|
||||
let headers = root.headers();
|
||||
let mut has_mime_version = false;
|
||||
let mut has_content_type = false;
|
||||
for header in headers.iter() {
|
||||
if raw
|
||||
.get(header.offset_field() as usize..header.offset_end() as usize)
|
||||
.is_none()
|
||||
|| header.offset_start() < header.offset_field()
|
||||
{
|
||||
return Err(EncryptError::MalformedMessage);
|
||||
}
|
||||
match header.name() {
|
||||
HeaderName::MimeVersion => has_mime_version = true,
|
||||
HeaderName::ContentType => has_content_type = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let body_offset = root.offset_body() as usize;
|
||||
if body_offset > raw.len() {
|
||||
return Err(EncryptError::MalformedMessage);
|
||||
}
|
||||
let body_canonical = !raw
|
||||
.get(body_offset..)
|
||||
.is_some_and(|body| has_bare_lf(body, false));
|
||||
let protection = if protection != HeaderProtection::None
|
||||
&& crate::mime::protection::protection(message) == Protection::Signed
|
||||
{
|
||||
HeaderProtection::None
|
||||
} else {
|
||||
protection
|
||||
};
|
||||
let legacy = if protection == HeaderProtection::Baseline {
|
||||
LegacyParts::collect(message)
|
||||
} else {
|
||||
LegacyParts::none()
|
||||
};
|
||||
Ok(Entity {
|
||||
raw,
|
||||
headers,
|
||||
body_offset,
|
||||
body_canonical,
|
||||
has_mime_version,
|
||||
has_content_type,
|
||||
protection,
|
||||
legacy,
|
||||
})
|
||||
}
|
||||
|
||||
fn field_bytes(&self, header: &Header<'x>) -> &'x [u8] {
|
||||
self.raw
|
||||
.get(header.offset_field() as usize..header.offset_end() as usize)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn fields(&self) -> impl Iterator<Item = (Field, Header<'x>)> + '_ {
|
||||
self.headers
|
||||
.iter()
|
||||
.map(|header| (Field::classify(&header.name(), self.protection), header))
|
||||
}
|
||||
|
||||
pub(crate) fn outer_len(&self) -> usize {
|
||||
let mut counter = Counter::default();
|
||||
self.write_outer(&mut counter);
|
||||
counter.0
|
||||
}
|
||||
|
||||
pub(crate) fn write_outer<S: Sink>(&self, out: &mut S) {
|
||||
for (field, header) in self.fields() {
|
||||
match field {
|
||||
Field::ContentType | Field::Mime | Field::Protected(Outer::Remove) => {}
|
||||
Field::Protected(Outer::Obscure) => out.put(OBSCURED_SUBJECT),
|
||||
Field::Protected(Outer::Keep) | Field::Unprotected => {
|
||||
write_field(out, self.field_bytes(&header))
|
||||
}
|
||||
}
|
||||
}
|
||||
if !self.has_mime_version {
|
||||
out.put(MIME_VERSION);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn inner_len(&self) -> usize {
|
||||
let mut counter = Counter::default();
|
||||
self.write_inner(&mut counter);
|
||||
counter.0
|
||||
}
|
||||
|
||||
pub(crate) fn write_inner<S: Sink>(&self, sink: &mut S) {
|
||||
let mut out = Canonical::new(sink);
|
||||
let protected = self.protection != HeaderProtection::None;
|
||||
if protected {
|
||||
for (field, header) in self.fields() {
|
||||
if matches!(field, Field::Protected(_)) {
|
||||
write_field(&mut out, self.field_bytes(&header));
|
||||
}
|
||||
}
|
||||
for (field, header) in self.fields() {
|
||||
match field {
|
||||
Field::Protected(Outer::Keep) => {
|
||||
out.put(HP_OUTER);
|
||||
out.put(header.raw_name().as_bytes());
|
||||
out.put(NAME_SEPARATOR);
|
||||
write_field(&mut out, header.raw_value().trim_ascii_start());
|
||||
}
|
||||
Field::Protected(Outer::Obscure) => out.put(HP_OUTER_SUBJECT),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let root_params: &[&[u8]] = if self.legacy.root {
|
||||
&[HP_CIPHER, LEGACY_PARAM]
|
||||
} else {
|
||||
&[HP_CIPHER]
|
||||
};
|
||||
for (field, header) in self.fields() {
|
||||
match field {
|
||||
Field::ContentType if protected => {
|
||||
write_with_params(&mut out, self.field_bytes(&header), root_params)
|
||||
}
|
||||
Field::ContentType | Field::Mime => {
|
||||
write_field(&mut out, self.field_bytes(&header))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if protected && !self.has_content_type {
|
||||
write_with_params(&mut out, DEFAULT_CONTENT_TYPE, root_params);
|
||||
}
|
||||
out.put(CRLF);
|
||||
self.write_body(&mut out);
|
||||
}
|
||||
|
||||
fn write_body<S: Sink>(&self, out: &mut Canonical<'_, S>) {
|
||||
let raw = self.raw;
|
||||
let mut pos = self.body_offset;
|
||||
let put = |out: &mut Canonical<'_, S>, data: &[u8]| {
|
||||
if self.body_canonical {
|
||||
out.put_canonical(data);
|
||||
} else {
|
||||
out.put(data);
|
||||
}
|
||||
};
|
||||
for part in self.legacy.iter() {
|
||||
if let Some((start, end)) = part.content_type {
|
||||
put(out, raw.get(pos..start).unwrap_or_default());
|
||||
write_with_params(
|
||||
out,
|
||||
raw.get(start..end).unwrap_or_default(),
|
||||
&[LEGACY_PARAM],
|
||||
);
|
||||
pos = end;
|
||||
}
|
||||
let (body_start, body_end) = part.body;
|
||||
put(out, raw.get(pos..body_start).unwrap_or_default());
|
||||
if part.is_base64() {
|
||||
out.put_reencoded(part);
|
||||
pos = body_end;
|
||||
} else {
|
||||
let insert = body_start + part.insert_at;
|
||||
put(out, raw.get(body_start..insert).unwrap_or_default());
|
||||
part.write_inline(out);
|
||||
pos = insert;
|
||||
}
|
||||
}
|
||||
put(out, raw.get(pos..).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
521
crates/crypto/src/mime/legacy.rs
Normal file
521
crates/crypto/src/mime/legacy.rs
Normal file
|
|
@ -0,0 +1,521 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use encodify::base64::STANDARD;
|
||||
use mail_parser::{Encoding, HeaderName, Message, MessagePart, PartKind};
|
||||
|
||||
use super::{CRLF, Counter, Sink};
|
||||
use crate::backend::base64::{MIME, MIME_LINE_BYTES, decode_base64, decoded_base64_len};
|
||||
|
||||
pub(crate) const MAX_LEGACY_PARTS: usize = 4;
|
||||
pub(crate) const LEGACY_PARAM: &[u8] = b"; hp-legacy-display=1";
|
||||
const MAX_DEPTH: usize = 8;
|
||||
const SUBJECT_PREFIX: &[u8] = b"Subject: ";
|
||||
const HTML_DIV: &[u8] = b"<div class=\"header-protection-legacy-display\">";
|
||||
const HTML_PRE: &[u8] = b"<pre>Subject: ";
|
||||
const HTML_CLOSE: &[u8] = b"</pre></div>";
|
||||
const QP_SOFT_BREAK: &[u8] = b"=\r\n";
|
||||
const QP_MAX_COLUMN: usize = 75;
|
||||
const UPPER_HEX: &[u8; 16] = b"0123456789ABCDEF";
|
||||
const BODY_TAG: &[u8; 4] = b"body";
|
||||
const B64_ENCODED_LINE: usize = MIME_LINE_BYTES / 3 * 4;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Markup {
|
||||
Plain,
|
||||
Html,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Transfer {
|
||||
SevenBit,
|
||||
EightBit,
|
||||
QuotedPrintable,
|
||||
Base64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum Subject<'x> {
|
||||
Decoded(&'x [u8]),
|
||||
Raw(&'x [u8]),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct LegacyPart<'x> {
|
||||
pub content_type: Option<(usize, usize)>,
|
||||
pub body: (usize, usize),
|
||||
pub insert_at: usize,
|
||||
markup: Markup,
|
||||
transfer: Transfer,
|
||||
subject: Subject<'x>,
|
||||
element_len: usize,
|
||||
decoded_len: usize,
|
||||
encoded_body: &'x [u8],
|
||||
}
|
||||
|
||||
pub(crate) struct LegacyParts<'x> {
|
||||
pub root: bool,
|
||||
pub parts: [Option<LegacyPart<'x>>; MAX_LEGACY_PARTS],
|
||||
}
|
||||
|
||||
impl<'x> LegacyParts<'x> {
|
||||
pub(crate) const fn none() -> Self {
|
||||
LegacyParts {
|
||||
root: false,
|
||||
parts: [None; MAX_LEGACY_PARTS],
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn collect(message: &'x Message<'x>) -> Self {
|
||||
let mut legacy = LegacyParts::none();
|
||||
let Some(subject) = message
|
||||
.root_part()
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|h| h.name() == HeaderName::Subject)
|
||||
else {
|
||||
return legacy;
|
||||
};
|
||||
let decoded = message.subject().unwrap_or_default().as_bytes();
|
||||
let raw = subject.raw_value().trim_ascii();
|
||||
let mut found = Found {
|
||||
legacy: &mut legacy,
|
||||
count: 0,
|
||||
min_offset: message.root_part().offset_body() as usize,
|
||||
root: message.root_part().id(),
|
||||
decoded,
|
||||
raw,
|
||||
};
|
||||
found.visit(message.root_part(), 0);
|
||||
legacy
|
||||
}
|
||||
|
||||
pub(crate) fn iter(&self) -> impl Iterator<Item = &LegacyPart<'x>> {
|
||||
self.parts.iter().flatten()
|
||||
}
|
||||
}
|
||||
|
||||
struct Found<'a, 'x> {
|
||||
legacy: &'a mut LegacyParts<'x>,
|
||||
count: usize,
|
||||
min_offset: usize,
|
||||
root: mail_parser::PartId,
|
||||
decoded: &'x [u8],
|
||||
raw: &'x [u8],
|
||||
}
|
||||
|
||||
impl<'x> Found<'_, 'x> {
|
||||
fn visit(&mut self, part: MessagePart<'x>, depth: usize) {
|
||||
if depth > MAX_DEPTH || self.count >= MAX_LEGACY_PARTS {
|
||||
return;
|
||||
}
|
||||
match part.kind() {
|
||||
PartKind::Multipart => {
|
||||
let alternative = part
|
||||
.content_type()
|
||||
.and_then(|ct| ct.subtype())
|
||||
.is_some_and(|sub| sub.eq_ignore_ascii_case("alternative"));
|
||||
if alternative {
|
||||
for child in part.children() {
|
||||
self.visit(child, depth + 1);
|
||||
}
|
||||
} else if let Some(first) = part.children().next() {
|
||||
self.visit(first, depth + 1);
|
||||
}
|
||||
}
|
||||
PartKind::Text | PartKind::Html => {
|
||||
if let Some(legacy) = self.leaf(&part) {
|
||||
self.min_offset = legacy.body.1;
|
||||
if let Some(slot) = self.legacy.parts.get_mut(self.count) {
|
||||
*slot = Some(legacy);
|
||||
self.count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn leaf(&mut self, part: &MessagePart<'x>) -> Option<LegacyPart<'x>> {
|
||||
let ct = part.content_type();
|
||||
let markup = match part.kind() {
|
||||
PartKind::Html => Markup::Html,
|
||||
_ if ct.as_ref().is_none_or(|ct| {
|
||||
ct.subtype()
|
||||
.is_some_and(|s| s.eq_ignore_ascii_case("plain"))
|
||||
}) =>
|
||||
{
|
||||
Markup::Plain
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
if part
|
||||
.content_disposition()
|
||||
.is_some_and(|cd| cd.ctype().eq_ignore_ascii_case("attachment"))
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let transfer = match part.encoding() {
|
||||
Encoding::QuotedPrintable => Transfer::QuotedPrintable,
|
||||
Encoding::Base64 => Transfer::Base64,
|
||||
Encoding::None => match part.content_transfer_encoding() {
|
||||
None => Transfer::SevenBit,
|
||||
Some(cte) => *hashify::map_ignore_case!(
|
||||
cte.trim().as_bytes(),
|
||||
Transfer,
|
||||
"7bit" => Transfer::SevenBit,
|
||||
"8bit" => Transfer::EightBit,
|
||||
"binary" => Transfer::EightBit,
|
||||
)?,
|
||||
},
|
||||
};
|
||||
let utf8 = ct
|
||||
.as_ref()
|
||||
.and_then(|ct| ct.attribute("charset"))
|
||||
.is_some_and(|cs| hashify::set_ignore_case!(cs.trim().as_bytes(), "utf-8", "utf8"));
|
||||
let subject = if self.decoded.is_ascii() || (utf8 && transfer != Transfer::SevenBit) {
|
||||
Subject::Decoded(self.decoded)
|
||||
} else if self.raw.is_ascii() {
|
||||
Subject::Raw(self.raw)
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let is_root = part.id() == self.root;
|
||||
let content_type = if is_root {
|
||||
None
|
||||
} else {
|
||||
let field = part
|
||||
.headers()
|
||||
.iter()
|
||||
.find(|h| h.name() == HeaderName::ContentType)?;
|
||||
Some((field.offset_field() as usize, field.offset_end() as usize))
|
||||
};
|
||||
let body = (part.offset_body() as usize, part.offset_end() as usize);
|
||||
let encoded_body = part.raw_body();
|
||||
let header_start = content_type.map_or(body.0, |(start, _)| start);
|
||||
if header_start < self.min_offset
|
||||
|| content_type.is_some_and(|(_, end)| end > body.0)
|
||||
|| body.1 < body.0
|
||||
|| encoded_body.len() != body.1 - body.0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let (decoded_len, insert_at) = match (transfer, markup) {
|
||||
(Transfer::Base64, Markup::Plain) => (decoded_base64_len(encoded_body), 0),
|
||||
(Transfer::Base64, Markup::Html) => {
|
||||
let mut finder = BodyTagFinder::default();
|
||||
decode_base64(encoded_body, &mut finder);
|
||||
(decoded_base64_len(encoded_body), finder.found.unwrap_or(0))
|
||||
}
|
||||
(_, Markup::Plain) => (0, 0),
|
||||
(_, Markup::Html) => {
|
||||
let mut finder = BodyTagFinder::default();
|
||||
finder.put(encoded_body);
|
||||
(0, finder.found.unwrap_or(0))
|
||||
}
|
||||
};
|
||||
let mut legacy = LegacyPart {
|
||||
content_type,
|
||||
body,
|
||||
insert_at,
|
||||
markup,
|
||||
transfer,
|
||||
subject,
|
||||
element_len: 0,
|
||||
decoded_len,
|
||||
encoded_body,
|
||||
};
|
||||
let mut counter = Counter::default();
|
||||
legacy.write_element(&mut counter, ElementEncoding::Raw);
|
||||
legacy.element_len = counter.0;
|
||||
if is_root {
|
||||
self.legacy.root = true;
|
||||
}
|
||||
Some(legacy)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum ElementEncoding {
|
||||
Raw,
|
||||
QuotedPrintable,
|
||||
}
|
||||
|
||||
struct ElementWriter<'s, S: Sink> {
|
||||
sink: &'s mut S,
|
||||
encoding: ElementEncoding,
|
||||
column: usize,
|
||||
last_ws: bool,
|
||||
}
|
||||
|
||||
impl<S: Sink> ElementWriter<'_, S> {
|
||||
fn text(&mut self, data: &[u8]) {
|
||||
match self.encoding {
|
||||
ElementEncoding::Raw => self.sink.put(data),
|
||||
ElementEncoding::QuotedPrintable => {
|
||||
for byte in data {
|
||||
self.qp_byte(*byte);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn qp_byte(&mut self, byte: u8) {
|
||||
let literal = matches!(byte, b' ' | b'\t' | b'!'..=b'<' | b'>'..=b'~');
|
||||
let width = if literal { 1 } else { 3 };
|
||||
if self.column + width > QP_MAX_COLUMN {
|
||||
self.sink.put(QP_SOFT_BREAK);
|
||||
self.column = 0;
|
||||
}
|
||||
if literal {
|
||||
self.sink.put(&[byte]);
|
||||
} else {
|
||||
self.sink.put(&[
|
||||
b'=',
|
||||
UPPER_HEX[usize::from(byte >> 4)],
|
||||
UPPER_HEX[usize::from(byte & 0x0F)],
|
||||
]);
|
||||
}
|
||||
self.column += width;
|
||||
self.last_ws = matches!(byte, b' ' | b'\t');
|
||||
}
|
||||
|
||||
fn newline(&mut self) {
|
||||
if self.encoding == ElementEncoding::QuotedPrintable && self.last_ws {
|
||||
self.sink.put(QP_SOFT_BREAK);
|
||||
}
|
||||
self.sink.put(CRLF);
|
||||
self.column = 0;
|
||||
self.last_ws = false;
|
||||
}
|
||||
|
||||
fn subject(&mut self, subject: Subject<'_>, markup: Markup) {
|
||||
let (bytes, unfold) = match subject {
|
||||
Subject::Decoded(bytes) => (bytes, false),
|
||||
Subject::Raw(bytes) => (bytes, true),
|
||||
};
|
||||
for byte in bytes {
|
||||
match (byte, markup) {
|
||||
(b'\r' | b'\n', _) if unfold => {}
|
||||
(b'&', Markup::Html) => self.text(b"&"),
|
||||
(b'<', Markup::Html) => self.text(b"<"),
|
||||
(b'>', Markup::Html) => self.text(b">"),
|
||||
_ => self.text(std::slice::from_ref(byte)),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl LegacyPart<'_> {
|
||||
fn write_element<S: Sink>(&self, sink: &mut S, encoding: ElementEncoding) {
|
||||
let mut writer = ElementWriter {
|
||||
sink,
|
||||
encoding,
|
||||
column: 0,
|
||||
last_ws: false,
|
||||
};
|
||||
match self.markup {
|
||||
Markup::Plain => {
|
||||
writer.text(SUBJECT_PREFIX);
|
||||
writer.subject(self.subject, self.markup);
|
||||
writer.newline();
|
||||
writer.newline();
|
||||
}
|
||||
Markup::Html => {
|
||||
writer.newline();
|
||||
writer.text(HTML_DIV);
|
||||
writer.newline();
|
||||
writer.text(HTML_PRE);
|
||||
writer.subject(self.subject, self.markup);
|
||||
writer.text(HTML_CLOSE);
|
||||
writer.newline();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_base64(&self) -> bool {
|
||||
self.transfer == Transfer::Base64
|
||||
}
|
||||
|
||||
pub(crate) fn write_inline<S: Sink>(&self, sink: &mut S) {
|
||||
let encoding = if self.transfer == Transfer::QuotedPrintable {
|
||||
ElementEncoding::QuotedPrintable
|
||||
} else {
|
||||
ElementEncoding::Raw
|
||||
};
|
||||
self.write_element(sink, encoding);
|
||||
}
|
||||
|
||||
pub(crate) fn base64_len(&self) -> usize {
|
||||
match self.element_len + self.decoded_len {
|
||||
0 => 0,
|
||||
len => MIME.encoded_len(len) - CRLF.len(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_base64<S: Sink>(&self, sink: &mut S) {
|
||||
let mut lines = Base64Lines {
|
||||
sink,
|
||||
line: [0u8; MIME_LINE_BYTES],
|
||||
filled: 0,
|
||||
started: false,
|
||||
};
|
||||
let mut splice = Splice {
|
||||
lines: &mut lines,
|
||||
remaining: Some(self.insert_at),
|
||||
part: self,
|
||||
};
|
||||
splice.insert_if_due();
|
||||
decode_base64(self.encoded_body, &mut splice);
|
||||
if splice.remaining.is_some() {
|
||||
self.write_element(splice.lines, ElementEncoding::Raw);
|
||||
}
|
||||
lines.finish();
|
||||
}
|
||||
}
|
||||
|
||||
struct Splice<'a, 'p, 's, S: Sink> {
|
||||
lines: &'a mut Base64Lines<'s, S>,
|
||||
remaining: Option<usize>,
|
||||
part: &'a LegacyPart<'p>,
|
||||
}
|
||||
|
||||
impl<S: Sink> Splice<'_, '_, '_, S> {
|
||||
fn insert_if_due(&mut self) {
|
||||
if self.remaining == Some(0) {
|
||||
self.part.write_element(self.lines, ElementEncoding::Raw);
|
||||
self.remaining = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Sink> Sink for Splice<'_, '_, '_, S> {
|
||||
fn put(&mut self, data: &[u8]) {
|
||||
match self.remaining {
|
||||
Some(remaining) if remaining <= data.len() => {
|
||||
let (head, tail) = data.split_at(remaining);
|
||||
self.lines.put(head);
|
||||
self.remaining = Some(0);
|
||||
self.insert_if_due();
|
||||
self.lines.put(tail);
|
||||
}
|
||||
Some(remaining) => {
|
||||
self.lines.put(data);
|
||||
self.remaining = Some(remaining - data.len());
|
||||
}
|
||||
None => self.lines.put(data),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Base64Lines<'s, S: Sink> {
|
||||
sink: &'s mut S,
|
||||
line: [u8; MIME_LINE_BYTES],
|
||||
filled: usize,
|
||||
started: bool,
|
||||
}
|
||||
|
||||
impl<S: Sink> Base64Lines<'_, S> {
|
||||
fn emit(&mut self) {
|
||||
if self.filled == 0 {
|
||||
return;
|
||||
}
|
||||
if self.started {
|
||||
self.sink.put(CRLF);
|
||||
}
|
||||
let mut encoded = [0u8; B64_ENCODED_LINE];
|
||||
let len = STANDARD
|
||||
.encode_slice(
|
||||
self.line.get(..self.filled).unwrap_or_default(),
|
||||
&mut encoded,
|
||||
)
|
||||
.unwrap_or_default();
|
||||
self.sink.put(encoded.get(..len).unwrap_or_default());
|
||||
self.started = true;
|
||||
self.filled = 0;
|
||||
}
|
||||
|
||||
fn finish(&mut self) {
|
||||
self.emit();
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Sink> Sink for Base64Lines<'_, S> {
|
||||
fn put(&mut self, mut data: &[u8]) {
|
||||
while !data.is_empty() {
|
||||
let free = self.line.get_mut(self.filled..).unwrap_or_default();
|
||||
let take = free.len().min(data.len());
|
||||
let (head, tail) = data.split_at(take);
|
||||
free.get_mut(..take)
|
||||
.unwrap_or_default()
|
||||
.copy_from_slice(head);
|
||||
self.filled += take;
|
||||
data = tail;
|
||||
if self.filled == MIME_LINE_BYTES {
|
||||
self.emit();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Copy, PartialEq, Eq)]
|
||||
enum TagState {
|
||||
#[default]
|
||||
Scan,
|
||||
Name(usize),
|
||||
Attributes,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct BodyTagFinder {
|
||||
offset: usize,
|
||||
state: TagState,
|
||||
found: Option<usize>,
|
||||
}
|
||||
|
||||
impl Sink for BodyTagFinder {
|
||||
fn put(&mut self, data: &[u8]) {
|
||||
let mut rest = data;
|
||||
while self.found.is_none() {
|
||||
if self.state == TagState::Scan {
|
||||
let Some(pos) = memchr::memchr(b'<', rest) else {
|
||||
self.offset += rest.len();
|
||||
return;
|
||||
};
|
||||
self.offset += pos + 1;
|
||||
rest = rest.get(pos + 1..).unwrap_or_default();
|
||||
self.state = TagState::Name(0);
|
||||
continue;
|
||||
}
|
||||
let Some((byte, tail)) = rest.split_first() else {
|
||||
return;
|
||||
};
|
||||
rest = tail;
|
||||
self.offset += 1;
|
||||
self.state = match self.state {
|
||||
TagState::Name(matched) => match BODY_TAG.get(matched) {
|
||||
Some(expected) if byte.to_ascii_lowercase() == *expected => {
|
||||
TagState::Name(matched + 1)
|
||||
}
|
||||
Some(_) if *byte == b'<' => TagState::Name(0),
|
||||
Some(_) => TagState::Scan,
|
||||
None if *byte == b'>' => {
|
||||
self.found = Some(self.offset);
|
||||
TagState::Scan
|
||||
}
|
||||
None if byte.is_ascii_whitespace() || *byte == b'/' => TagState::Attributes,
|
||||
None if *byte == b'<' => TagState::Name(0),
|
||||
None => TagState::Scan,
|
||||
},
|
||||
TagState::Attributes if *byte == b'>' => {
|
||||
self.found = Some(self.offset);
|
||||
TagState::Scan
|
||||
}
|
||||
state => state,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
130
crates/crypto/src/mime/mod.rs
Normal file
130
crates/crypto/src/mime/mod.rs
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub(crate) mod entity;
|
||||
pub(crate) mod legacy;
|
||||
pub mod protection;
|
||||
pub(crate) mod signed;
|
||||
|
||||
use legacy::LegacyPart;
|
||||
|
||||
pub(crate) trait Sink {
|
||||
fn put(&mut self, data: &[u8]);
|
||||
|
||||
fn put_reencoded(&mut self, part: &LegacyPart<'_>)
|
||||
where
|
||||
Self: Sized,
|
||||
{
|
||||
part.write_base64(self);
|
||||
}
|
||||
}
|
||||
|
||||
impl Sink for Vec<u8> {
|
||||
#[inline]
|
||||
fn put(&mut self, data: &[u8]) {
|
||||
self.extend_from_slice(data);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Counter(pub usize);
|
||||
|
||||
impl Sink for Counter {
|
||||
#[inline]
|
||||
fn put(&mut self, data: &[u8]) {
|
||||
self.0 += data.len();
|
||||
}
|
||||
|
||||
fn put_reencoded(&mut self, part: &LegacyPart<'_>) {
|
||||
self.0 += part.base64_len();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const CRLF: &[u8] = b"\r\n";
|
||||
pub(crate) const BOUNDARY_LEN: usize = 34;
|
||||
const BOUNDARY_PREFIX: &[u8; 2] = b"=_";
|
||||
const HEX: &[u8; 16] = b"0123456789abcdef";
|
||||
|
||||
pub(crate) fn boundary(random: &[u8; 16]) -> [u8; BOUNDARY_LEN] {
|
||||
let mut out = [0u8; BOUNDARY_LEN];
|
||||
let (prefix, hex) = out.split_at_mut(BOUNDARY_PREFIX.len());
|
||||
prefix.copy_from_slice(BOUNDARY_PREFIX);
|
||||
let (pairs, _) = hex.as_chunks_mut::<2>();
|
||||
for (pair, byte) in pairs.iter_mut().zip(random) {
|
||||
*pair = [HEX[usize::from(byte >> 4)], HEX[usize::from(byte & 0x0F)]];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
const SCAN_BLOCK: usize = 4096;
|
||||
|
||||
pub(crate) fn has_bare_lf(data: &[u8], prev_cr: bool) -> bool {
|
||||
let Some((first, rest)) = data.split_first() else {
|
||||
return false;
|
||||
};
|
||||
if *first == b'\n' && !prev_cr {
|
||||
return true;
|
||||
}
|
||||
let previous = data.get(..rest.len()).unwrap_or_default();
|
||||
rest.chunks(SCAN_BLOCK)
|
||||
.zip(previous.chunks(SCAN_BLOCK))
|
||||
.any(|(current, previous)| {
|
||||
current.iter().zip(previous).fold(0u8, |acc, (byte, prev)| {
|
||||
acc | (u8::from(*byte == b'\n') & u8::from(*prev != b'\r'))
|
||||
}) != 0
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) struct Canonical<'s, S: Sink> {
|
||||
sink: &'s mut S,
|
||||
prev_cr: bool,
|
||||
}
|
||||
|
||||
impl<'s, S: Sink> Canonical<'s, S> {
|
||||
pub(crate) fn new(sink: &'s mut S) -> Self {
|
||||
Canonical {
|
||||
sink,
|
||||
prev_cr: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn put_canonical(&mut self, data: &[u8]) {
|
||||
self.sink.put(data);
|
||||
if let Some(last) = data.last() {
|
||||
self.prev_cr = *last == b'\r';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: Sink> Sink for Canonical<'_, S> {
|
||||
fn put(&mut self, data: &[u8]) {
|
||||
if !has_bare_lf(data, self.prev_cr) {
|
||||
self.put_canonical(data);
|
||||
return;
|
||||
}
|
||||
let mut start = 0;
|
||||
for pos in memchr::memchr_iter(b'\n', data) {
|
||||
let has_cr = match pos.checked_sub(1) {
|
||||
Some(prev) => data.get(prev) == Some(&b'\r'),
|
||||
None => self.prev_cr,
|
||||
};
|
||||
if !has_cr {
|
||||
self.sink.put(data.get(start..pos).unwrap_or_default());
|
||||
self.sink.put(CRLF);
|
||||
start = pos + 1;
|
||||
}
|
||||
}
|
||||
self.sink.put(data.get(start..).unwrap_or_default());
|
||||
if let Some(last) = data.last() {
|
||||
self.prev_cr = *last == b'\r';
|
||||
}
|
||||
}
|
||||
|
||||
fn put_reencoded(&mut self, part: &LegacyPart<'_>) {
|
||||
self.sink.put_reencoded(part);
|
||||
self.prev_cr = false;
|
||||
}
|
||||
}
|
||||
241
crates/crypto/src/mime/protection.rs
Normal file
241
crates/crypto/src/mime/protection.rs
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::der::{oid, reader::Reader, tag};
|
||||
use encodify::base64::LENIENT;
|
||||
use mail_parser::{Message, MessagePart};
|
||||
use memchr::memmem;
|
||||
|
||||
const PGP_MESSAGE: &[u8] = b"-----BEGIN PGP MESSAGE-----";
|
||||
const PGP_MESSAGE_END: &[u8] = b"-----END PGP MESSAGE-----";
|
||||
const TAG_PKESK: u8 = 1;
|
||||
const TAG_SKESK: u8 = 3;
|
||||
const PGP_ENCRYPTED_PART: u32 = 2;
|
||||
const PGP_MIME_PARTS: usize = 3;
|
||||
const MAX_INLINE_PARTS: usize = 2;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Protection {
|
||||
None,
|
||||
Signed,
|
||||
Encrypted,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum MediaType {
|
||||
MultipartEncrypted,
|
||||
MultipartSigned,
|
||||
Pkcs7Mime,
|
||||
PgpEncrypted,
|
||||
OctetStream,
|
||||
Text,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum SmimeType {
|
||||
Enveloped,
|
||||
Signed,
|
||||
Other,
|
||||
}
|
||||
|
||||
fn media_type(main: &str, sub: &str) -> Option<MediaType> {
|
||||
if main.eq_ignore_ascii_case("text") {
|
||||
return Some(MediaType::Text);
|
||||
}
|
||||
if main.eq_ignore_ascii_case("multipart") {
|
||||
return hashify::map_ignore_case!(
|
||||
sub.as_bytes(),
|
||||
MediaType,
|
||||
"encrypted" => MediaType::MultipartEncrypted,
|
||||
"signed" => MediaType::MultipartSigned,
|
||||
)
|
||||
.copied();
|
||||
}
|
||||
if main.eq_ignore_ascii_case("application") {
|
||||
return hashify::map_ignore_case!(
|
||||
sub.as_bytes(),
|
||||
MediaType,
|
||||
"pkcs7-mime" => MediaType::Pkcs7Mime,
|
||||
"x-pkcs7-mime" => MediaType::Pkcs7Mime,
|
||||
"pgp-encrypted" => MediaType::PgpEncrypted,
|
||||
"octet-stream" => MediaType::OctetStream,
|
||||
)
|
||||
.copied();
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn smime_type(value: &str) -> SmimeType {
|
||||
hashify::map_ignore_case!(
|
||||
value.as_bytes(),
|
||||
SmimeType,
|
||||
"enveloped-data" => SmimeType::Enveloped,
|
||||
"authenveloped-data" => SmimeType::Enveloped,
|
||||
"signed-data" => SmimeType::Signed,
|
||||
)
|
||||
.copied()
|
||||
.unwrap_or(SmimeType::Other)
|
||||
}
|
||||
|
||||
fn has_p7m_name(part: &MessagePart<'_>) -> bool {
|
||||
let ends_p7m = |name: &str| {
|
||||
name.len() > 4
|
||||
&& name
|
||||
.get(name.len() - 4..)
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case(".p7m"))
|
||||
};
|
||||
part.content_type()
|
||||
.and_then(|ct| ct.attribute("name"))
|
||||
.is_some_and(ends_p7m)
|
||||
|| part
|
||||
.content_disposition()
|
||||
.and_then(|cd| cd.attribute("filename"))
|
||||
.is_some_and(ends_p7m)
|
||||
}
|
||||
|
||||
fn starts_with_pgp_message(part: &MessagePart<'_>) -> bool {
|
||||
part.raw_body().trim_ascii_start().starts_with(PGP_MESSAGE)
|
||||
}
|
||||
|
||||
pub fn protection(message: &Message<'_>) -> Protection {
|
||||
let root = message.root_part();
|
||||
let Some(ct) = root.content_type() else {
|
||||
return inline_protection(message);
|
||||
};
|
||||
match media_type(ct.ctype(), ct.subtype().unwrap_or_default()) {
|
||||
Some(MediaType::MultipartEncrypted) => {
|
||||
if ct
|
||||
.attribute("protocol")
|
||||
.is_some_and(|p| p.eq_ignore_ascii_case("application/pgp-encrypted"))
|
||||
{
|
||||
Protection::Encrypted
|
||||
} else {
|
||||
Protection::None
|
||||
}
|
||||
}
|
||||
Some(MediaType::MultipartSigned) => Protection::Signed,
|
||||
Some(MediaType::Pkcs7Mime) => match ct.attribute("smime-type").map(smime_type) {
|
||||
Some(SmimeType::Enveloped) => Protection::Encrypted,
|
||||
Some(SmimeType::Signed) => Protection::Signed,
|
||||
Some(SmimeType::Other) => Protection::None,
|
||||
None if has_p7m_name(&root) => Protection::Encrypted,
|
||||
None => Protection::None,
|
||||
},
|
||||
Some(MediaType::PgpEncrypted) => Protection::Encrypted,
|
||||
Some(MediaType::OctetStream) if has_p7m_name(&root) => Protection::Encrypted,
|
||||
_ => inline_protection(message),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_encrypted_media(main: &str, sub: &str, smime: Option<&str>) -> bool {
|
||||
match media_type(main, sub) {
|
||||
Some(MediaType::MultipartEncrypted | MediaType::PgpEncrypted) => true,
|
||||
Some(MediaType::Pkcs7Mime) => {
|
||||
matches!(smime.map(smime_type), Some(SmimeType::Enveloped))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_ciphertext(message: &Message<'_>) -> bool {
|
||||
let root = message.root_part();
|
||||
let Some(ct) = root.content_type() else {
|
||||
return inline_ciphertext(message);
|
||||
};
|
||||
match media_type(ct.ctype(), ct.subtype().unwrap_or_default()) {
|
||||
Some(MediaType::MultipartEncrypted) => {
|
||||
message.parts().len() == PGP_MIME_PARTS
|
||||
&& message
|
||||
.part(PGP_ENCRYPTED_PART)
|
||||
.is_some_and(|part| armored_ciphertext(&part.decoded()))
|
||||
}
|
||||
Some(MediaType::Pkcs7Mime) => cms_ciphertext(&root.decoded()),
|
||||
Some(MediaType::OctetStream) if has_p7m_name(&root) => cms_ciphertext(&root.decoded()),
|
||||
Some(MediaType::PgpEncrypted) => armored_ciphertext(&root.decoded()),
|
||||
_ => inline_ciphertext(message),
|
||||
}
|
||||
}
|
||||
|
||||
fn inline_ciphertext(message: &Message<'_>) -> bool {
|
||||
let mut found = false;
|
||||
for part in message.parts() {
|
||||
match part.content_type() {
|
||||
Some(ct) if ct.ctype().eq_ignore_ascii_case("multipart") => {}
|
||||
Some(ct)
|
||||
if !matches!(
|
||||
media_type(ct.ctype(), ct.subtype().unwrap_or_default()),
|
||||
Some(MediaType::Text)
|
||||
) =>
|
||||
{
|
||||
return false;
|
||||
}
|
||||
_ if armored_ciphertext(&part.decoded()) => found = true,
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn armored_ciphertext(body: &[u8]) -> bool {
|
||||
let Some(armor) = body
|
||||
.trim_ascii()
|
||||
.strip_prefix(PGP_MESSAGE)
|
||||
.and_then(|armor| armor.strip_suffix(PGP_MESSAGE_END))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if memmem::find(armor, b"-----").is_some() {
|
||||
return false;
|
||||
}
|
||||
armor
|
||||
.split(|&ch| ch == b'\n')
|
||||
.map(<[u8]>::trim_ascii)
|
||||
.skip(1)
|
||||
.skip_while(|line| !line.is_empty())
|
||||
.find(|line| !line.is_empty())
|
||||
.and_then(|line| LENIENT.decode(line).ok())
|
||||
.and_then(|data| data.first().copied())
|
||||
.is_some_and(is_encrypted_packet)
|
||||
}
|
||||
|
||||
fn is_encrypted_packet(header: u8) -> bool {
|
||||
let tag = if header & 0x40 != 0 {
|
||||
header & 0x3f
|
||||
} else {
|
||||
(header >> 2) & 0x0f
|
||||
};
|
||||
header & 0x80 != 0 && matches!(tag, TAG_PKESK | TAG_SKESK)
|
||||
}
|
||||
|
||||
fn cms_ciphertext(body: &[u8]) -> bool {
|
||||
Reader::new(body)
|
||||
.read_sequence()
|
||||
.ok()
|
||||
.and_then(|mut content_info| content_info.read_content(tag::OID).ok())
|
||||
.is_some_and(|id| id == oid::ENVELOPED_DATA || id == oid::AUTH_ENVELOPED_DATA)
|
||||
}
|
||||
|
||||
fn inline_protection(message: &Message<'_>) -> Protection {
|
||||
let parts = message.parts();
|
||||
if parts.len() > MAX_INLINE_PARTS {
|
||||
return Protection::None;
|
||||
}
|
||||
let inline = message.parts().any(|part| {
|
||||
let is_text = match part.content_type() {
|
||||
Some(ct) => matches!(
|
||||
media_type(ct.ctype(), ct.subtype().unwrap_or_default()),
|
||||
Some(MediaType::Text)
|
||||
),
|
||||
None => true,
|
||||
};
|
||||
is_text && starts_with_pgp_message(&part)
|
||||
});
|
||||
if inline {
|
||||
Protection::Encrypted
|
||||
} else {
|
||||
Protection::None
|
||||
}
|
||||
}
|
||||
55
crates/crypto/src/mime/signed.rs
Normal file
55
crates/crypto/src/mime/signed.rs
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use mail_parser::{Message, MessagePart};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum SignedProtocol {
|
||||
Pgp,
|
||||
Smime,
|
||||
}
|
||||
|
||||
pub(crate) struct DetachedSignature<'x> {
|
||||
pub protocol: SignedProtocol,
|
||||
pub content: &'x [u8],
|
||||
pub signature: MessagePart<'x>,
|
||||
}
|
||||
|
||||
pub(crate) fn detached_signature<'x>(message: &'x Message<'x>) -> Option<DetachedSignature<'x>> {
|
||||
let root = message.root_part();
|
||||
let ct = root.content_type()?;
|
||||
if !ct.ctype().eq_ignore_ascii_case("multipart")
|
||||
|| !ct.subtype()?.eq_ignore_ascii_case("signed")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let protocol = *hashify::map_ignore_case!(
|
||||
ct.attribute("protocol")?.trim().as_bytes(),
|
||||
SignedProtocol,
|
||||
"application/pgp-signature" => SignedProtocol::Pgp,
|
||||
"application/pkcs7-signature" => SignedProtocol::Smime,
|
||||
"application/x-pkcs7-signature" => SignedProtocol::Smime,
|
||||
)?;
|
||||
let mut children = root.children();
|
||||
let content = children.next()?.raw();
|
||||
let signature = children.next()?;
|
||||
Some(DetachedSignature {
|
||||
protocol,
|
||||
content,
|
||||
signature,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn opaque_signed_data<'x>(message: &'x Message<'x>) -> Option<MessagePart<'x>> {
|
||||
let root = message.root_part();
|
||||
let ct = root.content_type()?;
|
||||
let is_pkcs7 = ct.ctype().eq_ignore_ascii_case("application")
|
||||
&& hashify::set_ignore_case!(ct.subtype()?.as_bytes(), "pkcs7-mime", "x-pkcs7-mime");
|
||||
let signed = ct
|
||||
.attribute("smime-type")
|
||||
.is_some_and(|t| t.trim().eq_ignore_ascii_case("signed-data"));
|
||||
(is_pkcs7 && signed).then_some(root)
|
||||
}
|
||||
153
crates/crypto/src/pgp/armor.rs
Normal file
153
crates/crypto/src/pgp/armor.rs
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use encodify::base64::STANDARD;
|
||||
use memchr::memmem;
|
||||
|
||||
use crate::{backend::crc24::crc24, error::KeyError};
|
||||
|
||||
pub(crate) const BEGIN_MESSAGE: &[u8] = b"-----BEGIN PGP MESSAGE-----\r\n\r\n";
|
||||
pub(crate) const END_MESSAGE: &[u8] = b"-----END PGP MESSAGE-----\r\n";
|
||||
pub(crate) const CHECKSUM_LINE_LEN: usize = 7;
|
||||
const BEGIN: &[u8] = b"-----BEGIN ";
|
||||
const END: &[u8] = b"-----END ";
|
||||
const DASHES: &[u8] = b"-----";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ArmorLabel {
|
||||
PublicKey,
|
||||
PrivateKey,
|
||||
Message,
|
||||
Signature,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl ArmorLabel {
|
||||
fn parse(label: &[u8]) -> Self {
|
||||
hashify::map!(
|
||||
label,
|
||||
ArmorLabel,
|
||||
"PGP PUBLIC KEY BLOCK" => ArmorLabel::PublicKey,
|
||||
"PGP PRIVATE KEY BLOCK" => ArmorLabel::PrivateKey,
|
||||
"PGP SECRET KEY BLOCK" => ArmorLabel::PrivateKey,
|
||||
"PGP MESSAGE" => ArmorLabel::Message,
|
||||
"PGP SIGNATURE" => ArmorLabel::Signature,
|
||||
)
|
||||
.copied()
|
||||
.unwrap_or(ArmorLabel::Other)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct ArmorBlock<'x> {
|
||||
pub label: ArmorLabel,
|
||||
pub raw_label: &'x [u8],
|
||||
pub body: &'x [u8],
|
||||
}
|
||||
|
||||
pub(crate) fn checksum_line(data: &[u8]) -> [u8; CHECKSUM_LINE_LEN] {
|
||||
let [_, b0, b1, b2] = crc24(data).to_be_bytes();
|
||||
let mut line = *b"=XXXX\r\n";
|
||||
let _ = STANDARD.encode_slice([b0, b1, b2], &mut line[1..5]);
|
||||
line
|
||||
}
|
||||
|
||||
pub(crate) fn split_line(data: &[u8]) -> (&[u8], &[u8]) {
|
||||
match memchr::memchr(b'\n', data) {
|
||||
Some(pos) => {
|
||||
let (line, rest) = data.split_at(pos);
|
||||
(line.strip_suffix(b"\r").unwrap_or(line), &rest[1..])
|
||||
}
|
||||
None => (data.strip_suffix(b"\r").unwrap_or(data), &[]),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn next_block(data: &[u8]) -> Result<Option<(ArmorBlock<'_>, &[u8])>, KeyError> {
|
||||
let data = data.trim_ascii_start();
|
||||
if data.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let (line, rest) = split_line(data);
|
||||
let label = line
|
||||
.trim_ascii_end()
|
||||
.strip_prefix(BEGIN)
|
||||
.and_then(|l| l.strip_suffix(DASHES))
|
||||
.ok_or(KeyError::MalformedArmor)?;
|
||||
let finder = memmem::Finder::new(END);
|
||||
let end = finder.find(rest).ok_or(KeyError::MalformedArmor)?;
|
||||
let (body, tail) = rest.split_at(end);
|
||||
let (end_line, after) = split_line(tail);
|
||||
let end_label = end_line
|
||||
.trim_ascii_end()
|
||||
.strip_prefix(END)
|
||||
.and_then(|l| l.strip_suffix(DASHES))
|
||||
.ok_or(KeyError::MalformedArmor)?;
|
||||
if end_label != label {
|
||||
return Err(KeyError::MalformedArmor);
|
||||
}
|
||||
Ok(Some((
|
||||
ArmorBlock {
|
||||
label: ArmorLabel::parse(label),
|
||||
raw_label: label,
|
||||
body,
|
||||
},
|
||||
after,
|
||||
)))
|
||||
}
|
||||
|
||||
pub(crate) fn decode_body(body: &[u8], out: &mut Vec<u8>) -> Result<(), KeyError> {
|
||||
let mut rest = body;
|
||||
let mut in_headers = true;
|
||||
let mut text = Vec::with_capacity(body.len());
|
||||
while !rest.is_empty() {
|
||||
let (line, next) = split_line(rest);
|
||||
rest = next;
|
||||
let line = line.trim_ascii();
|
||||
if in_headers {
|
||||
if line.is_empty() {
|
||||
in_headers = false;
|
||||
continue;
|
||||
}
|
||||
if memchr::memchr(b':', line).is_some() {
|
||||
continue;
|
||||
}
|
||||
in_headers = false;
|
||||
}
|
||||
if line.first() == Some(&b'=') && line.len() == 5 {
|
||||
break;
|
||||
}
|
||||
text.extend_from_slice(line);
|
||||
}
|
||||
STANDARD
|
||||
.decode_append(&text, out)
|
||||
.map(drop)
|
||||
.map_err(|_| KeyError::MalformedArmor)
|
||||
}
|
||||
|
||||
pub(crate) fn is_armored(input: &[u8]) -> bool {
|
||||
input.trim_ascii_start().starts_with(BEGIN)
|
||||
}
|
||||
|
||||
pub(crate) fn dearmor_public_keys(input: &[u8]) -> Result<Cow<'_, [u8]>, KeyError> {
|
||||
if !is_armored(input) {
|
||||
return Ok(Cow::Borrowed(input));
|
||||
}
|
||||
let mut out = Vec::with_capacity(input.len() / 4 * 3);
|
||||
let mut rest = input;
|
||||
while let Some((block, next)) = next_block(rest)? {
|
||||
match block.label {
|
||||
ArmorLabel::PublicKey => decode_body(block.body, &mut out)?,
|
||||
ArmorLabel::PrivateKey => return Err(KeyError::SecretKey),
|
||||
ArmorLabel::Other if block.raw_label.ends_with(b"CERTIFICATE") => {
|
||||
return Err(KeyError::MixedKeyKinds);
|
||||
}
|
||||
_ => return Err(KeyError::MalformedArmor),
|
||||
}
|
||||
rest = next;
|
||||
}
|
||||
Ok(Cow::Owned(out))
|
||||
}
|
||||
627
crates/crypto/src/pgp/cert.rs
Normal file
627
crates/crypto/src/pgp/cert.rs
Normal file
|
|
@ -0,0 +1,627 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
backend::{
|
||||
aes::AesKeySize,
|
||||
agree::Curve,
|
||||
hash::HashAlgorithm,
|
||||
kem::{MlKem, MlKemPublicKey},
|
||||
rsa::{MAX_RSA_BITS, MIN_RSA_BITS, RsaPublicKey},
|
||||
},
|
||||
error::KeyError,
|
||||
pgp::{
|
||||
key::{
|
||||
ALG_ECDH, ALG_ECDSA, ALG_ED448, ALG_ED25519, ALG_EDDSA_LEGACY, ALG_MLDSA65_ED25519,
|
||||
ALG_MLDSA87_ED448, ALG_RSA, ALG_RSA_SIGN, EcdhCurve, KeyMaterial, KeyPacket,
|
||||
KeyVersion,
|
||||
},
|
||||
packet::{
|
||||
Packet, PacketReader, TAG_MARKER, TAG_PADDING, TAG_PUBLIC_KEY, TAG_PUBLIC_SUBKEY,
|
||||
TAG_SECRET_KEY, TAG_SECRET_SUBKEY, TAG_SIGNATURE, TAG_TRUST, TAG_USER_ATTRIBUTE,
|
||||
TAG_USER_ID,
|
||||
},
|
||||
signature::{
|
||||
AeadPrefs, FEATURE_SEIPDV2, FLAG_ENCRYPT_COMMUNICATIONS, FLAG_ENCRYPT_STORAGE,
|
||||
FLAG_SIGN, SIG_CERT_FIRST, SIG_CERT_LAST, SIG_DIRECT_KEY, SIG_KEY_REVOCATION,
|
||||
SIG_PRIMARY_BINDING, SIG_SUBKEY_BINDING, SIG_SUBKEY_REVOCATION, SigInfo, Signature,
|
||||
SymPrefs, hash_user_id,
|
||||
},
|
||||
},
|
||||
types::Fingerprint,
|
||||
};
|
||||
|
||||
const SIG_CERT_REVOCATION: u8 = 0x30;
|
||||
const ANONYMOUS_SENDER: &[u8; 20] = b"Anonymous Sender ";
|
||||
const MAX_KDF_PARAM_LEN: usize = 72;
|
||||
const WEAK_RSA_BITS: usize = 3072;
|
||||
const MAX_PACKETS: usize = 4096;
|
||||
|
||||
pub(crate) struct KdfParam {
|
||||
bytes: [u8; MAX_KDF_PARAM_LEN],
|
||||
len: u8,
|
||||
}
|
||||
|
||||
impl KdfParam {
|
||||
pub(crate) fn as_slice(&self) -> &[u8] {
|
||||
self.bytes.get(..usize::from(self.len)).unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) enum EncryptionKey {
|
||||
Rsa(RsaPublicKey),
|
||||
Ecdh {
|
||||
curve: EcdhCurve,
|
||||
point: Box<[u8]>,
|
||||
kdf_hash: HashAlgorithm,
|
||||
kek: AesKeySize,
|
||||
param: KdfParam,
|
||||
},
|
||||
X25519([u8; 32]),
|
||||
X448([u8; 56]),
|
||||
MlKem {
|
||||
ecdh: Box<[u8]>,
|
||||
kem: MlKemPublicKey,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) struct PgpKey {
|
||||
pub version: KeyVersion,
|
||||
pub algorithm: u8,
|
||||
pub fingerprint: Fingerprint,
|
||||
pub key_id: [u8; 8],
|
||||
pub seipd_v2: bool,
|
||||
pub sym_prefs: Option<SymPrefs>,
|
||||
pub aead_prefs: AeadPrefs,
|
||||
pub expires_at: Option<u64>,
|
||||
pub key: EncryptionKey,
|
||||
}
|
||||
|
||||
impl PgpKey {
|
||||
pub(crate) fn is_post_quantum(&self) -> bool {
|
||||
matches!(self.key, EncryptionKey::MlKem { .. })
|
||||
}
|
||||
|
||||
pub(crate) fn algorithm_name(&self) -> String {
|
||||
match &self.key {
|
||||
EncryptionKey::Rsa(key) => format!("RSA-{}", key.bits()),
|
||||
EncryptionKey::Ecdh {
|
||||
curve: EcdhCurve::Curve25519Legacy,
|
||||
..
|
||||
} => "X25519".to_string(),
|
||||
EncryptionKey::Ecdh {
|
||||
curve: EcdhCurve::Nist(curve),
|
||||
..
|
||||
} => format!("ECDH {}", curve.name()),
|
||||
EncryptionKey::X25519(_) => "X25519".to_string(),
|
||||
EncryptionKey::X448(_) => "X448".to_string(),
|
||||
EncryptionKey::MlKem { kem, .. } => match kem.kem() {
|
||||
MlKem::MlKem1024 => "ML-KEM-1024+X448".to_string(),
|
||||
kem => format!("{}+X25519", kem.name()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn heap_size(&self) -> usize {
|
||||
match &self.key {
|
||||
EncryptionKey::Rsa(key) => key.heap_size(),
|
||||
EncryptionKey::Ecdh { point, .. } => point.len(),
|
||||
EncryptionKey::X25519(_) | EncryptionKey::X448(_) => 0,
|
||||
EncryptionKey::MlKem { ecdh, kem } => ecdh.len() + kem.heap_size(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PgpCert {
|
||||
pub(crate) fn heap_size(&self) -> usize {
|
||||
self.keys
|
||||
.iter()
|
||||
.map(|key| size_of::<PgpKey>() + key.heap_size())
|
||||
.sum()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct PgpCert {
|
||||
pub fingerprint: Fingerprint,
|
||||
pub keys: Box<[PgpKey]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Purpose {
|
||||
Encrypt,
|
||||
Verify,
|
||||
}
|
||||
|
||||
pub(crate) const MAX_SIGNING_KEYS: usize = 4;
|
||||
const MAX_ENCRYPTION_KEYS: usize = 16;
|
||||
|
||||
pub(crate) struct ValidCert {
|
||||
pub cert: PgpCert,
|
||||
pub addresses: Vec<Box<str>>,
|
||||
pub weak_rsa: bool,
|
||||
pub signing: [Option<Fingerprint>; MAX_SIGNING_KEYS],
|
||||
}
|
||||
|
||||
struct RawSubkey<'x> {
|
||||
key: Result<KeyPacket<'x>, KeyError>,
|
||||
signatures: Vec<Signature<'x>>,
|
||||
}
|
||||
|
||||
struct RawUser<'x> {
|
||||
user_id: &'x [u8],
|
||||
signatures: Vec<Signature<'x>>,
|
||||
}
|
||||
|
||||
pub(crate) struct RawCert<'x> {
|
||||
primary: Result<KeyPacket<'x>, KeyError>,
|
||||
direct: Vec<Signature<'x>>,
|
||||
users: Vec<RawUser<'x>>,
|
||||
subkeys: Vec<RawSubkey<'x>>,
|
||||
}
|
||||
|
||||
enum Slot {
|
||||
Primary,
|
||||
User,
|
||||
Subkey,
|
||||
Ignored,
|
||||
}
|
||||
|
||||
pub(crate) fn split_certs(data: &[u8]) -> Result<Vec<RawCert<'_>>, KeyError> {
|
||||
let mut certs: Vec<RawCert<'_>> = Vec::new();
|
||||
let mut slot = Slot::Ignored;
|
||||
for (count, packet) in PacketReader::new(data).enumerate() {
|
||||
if count >= MAX_PACKETS {
|
||||
return Err(KeyError::TooLarge);
|
||||
}
|
||||
let Packet { tag, body } = packet?;
|
||||
match tag {
|
||||
TAG_PUBLIC_KEY => {
|
||||
certs.push(RawCert {
|
||||
primary: KeyPacket::parse(body),
|
||||
direct: Vec::new(),
|
||||
users: Vec::new(),
|
||||
subkeys: Vec::new(),
|
||||
});
|
||||
slot = Slot::Primary;
|
||||
continue;
|
||||
}
|
||||
TAG_SECRET_KEY | TAG_SECRET_SUBKEY => return Err(KeyError::SecretKey),
|
||||
TAG_MARKER | TAG_PADDING | TAG_TRUST => continue,
|
||||
_ => {}
|
||||
}
|
||||
let cert = certs.last_mut().ok_or(KeyError::MalformedPacket)?;
|
||||
match tag {
|
||||
TAG_SIGNATURE => {
|
||||
let Ok(signature) = Signature::parse(body) else {
|
||||
continue;
|
||||
};
|
||||
match slot {
|
||||
Slot::Primary => cert.direct.push(signature),
|
||||
Slot::User => {
|
||||
if let Some(user) = cert.users.last_mut() {
|
||||
user.signatures.push(signature);
|
||||
}
|
||||
}
|
||||
Slot::Subkey => {
|
||||
if let Some(subkey) = cert.subkeys.last_mut() {
|
||||
subkey.signatures.push(signature);
|
||||
}
|
||||
}
|
||||
Slot::Ignored => {}
|
||||
}
|
||||
}
|
||||
TAG_USER_ID => {
|
||||
cert.users.push(RawUser {
|
||||
user_id: body,
|
||||
signatures: Vec::new(),
|
||||
});
|
||||
slot = Slot::User;
|
||||
}
|
||||
TAG_USER_ATTRIBUTE => slot = Slot::Ignored,
|
||||
TAG_PUBLIC_SUBKEY => {
|
||||
cert.subkeys.push(RawSubkey {
|
||||
key: KeyPacket::parse(body),
|
||||
signatures: Vec::new(),
|
||||
});
|
||||
slot = Slot::Subkey;
|
||||
}
|
||||
0..40 => return Err(KeyError::MalformedPacket),
|
||||
_ => slot = Slot::Ignored,
|
||||
}
|
||||
}
|
||||
if certs.is_empty() {
|
||||
Err(KeyError::Empty)
|
||||
} else {
|
||||
Ok(certs)
|
||||
}
|
||||
}
|
||||
|
||||
fn newest_valid<'s, 'x>(
|
||||
signatures: impl Iterator<Item = &'s Signature<'x>>,
|
||||
mut verify: impl FnMut(&Signature<'x>) -> bool,
|
||||
) -> Option<&'s Signature<'x>>
|
||||
where
|
||||
'x: 's,
|
||||
{
|
||||
let mut candidates: Vec<&Signature<'x>> = signatures.collect();
|
||||
candidates.sort_unstable_by_key(|sig| std::cmp::Reverse(sig.info.created.unwrap_or(0)));
|
||||
candidates.into_iter().find(|sig| verify(sig))
|
||||
}
|
||||
|
||||
fn is_signing_algorithm(algorithm: u8) -> bool {
|
||||
matches!(
|
||||
algorithm,
|
||||
ALG_RSA
|
||||
| ALG_RSA_SIGN
|
||||
| ALG_ECDSA
|
||||
| ALG_EDDSA_LEGACY
|
||||
| ALG_ED25519
|
||||
| ALG_ED448
|
||||
| ALG_MLDSA65_ED25519
|
||||
| ALG_MLDSA87_ED448
|
||||
)
|
||||
}
|
||||
|
||||
fn expiry(created: u32, info: &SigInfo) -> Option<u64> {
|
||||
info.key_expires
|
||||
.map(|exp| u64::from(created) + u64::from(exp))
|
||||
}
|
||||
|
||||
pub(crate) fn email_address(user_id: &[u8]) -> Option<Box<str>> {
|
||||
let text = std::str::from_utf8(user_id).ok()?.trim();
|
||||
let address = match text.rsplit_once('<') {
|
||||
Some((_, rest)) => rest.split_once('>')?.0.trim(),
|
||||
None => text,
|
||||
};
|
||||
let (local, domain) = address.split_once('@')?;
|
||||
(!local.is_empty() && !domain.is_empty() && !address.contains(char::is_whitespace))
|
||||
.then(|| address.into())
|
||||
}
|
||||
|
||||
impl<'x> RawCert<'x> {
|
||||
pub(crate) fn validate(
|
||||
&self,
|
||||
primaries: &[&KeyPacket<'x>],
|
||||
now: u64,
|
||||
purpose: Purpose,
|
||||
) -> Result<ValidCert, KeyError> {
|
||||
let primary = self.primary.as_ref().map_err(|err| *err)?;
|
||||
if !is_signing_algorithm(primary.algorithm) {
|
||||
return Err(KeyError::UnsupportedPrimaryAlgorithm);
|
||||
}
|
||||
let verify_self =
|
||||
|sig: &Signature<'_>, data: &dyn Fn(&mut crate::backend::hash::Hasher)| {
|
||||
sig.is_issued_by(primary) && sig.verify(primary, data, now).is_ok()
|
||||
};
|
||||
let key_data = |h: &mut crate::backend::hash::Hasher| primary.hash_into(h);
|
||||
|
||||
let revoked = self
|
||||
.direct
|
||||
.iter()
|
||||
.filter(|sig| sig.sig_type == SIG_KEY_REVOCATION)
|
||||
.any(|sig| {
|
||||
if sig.is_issued_by(primary) {
|
||||
return sig.verify(primary, key_data, now).is_ok();
|
||||
}
|
||||
self.direct
|
||||
.iter()
|
||||
.filter_map(|d| d.info.revocation_key)
|
||||
.filter(|fp| Some(*fp) == sig.info.issuer_fingerprint)
|
||||
.filter_map(|fp| primaries.iter().find(|p| p.fingerprint == fp))
|
||||
.any(|revoker| sig.verify(revoker, key_data, now).is_ok())
|
||||
});
|
||||
if revoked {
|
||||
return Err(KeyError::Revoked);
|
||||
}
|
||||
|
||||
let direct = newest_valid(
|
||||
self.direct.iter().filter(|s| s.sig_type == SIG_DIRECT_KEY),
|
||||
|sig| verify_self(sig, &key_data),
|
||||
);
|
||||
let mut addresses = Vec::new();
|
||||
let mut primary_info: Option<SigInfo> = None;
|
||||
let mut primary_info_rank = (false, 0u32);
|
||||
for user in &self.users {
|
||||
let user_data = |h: &mut crate::backend::hash::Hasher| {
|
||||
primary.hash_into(h);
|
||||
hash_user_id(h, user.user_id);
|
||||
};
|
||||
let Some(sig) = newest_valid(
|
||||
user.signatures
|
||||
.iter()
|
||||
.filter(|s| (SIG_CERT_FIRST..=SIG_CERT_LAST).contains(&s.sig_type)),
|
||||
|sig| verify_self(sig, &user_data),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let created = sig.info.created.unwrap_or(0);
|
||||
let revoked = user
|
||||
.signatures
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
s.sig_type == SIG_CERT_REVOCATION && s.info.created.unwrap_or(0) >= created
|
||||
})
|
||||
.any(|s| verify_self(s, &user_data));
|
||||
if revoked {
|
||||
continue;
|
||||
}
|
||||
if let Some(address) = email_address(user.user_id) {
|
||||
addresses.push(address);
|
||||
}
|
||||
let rank = (sig.info.primary_uid, created);
|
||||
if primary_info.is_none() || rank > primary_info_rank {
|
||||
primary_info = Some(sig.info);
|
||||
primary_info_rank = rank;
|
||||
}
|
||||
}
|
||||
let info = match (primary.version, direct, primary_info) {
|
||||
(KeyVersion::V6, Some(direct), _) => direct.info,
|
||||
(KeyVersion::V6, None, _) => return Err(KeyError::NoValidSelfSignature),
|
||||
(KeyVersion::V4, _, Some(info)) => info,
|
||||
(KeyVersion::V4, Some(direct), None) => direct.info,
|
||||
(KeyVersion::V4, None, None) => return Err(KeyError::NoValidSelfSignature),
|
||||
};
|
||||
let primary_expiry = expiry(primary.created, &info)
|
||||
.or_else(|| direct.and_then(|d| expiry(primary.created, &d.info)));
|
||||
if primary_expiry.is_some_and(|exp| exp <= now) {
|
||||
return Err(KeyError::Expired);
|
||||
}
|
||||
|
||||
let mut error = KeyError::NoEncryptionKey;
|
||||
let mut candidates = vec![(primary, info, primary_expiry, None)];
|
||||
for subkey in &self.subkeys {
|
||||
let key = match &subkey.key {
|
||||
Ok(key) if key.version == primary.version => key,
|
||||
Ok(_) => continue,
|
||||
Err(err) => {
|
||||
error = *err;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let subkey_data = |h: &mut crate::backend::hash::Hasher| {
|
||||
primary.hash_into(h);
|
||||
key.hash_into(h);
|
||||
};
|
||||
let revoked = subkey
|
||||
.signatures
|
||||
.iter()
|
||||
.filter(|s| s.sig_type == SIG_SUBKEY_REVOCATION)
|
||||
.any(|s| verify_self(s, &subkey_data));
|
||||
if revoked {
|
||||
continue;
|
||||
}
|
||||
let Some(binding) = newest_valid(
|
||||
subkey
|
||||
.signatures
|
||||
.iter()
|
||||
.filter(|s| s.sig_type == SIG_SUBKEY_BINDING),
|
||||
|sig| verify_self(sig, &subkey_data),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let expires_at = match (expiry(key.created, &binding.info), primary_expiry) {
|
||||
(Some(a), Some(b)) => Some(a.min(b)),
|
||||
(a, b) => a.or(b),
|
||||
};
|
||||
candidates.push((key, binding.info, expires_at, Some(binding)));
|
||||
}
|
||||
|
||||
let mut keys = Vec::new();
|
||||
let mut weak_rsa = false;
|
||||
let mut signing = [None; MAX_SIGNING_KEYS];
|
||||
let mut signing_slots = signing.iter_mut();
|
||||
for (key, binding, expires_at, binding_sig) in candidates {
|
||||
let flags = binding.key_flags.unwrap_or(0);
|
||||
let expired = expires_at.is_some_and(|exp| exp <= now);
|
||||
if purpose == Purpose::Verify
|
||||
&& !expired
|
||||
&& match binding_sig {
|
||||
None => binding.key_flags.is_none_or(|f| f & FLAG_SIGN != 0),
|
||||
Some(sig) => {
|
||||
flags & FLAG_SIGN != 0 && has_primary_binding(sig, primary, key, now)
|
||||
}
|
||||
}
|
||||
&& let Some(slot) = signing_slots.next()
|
||||
{
|
||||
*slot = Some(key.fingerprint);
|
||||
}
|
||||
if flags & (FLAG_ENCRYPT_COMMUNICATIONS | FLAG_ENCRYPT_STORAGE) == 0
|
||||
|| keys.len() >= MAX_ENCRYPTION_KEYS
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if expired {
|
||||
error = KeyError::Expired;
|
||||
continue;
|
||||
}
|
||||
let features = binding.features.or(info.features);
|
||||
match encryption_key(key) {
|
||||
Ok((encryption_key, weak)) => {
|
||||
weak_rsa |= weak;
|
||||
keys.push(PgpKey {
|
||||
version: key.version,
|
||||
algorithm: key.algorithm,
|
||||
fingerprint: key.fingerprint,
|
||||
key_id: key.key_id(),
|
||||
seipd_v2: features
|
||||
.map(|f| f & FEATURE_SEIPDV2 != 0)
|
||||
.unwrap_or(key.version == KeyVersion::V6),
|
||||
sym_prefs: binding.sym_prefs.or(info.sym_prefs),
|
||||
aead_prefs: binding.aead_prefs.or(info.aead_prefs).unwrap_or_default(),
|
||||
expires_at,
|
||||
key: encryption_key,
|
||||
});
|
||||
}
|
||||
Err(err) => error = err,
|
||||
}
|
||||
}
|
||||
if keys.is_empty() && (purpose == Purpose::Encrypt || signing[0].is_none()) {
|
||||
return Err(error);
|
||||
}
|
||||
Ok(ValidCert {
|
||||
cert: PgpCert {
|
||||
fingerprint: primary.fingerprint,
|
||||
keys: keys.into_boxed_slice(),
|
||||
},
|
||||
addresses,
|
||||
weak_rsa,
|
||||
signing,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn key(&self, fingerprint: &Fingerprint) -> Option<&KeyPacket<'x>> {
|
||||
self.primary
|
||||
.as_ref()
|
||||
.ok()
|
||||
.into_iter()
|
||||
.chain(self.subkeys.iter().filter_map(|s| s.key.as_ref().ok()))
|
||||
.find(|key| key.fingerprint == *fingerprint)
|
||||
}
|
||||
|
||||
pub(crate) fn primary(&self) -> Option<&KeyPacket<'x>> {
|
||||
self.primary.as_ref().ok()
|
||||
}
|
||||
|
||||
pub(crate) fn certified_by(&self, signers: &[&KeyPacket<'_>], address: &str, now: u64) -> bool {
|
||||
let Ok(primary) = &self.primary else {
|
||||
return false;
|
||||
};
|
||||
self.users.iter().any(|user| {
|
||||
email_address(user.user_id).is_some_and(|bound| bound.eq_ignore_ascii_case(address))
|
||||
&& user
|
||||
.signatures
|
||||
.iter()
|
||||
.filter(|sig| (SIG_CERT_FIRST..=SIG_CERT_LAST).contains(&sig.sig_type))
|
||||
.any(|sig| {
|
||||
signers.iter().any(|signer| {
|
||||
signer.fingerprint != primary.fingerprint
|
||||
&& sig.is_issued_by(signer)
|
||||
&& sig
|
||||
.verify(
|
||||
signer,
|
||||
|h| {
|
||||
primary.hash_into(h);
|
||||
hash_user_id(h, user.user_id);
|
||||
},
|
||||
now,
|
||||
)
|
||||
.is_ok()
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn has_primary_binding(
|
||||
binding: &Signature<'_>,
|
||||
primary: &KeyPacket<'_>,
|
||||
subkey: &KeyPacket<'_>,
|
||||
now: u64,
|
||||
) -> bool {
|
||||
binding
|
||||
.embedded
|
||||
.and_then(|body| Signature::parse(body).ok())
|
||||
.is_some_and(|back| {
|
||||
back.sig_type == SIG_PRIMARY_BINDING
|
||||
&& back
|
||||
.verify(
|
||||
subkey,
|
||||
|h| {
|
||||
primary.hash_into(h);
|
||||
subkey.hash_into(h);
|
||||
},
|
||||
now,
|
||||
)
|
||||
.is_ok()
|
||||
})
|
||||
}
|
||||
|
||||
fn kdf_param(
|
||||
curve: EcdhCurve,
|
||||
hash_id: u8,
|
||||
kek_id: u8,
|
||||
fingerprint: &Fingerprint,
|
||||
) -> Result<KdfParam, KeyError> {
|
||||
let mut param = KdfParam {
|
||||
bytes: [0u8; MAX_KDF_PARAM_LEN],
|
||||
len: 0,
|
||||
};
|
||||
let oid = curve.oid();
|
||||
let parts: [&[u8]; 5] = [
|
||||
&[oid.len() as u8],
|
||||
oid,
|
||||
&[ALG_ECDH, 3, 1, hash_id, kek_id],
|
||||
ANONYMOUS_SENDER,
|
||||
fingerprint.as_bytes(),
|
||||
];
|
||||
let mut len = 0;
|
||||
for part in parts {
|
||||
let end = len + part.len();
|
||||
param
|
||||
.bytes
|
||||
.get_mut(len..end)
|
||||
.ok_or(KeyError::UnsupportedKeyAlgorithm)?
|
||||
.copy_from_slice(part);
|
||||
len = end;
|
||||
}
|
||||
param.len = len as u8;
|
||||
Ok(param)
|
||||
}
|
||||
|
||||
fn encryption_key(key: &KeyPacket<'_>) -> Result<(EncryptionKey, bool), KeyError> {
|
||||
Ok(match key.material {
|
||||
KeyMaterial::Rsa { n, e } if key.algorithm != ALG_RSA_SIGN => {
|
||||
let rsa = RsaPublicKey::from_components(n, e).map_err(|_| KeyError::WeakRsa)?;
|
||||
let bits = rsa.bits();
|
||||
if !(MIN_RSA_BITS..=MAX_RSA_BITS).contains(&bits) {
|
||||
return Err(KeyError::WeakRsa);
|
||||
}
|
||||
(EncryptionKey::Rsa(rsa), bits < WEAK_RSA_BITS)
|
||||
}
|
||||
KeyMaterial::Ecdh {
|
||||
curve,
|
||||
point,
|
||||
kdf_hash,
|
||||
kek,
|
||||
kdf_hash_id,
|
||||
kek_id,
|
||||
} => {
|
||||
curve
|
||||
.curve()
|
||||
.validate_public(point)
|
||||
.map_err(|_| KeyError::InvalidPublicKey)?;
|
||||
(
|
||||
EncryptionKey::Ecdh {
|
||||
curve,
|
||||
point: point.into(),
|
||||
kdf_hash,
|
||||
kek,
|
||||
param: kdf_param(curve, kdf_hash_id, kek_id, &key.fingerprint)?,
|
||||
},
|
||||
false,
|
||||
)
|
||||
}
|
||||
KeyMaterial::X25519(point) => (EncryptionKey::X25519(*point), false),
|
||||
KeyMaterial::X448(point) => (EncryptionKey::X448(*point), false),
|
||||
KeyMaterial::MlKem { kem, ecdh, mlkem } => {
|
||||
let curve = match kem {
|
||||
MlKem::MlKem1024 => Curve::X448,
|
||||
_ => Curve::X25519,
|
||||
};
|
||||
curve
|
||||
.validate_public(ecdh)
|
||||
.map_err(|_| KeyError::InvalidPublicKey)?;
|
||||
(
|
||||
EncryptionKey::MlKem {
|
||||
ecdh: ecdh.into(),
|
||||
kem: MlKemPublicKey::new(kem, mlkem).map_err(|_| KeyError::InvalidPublicKey)?,
|
||||
},
|
||||
false,
|
||||
)
|
||||
}
|
||||
_ => return Err(KeyError::UnsupportedKeyAlgorithm),
|
||||
})
|
||||
}
|
||||
665
crates/crypto/src/pgp/encrypt.rs
Normal file
665
crates/crypto/src/pgp/encrypt.rs
Normal file
|
|
@ -0,0 +1,665 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::{
|
||||
backend::{
|
||||
PrimitiveError,
|
||||
aes::{AesCipher, AesKeySize, BLOCK_LEN, cfb_encrypt_zero_iv},
|
||||
agree::Curve,
|
||||
base64::ARMOR,
|
||||
hash::HashAlgorithm,
|
||||
kdf::{HkdfHash, openpgp_ecdh},
|
||||
kem::MlKem,
|
||||
ocb::OcbKey,
|
||||
rng::Rng,
|
||||
symmetric::GcmKey,
|
||||
},
|
||||
error::{EncryptError, ProfileError},
|
||||
mime::{BOUNDARY_LEN, CRLF, Sink, boundary, entity::Entity},
|
||||
pgp::{
|
||||
armor::{BEGIN_MESSAGE, END_MESSAGE, checksum_line},
|
||||
cert::{EncryptionKey, PgpCert, PgpKey},
|
||||
key::{EcdhCurve, KeyVersion, SYM_AES128, SYM_AES256, aes_key_id},
|
||||
packet::{
|
||||
TAG_LITERAL, TAG_PADDING, TAG_PKESK, TAG_SEIPD, header_bytes, header_len, mpi_header,
|
||||
write_header,
|
||||
},
|
||||
signature::SymPrefs,
|
||||
},
|
||||
types::{EncryptOptions, HeaderProtection, Profile, RecipientIds},
|
||||
};
|
||||
|
||||
pub(crate) const AEAD_OCB: u8 = 2;
|
||||
pub(crate) const AEAD_GCM: u8 = 3;
|
||||
const TAG_LEN: usize = 16;
|
||||
const SALT_LEN: usize = 32;
|
||||
const SINGLE_CHUNK_OCTET: u8 = 16;
|
||||
pub(crate) const MULTI_CHUNK_OCTET: u8 = 12;
|
||||
const LITERAL_FIELDS: [u8; 6] = [b'b', 0, 0, 0, 0, 0];
|
||||
const LITERAL_OVERHEAD: usize = LITERAL_FIELDS.len();
|
||||
const MDC_LEN: usize = 22;
|
||||
const MDC_HEADER: [u8; 2] = [0xD3, 0x14];
|
||||
const PREFIX_LEN: usize = BLOCK_LEN + 2;
|
||||
const PADDING_GRANULE: usize = 512;
|
||||
const MAX_FIELDS: usize = 2048;
|
||||
const MAX_SESSION_KEY: usize = 32;
|
||||
const X25519_INFO: &[u8] = b"OpenPGP X25519";
|
||||
const X448_INFO: &[u8] = b"OpenPGP X448";
|
||||
const COMBINER_DOMAIN: &[u8] = b"OpenPGPCompositeKDFv1";
|
||||
const PKESK_V3: u8 = 3;
|
||||
const PKESK_V6: u8 = 6;
|
||||
const SEIPD_V1: u8 = 1;
|
||||
const SEIPD_V2: u8 = 2;
|
||||
const MAX_MESSAGE_LEN: usize = u32::MAX as usize - (1 << 20);
|
||||
|
||||
const MIME_HEADER_START: &[u8] =
|
||||
b"Content-Type: multipart/encrypted;\r\n\tprotocol=\"application/pgp-encrypted\";\r\n\tboundary=\"";
|
||||
const MIME_HEADER_END: &[u8] =
|
||||
b"\"\r\n\r\nOpenPGP/MIME message (Automatically encrypted by Stalwart)\r\n\r\n";
|
||||
const VERSION_PART: &[u8] =
|
||||
b"\r\nContent-Type: application/pgp-encrypted\r\n\r\nVersion: 1\r\n\r\n";
|
||||
const DATA_PART: &[u8] = b"\r\nContent-Type: application/octet-stream; name=\"encrypted.asc\"\r\nContent-Disposition: inline; filename=\"encrypted.asc\"\r\n\r\n";
|
||||
const DASHES: &[u8] = b"--";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Row {
|
||||
V1 { cipher: AesKeySize },
|
||||
V2 { cipher: AesKeySize, aead: u8 },
|
||||
}
|
||||
|
||||
pub(crate) fn selected_keys(
|
||||
certs: &[PgpCert],
|
||||
profile: Profile,
|
||||
) -> impl Iterator<Item = &PgpKey> + Clone {
|
||||
certs.iter().flat_map(move |cert| {
|
||||
let has_classical = cert.keys.iter().any(|k| !k.is_post_quantum());
|
||||
cert.keys.iter().filter(move |key| match profile {
|
||||
Profile::Compatible => !key.is_post_quantum() || !has_classical,
|
||||
Profile::Modern => true,
|
||||
Profile::PostQuantum => key.is_post_quantum(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn check_profile(certs: &[PgpCert], profile: Profile) -> Result<(), ProfileError> {
|
||||
if profile == Profile::PostQuantum
|
||||
&& certs
|
||||
.iter()
|
||||
.any(|cert| !cert.keys.iter().any(PgpKey::is_post_quantum))
|
||||
{
|
||||
return Err(ProfileError::NoPostQuantumKey);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn accepts_pair(key: &PgpKey, pair: (u8, u8)) -> bool {
|
||||
pair == (SYM_AES128, AEAD_OCB)
|
||||
|| (key.is_post_quantum() && pair == (SYM_AES256, AEAD_OCB))
|
||||
|| key.aead_prefs.as_slice().contains(&pair)
|
||||
}
|
||||
|
||||
fn accepts_aes256_v1(key: &PgpKey) -> bool {
|
||||
key.is_post_quantum() || key.sym_prefs.is_some_and(|p| p.contains(SymPrefs::AES256))
|
||||
}
|
||||
|
||||
fn aes_size(id: u8) -> AesKeySize {
|
||||
match id {
|
||||
SYM_AES256 => AesKeySize::Aes256,
|
||||
SYM_AES128 => AesKeySize::Aes128,
|
||||
_ => AesKeySize::Aes192,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn select_row<'x>(
|
||||
keys: impl Iterator<Item = &'x PgpKey> + Clone,
|
||||
profile: Profile,
|
||||
) -> Result<Row, EncryptError> {
|
||||
let mut iter = keys.clone();
|
||||
let first = iter.next().ok_or(EncryptError::NoRecipients)?;
|
||||
if !keys.clone().all(|k| k.seipd_v2) {
|
||||
return Ok(Row::V1 {
|
||||
cipher: if keys.clone().all(accepts_aes256_v1) {
|
||||
AesKeySize::Aes256
|
||||
} else {
|
||||
AesKeySize::Aes128
|
||||
},
|
||||
});
|
||||
}
|
||||
let all_accept = |pair: (u8, u8)| keys.clone().all(|k| accepts_pair(k, pair));
|
||||
let (cipher, aead) =
|
||||
if profile == Profile::PostQuantum || keys.clone().any(PgpKey::is_post_quantum) {
|
||||
[(SYM_AES256, AEAD_OCB), (SYM_AES256, AEAD_GCM)]
|
||||
.into_iter()
|
||||
.find(|pair| all_accept(*pair))
|
||||
.unwrap_or((SYM_AES256, AEAD_OCB))
|
||||
} else {
|
||||
let chosen = first
|
||||
.aead_prefs
|
||||
.as_slice()
|
||||
.iter()
|
||||
.copied()
|
||||
.chain([(SYM_AES128, AEAD_OCB)])
|
||||
.find(|pair| all_accept(*pair))
|
||||
.unwrap_or((SYM_AES128, AEAD_OCB));
|
||||
if profile == Profile::Modern
|
||||
&& chosen.0 != SYM_AES256
|
||||
&& all_accept((SYM_AES256, chosen.1))
|
||||
{
|
||||
(SYM_AES256, chosen.1)
|
||||
} else {
|
||||
chosen
|
||||
}
|
||||
};
|
||||
Ok(Row::V2 {
|
||||
cipher: aes_size(cipher),
|
||||
aead,
|
||||
})
|
||||
}
|
||||
|
||||
struct Fields {
|
||||
buf: [u8; MAX_FIELDS],
|
||||
len: usize,
|
||||
}
|
||||
|
||||
impl Fields {
|
||||
fn new() -> Self {
|
||||
Fields {
|
||||
buf: [0u8; MAX_FIELDS],
|
||||
len: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn put(&mut self, data: &[u8]) -> Result<(), PrimitiveError> {
|
||||
let end = self.len + data.len();
|
||||
self.buf
|
||||
.get_mut(self.len..end)
|
||||
.ok_or(PrimitiveError::InvalidLength)?
|
||||
.copy_from_slice(data);
|
||||
self.len = end;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reserve(&mut self, len: usize) -> Result<&mut [u8], PrimitiveError> {
|
||||
let end = self.len + len;
|
||||
let slot = self
|
||||
.buf
|
||||
.get_mut(self.len..end)
|
||||
.ok_or(PrimitiveError::InvalidLength)?;
|
||||
self.len = end;
|
||||
Ok(slot)
|
||||
}
|
||||
|
||||
fn put_mpi(&mut self, value: &[u8]) -> Result<(), PrimitiveError> {
|
||||
let (bits, value) = mpi_header(value);
|
||||
self.put(&bits)?;
|
||||
self.put(value)
|
||||
}
|
||||
|
||||
fn as_slice(&self) -> &[u8] {
|
||||
&self.buf[..self.len]
|
||||
}
|
||||
}
|
||||
|
||||
fn checksum(key: &[u8]) -> [u8; 2] {
|
||||
(key.iter().map(|b| u32::from(*b)).sum::<u32>() as u16).to_be_bytes()
|
||||
}
|
||||
|
||||
pub(crate) fn mlkem_kek(
|
||||
mlkem_shared: &[u8],
|
||||
ecdh_shared: &[u8],
|
||||
ecdh_ciphertext: &[u8],
|
||||
ecdh_public: &[u8],
|
||||
algorithm: u8,
|
||||
) -> Zeroizing<[u8; 32]> {
|
||||
let mut hasher = HashAlgorithm::Sha3_256.hasher();
|
||||
for part in [mlkem_shared, ecdh_shared, ecdh_ciphertext, ecdh_public] {
|
||||
hasher.update(part);
|
||||
}
|
||||
hasher.update(&[algorithm]);
|
||||
hasher.update(COMBINER_DOMAIN);
|
||||
hasher.update(&[COMBINER_DOMAIN.len() as u8]);
|
||||
let mut kek = Zeroizing::new([0u8; 32]);
|
||||
kek.copy_from_slice(hasher.finish().as_ref());
|
||||
kek
|
||||
}
|
||||
|
||||
fn wrap_into(
|
||||
fields: &mut Fields,
|
||||
kek: &[u8],
|
||||
sym: Option<u8>,
|
||||
session_key: &[u8],
|
||||
with_length: bool,
|
||||
) -> Result<(), PrimitiveError> {
|
||||
let wrapped_len = AesCipher::wrap_len(session_key.len());
|
||||
if with_length {
|
||||
fields.put(&[(wrapped_len + usize::from(sym.is_some())) as u8])?;
|
||||
}
|
||||
if let Some(sym) = sym {
|
||||
fields.put(&[sym])?;
|
||||
}
|
||||
let slot = fields.reserve(wrapped_len)?;
|
||||
AesCipher::new(kek)?.wrap(session_key, slot)
|
||||
}
|
||||
|
||||
fn pkesk_fields(
|
||||
key: &PgpKey,
|
||||
sym: Option<u8>,
|
||||
session_key: &[u8],
|
||||
rng: &mut impl Rng,
|
||||
fields: &mut Fields,
|
||||
) -> Result<(), PrimitiveError> {
|
||||
match &key.key {
|
||||
EncryptionKey::Rsa(rsa) => {
|
||||
let mut m = Zeroizing::new([0u8; MAX_SESSION_KEY + 3]);
|
||||
let mut len = 0;
|
||||
if let Some(sym) = sym {
|
||||
m[0] = sym;
|
||||
len = 1;
|
||||
}
|
||||
m[len..len + session_key.len()].copy_from_slice(session_key);
|
||||
len += session_key.len();
|
||||
m[len..len + 2].copy_from_slice(&checksum(session_key));
|
||||
len += 2;
|
||||
let mut ct = [0u8; 1024];
|
||||
let ct = ct
|
||||
.get_mut(..rsa.ciphertext_len())
|
||||
.ok_or(PrimitiveError::InvalidLength)?;
|
||||
rsa.encrypt_pkcs1(&m[..len], ct)?;
|
||||
fields.put_mpi(ct)
|
||||
}
|
||||
EncryptionKey::Ecdh {
|
||||
curve,
|
||||
point,
|
||||
kdf_hash,
|
||||
kek,
|
||||
param,
|
||||
} => {
|
||||
let agreement = curve.curve().ephemeral_agree(point, rng)?;
|
||||
let mut kek_bytes = Zeroizing::new([0u8; 32]);
|
||||
let kek_bytes = &mut kek_bytes[..kek.key_len()];
|
||||
openpgp_ecdh(
|
||||
*kdf_hash,
|
||||
agreement.shared(),
|
||||
&[param.as_slice()],
|
||||
kek_bytes,
|
||||
)?;
|
||||
let mut m = Zeroizing::new([0u8; 48]);
|
||||
let mut len = 0;
|
||||
if let Some(sym) = sym {
|
||||
m[0] = sym;
|
||||
len = 1;
|
||||
}
|
||||
m[len..len + session_key.len()].copy_from_slice(session_key);
|
||||
len += session_key.len();
|
||||
m[len..len + 2].copy_from_slice(&checksum(session_key));
|
||||
len += 2;
|
||||
let pad = 8 - len % 8;
|
||||
m[len..len + pad].fill(pad as u8);
|
||||
len += pad;
|
||||
match curve {
|
||||
EcdhCurve::Curve25519Legacy => {
|
||||
let mut native = [0u8; 33];
|
||||
native[0] = 0x40;
|
||||
native[1..].copy_from_slice(agreement.public());
|
||||
fields.put(&263u16.to_be_bytes())?;
|
||||
fields.put(&native)?;
|
||||
}
|
||||
EcdhCurve::Nist(_) => fields.put_mpi(agreement.public())?,
|
||||
}
|
||||
fields.put(&[AesCipher::wrap_len(len) as u8])?;
|
||||
let slot = fields.reserve(AesCipher::wrap_len(len))?;
|
||||
AesCipher::new(kek_bytes)?.wrap(&m[..len], slot)
|
||||
}
|
||||
EncryptionKey::X25519(recipient) => {
|
||||
let agreement = Curve::X25519.ephemeral_agree(recipient, rng)?;
|
||||
let mut kek = Zeroizing::new([0u8; 16]);
|
||||
HkdfHash::Sha256.derive(
|
||||
&[],
|
||||
&[agreement.public(), recipient, agreement.shared()],
|
||||
&[X25519_INFO],
|
||||
kek.as_mut(),
|
||||
)?;
|
||||
fields.put(agreement.public())?;
|
||||
wrap_into(fields, kek.as_ref(), sym, session_key, true)
|
||||
}
|
||||
EncryptionKey::X448(recipient) => {
|
||||
let agreement = Curve::X448.ephemeral_agree(recipient, rng)?;
|
||||
let mut kek = Zeroizing::new([0u8; 32]);
|
||||
HkdfHash::Sha512.derive(
|
||||
&[],
|
||||
&[agreement.public(), recipient, agreement.shared()],
|
||||
&[X448_INFO],
|
||||
kek.as_mut(),
|
||||
)?;
|
||||
fields.put(agreement.public())?;
|
||||
wrap_into(fields, kek.as_ref(), sym, session_key, true)
|
||||
}
|
||||
EncryptionKey::MlKem { ecdh, kem } => {
|
||||
let curve = match kem.kem() {
|
||||
MlKem::MlKem1024 => Curve::X448,
|
||||
_ => Curve::X25519,
|
||||
};
|
||||
let agreement = curve.ephemeral_agree(ecdh, rng)?;
|
||||
let encapsulation = kem.encapsulate()?;
|
||||
let kek = mlkem_kek(
|
||||
encapsulation.shared(),
|
||||
agreement.shared(),
|
||||
agreement.public(),
|
||||
ecdh,
|
||||
key.algorithm,
|
||||
);
|
||||
fields.put(agreement.public())?;
|
||||
fields.put(encapsulation.ciphertext())?;
|
||||
wrap_into(fields, kek.as_ref(), sym, session_key, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn write_pkesk(
|
||||
out: &mut Vec<u8>,
|
||||
key: &PgpKey,
|
||||
row: Row,
|
||||
ids: RecipientIds,
|
||||
session_key: &[u8],
|
||||
rng: &mut impl Rng,
|
||||
) -> Result<(), EncryptError> {
|
||||
let mut fields = Fields::new();
|
||||
let fp = key.fingerprint.as_bytes();
|
||||
match (row, ids) {
|
||||
(Row::V1 { cipher }, _) => {
|
||||
fields.put(&[PKESK_V3])?;
|
||||
fields.put(match ids {
|
||||
RecipientIds::Real => &key.key_id,
|
||||
RecipientIds::Anonymous => &[0u8; 8],
|
||||
})?;
|
||||
fields.put(&[key.algorithm])?;
|
||||
pkesk_fields(key, Some(aes_key_id(cipher)), session_key, rng, &mut fields)?;
|
||||
}
|
||||
(Row::V2 { .. }, RecipientIds::Real) => {
|
||||
let version = match key.version {
|
||||
KeyVersion::V4 => 4,
|
||||
KeyVersion::V6 => 6,
|
||||
};
|
||||
fields.put(&[PKESK_V6, (fp.len() + 1) as u8, version])?;
|
||||
fields.put(fp)?;
|
||||
fields.put(&[key.algorithm])?;
|
||||
pkesk_fields(key, None, session_key, rng, &mut fields)?;
|
||||
}
|
||||
(Row::V2 { .. }, RecipientIds::Anonymous) => {
|
||||
fields.put(&[PKESK_V6, 0, key.algorithm])?;
|
||||
pkesk_fields(key, None, session_key, rng, &mut fields)?;
|
||||
}
|
||||
}
|
||||
write_header(out, TAG_PKESK, fields.len);
|
||||
out.extend_from_slice(fields.as_slice());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) const fn pkesk_upper_bound(key: &PgpKey) -> usize {
|
||||
let fields = match &key.key {
|
||||
EncryptionKey::Rsa(_) => 1026,
|
||||
EncryptionKey::Ecdh { .. } => 2 + 133 + 1 + 48,
|
||||
EncryptionKey::X25519(_) => 32 + 2 + 40,
|
||||
EncryptionKey::X448(_) => 56 + 2 + 40,
|
||||
EncryptionKey::MlKem { .. } => 56 + 1568 + 2 + 40,
|
||||
};
|
||||
6 + 1 + 1 + 1 + 32 + 1 + fields
|
||||
}
|
||||
|
||||
pub(crate) struct ChunkWriter<'a> {
|
||||
pub out: &'a mut Vec<u8>,
|
||||
pub chunk: usize,
|
||||
pub filled: usize,
|
||||
}
|
||||
|
||||
impl Sink for ChunkWriter<'_> {
|
||||
fn put(&mut self, mut data: &[u8]) {
|
||||
while !data.is_empty() {
|
||||
if self.filled == self.chunk {
|
||||
self.out.extend_from_slice(&[0u8; TAG_LEN]);
|
||||
self.filled = 0;
|
||||
}
|
||||
let (head, rest) = data.split_at((self.chunk - self.filled).min(data.len()));
|
||||
self.out.extend_from_slice(head);
|
||||
self.filled += head.len();
|
||||
data = rest;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn padding_len(plain_len: usize) -> usize {
|
||||
let body = PADDING_GRANULE - (plain_len + 2) % PADDING_GRANULE;
|
||||
body.max(1)
|
||||
}
|
||||
|
||||
pub(crate) fn encrypt(
|
||||
message: &Entity<'_>,
|
||||
certs: &[PgpCert],
|
||||
options: &EncryptOptions,
|
||||
rng: &mut impl Rng,
|
||||
) -> Result<Vec<u8>, EncryptError> {
|
||||
check_profile(certs, options.profile)?;
|
||||
let keys = selected_keys(certs, options.profile);
|
||||
let row = select_row(keys.clone(), options.profile)?;
|
||||
let inner_len = message.inner_len();
|
||||
if inner_len > MAX_MESSAGE_LEN {
|
||||
return Err(EncryptError::MessageTooLarge);
|
||||
}
|
||||
let literal_body = LITERAL_OVERHEAD + inner_len;
|
||||
let literal_total = header_len(literal_body) + literal_body;
|
||||
|
||||
let (cipher, plain_len, padding_body, chunk_octet) = match row {
|
||||
Row::V1 { cipher } => (cipher, literal_total, 0, 0),
|
||||
Row::V2 { cipher, .. } => {
|
||||
let padding_body = if options.header_protection == HeaderProtection::Baseline {
|
||||
padding_len(literal_total)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let plain = literal_total
|
||||
+ if padding_body > 0 {
|
||||
header_len(padding_body) + padding_body
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let octet = if plain <= 1 << (u32::from(SINGLE_CHUNK_OCTET) + 6) {
|
||||
SINGLE_CHUNK_OCTET
|
||||
} else {
|
||||
MULTI_CHUNK_OCTET
|
||||
};
|
||||
(cipher, plain, padding_body, octet)
|
||||
}
|
||||
};
|
||||
let seipd_body = match row {
|
||||
Row::V1 { .. } => 1 + PREFIX_LEN + plain_len + MDC_LEN,
|
||||
Row::V2 { .. } => {
|
||||
let chunk = 1usize << (u32::from(chunk_octet) + 6);
|
||||
4 + SALT_LEN + plain_len + plain_len.div_ceil(chunk) * TAG_LEN + TAG_LEN
|
||||
}
|
||||
};
|
||||
let pkesk_bound: usize = keys.clone().map(pkesk_upper_bound).sum();
|
||||
let mut scratch = Vec::with_capacity(pkesk_bound + header_len(seipd_body) + seipd_body);
|
||||
|
||||
let mut session_key = Zeroizing::new([0u8; MAX_SESSION_KEY]);
|
||||
let session_key = &mut session_key[..cipher.key_len()];
|
||||
rng.fill(session_key)?;
|
||||
for key in keys {
|
||||
write_pkesk(
|
||||
&mut scratch,
|
||||
key,
|
||||
row,
|
||||
options.recipient_ids,
|
||||
session_key,
|
||||
rng,
|
||||
)?;
|
||||
}
|
||||
write_header(&mut scratch, TAG_SEIPD, seipd_body);
|
||||
match row {
|
||||
Row::V1 { .. } => {
|
||||
scratch.push(SEIPD_V1);
|
||||
let start = scratch.len();
|
||||
let mut prefix = [0u8; PREFIX_LEN];
|
||||
rng.fill(&mut prefix[..BLOCK_LEN])?;
|
||||
prefix[BLOCK_LEN] = prefix[BLOCK_LEN - 2];
|
||||
prefix[BLOCK_LEN + 1] = prefix[BLOCK_LEN - 1];
|
||||
scratch.extend_from_slice(&prefix);
|
||||
write_header(&mut scratch, TAG_LITERAL, literal_body);
|
||||
scratch.extend_from_slice(&LITERAL_FIELDS);
|
||||
message.write_inner(&mut scratch);
|
||||
scratch.extend_from_slice(&MDC_HEADER);
|
||||
let mdc = HashAlgorithm::Sha1.digest(&scratch[start..]);
|
||||
scratch.extend_from_slice(mdc.as_ref());
|
||||
cfb_encrypt_zero_iv(session_key, &mut scratch[start..])?;
|
||||
}
|
||||
Row::V2 { cipher, aead } => {
|
||||
let info = [0xD2, SEIPD_V2, aes_key_id(cipher), aead, chunk_octet];
|
||||
scratch.extend_from_slice(&info[1..]);
|
||||
let mut salt = [0u8; SALT_LEN];
|
||||
rng.fill(&mut salt)?;
|
||||
scratch.extend_from_slice(&salt);
|
||||
let start = scratch.len();
|
||||
let chunk = 1usize << (u32::from(chunk_octet) + 6);
|
||||
let mut writer = ChunkWriter {
|
||||
out: &mut scratch,
|
||||
chunk,
|
||||
filled: 0,
|
||||
};
|
||||
let (header, header_size) = header_bytes(TAG_LITERAL, literal_body);
|
||||
writer.put(&header[..header_size]);
|
||||
writer.put(&LITERAL_FIELDS);
|
||||
message.write_inner(&mut writer);
|
||||
if padding_body > 0 {
|
||||
let (header, header_size) = header_bytes(TAG_PADDING, padding_body);
|
||||
writer.put(&header[..header_size]);
|
||||
let mut random = [0u8; PADDING_GRANULE];
|
||||
rng.fill(&mut random[..padding_body])?;
|
||||
writer.put(&random[..padding_body]);
|
||||
}
|
||||
if writer.filled > 0 {
|
||||
writer.out.extend_from_slice(&[0u8; TAG_LEN]);
|
||||
}
|
||||
scratch.extend_from_slice(&[0u8; TAG_LEN]);
|
||||
seal_v2(
|
||||
&mut scratch[start..],
|
||||
session_key,
|
||||
&salt,
|
||||
&info,
|
||||
aead,
|
||||
chunk,
|
||||
plain_len,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
session_key.fill(0);
|
||||
|
||||
let checksum = match row {
|
||||
Row::V1 { .. } => Some(checksum_line(&scratch)),
|
||||
Row::V2 { .. } => None,
|
||||
};
|
||||
let armored = ARMOR.encoded_len(scratch.len()) + checksum.as_ref().map_or(0, |line| line.len());
|
||||
let total = message.outer_len()
|
||||
+ MIME_HEADER_START.len()
|
||||
+ BOUNDARY_LEN
|
||||
+ MIME_HEADER_END.len()
|
||||
+ 2 * (DASHES.len() + BOUNDARY_LEN)
|
||||
+ VERSION_PART.len()
|
||||
+ DATA_PART.len()
|
||||
+ BEGIN_MESSAGE.len()
|
||||
+ armored
|
||||
+ END_MESSAGE.len()
|
||||
+ CRLF.len()
|
||||
+ DASHES.len()
|
||||
+ BOUNDARY_LEN
|
||||
+ DASHES.len()
|
||||
+ CRLF.len();
|
||||
let mut random = [0u8; 16];
|
||||
rng.fill(&mut random)?;
|
||||
let boundary = boundary(&random);
|
||||
let mut out = Vec::with_capacity(total);
|
||||
message.write_outer(&mut out);
|
||||
for part in [
|
||||
MIME_HEADER_START,
|
||||
&boundary,
|
||||
MIME_HEADER_END,
|
||||
DASHES,
|
||||
&boundary,
|
||||
VERSION_PART,
|
||||
DASHES,
|
||||
&boundary,
|
||||
DATA_PART,
|
||||
BEGIN_MESSAGE,
|
||||
] {
|
||||
out.extend_from_slice(part);
|
||||
}
|
||||
ARMOR.encode_append(&scratch, &mut out);
|
||||
if let Some(line) = &checksum {
|
||||
out.extend_from_slice(line);
|
||||
}
|
||||
for part in [END_MESSAGE, CRLF, DASHES, &boundary, DASHES, CRLF] {
|
||||
out.extend_from_slice(part);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(crate) fn seal_v2(
|
||||
data: &mut [u8],
|
||||
session_key: &[u8],
|
||||
salt: &[u8; SALT_LEN],
|
||||
info: &[u8; 5],
|
||||
aead: u8,
|
||||
chunk: usize,
|
||||
plain_len: usize,
|
||||
) -> Result<(), EncryptError> {
|
||||
let key_len = session_key.len();
|
||||
let nonce_len = if aead == AEAD_OCB { 15 } else { 12 };
|
||||
let iv_len = nonce_len - 8;
|
||||
let mut okm = Zeroizing::new([0u8; MAX_SESSION_KEY + 8]);
|
||||
let okm = &mut okm[..key_len + iv_len];
|
||||
HkdfHash::Sha256.derive(salt, &[session_key], &[info], okm)?;
|
||||
let (message_key, iv) = okm.split_at(key_len);
|
||||
let mut nonce = [0u8; 15];
|
||||
nonce[..iv_len].copy_from_slice(iv);
|
||||
let mut final_ad = [0u8; 13];
|
||||
final_ad[..5].copy_from_slice(info);
|
||||
final_ad[5..].copy_from_slice(&(plain_len as u64).to_be_bytes());
|
||||
|
||||
let (body, final_tag) = data
|
||||
.split_last_chunk_mut::<TAG_LEN>()
|
||||
.ok_or(EncryptError::MalformedMessage)?;
|
||||
let chunk_count = plain_len.div_ceil(chunk) as u64;
|
||||
match aead {
|
||||
AEAD_OCB => {
|
||||
let key = OcbKey::new(message_key)?;
|
||||
let ad_hash = key.hash(info);
|
||||
for (index, segment) in (0u64..).zip(body.chunks_mut(chunk + TAG_LEN)) {
|
||||
nonce[iv_len..nonce_len].copy_from_slice(&index.to_be_bytes());
|
||||
let (plain, tag) = segment
|
||||
.split_last_chunk_mut::<TAG_LEN>()
|
||||
.ok_or(EncryptError::MalformedMessage)?;
|
||||
*tag = key.seal_in_place(&nonce[..nonce_len], ad_hash, plain)?;
|
||||
}
|
||||
nonce[iv_len..nonce_len].copy_from_slice(&chunk_count.to_be_bytes());
|
||||
*final_tag = key.seal_in_place(&nonce[..nonce_len], key.hash(&final_ad), &mut [])?;
|
||||
}
|
||||
_ => {
|
||||
let key = GcmKey::new(message_key)?;
|
||||
let mut gcm_nonce = [0u8; 12];
|
||||
gcm_nonce[..iv_len].copy_from_slice(&nonce[..iv_len]);
|
||||
for (index, segment) in (0u64..).zip(body.chunks_mut(chunk + TAG_LEN)) {
|
||||
gcm_nonce[iv_len..].copy_from_slice(&index.to_be_bytes());
|
||||
let (plain, tag) = segment
|
||||
.split_last_chunk_mut::<TAG_LEN>()
|
||||
.ok_or(EncryptError::MalformedMessage)?;
|
||||
*tag = key.seal_in_place(gcm_nonce, info, plain)?;
|
||||
}
|
||||
gcm_nonce[iv_len..].copy_from_slice(&chunk_count.to_be_bytes());
|
||||
*final_tag = key.seal_in_place(gcm_nonce, &final_ad, &mut [])?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
394
crates/crypto/src/pgp/key.rs
Normal file
394
crates/crypto/src/pgp/key.rs
Normal file
|
|
@ -0,0 +1,394 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
backend::{
|
||||
aes::AesKeySize,
|
||||
agree::Curve,
|
||||
hash::HashAlgorithm,
|
||||
kem::MlKem,
|
||||
verify::{EcCurve, MlDsa},
|
||||
},
|
||||
error::KeyError,
|
||||
pgp::packet::Fields,
|
||||
types::Fingerprint,
|
||||
};
|
||||
|
||||
pub(crate) const ALG_RSA: u8 = 1;
|
||||
pub(crate) const ALG_RSA_ENCRYPT: u8 = 2;
|
||||
pub(crate) const ALG_RSA_SIGN: u8 = 3;
|
||||
pub(crate) const ALG_ELGAMAL: u8 = 16;
|
||||
pub(crate) const ALG_DSA: u8 = 17;
|
||||
pub(crate) const ALG_ECDH: u8 = 18;
|
||||
pub(crate) const ALG_ECDSA: u8 = 19;
|
||||
pub(crate) const ALG_ELGAMAL_SIGN: u8 = 20;
|
||||
pub(crate) const ALG_EDDSA_LEGACY: u8 = 22;
|
||||
pub(crate) const ALG_X25519: u8 = 25;
|
||||
pub(crate) const ALG_X448: u8 = 26;
|
||||
pub(crate) const ALG_ED25519: u8 = 27;
|
||||
pub(crate) const ALG_ED448: u8 = 28;
|
||||
pub(crate) const ALG_MLDSA65_ED25519: u8 = 30;
|
||||
pub(crate) const ALG_MLDSA87_ED448: u8 = 31;
|
||||
pub(crate) const ALG_SLHDSA_FIRST: u8 = 32;
|
||||
pub(crate) const ALG_SLHDSA_LAST: u8 = 34;
|
||||
pub(crate) const ALG_MLKEM768_X25519: u8 = 35;
|
||||
pub(crate) const ALG_MLKEM1024_X448: u8 = 36;
|
||||
|
||||
pub(crate) const SYM_AES128: u8 = 7;
|
||||
pub(crate) const SYM_AES192: u8 = 8;
|
||||
pub(crate) const SYM_AES256: u8 = 9;
|
||||
|
||||
const OID_P256: &[u8] = &[0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x03, 0x01, 0x07];
|
||||
const OID_P384: &[u8] = &[0x2B, 0x81, 0x04, 0x00, 0x22];
|
||||
const OID_P521: &[u8] = &[0x2B, 0x81, 0x04, 0x00, 0x23];
|
||||
const OID_CURVE25519_LEGACY: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0x97, 0x55, 0x01, 0x05, 0x01];
|
||||
const OID_ED25519_LEGACY: &[u8] = &[0x2B, 0x06, 0x01, 0x04, 0x01, 0xDA, 0x47, 0x0F, 0x01];
|
||||
const OID_BRAINPOOL_PREFIX: &[u8] = &[0x2B, 0x24, 0x03, 0x03, 0x02, 0x08, 0x01, 0x01];
|
||||
|
||||
const ED25519_LEN: usize = 32;
|
||||
const ED448_LEN: usize = 57;
|
||||
const X25519_LEN: usize = 32;
|
||||
const X448_LEN: usize = 56;
|
||||
const NATIVE_POINT_PREFIX: u8 = 0x40;
|
||||
const MLDSA65_PUBLIC_LEN: usize = 1952;
|
||||
const MLDSA87_PUBLIC_LEN: usize = 2592;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub(crate) enum KeyVersion {
|
||||
V4,
|
||||
V6,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum EcdhCurve {
|
||||
Nist(Curve),
|
||||
Curve25519Legacy,
|
||||
}
|
||||
|
||||
impl EcdhCurve {
|
||||
pub(crate) fn oid(self) -> &'static [u8] {
|
||||
match self {
|
||||
EcdhCurve::Nist(Curve::P256) => OID_P256,
|
||||
EcdhCurve::Nist(Curve::P384) => OID_P384,
|
||||
EcdhCurve::Nist(_) => OID_P521,
|
||||
EcdhCurve::Curve25519Legacy => OID_CURVE25519_LEGACY,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn curve(self) -> Curve {
|
||||
match self {
|
||||
EcdhCurve::Nist(curve) => curve,
|
||||
EcdhCurve::Curve25519Legacy => Curve::X25519,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum KeyMaterial<'x> {
|
||||
Rsa {
|
||||
n: &'x [u8],
|
||||
e: &'x [u8],
|
||||
},
|
||||
Ecdsa {
|
||||
curve: EcCurve,
|
||||
point: &'x [u8],
|
||||
},
|
||||
EdDsaLegacy {
|
||||
point: &'x [u8; ED25519_LEN],
|
||||
},
|
||||
Ecdh {
|
||||
curve: EcdhCurve,
|
||||
point: &'x [u8],
|
||||
kdf_hash: HashAlgorithm,
|
||||
kek: AesKeySize,
|
||||
kdf_hash_id: u8,
|
||||
kek_id: u8,
|
||||
},
|
||||
X25519(&'x [u8; X25519_LEN]),
|
||||
X448(&'x [u8; X448_LEN]),
|
||||
Ed25519(&'x [u8; ED25519_LEN]),
|
||||
Ed448(&'x [u8; ED448_LEN]),
|
||||
MlKem {
|
||||
kem: MlKem,
|
||||
ecdh: &'x [u8],
|
||||
mlkem: &'x [u8],
|
||||
},
|
||||
MlDsa {
|
||||
dsa: MlDsa,
|
||||
eddsa: &'x [u8],
|
||||
mldsa: &'x [u8],
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct KeyPacket<'x> {
|
||||
pub version: KeyVersion,
|
||||
pub created: u32,
|
||||
pub algorithm: u8,
|
||||
pub material: KeyMaterial<'x>,
|
||||
pub body: &'x [u8],
|
||||
pub fingerprint: Fingerprint,
|
||||
}
|
||||
|
||||
pub(crate) fn hash_id(id: u8) -> Option<HashAlgorithm> {
|
||||
match id {
|
||||
2 => Some(HashAlgorithm::Sha1),
|
||||
8 => Some(HashAlgorithm::Sha256),
|
||||
9 => Some(HashAlgorithm::Sha384),
|
||||
10 => Some(HashAlgorithm::Sha512),
|
||||
11 => Some(HashAlgorithm::Sha224),
|
||||
12 => Some(HashAlgorithm::Sha3_256),
|
||||
14 => Some(HashAlgorithm::Sha3_512),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn aes_id(id: u8) -> Option<AesKeySize> {
|
||||
match id {
|
||||
SYM_AES128 => Some(AesKeySize::Aes128),
|
||||
SYM_AES192 => Some(AesKeySize::Aes192),
|
||||
SYM_AES256 => Some(AesKeySize::Aes256),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn aes_key_id(size: AesKeySize) -> u8 {
|
||||
match size {
|
||||
AesKeySize::Aes128 => SYM_AES128,
|
||||
AesKeySize::Aes192 => SYM_AES192,
|
||||
AesKeySize::Aes256 => SYM_AES256,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_oid(fields: &mut Fields<'_>) -> Result<&'static [u8], KeyError> {
|
||||
let oid = fields.short_bytes()?;
|
||||
[
|
||||
OID_P256,
|
||||
OID_P384,
|
||||
OID_P521,
|
||||
OID_CURVE25519_LEGACY,
|
||||
OID_ED25519_LEGACY,
|
||||
]
|
||||
.into_iter()
|
||||
.find(|known| *known == oid)
|
||||
.ok_or(if oid.starts_with(OID_BRAINPOOL_PREFIX) {
|
||||
KeyError::Brainpool
|
||||
} else {
|
||||
KeyError::UnsupportedKeyAlgorithm
|
||||
})
|
||||
}
|
||||
|
||||
fn native_point(point: &[u8]) -> Result<&[u8; 32], KeyError> {
|
||||
match point.split_first() {
|
||||
Some((&NATIVE_POINT_PREFIX, rest)) => {
|
||||
rest.try_into().map_err(|_| KeyError::MalformedPacket)
|
||||
}
|
||||
_ => Err(KeyError::MalformedPacket),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_material<'x>(
|
||||
algorithm: u8,
|
||||
fields: &mut Fields<'x>,
|
||||
version: KeyVersion,
|
||||
) -> Result<KeyMaterial<'x>, KeyError> {
|
||||
Ok(match algorithm {
|
||||
ALG_RSA | ALG_RSA_ENCRYPT | ALG_RSA_SIGN => KeyMaterial::Rsa {
|
||||
n: fields.mpi()?,
|
||||
e: fields.mpi()?,
|
||||
},
|
||||
ALG_ECDSA => {
|
||||
let curve = match parse_oid(fields)? {
|
||||
OID_P256 => EcCurve::P256,
|
||||
OID_P384 => EcCurve::P384,
|
||||
OID_P521 => EcCurve::P521,
|
||||
_ => return Err(KeyError::UnsupportedKeyAlgorithm),
|
||||
};
|
||||
KeyMaterial::Ecdsa {
|
||||
curve,
|
||||
point: fields.mpi()?,
|
||||
}
|
||||
}
|
||||
ALG_EDDSA_LEGACY => {
|
||||
if parse_oid(fields)? != OID_ED25519_LEGACY || version == KeyVersion::V6 {
|
||||
return Err(KeyError::UnsupportedKeyAlgorithm);
|
||||
}
|
||||
KeyMaterial::EdDsaLegacy {
|
||||
point: native_point(fields.mpi()?)?,
|
||||
}
|
||||
}
|
||||
ALG_ECDH => {
|
||||
let curve = match parse_oid(fields)? {
|
||||
OID_P256 => EcdhCurve::Nist(Curve::P256),
|
||||
OID_P384 => EcdhCurve::Nist(Curve::P384),
|
||||
OID_P521 => EcdhCurve::Nist(Curve::P521),
|
||||
OID_CURVE25519_LEGACY if version == KeyVersion::V4 => EcdhCurve::Curve25519Legacy,
|
||||
_ => return Err(KeyError::UnsupportedKeyAlgorithm),
|
||||
};
|
||||
let point = fields.mpi()?;
|
||||
let point = match curve {
|
||||
EcdhCurve::Curve25519Legacy => native_point(point)?.as_slice(),
|
||||
EcdhCurve::Nist(_) => point,
|
||||
};
|
||||
let kdf = fields.short_bytes()?;
|
||||
let [1, kdf_hash_id, kek_id] = kdf else {
|
||||
return Err(KeyError::MalformedPacket);
|
||||
};
|
||||
KeyMaterial::Ecdh {
|
||||
curve,
|
||||
point,
|
||||
kdf_hash: hash_id(*kdf_hash_id)
|
||||
.filter(|h| {
|
||||
!matches!(
|
||||
h,
|
||||
HashAlgorithm::Sha1 | HashAlgorithm::Sha3_256 | HashAlgorithm::Sha3_512
|
||||
)
|
||||
})
|
||||
.ok_or(KeyError::UnsupportedKeyAlgorithm)?,
|
||||
kek: aes_id(*kek_id).ok_or(KeyError::UnsupportedKeyAlgorithm)?,
|
||||
kdf_hash_id: *kdf_hash_id,
|
||||
kek_id: *kek_id,
|
||||
}
|
||||
}
|
||||
ALG_X25519 => KeyMaterial::X25519(
|
||||
fields
|
||||
.bytes(X25519_LEN)?
|
||||
.try_into()
|
||||
.map_err(|_| KeyError::MalformedPacket)?,
|
||||
),
|
||||
ALG_X448 => KeyMaterial::X448(
|
||||
fields
|
||||
.bytes(X448_LEN)?
|
||||
.try_into()
|
||||
.map_err(|_| KeyError::MalformedPacket)?,
|
||||
),
|
||||
ALG_ED25519 => KeyMaterial::Ed25519(
|
||||
fields
|
||||
.bytes(ED25519_LEN)?
|
||||
.try_into()
|
||||
.map_err(|_| KeyError::MalformedPacket)?,
|
||||
),
|
||||
ALG_ED448 => KeyMaterial::Ed448(
|
||||
fields
|
||||
.bytes(ED448_LEN)?
|
||||
.try_into()
|
||||
.map_err(|_| KeyError::MalformedPacket)?,
|
||||
),
|
||||
ALG_MLKEM768_X25519 => KeyMaterial::MlKem {
|
||||
kem: MlKem::MlKem768,
|
||||
ecdh: fields.bytes(X25519_LEN)?,
|
||||
mlkem: fields.bytes(MlKem::MlKem768.public_len())?,
|
||||
},
|
||||
ALG_MLKEM1024_X448 if version == KeyVersion::V6 => KeyMaterial::MlKem {
|
||||
kem: MlKem::MlKem1024,
|
||||
ecdh: fields.bytes(X448_LEN)?,
|
||||
mlkem: fields.bytes(MlKem::MlKem1024.public_len())?,
|
||||
},
|
||||
ALG_MLDSA65_ED25519 if version == KeyVersion::V6 => KeyMaterial::MlDsa {
|
||||
dsa: MlDsa::MlDsa65,
|
||||
eddsa: fields.bytes(ED25519_LEN)?,
|
||||
mldsa: fields.bytes(MLDSA65_PUBLIC_LEN)?,
|
||||
},
|
||||
ALG_MLDSA87_ED448 if version == KeyVersion::V6 => KeyMaterial::MlDsa {
|
||||
dsa: MlDsa::MlDsa87,
|
||||
eddsa: fields.bytes(ED448_LEN)?,
|
||||
mldsa: fields.bytes(MLDSA87_PUBLIC_LEN)?,
|
||||
},
|
||||
ALG_ELGAMAL | ALG_ELGAMAL_SIGN => return Err(KeyError::Elgamal),
|
||||
ALG_DSA | ALG_SLHDSA_FIRST..=ALG_SLHDSA_LAST => {
|
||||
return Err(KeyError::UnsupportedPrimaryAlgorithm);
|
||||
}
|
||||
_ => return Err(KeyError::UnsupportedKeyAlgorithm),
|
||||
})
|
||||
}
|
||||
|
||||
impl<'x> KeyPacket<'x> {
|
||||
pub(crate) fn parse(body: &'x [u8]) -> Result<Self, KeyError> {
|
||||
let mut fields = Fields::new(body);
|
||||
let version = match fields.u8()? {
|
||||
4 => KeyVersion::V4,
|
||||
6 => KeyVersion::V6,
|
||||
_ => return Err(KeyError::UnsupportedKeyVersion),
|
||||
};
|
||||
let created = fields.u32()?;
|
||||
let algorithm = fields.u8()?;
|
||||
let material = if version == KeyVersion::V6 {
|
||||
let len = fields.u32()? as usize;
|
||||
let mut material_fields = Fields::new(fields.bytes(len)?);
|
||||
let material = parse_material(algorithm, &mut material_fields, version)?;
|
||||
if !material_fields.is_empty() {
|
||||
return Err(KeyError::MalformedPacket);
|
||||
}
|
||||
material
|
||||
} else {
|
||||
parse_material(algorithm, &mut fields, version)?
|
||||
};
|
||||
if !fields.is_empty() {
|
||||
return Err(KeyError::MalformedPacket);
|
||||
}
|
||||
Ok(KeyPacket {
|
||||
version,
|
||||
created,
|
||||
algorithm,
|
||||
material,
|
||||
body,
|
||||
fingerprint: fingerprint(version, body),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn key_id(&self) -> [u8; 8] {
|
||||
let mut id = [0u8; 8];
|
||||
match &self.fingerprint {
|
||||
Fingerprint::V4(fp) => id.copy_from_slice(&fp[12..]),
|
||||
Fingerprint::V6(fp) | Fingerprint::X509Sha256(fp) => id.copy_from_slice(&fp[..8]),
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
pub(crate) fn hash_into(&self, hasher: &mut crate::backend::hash::Hasher) {
|
||||
hash_key_body(self.version, self.body, hasher);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn hash_key_body(
|
||||
version: KeyVersion,
|
||||
body: &[u8],
|
||||
hasher: &mut crate::backend::hash::Hasher,
|
||||
) {
|
||||
match version {
|
||||
KeyVersion::V4 => {
|
||||
hasher.update(&[0x99]);
|
||||
hasher.update(&(body.len() as u16).to_be_bytes());
|
||||
}
|
||||
KeyVersion::V6 => {
|
||||
hasher.update(&[0x9B]);
|
||||
hasher.update(&(body.len() as u32).to_be_bytes());
|
||||
}
|
||||
}
|
||||
hasher.update(body);
|
||||
}
|
||||
|
||||
fn fingerprint(version: KeyVersion, body: &[u8]) -> Fingerprint {
|
||||
let alg = match version {
|
||||
KeyVersion::V4 => HashAlgorithm::Sha1,
|
||||
KeyVersion::V6 => HashAlgorithm::Sha256,
|
||||
};
|
||||
let mut hasher = alg.hasher();
|
||||
hash_key_body(version, body, &mut hasher);
|
||||
let digest = hasher.finish();
|
||||
match version {
|
||||
KeyVersion::V4 => {
|
||||
let mut fp = [0u8; 20];
|
||||
fp.copy_from_slice(digest.as_ref());
|
||||
Fingerprint::V4(fp)
|
||||
}
|
||||
KeyVersion::V6 => {
|
||||
let mut fp = [0u8; 32];
|
||||
fp.copy_from_slice(digest.as_ref());
|
||||
Fingerprint::V6(fp)
|
||||
}
|
||||
}
|
||||
}
|
||||
206
crates/crypto/src/pgp/mod.rs
Normal file
206
crates/crypto/src/pgp/mod.rs
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub(crate) mod armor;
|
||||
pub(crate) mod cert;
|
||||
pub(crate) mod encrypt;
|
||||
pub(crate) mod key;
|
||||
pub(crate) mod packet;
|
||||
pub(crate) mod signature;
|
||||
pub(crate) mod verify;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
error::KeyError,
|
||||
pgp::packet::{
|
||||
Packet, PacketReader, TAG_MARKER, TAG_PADDING, TAG_PUBLIC_KEY, TAG_SIGNATURE, TAG_TRUST,
|
||||
TAG_USER_ATTRIBUTE, TAG_USER_ID,
|
||||
},
|
||||
types::{
|
||||
AddressKey, KeyCapabilities, KeyCapability, KeyKind, KeyWarning, ParsedKeys, RecipientSet,
|
||||
Recipients,
|
||||
},
|
||||
};
|
||||
|
||||
pub const EXPIRES_SOON_SECS: u64 = 14 * 86_400;
|
||||
const MAX_ADDRESS_KEYS: usize = 5;
|
||||
|
||||
pub(crate) fn parse_public_keys_for(
|
||||
input: &[u8],
|
||||
address: &str,
|
||||
now: u64,
|
||||
) -> Result<Vec<AddressKey>, KeyError> {
|
||||
let binary = armor::dearmor_public_keys(input)?;
|
||||
let mut keys = Vec::new();
|
||||
let mut first_error = None;
|
||||
let mut current = Vec::new();
|
||||
let mut keep_signatures = false;
|
||||
let mut has_user_id = false;
|
||||
let mut reader = PacketReader::new(&binary);
|
||||
loop {
|
||||
let packet = if reader.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(reader.read_raw()?)
|
||||
};
|
||||
if matches!(
|
||||
packet,
|
||||
None | Some((
|
||||
Packet {
|
||||
tag: TAG_PUBLIC_KEY,
|
||||
..
|
||||
},
|
||||
_
|
||||
))
|
||||
) {
|
||||
if has_user_id && keys.len() < MAX_ADDRESS_KEYS {
|
||||
match parse_public_keys(¤t, now) {
|
||||
Ok(parsed) => keys.push(AddressKey {
|
||||
parsed,
|
||||
key: std::mem::take(&mut current),
|
||||
}),
|
||||
Err(err) => {
|
||||
first_error.get_or_insert(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
current.clear();
|
||||
keep_signatures = true;
|
||||
has_user_id = false;
|
||||
}
|
||||
let Some((Packet { tag, body }, raw)) = packet else {
|
||||
break;
|
||||
};
|
||||
match tag {
|
||||
TAG_USER_ID => {
|
||||
keep_signatures = cert::email_address(body)
|
||||
.is_some_and(|candidate| candidate.eq_ignore_ascii_case(address));
|
||||
has_user_id |= keep_signatures;
|
||||
if keep_signatures {
|
||||
current.extend_from_slice(raw);
|
||||
}
|
||||
}
|
||||
TAG_USER_ATTRIBUTE => keep_signatures = false,
|
||||
TAG_SIGNATURE => {
|
||||
if keep_signatures {
|
||||
current.extend_from_slice(raw);
|
||||
}
|
||||
}
|
||||
TAG_MARKER | TAG_PADDING | TAG_TRUST => {}
|
||||
_ => {
|
||||
keep_signatures = true;
|
||||
current.extend_from_slice(raw);
|
||||
}
|
||||
}
|
||||
}
|
||||
if keys.is_empty() {
|
||||
Err(first_error.unwrap_or(KeyError::NoEncryptionKey))
|
||||
} else {
|
||||
Ok(keys)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn certifies(old_key: &[u8], new_key: &[u8], address: &str, now: u64) -> bool {
|
||||
let (Ok(old_key), Ok(new_key)) = (
|
||||
armor::dearmor_public_keys(old_key),
|
||||
armor::dearmor_public_keys(new_key),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
let (Ok(old_certs), Ok(new_certs)) = (cert::split_certs(&old_key), cert::split_certs(&new_key))
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let signers: Vec<_> = old_certs
|
||||
.iter()
|
||||
.filter_map(cert::RawCert::primary)
|
||||
.collect();
|
||||
new_certs
|
||||
.iter()
|
||||
.any(|cert| cert.certified_by(&signers, address, now))
|
||||
}
|
||||
|
||||
pub(crate) fn revoked_fingerprints(input: &[u8], now: u64) -> Vec<crate::Fingerprint> {
|
||||
let Ok(binary) = armor::dearmor_public_keys(input) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(raw) = cert::split_certs(&binary) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let primaries: Vec<_> = raw.iter().filter_map(cert::RawCert::primary).collect();
|
||||
raw.iter()
|
||||
.filter(|cert| {
|
||||
matches!(
|
||||
cert.validate(&primaries, now, cert::Purpose::Encrypt),
|
||||
Err(KeyError::Revoked)
|
||||
)
|
||||
})
|
||||
.filter_map(|cert| cert.primary().map(|primary| primary.fingerprint))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn parse_public_keys(input: &[u8], now: u64) -> Result<ParsedKeys, KeyError> {
|
||||
let binary = armor::dearmor_public_keys(input)?;
|
||||
let raw = cert::split_certs(&binary)?;
|
||||
let primaries: Vec<_> = raw.iter().filter_map(cert::RawCert::primary).collect();
|
||||
let mut certs = Vec::with_capacity(raw.len());
|
||||
let mut addresses = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
let mut first_error = None;
|
||||
for raw_cert in &raw {
|
||||
match raw_cert.validate(&primaries, now, cert::Purpose::Encrypt) {
|
||||
Ok(valid) => {
|
||||
if valid.weak_rsa && !warnings.contains(&KeyWarning::WeakRsa) {
|
||||
warnings.push(KeyWarning::WeakRsa);
|
||||
}
|
||||
for address in valid.addresses {
|
||||
if !addresses.contains(&address) {
|
||||
addresses.push(address);
|
||||
}
|
||||
}
|
||||
certs.push(valid.cert);
|
||||
}
|
||||
Err(err) => {
|
||||
first_error.get_or_insert(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
if certs.is_empty() {
|
||||
return Err(first_error.unwrap_or(KeyError::NoEncryptionKey));
|
||||
}
|
||||
let keys = certs.iter().flat_map(|c| c.keys.iter());
|
||||
let mut capabilities = KeyCapabilities::default();
|
||||
if keys.clone().all(|k| k.seipd_v2) {
|
||||
capabilities.insert(KeyCapability::Aead);
|
||||
}
|
||||
if keys.clone().any(|k| k.is_post_quantum()) {
|
||||
capabilities.insert(KeyCapability::PostQuantum);
|
||||
}
|
||||
if certs
|
||||
.iter()
|
||||
.any(|c| c.keys.iter().all(cert::PgpKey::is_post_quantum))
|
||||
{
|
||||
warnings.push(KeyWarning::PostQuantumOnly);
|
||||
}
|
||||
let expires_at = keys
|
||||
.clone()
|
||||
.map(|k| k.expires_at)
|
||||
.try_fold(0u64, |acc, exp| exp.map(|e| acc.max(e)));
|
||||
if expires_at.is_some_and(|exp| exp <= now + EXPIRES_SOON_SECS) {
|
||||
warnings.push(KeyWarning::ExpiresSoon);
|
||||
}
|
||||
Ok(ParsedKeys {
|
||||
kind: KeyKind::OpenPgp,
|
||||
fingerprints: certs.iter().map(|c| c.fingerprint).collect(),
|
||||
set: RecipientSet(Arc::new(Recipients::OpenPgp(certs.into_boxed_slice()))),
|
||||
addresses,
|
||||
expires_at,
|
||||
capabilities,
|
||||
warnings,
|
||||
smime_capabilities: None,
|
||||
})
|
||||
}
|
||||
214
crates/crypto/src/pgp/packet.rs
Normal file
214
crates/crypto/src/pgp/packet.rs
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::error::KeyError;
|
||||
|
||||
pub(crate) const TAG_PKESK: u8 = 1;
|
||||
pub(crate) const TAG_SIGNATURE: u8 = 2;
|
||||
pub(crate) const TAG_SECRET_KEY: u8 = 5;
|
||||
pub(crate) const TAG_PUBLIC_KEY: u8 = 6;
|
||||
pub(crate) const TAG_SECRET_SUBKEY: u8 = 7;
|
||||
pub(crate) const TAG_MARKER: u8 = 10;
|
||||
pub(crate) const TAG_LITERAL: u8 = 11;
|
||||
pub(crate) const TAG_TRUST: u8 = 12;
|
||||
pub(crate) const TAG_USER_ID: u8 = 13;
|
||||
pub(crate) const TAG_PUBLIC_SUBKEY: u8 = 14;
|
||||
pub(crate) const TAG_USER_ATTRIBUTE: u8 = 17;
|
||||
pub(crate) const TAG_SEIPD: u8 = 18;
|
||||
pub(crate) const TAG_PADDING: u8 = 21;
|
||||
|
||||
const NEW_FORMAT: u8 = 0x40;
|
||||
const PACKET_BIT: u8 = 0x80;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Packet<'x> {
|
||||
pub tag: u8,
|
||||
pub body: &'x [u8],
|
||||
}
|
||||
|
||||
pub(crate) struct PacketReader<'x> {
|
||||
data: &'x [u8],
|
||||
}
|
||||
|
||||
impl<'x> PacketReader<'x> {
|
||||
pub(crate) fn new(data: &'x [u8]) -> Self {
|
||||
PacketReader { data }
|
||||
}
|
||||
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.data.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn read_raw(&mut self) -> Result<(Packet<'x>, &'x [u8]), KeyError> {
|
||||
let start = self.data;
|
||||
let packet = self.read()?;
|
||||
let (raw, _) = start
|
||||
.split_at_checked(start.len() - self.data.len())
|
||||
.ok_or(KeyError::MalformedPacket)?;
|
||||
Ok((packet, raw))
|
||||
}
|
||||
|
||||
fn read(&mut self) -> Result<Packet<'x>, KeyError> {
|
||||
let [header, rest @ ..] = self.data else {
|
||||
return Err(KeyError::MalformedPacket);
|
||||
};
|
||||
if header & PACKET_BIT == 0 {
|
||||
return Err(KeyError::MalformedPacket);
|
||||
}
|
||||
let (tag, len, rest) = if header & NEW_FORMAT != 0 {
|
||||
let tag = header & 0x3F;
|
||||
match rest {
|
||||
[a, rest @ ..] if *a < 192 => (tag, usize::from(*a), rest),
|
||||
[a, b, rest @ ..] if *a < 224 => (
|
||||
tag,
|
||||
((usize::from(*a) - 192) << 8) + usize::from(*b) + 192,
|
||||
rest,
|
||||
),
|
||||
[255, a, b, c, d, rest @ ..] => {
|
||||
(tag, u32::from_be_bytes([*a, *b, *c, *d]) as usize, rest)
|
||||
}
|
||||
_ => return Err(KeyError::MalformedPacket),
|
||||
}
|
||||
} else {
|
||||
let tag = (header >> 2) & 0x0F;
|
||||
match (header & 0x03, rest) {
|
||||
(0, [a, rest @ ..]) => (tag, usize::from(*a), rest),
|
||||
(1, [a, b, rest @ ..]) => (tag, usize::from(u16::from_be_bytes([*a, *b])), rest),
|
||||
(2, [a, b, c, d, rest @ ..]) => {
|
||||
(tag, u32::from_be_bytes([*a, *b, *c, *d]) as usize, rest)
|
||||
}
|
||||
_ => return Err(KeyError::MalformedPacket),
|
||||
}
|
||||
};
|
||||
let (body, rest) = rest
|
||||
.split_at_checked(len)
|
||||
.ok_or(KeyError::MalformedPacket)?;
|
||||
self.data = rest;
|
||||
Ok(Packet { tag, body })
|
||||
}
|
||||
}
|
||||
|
||||
impl<'x> Iterator for PacketReader<'x> {
|
||||
type Item = Result<Packet<'x>, KeyError>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.data.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let result = self.read();
|
||||
if result.is_err() {
|
||||
self.data = &[];
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn header_len(body_len: usize) -> usize {
|
||||
if body_len < 192 {
|
||||
2
|
||||
} else if body_len < 8384 {
|
||||
3
|
||||
} else {
|
||||
6
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn header_bytes(tag: u8, body_len: usize) -> ([u8; 6], usize) {
|
||||
let mut out = [0u8; 6];
|
||||
out[0] = PACKET_BIT | NEW_FORMAT | tag;
|
||||
if body_len < 192 {
|
||||
out[1] = body_len as u8;
|
||||
} else if body_len < 8384 {
|
||||
let v = body_len - 192;
|
||||
out[1] = ((v >> 8) + 192) as u8;
|
||||
out[2] = v as u8;
|
||||
} else {
|
||||
out[1] = 255;
|
||||
out[2..6].copy_from_slice(&(body_len as u32).to_be_bytes());
|
||||
}
|
||||
(out, header_len(body_len))
|
||||
}
|
||||
|
||||
pub(crate) fn write_header(out: &mut Vec<u8>, tag: u8, body_len: usize) {
|
||||
let (bytes, len) = header_bytes(tag, body_len);
|
||||
out.extend_from_slice(&bytes[..len]);
|
||||
}
|
||||
|
||||
pub(crate) struct Fields<'x> {
|
||||
data: &'x [u8],
|
||||
}
|
||||
|
||||
impl<'x> Fields<'x> {
|
||||
pub(crate) fn new(data: &'x [u8]) -> Self {
|
||||
Fields { data }
|
||||
}
|
||||
|
||||
pub(crate) fn remaining(&self) -> &'x [u8] {
|
||||
self.data
|
||||
}
|
||||
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.data.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn u8(&mut self) -> Result<u8, KeyError> {
|
||||
let (first, rest) = self.data.split_first().ok_or(KeyError::MalformedPacket)?;
|
||||
self.data = rest;
|
||||
Ok(*first)
|
||||
}
|
||||
|
||||
pub(crate) fn u16(&mut self) -> Result<u16, KeyError> {
|
||||
self.array::<2>().map(u16::from_be_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn u32(&mut self) -> Result<u32, KeyError> {
|
||||
self.array::<4>().map(u32::from_be_bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn array<const N: usize>(&mut self) -> Result<[u8; N], KeyError> {
|
||||
let (head, rest) = self
|
||||
.data
|
||||
.split_first_chunk::<N>()
|
||||
.ok_or(KeyError::MalformedPacket)?;
|
||||
self.data = rest;
|
||||
Ok(*head)
|
||||
}
|
||||
|
||||
pub(crate) fn bytes(&mut self, len: usize) -> Result<&'x [u8], KeyError> {
|
||||
let (head, rest) = self
|
||||
.data
|
||||
.split_at_checked(len)
|
||||
.ok_or(KeyError::MalformedPacket)?;
|
||||
self.data = rest;
|
||||
Ok(head)
|
||||
}
|
||||
|
||||
pub(crate) fn mpi(&mut self) -> Result<&'x [u8], KeyError> {
|
||||
let bits = usize::from(self.u16()?);
|
||||
let bytes = self.bytes(bits.div_ceil(8))?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn short_bytes(&mut self) -> Result<&'x [u8], KeyError> {
|
||||
let len = usize::from(self.u8()?);
|
||||
self.bytes(len)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn strip_leading_zeros(value: &[u8]) -> &[u8] {
|
||||
let first = value.iter().position(|b| *b != 0).unwrap_or(value.len());
|
||||
&value[first..]
|
||||
}
|
||||
|
||||
pub(crate) fn mpi_header(value: &[u8]) -> ([u8; 2], &[u8]) {
|
||||
let value = strip_leading_zeros(value);
|
||||
let bits = match value.first() {
|
||||
Some(first) => value.len() * 8 - first.leading_zeros() as usize,
|
||||
None => 0,
|
||||
};
|
||||
((bits as u16).to_be_bytes(), value)
|
||||
}
|
||||
423
crates/crypto/src/pgp/signature.rs
Normal file
423
crates/crypto/src/pgp/signature.rs
Normal file
|
|
@ -0,0 +1,423 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
backend::{
|
||||
PrimitiveError,
|
||||
hash::{HashAlgorithm, Hasher},
|
||||
verify::{MlDsa, SignatureScheme},
|
||||
},
|
||||
der::tag,
|
||||
der::writer::{
|
||||
rsa_public_key_len, tlv_len, unsigned_integer_len, write_header, write_rsa_public_key,
|
||||
write_unsigned_integer,
|
||||
},
|
||||
error::KeyError,
|
||||
pgp::{
|
||||
key::{KeyMaterial, KeyPacket, KeyVersion, hash_id},
|
||||
packet::{Fields, strip_leading_zeros},
|
||||
},
|
||||
types::Fingerprint,
|
||||
};
|
||||
|
||||
pub(crate) const SIG_BINARY: u8 = 0x00;
|
||||
pub(crate) const SIG_TEXT: u8 = 0x01;
|
||||
pub(crate) const SIG_PRIMARY_BINDING: u8 = 0x19;
|
||||
pub(crate) const SIG_CERT_FIRST: u8 = 0x10;
|
||||
pub(crate) const SIG_CERT_LAST: u8 = 0x13;
|
||||
pub(crate) const SIG_SUBKEY_BINDING: u8 = 0x18;
|
||||
pub(crate) const SIG_DIRECT_KEY: u8 = 0x1F;
|
||||
pub(crate) const SIG_KEY_REVOCATION: u8 = 0x20;
|
||||
pub(crate) const SIG_SUBKEY_REVOCATION: u8 = 0x28;
|
||||
|
||||
const SHA1_CUTOFF: u32 = 1_675_209_600;
|
||||
const MAX_SUBPACKET_AREA: usize = 1 << 16;
|
||||
const ED25519_SIG_LEN: usize = 64;
|
||||
const ED448_SIG_LEN: usize = 114;
|
||||
const MLDSA65_SIG_LEN: usize = 3309;
|
||||
const MLDSA87_SIG_LEN: usize = 4627;
|
||||
const CRITICAL: u8 = 0x80;
|
||||
|
||||
pub(crate) const FEATURE_SEIPDV2: u8 = 0x08;
|
||||
pub(crate) const FLAG_SIGN: u8 = 0x02;
|
||||
pub(crate) const FLAG_ENCRYPT_COMMUNICATIONS: u8 = 0x04;
|
||||
pub(crate) const FLAG_ENCRYPT_STORAGE: u8 = 0x08;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub(crate) struct SymPrefs(u8);
|
||||
|
||||
impl SymPrefs {
|
||||
pub(crate) const AES128: u8 = 1;
|
||||
pub(crate) const AES192: u8 = 2;
|
||||
pub(crate) const AES256: u8 = 4;
|
||||
|
||||
pub(crate) fn contains(self, bit: u8) -> bool {
|
||||
self.0 & bit != 0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub(crate) struct AeadPrefs {
|
||||
pairs: [(u8, u8); 6],
|
||||
len: u8,
|
||||
}
|
||||
|
||||
impl AeadPrefs {
|
||||
fn push(&mut self, pair: (u8, u8)) {
|
||||
if self.as_slice().contains(&pair) {
|
||||
return;
|
||||
}
|
||||
if let Some(slot) = self.pairs.get_mut(usize::from(self.len)) {
|
||||
*slot = pair;
|
||||
self.len += 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn as_slice(&self) -> &[(u8, u8)] {
|
||||
&self.pairs[..usize::from(self.len)]
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct SigInfo {
|
||||
pub created: Option<u32>,
|
||||
pub sig_expires: Option<u32>,
|
||||
pub key_expires: Option<u32>,
|
||||
pub key_flags: Option<u8>,
|
||||
pub features: Option<u8>,
|
||||
pub sym_prefs: Option<SymPrefs>,
|
||||
pub aead_prefs: Option<AeadPrefs>,
|
||||
pub primary_uid: bool,
|
||||
pub revocation_key: Option<Fingerprint>,
|
||||
pub issuer_fingerprint: Option<Fingerprint>,
|
||||
pub issuer_key_id: Option<[u8; 8]>,
|
||||
pub unknown_critical: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum SigVersion {
|
||||
V4,
|
||||
V6,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Signature<'x> {
|
||||
pub version: SigVersion,
|
||||
pub sig_type: u8,
|
||||
pub pk_algorithm: u8,
|
||||
pub hash_algorithm: u8,
|
||||
pub hashed_prefix: &'x [u8],
|
||||
pub left16: [u8; 2],
|
||||
pub salt: &'x [u8],
|
||||
pub material: &'x [u8],
|
||||
pub embedded: Option<&'x [u8]>,
|
||||
pub info: SigInfo,
|
||||
}
|
||||
|
||||
fn subpackets(mut data: &[u8]) -> impl Iterator<Item = Result<(u8, bool, &[u8]), KeyError>> {
|
||||
std::iter::from_fn(move || {
|
||||
if data.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let mut fields = Fields::new(data);
|
||||
let result = (|| {
|
||||
let first = fields.u8()?;
|
||||
let len = match first {
|
||||
0..192 => usize::from(first),
|
||||
192..255 => ((usize::from(first) - 192) << 8) + usize::from(fields.u8()?) + 192,
|
||||
255 => fields.u32()? as usize,
|
||||
};
|
||||
let body = fields.bytes(len)?;
|
||||
let (type_byte, value) = body.split_first().ok_or(KeyError::MalformedPacket)?;
|
||||
Ok((type_byte & !CRITICAL, type_byte & CRITICAL != 0, value))
|
||||
})();
|
||||
data = if result.is_ok() {
|
||||
fields.remaining()
|
||||
} else {
|
||||
&[]
|
||||
};
|
||||
Some(result)
|
||||
})
|
||||
}
|
||||
|
||||
fn be_u32(value: &[u8]) -> Result<u32, KeyError> {
|
||||
value
|
||||
.try_into()
|
||||
.map(u32::from_be_bytes)
|
||||
.map_err(|_| KeyError::MalformedPacket)
|
||||
}
|
||||
|
||||
fn parse_fingerprint(value: &[u8]) -> Option<Fingerprint> {
|
||||
match value.split_first() {
|
||||
Some((4, fp)) => fp.try_into().ok().map(Fingerprint::V4),
|
||||
Some((6, fp)) => fp.try_into().ok().map(Fingerprint::V6),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_hashed<'x>(info: &mut SigInfo, area: &'x [u8]) -> Result<Option<&'x [u8]>, KeyError> {
|
||||
let mut embedded = None;
|
||||
for subpacket in subpackets(area) {
|
||||
let (kind, critical, value) = subpacket?;
|
||||
match kind {
|
||||
2 => info.created = Some(be_u32(value)?),
|
||||
3 => info.sig_expires = Some(be_u32(value)?).filter(|v| *v != 0),
|
||||
9 => info.key_expires = Some(be_u32(value)?).filter(|v| *v != 0),
|
||||
11 => {
|
||||
let mut prefs = SymPrefs::default();
|
||||
for alg in value {
|
||||
prefs.0 |= match alg {
|
||||
7 => SymPrefs::AES128,
|
||||
8 => SymPrefs::AES192,
|
||||
9 => SymPrefs::AES256,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
info.sym_prefs = Some(prefs);
|
||||
}
|
||||
12 => {
|
||||
if let [_class, _alg, fp @ ..] = value {
|
||||
info.revocation_key = fp.try_into().ok().map(Fingerprint::V4);
|
||||
}
|
||||
}
|
||||
16 => info.issuer_key_id = value.try_into().ok(),
|
||||
25 => info.primary_uid = value.first().is_some_and(|v| *v != 0),
|
||||
27 => info.key_flags = Some(value.first().copied().unwrap_or(0)),
|
||||
30 => info.features = Some(value.first().copied().unwrap_or(0)),
|
||||
33 => info.issuer_fingerprint = parse_fingerprint(value),
|
||||
39 => {
|
||||
let mut prefs = AeadPrefs::default();
|
||||
let (pairs, _) = value.as_chunks::<2>();
|
||||
for [cipher, aead] in pairs {
|
||||
if matches!(cipher, 7..=9) && matches!(aead, 2 | 3) {
|
||||
prefs.push((*cipher, *aead));
|
||||
}
|
||||
}
|
||||
info.aead_prefs = Some(prefs);
|
||||
}
|
||||
32 => embedded = Some(value),
|
||||
4 | 5 | 6 | 7 | 20 | 21 | 22 | 23 | 24 | 26 | 28 | 29 | 31 | 34 | 35 | 37 => {
|
||||
if critical && matches!(kind, 5 | 6 | 20 | 34 | 37) {
|
||||
info.unknown_critical = true;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if critical {
|
||||
info.unknown_critical = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(embedded)
|
||||
}
|
||||
|
||||
fn parse_unhashed<'x>(info: &mut SigInfo, area: &'x [u8]) -> Result<Option<&'x [u8]>, KeyError> {
|
||||
let mut embedded = None;
|
||||
for subpacket in subpackets(area) {
|
||||
let (kind, _, value) = subpacket?;
|
||||
match kind {
|
||||
32 => embedded = Some(value),
|
||||
16 if info.issuer_key_id.is_none() => info.issuer_key_id = value.try_into().ok(),
|
||||
33 if info.issuer_fingerprint.is_none() => {
|
||||
info.issuer_fingerprint = parse_fingerprint(value)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(embedded)
|
||||
}
|
||||
|
||||
impl<'x> Signature<'x> {
|
||||
pub(crate) fn parse(body: &'x [u8]) -> Result<Self, KeyError> {
|
||||
let mut fields = Fields::new(body);
|
||||
let version = match fields.u8()? {
|
||||
4 => SigVersion::V4,
|
||||
6 => SigVersion::V6,
|
||||
_ => return Err(KeyError::UnsupportedKeyVersion),
|
||||
};
|
||||
let sig_type = fields.u8()?;
|
||||
let pk_algorithm = fields.u8()?;
|
||||
let hash_algorithm = fields.u8()?;
|
||||
let read_area = |fields: &mut Fields<'x>| -> Result<&'x [u8], KeyError> {
|
||||
let len = match version {
|
||||
SigVersion::V4 => usize::from(fields.u16()?),
|
||||
SigVersion::V6 => fields.u32()? as usize,
|
||||
};
|
||||
if len > MAX_SUBPACKET_AREA {
|
||||
return Err(KeyError::MalformedPacket);
|
||||
}
|
||||
fields.bytes(len)
|
||||
};
|
||||
let hashed = read_area(&mut fields)?;
|
||||
let hashed_prefix = &body[..body.len() - fields.remaining().len()];
|
||||
let unhashed = read_area(&mut fields)?;
|
||||
let left16 = fields.array::<2>()?;
|
||||
let salt = match version {
|
||||
SigVersion::V4 => &[][..],
|
||||
SigVersion::V6 => fields.short_bytes()?,
|
||||
};
|
||||
let mut info = SigInfo::default();
|
||||
let embedded = parse_hashed(&mut info, hashed)?.or(parse_unhashed(&mut info, unhashed)?);
|
||||
Ok(Signature {
|
||||
version,
|
||||
sig_type,
|
||||
pk_algorithm,
|
||||
hash_algorithm,
|
||||
hashed_prefix,
|
||||
left16,
|
||||
salt,
|
||||
material: fields.remaining(),
|
||||
embedded,
|
||||
info,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_issued_by(&self, key: &KeyPacket<'_>) -> bool {
|
||||
match (&self.info.issuer_fingerprint, &self.info.issuer_key_id) {
|
||||
(Some(fp), _) => *fp == key.fingerprint,
|
||||
(None, Some(id)) => *id == key.key_id(),
|
||||
(None, None) => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn hasher(&self, now: u64) -> Result<(HashAlgorithm, Hasher), KeyError> {
|
||||
let hash = hash_id(self.hash_algorithm).ok_or(KeyError::UnsupportedKeyAlgorithm)?;
|
||||
let created = self.info.created.ok_or(KeyError::NoValidSelfSignature)?;
|
||||
if self.info.unknown_critical
|
||||
|| (hash == HashAlgorithm::Sha1 && created > SHA1_CUTOFF)
|
||||
|| u64::from(created) > now
|
||||
|| self
|
||||
.info
|
||||
.sig_expires
|
||||
.is_some_and(|exp| u64::from(created) + u64::from(exp) <= now)
|
||||
{
|
||||
return Err(KeyError::NoValidSelfSignature);
|
||||
}
|
||||
if self.version == SigVersion::V6 {
|
||||
let expected_salt = match hash {
|
||||
HashAlgorithm::Sha256 | HashAlgorithm::Sha224 | HashAlgorithm::Sha3_256 => 16,
|
||||
HashAlgorithm::Sha384 => 24,
|
||||
HashAlgorithm::Sha512 | HashAlgorithm::Sha3_512 => 32,
|
||||
HashAlgorithm::Sha1 => return Err(KeyError::NoValidSelfSignature),
|
||||
};
|
||||
if self.salt.len() != expected_salt {
|
||||
return Err(KeyError::MalformedPacket);
|
||||
}
|
||||
}
|
||||
let mut hasher = hash.hasher();
|
||||
hasher.update(self.salt);
|
||||
Ok((hash, hasher))
|
||||
}
|
||||
|
||||
pub(crate) fn finish(&self, mut hasher: Hasher) -> aws_lc_rs::digest::Digest {
|
||||
hasher.update(self.hashed_prefix);
|
||||
let marker = match self.version {
|
||||
SigVersion::V4 => 4,
|
||||
SigVersion::V6 => 6,
|
||||
};
|
||||
hasher.update(&[marker, 0xFF]);
|
||||
hasher.update(&(self.hashed_prefix.len() as u32).to_be_bytes());
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
pub(crate) fn verify(
|
||||
&self,
|
||||
signer: &KeyPacket<'_>,
|
||||
data: impl FnOnce(&mut Hasher),
|
||||
now: u64,
|
||||
) -> Result<(), KeyError> {
|
||||
if self.pk_algorithm != signer.algorithm
|
||||
|| (self.version == SigVersion::V6) != (signer.version == KeyVersion::V6)
|
||||
{
|
||||
return Err(KeyError::NoValidSelfSignature);
|
||||
}
|
||||
let (hash, mut hasher) = self.hasher(now)?;
|
||||
data(&mut hasher);
|
||||
let digest = self.finish(hasher);
|
||||
if digest.as_ref().get(..2) != Some(self.left16.as_slice()) {
|
||||
return Err(KeyError::NoValidSelfSignature);
|
||||
}
|
||||
verify_digest(&signer.material, hash, &digest, self.material)
|
||||
.map_err(|_| KeyError::NoValidSelfSignature)
|
||||
}
|
||||
}
|
||||
|
||||
fn left_pad<const N: usize>(value: &[u8]) -> Result<[u8; N], PrimitiveError> {
|
||||
let value = strip_leading_zeros(value);
|
||||
let mut out = [0u8; N];
|
||||
let start = N
|
||||
.checked_sub(value.len())
|
||||
.ok_or(PrimitiveError::BadSignature)?;
|
||||
out[start..].copy_from_slice(value);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn verify_digest(
|
||||
material: &KeyMaterial<'_>,
|
||||
hash: HashAlgorithm,
|
||||
digest: &aws_lc_rs::digest::Digest,
|
||||
signature: &[u8],
|
||||
) -> Result<(), PrimitiveError> {
|
||||
let mut fields = Fields::new(signature);
|
||||
let mut mpi = || fields.mpi().map_err(|_| PrimitiveError::BadSignature);
|
||||
match material {
|
||||
KeyMaterial::Rsa { n, e } => {
|
||||
let n = strip_leading_zeros(n);
|
||||
let sig = strip_leading_zeros(mpi()?);
|
||||
if sig.len() > n.len() {
|
||||
return Err(PrimitiveError::BadSignature);
|
||||
}
|
||||
let mut padded = vec![0u8; n.len()];
|
||||
padded[n.len() - sig.len()..].copy_from_slice(sig);
|
||||
let mut key = Vec::with_capacity(rsa_public_key_len(n, e));
|
||||
write_rsa_public_key(&mut key, n, e);
|
||||
SignatureScheme::RsaPkcs1(hash).verify_digest(&key, digest, &padded)
|
||||
}
|
||||
KeyMaterial::Ecdsa { curve, point } => {
|
||||
let r = mpi()?;
|
||||
let s = mpi()?;
|
||||
let content = unsigned_integer_len(r) + unsigned_integer_len(s);
|
||||
let mut der = Vec::with_capacity(tlv_len(content));
|
||||
write_header(&mut der, tag::SEQUENCE, content);
|
||||
write_unsigned_integer(&mut der, r);
|
||||
write_unsigned_integer(&mut der, s);
|
||||
SignatureScheme::Ecdsa(*curve, hash).verify_digest(point, digest, &der)
|
||||
}
|
||||
KeyMaterial::EdDsaLegacy { point } => {
|
||||
let r = left_pad::<32>(mpi()?)?;
|
||||
let s = left_pad::<32>(mpi()?)?;
|
||||
let mut sig = [0u8; ED25519_SIG_LEN];
|
||||
sig[..32].copy_from_slice(&r);
|
||||
sig[32..].copy_from_slice(&s);
|
||||
SignatureScheme::Ed25519.verify(point.as_slice(), digest.as_ref(), &sig)
|
||||
}
|
||||
KeyMaterial::Ed25519(point) => {
|
||||
SignatureScheme::Ed25519.verify(point.as_slice(), digest.as_ref(), signature)
|
||||
}
|
||||
KeyMaterial::Ed448(point) => {
|
||||
SignatureScheme::Ed448.verify(point.as_slice(), digest.as_ref(), signature)
|
||||
}
|
||||
KeyMaterial::MlDsa { dsa, eddsa, mldsa } => {
|
||||
let (eddsa_scheme, eddsa_len, mldsa_len) = match dsa {
|
||||
MlDsa::MlDsa65 => (SignatureScheme::Ed25519, ED25519_SIG_LEN, MLDSA65_SIG_LEN),
|
||||
_ => (SignatureScheme::Ed448, ED448_SIG_LEN, MLDSA87_SIG_LEN),
|
||||
};
|
||||
let (eddsa_sig, mldsa_sig) = signature
|
||||
.split_at_checked(eddsa_len)
|
||||
.filter(|(_, m)| m.len() == mldsa_len)
|
||||
.ok_or(PrimitiveError::BadSignature)?;
|
||||
eddsa_scheme.verify(eddsa, digest.as_ref(), eddsa_sig)?;
|
||||
SignatureScheme::MlDsa(*dsa).verify(mldsa, digest.as_ref(), mldsa_sig)
|
||||
}
|
||||
_ => Err(PrimitiveError::UnsupportedAlgorithm),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn hash_user_id(hasher: &mut Hasher, user_id: &[u8]) {
|
||||
hasher.update(&[0xB4]);
|
||||
hasher.update(&(user_id.len() as u32).to_be_bytes());
|
||||
hasher.update(user_id);
|
||||
}
|
||||
102
crates/crypto/src/pgp/verify.rs
Normal file
102
crates/crypto/src/pgp/verify.rs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::{
|
||||
error::VerifyError,
|
||||
mime::{Canonical, Sink},
|
||||
pgp::{
|
||||
armor::{ArmorLabel, decode_body, is_armored, next_block},
|
||||
cert::{Purpose, RawCert, ValidCert},
|
||||
packet::{Packet, PacketReader, TAG_SIGNATURE},
|
||||
signature::{SIG_BINARY, SIG_TEXT, Signature},
|
||||
},
|
||||
types::Fingerprint,
|
||||
};
|
||||
|
||||
const MAX_SIGNATURES: usize = 16;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) struct PgpVerified {
|
||||
pub signer: Fingerprint,
|
||||
pub created: u64,
|
||||
}
|
||||
|
||||
fn dearmor_signature(input: &[u8]) -> Result<Cow<'_, [u8]>, VerifyError> {
|
||||
if !is_armored(input) {
|
||||
return Ok(Cow::Borrowed(input));
|
||||
}
|
||||
let (block, _) = next_block(input)
|
||||
.ok()
|
||||
.flatten()
|
||||
.ok_or(VerifyError::Malformed)?;
|
||||
if block.label != ArmorLabel::Signature {
|
||||
return Err(VerifyError::Malformed);
|
||||
}
|
||||
let mut out = Vec::with_capacity(block.body.len() / 4 * 3);
|
||||
decode_body(block.body, &mut out).map_err(|_| VerifyError::Malformed)?;
|
||||
Ok(Cow::Owned(out))
|
||||
}
|
||||
|
||||
pub(crate) fn validate_signers<'c, 'x>(
|
||||
certs: &'c [RawCert<'x>],
|
||||
now: u64,
|
||||
) -> Vec<(&'c RawCert<'x>, ValidCert)> {
|
||||
let primaries: Vec<_> = certs.iter().filter_map(RawCert::primary).collect();
|
||||
certs
|
||||
.iter()
|
||||
.filter_map(|cert| {
|
||||
cert.validate(&primaries, now, Purpose::Verify)
|
||||
.ok()
|
||||
.map(|valid| (cert, valid))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn verify_detached(
|
||||
signers: &[(&RawCert<'_>, ValidCert)],
|
||||
signature: &[u8],
|
||||
content: &[u8],
|
||||
now: u64,
|
||||
) -> Result<PgpVerified, VerifyError> {
|
||||
if signers.is_empty() {
|
||||
return Err(VerifyError::InvalidCertificate(
|
||||
crate::error::KeyError::NoValidSelfSignature,
|
||||
));
|
||||
}
|
||||
let signature = dearmor_signature(signature)?;
|
||||
let mut error = VerifyError::UnknownSigner;
|
||||
for packet in PacketReader::new(&signature).take(MAX_SIGNATURES) {
|
||||
let Packet { tag, body } = packet.map_err(|_| VerifyError::Malformed)?;
|
||||
if tag != TAG_SIGNATURE {
|
||||
continue;
|
||||
}
|
||||
let Ok(sig) = Signature::parse(body) else {
|
||||
continue;
|
||||
};
|
||||
if !matches!(sig.sig_type, SIG_BINARY | SIG_TEXT) {
|
||||
continue;
|
||||
}
|
||||
for (cert, valid) in signers {
|
||||
for fingerprint in valid.signing.iter().flatten() {
|
||||
let Some(key) = cert.key(fingerprint).filter(|key| sig.is_issued_by(key)) else {
|
||||
continue;
|
||||
};
|
||||
match sig.verify(key, |h| Canonical::new(h).put(content), now) {
|
||||
Ok(()) => {
|
||||
return Ok(PgpVerified {
|
||||
signer: *fingerprint,
|
||||
created: u64::from(sig.info.created.unwrap_or_default()),
|
||||
});
|
||||
}
|
||||
Err(_) => error = VerifyError::BadSignature,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error)
|
||||
}
|
||||
262
crates/crypto/src/types.rs
Normal file
262
crates/crypto/src/types.rs
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
pgp::{cert::PgpCert, key::KeyVersion},
|
||||
x509::recipient::SmimeRecipient,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum KeyKind {
|
||||
OpenPgp,
|
||||
Smime,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum Fingerprint {
|
||||
V4([u8; 20]),
|
||||
V6([u8; 32]),
|
||||
X509Sha256([u8; 32]),
|
||||
}
|
||||
|
||||
impl Fingerprint {
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
match self {
|
||||
Fingerprint::V4(fp) => fp,
|
||||
Fingerprint::V6(fp) | Fingerprint::X509Sha256(fp) => fp,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_hex(&self) -> String {
|
||||
const HEX: &[u8; 16] = b"0123456789ABCDEF";
|
||||
let bytes = self.as_bytes();
|
||||
let mut hex = String::with_capacity(bytes.len() * 2);
|
||||
for byte in bytes {
|
||||
hex.push(char::from(HEX[usize::from(byte >> 4)]));
|
||||
hex.push(char::from(HEX[usize::from(byte & 0x0f)]));
|
||||
}
|
||||
hex
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum KeyCapability {
|
||||
Aead,
|
||||
PostQuantum,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub struct KeyCapabilities(u8);
|
||||
|
||||
impl KeyCapabilities {
|
||||
const fn bit(capability: KeyCapability) -> u8 {
|
||||
match capability {
|
||||
KeyCapability::Aead => 1,
|
||||
KeyCapability::PostQuantum => 2,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contains(self, capability: KeyCapability) -> bool {
|
||||
self.0 & Self::bit(capability) != 0
|
||||
}
|
||||
|
||||
pub(crate) fn insert(&mut self, capability: KeyCapability) {
|
||||
self.0 |= Self::bit(capability);
|
||||
}
|
||||
|
||||
pub fn iter(self) -> impl Iterator<Item = KeyCapability> {
|
||||
[KeyCapability::Aead, KeyCapability::PostQuantum]
|
||||
.into_iter()
|
||||
.filter(move |c| self.contains(*c))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum KeyWarning {
|
||||
WeakRsa,
|
||||
NoKnownDecryptor,
|
||||
PostQuantumOnly,
|
||||
ExpiresSoon,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum SmimeCipher {
|
||||
Aes128Cbc,
|
||||
Aes192Cbc,
|
||||
Aes256Cbc,
|
||||
Aes128Gcm,
|
||||
Aes192Gcm,
|
||||
Aes256Gcm,
|
||||
ChaCha20Poly1305,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct SmimeCapabilities {
|
||||
pub ciphers: Vec<SmimeCipher>,
|
||||
pub rsaes_oaep: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AddressKey {
|
||||
pub parsed: ParsedKeys,
|
||||
pub key: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ParsedKeys {
|
||||
pub kind: KeyKind,
|
||||
pub set: RecipientSet,
|
||||
pub addresses: Vec<Box<str>>,
|
||||
pub expires_at: Option<u64>,
|
||||
pub fingerprints: Vec<Fingerprint>,
|
||||
pub capabilities: KeyCapabilities,
|
||||
pub warnings: Vec<KeyWarning>,
|
||||
pub smime_capabilities: Option<SmimeCapabilities>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RecipientSet(pub(crate) Arc<Recipients>);
|
||||
|
||||
pub(crate) enum Recipients {
|
||||
OpenPgp(Box<[PgpCert]>),
|
||||
Smime(Box<[SmimeRecipient]>),
|
||||
}
|
||||
|
||||
impl RecipientSet {
|
||||
pub fn kind(&self) -> KeyKind {
|
||||
match self.0.as_ref() {
|
||||
Recipients::OpenPgp(_) => KeyKind::OpenPgp,
|
||||
Recipients::Smime(_) => KeyKind::Smime,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn inferred_profile(&self, authenticated_encryption: bool) -> Profile {
|
||||
if crate::check_profile(self, Profile::PostQuantum).is_ok() {
|
||||
Profile::PostQuantum
|
||||
} else if authenticated_encryption && self.kind() == KeyKind::Smime {
|
||||
Profile::Modern
|
||||
} else {
|
||||
Profile::Compatible
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key_type(&self) -> String {
|
||||
let (prefix, algorithms): (&str, Vec<String>) = match self.0.as_ref() {
|
||||
Recipients::OpenPgp(certs) => (
|
||||
match certs
|
||||
.first()
|
||||
.and_then(|cert| cert.keys.first())
|
||||
.map(|key| key.version)
|
||||
{
|
||||
Some(KeyVersion::V6) => "OpenPGP v6",
|
||||
_ => "OpenPGP v4",
|
||||
},
|
||||
certs
|
||||
.iter()
|
||||
.flat_map(|cert| cert.keys.iter())
|
||||
.map(|key| key.algorithm_name())
|
||||
.collect(),
|
||||
),
|
||||
Recipients::Smime(recipients) => (
|
||||
"S/MIME",
|
||||
recipients
|
||||
.iter()
|
||||
.map(|recipient| recipient.key.algorithm_name())
|
||||
.collect(),
|
||||
),
|
||||
};
|
||||
let mut key_type = String::with_capacity(32);
|
||||
key_type.push_str(prefix);
|
||||
key_type.push_str(": ");
|
||||
for (idx, algorithm) in algorithms.iter().enumerate() {
|
||||
if !algorithms[..idx].contains(algorithm) {
|
||||
if !key_type.ends_with(": ") {
|
||||
key_type.push_str(", ");
|
||||
}
|
||||
key_type.push_str(algorithm);
|
||||
}
|
||||
}
|
||||
key_type
|
||||
}
|
||||
|
||||
pub fn heap_size(&self) -> usize {
|
||||
size_of::<Recipients>()
|
||||
+ match self.0.as_ref() {
|
||||
Recipients::OpenPgp(certs) => certs
|
||||
.iter()
|
||||
.map(|cert| size_of::<PgpCert>() + cert.heap_size())
|
||||
.sum::<usize>(),
|
||||
Recipients::Smime(recipients) => recipients
|
||||
.iter()
|
||||
.map(|recipient| size_of::<SmimeRecipient>() + recipient.heap_size())
|
||||
.sum::<usize>(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RecipientSet {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let count = match self.0.as_ref() {
|
||||
Recipients::OpenPgp(certs) => certs.len(),
|
||||
Recipients::Smime(certs) => certs.len(),
|
||||
};
|
||||
f.debug_struct("RecipientSet")
|
||||
.field("kind", &self.kind())
|
||||
.field("certificates", &count)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub enum Profile {
|
||||
#[default]
|
||||
Compatible,
|
||||
Modern,
|
||||
PostQuantum,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub enum HeaderProtection {
|
||||
#[default]
|
||||
None,
|
||||
Full,
|
||||
Baseline,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub enum EcdhWrapParameters {
|
||||
#[default]
|
||||
Absent,
|
||||
Null,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub enum RecipientIds {
|
||||
#[default]
|
||||
Real,
|
||||
Anonymous,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
|
||||
pub struct EncryptOptions {
|
||||
pub profile: Profile,
|
||||
pub header_protection: HeaderProtection,
|
||||
pub ecdh_wrap_parameters: EcdhWrapParameters,
|
||||
pub recipient_ids: RecipientIds,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum EncryptWarning {
|
||||
ExceedsNssLimit,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Encrypted {
|
||||
pub message: Vec<u8>,
|
||||
pub warning: Option<EncryptWarning>,
|
||||
}
|
||||
453
crates/crypto/src/x509/cert.rs
Normal file
453
crates/crypto/src/x509/cert.rs
Normal file
|
|
@ -0,0 +1,453 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
backend::{
|
||||
hash::HashAlgorithm,
|
||||
verify::{EcCurve, MlDsa, SignatureScheme},
|
||||
},
|
||||
der::{
|
||||
DerError, oid,
|
||||
reader::{Reader, Tlv},
|
||||
tag,
|
||||
},
|
||||
x509::{
|
||||
names::{GN_OTHER_NAME, GN_RFC822, GN_URI, general_names, smtp_utf8_mailbox, uris},
|
||||
time::parse_time,
|
||||
},
|
||||
};
|
||||
|
||||
pub(crate) const KU_DIGITAL_SIGNATURE: u16 = 1 << 0;
|
||||
pub(crate) const KU_NON_REPUDIATION: u16 = 1 << 1;
|
||||
pub(crate) const KU_KEY_ENCIPHERMENT: u16 = 1 << 2;
|
||||
pub(crate) const KU_DATA_ENCIPHERMENT: u16 = 1 << 3;
|
||||
pub(crate) const KU_KEY_AGREEMENT: u16 = 1 << 4;
|
||||
pub(crate) const KU_KEY_CERT_SIGN: u16 = 1 << 5;
|
||||
pub(crate) const KU_CRL_SIGN: u16 = 1 << 6;
|
||||
pub(crate) const KU_ENCIPHER_ONLY: u16 = 1 << 7;
|
||||
pub(crate) const KU_DECIPHER_ONLY: u16 = 1 << 8;
|
||||
|
||||
const DP_NAME: u8 = tag::context_constructed(0);
|
||||
const DP_FULL_NAME: u8 = tag::context_constructed(0);
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct AlgorithmId<'x> {
|
||||
pub oid: &'x [u8],
|
||||
pub params: Option<Tlv<'x>>,
|
||||
pub raw: &'x [u8],
|
||||
}
|
||||
|
||||
impl<'x> AlgorithmId<'x> {
|
||||
pub(crate) fn parse(tlv: Tlv<'x>) -> Result<Self, DerError> {
|
||||
let tlv = tlv.expect(tag::SEQUENCE)?;
|
||||
let mut reader = tlv.reader();
|
||||
let oid = reader.read_content(tag::OID)?;
|
||||
let params = if reader.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(reader.read()?)
|
||||
};
|
||||
reader.finish()?;
|
||||
Ok(AlgorithmId {
|
||||
oid,
|
||||
params,
|
||||
raw: tlv.raw,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Spki<'x> {
|
||||
pub algorithm: AlgorithmId<'x>,
|
||||
pub key: &'x [u8],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct BasicConstraints {
|
||||
pub ca: bool,
|
||||
pub path_len: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub(crate) struct Extensions<'x> {
|
||||
pub key_usage: Option<u16>,
|
||||
pub eku: Option<&'x [u8]>,
|
||||
pub san: Option<&'x [u8]>,
|
||||
pub ski: Option<&'x [u8]>,
|
||||
pub aki: Option<&'x [u8]>,
|
||||
pub basic_constraints: Option<BasicConstraints>,
|
||||
pub aia: Option<&'x [u8]>,
|
||||
pub crl_distribution_points: Option<&'x [u8]>,
|
||||
pub policies: Option<&'x [u8]>,
|
||||
pub name_constraints: Option<&'x [u8]>,
|
||||
pub smime_capabilities: Option<&'x [u8]>,
|
||||
pub unknown_critical: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Certificate<'x> {
|
||||
pub raw: &'x [u8],
|
||||
pub tbs: &'x [u8],
|
||||
pub signature_algorithm: AlgorithmId<'x>,
|
||||
pub signature: &'x [u8],
|
||||
pub serial: &'x [u8],
|
||||
pub issuer: &'x [u8],
|
||||
pub subject: &'x [u8],
|
||||
pub not_before: u64,
|
||||
pub not_after: u64,
|
||||
pub spki: Spki<'x>,
|
||||
pub extensions: Extensions<'x>,
|
||||
}
|
||||
|
||||
pub(crate) fn bit_string(tlv: Tlv<'_>) -> Result<&[u8], DerError> {
|
||||
match tlv.expect(tag::BIT_STRING)?.content {
|
||||
[0, rest @ ..] => Ok(rest),
|
||||
_ => Err(DerError::InvalidValue),
|
||||
}
|
||||
}
|
||||
|
||||
fn key_usage_bits(content: &[u8]) -> Result<u16, DerError> {
|
||||
match content {
|
||||
[unused, bytes @ ..] if *unused < 8 => {
|
||||
Ok(bytes.iter().take(2).enumerate().fold(0u16, |acc, (i, b)| {
|
||||
acc | u16::from(b.reverse_bits()) << (8 * i)
|
||||
}))
|
||||
}
|
||||
_ => Err(DerError::InvalidValue),
|
||||
}
|
||||
}
|
||||
|
||||
fn distinguished_name(name: Tlv<'_>) -> Result<&[u8], DerError> {
|
||||
for rdn in name.reader() {
|
||||
for attribute in rdn?.expect(tag::SET)?.reader() {
|
||||
let mut attribute = attribute?.expect(tag::SEQUENCE)?.reader();
|
||||
attribute.read_tag(tag::OID)?;
|
||||
attribute.read()?;
|
||||
attribute.finish()?;
|
||||
}
|
||||
}
|
||||
Ok(name.raw)
|
||||
}
|
||||
|
||||
fn parse_extensions<'x>(tlv: Tlv<'x>) -> Result<Extensions<'x>, DerError> {
|
||||
let mut ext = Extensions::default();
|
||||
let mut list = tlv.reader().read_sequence()?;
|
||||
while !list.is_empty() {
|
||||
let mut item = list.read_sequence()?;
|
||||
let id = item.read_content(tag::OID)?;
|
||||
let critical = item.read_bool_default_false()?;
|
||||
let value = item.read_content(tag::OCTET_STRING)?;
|
||||
item.finish()?;
|
||||
let mut inner = Reader::new(value);
|
||||
match id {
|
||||
oid::EXT_KEY_USAGE => {
|
||||
ext.key_usage = Some(key_usage_bits(inner.read_content(tag::BIT_STRING)?)?)
|
||||
}
|
||||
oid::EXT_EXTENDED_KEY_USAGE => ext.eku = Some(inner.read_content(tag::SEQUENCE)?),
|
||||
oid::EXT_SUBJECT_ALT_NAME => {
|
||||
ext.san = Some(general_names(inner.read_content(tag::SEQUENCE)?)?)
|
||||
}
|
||||
oid::EXT_SUBJECT_KEY_ID => ext.ski = Some(inner.read_content(tag::OCTET_STRING)?),
|
||||
oid::EXT_AUTHORITY_KEY_ID => {
|
||||
let mut aki = inner.read_sequence()?;
|
||||
ext.aki = aki.read_optional(tag::context(0))?.map(|t| t.content);
|
||||
}
|
||||
oid::EXT_BASIC_CONSTRAINTS => {
|
||||
let mut bc = inner.read_sequence()?;
|
||||
let ca = bc.read_bool_default_false()?;
|
||||
let path_len = if bc.peek_tag() == Some(tag::INTEGER) {
|
||||
Some(bc.read_small_unsigned()?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
ext.basic_constraints = Some(BasicConstraints { ca, path_len });
|
||||
}
|
||||
oid::EXT_AUTHORITY_INFO_ACCESS => ext.aia = Some(inner.read_content(tag::SEQUENCE)?),
|
||||
oid::EXT_CRL_DISTRIBUTION_POINTS => {
|
||||
ext.crl_distribution_points = Some(inner.read_content(tag::SEQUENCE)?)
|
||||
}
|
||||
oid::EXT_CERTIFICATE_POLICIES => {
|
||||
ext.policies = Some(inner.read_content(tag::SEQUENCE)?)
|
||||
}
|
||||
oid::EXT_NAME_CONSTRAINTS => {
|
||||
ext.name_constraints = Some(inner.read_content(tag::SEQUENCE)?)
|
||||
}
|
||||
oid::SMIME_CAPABILITIES => {
|
||||
ext.smime_capabilities = Some(inner.read_content(tag::SEQUENCE)?)
|
||||
}
|
||||
oid::EXT_POLICY_CONSTRAINTS
|
||||
| oid::EXT_INHIBIT_ANY_POLICY
|
||||
| oid::EXT_POLICY_MAPPINGS
|
||||
| oid::EXT_ISSUER_ALT_NAME => continue,
|
||||
_ => {
|
||||
ext.unknown_critical |= critical;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
inner.finish()?;
|
||||
}
|
||||
Ok(ext)
|
||||
}
|
||||
|
||||
impl<'x> Certificate<'x> {
|
||||
pub(crate) fn parse(der: &'x [u8]) -> Result<Self, DerError> {
|
||||
let mut outer = Reader::new(der);
|
||||
let cert_tlv = outer.read_tag(tag::SEQUENCE)?;
|
||||
outer.finish()?;
|
||||
Self::parse_tlv(cert_tlv)
|
||||
}
|
||||
|
||||
pub(crate) fn parse_tlv(cert_tlv: Tlv<'x>) -> Result<Self, DerError> {
|
||||
let mut cert = cert_tlv.reader();
|
||||
let tbs_tlv = cert.read_tag(tag::SEQUENCE)?;
|
||||
let signature_algorithm = AlgorithmId::parse(cert.read()?)?;
|
||||
let signature = bit_string(cert.read()?)?;
|
||||
cert.finish()?;
|
||||
|
||||
let mut tbs = tbs_tlv.reader();
|
||||
if let Some(version) = tbs.read_optional(tag::context_constructed(0))? {
|
||||
let v = version.reader().read_small_unsigned()?;
|
||||
if v > 2 {
|
||||
return Err(DerError::InvalidValue);
|
||||
}
|
||||
}
|
||||
let serial = tbs.read_content(tag::INTEGER)?;
|
||||
if AlgorithmId::parse(tbs.read()?)?.raw != signature_algorithm.raw {
|
||||
return Err(DerError::InvalidValue);
|
||||
}
|
||||
let issuer = tbs.read_tag(tag::SEQUENCE)?.raw;
|
||||
let mut validity = tbs.read_sequence()?;
|
||||
let not_before = parse_time(validity.read()?)?;
|
||||
let not_after = parse_time(validity.read()?)?;
|
||||
validity.finish()?;
|
||||
let subject = distinguished_name(tbs.read_tag(tag::SEQUENCE)?)?;
|
||||
let spki_tlv = tbs.read_tag(tag::SEQUENCE)?;
|
||||
let mut spki_reader = spki_tlv.reader();
|
||||
let algorithm = AlgorithmId::parse(spki_reader.read()?)?;
|
||||
let key = bit_string(spki_reader.read()?)?;
|
||||
spki_reader.finish()?;
|
||||
let mut extensions = Extensions::default();
|
||||
for tlv in tbs {
|
||||
let tlv = tlv?;
|
||||
match tlv.tag {
|
||||
t if t == tag::context(1) || t == tag::context(2) => {}
|
||||
t if t == tag::context_constructed(3) => extensions = parse_extensions(tlv)?,
|
||||
_ => return Err(DerError::UnexpectedTag),
|
||||
}
|
||||
}
|
||||
Ok(Certificate {
|
||||
raw: cert_tlv.raw,
|
||||
tbs: tbs_tlv.raw,
|
||||
signature_algorithm,
|
||||
signature,
|
||||
serial,
|
||||
issuer,
|
||||
subject,
|
||||
not_before,
|
||||
not_after,
|
||||
spki: Spki { algorithm, key },
|
||||
extensions,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn is_ca(&self) -> bool {
|
||||
self.extensions.basic_constraints.is_some_and(|bc| bc.ca)
|
||||
}
|
||||
|
||||
pub(crate) fn email_addresses(&self) -> impl Iterator<Item = &'x str> + use<'x> {
|
||||
let san = self
|
||||
.extensions
|
||||
.san
|
||||
.into_iter()
|
||||
.flat_map(|san| Reader::new(san).map_while(Result::ok))
|
||||
.filter_map(|name| match name.tag {
|
||||
GN_RFC822 => std::str::from_utf8(name.content).ok(),
|
||||
GN_OTHER_NAME => std::str::from_utf8(smtp_utf8_mailbox(name.content)?).ok(),
|
||||
_ => None,
|
||||
});
|
||||
let subject = name_attributes(self.subject)
|
||||
.filter(|(id, _)| *id == oid::EMAIL_ADDRESS)
|
||||
.filter_map(|(_, value)| std::str::from_utf8(value).ok());
|
||||
san.chain(subject)
|
||||
}
|
||||
|
||||
pub(crate) fn has_email_protection(&self) -> bool {
|
||||
self.extensions.eku.is_none_or(|eku| {
|
||||
Reader::new(eku).map_while(Result::ok).any(|id| {
|
||||
id.content == oid::EMAIL_PROTECTION || id.content == oid::ANY_EXTENDED_KEY_USAGE
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn verify_signed_by(&self, issuer_spki: &Spki<'_>) -> bool {
|
||||
verify_signature(
|
||||
&self.signature_algorithm,
|
||||
issuer_spki,
|
||||
self.tbs,
|
||||
self.signature,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn display_name(&self) -> String {
|
||||
[oid::COMMON_NAME, oid::ORGANIZATION]
|
||||
.into_iter()
|
||||
.find_map(|id| {
|
||||
name_attributes(self.subject)
|
||||
.find(|(attribute, _)| *attribute == id)
|
||||
.and_then(|(_, value)| std::str::from_utf8(value).ok())
|
||||
})
|
||||
.or_else(|| {
|
||||
name_attributes(self.subject).find_map(|(_, value)| std::str::from_utf8(value).ok())
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
pub(crate) fn is_self_issued(&self) -> bool {
|
||||
self.subject == self.issuer
|
||||
}
|
||||
|
||||
pub(crate) fn is_valid_at(&self, now: u64) -> bool {
|
||||
self.not_before <= now && now <= self.not_after
|
||||
}
|
||||
|
||||
pub(crate) fn crl_urls(&self) -> impl Iterator<Item = &'x str> + use<'x> {
|
||||
self.extensions
|
||||
.crl_distribution_points
|
||||
.into_iter()
|
||||
.flat_map(|points| Reader::new(points).map_while(Result::ok))
|
||||
.filter_map(|point| {
|
||||
let name = point.reader().read_optional(DP_NAME).ok()??;
|
||||
let full = name.reader().read().ok()?;
|
||||
(full.tag == DP_FULL_NAME).then_some(full.content)
|
||||
})
|
||||
.flat_map(uris)
|
||||
}
|
||||
|
||||
pub(crate) fn ca_issuer_urls(&self) -> impl Iterator<Item = &'x str> + use<'x> {
|
||||
self.extensions
|
||||
.aia
|
||||
.into_iter()
|
||||
.flat_map(|aia| Reader::new(aia).map_while(Result::ok))
|
||||
.filter_map(|access| {
|
||||
let mut access = access.reader();
|
||||
if access.read_content(tag::OID).ok()? != oid::CA_ISSUERS {
|
||||
return None;
|
||||
}
|
||||
let location = access.read().ok()?;
|
||||
(location.tag == GN_URI)
|
||||
.then(|| std::str::from_utf8(location.content).ok())
|
||||
.flatten()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn name_attributes(name: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
|
||||
Reader::new(name)
|
||||
.read_sequence()
|
||||
.into_iter()
|
||||
.flat_map(|rdns| rdns.map_while(Result::ok))
|
||||
.flat_map(|rdn| rdn.reader().map_while(Result::ok))
|
||||
.filter_map(|atv| {
|
||||
let mut atv = atv.reader();
|
||||
let id = atv.read_content(tag::OID).ok()?;
|
||||
let value = atv.read().ok()?;
|
||||
Some((id, value.content))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn signature_scheme(
|
||||
algorithm: &AlgorithmId<'_>,
|
||||
spki: &Spki<'_>,
|
||||
) -> Option<SignatureScheme> {
|
||||
let ec_curve = || {
|
||||
let params = spki.algorithm.params?;
|
||||
match params.content {
|
||||
oid::P256 => Some(EcCurve::P256),
|
||||
oid::P384 => Some(EcCurve::P384),
|
||||
oid::P521 => Some(EcCurve::P521),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
Some(match algorithm.oid {
|
||||
oid::SHA1_WITH_RSA => SignatureScheme::RsaPkcs1(HashAlgorithm::Sha1),
|
||||
oid::SHA256_WITH_RSA => SignatureScheme::RsaPkcs1(HashAlgorithm::Sha256),
|
||||
oid::SHA384_WITH_RSA => SignatureScheme::RsaPkcs1(HashAlgorithm::Sha384),
|
||||
oid::SHA512_WITH_RSA => SignatureScheme::RsaPkcs1(HashAlgorithm::Sha512),
|
||||
oid::RSASSA_PSS => SignatureScheme::RsaPss(pss_hash(algorithm)?),
|
||||
oid::ECDSA_SHA1 => SignatureScheme::Ecdsa(ec_curve()?, HashAlgorithm::Sha1),
|
||||
oid::ECDSA_SHA256 => SignatureScheme::Ecdsa(ec_curve()?, HashAlgorithm::Sha256),
|
||||
oid::ECDSA_SHA384 => SignatureScheme::Ecdsa(ec_curve()?, HashAlgorithm::Sha384),
|
||||
oid::ECDSA_SHA512 => SignatureScheme::Ecdsa(ec_curve()?, HashAlgorithm::Sha512),
|
||||
oid::ED25519 => SignatureScheme::Ed25519,
|
||||
oid::ED448 => SignatureScheme::Ed448,
|
||||
oid::ML_DSA_44 => SignatureScheme::MlDsa(MlDsa::MlDsa44),
|
||||
oid::ML_DSA_65 => SignatureScheme::MlDsa(MlDsa::MlDsa65),
|
||||
oid::ML_DSA_87 => SignatureScheme::MlDsa(MlDsa::MlDsa87),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn digest_oid_hash(id: &[u8]) -> Option<HashAlgorithm> {
|
||||
Some(match id {
|
||||
oid::SHA1 => HashAlgorithm::Sha1,
|
||||
oid::SHA224 => HashAlgorithm::Sha224,
|
||||
oid::SHA256 => HashAlgorithm::Sha256,
|
||||
oid::SHA384 => HashAlgorithm::Sha384,
|
||||
oid::SHA512 => HashAlgorithm::Sha512,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn pss_hash(algorithm: &AlgorithmId<'_>) -> Option<HashAlgorithm> {
|
||||
let params = algorithm.params?;
|
||||
let mut reader = params.reader();
|
||||
let hash = reader.read_optional(tag::context_constructed(0)).ok()??;
|
||||
let hash = AlgorithmId::parse(hash.reader().read().ok()?).ok()?;
|
||||
digest_oid_hash(hash.oid).filter(|h| {
|
||||
matches!(
|
||||
h,
|
||||
HashAlgorithm::Sha256 | HashAlgorithm::Sha384 | HashAlgorithm::Sha512
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn signature_hash(algorithm: &AlgorithmId<'_>) -> Option<HashAlgorithm> {
|
||||
match algorithm.oid {
|
||||
oid::SHA1_WITH_RSA | oid::ECDSA_SHA1 => Some(HashAlgorithm::Sha1),
|
||||
oid::SHA256_WITH_RSA | oid::ECDSA_SHA256 => Some(HashAlgorithm::Sha256),
|
||||
oid::SHA384_WITH_RSA | oid::ECDSA_SHA384 => Some(HashAlgorithm::Sha384),
|
||||
oid::SHA512_WITH_RSA | oid::ECDSA_SHA512 => Some(HashAlgorithm::Sha512),
|
||||
oid::RSASSA_PSS => pss_hash(algorithm),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn verify_prehashed(
|
||||
algorithm: &AlgorithmId<'_>,
|
||||
spki: &Spki<'_>,
|
||||
digest: &[u8],
|
||||
signature: &[u8],
|
||||
) -> bool {
|
||||
let Some(hash) = signature_hash(algorithm) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(digest) = aws_lc_rs::digest::Digest::import_less_safe(digest, hash.algorithm()) else {
|
||||
return false;
|
||||
};
|
||||
signature_scheme(algorithm, spki)
|
||||
.is_some_and(|scheme| scheme.verify_digest(spki.key, &digest, signature).is_ok())
|
||||
}
|
||||
|
||||
pub(crate) fn verify_signature(
|
||||
algorithm: &AlgorithmId<'_>,
|
||||
spki: &Spki<'_>,
|
||||
message: &[u8],
|
||||
signature: &[u8],
|
||||
) -> bool {
|
||||
signature_scheme(algorithm, spki)
|
||||
.is_some_and(|scheme| scheme.verify(spki.key, message, signature).is_ok())
|
||||
}
|
||||
288
crates/crypto/src/x509/chain.rs
Normal file
288
crates/crypto/src/x509/chain.rs
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
backend::hash::HashAlgorithm,
|
||||
error::ChainError,
|
||||
x509::{
|
||||
cert::{Certificate, KU_CRL_SIGN, KU_KEY_CERT_SIGN, signature_hash},
|
||||
crl::Crl,
|
||||
names::NameConstraints,
|
||||
trust::{Anchor, TrustAnchors},
|
||||
},
|
||||
};
|
||||
|
||||
const MAX_PATH: usize = 6;
|
||||
const MAX_TRACKED_URLS: usize = 8;
|
||||
const MAX_SIGNATURE_CHECKS: usize = 48;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct TrustContext<'x> {
|
||||
pub anchors: &'x TrustAnchors,
|
||||
pub intermediates: &'x [&'x [u8]],
|
||||
pub crls: &'x [Crl],
|
||||
pub now: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum ChainStatus {
|
||||
Valid,
|
||||
RevocationUnknown,
|
||||
Expired,
|
||||
Revoked,
|
||||
Untrusted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ChainVerdict {
|
||||
pub status: ChainStatus,
|
||||
pub crl_urls: Vec<Box<str>>,
|
||||
pub issuer_urls: Vec<Box<str>>,
|
||||
}
|
||||
|
||||
enum Revocation {
|
||||
Good,
|
||||
Revoked,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
struct Search<'c, 'x> {
|
||||
ctx: &'c TrustContext<'x>,
|
||||
path: [Option<Certificate<'x>>; MAX_PATH],
|
||||
budget: usize,
|
||||
best: Option<(ChainStatus, Vec<Box<str>>)>,
|
||||
issuer_urls: Vec<Box<str>>,
|
||||
}
|
||||
|
||||
fn push_unique(urls: &mut Vec<Box<str>>, url: &str) {
|
||||
if urls.len() < MAX_TRACKED_URLS && !urls.iter().any(|known| known.as_ref() == url) {
|
||||
urls.push(url.into());
|
||||
}
|
||||
}
|
||||
|
||||
fn key_ids_match(child: &Certificate<'_>, issuer: &Certificate<'_>) -> bool {
|
||||
match (child.extensions.aki, issuer.extensions.ski) {
|
||||
(Some(aki), Some(ski)) => aki == ski,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn verify_smime_chain(leaf: &[u8], ctx: &TrustContext<'_>) -> Result<ChainVerdict, ChainError> {
|
||||
let leaf = Certificate::parse(leaf).map_err(|_| ChainError::MalformedCertificate)?;
|
||||
if leaf.extensions.unknown_critical {
|
||||
return Err(ChainError::UnsupportedCriticalExtension);
|
||||
}
|
||||
if !leaf.has_email_protection() {
|
||||
return Err(ChainError::NoEmailProtection);
|
||||
}
|
||||
if ctx.anchors.contains(&leaf) {
|
||||
let status = if leaf.is_valid_at(ctx.now) {
|
||||
ChainStatus::Valid
|
||||
} else {
|
||||
ChainStatus::Expired
|
||||
};
|
||||
return Ok(ChainVerdict {
|
||||
status,
|
||||
crl_urls: Vec::new(),
|
||||
issuer_urls: Vec::new(),
|
||||
});
|
||||
}
|
||||
let mut path = [None; MAX_PATH];
|
||||
path[0] = Some(leaf);
|
||||
let mut search = Search {
|
||||
ctx,
|
||||
path,
|
||||
budget: MAX_SIGNATURE_CHECKS,
|
||||
best: None,
|
||||
issuer_urls: Vec::new(),
|
||||
};
|
||||
search.extend(1);
|
||||
Ok(match search.best {
|
||||
Some((status, crl_urls)) => ChainVerdict {
|
||||
status,
|
||||
crl_urls,
|
||||
issuer_urls: Vec::new(),
|
||||
},
|
||||
None => ChainVerdict {
|
||||
status: ChainStatus::Untrusted,
|
||||
crl_urls: Vec::new(),
|
||||
issuer_urls: search.issuer_urls,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
impl<'x> Search<'_, 'x> {
|
||||
fn below(&self, depth: usize) -> impl Iterator<Item = &Certificate<'x>> {
|
||||
self.path.get(..depth).unwrap_or_default().iter().flatten()
|
||||
}
|
||||
|
||||
fn intermediates_below(&self, depth: usize) -> u32 {
|
||||
self.below(depth)
|
||||
.skip(1)
|
||||
.filter(|cert| !cert.is_self_issued())
|
||||
.count() as u32
|
||||
}
|
||||
|
||||
fn signs(&mut self, issuer: &Certificate<'_>, child: &Certificate<'_>) -> bool {
|
||||
if self.budget == 0 {
|
||||
return false;
|
||||
}
|
||||
self.budget -= 1;
|
||||
signature_hash(&child.signature_algorithm) != Some(HashAlgorithm::Sha1)
|
||||
&& child.verify_signed_by(&issuer.spki)
|
||||
}
|
||||
|
||||
fn constraints_permit(&self, issuer: &Certificate<'_>, depth: usize) -> bool {
|
||||
let Some(content) = issuer.extensions.name_constraints else {
|
||||
return true;
|
||||
};
|
||||
let Ok(constraints) = NameConstraints::parse(content) else {
|
||||
return false;
|
||||
};
|
||||
self.below(depth)
|
||||
.enumerate()
|
||||
.all(|(index, cert)| (index > 0 && cert.is_self_issued()) || constraints.permits(cert))
|
||||
}
|
||||
|
||||
fn path_len_ok(&self, issuer: &Certificate<'_>, depth: usize) -> bool {
|
||||
issuer
|
||||
.extensions
|
||||
.basic_constraints
|
||||
.and_then(|bc| bc.path_len)
|
||||
.is_none_or(|max| self.intermediates_below(depth) <= max)
|
||||
}
|
||||
|
||||
fn intermediate_ok(&self, candidate: &Certificate<'_>, depth: usize) -> bool {
|
||||
!candidate.extensions.unknown_critical
|
||||
&& candidate.is_ca()
|
||||
&& candidate
|
||||
.extensions
|
||||
.key_usage
|
||||
.is_none_or(|bits| bits & KU_KEY_CERT_SIGN != 0)
|
||||
&& candidate.has_email_protection()
|
||||
&& self.path_len_ok(candidate, depth)
|
||||
&& self.constraints_permit(candidate, depth)
|
||||
}
|
||||
|
||||
fn anchor_ok(&self, anchor: &Anchor<'_>, depth: usize) -> bool {
|
||||
let leaf_issued = self.path[0].map_or(0, |leaf| leaf.not_before);
|
||||
anchor
|
||||
.distrust_after
|
||||
.is_none_or(|distrust| leaf_issued <= distrust)
|
||||
&& self.path_len_ok(&anchor.cert, depth)
|
||||
&& self.constraints_permit(&anchor.cert, depth)
|
||||
}
|
||||
|
||||
fn extend(&mut self, depth: usize) -> bool {
|
||||
let Some(Some(child)) = self.path.get(depth - 1).copied() else {
|
||||
return false;
|
||||
};
|
||||
let ctx = self.ctx;
|
||||
let mut issuer_seen = false;
|
||||
for anchor in ctx.anchors.find(child.issuer) {
|
||||
issuer_seen = true;
|
||||
if !key_ids_match(&child, &anchor.cert)
|
||||
|| !self.anchor_ok(&anchor, depth)
|
||||
|| !self.signs(&anchor.cert, &child)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (status, urls) = self.evaluate(depth, &anchor.cert);
|
||||
if self.best.as_ref().is_none_or(|(best, _)| status < *best) {
|
||||
self.best = Some((status, urls));
|
||||
}
|
||||
if status == ChainStatus::Valid {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if depth < MAX_PATH {
|
||||
for der in ctx.intermediates {
|
||||
let Ok(candidate) = Certificate::parse(der) else {
|
||||
continue;
|
||||
};
|
||||
if candidate.subject != child.issuer {
|
||||
continue;
|
||||
}
|
||||
issuer_seen = true;
|
||||
if self.below(depth).any(|known| known.raw == candidate.raw)
|
||||
|| !key_ids_match(&child, &candidate)
|
||||
|| !self.intermediate_ok(&candidate, depth)
|
||||
|| !self.signs(&candidate, &child)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if let Some(slot) = self.path.get_mut(depth) {
|
||||
*slot = Some(candidate);
|
||||
}
|
||||
if self.extend(depth + 1) {
|
||||
return true;
|
||||
}
|
||||
if let Some(slot) = self.path.get_mut(depth) {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !issuer_seen {
|
||||
for url in child.ca_issuer_urls() {
|
||||
push_unique(&mut self.issuer_urls, url);
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn revocation(&self, cert: &Certificate<'_>, issuer: &Certificate<'_>) -> Revocation {
|
||||
let mut result = Revocation::Unknown;
|
||||
if issuer
|
||||
.extensions
|
||||
.key_usage
|
||||
.is_some_and(|bits| bits & KU_CRL_SIGN == 0)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
for crl in self.ctx.crls {
|
||||
if crl.covers(cert) && crl.is_current(self.ctx.now) && crl.verify(&issuer.spki) {
|
||||
if crl.is_revoked(cert.serial) {
|
||||
return Revocation::Revoked;
|
||||
}
|
||||
result = Revocation::Good;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn evaluate(&self, depth: usize, anchor: &Certificate<'_>) -> (ChainStatus, Vec<Box<str>>) {
|
||||
let mut expired = false;
|
||||
let mut revoked = false;
|
||||
let mut crl_urls = Vec::new();
|
||||
let mut certs = self.below(depth).peekable();
|
||||
while let Some(cert) = certs.next() {
|
||||
let issuer = certs.peek().copied().unwrap_or(anchor);
|
||||
expired |= !cert.is_valid_at(self.ctx.now);
|
||||
match self.revocation(cert, issuer) {
|
||||
Revocation::Good => {}
|
||||
Revocation::Revoked => revoked = true,
|
||||
Revocation::Unknown => {
|
||||
for url in cert.crl_urls() {
|
||||
push_unique(&mut crl_urls, url);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let status = if revoked {
|
||||
ChainStatus::Revoked
|
||||
} else if expired {
|
||||
ChainStatus::Expired
|
||||
} else if !crl_urls.is_empty() {
|
||||
ChainStatus::RevocationUnknown
|
||||
} else {
|
||||
ChainStatus::Valid
|
||||
};
|
||||
if status != ChainStatus::RevocationUnknown {
|
||||
crl_urls.clear();
|
||||
}
|
||||
(status, crl_urls)
|
||||
}
|
||||
}
|
||||
323
crates/crypto/src/x509/crl.rs
Normal file
323
crates/crypto/src/x509/crl.rs
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::{
|
||||
backend::hash::HashAlgorithm,
|
||||
der::{
|
||||
oid,
|
||||
reader::{Reader, Tlv},
|
||||
tag,
|
||||
},
|
||||
error::CrlError,
|
||||
pgp::armor::{decode_body, next_block},
|
||||
x509::{
|
||||
cert::{AlgorithmId, Certificate, Spki, bit_string, signature_hash, verify_prehashed},
|
||||
names::uris,
|
||||
time::parse_time,
|
||||
},
|
||||
};
|
||||
|
||||
const MAX_CRL_LEN: usize = 64 << 20;
|
||||
const MAX_SERIAL_LEN: usize = 20;
|
||||
const LONG_SERIAL: u8 = 0xFF;
|
||||
const PEM_CRL: &[u8] = b"X509 CRL";
|
||||
const IDP_DISTRIBUTION_POINT: u8 = tag::context_constructed(0);
|
||||
const IDP_FULL_NAME: u8 = tag::context_constructed(0);
|
||||
const IDP_ONLY_USER: u8 = tag::context(1);
|
||||
const IDP_ONLY_CA: u8 = tag::context(2);
|
||||
const IDP_ONLY_SOME_REASONS: u8 = tag::context(3);
|
||||
const IDP_INDIRECT: u8 = tag::context(4);
|
||||
const IDP_ONLY_ATTRIBUTE: u8 = tag::context(5);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
struct SerialKey([u8; MAX_SERIAL_LEN + 1]);
|
||||
|
||||
impl SerialKey {
|
||||
fn new(serial: &[u8]) -> Self {
|
||||
let mut key = [0u8; MAX_SERIAL_LEN + 1];
|
||||
let (len, bytes) = key.split_at_mut(1);
|
||||
match bytes.get_mut(..serial.len()) {
|
||||
Some(slot) => {
|
||||
slot.copy_from_slice(serial);
|
||||
len[0] = serial.len() as u8;
|
||||
}
|
||||
None => {
|
||||
let digest = HashAlgorithm::Sha1.digest(serial);
|
||||
bytes.copy_from_slice(digest.as_ref());
|
||||
len[0] = LONG_SERIAL;
|
||||
}
|
||||
}
|
||||
SerialKey(key)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
enum CertScope {
|
||||
#[default]
|
||||
All,
|
||||
EndEntity,
|
||||
Authority,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct Scope {
|
||||
certs: CertScope,
|
||||
distribution_points: Box<[Box<str>]>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
enum SignedPayload {
|
||||
Digest(Box<[u8]>),
|
||||
Message(Box<[u8]>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Crl {
|
||||
issuer: Box<[u8]>,
|
||||
this_update: u64,
|
||||
next_update: Option<u64>,
|
||||
scope: Scope,
|
||||
revoked: Box<[SerialKey]>,
|
||||
algorithm: Box<[u8]>,
|
||||
payload: SignedPayload,
|
||||
signature: Box<[u8]>,
|
||||
}
|
||||
|
||||
impl Crl {
|
||||
pub fn issuer_der(&self) -> &[u8] {
|
||||
&self.issuer
|
||||
}
|
||||
|
||||
pub fn this_update(&self) -> u64 {
|
||||
self.this_update
|
||||
}
|
||||
|
||||
pub fn next_update(&self) -> Option<u64> {
|
||||
self.next_update
|
||||
}
|
||||
|
||||
pub fn revoked_count(&self) -> usize {
|
||||
self.revoked.len()
|
||||
}
|
||||
|
||||
pub(crate) fn is_current(&self, now: u64) -> bool {
|
||||
self.this_update <= now && self.next_update.is_some_and(|next| now <= next)
|
||||
}
|
||||
|
||||
pub(crate) fn covers(&self, cert: &Certificate<'_>) -> bool {
|
||||
if cert.issuer != self.issuer.as_ref() {
|
||||
return false;
|
||||
}
|
||||
let scope_ok = match self.scope.certs {
|
||||
CertScope::All => true,
|
||||
CertScope::EndEntity => !cert.is_ca(),
|
||||
CertScope::Authority => cert.is_ca(),
|
||||
};
|
||||
scope_ok
|
||||
&& (self.scope.distribution_points.is_empty()
|
||||
|| cert.crl_urls().any(|url| {
|
||||
self.scope
|
||||
.distribution_points
|
||||
.iter()
|
||||
.any(|dp| dp.as_bytes() == url.as_bytes())
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn is_revoked(&self, serial: &[u8]) -> bool {
|
||||
self.revoked.binary_search(&SerialKey::new(serial)).is_ok()
|
||||
}
|
||||
|
||||
pub(crate) fn verify(&self, issuer: &Spki<'_>) -> bool {
|
||||
let Ok(algorithm) = Reader::new(&self.algorithm)
|
||||
.read()
|
||||
.and_then(AlgorithmId::parse)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
match &self.payload {
|
||||
SignedPayload::Digest(digest) => {
|
||||
verify_prehashed(&algorithm, issuer, digest, &self.signature)
|
||||
}
|
||||
SignedPayload::Message(message) => {
|
||||
crate::x509::cert::verify_signature(&algorithm, issuer, message, &self.signature)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_crl(input: &[u8]) -> Result<Crl, CrlError> {
|
||||
if input.len() > MAX_CRL_LEN {
|
||||
return Err(CrlError::TooLarge);
|
||||
}
|
||||
let der = pem_or_der(input)?;
|
||||
parse_der(&der)
|
||||
}
|
||||
|
||||
fn pem_or_der(input: &[u8]) -> Result<Cow<'_, [u8]>, CrlError> {
|
||||
let trimmed = input.trim_ascii_start();
|
||||
if !trimmed.starts_with(b"-----BEGIN ") {
|
||||
return Ok(Cow::Borrowed(input));
|
||||
}
|
||||
let (block, _) = next_block(trimmed)
|
||||
.ok()
|
||||
.flatten()
|
||||
.ok_or(CrlError::Malformed)?;
|
||||
if block.raw_label != PEM_CRL {
|
||||
return Err(CrlError::Malformed);
|
||||
}
|
||||
let mut out = Vec::with_capacity(block.body.len() / 4 * 3);
|
||||
decode_body(block.body, &mut out).map_err(|_| CrlError::Malformed)?;
|
||||
Ok(Cow::Owned(out))
|
||||
}
|
||||
|
||||
fn parse_der(der: &[u8]) -> Result<Crl, CrlError> {
|
||||
let mut outer = Reader::new(der);
|
||||
let list = outer.read_tag(tag::SEQUENCE)?;
|
||||
outer.finish()?;
|
||||
let mut list = list.reader();
|
||||
let tbs_tlv = list.read_tag(tag::SEQUENCE)?;
|
||||
let algorithm_tlv = list.read()?;
|
||||
let algorithm = AlgorithmId::parse(algorithm_tlv)?;
|
||||
let signature = bit_string(list.read()?)?;
|
||||
list.finish()?;
|
||||
let hash = signature_hash(&algorithm);
|
||||
if hash == Some(HashAlgorithm::Sha1) {
|
||||
return Err(CrlError::Sha1Signature);
|
||||
}
|
||||
|
||||
let mut tbs = tbs_tlv.reader();
|
||||
if tbs.peek_tag() == Some(tag::INTEGER) {
|
||||
let version = tbs.read_small_unsigned()?;
|
||||
if version > 1 {
|
||||
return Err(CrlError::Malformed);
|
||||
}
|
||||
}
|
||||
let inner_algorithm = tbs.read()?;
|
||||
if inner_algorithm.raw != algorithm_tlv.raw {
|
||||
return Err(CrlError::Malformed);
|
||||
}
|
||||
let issuer = tbs.read_tag(tag::SEQUENCE)?.raw;
|
||||
let this_update = parse_time(tbs.read()?)?;
|
||||
let next_update = match tbs.peek_tag() {
|
||||
Some(tag::UTC_TIME | tag::GENERALIZED_TIME) => Some(parse_time(tbs.read()?)?),
|
||||
_ => None,
|
||||
};
|
||||
let entries = tbs.read_optional(tag::SEQUENCE)?;
|
||||
let scope = match tbs.read_optional(tag::context_constructed(0))? {
|
||||
Some(extensions) => parse_extensions(extensions)?,
|
||||
None => Scope::default(),
|
||||
};
|
||||
tbs.finish()?;
|
||||
|
||||
let revoked = match entries {
|
||||
Some(entries) => parse_entries(entries)?,
|
||||
None => Box::default(),
|
||||
};
|
||||
let payload = match hash {
|
||||
Some(hash) => SignedPayload::Digest(hash.digest(tbs_tlv.raw).as_ref().into()),
|
||||
None => SignedPayload::Message(tbs_tlv.raw.into()),
|
||||
};
|
||||
Ok(Crl {
|
||||
issuer: issuer.into(),
|
||||
this_update,
|
||||
next_update,
|
||||
scope,
|
||||
revoked,
|
||||
algorithm: algorithm.raw.into(),
|
||||
payload,
|
||||
signature: signature.into(),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_entries(entries: Tlv<'_>) -> Result<Box<[SerialKey]>, CrlError> {
|
||||
let count = entries
|
||||
.reader()
|
||||
.try_fold(0usize, |count, entry| entry.map(|_| count + 1))?;
|
||||
let mut revoked = Vec::with_capacity(count);
|
||||
for entry in entries.reader() {
|
||||
let mut entry = entry?.expect(tag::SEQUENCE)?.reader();
|
||||
let serial = entry.read_content(tag::INTEGER)?;
|
||||
parse_time(entry.read()?)?;
|
||||
if let Some(extensions) = entry.read_optional(tag::SEQUENCE)? {
|
||||
for extension in extensions.reader() {
|
||||
let mut extension = extension?.expect(tag::SEQUENCE)?.reader();
|
||||
let id = extension.read_content(tag::OID)?;
|
||||
let critical = extension.read_bool_default_false()?;
|
||||
if critical && id != oid::EXT_REASON_CODE && id != oid::EXT_INVALIDITY_DATE {
|
||||
return Err(CrlError::UnsupportedCriticalExtension);
|
||||
}
|
||||
}
|
||||
}
|
||||
entry.finish()?;
|
||||
revoked.push(SerialKey::new(serial));
|
||||
}
|
||||
revoked.sort_unstable();
|
||||
Ok(revoked.into_boxed_slice())
|
||||
}
|
||||
|
||||
fn parse_extensions(extensions: Tlv<'_>) -> Result<Scope, CrlError> {
|
||||
let mut scope = Scope::default();
|
||||
let mut list = extensions.reader().read_sequence()?;
|
||||
while !list.is_empty() {
|
||||
let mut extension = list.read_sequence()?;
|
||||
let id = extension.read_content(tag::OID)?;
|
||||
let critical = extension.read_bool_default_false()?;
|
||||
let value = extension.read_content(tag::OCTET_STRING)?;
|
||||
extension.finish()?;
|
||||
match id {
|
||||
oid::EXT_DELTA_CRL_INDICATOR => return Err(CrlError::DeltaCrl),
|
||||
oid::EXT_ISSUING_DISTRIBUTION_POINT => {
|
||||
scope = parse_idp(value)?;
|
||||
}
|
||||
oid::EXT_AUTHORITY_KEY_ID
|
||||
| oid::EXT_CRL_NUMBER
|
||||
| oid::EXT_FRESHEST_CRL
|
||||
| oid::EXT_ISSUER_ALT_NAME => {}
|
||||
_ if critical => return Err(CrlError::UnsupportedCriticalExtension),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(scope)
|
||||
}
|
||||
|
||||
fn parse_idp(value: &[u8]) -> Result<Scope, CrlError> {
|
||||
let mut idp = Reader::new(value).read_sequence()?;
|
||||
let mut distribution_points = Box::default();
|
||||
if let Some(point) = idp.read_optional(IDP_DISTRIBUTION_POINT)? {
|
||||
let name = point.reader().read()?;
|
||||
if name.tag != IDP_FULL_NAME {
|
||||
return Err(CrlError::UnsupportedScope);
|
||||
}
|
||||
distribution_points = uris(name.content).map(Box::from).collect();
|
||||
}
|
||||
let flag = |idp: &mut Reader<'_>, tag: u8| -> Result<bool, CrlError> {
|
||||
Ok(match idp.read_optional(tag)? {
|
||||
Some(tlv) => matches!(tlv.content, [value] if *value != 0),
|
||||
None => false,
|
||||
})
|
||||
};
|
||||
let only_user = flag(&mut idp, IDP_ONLY_USER)?;
|
||||
let only_ca = flag(&mut idp, IDP_ONLY_CA)?;
|
||||
if idp.read_optional(IDP_ONLY_SOME_REASONS)?.is_some()
|
||||
|| flag(&mut idp, IDP_INDIRECT)?
|
||||
|| flag(&mut idp, IDP_ONLY_ATTRIBUTE)?
|
||||
{
|
||||
return Err(CrlError::UnsupportedScope);
|
||||
}
|
||||
idp.finish()?;
|
||||
let certs = match (only_user, only_ca) {
|
||||
(false, false) => CertScope::All,
|
||||
(true, false) => CertScope::EndEntity,
|
||||
(false, true) => CertScope::Authority,
|
||||
(true, true) => return Err(CrlError::Malformed),
|
||||
};
|
||||
Ok(Scope {
|
||||
certs,
|
||||
distribution_points,
|
||||
})
|
||||
}
|
||||
13
crates/crypto/src/x509/mod.rs
Normal file
13
crates/crypto/src/x509/mod.rs
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
pub(crate) mod cert;
|
||||
pub mod chain;
|
||||
pub mod crl;
|
||||
pub(crate) mod names;
|
||||
pub(crate) mod recipient;
|
||||
pub(crate) mod time;
|
||||
pub mod trust;
|
||||
246
crates/crypto/src/x509/names.rs
Normal file
246
crates/crypto/src/x509/names.rs
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
der::{DerError, oid, reader::Reader, tag},
|
||||
x509::cert::{Certificate, name_attributes},
|
||||
};
|
||||
|
||||
pub(crate) const GN_OTHER_NAME: u8 = tag::context_constructed(0);
|
||||
pub(crate) const GN_RFC822: u8 = tag::context(1);
|
||||
pub(crate) const GN_DNS: u8 = tag::context(2);
|
||||
pub(crate) const GN_DIRECTORY: u8 = tag::context_constructed(4);
|
||||
pub(crate) const GN_URI: u8 = tag::context(6);
|
||||
pub(crate) const GN_IP: u8 = tag::context(7);
|
||||
const PERMITTED: u8 = tag::context_constructed(0);
|
||||
const EXCLUDED: u8 = tag::context_constructed(1);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Form {
|
||||
Email,
|
||||
Dns,
|
||||
Directory,
|
||||
Ip,
|
||||
Other(u8),
|
||||
}
|
||||
|
||||
impl Form {
|
||||
fn of(tag: u8) -> Self {
|
||||
match tag {
|
||||
GN_RFC822 => Form::Email,
|
||||
GN_DNS => Form::Dns,
|
||||
GN_DIRECTORY => Form::Directory,
|
||||
GN_IP => Form::Ip,
|
||||
other => Form::Other(other & !tag::CONSTRUCTED),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Name<'x> {
|
||||
form: Form,
|
||||
value: &'x [u8],
|
||||
}
|
||||
|
||||
pub(crate) fn uris(general_names: &[u8]) -> impl Iterator<Item = &str> {
|
||||
Reader::new(general_names)
|
||||
.map_while(Result::ok)
|
||||
.filter(|name| name.tag == GN_URI)
|
||||
.filter_map(|name| std::str::from_utf8(name.content).ok())
|
||||
}
|
||||
|
||||
pub(crate) fn smtp_utf8_mailbox(other_name: &[u8]) -> Option<&[u8]> {
|
||||
let mut other = Reader::new(other_name);
|
||||
if other.read_content(tag::OID).ok()? != oid::SMTP_UTF8_MAILBOX {
|
||||
return None;
|
||||
}
|
||||
let value = other.read_tag(tag::context_constructed(0)).ok()?;
|
||||
value.reader().read_content(tag::UTF8_STRING).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn general_names(content: &[u8]) -> Result<&[u8], DerError> {
|
||||
for name in Reader::new(content) {
|
||||
let name = name?;
|
||||
if name.tag == GN_OTHER_NAME
|
||||
&& Reader::new(name.content).read_content(tag::OID)? == oid::SMTP_UTF8_MAILBOX
|
||||
&& smtp_utf8_mailbox(name.content).is_none()
|
||||
{
|
||||
return Err(DerError::InvalidValue);
|
||||
}
|
||||
}
|
||||
Ok(content)
|
||||
}
|
||||
|
||||
fn cert_names<'x>(cert: &Certificate<'x>) -> impl Iterator<Item = Name<'x>> {
|
||||
let subject = Reader::new(cert.subject)
|
||||
.read_tag(tag::SEQUENCE)
|
||||
.ok()
|
||||
.filter(|dn| !dn.content.is_empty())
|
||||
.map(|dn| Name {
|
||||
form: Form::Directory,
|
||||
value: dn.content,
|
||||
});
|
||||
let san = cert
|
||||
.extensions
|
||||
.san
|
||||
.into_iter()
|
||||
.flat_map(|san| Reader::new(san).map_while(Result::ok))
|
||||
.map(|name| match name.tag {
|
||||
GN_OTHER_NAME => match smtp_utf8_mailbox(name.content) {
|
||||
Some(mailbox) => Name {
|
||||
form: Form::Email,
|
||||
value: mailbox,
|
||||
},
|
||||
None => Name {
|
||||
form: Form::Other(name.tag & !tag::CONSTRUCTED),
|
||||
value: name.content,
|
||||
},
|
||||
},
|
||||
other => Name {
|
||||
form: Form::of(other),
|
||||
value: name.content,
|
||||
},
|
||||
});
|
||||
let emails = name_attributes(cert.subject)
|
||||
.filter(|(id, _)| *id == oid::EMAIL_ADDRESS)
|
||||
.map(|(_, value)| Name {
|
||||
form: Form::Email,
|
||||
value,
|
||||
});
|
||||
subject.into_iter().chain(san).chain(emails)
|
||||
}
|
||||
|
||||
fn ends_with_ignore_case(value: &[u8], suffix: &[u8]) -> bool {
|
||||
value
|
||||
.len()
|
||||
.checked_sub(suffix.len())
|
||||
.and_then(|start| value.get(start..))
|
||||
.is_some_and(|tail| tail.eq_ignore_ascii_case(suffix))
|
||||
}
|
||||
|
||||
fn domain_matches(domain: &[u8], constraint: &[u8]) -> bool {
|
||||
match constraint.strip_prefix(b".") {
|
||||
Some(_) => domain.len() > constraint.len() && ends_with_ignore_case(domain, constraint),
|
||||
None => {
|
||||
domain.eq_ignore_ascii_case(constraint)
|
||||
|| (ends_with_ignore_case(domain, constraint)
|
||||
&& domain
|
||||
.len()
|
||||
.checked_sub(constraint.len() + 1)
|
||||
.and_then(|dot| domain.get(dot))
|
||||
== Some(&b'.'))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn email_matches(address: &[u8], constraint: &[u8]) -> bool {
|
||||
if memchr::memchr(b'@', constraint).is_some() {
|
||||
return address.eq_ignore_ascii_case(constraint);
|
||||
}
|
||||
let mut parts = address.rsplitn(2, |b| *b == b'@');
|
||||
let (Some(domain), Some(_)) = (parts.next(), parts.next()) else {
|
||||
return false;
|
||||
};
|
||||
match constraint.strip_prefix(b".") {
|
||||
Some(_) => domain.len() > constraint.len() && ends_with_ignore_case(domain, constraint),
|
||||
None => domain.eq_ignore_ascii_case(constraint),
|
||||
}
|
||||
}
|
||||
|
||||
fn dns_matches(name: &[u8], constraint: &[u8]) -> bool {
|
||||
let constraint = constraint.strip_prefix(b".").unwrap_or(constraint);
|
||||
constraint.is_empty() || domain_matches(name, constraint)
|
||||
}
|
||||
|
||||
fn directory_matches(subject: &[u8], constraint: &[u8]) -> bool {
|
||||
let mut subject = Reader::new(subject);
|
||||
for rdn in Reader::new(constraint) {
|
||||
match (rdn, subject.read()) {
|
||||
(Ok(expected), Ok(actual)) if expected.raw == actual.raw => {}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn ip_matches(address: &[u8], constraint: &[u8]) -> bool {
|
||||
if constraint.len() != address.len() * 2 {
|
||||
return false;
|
||||
}
|
||||
let (network, mask) = constraint.split_at(address.len());
|
||||
address
|
||||
.iter()
|
||||
.zip(network)
|
||||
.zip(mask)
|
||||
.all(|((a, n), m)| a & m == n & m)
|
||||
}
|
||||
|
||||
fn matches(name: Name<'_>, base: &[u8]) -> bool {
|
||||
match name.form {
|
||||
Form::Email => email_matches(name.value, base),
|
||||
Form::Dns => dns_matches(name.value, base),
|
||||
Form::Directory => directory_matches(name.value, base),
|
||||
Form::Ip => ip_matches(name.value, base),
|
||||
Form::Other(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn subtree_bases(subtrees: Option<&[u8]>) -> impl Iterator<Item = Result<(Form, &[u8]), DerError>> {
|
||||
subtrees.into_iter().flat_map(Reader::new).map(|subtree| {
|
||||
let subtree = subtree?.expect(tag::SEQUENCE)?;
|
||||
let base = subtree.reader().read()?;
|
||||
let content = if base.tag == GN_DIRECTORY {
|
||||
base.reader().read_tag(tag::SEQUENCE)?.content
|
||||
} else {
|
||||
base.content
|
||||
};
|
||||
Ok((Form::of(base.tag), content))
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct NameConstraints<'x> {
|
||||
permitted: Option<&'x [u8]>,
|
||||
excluded: Option<&'x [u8]>,
|
||||
}
|
||||
|
||||
impl<'x> NameConstraints<'x> {
|
||||
pub(crate) fn parse(content: &'x [u8]) -> Result<Self, DerError> {
|
||||
let mut reader = Reader::new(content);
|
||||
let permitted = reader.read_optional(PERMITTED)?.map(|t| t.content);
|
||||
let excluded = reader.read_optional(EXCLUDED)?.map(|t| t.content);
|
||||
reader.finish()?;
|
||||
let constraints = NameConstraints {
|
||||
permitted,
|
||||
excluded,
|
||||
};
|
||||
for base in subtree_bases(permitted).chain(subtree_bases(excluded)) {
|
||||
base?;
|
||||
}
|
||||
Ok(constraints)
|
||||
}
|
||||
|
||||
pub(crate) fn permits(&self, cert: &Certificate<'_>) -> bool {
|
||||
cert_names(cert).all(|name| self.permits_name(name))
|
||||
}
|
||||
|
||||
fn permits_name(&self, name: Name<'_>) -> bool {
|
||||
let same_form = |subtrees| {
|
||||
subtree_bases(subtrees)
|
||||
.filter_map(Result::ok)
|
||||
.filter(move |(form, _)| *form == name.form)
|
||||
};
|
||||
if same_form(self.excluded).any(|(form, base)| match form {
|
||||
Form::Other(_) => true,
|
||||
_ => matches(name, base),
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
let mut permitted = same_form(self.permitted).peekable();
|
||||
permitted.peek().is_none()
|
||||
|| permitted.any(|(form, base)| !matches!(form, Form::Other(_)) && matches(name, base))
|
||||
}
|
||||
}
|
||||
430
crates/crypto/src/x509/recipient.rs
Normal file
430
crates/crypto/src/x509/recipient.rs
Normal file
|
|
@ -0,0 +1,430 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
backend::{
|
||||
agree::Curve,
|
||||
hash::HashAlgorithm,
|
||||
kem::{MlKem, MlKemPublicKey},
|
||||
rsa::{MAX_RSA_BITS, MIN_RSA_BITS, OaepHash, RsaPublicKey},
|
||||
},
|
||||
der::{
|
||||
oid,
|
||||
reader::Reader,
|
||||
tag,
|
||||
writer::{tlv_len, write_header, write_tlv},
|
||||
},
|
||||
error::KeyError,
|
||||
pgp::armor::{decode_body, next_block},
|
||||
types::{
|
||||
Fingerprint, KeyCapabilities, KeyCapability, KeyKind, KeyWarning, ParsedKeys, RecipientSet,
|
||||
Recipients, SmimeCapabilities, SmimeCipher,
|
||||
},
|
||||
x509::cert::{
|
||||
AlgorithmId, Certificate, KU_DATA_ENCIPHERMENT, KU_DECIPHER_ONLY, KU_DIGITAL_SIGNATURE,
|
||||
KU_ENCIPHER_ONLY, KU_KEY_AGREEMENT, KU_KEY_ENCIPHERMENT, KU_NON_REPUDIATION,
|
||||
digest_oid_hash,
|
||||
},
|
||||
};
|
||||
|
||||
const WEAK_RSA_BITS: usize = 3072;
|
||||
const PKCS12_VERSION: u32 = 3;
|
||||
const PEM_CERTIFICATE: &[u8] = b"CERTIFICATE";
|
||||
const PEM_PGP_PREFIX: &[u8] = b"PGP ";
|
||||
const MAX_CERTIFICATES: usize = 64;
|
||||
|
||||
pub(crate) enum SmimeKey {
|
||||
Rsa {
|
||||
key: RsaPublicKey,
|
||||
oaep: Option<OaepHash>,
|
||||
},
|
||||
Ec {
|
||||
curve: Curve,
|
||||
point: Box<[u8]>,
|
||||
},
|
||||
X25519([u8; 32]),
|
||||
X448([u8; 56]),
|
||||
MlKem(MlKemPublicKey),
|
||||
}
|
||||
|
||||
pub(crate) struct SmimeRecipient {
|
||||
pub issuer_and_serial: Box<[u8]>,
|
||||
pub fingerprint: [u8; 32],
|
||||
pub key: SmimeKey,
|
||||
pub gcm: bool,
|
||||
}
|
||||
|
||||
impl SmimeKey {
|
||||
pub(crate) fn algorithm_name(&self) -> String {
|
||||
match self {
|
||||
SmimeKey::Rsa { key, .. } => format!("RSA-{}", key.bits()),
|
||||
SmimeKey::Ec { curve, .. } => format!("ECDH {}", curve.name()),
|
||||
SmimeKey::X25519(_) => "X25519".to_string(),
|
||||
SmimeKey::X448(_) => "X448".to_string(),
|
||||
SmimeKey::MlKem(key) => key.kem().name().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SmimeRecipient {
|
||||
pub(crate) fn heap_size(&self) -> usize {
|
||||
self.issuer_and_serial.len()
|
||||
+ match &self.key {
|
||||
SmimeKey::Rsa { key, .. } => key.heap_size(),
|
||||
SmimeKey::Ec { point, .. } => point.len(),
|
||||
SmimeKey::X25519(_) | SmimeKey::X448(_) => 0,
|
||||
SmimeKey::MlKem(key) => key.heap_size(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode_certificates(input: &[u8]) -> Result<Vec<u8>, KeyError> {
|
||||
let trimmed = input.trim_ascii_start();
|
||||
if !trimmed.starts_with(b"-----BEGIN ") {
|
||||
return Ok(input.to_vec());
|
||||
}
|
||||
let mut out = Vec::with_capacity(input.len() / 4 * 3);
|
||||
let mut rest = trimmed;
|
||||
while let Some((block, next)) = next_block(rest)? {
|
||||
match block.raw_label {
|
||||
PEM_CERTIFICATE | b"X509 CERTIFICATE" | b"TRUSTED CERTIFICATE" => {
|
||||
decode_body(block.body, &mut out)?
|
||||
}
|
||||
label if label.ends_with(b"PRIVATE KEY") => return Err(KeyError::PrivateKey),
|
||||
label if label.starts_with(PEM_PGP_PREFIX) => return Err(KeyError::MixedKeyKinds),
|
||||
b"PKCS12" => return Err(KeyError::Pkcs12),
|
||||
_ => {}
|
||||
}
|
||||
rest = next;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub(crate) fn split_certificates(input: &[u8]) -> Result<Vec<Vec<u8>>, KeyError> {
|
||||
let der = decode_certificates(input)?;
|
||||
let parsed = certificates(&der).collect::<Result<Vec<_>, _>>()?;
|
||||
let leaves = parsed.iter().filter(|cert| !cert.is_ca());
|
||||
let authorities = parsed.iter().filter(|cert| cert.is_ca());
|
||||
Ok(leaves
|
||||
.chain(authorities)
|
||||
.map(|cert| cert.raw.to_vec())
|
||||
.collect())
|
||||
}
|
||||
|
||||
pub(crate) fn certificates(der: &[u8]) -> impl Iterator<Item = Result<Certificate<'_>, KeyError>> {
|
||||
Reader::new(der).take(MAX_CERTIFICATES).map(|tlv| {
|
||||
let tlv = tlv?.expect(tag::SEQUENCE)?;
|
||||
if let Some(Ok(first)) = tlv.reader().next()
|
||||
&& first.tag == tag::INTEGER
|
||||
{
|
||||
let version = first.content.last().copied().unwrap_or(0);
|
||||
return Err(if u32::from(version) == PKCS12_VERSION {
|
||||
KeyError::Pkcs12
|
||||
} else {
|
||||
KeyError::PrivateKey
|
||||
});
|
||||
}
|
||||
Certificate::parse_tlv(tlv).map_err(KeyError::from)
|
||||
})
|
||||
}
|
||||
|
||||
fn oaep_params(algorithm: &AlgorithmId<'_>) -> Result<OaepHash, KeyError> {
|
||||
let Some(params) = algorithm.params.filter(|p| p.tag == tag::SEQUENCE) else {
|
||||
return Ok(OaepHash::Sha1);
|
||||
};
|
||||
let mut reader = params.reader();
|
||||
let hash = match reader.read_optional(tag::context_constructed(0))? {
|
||||
Some(t) => digest_oid_hash(AlgorithmId::parse(t.reader().read()?)?.oid),
|
||||
None => Some(HashAlgorithm::Sha1),
|
||||
};
|
||||
let mgf_hash = match reader.read_optional(tag::context_constructed(1))? {
|
||||
Some(t) => {
|
||||
let mgf = AlgorithmId::parse(t.reader().read()?)?;
|
||||
if mgf.oid != oid::MGF1 {
|
||||
return Err(KeyError::UnsupportedKeyAlgorithm);
|
||||
}
|
||||
let inner = mgf.params.ok_or(KeyError::MalformedCertificate)?;
|
||||
digest_oid_hash(AlgorithmId::parse(inner)?.oid)
|
||||
}
|
||||
None => Some(HashAlgorithm::Sha1),
|
||||
};
|
||||
if reader.read_optional(tag::context_constructed(2))?.is_some() || hash != mgf_hash {
|
||||
return Err(KeyError::UnsupportedKeyAlgorithm);
|
||||
}
|
||||
match hash {
|
||||
Some(HashAlgorithm::Sha1) => Ok(OaepHash::Sha1),
|
||||
Some(HashAlgorithm::Sha256) => Ok(OaepHash::Sha256),
|
||||
Some(HashAlgorithm::Sha384) => Ok(OaepHash::Sha384),
|
||||
Some(HashAlgorithm::Sha512) => Ok(OaepHash::Sha512),
|
||||
_ => Err(KeyError::UnsupportedKeyAlgorithm),
|
||||
}
|
||||
}
|
||||
|
||||
enum Usage {
|
||||
Encipherment,
|
||||
OaepEncipherment,
|
||||
Agreement,
|
||||
}
|
||||
|
||||
fn classify(cert: &Certificate<'_>) -> Result<(SmimeKey, Usage, bool), KeyError> {
|
||||
let spki = &cert.spki;
|
||||
Ok(match spki.algorithm.oid {
|
||||
oid::RSA_ENCRYPTION | oid::RSAES_OAEP => {
|
||||
let oaep = if spki.algorithm.oid == oid::RSAES_OAEP {
|
||||
Some(oaep_params(&spki.algorithm)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut rsa = Reader::new(spki.key).read_sequence()?;
|
||||
let n = rsa.read_content(tag::INTEGER)?;
|
||||
let e = rsa.read_content(tag::INTEGER)?;
|
||||
let key = RsaPublicKey::from_components(n, e).map_err(|_| KeyError::WeakRsa)?;
|
||||
let bits = key.bits();
|
||||
if !(MIN_RSA_BITS..=MAX_RSA_BITS).contains(&bits) {
|
||||
return Err(KeyError::WeakRsa);
|
||||
}
|
||||
let usage = if oaep.is_some() {
|
||||
Usage::OaepEncipherment
|
||||
} else {
|
||||
Usage::Encipherment
|
||||
};
|
||||
(SmimeKey::Rsa { key, oaep }, usage, bits < WEAK_RSA_BITS)
|
||||
}
|
||||
oid::EC_PUBLIC_KEY => {
|
||||
let params = spki
|
||||
.algorithm
|
||||
.params
|
||||
.ok_or(KeyError::MalformedCertificate)?;
|
||||
let curve = match params.content {
|
||||
oid::P256 => Curve::P256,
|
||||
oid::P384 => Curve::P384,
|
||||
oid::P521 => Curve::P521,
|
||||
other if other.starts_with(oid::BRAINPOOL_PREFIX) => {
|
||||
return Err(KeyError::Brainpool);
|
||||
}
|
||||
_ => return Err(KeyError::UnsupportedKeyAlgorithm),
|
||||
};
|
||||
curve
|
||||
.validate_public(spki.key)
|
||||
.map_err(|_| KeyError::InvalidPublicKey)?;
|
||||
(
|
||||
SmimeKey::Ec {
|
||||
curve,
|
||||
point: spki.key.into(),
|
||||
},
|
||||
Usage::Agreement,
|
||||
false,
|
||||
)
|
||||
}
|
||||
oid::X25519 => (
|
||||
SmimeKey::X25519(
|
||||
spki.key
|
||||
.try_into()
|
||||
.map_err(|_| KeyError::InvalidPublicKey)?,
|
||||
),
|
||||
Usage::Agreement,
|
||||
false,
|
||||
),
|
||||
oid::X448 => (
|
||||
SmimeKey::X448(
|
||||
spki.key
|
||||
.try_into()
|
||||
.map_err(|_| KeyError::InvalidPublicKey)?,
|
||||
),
|
||||
Usage::Agreement,
|
||||
false,
|
||||
),
|
||||
oid::ML_KEM_512 | oid::ML_KEM_768 | oid::ML_KEM_1024 => {
|
||||
let kem = match spki.algorithm.oid {
|
||||
oid::ML_KEM_512 => MlKem::MlKem512,
|
||||
oid::ML_KEM_768 => MlKem::MlKem768,
|
||||
_ => MlKem::MlKem1024,
|
||||
};
|
||||
(
|
||||
SmimeKey::MlKem(
|
||||
MlKemPublicKey::new(kem, spki.key).map_err(|_| KeyError::InvalidPublicKey)?,
|
||||
),
|
||||
Usage::Encipherment,
|
||||
false,
|
||||
)
|
||||
}
|
||||
_ => return Err(KeyError::UnsupportedKeyAlgorithm),
|
||||
})
|
||||
}
|
||||
|
||||
fn check_key_usage(cert: &Certificate<'_>, usage: &Usage) -> Result<(), KeyError> {
|
||||
let Some(bits) = cert.extensions.key_usage else {
|
||||
return Ok(());
|
||||
};
|
||||
let allowed = match usage {
|
||||
Usage::Encipherment => bits & KU_KEY_ENCIPHERMENT != 0,
|
||||
Usage::OaepEncipherment => bits & (KU_KEY_ENCIPHERMENT | KU_DATA_ENCIPHERMENT) != 0,
|
||||
Usage::Agreement => {
|
||||
if bits & KU_KEY_AGREEMENT != 0
|
||||
&& bits & KU_ENCIPHER_ONLY != 0
|
||||
&& bits & KU_DECIPHER_ONLY == 0
|
||||
{
|
||||
return Err(KeyError::EncipherOnlyCertificate);
|
||||
}
|
||||
bits & KU_KEY_AGREEMENT != 0
|
||||
}
|
||||
};
|
||||
if allowed {
|
||||
Ok(())
|
||||
} else if bits & (KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION) != 0 {
|
||||
Err(KeyError::SignatureOnlyCertificate)
|
||||
} else {
|
||||
Err(KeyError::UnsupportedKeyAlgorithm)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn issuer_and_serial(cert: &Certificate<'_>) -> Box<[u8]> {
|
||||
let content = cert.issuer.len() + tlv_len(cert.serial.len());
|
||||
let mut out = Vec::with_capacity(tlv_len(content));
|
||||
write_header(&mut out, tag::SEQUENCE, content);
|
||||
out.extend_from_slice(cert.issuer);
|
||||
write_tlv(&mut out, tag::INTEGER, cert.serial);
|
||||
out.into_boxed_slice()
|
||||
}
|
||||
|
||||
pub(crate) fn parse_capabilities(content: &[u8]) -> SmimeCapabilities {
|
||||
let mut caps = SmimeCapabilities::default();
|
||||
for capability in Reader::new(content).map_while(Result::ok) {
|
||||
let Ok(id) = capability.reader().read_content(tag::OID) else {
|
||||
continue;
|
||||
};
|
||||
let cipher = match id {
|
||||
oid::AES128_CBC => Some(SmimeCipher::Aes128Cbc),
|
||||
oid::AES192_CBC => Some(SmimeCipher::Aes192Cbc),
|
||||
oid::AES256_CBC => Some(SmimeCipher::Aes256Cbc),
|
||||
oid::AES128_GCM => Some(SmimeCipher::Aes128Gcm),
|
||||
oid::AES192_GCM => Some(SmimeCipher::Aes192Gcm),
|
||||
oid::AES256_GCM => Some(SmimeCipher::Aes256Gcm),
|
||||
oid::CHACHA20_POLY1305 => Some(SmimeCipher::ChaCha20Poly1305),
|
||||
oid::RSAES_OAEP => {
|
||||
caps.rsaes_oaep = true;
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(cipher) = cipher
|
||||
&& !caps.ciphers.contains(&cipher)
|
||||
{
|
||||
caps.ciphers.push(cipher);
|
||||
}
|
||||
}
|
||||
caps
|
||||
}
|
||||
|
||||
pub(crate) fn lists_gcm(caps: &SmimeCapabilities) -> bool {
|
||||
caps.ciphers.iter().any(|c| {
|
||||
matches!(
|
||||
c,
|
||||
SmimeCipher::Aes128Gcm | SmimeCipher::Aes192Gcm | SmimeCipher::Aes256Gcm
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn validate_leaf(
|
||||
cert: &Certificate<'_>,
|
||||
now: u64,
|
||||
) -> Result<(SmimeRecipient, bool, bool), KeyError> {
|
||||
if now < cert.not_before {
|
||||
return Err(KeyError::NotYetValid);
|
||||
}
|
||||
if now > cert.not_after {
|
||||
return Err(KeyError::Expired);
|
||||
}
|
||||
let (key, usage, weak) = classify(cert)?;
|
||||
check_key_usage(cert, &usage)?;
|
||||
if !cert.has_email_protection() {
|
||||
return Err(KeyError::NoEmailProtection);
|
||||
}
|
||||
let no_known_decryptor = matches!(key, SmimeKey::X25519(_) | SmimeKey::X448(_));
|
||||
let mut fingerprint = [0u8; 32];
|
||||
fingerprint.copy_from_slice(HashAlgorithm::Sha256.digest(cert.raw).as_ref());
|
||||
let gcm = cert
|
||||
.extensions
|
||||
.smime_capabilities
|
||||
.is_some_and(|c| lists_gcm(&parse_capabilities(c)));
|
||||
Ok((
|
||||
SmimeRecipient {
|
||||
issuer_and_serial: issuer_and_serial(cert),
|
||||
fingerprint,
|
||||
key,
|
||||
gcm,
|
||||
},
|
||||
weak,
|
||||
no_known_decryptor,
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) fn parse_public_keys(input: &[u8], now: u64) -> Result<ParsedKeys, KeyError> {
|
||||
let der = decode_certificates(input)?;
|
||||
let mut recipients = Vec::new();
|
||||
let mut addresses: Vec<Box<str>> = Vec::new();
|
||||
let mut warnings = Vec::new();
|
||||
let mut capabilities = KeyCapabilities::default();
|
||||
let mut smime_capabilities = None;
|
||||
let mut expires_at = 0u64;
|
||||
let mut first_error = None;
|
||||
let mut all_gcm = true;
|
||||
let parsed = certificates(&der).collect::<Result<Vec<_>, _>>()?;
|
||||
let only_ca = parsed.iter().all(Certificate::is_ca);
|
||||
for cert in parsed.iter().filter(|c| only_ca || !c.is_ca()) {
|
||||
match validate_leaf(cert, now) {
|
||||
Ok((recipient, weak, no_decryptor)) => {
|
||||
if weak && !warnings.contains(&KeyWarning::WeakRsa) {
|
||||
warnings.push(KeyWarning::WeakRsa);
|
||||
}
|
||||
if no_decryptor && !warnings.contains(&KeyWarning::NoKnownDecryptor) {
|
||||
warnings.push(KeyWarning::NoKnownDecryptor);
|
||||
}
|
||||
if matches!(recipient.key, SmimeKey::MlKem(_)) {
|
||||
capabilities.insert(KeyCapability::PostQuantum);
|
||||
}
|
||||
all_gcm &= recipient.gcm;
|
||||
if smime_capabilities.is_none() {
|
||||
smime_capabilities = cert.extensions.smime_capabilities.map(parse_capabilities);
|
||||
}
|
||||
for address in cert.email_addresses() {
|
||||
if !addresses.iter().any(|a| a.eq_ignore_ascii_case(address)) {
|
||||
addresses.push(address.into());
|
||||
}
|
||||
}
|
||||
expires_at = expires_at.max(cert.not_after);
|
||||
recipients.push(recipient);
|
||||
}
|
||||
Err(err) => {
|
||||
first_error.get_or_insert(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
if recipients.is_empty() {
|
||||
return Err(first_error.unwrap_or(KeyError::NoEncryptionKey));
|
||||
}
|
||||
if all_gcm {
|
||||
capabilities.insert(KeyCapability::Aead);
|
||||
}
|
||||
if expires_at <= now + crate::pgp::EXPIRES_SOON_SECS {
|
||||
warnings.push(KeyWarning::ExpiresSoon);
|
||||
}
|
||||
Ok(ParsedKeys {
|
||||
kind: KeyKind::Smime,
|
||||
fingerprints: recipients
|
||||
.iter()
|
||||
.map(|r| Fingerprint::X509Sha256(r.fingerprint))
|
||||
.collect(),
|
||||
set: RecipientSet(Arc::new(Recipients::Smime(recipients.into_boxed_slice()))),
|
||||
addresses,
|
||||
expires_at: Some(expires_at),
|
||||
capabilities,
|
||||
warnings,
|
||||
smime_capabilities,
|
||||
})
|
||||
}
|
||||
71
crates/crypto/src/x509/time.rs
Normal file
71
crates/crypto/src/x509/time.rs
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::der::{DerError, reader::Tlv, tag};
|
||||
|
||||
fn digits(bytes: &[u8]) -> Result<u32, DerError> {
|
||||
bytes.iter().try_fold(0u32, |acc, b| {
|
||||
if b.is_ascii_digit() {
|
||||
Ok(acc * 10 + u32::from(b - b'0'))
|
||||
} else {
|
||||
Err(DerError::InvalidValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn days_from_civil(year: i64, month: u32, day: u32) -> i64 {
|
||||
let y = if month <= 2 { year - 1 } else { year };
|
||||
let era = y.div_euclid(400);
|
||||
let yoe = y - era * 400;
|
||||
let m = i64::from(month);
|
||||
let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(day) - 1;
|
||||
let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
|
||||
era * 146_097 + doe - 719_468
|
||||
}
|
||||
|
||||
fn days_in_month(year: u32, month: u32) -> u32 {
|
||||
match month {
|
||||
2 if year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400)) => {
|
||||
29
|
||||
}
|
||||
2 => 28,
|
||||
4 | 6 | 9 | 11 => 30,
|
||||
_ => 31,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_time(tlv: Tlv<'_>) -> Result<u64, DerError> {
|
||||
let (year, rest) = match (tlv.tag, tlv.content) {
|
||||
(tag::UTC_TIME, [y0, y1, rest @ ..]) => {
|
||||
let yy = digits(&[*y0, *y1])?;
|
||||
(if yy >= 50 { 1900 + yy } else { 2000 + yy }, rest)
|
||||
}
|
||||
(tag::GENERALIZED_TIME, [y0, y1, y2, y3, rest @ ..]) => {
|
||||
(digits(&[*y0, *y1, *y2, *y3])?, rest)
|
||||
}
|
||||
_ => return Err(DerError::UnexpectedTag),
|
||||
};
|
||||
let [m0, m1, d0, d1, h0, h1, mi0, mi1, s0, s1, b'Z'] = rest else {
|
||||
return Err(DerError::InvalidValue);
|
||||
};
|
||||
let month = digits(&[*m0, *m1])?;
|
||||
let day = digits(&[*d0, *d1])?;
|
||||
let hour = digits(&[*h0, *h1])?;
|
||||
let minute = digits(&[*mi0, *mi1])?;
|
||||
let second = digits(&[*s0, *s1])?;
|
||||
if !(1..=12).contains(&month)
|
||||
|| day == 0
|
||||
|| day > days_in_month(year, month)
|
||||
|| hour > 23
|
||||
|| minute > 59
|
||||
|| second > 59
|
||||
{
|
||||
return Err(DerError::InvalidValue);
|
||||
}
|
||||
let days = days_from_civil(i64::from(year), month, day);
|
||||
let secs = days * 86_400 + i64::from(hour * 3600 + minute * 60 + second);
|
||||
u64::try_from(secs).map_err(|_| DerError::InvalidValue)
|
||||
}
|
||||
179
crates/crypto/src/x509/trust.rs
Normal file
179
crates/crypto/src/x509/trust.rs
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use crate::{
|
||||
error::ChainError,
|
||||
x509::{
|
||||
cert::Certificate,
|
||||
recipient::{certificates, decode_certificates},
|
||||
},
|
||||
};
|
||||
|
||||
static EMBEDDED: &[u8] = include_bytes!("../../resources/email-anchors.bin");
|
||||
const MAGIC: &[u8; 4] = b"SWTA";
|
||||
const MAX_CUSTOM_ANCHORS: usize = 256;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Anchor<'x> {
|
||||
pub cert: Certificate<'x>,
|
||||
pub distrust_after: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TrustAnchor {
|
||||
pub subject: String,
|
||||
pub expires_at: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct TrustAnchors {
|
||||
embedded: bool,
|
||||
custom: Vec<Box<[u8]>>,
|
||||
}
|
||||
|
||||
fn be_u32(data: &[u8]) -> Option<usize> {
|
||||
data.first_chunk::<4>()
|
||||
.map(|bytes| u32::from_be_bytes(*bytes) as usize)
|
||||
}
|
||||
|
||||
pub(crate) fn embedded_count() -> usize {
|
||||
EMBEDDED
|
||||
.strip_prefix(MAGIC)
|
||||
.and_then(be_u32)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn embedded_record(index: usize) -> Option<(u64, &'static [u8])> {
|
||||
let table = EMBEDDED.get(MAGIC.len() + 4..)?;
|
||||
let offset = be_u32(table.get(index.checked_mul(4)?..)?)?;
|
||||
let record = EMBEDDED.get(offset..)?;
|
||||
let (distrust, rest) = record.split_first_chunk::<8>()?;
|
||||
let (len, rest) = rest.split_first_chunk::<4>()?;
|
||||
let der = rest.get(..u32::from_be_bytes(*len) as usize)?;
|
||||
Some((u64::from_be_bytes(*distrust), der))
|
||||
}
|
||||
|
||||
pub(crate) fn embedded_anchor(index: usize) -> Option<Anchor<'static>> {
|
||||
let (distrust, der) = embedded_record(index)?;
|
||||
Some(Anchor {
|
||||
cert: Certificate::parse(der).ok()?,
|
||||
distrust_after: (distrust != 0).then_some(distrust),
|
||||
})
|
||||
}
|
||||
|
||||
impl<'x> Anchor<'x> {
|
||||
fn shorten<'s>(self) -> Anchor<'s>
|
||||
where
|
||||
'x: 's,
|
||||
{
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl TrustAnchors {
|
||||
pub fn embedded() -> Self {
|
||||
TrustAnchors {
|
||||
embedded: true,
|
||||
custom: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn empty() -> Self {
|
||||
TrustAnchors::default()
|
||||
}
|
||||
|
||||
pub fn add(&mut self, input: &[u8]) -> Result<usize, ChainError> {
|
||||
let der = decode_certificates(input).map_err(|_| ChainError::MalformedCertificate)?;
|
||||
let mut added = 0;
|
||||
for cert in certificates(&der) {
|
||||
let cert = cert.map_err(|_| ChainError::MalformedCertificate)?;
|
||||
if self.custom.len() >= MAX_CUSTOM_ANCHORS {
|
||||
return Err(ChainError::TooManyAnchors);
|
||||
}
|
||||
if !self.custom.iter().any(|known| known.as_ref() == cert.raw) {
|
||||
self.custom.push(cert.raw.into());
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
Ok(added)
|
||||
}
|
||||
|
||||
pub fn inspect(input: &[u8]) -> Result<TrustAnchor, ChainError> {
|
||||
let der = decode_certificates(input).map_err(|_| ChainError::MalformedCertificate)?;
|
||||
let mut certs = certificates(&der);
|
||||
let cert = certs
|
||||
.next()
|
||||
.ok_or(ChainError::MalformedCertificate)?
|
||||
.map_err(|_| ChainError::MalformedCertificate)?;
|
||||
if certs.next().is_some() || !cert.is_ca() {
|
||||
return Err(ChainError::MalformedCertificate);
|
||||
}
|
||||
Ok(TrustAnchor {
|
||||
subject: cert.display_name(),
|
||||
expires_at: cert.not_after,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.custom.len() + if self.embedded { embedded_count() } else { 0 }
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.len() == 0
|
||||
}
|
||||
|
||||
pub(crate) fn find<'s>(&'s self, subject: &'s [u8]) -> impl Iterator<Item = Anchor<'s>> + 's {
|
||||
let custom = self
|
||||
.custom
|
||||
.iter()
|
||||
.filter_map(|der| Certificate::parse(der).ok())
|
||||
.filter(move |cert| cert.subject == subject)
|
||||
.map(|cert| Anchor {
|
||||
cert,
|
||||
distrust_after: None,
|
||||
});
|
||||
let embedded = if self.embedded {
|
||||
embedded_range(subject)
|
||||
} else {
|
||||
0..0
|
||||
};
|
||||
custom.chain(
|
||||
embedded
|
||||
.filter_map(|index| embedded_anchor(index).map(Anchor::shorten))
|
||||
.filter(move |anchor| anchor.cert.subject == subject),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn contains(&self, cert: &Certificate<'_>) -> bool {
|
||||
self.find(cert.subject)
|
||||
.any(|anchor| anchor.cert.raw == cert.raw)
|
||||
}
|
||||
}
|
||||
|
||||
fn embedded_subject(index: usize) -> &'static [u8] {
|
||||
embedded_record(index)
|
||||
.and_then(|(_, der)| Certificate::parse(der).ok())
|
||||
.map(|cert| cert.subject)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn lower_bound(count: usize, before: impl Fn(&[u8]) -> bool) -> usize {
|
||||
let (mut low, mut high) = (0, count);
|
||||
while low < high {
|
||||
let mid = low + (high - low) / 2;
|
||||
if before(embedded_subject(mid)) {
|
||||
low = mid + 1;
|
||||
} else {
|
||||
high = mid;
|
||||
}
|
||||
}
|
||||
low
|
||||
}
|
||||
|
||||
fn embedded_range(subject: &[u8]) -> std::ops::Range<usize> {
|
||||
let count = embedded_count();
|
||||
lower_bound(count, |s| s < subject)..lower_bound(count, |s| s <= subject)
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "dav-proto"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "dav"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "directory"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
|
|||
|
|
@ -67,7 +67,11 @@ impl OpenIdDirectory {
|
|||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
let outbound_policy = OutboundPolicy::for_tenant(config.member_tenant_id);
|
||||
let outbound_policy = if config.trusted_provider {
|
||||
OutboundPolicy::Trusted
|
||||
} else {
|
||||
OutboundPolicy::for_tenant(config.member_tenant_id)
|
||||
};
|
||||
// SPDX-SnippetEnd
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
let outbound_policy = OutboundPolicy::Trusted;
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ use std::{
|
|||
time::{Duration, Instant},
|
||||
};
|
||||
use trc::AuthEvent;
|
||||
use utils::outbound::OutboundClient;
|
||||
use utils::{error_chain, outbound::OutboundClient};
|
||||
|
||||
const JWKS_DEFAULT_MAX_AGE: Duration = Duration::from_secs(3600);
|
||||
const JWKS_MIN_MAX_AGE: Duration = Duration::from_secs(300);
|
||||
|
|
@ -162,7 +162,7 @@ pub(crate) async fn fetch_jwks(
|
|||
.map_err(|err| OidcError::Config(format!("Invalid JWKS URL: {err}")))?
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| OidcError::Network(format!("JWKS fetch failed: {e}")))?
|
||||
.map_err(|e| OidcError::Network(format!("JWKS fetch failed: {}", error_chain(&e))))?
|
||||
.error_for_status()
|
||||
.map_err(|e| OidcError::Provider(format!("JWKS HTTP error: {e}")))?;
|
||||
let max_age = cache_max_age(response.headers());
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "email"
|
||||
version = "1.0.1"
|
||||
version = "1.0.2"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
|
|
@ -14,22 +14,13 @@ jmap-tools = { path = "../jmap-tools" }
|
|||
common = { path = "../common" }
|
||||
groupware = { path = "../groupware" }
|
||||
registry = { path = "../registry" }
|
||||
crypto = { path = "../crypto" }
|
||||
text-extract = { path = "../text-extract" }
|
||||
mail-parser = { version = "1.0", features = ["full_encoding"] }
|
||||
mail-builder = { version = "2.0" }
|
||||
encodify = "1.0"
|
||||
sieve-rs = { path = "../sieve" }
|
||||
tokio = { version = "1.54", features = ["net", "macros"] }
|
||||
aes = "0.9"
|
||||
aes-gcm = "0.11.1"
|
||||
chacha20poly1305 = "0.11"
|
||||
cbc = { version = "0.2", features = ["alloc"] }
|
||||
rasn = "0.29"
|
||||
rasn-cms = "0.29"
|
||||
rasn-pkix = "0.29"
|
||||
rsa = { version = "0.9.10", features = ["sha2"] }
|
||||
rand = "0.8"
|
||||
sequoia-openpgp = { version = "2.4", default-features = false, features = ["crypto-rust", "allow-experimental-crypto", "allow-variable-time-crypto"] }
|
||||
hashify = "0.3"
|
||||
rkyv.workspace = true
|
||||
compact_str = "0.10.0"
|
||||
|
|
@ -40,6 +31,7 @@ bytecount = "0.6"
|
|||
enterprise = ["utils/enterprise", "store/enterprise", "trc/enterprise", "jmap_proto/enterprise", "common/enterprise", "groupware/enterprise", "registry/enterprise"]
|
||||
|
||||
[dev-dependencies]
|
||||
encodify = "1.0"
|
||||
tokio = { version = "1.54", features = ["full"] }
|
||||
serde_json = "1.0"
|
||||
|
||||
|
|
|
|||
9
crates/email/src/cache/email.rs
vendored
9
crates/email/src/cache/email.rs
vendored
|
|
@ -23,6 +23,7 @@ use store::{
|
|||
use trc::AddContext;
|
||||
use types::{
|
||||
acl::Acl,
|
||||
id::Id,
|
||||
keyword::{DRAFT, Keyword, SEEN},
|
||||
metadata::MetadataKinds,
|
||||
};
|
||||
|
|
@ -406,6 +407,8 @@ impl MessageAccess {
|
|||
pub trait MessageCacheAccess {
|
||||
fn email_by_id(&self, id: &u32) -> Option<MessageRef<'_>>;
|
||||
|
||||
fn email_by_jmap_id(&self, id: Id) -> Option<MessageRef<'_>>;
|
||||
|
||||
fn has_email_id(&self, id: &u32) -> bool;
|
||||
|
||||
fn custom_keywords(&self, message: MessageRef<'_>) -> &[CompactString];
|
||||
|
|
@ -614,6 +617,12 @@ impl MessageCacheAccess for MessageStoreCache {
|
|||
self.emails.by_id(*id)
|
||||
}
|
||||
|
||||
fn email_by_jmap_id(&self, id: Id) -> Option<MessageRef<'_>> {
|
||||
self.emails
|
||||
.by_id(id.document_id())
|
||||
.filter(|message| message.thread_id() == id.prefix_id())
|
||||
}
|
||||
|
||||
fn has_email_id(&self, id: &u32) -> bool {
|
||||
self.emails.contains(*id)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -109,7 +109,7 @@ impl MailboxFnc for Server {
|
|||
if !create_paths.is_empty() {
|
||||
if create_paths
|
||||
.iter()
|
||||
.any(|name| name.len() > self.core.email.mailbox_name_max_len)
|
||||
.any(|name| self.core.email.is_mailbox_name_too_long(name))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,618 +0,0 @@
|
|||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use aes::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7};
|
||||
use aes_gcm::{
|
||||
Aes256Gcm,
|
||||
aead::{AeadInOut, KeyInit},
|
||||
};
|
||||
use chacha20poly1305::ChaCha20Poly1305;
|
||||
use common::auth::{
|
||||
ACCOUNT_FLAG_ENCRYPT_ALGO_AES256, ACCOUNT_FLAG_ENCRYPT_ALGO_AES256_GCM,
|
||||
ACCOUNT_FLAG_ENCRYPT_ALGO_CHACHA20_POLY1305, ACCOUNT_FLAG_ENCRYPT_APPEND,
|
||||
ACCOUNT_FLAG_ENCRYPT_METHOD_PGP, ACCOUNT_FLAG_ENCRYPT_TRAIN_SPAM_FILTER, EncryptionKeys,
|
||||
};
|
||||
use encodify::base64::MIME;
|
||||
use mail_builder::mime::make_boundary;
|
||||
use mail_parser::{Message, PartKind};
|
||||
use openpgp::{
|
||||
parse::Parse,
|
||||
serialize::stream,
|
||||
types::{KeyFlags, SymmetricAlgorithm},
|
||||
};
|
||||
use rand::{RngCore, SeedableRng, rngs::StdRng};
|
||||
use rasn::Encoder;
|
||||
use rasn::types::{OctetString, Oid, SetOf};
|
||||
use rasn_cms::{
|
||||
AlgorithmIdentifier, AuthEnvelopedData, CONTENT_DATA, CONTENT_ENVELOPED_DATA, EncryptedContent,
|
||||
EncryptedContentInfo, EncryptedKey, EnvelopedData, IssuerAndSerialNumber,
|
||||
KeyTransRecipientInfo, RecipientIdentifier, RecipientInfo,
|
||||
algorithms::{AES128_CBC, AES256_CBC, RSA},
|
||||
pkcs7_compat::EncapsulatedContentInfo,
|
||||
};
|
||||
use rsa::{Oaep, Pkcs1v15Encrypt, RsaPublicKey, pkcs1::DecodeRsaPublicKey, sha2::Sha256};
|
||||
use sequoia_openpgp as openpgp;
|
||||
use std::{fmt::Display, io::Cursor};
|
||||
|
||||
const AES256_GCM: &Oid =
|
||||
Oid::JOINT_ISO_ITU_T_COUNTRY_US_ORGANIZATION_GOV_CSOR_NIST_ALGORITHMS_AES256_GCM;
|
||||
const CHACHA20_POLY1305: &Oid = Oid::const_new(&[1, 2, 840, 113549, 1, 9, 16, 3, 18]);
|
||||
const CONTENT_AUTH_ENVELOPED_DATA: &Oid =
|
||||
Oid::ISO_MEMBER_BODY_US_RSADSI_PKCS9_SMIME_CT_AUTH_ENVELOPED_DATA;
|
||||
const SHA256: &Oid =
|
||||
Oid::JOINT_ISO_ITU_T_COUNTRY_US_ORGANIZATION_GOV_CSOR_NIST_ALGORITHMS_HASH_SHA256;
|
||||
const MGF1: &Oid = Oid::ISO_MEMBER_BODY_US_RSADSI_PKCS1_MGF1;
|
||||
const RSAES_OAEP: &Oid = Oid::ISO_MEMBER_BODY_US_RSADSI_PKCS1_RSAES_OAEP;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum EncryptMessageError {
|
||||
AlreadyEncrypted,
|
||||
Error(String),
|
||||
}
|
||||
|
||||
#[allow(async_fn_in_trait)]
|
||||
pub trait EncryptMessage {
|
||||
async fn encrypt(
|
||||
&self,
|
||||
keys: &EncryptionKeys,
|
||||
flags: u64,
|
||||
) -> Result<Vec<u8>, EncryptMessageError>;
|
||||
fn is_encrypted(&self) -> bool;
|
||||
fn split_mime_headers(&self) -> (Vec<u8>, Vec<u8>);
|
||||
}
|
||||
|
||||
impl EncryptMessage for Message<'_> {
|
||||
async fn encrypt(
|
||||
&self,
|
||||
keys: &EncryptionKeys,
|
||||
flags: u64,
|
||||
) -> Result<Vec<u8>, EncryptMessageError> {
|
||||
if flags & ACCOUNT_FLAG_ENCRYPT_METHOD_PGP != 0 && flags.cipher().is_aead() {
|
||||
return Err(EncryptMessageError::Error(
|
||||
"AES-256-GCM and ChaCha20-Poly1305 are only supported for S/MIME encryption."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
|
||||
let (mut outer_message, inner_message) = self.split_mime_headers();
|
||||
|
||||
// Encrypt inner message
|
||||
if flags & ACCOUNT_FLAG_ENCRYPT_METHOD_PGP != 0 {
|
||||
// Prepare encrypted message
|
||||
let boundary = make_boundary("_");
|
||||
outer_message.extend_from_slice(
|
||||
concat!(
|
||||
"Content-Type: multipart/encrypted;\r\n\t",
|
||||
"protocol=\"application/pgp-encrypted\";\r\n\t",
|
||||
"boundary=\""
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
outer_message.extend_from_slice(boundary.as_bytes());
|
||||
outer_message.extend_from_slice(
|
||||
concat!(
|
||||
"\"\r\n\r\n",
|
||||
"OpenPGP/MIME message (Automatically encrypted by Stalwart)\r\n\r\n",
|
||||
"--"
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
outer_message.extend_from_slice(boundary.as_bytes());
|
||||
outer_message.extend_from_slice(
|
||||
concat!(
|
||||
"\r\nContent-Type: application/pgp-encrypted\r\n\r\n",
|
||||
"Version: 1\r\n\r\n--"
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
outer_message.extend_from_slice(boundary.as_bytes());
|
||||
outer_message.extend_from_slice(
|
||||
concat!(
|
||||
"\r\nContent-Type: application/octet-stream; name=\"encrypted.asc\"\r\n",
|
||||
"Content-Disposition: inline; filename=\"encrypted.asc\"\r\n\r\n"
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
|
||||
let certs = keys
|
||||
.iter()
|
||||
.map(openpgp::Cert::from_bytes)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!(
|
||||
"Failed to parse OpenPGP public key: {}",
|
||||
err
|
||||
))
|
||||
})?;
|
||||
|
||||
// Encrypt contents (TODO: use rayon)
|
||||
let encrypted_contents = tokio::task::spawn_blocking(move || {
|
||||
// Parse public key
|
||||
let mut keys = Vec::with_capacity(certs.len());
|
||||
let policy = openpgp::policy::StandardPolicy::new();
|
||||
|
||||
for cert in &certs {
|
||||
for key in cert
|
||||
.keys()
|
||||
.with_policy(&policy, None)
|
||||
.supported()
|
||||
.alive()
|
||||
.revoked(false)
|
||||
.key_flags(KeyFlags::empty().set_transport_encryption())
|
||||
{
|
||||
keys.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Compose a writer stack corresponding to the output format and
|
||||
// packet structure we want.
|
||||
let mut sink = Vec::with_capacity(inner_message.len());
|
||||
|
||||
// Stream an OpenPGP message.
|
||||
let message = stream::Armorer::new(stream::Message::new(&mut sink))
|
||||
.build()
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to create armorer: {}", err))
|
||||
})?;
|
||||
let message = stream::Encryptor::for_recipients(message, keys)
|
||||
.symmetric_algo(flags.algo())
|
||||
.build()
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to build encryptor: {}", err))
|
||||
})?;
|
||||
let mut message = stream::LiteralWriter::new(message).build().map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to create literal writer: {}", err))
|
||||
})?;
|
||||
std::io::copy(&mut Cursor::new(inner_message), &mut message).map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to encrypt message: {}", err))
|
||||
})?;
|
||||
message.finalize().map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to finalize message: {}", err))
|
||||
})?;
|
||||
|
||||
String::from_utf8(sink).map_err(|err| {
|
||||
EncryptMessageError::Error(format!(
|
||||
"Failed to convert encrypted message to UTF-8: {}",
|
||||
err
|
||||
))
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to encrypt message: {}", err))
|
||||
})??;
|
||||
outer_message.extend_from_slice(encrypted_contents.as_bytes());
|
||||
outer_message.extend_from_slice(b"\r\n--");
|
||||
outer_message.extend_from_slice(boundary.as_bytes());
|
||||
outer_message.extend_from_slice(b"--\r\n");
|
||||
} else {
|
||||
let cipher = flags.cipher();
|
||||
|
||||
// Generate random nonce
|
||||
let mut rng = StdRng::from_entropy();
|
||||
let mut nonce = vec![0u8; cipher.nonce_size()];
|
||||
rng.fill_bytes(&mut nonce);
|
||||
|
||||
// Generate random key
|
||||
let mut key = vec![0u8; cipher.key_size()];
|
||||
rng.fill_bytes(&mut key);
|
||||
|
||||
// Encrypt contents (TODO: use rayon)
|
||||
let (encrypted_contents, mac, key, nonce) = tokio::task::spawn_blocking(move || {
|
||||
cipher
|
||||
.encrypt(&key, &nonce, &inner_message)
|
||||
.map(|(encrypted_contents, mac)| (encrypted_contents, mac, key, nonce))
|
||||
})
|
||||
.await
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to encrypt message: {}", err))
|
||||
})??;
|
||||
|
||||
// Encrypt key using public keys
|
||||
let key_encryption_algorithm = cipher.key_encryption_algorithm()?;
|
||||
let mut recipient_infos = SetOf::new();
|
||||
for cert in keys.iter() {
|
||||
let cert = rasn::der::decode::<rasn_pkix::Certificate>(cert).map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to parse certificate: {}", err))
|
||||
})?;
|
||||
|
||||
let public_key = RsaPublicKey::from_pkcs1_der(
|
||||
cert.tbs_certificate
|
||||
.subject_public_key_info
|
||||
.subject_public_key
|
||||
.as_raw_slice(),
|
||||
)
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to parse public key: {}", err))
|
||||
})?;
|
||||
let encrypted_key = if cipher.is_aead() {
|
||||
public_key.encrypt(&mut rng, Oaep::new::<Sha256>(), &key[..])
|
||||
} else {
|
||||
public_key.encrypt(&mut rng, Pkcs1v15Encrypt, &key[..])
|
||||
}
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to encrypt key: {}", err))
|
||||
})?;
|
||||
|
||||
recipient_infos.insert(RecipientInfo::KeyTransRecipientInfo(
|
||||
KeyTransRecipientInfo {
|
||||
version: 0.into(),
|
||||
rid: RecipientIdentifier::IssuerAndSerialNumber(IssuerAndSerialNumber {
|
||||
issuer: cert.tbs_certificate.issuer,
|
||||
serial_number: cert.tbs_certificate.serial_number,
|
||||
}),
|
||||
key_encryption_algorithm: key_encryption_algorithm.clone(),
|
||||
encrypted_key: EncryptedKey::from(encrypted_key),
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
let encrypted_content_info = EncryptedContentInfo {
|
||||
content_type: CONTENT_DATA.into(),
|
||||
content_encryption_algorithm: cipher.content_encryption_algorithm(&nonce)?,
|
||||
encrypted_content: Some(EncryptedContent::from(encrypted_contents)),
|
||||
};
|
||||
|
||||
let (content_type, content) = if let Some(mac) = mac {
|
||||
(
|
||||
CONTENT_AUTH_ENVELOPED_DATA,
|
||||
rasn::der::encode(&AuthEnvelopedData {
|
||||
version: 0.into(),
|
||||
originator_info: None,
|
||||
recipient_infos,
|
||||
auth_encrypted_content_info: encrypted_content_info,
|
||||
auth_attrs: None,
|
||||
mac: OctetString::from(mac),
|
||||
unauth_attrs: None,
|
||||
})
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!(
|
||||
"Failed to encode AuthEnvelopedData: {}",
|
||||
err
|
||||
))
|
||||
})?,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
CONTENT_ENVELOPED_DATA,
|
||||
rasn::der::encode(&EnvelopedData {
|
||||
version: 0.into(),
|
||||
originator_info: None,
|
||||
recipient_infos,
|
||||
encrypted_content_info,
|
||||
unprotected_attrs: None,
|
||||
})
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!(
|
||||
"Failed to encode EnvelopedData: {}",
|
||||
err
|
||||
))
|
||||
})?,
|
||||
)
|
||||
};
|
||||
|
||||
let pkcs7 = rasn::der::encode(&EncapsulatedContentInfo {
|
||||
content_type: content_type.into(),
|
||||
content: Some(content.into()),
|
||||
})
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to encode ContentInfo: {}", err))
|
||||
})?;
|
||||
|
||||
// Generate message
|
||||
outer_message.extend_from_slice(b"Content-Type: application/pkcs7-mime;\r\n");
|
||||
outer_message.extend_from_slice(b"\tname=\"smime.p7m\";\r\n\tsmime-type=");
|
||||
outer_message.extend_from_slice(if cipher.is_aead() {
|
||||
b"authenticated-enveloped-data\r\n"
|
||||
} else {
|
||||
b"enveloped-data\r\n"
|
||||
});
|
||||
outer_message.extend_from_slice(
|
||||
concat!(
|
||||
"Content-Disposition: attachment;\r\n",
|
||||
"\tfilename=\"smime.p7m\"\r\n",
|
||||
"Content-Transfer-Encoding: base64\r\n\r\n"
|
||||
)
|
||||
.as_bytes(),
|
||||
);
|
||||
MIME.encode_append(&pkcs7, &mut outer_message);
|
||||
}
|
||||
|
||||
Ok(outer_message)
|
||||
}
|
||||
|
||||
fn split_mime_headers(&self) -> (Vec<u8>, Vec<u8>) {
|
||||
let root = self.root_part();
|
||||
let raw_message = self.raw();
|
||||
let mut outer_message = Vec::with_capacity((raw_message.len() as f64 * 1.5) as usize);
|
||||
let mut inner_message = Vec::with_capacity(raw_message.len());
|
||||
for header in root.headers() {
|
||||
let target = if header.name().is_mime_header() {
|
||||
&mut inner_message
|
||||
} else {
|
||||
&mut outer_message
|
||||
};
|
||||
let field = raw_message
|
||||
.get(header.offset_field() as usize..header.offset_end() as usize)
|
||||
.unwrap_or_default();
|
||||
target.extend_from_slice(field);
|
||||
if !field.ends_with(b"\n") {
|
||||
target.extend_from_slice(b"\r\n");
|
||||
}
|
||||
}
|
||||
inner_message.extend_from_slice(b"\r\n");
|
||||
inner_message.extend_from_slice(
|
||||
raw_message
|
||||
.get(root.offset_body() as usize..)
|
||||
.unwrap_or_default(),
|
||||
);
|
||||
(outer_message, inner_message)
|
||||
}
|
||||
|
||||
fn is_encrypted(&self) -> bool {
|
||||
if self.content_type().is_some_and(|ct| {
|
||||
let main_type = ct.ctype();
|
||||
let sub_type = ct.subtype().unwrap_or_default();
|
||||
|
||||
(main_type.eq_ignore_ascii_case("application")
|
||||
&& (sub_type.eq_ignore_ascii_case("pkcs7-mime")
|
||||
|| sub_type.eq_ignore_ascii_case("pkcs7-signature")
|
||||
|| (sub_type.eq_ignore_ascii_case("octet-stream")
|
||||
&& self.attachment_name().is_some_and(|name| {
|
||||
name.rsplit_once('.')
|
||||
.is_some_and(|(_, ext)| ["p7m", "p7s", "p7c", "p7z"].contains(&ext))
|
||||
}))))
|
||||
|| (main_type.eq_ignore_ascii_case("multipart")
|
||||
&& sub_type.eq_ignore_ascii_case("encrypted"))
|
||||
}) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let root = self.root();
|
||||
let num_parts = root.parts().count();
|
||||
if num_parts <= 2 {
|
||||
let mut text_part = None;
|
||||
let mut is_multipart = false;
|
||||
|
||||
for part in root.parts() {
|
||||
match part.kind() {
|
||||
PartKind::Text => {
|
||||
text_part = part.text();
|
||||
}
|
||||
PartKind::Multipart => {
|
||||
is_multipart = true;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
match text_part {
|
||||
Some(text)
|
||||
if (num_parts == 1 || is_multipart)
|
||||
&& text.trim_start().starts_with("-----BEGIN PGP MESSAGE-----") =>
|
||||
{
|
||||
return true;
|
||||
}
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub trait EncryptionFlags {
|
||||
fn cipher(&self) -> SymmetricCipher;
|
||||
fn can_train_spam_filter(&self) -> bool;
|
||||
fn encrypt_on_append(&self) -> bool;
|
||||
fn algo(&self) -> SymmetricAlgorithm;
|
||||
}
|
||||
|
||||
impl EncryptionFlags for u64 {
|
||||
fn cipher(&self) -> SymmetricCipher {
|
||||
if *self & ACCOUNT_FLAG_ENCRYPT_ALGO_AES256_GCM != 0 {
|
||||
SymmetricCipher::Aes256Gcm
|
||||
} else if *self & ACCOUNT_FLAG_ENCRYPT_ALGO_CHACHA20_POLY1305 != 0 {
|
||||
SymmetricCipher::ChaCha20Poly1305
|
||||
} else if *self & ACCOUNT_FLAG_ENCRYPT_ALGO_AES256 != 0 {
|
||||
SymmetricCipher::Aes256Cbc
|
||||
} else {
|
||||
SymmetricCipher::Aes128Cbc
|
||||
}
|
||||
}
|
||||
|
||||
fn can_train_spam_filter(&self) -> bool {
|
||||
*self & ACCOUNT_FLAG_ENCRYPT_TRAIN_SPAM_FILTER != 0
|
||||
}
|
||||
|
||||
fn encrypt_on_append(&self) -> bool {
|
||||
*self & ACCOUNT_FLAG_ENCRYPT_APPEND != 0
|
||||
}
|
||||
|
||||
fn algo(&self) -> SymmetricAlgorithm {
|
||||
if *self & ACCOUNT_FLAG_ENCRYPT_ALGO_AES256 != 0 {
|
||||
SymmetricAlgorithm::AES256
|
||||
} else {
|
||||
SymmetricAlgorithm::AES128
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cold]
|
||||
fn encrypt_error(algorithm: &str, err: impl Display) -> EncryptMessageError {
|
||||
EncryptMessageError::Error(format!("{algorithm} encryption failed: {err}"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SymmetricCipher {
|
||||
Aes128Cbc,
|
||||
Aes256Cbc,
|
||||
Aes256Gcm,
|
||||
ChaCha20Poly1305,
|
||||
}
|
||||
|
||||
impl SymmetricCipher {
|
||||
fn key_size(self) -> usize {
|
||||
match self {
|
||||
SymmetricCipher::Aes128Cbc => 16,
|
||||
SymmetricCipher::Aes256Cbc
|
||||
| SymmetricCipher::Aes256Gcm
|
||||
| SymmetricCipher::ChaCha20Poly1305 => 32,
|
||||
}
|
||||
}
|
||||
|
||||
fn nonce_size(self) -> usize {
|
||||
match self {
|
||||
SymmetricCipher::Aes128Cbc | SymmetricCipher::Aes256Cbc => 16,
|
||||
SymmetricCipher::Aes256Gcm | SymmetricCipher::ChaCha20Poly1305 => 12,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_aead(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
SymmetricCipher::Aes256Gcm | SymmetricCipher::ChaCha20Poly1305
|
||||
)
|
||||
}
|
||||
|
||||
fn encrypt(
|
||||
self,
|
||||
key: &[u8],
|
||||
nonce: &[u8],
|
||||
contents: &[u8],
|
||||
) -> Result<(Vec<u8>, Option<Vec<u8>>), EncryptMessageError> {
|
||||
match self {
|
||||
SymmetricCipher::Aes128Cbc => {
|
||||
cbc::Encryptor::<aes::Aes128>::new_from_slices(key, nonce)
|
||||
.map(|cipher| (cipher.encrypt_padded_vec::<Pkcs7>(contents), None))
|
||||
.map_err(|err| encrypt_error("AES-128-CBC", err))
|
||||
}
|
||||
SymmetricCipher::Aes256Cbc => {
|
||||
cbc::Encryptor::<aes::Aes256>::new_from_slices(key, nonce)
|
||||
.map(|cipher| (cipher.encrypt_padded_vec::<Pkcs7>(contents), None))
|
||||
.map_err(|err| encrypt_error("AES-256-CBC", err))
|
||||
}
|
||||
SymmetricCipher::Aes256Gcm => {
|
||||
let cipher = Aes256Gcm::new_from_slice(key)
|
||||
.map_err(|err| encrypt_error("AES-256-GCM", err))?;
|
||||
let nonce = nonce
|
||||
.try_into()
|
||||
.map_err(|err| encrypt_error("AES-256-GCM", err))?;
|
||||
let mut buffer = contents.to_vec();
|
||||
let tag = cipher
|
||||
.encrypt_inout_detached(nonce, b"", buffer.as_mut_slice().into())
|
||||
.map_err(|err| encrypt_error("AES-256-GCM", err))?;
|
||||
Ok((buffer, Some(tag.to_vec())))
|
||||
}
|
||||
SymmetricCipher::ChaCha20Poly1305 => {
|
||||
let cipher = ChaCha20Poly1305::new_from_slice(key)
|
||||
.map_err(|err| encrypt_error("ChaCha20-Poly1305", err))?;
|
||||
let nonce = nonce
|
||||
.try_into()
|
||||
.map_err(|err| encrypt_error("ChaCha20-Poly1305", err))?;
|
||||
let mut buffer = contents.to_vec();
|
||||
let tag = cipher
|
||||
.encrypt_inout_detached(nonce, b"", buffer.as_mut_slice().into())
|
||||
.map_err(|err| encrypt_error("ChaCha20-Poly1305", err))?;
|
||||
Ok((buffer, Some(tag.to_vec())))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn content_encryption_algorithm(
|
||||
self,
|
||||
nonce: &[u8],
|
||||
) -> Result<AlgorithmIdentifier, EncryptMessageError> {
|
||||
let (algorithm, parameters) = match self {
|
||||
SymmetricCipher::Aes128Cbc => (AES128_CBC, encode_octet_string(nonce)?),
|
||||
SymmetricCipher::Aes256Cbc => (AES256_CBC, encode_octet_string(nonce)?),
|
||||
SymmetricCipher::ChaCha20Poly1305 => (CHACHA20_POLY1305, encode_octet_string(nonce)?),
|
||||
SymmetricCipher::Aes256Gcm => (
|
||||
AES256_GCM,
|
||||
rasn::der::encode(&GcmParameters {
|
||||
nonce: OctetString::from_slice(nonce),
|
||||
icv_len: 16,
|
||||
})
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to encode GCM parameters: {}", err))
|
||||
})?,
|
||||
),
|
||||
};
|
||||
|
||||
Ok(AlgorithmIdentifier {
|
||||
algorithm: algorithm.into(),
|
||||
parameters: Some(parameters.into()),
|
||||
})
|
||||
}
|
||||
|
||||
fn key_encryption_algorithm(self) -> Result<AlgorithmIdentifier, EncryptMessageError> {
|
||||
if self.is_aead() {
|
||||
let sha256 = AlgorithmIdentifier {
|
||||
algorithm: SHA256.into(),
|
||||
parameters: Some(encode_null()?.into()),
|
||||
};
|
||||
let parameters = rasn::der::encode(&OaepParameters {
|
||||
hash_algorithm: sha256.clone(),
|
||||
mask_gen_algorithm: AlgorithmIdentifier {
|
||||
algorithm: MGF1.into(),
|
||||
parameters: Some(
|
||||
rasn::der::encode(&sha256)
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!(
|
||||
"Failed to encode MGF1 parameters: {}",
|
||||
err
|
||||
))
|
||||
})?
|
||||
.into(),
|
||||
),
|
||||
},
|
||||
})
|
||||
.map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to encode OAEP parameters: {}", err))
|
||||
})?;
|
||||
|
||||
Ok(AlgorithmIdentifier {
|
||||
algorithm: RSAES_OAEP.into(),
|
||||
parameters: Some(parameters.into()),
|
||||
})
|
||||
} else {
|
||||
Ok(AlgorithmIdentifier {
|
||||
algorithm: RSA.into(),
|
||||
parameters: Some(encode_null()?.into()),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(rasn::AsnType, rasn::Encode)]
|
||||
struct GcmParameters {
|
||||
nonce: OctetString,
|
||||
icv_len: u8,
|
||||
}
|
||||
|
||||
#[derive(rasn::AsnType, rasn::Encode)]
|
||||
struct OaepParameters {
|
||||
#[rasn(tag(explicit(0)))]
|
||||
hash_algorithm: AlgorithmIdentifier,
|
||||
#[rasn(tag(explicit(1)))]
|
||||
mask_gen_algorithm: AlgorithmIdentifier,
|
||||
}
|
||||
|
||||
fn encode_octet_string(value: &[u8]) -> Result<Vec<u8>, EncryptMessageError> {
|
||||
rasn::der::encode(&OctetString::from_slice(value))
|
||||
.map_err(|err| EncryptMessageError::Error(format!("Failed to encode nonce: {}", err)))
|
||||
}
|
||||
|
||||
fn encode_null() -> Result<Vec<u8>, EncryptMessageError> {
|
||||
rasn::der::encode(&()).map_err(|err| {
|
||||
EncryptMessageError::Error(format!("Failed to encode NULL parameters: {}", err))
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(all(test, stalwart_tests))]
|
||||
#[rustfmt::skip]
|
||||
#[path = "../../../../../stalwart-tests/unit/email/src/message/crypto/tests.rs"]
|
||||
mod tests;
|
||||
|
|
@ -9,6 +9,7 @@ use crate::{mailbox::INBOX_ID, sieve::ingest::SieveScriptIngest};
|
|||
use common::{
|
||||
Server,
|
||||
auth::BuildAccessToken,
|
||||
gateway::harvest::KeyHarvest,
|
||||
ipc::{EmailPush, PushNotification},
|
||||
};
|
||||
use mail_parser::MessageParser;
|
||||
|
|
@ -156,6 +157,14 @@ impl MailDelivery for Server {
|
|||
status: Vec::with_capacity(message.recipients.len()),
|
||||
autogenerated: Vec::new(),
|
||||
};
|
||||
let mut harvest_message = false;
|
||||
let mut parsed_message = (message.sender_authentication == SenderAuthentication::DmarcPass
|
||||
&& self.harvest_enabled())
|
||||
.then(|| MessageParser::new().parse(&raw_message))
|
||||
.flatten();
|
||||
let harvest = parsed_message
|
||||
.as_ref()
|
||||
.is_some_and(|parsed| self.harvest_candidate(parsed));
|
||||
|
||||
for rcpt in message.recipients {
|
||||
let account_id = match self.account_id_from_email(&rcpt.address, false).await {
|
||||
|
|
@ -196,14 +205,19 @@ impl MailDelivery for Server {
|
|||
.assert_has_permission(Permission::EmailReceive)
|
||||
}) {
|
||||
Ok(access_token) => {
|
||||
harvest_message |= harvest && !rcpt.is_spam();
|
||||
|
||||
// Check if there is an active sieve script
|
||||
match self.sieve_script_get_active(account_id).await {
|
||||
Ok(None) => {
|
||||
// Ingest message
|
||||
if parsed_message.is_none() {
|
||||
parsed_message = MessageParser::new().parse(&raw_message);
|
||||
}
|
||||
self.email_ingest(IngestEmail {
|
||||
raw_message: &raw_message,
|
||||
blob_hash: Some(&message.message_blob),
|
||||
message: MessageParser::new().parse(&raw_message),
|
||||
message: parsed_message.as_ref(),
|
||||
access_token: &access_token,
|
||||
mailbox_ids: vec![INBOX_ID],
|
||||
keywords: vec![],
|
||||
|
|
@ -313,6 +327,11 @@ impl MailDelivery for Server {
|
|||
result.status.push(status);
|
||||
}
|
||||
|
||||
drop(parsed_message);
|
||||
if harvest_message {
|
||||
self.spawn_harvest(raw_message, message.session_id);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,11 +4,9 @@
|
|||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
use super::crypto::{EncryptMessage, EncryptMessageError};
|
||||
use crate::{
|
||||
mailbox::{INBOX_ID, JUNK_ID, TRASH_ID},
|
||||
message::{
|
||||
crypto::EncryptionFlags,
|
||||
delivery::SenderAuthentication,
|
||||
index::IndexMessage,
|
||||
ingest_metadata::IngestMetadata,
|
||||
|
|
@ -18,10 +16,12 @@ use crate::{
|
|||
},
|
||||
};
|
||||
use common::{
|
||||
MAX_RECEIVED_AT, MessageUid, Server, auth::AccessToken,
|
||||
storage::metadata::PrivateMetadataCommit,
|
||||
MAX_RECEIVED_AT, MessageUid, Server,
|
||||
auth::AccessToken,
|
||||
storage::{encryption::EncryptFailure, metadata::PrivateMetadataCommit},
|
||||
};
|
||||
use compact_str::{CompactString, ToCompactString};
|
||||
use crypto::Protection;
|
||||
use groupware::{
|
||||
calendar::itip::{ItipIngest, ItipIngestError},
|
||||
scheduling::{ItipError, ItipMessages},
|
||||
|
|
@ -87,6 +87,7 @@ pub struct PendingEmail {
|
|||
thread_recheck: Option<PendingThread>,
|
||||
private_commit: PrivateMetadataCommit,
|
||||
event: MessageIngestEvent,
|
||||
encrypted: bool,
|
||||
mailbox_ids: Vec<u32>,
|
||||
message_id: Option<String>,
|
||||
session_id: u64,
|
||||
|
|
@ -96,7 +97,7 @@ pub struct PendingEmail {
|
|||
pub struct IngestEmail<'x> {
|
||||
pub raw_message: &'x [u8],
|
||||
pub blob_hash: Option<&'x BlobHash>,
|
||||
pub message: Option<Message<'x>>,
|
||||
pub message: Option<&'x Message<'x>>,
|
||||
pub access_token: &'x AccessToken,
|
||||
pub mailbox_ids: Vec<u32>,
|
||||
pub keywords: Vec<Keyword>,
|
||||
|
|
@ -181,13 +182,22 @@ pub struct SpamSample {
|
|||
from: String,
|
||||
subject: String,
|
||||
is_spam: bool,
|
||||
encrypted: bool,
|
||||
}
|
||||
|
||||
impl SpamSample {
|
||||
pub fn from_metadata(bytes: &[u8], is_spam: bool) -> trc::Result<Self> {
|
||||
let structure = MetadataStructure::deserialize(bytes)?;
|
||||
let metadata = structure.unarchive().caused_by(trc::location!())?;
|
||||
let envelope = metadata.root().envelope();
|
||||
let root = metadata.root();
|
||||
let envelope = root.envelope();
|
||||
let encrypted = root.root_part().content_type().is_some_and(|ct| {
|
||||
crypto::is_encrypted_media(
|
||||
ct.ctype(),
|
||||
ct.subtype().unwrap_or_default(),
|
||||
ct.attribute("smime-type"),
|
||||
)
|
||||
});
|
||||
Ok(SpamSample {
|
||||
hash: metadata.blob_hash(),
|
||||
size: metadata.blob_size() as u64,
|
||||
|
|
@ -199,6 +209,7 @@ impl SpamSample {
|
|||
.to_string(),
|
||||
subject: thread_name(envelope.subject().unwrap_or_default()).to_string(),
|
||||
is_spam,
|
||||
encrypted,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -317,14 +328,14 @@ impl EmailIngest for Server {
|
|||
|
||||
// Parse message
|
||||
let mut raw_message = Cow::from(params.raw_message);
|
||||
let mut message = params.message.take().ok_or_else(|| {
|
||||
let mut message = params.message.ok_or_else(|| {
|
||||
trc::EventType::MessageIngest(trc::MessageIngestEvent::Error)
|
||||
.ctx(trc::Key::Code, 550)
|
||||
.ctx(trc::Key::Reason, "Failed to parse e-mail message.")
|
||||
})?;
|
||||
|
||||
// Obtain message references and thread name
|
||||
let fields = ThreadFields::scan(&message);
|
||||
let fields = ThreadFields::scan(message);
|
||||
let mut thread_result = self
|
||||
.find_thread_id(account_id, fields.subject, &fields.message_ids)
|
||||
.await?;
|
||||
|
|
@ -606,26 +617,23 @@ impl EmailIngest for Server {
|
|||
_ => false,
|
||||
};
|
||||
|
||||
// Encrypt message
|
||||
let do_encrypt = match params.source {
|
||||
IngestSource::Jmap { .. } if params.keywords.contains(&Keyword::Draft) => false,
|
||||
IngestSource::Jmap { .. } | IngestSource::Imap { .. } => {
|
||||
self.core.email.encrypt
|
||||
&& self.core.email.encrypt_append
|
||||
&& account.flags.encrypt_on_append()
|
||||
}
|
||||
IngestSource::Smtp { .. } => self.core.email.encrypt,
|
||||
IngestSource::Restore => false,
|
||||
let encryption = match params.source {
|
||||
IngestSource::Jmap { .. } if params.keywords.contains(&Keyword::Draft) => None,
|
||||
IngestSource::Jmap { .. } | IngestSource::Imap { .. } => account
|
||||
.encryption()
|
||||
.filter(|e| self.core.email.encrypt && e.encrypt_on_append),
|
||||
IngestSource::Smtp { .. } => account.encryption().filter(|_| self.core.email.encrypt),
|
||||
IngestSource::Restore => None,
|
||||
};
|
||||
let is_encrypted = if do_encrypt
|
||||
&& !message.is_encrypted()
|
||||
&& let Some(encrypt_keys) = account.encryption_key()
|
||||
let encrypted_message;
|
||||
let is_encrypted = if let Some(encryption) = encryption
|
||||
&& crypto::protection(message) != Protection::Encrypted
|
||||
{
|
||||
match message.encrypt(encrypt_keys, account.flags).await {
|
||||
Ok(new_raw_message) => {
|
||||
raw_message = Cow::from(new_raw_message);
|
||||
match encryption.encrypt(message, now()) {
|
||||
Ok(encrypted) => {
|
||||
raw_message = Cow::from(encrypted.message);
|
||||
raw_message_len = raw_message.len() as u64;
|
||||
message = MessageParser::default()
|
||||
encrypted_message = MessageParser::default()
|
||||
.parse(raw_message.as_ref())
|
||||
.ok_or_else(|| {
|
||||
trc::EventType::MessageIngest(trc::MessageIngestEvent::Error)
|
||||
|
|
@ -635,23 +643,30 @@ impl EmailIngest for Server {
|
|||
"Failed to parse encrypted e-mail message.",
|
||||
)
|
||||
})?;
|
||||
message = &encrypted_message;
|
||||
|
||||
// Disable spam training if requested
|
||||
if !account.flags.can_train_spam_filter() {
|
||||
if !encryption.train_spam {
|
||||
train_spam = None;
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
Err(EncryptMessageError::Error(err)) => {
|
||||
Err(EncryptFailure::Skipped(reason)) => {
|
||||
trc::event!(
|
||||
Encryption(trc::EncryptionEvent::EncryptionSkipped),
|
||||
AccountId = account_id,
|
||||
Reason = reason.as_str(),
|
||||
);
|
||||
false
|
||||
}
|
||||
Err(EncryptFailure::Error(err)) => {
|
||||
trc::bail!(
|
||||
trc::StoreEvent::CryptoError
|
||||
.into_err()
|
||||
.caused_by(trc::location!())
|
||||
.reason(err)
|
||||
.ctx(trc::Key::Reason, err.as_str())
|
||||
);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
} else {
|
||||
false
|
||||
|
|
@ -672,6 +687,24 @@ impl EmailIngest for Server {
|
|||
.caused_by(trc::location!())?
|
||||
};
|
||||
|
||||
let sample_blob = if train_spam.is_some()
|
||||
&& is_encrypted
|
||||
&& params.blob_hash.is_none()
|
||||
&& self.core.spam.classifier.is_some()
|
||||
{
|
||||
self.hold_blob(
|
||||
account_id,
|
||||
BlobHash::generate(params.raw_message),
|
||||
params.raw_message,
|
||||
60,
|
||||
)
|
||||
.await
|
||||
.map(Some)
|
||||
.caused_by(trc::location!())?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Build write batch
|
||||
batch.with_account_id(account_id);
|
||||
self.limit_disk_quota(batch, &account);
|
||||
|
|
@ -737,8 +770,13 @@ impl EmailIngest for Server {
|
|||
self.add_spam_sample(
|
||||
account_id,
|
||||
batch,
|
||||
params.blob_hash.unwrap_or(&blob_hash).clone(),
|
||||
if params.blob_hash.is_some() {
|
||||
sample_blob
|
||||
.as_ref()
|
||||
.map(|(hash, _)| hash)
|
||||
.or(params.blob_hash)
|
||||
.unwrap_or(&blob_hash)
|
||||
.clone(),
|
||||
if sample_blob.is_some() || params.blob_hash.is_some() {
|
||||
params.raw_message.len()
|
||||
} else {
|
||||
raw_message.len()
|
||||
|
|
@ -768,12 +806,12 @@ impl EmailIngest for Server {
|
|||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
#[cfg(feature = "enterprise")]
|
||||
batch
|
||||
.index_message(tenant_id, &message, &extra_headers, blob_hash.clone(), data)
|
||||
.index_message(tenant_id, message, &extra_headers, blob_hash.clone(), data)
|
||||
.caused_by(trc::location!())?;
|
||||
// SPDX-SnippetEnd
|
||||
#[cfg(not(feature = "enterprise"))]
|
||||
batch
|
||||
.index_message(&message, &extra_headers, blob_hash.clone(), data)
|
||||
.index_message(message, &extra_headers, blob_hash.clone(), data)
|
||||
.caused_by(trc::location!())?;
|
||||
batch
|
||||
.set(
|
||||
|
|
@ -806,6 +844,9 @@ impl EmailIngest for Server {
|
|||
if let Some(blob_hold) = blob_hold {
|
||||
blob_hold.release(batch);
|
||||
}
|
||||
if let Some((_, sample_hold)) = sample_blob {
|
||||
sample_hold.release(batch);
|
||||
}
|
||||
|
||||
// Merge threads if necessary
|
||||
let thread_recheck = if !thread_result.merge_ids.is_empty() {
|
||||
|
|
@ -858,6 +899,7 @@ impl EmailIngest for Server {
|
|||
IngestSource::Jmap { .. } | IngestSource::Restore => MessageIngestEvent::JmapAppend,
|
||||
IngestSource::Imap { .. } => MessageIngestEvent::ImapAppend,
|
||||
},
|
||||
encrypted: is_encrypted,
|
||||
mailbox_ids: std::mem::take(&mut params.mailbox_ids),
|
||||
message_id,
|
||||
session_id: params.session_id,
|
||||
|
|
@ -880,6 +922,7 @@ impl EmailIngest for Server {
|
|||
thread_recheck,
|
||||
private_commit,
|
||||
event,
|
||||
encrypted,
|
||||
mailbox_ids,
|
||||
message_id,
|
||||
session_id,
|
||||
|
|
@ -911,6 +954,15 @@ impl EmailIngest for Server {
|
|||
Elapsed = start_time.elapsed(),
|
||||
);
|
||||
|
||||
if encrypted {
|
||||
trc::event!(
|
||||
Encryption(trc::EncryptionEvent::AtRestEncrypted),
|
||||
SpanId = session_id,
|
||||
AccountId = account_id,
|
||||
DocumentId = document_id,
|
||||
);
|
||||
}
|
||||
|
||||
IngestedEmail {
|
||||
document_id,
|
||||
thread_id,
|
||||
|
|
@ -1048,7 +1100,7 @@ impl EmailIngest for Server {
|
|||
prepared,
|
||||
} = samples;
|
||||
batch.with_account_id(account_id);
|
||||
for sample in prepared {
|
||||
for sample in prepared.into_iter().filter(|sample| !sample.encrypted) {
|
||||
self.add_spam_sample(
|
||||
account_id,
|
||||
batch,
|
||||
|
|
@ -1068,18 +1120,20 @@ impl EmailIngest for Server {
|
|||
|
||||
self.message_metadata(account_id, &documents, |document_id, bytes| {
|
||||
let sample = SpamSample::from_metadata(bytes, spam.contains(document_id))?;
|
||||
self.add_spam_sample(
|
||||
account_id,
|
||||
batch,
|
||||
sample.hash,
|
||||
sample.size,
|
||||
sample.from,
|
||||
sample.subject,
|
||||
sample.is_spam,
|
||||
true,
|
||||
span_id,
|
||||
);
|
||||
batch.commit_point();
|
||||
if !sample.encrypted {
|
||||
self.add_spam_sample(
|
||||
account_id,
|
||||
batch,
|
||||
sample.hash,
|
||||
sample.size,
|
||||
sample.from,
|
||||
sample.subject,
|
||||
sample.is_spam,
|
||||
true,
|
||||
span_id,
|
||||
);
|
||||
batch.commit_point();
|
||||
}
|
||||
Ok(true)
|
||||
})
|
||||
.await
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@
|
|||
|
||||
pub mod body;
|
||||
pub mod copy;
|
||||
pub mod crypto;
|
||||
pub mod delete;
|
||||
pub mod delivery;
|
||||
pub mod headers;
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue