Kali Linux Full Stack Guide: From File System to Enterprise-Level Security Deployment Practice

Kali Linux Full Stack Guide: From File System to Enterprise-Level Security Deployment Practice

1. Detailed Explanation of Core Directories in the File System

1. /etc Directory: The Central Configuration Hub

/etc is the core configuration directory of the Linux system, containing critical configuration files for networking, users, services, etc. Typical cases include:

  • Network Configuration: The <span>/etc/network/interfaces</span> file defines static IP configuration:
    auto eth0
    iface eth0 inet static
    address 192.168.1.100
    netmask 255.255.255.0
    gateway 192.168.1.1
    dns-nameservers 8.8.8.8
  • Software Source Management: Switch to the USTC mirror source by modifying <span>/etc/apt/sources.list</span>:
    deb http://mirrors.ustc.edu.cn/kali kali-rolling main non-free contrib
    deb-src http://mirrors.ustc.edu.cn/kali kali-rolling main non-free contrib
  • Service Configuration: The SSH service configuration file <span>/etc/ssh/sshd_config</span> allows root login:
    PermitRootLogin yes

2. /var Directory: Dynamic Data Storage

/var is used to store runtime data, with key subdirectories including:

  • Log Files: The <span>/var/log/auth.log</span> records user authentication logs, which can be monitored in real-time with the following command:
    tail -f /var/log/auth.log
  • Cache Data: The <span>/var/cache/apt/archives</span> stores downloaded packages, and periodic cleaning can free up space:
    sudo apt clean
  • Temporary Files: The <span>/var/tmp</span> stores temporary files that need to persist across reboots, unlike <span>/tmp</span>, which are automatically deleted after a reboot.

3. /home Directory: User Data Isolation

Each user has an independent subdirectory, with permissions set to <span>755</span> (full control for the owner, read-only for other users). Typical operations include:

  • Create User-Specific Directory:
    sudo mkdir /home/testuser/projects
    sudo chown testuser:testuser /home/testuser/projects
  • Restrict Directory Access: Use <span>chmod 700</span> to prohibit access by other users:
    chmod 700 /home/testuser/private_data

2. Practical Permission Management

1. chmod: Fine Control of File Permissions

Symbolic Mode Example:

chmod u=rwx,g=rx,o= test.sh  # Owner has full permissions, group has read+execute, others have no permissions
chmod a+w config.ini         # All users add write permissions

Numeric Mode Example:

chmod 750 /var/www/html      # Owner has full permissions, group has read+execute, others have no permissions
chmod 644 report.txt         # Owner has read+write, others have read only

2. chown: Change File Ownership

Single File Modification:

sudo chown root:root /etc/sudoers  # Return ownership of the sudoers file to root

Recursive Directory Modification:

sudo chown -R www-data:www-data /var/www  # Transfer ownership of the website directory to the web server user

3. sudo: Permission Elevation Mechanism

Configure sudo Permissions:

  1. 1. Edit the <span>/etc/sudoers</span> file (use the <span>visudo</span> command for safe editing):
    testuser ALL=(ALL) NOPASSWD: /usr/bin/apt, /usr/bin/systemctl
  2. 2. Verify Configuration:
    sudo -l -U testuser  # View testuser's sudo permissions

Typical Use Cases:

sudo systemctl restart apache2  # Restart service with root permissions
sudo -u postgres psql          # Execute command as postgres user

3. Advanced User Group Configuration

1. User Group Management Commands

  • Create Group:
    sudo groupadd developers
  • Change User’s Primary Group:
    sudo usermod -g developers alice  # Change alice's primary group to developers
  • Add to Supplementary Group:
    sudo usermod -aG sudo bob  # Add bob to the sudo group (keeping existing groups)

2. Practical Case: Team Project Permission Control

Requirement: Create a shared directory <span>/projects/alpha</span> with the following requirements:

  • • Owner: admin (read, write, execute)
  • • Group: developers (read, write, execute)
  • • Other users: read only

Implementation Steps:

sudo mkdir /projects/alpha
sudo chown admin:developers /projects/alpha
sudo chmod 775 /projects/alpha

Verify Effect:

ls -ld /projects/alpha  # Output should be drwxrwxr-x

4. Advanced Vim Editing Techniques

1. Find and Replace

Basic Replacement:

:%s/old_text/new_text/g  # Global replacement
:5,10s/foo/bar/gc        # Replace lines 5-10 and confirm

Regex Replacement:

:%s/\b\d{3}-\d{4}\b/XXX-XXXX/g  # Replace phone number format

2. Multi-Window Management

Horizontal Split:

:sp /etc/nginx/nginx.conf  # Open a new file and split horizontally

Vertical Split:

:vsp ~/.bashrc  # Open a new file and split vertically

Window Navigation:

Ctrl+w w  # Cycle through windows
Ctrl+w h  # Jump to the left window
Ctrl+w j  # Jump to the lower window

3. Practical Case: Batch Modify Configuration Files

Requirement: Change all <span>.conf</span> files to replace <span>listen 80</span> with <span>listen 8080</span>

