Remove pam and implement totp in rust
This commit is contained in:
parent
043ab278f5
commit
256546164f
4 changed files with 850 additions and 36 deletions
91
src/auth.rs
91
src/auth.rs
|
|
@ -5,15 +5,17 @@ use axum::{
|
|||
};
|
||||
use base64::{Engine, engine::general_purpose};
|
||||
use jsonwebtoken::{DecodingKey, EncodingKey, Header, Validation, decode, encode};
|
||||
use pam::Client;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::OnceLock;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use totp_rs::{Algorithm, Secret, TOTP};
|
||||
use yescrypt::{PasswordHash, PasswordVerifier, Yescrypt};
|
||||
|
||||
static JWT_SECRET: OnceLock<String> = OnceLock::new();
|
||||
|
||||
const ROTATION_DAYS: u64 = 7;
|
||||
const TOTP_SECRET_PATH: &str = "/var/lib/server-dash-api/google-auth/jack";
|
||||
|
||||
fn secret_path() -> PathBuf {
|
||||
PathBuf::from("/var/lib/server-dash-api/jwt_secret")
|
||||
|
|
@ -39,7 +41,6 @@ pub fn jwt_secret() -> &'static str {
|
|||
let path = secret_path();
|
||||
std::fs::create_dir_all(path.parent().unwrap()).ok();
|
||||
|
||||
// file format: "timestamp:secret"
|
||||
if let Ok(contents) = std::fs::read_to_string(&path) {
|
||||
if let Some((ts_str, secret)) = contents.trim().split_once(':') {
|
||||
if let Ok(ts) = ts_str.parse::<u64>() {
|
||||
|
|
@ -98,24 +99,86 @@ pub fn verify_token(headers: &HeaderMap) -> bool {
|
|||
.is_ok()
|
||||
}
|
||||
|
||||
pub fn decode_basic_auth(headers: &HeaderMap) -> Option<(String, String)> {
|
||||
pub fn decode_basic_auth(headers: &HeaderMap) -> Option<(String, String, String)> {
|
||||
let val = headers.get("Authorization")?.to_str().ok()?;
|
||||
let encoded = val.strip_prefix("Basic ")?;
|
||||
let decoded = general_purpose::STANDARD.decode(encoded).ok()?;
|
||||
let s = String::from_utf8(decoded).ok()?;
|
||||
let (user, pass) = s.split_once(':')?;
|
||||
Some((user.to_string(), pass.to_string()))
|
||||
let (user, rest) = s.split_once(':')?;
|
||||
if rest.len() < 6 {
|
||||
return None;
|
||||
}
|
||||
let (password, totp) = rest.split_at(rest.len() - 6);
|
||||
Some((user.to_string(), password.to_string(), totp.to_string()))
|
||||
}
|
||||
|
||||
pub fn verify_system_credentials(username: &str, password: &str) -> bool {
|
||||
let mut client = match Client::with_password("server-dash-api") {
|
||||
fn verify_password(username: &str, password: &str) -> bool {
|
||||
let shadow_content = match std::fs::read_to_string("/etc/shadow") {
|
||||
Ok(c) => c,
|
||||
Err(_) => return false,
|
||||
Err(e) => {
|
||||
println!("Failed to read /etc/shadow: {}", e);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
client
|
||||
.conversation_mut()
|
||||
.set_credentials(username, password);
|
||||
client.authenticate().is_ok()
|
||||
for line in shadow_content.lines() {
|
||||
let fields: Vec<&str> = line.split(':').collect();
|
||||
if fields.len() < 2 {
|
||||
continue;
|
||||
}
|
||||
if fields[0] != username {
|
||||
continue;
|
||||
}
|
||||
return verify_shadow_hash(password, fields[1]);
|
||||
}
|
||||
println!("User not found in shadow");
|
||||
false
|
||||
}
|
||||
|
||||
fn verify_shadow_hash(password: &str, hash: &str) -> bool {
|
||||
let parsed_hash = match PasswordHash::new(hash) {
|
||||
Ok(h) => h,
|
||||
Err(e) => {
|
||||
println!("Failed to parse hash: {:?}", e);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
Yescrypt::default()
|
||||
.verify_password(password.as_bytes(), &parsed_hash)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
fn verify_totp(totp_code: &str) -> bool {
|
||||
let secret_file = match std::fs::read_to_string(TOTP_SECRET_PATH) {
|
||||
Ok(f) => f,
|
||||
Err(e) => {
|
||||
println!("Failed to read TOTP secret: {}", e);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
let secret_b32 = secret_file.lines().next().unwrap_or("").trim().to_string();
|
||||
|
||||
let totp = match TOTP::new(
|
||||
Algorithm::SHA1,
|
||||
6,
|
||||
1,
|
||||
30,
|
||||
Secret::Encoded(secret_b32).to_bytes().unwrap(),
|
||||
None,
|
||||
"jack".to_string(),
|
||||
) {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
println!("Failed to create TOTP: {:?}", e);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
totp.check_current(totp_code).unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn verify_system_credentials(username: &str, password: &str, totp: &str) -> bool {
|
||||
verify_password(username, password) && verify_totp(totp)
|
||||
}
|
||||
|
||||
pub async fn require_auth(headers: HeaderMap, request: Request<Body>, next: Next) -> Response {
|
||||
|
|
@ -128,7 +191,7 @@ pub async fn require_auth(headers: HeaderMap, request: Request<Body>, next: Next
|
|||
|
||||
// POST /auth/login
|
||||
pub async fn post_login(headers: HeaderMap) -> impl IntoResponse {
|
||||
let (username, password_and_totp) = match decode_basic_auth(&headers) {
|
||||
let (username, password, totp) = match decode_basic_auth(&headers) {
|
||||
Some(c) => c,
|
||||
None => {
|
||||
return (
|
||||
|
|
@ -139,7 +202,7 @@ pub async fn post_login(headers: HeaderMap) -> impl IntoResponse {
|
|||
}
|
||||
};
|
||||
|
||||
if !verify_system_credentials(&username, &password_and_totp) {
|
||||
if !verify_system_credentials(&username, &password, &totp) {
|
||||
return (StatusCode::UNAUTHORIZED, "Invalid credentials").into_response();
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue