server_forge/
security.rs

1//! # Security Module
2//!
3//! This module provides functions for implementing various security measures on a Linux server.
4//! It includes functionality for configuring Fail2Ban, setting up advanced security measures
5//! (SELinux or AppArmor), implementing rootkit detection, and scheduling regular security scans.
6
7use crate::config::Config;
8use crate::distro::{get_package_manager, PackageManager};
9use crate::rollback::RollbackManager;
10use crate::utils::run_command;
11use log::info;
12use std::error::Error;
13
14/// Implements all security measures based on the provided configuration.
15///
16/// This function orchestrates the implementation of various security measures including:
17/// - Configuring Fail2Ban
18/// - Setting up advanced security (SELinux or AppArmor)
19/// - Setting up rootkit detection
20/// - Configuring regular security scans
21///
22/// # Arguments
23///
24/// * `config` - A reference to the `Config` struct containing user-defined configuration options
25/// * `rollback` - A reference to the `RollbackManager` for managing system state
26///
27/// # Errors
28///
29/// Returns an error if any of the security measures fail to implement
30pub fn implement_security_measures(
31    config: &Config,
32    rollback: &RollbackManager,
33) -> Result<(), Box<dyn Error>> {
34    info!("Implementing security measures...");
35
36    let snapshot = rollback.create_snapshot()?;
37
38    configure_fail2ban()?;
39    setup_advanced_security(config)?;
40    setup_rootkit_detection(config)?;
41    setup_security_scans()?;
42
43    rollback.commit_snapshot(snapshot)?;
44
45    info!("Security measures implemented");
46    Ok(())
47}
48
49/// Configures and starts the Fail2Ban service.
50///
51/// This function installs Fail2Ban, creates a basic configuration for SSH,
52/// and starts the Fail2Ban service.
53///
54/// # Errors
55///
56/// Returns an error if Fail2Ban installation or configuration fails
57pub fn configure_fail2ban() -> Result<(), Box<dyn Error>> {
58    let package_manager = get_package_manager()?;
59    match package_manager {
60        PackageManager::Apt => run_command("apt", &["install", "-y", "fail2ban"])?,
61        PackageManager::Yum => run_command("yum", &["install", "-y", "fail2ban"])?,
62        PackageManager::Dnf => run_command("dnf", &["install", "-y", "fail2ban"])?,
63    }
64
65    let fail2ban_config = r#"
66[sshd]
67enabled = true
68port = ssh
69filter = sshd
70logpath = /var/log/auth.log
71maxretry = 3
72bantime = 3600
73"#;
74    std::fs::write("/etc/fail2ban/jail.local", fail2ban_config)?;
75
76    run_command("systemctl", &["enable", "fail2ban"])?;
77    run_command("systemctl", &["start", "fail2ban"])?;
78
79    Ok(())
80}
81
82/// Sets up advanced security measures based on the Linux distribution.
83///
84/// For Ubuntu, this function sets up AppArmor.
85/// For CentOS or Fedora, this function sets up SELinux.
86///
87/// # Arguments
88///
89/// * `config` - A reference to the `Config` struct containing user-defined configuration options
90///
91/// # Errors
92///
93/// Returns an error if the setup fails or if the Linux distribution is not supported
94pub fn setup_advanced_security(config: &Config) -> Result<(), Box<dyn Error>> {
95    if config.security_level == "advanced" {
96        // Enable and configure SELinux or AppArmor based on the distribution
97        match config.linux_distro.as_str() {
98            "ubuntu" => {
99                run_command("apt", &["install", "-y", "apparmor", "apparmor-utils"])?;
100                run_command("aa-enforce", &["/etc/apparmor.d/*"])?;
101            }
102            "centos" | "fedora" => {
103                run_command(
104                    "yum",
105                    &["install", "-y", "selinux-policy", "selinux-policy-targeted"],
106                )?;
107                std::fs::write(
108                    "/etc/selinux/config",
109                    "SELINUX=enforcing\nSELINUXTYPE=targeted\n",
110                )?;
111            }
112            _ => return Err("Unsupported Linux distribution for advanced security".into()),
113        }
114    }
115    Ok(())
116}
117
118/// Sets up rootkit detection tools (rkhunter and chkrootkit).
119///
120/// This function installs rkhunter and chkrootkit, then updates the rkhunter database.
121///
122/// # Arguments
123///
124/// * `config` - A reference to the `Config` struct (unused in the current implementation)
125///
126/// # Errors
127///
128/// Returns an error if installation or configuration of rootkit detection tools fails
129pub fn setup_rootkit_detection(config: &Config) -> Result<(), Box<dyn Error>> {
130    let package_manager = get_package_manager()?;
131    match package_manager {
132        PackageManager::Apt => run_command("apt", &["install", "-y", "rkhunter", "chkrootkit"])?,
133        PackageManager::Yum => run_command("yum", &["install", "-y", "rkhunter", "chkrootkit"])?,
134        PackageManager::Dnf => run_command("dnf", &["install", "-y", "rkhunter", "chkrootkit"])?,
135    }
136
137    // Update rkhunter database
138    run_command("rkhunter", &["--update"])?;
139    run_command("rkhunter", &["--propupd"])?;
140
141    Ok(())
142}
143
144/// Sets up regular security scans using rkhunter and chkrootkit.
145///
146/// This function creates a script to run both rkhunter and chkrootkit,
147/// then sets up a weekly cron job to execute this script.
148///
149/// # Errors
150///
151/// Returns an error if creating the script or setting up the cron job fails
152pub fn setup_security_scans() -> Result<(), Box<dyn Error>> {
153    let scan_script = r#"#!/bin/bash
154rkhunter --check --skip-keypress
155chkrootkit
156"#;
157    std::fs::write("/usr/local/bin/security_scan.sh", scan_script)?;
158    run_command("chmod", &["+x", "/usr/local/bin/security_scan.sh"])?;
159
160    // Add weekly cron job for security scans
161    let cron_job =
162        "0 2 * * 0 root /usr/local/bin/security_scan.sh > /var/log/security_scan.log 2>&1\n";
163    std::fs::write("/etc/cron.d/security_scan", cron_job)?;
164
165    Ok(())
166}