Solution:

:args **/*.conf  # Load all conf files into the argument list
:argdo %s/listen 80/listen 8080/ge | update  # Batch replace and save

5. In-Depth Practice of Network Configuration

1. ifconfig Alternative: ip Command

Modern systems recommend using the <span>ip</span> command as a replacement for the deprecated <span>ifconfig</span>:

ip addr show eth0      # View IP address
ip link set eth0 down  # Disable network interface
ip link set eth0 up    # Enable network interface

2. netstat Alternative: ss Command

ss -tulnp  # View all listening ports and corresponding processes
ss -s      # Display network connection statistics

3. Basic iptables Rules

Allow SSH Access:

sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

Port Forwarding:

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

Save Rules (requires installation of iptables-persistent):

sudo netfilter-persistent save

6. Core of Shell Script Programming

1. Variables and References

#!/bin/bash

# Variable Definition
USER="kali"
PATH="$PATH:/usr/local/bin"

# Special Variables
echo "Script Name: $0"
echo "Number of Parameters: $#"
echo "All Parameters: $@"

# Command Substitution
CURRENT_IP=$(hostname -I | awk '{print $1}')

2. Conditional Statements

Numeric Comparison:

if [ "$1" -gt 100 ]; then
    echo "Parameter greater than 100"
elif [ "$1" -eq 100 ]; then
    echo "Parameter equals 100"
else
    echo "Parameter less than 100"
fi

String Comparison:

if [ "$USER" = "root" ]; then
    echo "Current user is root"
fi

File Test:

if [ -f "/etc/passwd" ]; then
    echo "passwd file exists"
fi

3. Loop Structures

for Loop:

# Numeric Range
for i in {1..5}; do
    echo "Iteration Count: $i"
done

# File Traversal
for file in *.log; do
    gzip "$file"
done

while Loop:

# Read File Content
while IFS= read -r line; do
    echo "Processing Line: $line"
done < /etc/hosts

# Numeric Condition
count=1
while [ $count -le 5 ]; do
    echo "Count: $count"
    ((count++))
done

4. Practical Case: Log Analysis Script

Requirement: Count the source IPs of requests with status code 404 in the Nginx access log

#!/bin/bash

LOG_FILE="/var/log/nginx/access.log"
REPORT_FILE="/tmp/404_report.txt"

# Clear old report
> "$REPORT_FILE"

# Extract 404 request IPs and count
awk '$9 == "404" {print $1}' "$LOG_FILE" | sort | uniq -c | sort -nr > "$REPORT_FILE"

# Output results
echo "404 Error Request Statistics:"
cat "$REPORT_FILE"

# Send email notification (requires mailutils configuration)
if [ -s "$REPORT_FILE" ]; then
    mail -s "404 Error Alert" [email protected] < "$REPORT_FILE"
fi

7. Comprehensive Practice: Deploying a Web Server

1. Install Necessary Software

sudo apt update
sudo apt install -y nginx php-fpm mariadb-server

2. Configure Database

sudo mysql_secure_installation  # Secure initialization

# Create database and user
sudo mysql -e "CREATE DATABASE wordpress;"
sudo mysql -e "GRANT ALL PRIVILEGES ON wordpress.* TO 'wpuser'@'localhost' IDENTIFIED BY 'securepassword';"
sudo mysql -e "FLUSH PRIVILEGES;"

3. Configure Nginx

Edit <span>/etc/nginx/sites-available/wordpress</span>:

server {
    listen 80;
    server_name example.com;
    root /var/www/wordpress;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    }
}

Enable configuration and restart services:

sudo ln -s /etc/nginx/sites-available/wordpress /etc/nginx/sites-enabled/
sudo systemctl restart nginx php7.4-fpm

4. Deploy WordPress

sudo wget https://wordpress.org/latest.tar.gz
sudo tar -xzf latest.tar.gz -C /var/www/
sudo chown -R www-data:www-data /var/www/wordpress

Access the server IP via a browser to complete the installation wizard, using the previously created database credentials.

8. Security Hardening Recommendations

  1. 1. Firewall Configuration:
    sudo ufw default deny incoming
    sudo ufw allow 22/tcp  # SSH
    sudo ufw allow 80/tcp  # HTTP
    sudo ufw allow 443/tcp # HTTPS
    sudo ufw enable
  2. 2. Failed Login Limit: Edit <span>/etc/security/limits.conf</span> to add:
    * hard maxlogins 3
    * soft core 0
  3. 3. Regular Updates:
    sudo apt update && sudo apt upgrade -y
    sudo unattended-upgrades  # Enable automatic updates
  4. 4. Audit Log Monitoring:
    sudo apt install -y auditd
    sudo auditctl -w /etc/passwd -p wa -k passwd_changes
    sudo auditctl -w /etc/shadow -p wa -k shadow_changes

Through this systematic operational guide, you have mastered the complete skill set of Kali Linux from basic file management to advanced script programming. It is recommended to practice in real environments according to specific needs, gradually building your own security operation toolset.

Leave a Comment