From 798c2f274bc14b329d202957f250c88c7967c728 Mon Sep 17 00:00:00 2001 From: BlackDex Date: Sun, 14 Jul 2024 15:18:08 +0200 Subject: [PATCH] Fix for RSA Keys which are read only Sometimes an RSA Key file could be read only. We currently failed because we also wanted to write. Added an extra check if the file exists already and is not 0 in size. If it does already exists and is larger then 0, then open in read only mode. Fixes #4644 --- src/auth.rs | 27 ++++++++++++++++----------- src/main.rs | 2 +- 2 files changed, 17 insertions(+), 12 deletions(-) diff --git a/src/auth.rs b/src/auth.rs index 4ee9c188..ca242e66 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -1,13 +1,19 @@ // JWT Handling // use chrono::{TimeDelta, Utc}; +use jsonwebtoken::{errors::ErrorKind, Algorithm, DecodingKey, EncodingKey, Header}; use num_traits::FromPrimitive; use once_cell::sync::{Lazy, OnceCell}; - -use jsonwebtoken::{errors::ErrorKind, Algorithm, DecodingKey, EncodingKey, Header}; use openssl::rsa::Rsa; use serde::de::DeserializeOwned; use serde::ser::Serialize; +use std::{ + env, + fs::File, + io::{Read, Write}, + net::IpAddr, + path::Path, +}; use crate::{error::Error, CONFIG}; @@ -34,8 +40,13 @@ pub fn initialize_keys() -> Result<(), crate::error::Error> { let mut priv_key_buffer = Vec::with_capacity(2048); let priv_key = { - let mut priv_key_file = - File::options().create(true).truncate(false).read(true).write(true).open(CONFIG.private_rsa_key())?; + let mut priv_key_file = if !Path::new(&CONFIG.private_rsa_key()).exists() + || std::fs::metadata(CONFIG.private_rsa_key())?.len() == 0 + { + File::options().create(true).truncate(false).read(true).write(true).open(CONFIG.private_rsa_key())? + } else { + File::options().read(true).open(CONFIG.private_rsa_key())? + }; #[allow(clippy::verbose_file_reads)] let bytes_read = priv_key_file.read_to_end(&mut priv_key_buffer)?; @@ -47,7 +58,7 @@ pub fn initialize_keys() -> Result<(), crate::error::Error> { let rsa_key = openssl::rsa::Rsa::generate(2048)?; priv_key_buffer = rsa_key.private_key_to_pem()?; priv_key_file.write_all(&priv_key_buffer)?; - info!("Private key created correctly."); + info!("Private key '{}' created correctly.", CONFIG.private_rsa_key()); rsa_key } }; @@ -803,12 +814,6 @@ impl<'r> FromRequest<'r> for OwnerHeaders { // // Client IP address detection // -use std::{ - env, - fs::File, - io::{Read, Write}, - net::IpAddr, -}; pub struct ClientIp { pub ip: IpAddr, diff --git a/src/main.rs b/src/main.rs index ecc4f320..6c0bdd52 100644 --- a/src/main.rs +++ b/src/main.rs @@ -77,7 +77,7 @@ async fn main() -> Result<(), Error> { check_data_folder().await; auth::initialize_keys().unwrap_or_else(|_| { - error!("Error creating keys, exiting..."); + error!("Error creating private key '{}', exiting...", CONFIG.private_rsa_key()); exit(1); }); check_web_vault();