1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-07-29 22:01:14 +03:00

Move the Encrypter from the config to the keystore

This commit is contained in:
Quentin Gliech
2022-08-31 18:42:23 +02:00
parent e1d50b818e
commit 8c25dc03ce
26 changed files with 157 additions and 137 deletions

View File

@ -29,11 +29,10 @@ tower = { version = "0.4.13", features = ["util"] }
tracing = "0.1.36"
url = "2.2.2"
# TODO: remove the config dependency by moving out the encrypter
mas-config = { path = "../config" }
mas-templates = { path = "../templates" }
mas-storage = { path = "../storage" }
mas-data-model = { path = "../data-model" }
mas-jose = { path = "../jose" }
mas-iana = { path = "../iana" }
mas-http = { path = "../http", features = ["client"] }
mas-iana = { path = "../iana" }
mas-jose = { path = "../jose" }
mas-keystore = { path = "../keystore" }
mas-storage = { path = "../storage" }
mas-templates = { path = "../templates" }

View File

@ -26,7 +26,7 @@ use axum::{
};
use headers::{authorization::Basic, Authorization};
use http::StatusCode;
use mas_config::Encrypter;
use mas_keystore::Encrypter;
use mas_data_model::{Client, JwksOrJwksUri, StorageBackend};
use mas_http::HttpServiceExt;
use mas_iana::oauth::OAuthClientAuthenticationMethod;

View File

@ -26,9 +26,6 @@ lettre = { version = "0.10.1", default-features = false, features = ["serde", "b
pem-rfc7468 = "0.6.0"
rand = "0.8.5"
chacha20poly1305 = { version = "0.10.1", features = ["std"] }
cookie = { version = "0.16.0", features = ["private", "key-expansion"] }
data-encoding = "2.3.2"
indoc = "1.0.7"

View File

@ -35,7 +35,7 @@ pub use self::{
http::HttpConfig,
matrix::MatrixConfig,
policy::PolicyConfig,
secrets::{Encrypter, SecretsConfig},
secrets::SecretsConfig,
telemetry::{
MetricsConfig, MetricsExporterConfig, Propagator, TelemetryConfig, TracingConfig,
TracingExporterConfig,

View File

@ -12,18 +12,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{borrow::Cow, path::PathBuf, sync::Arc};
use std::{borrow::Cow, path::PathBuf};
use anyhow::Context;
use async_trait::async_trait;
use chacha20poly1305::{
aead::{generic_array::GenericArray, Aead},
ChaCha20Poly1305, KeyInit,
};
use cookie::Key;
use data_encoding::BASE64;
use mas_jose::jwk::{JsonWebKey, JsonWebKeySet};
use mas_keystore::{Keystore, PrivateKey};
use mas_keystore::{Encrypter, Keystore, PrivateKey};
use rand::{
distributions::{Alphanumeric, DistString},
thread_rng,
@ -36,90 +30,6 @@ use tracing::info;
use super::ConfigurationSection;
/// Helps encrypting and decrypting data
#[derive(Clone)]
pub struct Encrypter {
cookie_key: Arc<Key>,
aead: Arc<ChaCha20Poly1305>,
}
// TODO: move this somewhere else
impl Encrypter {
/// Creates an [`Encrypter`] out of an encryption key
#[must_use]
pub fn new(key: &[u8; 32]) -> Self {
let cookie_key = Key::derive_from(&key[..]);
let cookie_key = Arc::new(cookie_key);
let key = GenericArray::from_slice(key);
let aead = ChaCha20Poly1305::new(key);
let aead = Arc::new(aead);
Self { cookie_key, aead }
}
/// Encrypt a payload
///
/// # Errors
///
/// Will return `Err` when the payload failed to encrypt
pub fn encrypt(&self, nonce: &[u8; 12], decrypted: &[u8]) -> anyhow::Result<Vec<u8>> {
let nonce = GenericArray::from_slice(&nonce[..]);
let encrypted = self.aead.encrypt(nonce, decrypted)?;
Ok(encrypted)
}
/// Decrypts a payload
///
/// # Errors
///
/// Will return `Err` when the payload failed to decrypt
pub fn decrypt(&self, nonce: &[u8; 12], encrypted: &[u8]) -> anyhow::Result<Vec<u8>> {
let nonce = GenericArray::from_slice(&nonce[..]);
let encrypted = self.aead.decrypt(nonce, encrypted)?;
Ok(encrypted)
}
/// Encrypt a payload to a self-contained base64-encoded string
///
/// # Errors
///
/// Will return `Err` when the payload failed to encrypt
pub fn encryt_to_string(&self, decrypted: &[u8]) -> anyhow::Result<String> {
let nonce = rand::random();
let encrypted = self.encrypt(&nonce, decrypted)?;
let encrypted = [&nonce[..], &encrypted].concat();
let encrypted = BASE64.encode(&encrypted);
Ok(encrypted)
}
/// Decrypt a payload from a self-contained base64-encoded string
///
/// # Errors
///
/// Will return `Err` when the payload failed to decrypt
pub fn decrypt_string(&self, encrypted: &str) -> anyhow::Result<Vec<u8>> {
let encrypted = BASE64.decode(encrypted.as_bytes())?;
let nonce: &[u8; 12] = encrypted
.get(0..12)
.ok_or_else(|| anyhow::anyhow!("invalid payload serialization"))?
.try_into()?;
let payload = encrypted
.get(12..)
.ok_or_else(|| anyhow::anyhow!("invalid payload serialization"))?;
let decrypted_client_secret = self.decrypt(nonce, payload)?;
Ok(decrypted_client_secret)
}
}
impl From<Encrypter> for Key {
fn from(e: Encrypter) -> Self {
e.cookie_key.as_ref().clone()
}
}
fn example_secret() -> &'static str {
"0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff"
}

View File

@ -26,8 +26,8 @@ use mas_axum_utils::{
csrf::{CsrfExt, ProtectedForm},
FancyError, SessionInfoExt,
};
use mas_config::Encrypter;
use mas_data_model::Device;
use mas_keystore::Encrypter;
use mas_router::{CompatLoginSsoAction, PostAuthAction, Route};
use mas_storage::compat::{fullfill_compat_sso_login, get_compat_sso_login_by_id};
use mas_templates::{CompatSsoContext, ErrorContext, TemplateContext, Templates};

View File

@ -30,10 +30,10 @@ use axum::{
};
use headers::HeaderName;
use hyper::header::{ACCEPT, ACCEPT_LANGUAGE, AUTHORIZATION, CONTENT_LANGUAGE, CONTENT_TYPE};
use mas_config::{Encrypter, MatrixConfig};
use mas_config::MatrixConfig;
use mas_email::Mailer;
use mas_http::CorsLayerExt;
use mas_keystore::Keystore;
use mas_keystore::{Encrypter, Keystore};
use mas_policy::PolicyFactory;
use mas_router::{Route, UrlBuilder};
use mas_templates::{ErrorContext, Templates};

View File

@ -23,8 +23,8 @@ use axum::{
use axum_extra::extract::PrivateCookieJar;
use hyper::StatusCode;
use mas_axum_utils::SessionInfoExt;
use mas_config::Encrypter;
use mas_data_model::{AuthorizationGrant, BrowserSession};
use mas_keystore::Encrypter;
use mas_policy::PolicyFactory;
use mas_router::{PostAuthAction, Route};
use mas_storage::{

View File

@ -22,9 +22,9 @@ use axum::{
use axum_extra::extract::PrivateCookieJar;
use hyper::StatusCode;
use mas_axum_utils::SessionInfoExt;
use mas_config::Encrypter;
use mas_data_model::{AuthorizationCode, Pkce};
use mas_iana::oauth::OAuthAuthorizationEndpointResponseType;
use mas_keystore::Encrypter;
use mas_policy::PolicyFactory;
use mas_router::{PostAuthAction, Route};
use mas_storage::oauth2::{

View File

@ -25,8 +25,8 @@ use mas_axum_utils::{
csrf::{CsrfExt, ProtectedForm},
SessionInfoExt,
};
use mas_config::Encrypter;
use mas_data_model::AuthorizationGrantStage;
use mas_keystore::Encrypter;
use mas_policy::PolicyFactory;
use mas_router::{PostAuthAction, Route};
use mas_storage::oauth2::{

View File

@ -15,9 +15,9 @@
use axum::{extract::Extension, response::IntoResponse, Json};
use hyper::StatusCode;
use mas_axum_utils::client_authorization::{ClientAuthorization, CredentialsVerificationError};
use mas_config::Encrypter;
use mas_data_model::{TokenFormatError, TokenType};
use mas_iana::oauth::{OAuthClientAuthenticationMethod, OAuthTokenTypeHint};
use mas_keystore::Encrypter;
use mas_storage::{
compat::{
lookup_active_compat_access_token, lookup_active_compat_refresh_token,

View File

@ -21,7 +21,6 @@ use data_encoding::BASE64URL_NOPAD;
use headers::{CacheControl, HeaderMap, HeaderMapExt, Pragma};
use hyper::StatusCode;
use mas_axum_utils::client_authorization::{ClientAuthorization, CredentialsVerificationError};
use mas_config::Encrypter;
use mas_data_model::{AuthorizationGrantStage, Client, TokenType};
use mas_iana::jose::JsonWebSignatureAlg;
use mas_jose::{
@ -29,7 +28,7 @@ use mas_jose::{
constraints::Constrainable,
jwt::{JsonWebSignatureHeader, Jwt, JwtSignatureError},
};
use mas_keystore::Keystore;
use mas_keystore::{Encrypter, Keystore};
use mas_router::UrlBuilder;
use mas_storage::{
oauth2::{

View File

@ -21,8 +21,8 @@ use mas_axum_utils::{
csrf::{CsrfExt, ProtectedForm},
FancyError, SessionInfoExt,
};
use mas_config::Encrypter;
use mas_email::Mailer;
use mas_keystore::Encrypter;
use mas_router::Route;
use mas_storage::user::add_user_email;
use mas_templates::{EmailAddContext, TemplateContext, Templates};

View File

@ -22,9 +22,9 @@ use mas_axum_utils::{
csrf::{CsrfExt, ProtectedForm},
FancyError, SessionInfoExt,
};
use mas_config::Encrypter;
use mas_data_model::{BrowserSession, User, UserEmail};
use mas_email::Mailer;
use mas_keystore::Encrypter;
use mas_router::Route;
use mas_storage::{
user::{

View File

@ -22,7 +22,7 @@ use mas_axum_utils::{
csrf::{CsrfExt, ProtectedForm},
FancyError, SessionInfoExt,
};
use mas_config::Encrypter;
use mas_keystore::Encrypter;
use mas_router::Route;
use mas_storage::user::{
consume_email_verification, lookup_user_email_by_id, lookup_user_email_verification_code,

View File

@ -21,7 +21,7 @@ use axum::{
};
use axum_extra::extract::PrivateCookieJar;
use mas_axum_utils::{csrf::CsrfExt, FancyError, SessionInfoExt};
use mas_config::Encrypter;
use mas_keystore::Encrypter;
use mas_router::Route;
use mas_storage::user::{count_active_sessions, get_user_emails};
use mas_templates::{AccountContext, TemplateContext, Templates};

View File

@ -22,8 +22,8 @@ use mas_axum_utils::{
csrf::{CsrfExt, ProtectedForm},
FancyError, SessionInfoExt,
};
use mas_config::Encrypter;
use mas_data_model::BrowserSession;
use mas_keystore::Encrypter;
use mas_router::Route;
use mas_storage::{
user::{authenticate_session, set_password},

View File

@ -18,7 +18,7 @@ use axum::{
};
use axum_extra::extract::PrivateCookieJar;
use mas_axum_utils::{csrf::CsrfExt, FancyError, SessionInfoExt};
use mas_config::Encrypter;
use mas_keystore::Encrypter;
use mas_router::UrlBuilder;
use mas_templates::{IndexContext, TemplateContext, Templates};
use sqlx::PgPool;

View File

@ -21,7 +21,7 @@ use mas_axum_utils::{
csrf::{CsrfExt, CsrfToken, ProtectedForm},
FancyError, SessionInfoExt,
};
use mas_config::Encrypter;
use mas_keystore::Encrypter;
use mas_router::Route;
use mas_storage::user::{login, LoginError};
use mas_templates::{

View File

@ -21,7 +21,7 @@ use mas_axum_utils::{
csrf::{CsrfExt, ProtectedForm},
FancyError, SessionInfoExt,
};
use mas_config::Encrypter;
use mas_keystore::Encrypter;
use mas_router::{PostAuthAction, Route};
use mas_storage::user::end_session;
use sqlx::PgPool;

View File

@ -21,7 +21,7 @@ use mas_axum_utils::{
csrf::{CsrfExt, ProtectedForm},
FancyError, SessionInfoExt,
};
use mas_config::Encrypter;
use mas_keystore::Encrypter;
use mas_router::Route;
use mas_storage::user::authenticate_session;
use mas_templates::{ReauthContext, TemplateContext, Templates};

View File

@ -27,8 +27,8 @@ use mas_axum_utils::{
csrf::{CsrfExt, CsrfToken, ProtectedForm},
FancyError, SessionInfoExt,
};
use mas_config::Encrypter;
use mas_email::Mailer;
use mas_keystore::Encrypter;
use mas_policy::PolicyFactory;
use mas_router::Route;
use mas_storage::user::{

View File

@ -7,21 +7,26 @@ license = "Apache-2.0"
[dependencies]
anyhow = "1.0.62"
aead = { version = "0.5.1", features = ["std"] }
const-oid = { version = "0.9.0", features = ["std"] }
cookie = { version = "0.16.0", features = ["key-expansion", "private"] }
der = { version = "0.6.0", features = ["std"] }
ecdsa = { version = "0.14.4", features = ["std"] }
elliptic-curve = { version = "0.12.3", features = ["std", "pem", "sec1"] }
k256 = { version = "0.11.1", features = ["std"] }
p256 = { version = "0.11.1", features = ["std"] }
p384 = { version = "0.11.1", features = ["std"] }
pem-rfc7468 = { version = "0.6.0", features = ["std"] }
pkcs1 = { version = "0.4.0", features = ["std"] }
spki = { version = "0.6.0", features = ["std"] }
ecdsa = { version = "0.14.4", features = ["std"] }
pkcs8 = { version = "0.9.0", features = ["std", "pkcs5", "encryption"] }
const-oid = { version = "0.9.0", features = ["std"] }
rand = "0.8.5"
rsa = { git = "https://github.com/RustCrypto/RSA.git", features = ["std", "pem"] }
sec1 = { version = "0.3.0", features = ["std"] }
spki = { version = "0.6.0", features = ["std"] }
thiserror = "1.0.32"
rand_core = "0.6.3"
generic-array = "0.14.6"
chacha20poly1305 = { version = "0.10.1", features = ["std"] }
base64ct = "1.5.2"
mas-iana = { path = "../iana" }
mas-jose = { path = "../jose" }

View File

@ -0,0 +1,104 @@
// Copyright 2022 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use aead::Aead;
use base64ct::{Base64, Encoding};
use chacha20poly1305::{ChaCha20Poly1305, KeyInit};
use cookie::Key;
use generic_array::GenericArray;
/// Helps encrypting and decrypting data
#[derive(Clone)]
pub struct Encrypter {
cookie_key: Arc<Key>,
aead: Arc<ChaCha20Poly1305>,
}
impl From<Encrypter> for Key {
fn from(e: Encrypter) -> Self {
e.cookie_key.as_ref().clone()
}
}
impl Encrypter {
/// Creates an [`Encrypter`] out of an encryption key
#[must_use]
pub fn new(key: &[u8; 32]) -> Self {
let cookie_key = Key::derive_from(&key[..]);
let cookie_key = Arc::new(cookie_key);
let key = GenericArray::from_slice(key);
let aead = ChaCha20Poly1305::new(key);
let aead = Arc::new(aead);
Self { cookie_key, aead }
}
/// Encrypt a payload
///
/// # Errors
///
/// Will return `Err` when the payload failed to encrypt
pub fn encrypt(&self, nonce: &[u8; 12], decrypted: &[u8]) -> anyhow::Result<Vec<u8>> {
let nonce = GenericArray::from_slice(&nonce[..]);
let encrypted = self.aead.encrypt(nonce, decrypted)?;
Ok(encrypted)
}
/// Decrypts a payload
///
/// # Errors
///
/// Will return `Err` when the payload failed to decrypt
pub fn decrypt(&self, nonce: &[u8; 12], encrypted: &[u8]) -> anyhow::Result<Vec<u8>> {
let nonce = GenericArray::from_slice(&nonce[..]);
let encrypted = self.aead.decrypt(nonce, encrypted)?;
Ok(encrypted)
}
/// Encrypt a payload to a self-contained base64-encoded string
///
/// # Errors
///
/// Will return `Err` when the payload failed to encrypt
pub fn encryt_to_string(&self, decrypted: &[u8]) -> anyhow::Result<String> {
let nonce = rand::random();
let encrypted = self.encrypt(&nonce, decrypted)?;
let encrypted = [&nonce[..], &encrypted].concat();
let encrypted = Base64::encode_string(&encrypted);
Ok(encrypted)
}
/// Decrypt a payload from a self-contained base64-encoded string
///
/// # Errors
///
/// Will return `Err` when the payload failed to decrypt
pub fn decrypt_string(&self, encrypted: &str) -> anyhow::Result<Vec<u8>> {
let encrypted = Base64::decode_vec(encrypted)?;
let nonce: &[u8; 12] = encrypted
.get(0..12)
.ok_or_else(|| anyhow::anyhow!("invalid payload serialization"))?
.try_into()?;
let payload = encrypted
.get(12..)
.ok_or_else(|| anyhow::anyhow!("invalid payload serialization"))?;
let decrypted_client_secret = self.decrypt(nonce, payload)?;
Ok(decrypted_client_secret)
}
}

View File

@ -37,11 +37,15 @@ use mas_jose::{
use pem_rfc7468::PemLabel;
use pkcs1::EncodeRsaPrivateKey;
use pkcs8::{AssociatedOid, PrivateKeyInfo};
use rand_core::{CryptoRng, RngCore};
use rand::{CryptoRng, RngCore};
use rsa::BigUint;
use sec1::EncodeEcPrivateKey;
use thiserror::Error;
mod encrypter;
pub use self::encrypter::Encrypter;
/// Error type used when a key could not be loaded
#[derive(Debug, Error)]
pub enum LoadError {