You've already forked authentication-service
mirror of
https://github.com/matrix-org/matrix-authentication-service.git
synced 2025-07-31 09:24:31 +03:00
Move the Encrypter from the config to the keystore
This commit is contained in:
22
Cargo.lock
generated
22
Cargo.lock
generated
@ -28,9 +28,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "aead"
|
name = "aead"
|
||||||
version = "0.5.0"
|
version = "0.5.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ae06cea71059b6b79d879afcdd237a33ac61afc052fdd605815e6f3916254abf"
|
checksum = "5c192eb8f11fc081b0fe4259ba5af04217d4e0faddd02417310a927911abd7c8"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"crypto-common",
|
"crypto-common",
|
||||||
"generic-array",
|
"generic-array",
|
||||||
@ -790,7 +790,7 @@ version = "0.10.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
|
checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aead 0.5.0",
|
"aead 0.5.1",
|
||||||
"chacha20",
|
"chacha20",
|
||||||
"cipher 0.4.3",
|
"cipher 0.4.3",
|
||||||
"poly1305",
|
"poly1305",
|
||||||
@ -1698,9 +1698,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "generic-array"
|
name = "generic-array"
|
||||||
version = "0.14.5"
|
version = "0.14.6"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803"
|
checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"typenum",
|
"typenum",
|
||||||
"version_check",
|
"version_check",
|
||||||
@ -2358,11 +2358,11 @@ dependencies = [
|
|||||||
"headers",
|
"headers",
|
||||||
"http",
|
"http",
|
||||||
"http-body",
|
"http-body",
|
||||||
"mas-config",
|
|
||||||
"mas-data-model",
|
"mas-data-model",
|
||||||
"mas-http",
|
"mas-http",
|
||||||
"mas-iana",
|
"mas-iana",
|
||||||
"mas-jose",
|
"mas-jose",
|
||||||
|
"mas-keystore",
|
||||||
"mas-storage",
|
"mas-storage",
|
||||||
"mas-templates",
|
"mas-templates",
|
||||||
"mime",
|
"mime",
|
||||||
@ -2426,10 +2426,7 @@ version = "0.1.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"chacha20poly1305",
|
|
||||||
"chrono",
|
"chrono",
|
||||||
"cookie",
|
|
||||||
"data-encoding",
|
|
||||||
"figment",
|
"figment",
|
||||||
"indoc",
|
"indoc",
|
||||||
"lettre",
|
"lettre",
|
||||||
@ -2616,11 +2613,16 @@ dependencies = [
|
|||||||
name = "mas-keystore"
|
name = "mas-keystore"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"aead 0.5.1",
|
||||||
"anyhow",
|
"anyhow",
|
||||||
|
"base64ct",
|
||||||
|
"chacha20poly1305",
|
||||||
"const-oid",
|
"const-oid",
|
||||||
|
"cookie",
|
||||||
"der",
|
"der",
|
||||||
"ecdsa",
|
"ecdsa",
|
||||||
"elliptic-curve",
|
"elliptic-curve",
|
||||||
|
"generic-array",
|
||||||
"k256",
|
"k256",
|
||||||
"mas-iana",
|
"mas-iana",
|
||||||
"mas-jose",
|
"mas-jose",
|
||||||
@ -2629,7 +2631,7 @@ dependencies = [
|
|||||||
"pem-rfc7468",
|
"pem-rfc7468",
|
||||||
"pkcs1",
|
"pkcs1",
|
||||||
"pkcs8",
|
"pkcs8",
|
||||||
"rand_core",
|
"rand",
|
||||||
"rsa",
|
"rsa",
|
||||||
"sec1",
|
"sec1",
|
||||||
"spki",
|
"spki",
|
||||||
|
@ -29,11 +29,10 @@ tower = { version = "0.4.13", features = ["util"] }
|
|||||||
tracing = "0.1.36"
|
tracing = "0.1.36"
|
||||||
url = "2.2.2"
|
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-data-model = { path = "../data-model" }
|
||||||
mas-jose = { path = "../jose" }
|
|
||||||
mas-iana = { path = "../iana" }
|
|
||||||
mas-http = { path = "../http", features = ["client"] }
|
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" }
|
||||||
|
@ -26,7 +26,7 @@ use axum::{
|
|||||||
};
|
};
|
||||||
use headers::{authorization::Basic, Authorization};
|
use headers::{authorization::Basic, Authorization};
|
||||||
use http::StatusCode;
|
use http::StatusCode;
|
||||||
use mas_config::Encrypter;
|
use mas_keystore::Encrypter;
|
||||||
use mas_data_model::{Client, JwksOrJwksUri, StorageBackend};
|
use mas_data_model::{Client, JwksOrJwksUri, StorageBackend};
|
||||||
use mas_http::HttpServiceExt;
|
use mas_http::HttpServiceExt;
|
||||||
use mas_iana::oauth::OAuthClientAuthenticationMethod;
|
use mas_iana::oauth::OAuthClientAuthenticationMethod;
|
||||||
|
@ -26,9 +26,6 @@ lettre = { version = "0.10.1", default-features = false, features = ["serde", "b
|
|||||||
|
|
||||||
pem-rfc7468 = "0.6.0"
|
pem-rfc7468 = "0.6.0"
|
||||||
rand = "0.8.5"
|
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"
|
indoc = "1.0.7"
|
||||||
|
|
||||||
|
@ -35,7 +35,7 @@ pub use self::{
|
|||||||
http::HttpConfig,
|
http::HttpConfig,
|
||||||
matrix::MatrixConfig,
|
matrix::MatrixConfig,
|
||||||
policy::PolicyConfig,
|
policy::PolicyConfig,
|
||||||
secrets::{Encrypter, SecretsConfig},
|
secrets::SecretsConfig,
|
||||||
telemetry::{
|
telemetry::{
|
||||||
MetricsConfig, MetricsExporterConfig, Propagator, TelemetryConfig, TracingConfig,
|
MetricsConfig, MetricsExporterConfig, Propagator, TelemetryConfig, TracingConfig,
|
||||||
TracingExporterConfig,
|
TracingExporterConfig,
|
||||||
|
@ -12,18 +12,12 @@
|
|||||||
// See the License for the specific language governing permissions and
|
// See the License for the specific language governing permissions and
|
||||||
// limitations under the License.
|
// limitations under the License.
|
||||||
|
|
||||||
use std::{borrow::Cow, path::PathBuf, sync::Arc};
|
use std::{borrow::Cow, path::PathBuf};
|
||||||
|
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use async_trait::async_trait;
|
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_jose::jwk::{JsonWebKey, JsonWebKeySet};
|
||||||
use mas_keystore::{Keystore, PrivateKey};
|
use mas_keystore::{Encrypter, Keystore, PrivateKey};
|
||||||
use rand::{
|
use rand::{
|
||||||
distributions::{Alphanumeric, DistString},
|
distributions::{Alphanumeric, DistString},
|
||||||
thread_rng,
|
thread_rng,
|
||||||
@ -36,90 +30,6 @@ use tracing::info;
|
|||||||
|
|
||||||
use super::ConfigurationSection;
|
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 {
|
fn example_secret() -> &'static str {
|
||||||
"0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff"
|
"0000111122223333444455556666777788889999aaaabbbbccccddddeeeeffff"
|
||||||
}
|
}
|
||||||
|
@ -26,8 +26,8 @@ use mas_axum_utils::{
|
|||||||
csrf::{CsrfExt, ProtectedForm},
|
csrf::{CsrfExt, ProtectedForm},
|
||||||
FancyError, SessionInfoExt,
|
FancyError, SessionInfoExt,
|
||||||
};
|
};
|
||||||
use mas_config::Encrypter;
|
|
||||||
use mas_data_model::Device;
|
use mas_data_model::Device;
|
||||||
|
use mas_keystore::Encrypter;
|
||||||
use mas_router::{CompatLoginSsoAction, PostAuthAction, Route};
|
use mas_router::{CompatLoginSsoAction, PostAuthAction, Route};
|
||||||
use mas_storage::compat::{fullfill_compat_sso_login, get_compat_sso_login_by_id};
|
use mas_storage::compat::{fullfill_compat_sso_login, get_compat_sso_login_by_id};
|
||||||
use mas_templates::{CompatSsoContext, ErrorContext, TemplateContext, Templates};
|
use mas_templates::{CompatSsoContext, ErrorContext, TemplateContext, Templates};
|
||||||
|
@ -30,10 +30,10 @@ use axum::{
|
|||||||
};
|
};
|
||||||
use headers::HeaderName;
|
use headers::HeaderName;
|
||||||
use hyper::header::{ACCEPT, ACCEPT_LANGUAGE, AUTHORIZATION, CONTENT_LANGUAGE, CONTENT_TYPE};
|
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_email::Mailer;
|
||||||
use mas_http::CorsLayerExt;
|
use mas_http::CorsLayerExt;
|
||||||
use mas_keystore::Keystore;
|
use mas_keystore::{Encrypter, Keystore};
|
||||||
use mas_policy::PolicyFactory;
|
use mas_policy::PolicyFactory;
|
||||||
use mas_router::{Route, UrlBuilder};
|
use mas_router::{Route, UrlBuilder};
|
||||||
use mas_templates::{ErrorContext, Templates};
|
use mas_templates::{ErrorContext, Templates};
|
||||||
|
@ -23,8 +23,8 @@ use axum::{
|
|||||||
use axum_extra::extract::PrivateCookieJar;
|
use axum_extra::extract::PrivateCookieJar;
|
||||||
use hyper::StatusCode;
|
use hyper::StatusCode;
|
||||||
use mas_axum_utils::SessionInfoExt;
|
use mas_axum_utils::SessionInfoExt;
|
||||||
use mas_config::Encrypter;
|
|
||||||
use mas_data_model::{AuthorizationGrant, BrowserSession};
|
use mas_data_model::{AuthorizationGrant, BrowserSession};
|
||||||
|
use mas_keystore::Encrypter;
|
||||||
use mas_policy::PolicyFactory;
|
use mas_policy::PolicyFactory;
|
||||||
use mas_router::{PostAuthAction, Route};
|
use mas_router::{PostAuthAction, Route};
|
||||||
use mas_storage::{
|
use mas_storage::{
|
||||||
|
@ -22,9 +22,9 @@ use axum::{
|
|||||||
use axum_extra::extract::PrivateCookieJar;
|
use axum_extra::extract::PrivateCookieJar;
|
||||||
use hyper::StatusCode;
|
use hyper::StatusCode;
|
||||||
use mas_axum_utils::SessionInfoExt;
|
use mas_axum_utils::SessionInfoExt;
|
||||||
use mas_config::Encrypter;
|
|
||||||
use mas_data_model::{AuthorizationCode, Pkce};
|
use mas_data_model::{AuthorizationCode, Pkce};
|
||||||
use mas_iana::oauth::OAuthAuthorizationEndpointResponseType;
|
use mas_iana::oauth::OAuthAuthorizationEndpointResponseType;
|
||||||
|
use mas_keystore::Encrypter;
|
||||||
use mas_policy::PolicyFactory;
|
use mas_policy::PolicyFactory;
|
||||||
use mas_router::{PostAuthAction, Route};
|
use mas_router::{PostAuthAction, Route};
|
||||||
use mas_storage::oauth2::{
|
use mas_storage::oauth2::{
|
||||||
|
@ -25,8 +25,8 @@ use mas_axum_utils::{
|
|||||||
csrf::{CsrfExt, ProtectedForm},
|
csrf::{CsrfExt, ProtectedForm},
|
||||||
SessionInfoExt,
|
SessionInfoExt,
|
||||||
};
|
};
|
||||||
use mas_config::Encrypter;
|
|
||||||
use mas_data_model::AuthorizationGrantStage;
|
use mas_data_model::AuthorizationGrantStage;
|
||||||
|
use mas_keystore::Encrypter;
|
||||||
use mas_policy::PolicyFactory;
|
use mas_policy::PolicyFactory;
|
||||||
use mas_router::{PostAuthAction, Route};
|
use mas_router::{PostAuthAction, Route};
|
||||||
use mas_storage::oauth2::{
|
use mas_storage::oauth2::{
|
||||||
|
@ -15,9 +15,9 @@
|
|||||||
use axum::{extract::Extension, response::IntoResponse, Json};
|
use axum::{extract::Extension, response::IntoResponse, Json};
|
||||||
use hyper::StatusCode;
|
use hyper::StatusCode;
|
||||||
use mas_axum_utils::client_authorization::{ClientAuthorization, CredentialsVerificationError};
|
use mas_axum_utils::client_authorization::{ClientAuthorization, CredentialsVerificationError};
|
||||||
use mas_config::Encrypter;
|
|
||||||
use mas_data_model::{TokenFormatError, TokenType};
|
use mas_data_model::{TokenFormatError, TokenType};
|
||||||
use mas_iana::oauth::{OAuthClientAuthenticationMethod, OAuthTokenTypeHint};
|
use mas_iana::oauth::{OAuthClientAuthenticationMethod, OAuthTokenTypeHint};
|
||||||
|
use mas_keystore::Encrypter;
|
||||||
use mas_storage::{
|
use mas_storage::{
|
||||||
compat::{
|
compat::{
|
||||||
lookup_active_compat_access_token, lookup_active_compat_refresh_token,
|
lookup_active_compat_access_token, lookup_active_compat_refresh_token,
|
||||||
|
@ -21,7 +21,6 @@ use data_encoding::BASE64URL_NOPAD;
|
|||||||
use headers::{CacheControl, HeaderMap, HeaderMapExt, Pragma};
|
use headers::{CacheControl, HeaderMap, HeaderMapExt, Pragma};
|
||||||
use hyper::StatusCode;
|
use hyper::StatusCode;
|
||||||
use mas_axum_utils::client_authorization::{ClientAuthorization, CredentialsVerificationError};
|
use mas_axum_utils::client_authorization::{ClientAuthorization, CredentialsVerificationError};
|
||||||
use mas_config::Encrypter;
|
|
||||||
use mas_data_model::{AuthorizationGrantStage, Client, TokenType};
|
use mas_data_model::{AuthorizationGrantStage, Client, TokenType};
|
||||||
use mas_iana::jose::JsonWebSignatureAlg;
|
use mas_iana::jose::JsonWebSignatureAlg;
|
||||||
use mas_jose::{
|
use mas_jose::{
|
||||||
@ -29,7 +28,7 @@ use mas_jose::{
|
|||||||
constraints::Constrainable,
|
constraints::Constrainable,
|
||||||
jwt::{JsonWebSignatureHeader, Jwt, JwtSignatureError},
|
jwt::{JsonWebSignatureHeader, Jwt, JwtSignatureError},
|
||||||
};
|
};
|
||||||
use mas_keystore::Keystore;
|
use mas_keystore::{Encrypter, Keystore};
|
||||||
use mas_router::UrlBuilder;
|
use mas_router::UrlBuilder;
|
||||||
use mas_storage::{
|
use mas_storage::{
|
||||||
oauth2::{
|
oauth2::{
|
||||||
|
@ -21,8 +21,8 @@ use mas_axum_utils::{
|
|||||||
csrf::{CsrfExt, ProtectedForm},
|
csrf::{CsrfExt, ProtectedForm},
|
||||||
FancyError, SessionInfoExt,
|
FancyError, SessionInfoExt,
|
||||||
};
|
};
|
||||||
use mas_config::Encrypter;
|
|
||||||
use mas_email::Mailer;
|
use mas_email::Mailer;
|
||||||
|
use mas_keystore::Encrypter;
|
||||||
use mas_router::Route;
|
use mas_router::Route;
|
||||||
use mas_storage::user::add_user_email;
|
use mas_storage::user::add_user_email;
|
||||||
use mas_templates::{EmailAddContext, TemplateContext, Templates};
|
use mas_templates::{EmailAddContext, TemplateContext, Templates};
|
||||||
|
@ -22,9 +22,9 @@ use mas_axum_utils::{
|
|||||||
csrf::{CsrfExt, ProtectedForm},
|
csrf::{CsrfExt, ProtectedForm},
|
||||||
FancyError, SessionInfoExt,
|
FancyError, SessionInfoExt,
|
||||||
};
|
};
|
||||||
use mas_config::Encrypter;
|
|
||||||
use mas_data_model::{BrowserSession, User, UserEmail};
|
use mas_data_model::{BrowserSession, User, UserEmail};
|
||||||
use mas_email::Mailer;
|
use mas_email::Mailer;
|
||||||
|
use mas_keystore::Encrypter;
|
||||||
use mas_router::Route;
|
use mas_router::Route;
|
||||||
use mas_storage::{
|
use mas_storage::{
|
||||||
user::{
|
user::{
|
||||||
|
@ -22,7 +22,7 @@ use mas_axum_utils::{
|
|||||||
csrf::{CsrfExt, ProtectedForm},
|
csrf::{CsrfExt, ProtectedForm},
|
||||||
FancyError, SessionInfoExt,
|
FancyError, SessionInfoExt,
|
||||||
};
|
};
|
||||||
use mas_config::Encrypter;
|
use mas_keystore::Encrypter;
|
||||||
use mas_router::Route;
|
use mas_router::Route;
|
||||||
use mas_storage::user::{
|
use mas_storage::user::{
|
||||||
consume_email_verification, lookup_user_email_by_id, lookup_user_email_verification_code,
|
consume_email_verification, lookup_user_email_by_id, lookup_user_email_verification_code,
|
||||||
|
@ -21,7 +21,7 @@ use axum::{
|
|||||||
};
|
};
|
||||||
use axum_extra::extract::PrivateCookieJar;
|
use axum_extra::extract::PrivateCookieJar;
|
||||||
use mas_axum_utils::{csrf::CsrfExt, FancyError, SessionInfoExt};
|
use mas_axum_utils::{csrf::CsrfExt, FancyError, SessionInfoExt};
|
||||||
use mas_config::Encrypter;
|
use mas_keystore::Encrypter;
|
||||||
use mas_router::Route;
|
use mas_router::Route;
|
||||||
use mas_storage::user::{count_active_sessions, get_user_emails};
|
use mas_storage::user::{count_active_sessions, get_user_emails};
|
||||||
use mas_templates::{AccountContext, TemplateContext, Templates};
|
use mas_templates::{AccountContext, TemplateContext, Templates};
|
||||||
|
@ -22,8 +22,8 @@ use mas_axum_utils::{
|
|||||||
csrf::{CsrfExt, ProtectedForm},
|
csrf::{CsrfExt, ProtectedForm},
|
||||||
FancyError, SessionInfoExt,
|
FancyError, SessionInfoExt,
|
||||||
};
|
};
|
||||||
use mas_config::Encrypter;
|
|
||||||
use mas_data_model::BrowserSession;
|
use mas_data_model::BrowserSession;
|
||||||
|
use mas_keystore::Encrypter;
|
||||||
use mas_router::Route;
|
use mas_router::Route;
|
||||||
use mas_storage::{
|
use mas_storage::{
|
||||||
user::{authenticate_session, set_password},
|
user::{authenticate_session, set_password},
|
||||||
|
@ -18,7 +18,7 @@ use axum::{
|
|||||||
};
|
};
|
||||||
use axum_extra::extract::PrivateCookieJar;
|
use axum_extra::extract::PrivateCookieJar;
|
||||||
use mas_axum_utils::{csrf::CsrfExt, FancyError, SessionInfoExt};
|
use mas_axum_utils::{csrf::CsrfExt, FancyError, SessionInfoExt};
|
||||||
use mas_config::Encrypter;
|
use mas_keystore::Encrypter;
|
||||||
use mas_router::UrlBuilder;
|
use mas_router::UrlBuilder;
|
||||||
use mas_templates::{IndexContext, TemplateContext, Templates};
|
use mas_templates::{IndexContext, TemplateContext, Templates};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
@ -21,7 +21,7 @@ use mas_axum_utils::{
|
|||||||
csrf::{CsrfExt, CsrfToken, ProtectedForm},
|
csrf::{CsrfExt, CsrfToken, ProtectedForm},
|
||||||
FancyError, SessionInfoExt,
|
FancyError, SessionInfoExt,
|
||||||
};
|
};
|
||||||
use mas_config::Encrypter;
|
use mas_keystore::Encrypter;
|
||||||
use mas_router::Route;
|
use mas_router::Route;
|
||||||
use mas_storage::user::{login, LoginError};
|
use mas_storage::user::{login, LoginError};
|
||||||
use mas_templates::{
|
use mas_templates::{
|
||||||
|
@ -21,7 +21,7 @@ use mas_axum_utils::{
|
|||||||
csrf::{CsrfExt, ProtectedForm},
|
csrf::{CsrfExt, ProtectedForm},
|
||||||
FancyError, SessionInfoExt,
|
FancyError, SessionInfoExt,
|
||||||
};
|
};
|
||||||
use mas_config::Encrypter;
|
use mas_keystore::Encrypter;
|
||||||
use mas_router::{PostAuthAction, Route};
|
use mas_router::{PostAuthAction, Route};
|
||||||
use mas_storage::user::end_session;
|
use mas_storage::user::end_session;
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
|
@ -21,7 +21,7 @@ use mas_axum_utils::{
|
|||||||
csrf::{CsrfExt, ProtectedForm},
|
csrf::{CsrfExt, ProtectedForm},
|
||||||
FancyError, SessionInfoExt,
|
FancyError, SessionInfoExt,
|
||||||
};
|
};
|
||||||
use mas_config::Encrypter;
|
use mas_keystore::Encrypter;
|
||||||
use mas_router::Route;
|
use mas_router::Route;
|
||||||
use mas_storage::user::authenticate_session;
|
use mas_storage::user::authenticate_session;
|
||||||
use mas_templates::{ReauthContext, TemplateContext, Templates};
|
use mas_templates::{ReauthContext, TemplateContext, Templates};
|
||||||
|
@ -27,8 +27,8 @@ use mas_axum_utils::{
|
|||||||
csrf::{CsrfExt, CsrfToken, ProtectedForm},
|
csrf::{CsrfExt, CsrfToken, ProtectedForm},
|
||||||
FancyError, SessionInfoExt,
|
FancyError, SessionInfoExt,
|
||||||
};
|
};
|
||||||
use mas_config::Encrypter;
|
|
||||||
use mas_email::Mailer;
|
use mas_email::Mailer;
|
||||||
|
use mas_keystore::Encrypter;
|
||||||
use mas_policy::PolicyFactory;
|
use mas_policy::PolicyFactory;
|
||||||
use mas_router::Route;
|
use mas_router::Route;
|
||||||
use mas_storage::user::{
|
use mas_storage::user::{
|
||||||
|
@ -7,21 +7,26 @@ license = "Apache-2.0"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
anyhow = "1.0.62"
|
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"] }
|
der = { version = "0.6.0", features = ["std"] }
|
||||||
|
ecdsa = { version = "0.14.4", features = ["std"] }
|
||||||
elliptic-curve = { version = "0.12.3", features = ["std", "pem", "sec1"] }
|
elliptic-curve = { version = "0.12.3", features = ["std", "pem", "sec1"] }
|
||||||
k256 = { version = "0.11.1", features = ["std"] }
|
k256 = { version = "0.11.1", features = ["std"] }
|
||||||
p256 = { version = "0.11.1", features = ["std"] }
|
p256 = { version = "0.11.1", features = ["std"] }
|
||||||
p384 = { version = "0.11.1", features = ["std"] }
|
p384 = { version = "0.11.1", features = ["std"] }
|
||||||
pem-rfc7468 = { version = "0.6.0", features = ["std"] }
|
pem-rfc7468 = { version = "0.6.0", features = ["std"] }
|
||||||
pkcs1 = { version = "0.4.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"] }
|
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"] }
|
rsa = { git = "https://github.com/RustCrypto/RSA.git", features = ["std", "pem"] }
|
||||||
sec1 = { version = "0.3.0", features = ["std"] }
|
sec1 = { version = "0.3.0", features = ["std"] }
|
||||||
|
spki = { version = "0.6.0", features = ["std"] }
|
||||||
thiserror = "1.0.32"
|
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-iana = { path = "../iana" }
|
||||||
mas-jose = { path = "../jose" }
|
mas-jose = { path = "../jose" }
|
||||||
|
104
crates/keystore/src/encrypter.rs
Normal file
104
crates/keystore/src/encrypter.rs
Normal 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)
|
||||||
|
}
|
||||||
|
}
|
@ -37,11 +37,15 @@ use mas_jose::{
|
|||||||
use pem_rfc7468::PemLabel;
|
use pem_rfc7468::PemLabel;
|
||||||
use pkcs1::EncodeRsaPrivateKey;
|
use pkcs1::EncodeRsaPrivateKey;
|
||||||
use pkcs8::{AssociatedOid, PrivateKeyInfo};
|
use pkcs8::{AssociatedOid, PrivateKeyInfo};
|
||||||
use rand_core::{CryptoRng, RngCore};
|
use rand::{CryptoRng, RngCore};
|
||||||
use rsa::BigUint;
|
use rsa::BigUint;
|
||||||
use sec1::EncodeEcPrivateKey;
|
use sec1::EncodeEcPrivateKey;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
|
|
||||||
|
mod encrypter;
|
||||||
|
|
||||||
|
pub use self::encrypter::Encrypter;
|
||||||
|
|
||||||
/// Error type used when a key could not be loaded
|
/// Error type used when a key could not be loaded
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum LoadError {
|
pub enum LoadError {
|
||||||
|
Reference in New Issue
Block a user