/*
* This file is part of mailpot
*
* Copyright 2020 - Manos Pitsidianakis
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see .
*/
use std::{borrow::Cow, process::Stdio};
use tempfile::NamedTempFile;
use tokio::{fs::File, io::AsyncWriteExt, process::Command};
use super::*;
const TOKEN_KEY: &str = "ssh_challenge";
const EXPIRY_IN_SECS: i64 = 6 * 60;
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum Role {
User,
Admin,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct User {
/// SSH signature.
pub ssh_signature: String,
/// User role.
pub role: Role,
/// Database primary key.
pub pk: i64,
/// Accounts's display name, optional.
pub name: Option,
/// Account's e-mail address.
pub address: String,
/// GPG public key.
pub public_key: Option,
/// SSH public key.
pub password: String,
/// Whether this account is enabled.
pub enabled: bool,
}
impl AuthUser for User {
fn get_id(&self) -> i64 {
self.pk
}
fn get_password_hash(&self) -> SecretVec {
SecretVec::new(self.ssh_signature.clone().into())
}
fn get_role(&self) -> Option {
Some(self.role)
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Default)]
pub struct AuthFormPayload {
pub address: String,
pub password: String,
}
pub async fn ssh_signin(
_: LoginPath,
mut session: WritableSession,
Query(next): Query,
auth: AuthContext,
State(state): State>,
) -> impl IntoResponse {
if auth.current_user.is_some() {
if let Err(err) = session.add_message(Message {
message: "You are already logged in.".into(),
level: Level::Info,
}) {
return err.into_response();
}
return next
.or_else(|| format!("{}{}", state.root_url_prefix, SettingsPath.to_uri()))
.into_response();
}
if next.next.is_some() {
if let Err(err) = session.add_message(Message {
message: "You need to be logged in to access this page.".into(),
level: Level::Info,
}) {
return err.into_response();
};
}
let now: i64 = chrono::offset::Utc::now().timestamp();
let prev_token = if let Some(tok) = session.get::<(String, i64)>(TOKEN_KEY) {
let timestamp: i64 = tok.1;
if !(timestamp < now && now - timestamp < EXPIRY_IN_SECS) {
session.remove(TOKEN_KEY);
None
} else {
Some(tok)
}
} else {
None
};
let (token, timestamp): (String, i64) = if let Some(tok) = prev_token {
tok
} else {
use rand::{distributions::Alphanumeric, thread_rng, Rng};
let mut rng = thread_rng();
let chars: String = (0..7).map(|_| rng.sample(Alphanumeric) as char).collect();
println!("Random chars: {}", chars);
session.insert(TOKEN_KEY, (&chars, now)).unwrap();
(chars, now)
};
let timeout_left = ((timestamp + EXPIRY_IN_SECS) - now) as f64 / 60.0;
let root_url_prefix = &state.root_url_prefix;
let crumbs = vec![
Crumb {
label: "Home".into(),
url: "/".into(),
},
Crumb {
label: "Sign in".into(),
url: LoginPath.to_crumb(),
},
];
let context = minijinja::context! {
namespace => &state.public_url,
title => state.site_title.as_ref(),
page_title => "Log in",
description => "",
root_url_prefix => &root_url_prefix,
ssh_challenge => token,
timeout_left => timeout_left,
current_user => auth.current_user,
messages => session.drain_messages(),
crumbs => crumbs,
};
Html(
TEMPLATES
.get_template("auth.html")
.unwrap()
.render(context)
.unwrap_or_else(|err| err.to_string()),
)
.into_response()
}
pub async fn ssh_signin_post(
_: LoginPath,
mut session: WritableSession,
Query(next): Query,
mut auth: AuthContext,
Form(payload): Form,
state: Arc,
) -> Result {
if auth.current_user.as_ref().is_some() {
session.add_message(Message {
message: "You are already logged in.".into(),
level: Level::Info,
})?;
return Ok(next.or_else(|| format!("{}{}", state.root_url_prefix, SettingsPath.to_uri())));
}
let now: i64 = chrono::offset::Utc::now().timestamp();
let (prev_token, _) =
if let Some(tok @ (_, timestamp)) = session.get::<(String, i64)>(TOKEN_KEY) {
if !(timestamp < now && now - timestamp < EXPIRY_IN_SECS) {
session.add_message(Message {
message: "The token has expired. Please retry.".into(),
level: Level::Error,
})?;
return Ok(Redirect::to(&format!(
"{}{}{}",
state.root_url_prefix,
LoginPath.to_uri(),
if let Some(ref next) = next.next {
next.as_str()
} else {
""
}
)));
} else {
tok
}
} else {
session.add_message(Message {
message: "The token has expired. Please retry.".into(),
level: Level::Error,
})?;
return Ok(Redirect::to(&format!(
"{}{}{}",
state.root_url_prefix,
LoginPath.to_uri(),
if let Some(ref next) = next.next {
next.as_str()
} else {
""
}
)));
};
drop(session);
let db = Connection::open_db(state.conf.clone())?;
let mut acc = match db
.account_by_address(&payload.address)
.with_status(StatusCode::BAD_REQUEST)?
{
Some(v) => v,
None => {
return Err(ResponseError::new(
format!("Account for {} not found", payload.address),
StatusCode::NOT_FOUND,
));
}
};
let sig = SshSignature {
email: payload.address.clone(),
ssh_public_key: acc.password.clone(),
ssh_signature: payload.password.clone(),
namespace: std::env::var("SSH_NAMESPACE")
.unwrap_or_else(|_| "lists.mailpot.rs".to_string())
.into(),
token: prev_token,
};
ssh_keygen(sig).await?;
let user = User {
pk: acc.pk(),
ssh_signature: payload.password,
role: Role::User,
public_key: std::mem::take(&mut acc.public_key),
password: std::mem::take(&mut acc.password),
name: std::mem::take(&mut acc.name),
address: payload.address,
enabled: acc.enabled,
};
state.insert_user(acc.pk(), user.clone()).await;
auth.login(&user)
.await
.map_err(|err| ResponseError::new(err.to_string(), StatusCode::BAD_REQUEST))?;
Ok(next.or_else(|| format!("{}{}", state.root_url_prefix, SettingsPath.to_uri())))
}
#[derive(Debug, Clone, Default)]
pub struct SshSignature {
pub email: String,
pub ssh_public_key: String,
pub ssh_signature: String,
pub namespace: Cow<'static, str>,
pub token: String,
}
/// Run ssh signature validation with `ssh-keygen` binary.
///
/// ```no_run
/// use mailpot_web::{ssh_keygen, SshSignature};
///
/// async fn key_gen(
/// ssh_public_key: String,
/// ssh_signature: String,
/// ) -> std::result::Result<(), Box> {
/// let mut sig = SshSignature {
/// email: "user@example.com".to_string(),
/// ssh_public_key,
/// ssh_signature,
/// namespace: "doc-test@example.com".into(),
/// token: "d074a61990".to_string(),
/// };
///
/// ssh_keygen(sig.clone()).await?;
/// Ok(())
/// }
/// ```
pub async fn ssh_keygen(sig: SshSignature) -> Result<(), Box> {
let SshSignature {
email,
ssh_public_key,
ssh_signature,
namespace,
token,
} = sig;
let dir = tempfile::tempdir()?;
let mut allowed_signers_fp = NamedTempFile::new_in(dir.path())?;
let mut signature_fp = NamedTempFile::new_in(dir.path())?;
{
let (tempfile, path) = allowed_signers_fp.into_parts();
let mut file = File::from(tempfile);
file.write_all(format!("{email} {ssh_public_key}").as_bytes())
.await?;
file.flush().await?;
allowed_signers_fp = NamedTempFile::from_parts(file.into_std().await, path);
}
{
let (tempfile, path) = signature_fp.into_parts();
let mut file = File::from(tempfile);
file.write_all(ssh_signature.trim().replace("\r\n", "\n").as_bytes())
.await?;
file.flush().await?;
signature_fp = NamedTempFile::from_parts(file.into_std().await, path);
}
let mut cmd = Command::new("ssh-keygen");
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
cmd.stdin(Stdio::piped());
// Once you have your allowed signers file, verification works like this:
// ssh-keygen -Y verify -f allowed_signers -I alice@example.com -n file -s file_to_verify.sig < file_to_verify
// Here are the arguments you may need to change:
// allowed_signers is the path to the allowed signers file.
// alice@example.com is the email address of the person who allegedly signed the file. This email address is looked up in the allowed signers file to get possible public keys.
// file is the "namespace", which must match the namespace used for signing as described above.
// file_to_verify.sig is the path to the signature file.
// file_to_verify is the path to the file to be verified. Note that this file is read from standard in. In the above command, the < shell operator is used to redirect standard in from this file.
// If the signature is valid, the command exits with status 0 and prints a message like this:
// Good "file" signature for alice@example.com with ED25519 key SHA256:ZGa8RztddW4kE2XKPPsP9ZYC7JnMObs6yZzyxg8xZSk
// Otherwise, the command exits with a non-zero status and prints an error message.
let mut child = cmd
.arg("-Y")
.arg("verify")
.arg("-f")
.arg(allowed_signers_fp.path())
.arg("-I")
.arg(&email)
.arg("-n")
.arg(namespace.as_ref())
.arg("-s")
.arg(signature_fp.path())
.spawn()
.expect("failed to spawn command");
let mut stdin = child
.stdin
.take()
.expect("child did not have a handle to stdin");
stdin
.write_all(token.as_bytes())
.await
.expect("could not write to stdin");
drop(stdin);
let op = child.wait_with_output().await?;
if !op.status.success() {
return Err(format!(
"ssh-keygen exited with {}:\nstdout: {}\n\nstderr: {}",
op.status.code().unwrap_or(-1),
String::from_utf8_lossy(&op.stdout),
String::from_utf8_lossy(&op.stderr)
)
.into());
}
Ok(())
}
pub async fn logout_handler(
_: LogoutPath,
mut auth: AuthContext,
State(state): State>,
) -> Redirect {
auth.logout().await;
Redirect::to(&format!("{}/", state.root_url_prefix))
}
pub mod auth_request {
use std::{marker::PhantomData, ops::RangeBounds};
use axum::body::HttpBody;
use dyn_clone::DynClone;
use tower_http::auth::AuthorizeRequest;
use super::*;
trait RoleBounds: DynClone + Send + Sync {
fn contains(&self, role: Option) -> bool;
}
impl RoleBounds for T
where
Role: PartialOrd + PartialEq,
T: RangeBounds + Clone + Send + Sync,
{
fn contains(&self, role: Option) -> bool {
if let Some(role) = role {
RangeBounds::contains(self, &role)
} else {
role.is_none()
}
}
}
/// Type that performs login authorization.
///
/// See [`RequireAuthorizationLayer::login`] for more details.
pub struct Login {
login_url: Option>>,
redirect_field_name: Option>>,
role_bounds: Box>,
_user_id_type: PhantomData,
_user_type: PhantomData,
_body_type: PhantomData ResBody>,
}
impl Clone for Login {
fn clone(&self) -> Self {
Self {
login_url: self.login_url.clone(),
redirect_field_name: self.redirect_field_name.clone(),
role_bounds: dyn_clone::clone_box(&*self.role_bounds),
_user_id_type: PhantomData,
_user_type: PhantomData,
_body_type: PhantomData,
}
}
}
impl AuthorizeRequest
for Login
where
Role: PartialOrd + PartialEq + Clone + Send + Sync + 'static,
User: AuthUser,
ResBody: HttpBody + Default,
{
type ResponseBody = ResBody;
fn authorize(
&mut self,
request: &mut Request,
) -> Result<(), Response> {
let user = request
.extensions()
.get::