Skip to content

Commit

Permalink
adds debug statements as logs
Browse files Browse the repository at this point in the history
  • Loading branch information
Arshdeep54 committed Dec 22, 2024
1 parent 6dd0690 commit f46758a
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 11 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ toml_edit="0.1.5"
nix = "0.9.0"
openssl = "0.10"
openssl-sys = "0.9.58"
chrono = "0.4"

[[ bin ]]
name = "watchdog"
Expand Down
20 changes: 15 additions & 5 deletions src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,34 @@ use lib::utils::AUTH_LOG_PATH;
pub fn handle_auth(ssh_host_username: &str, ssh_key: &str) -> Result<()> {
let config = read_config()?;
init(&config)?;

logger::logln(&format!("ssh_key in handle_auth: {}", ssh_key));
match validate_user(&config, ssh_host_username.to_string(), ssh_key) {
Ok(true) => {
logger::logln("User validated");
let data = format!(
"ssh_host_username = '{}'\nssh_key = '{}'\n",
ssh_host_username, ssh_key
);

fs::write("/opt/watchdog/ssh_env", data)
.chain_err(|| "Cannot write temporary environment file. Please check if the watchdog `auth_keys_cmd` is run by the root user")?;

logger::logln("Temporary environment file written");
println!("{}", ssh_key);
let name = get_name(&config, ssh_key)?;
if let Err(e) = logger::log(AUTH_LOG_PATH, "SUCCESS", &format!("User: {}", name)) {
println!("Failed to log: {}", e);
}
logger::logln("Logging successful");
Ok(())
}

Ok(false) => {
logger::logln("User not validated");
let name = get_name(&config, ssh_key)?;
if let Err(e) = logger::log(AUTH_LOG_PATH, "SUCCESS", &format!("User: {}", name)) {
if let Err(e) = logger::log(AUTH_LOG_PATH, "Failed", &format!("User: {}", name)) {
println!("Failed to log: {}", e);
}
logger::logln("Logging failed");
match fork() {
Ok(ForkResult::Parent { .. }) => {}
Ok(ForkResult::Child) => {
Expand All @@ -48,7 +56,9 @@ pub fn handle_auth(ssh_host_username: &str, ssh_key: &str) -> Result<()> {
}
Ok(())
}

Err(e) => Err(e).chain_err(|| "Error while validating user from keyhouse"),
Err(e) => {
logger::logln("Error while validating user from keyhouse");
Err(e).chain_err(|| "Error while validating user from keyhouse")
}
}
}
26 changes: 23 additions & 3 deletions src/lib/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ use std::fs::OpenOptions;
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};
use std::io::Result;
use chrono::{DateTime, Utc};

pub fn log(filepath: &str, status: &str, message: &str) -> Result<()> {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards");
let timestamp = since_the_epoch.as_secs();

let log_message = format!("{} - {} - {}\n", timestamp, status, message);
let datetime = DateTime::<Utc>::from(SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(timestamp));
let readable_time = datetime.format("%Y-%m-%d %H:%M:%S").to_string();
let log_message = format!("{} - {} - {}\n", readable_time, status, message);

let mut file = OpenOptions::new()
.append(true)
Expand All @@ -17,4 +19,22 @@ pub fn log(filepath: &str, status: &str, message: &str) -> Result<()> {

file.write_all(log_message.as_bytes())?;
Ok(())
}
}

pub fn logln(message: &str) {
let start = SystemTime::now();
let since_the_epoch = start.duration_since(UNIX_EPOCH).expect("Time went backwards");
let timestamp = since_the_epoch.as_secs();
let datetime = DateTime::<Utc>::from(SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(timestamp));
let readable_time = datetime.format("%Y-%m-%d %H:%M:%S").to_string();
let log_message = format!("{} - {}\n", readable_time, message);

let filepath = "/opt/watchdog/custom-logs/watchdog.logs";
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(filepath).expect("Failed to open log file");


file.write_all(log_message.as_bytes()).expect("Failed to write to log file");
}
6 changes: 5 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use clap::{App, AppSettings, Arg, SubCommand};

use lib::config::{get_config_value, set_config_value};
use lib::errors::Error;

use lib::logger;
use auth::handle_auth;
use ssh::{handle_ssh, handle_ssh_logs};
use su::{handle_su, handle_su_logs};
Expand Down Expand Up @@ -94,6 +94,7 @@ fn main() {
std::process::exit(1);
}
} else if let Some(ref _matches) = matches.subcommand_matches("ssh") {
logger::logln("SSH Command");
if let Err(e) = handle_ssh() {
println!("watchdog-ssh error: {}", e);
print_traceback(e);
Expand All @@ -104,13 +105,16 @@ fn main() {
let keytype = matches.value_of("keytype").unwrap();
let user = matches.value_of("user").unwrap();
let ssh_key = format!("{} {}", keytype, pubkey);
logger::logln(&format!("ssh_key: {}", ssh_key));
if let Err(e) = handle_auth(&user, &ssh_key) {
println!("watchdog-auth error: {}", e);
logger::logln(&format!("watchdog-auth error: {}", e));
print_traceback(e);
std::process::exit(1);
}
} else if let Some(ref matches) = matches.subcommand_matches("logs") {
let filter = matches.value_of("filter").unwrap();
logger::logln(&format!("Filter: {}", filter));
if filter == "all" {
handle_all_logs();
} else if filter == "sudo" {
Expand Down
6 changes: 5 additions & 1 deletion src/ssh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,21 @@ use lib::logger;
use lib::utils::SSH_LOG_PATH;

pub fn handle_ssh() -> Result<()> {
logger::logln("in handle_ssh SSH Command");
let pam_type = env::var("PAM_TYPE")
.chain_err(|| "PAM_TYPE not set. If you are running this by `watchdog ssh`, please don't. It's an internal command, intended to be used by PAM.")?;

logger::logln(&format!("PAM_TYPE: {}", pam_type));
if pam_type == "open_session" {
let config = read_config()?;
init(&config)?;

let env = read_temp_env("/opt/watchdog/ssh_env")?;
logger::logln(&format!("env: {{ ssh_host_username: {}, ssh_key: {} }}", env.ssh_host_username, env.ssh_key));
let name = get_name(&config, &env.ssh_key)?;
if let Err(e) = logger::log(SSH_LOG_PATH, "SUCCESS", &format!("User: {}", name)) {
println!("Failed to log: {}", e);
}
logger::logln("Logging successful");
match fork() {
Ok(ForkResult::Parent { .. }) => {}
Ok(ForkResult::Child) => {
Expand All @@ -38,6 +41,7 @@ pub fn handle_ssh() -> Result<()> {
}

pub fn handle_ssh_logs() {
logger::logln("in handle_ssh_logs");
Command::new("less")
.arg("/opt/watchdog/logs/ssh.logs")
.status()
Expand Down
4 changes: 3 additions & 1 deletion src/sudo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,15 @@ pub fn handle_sudo() -> Result<()> {

let pam_ruser = env::var("PAM_RUSER")
.chain_err(|| "PAM_RUSER not set. If you are running this by `watchdog sudo`, please don't. It's an internal command, intended to be used by PAM.")?;

logger::logln(&format!("PAM_RUSER: {}", pam_ruser));
logger::logln(&format!("PAM_TYPE: {}", pam_type));
if pam_type == "open_session" {
let config = read_config()?;
init(&config)?;
if let Err(e) = logger::log(SUDO_LOG_PATH, "SUCCESS", &format!("User: {}", pam_ruser)) {
println!("Failed to log: {}", e);
}
logger::logln("Logging successful");
match fork() {
Ok(ForkResult::Parent { .. }) => {}
Ok(ForkResult::Child) => {
Expand Down

0 comments on commit f46758a

Please sign in to comment.