DEV Community

Cover image for Day 18 — Building a Linux Vulnerability Analyzer
Hafiz Shamnad
Hafiz Shamnad

Posted on

Day 18 — Building a Linux Vulnerability Analyzer

In most cybersecurity learning paths, people focus on tools first. But sometimes the better exercise is building your own. Today I spent time creating a Linux vulnerability analyzer, a command line tool designed to audit a system and surface common security weaknesses.

The idea is simple: treat the Linux machine like a fortress and walk through it gate by gate. Which services are listening? Which configurations are unsafe? Which permissions look suspicious? A small script can turn those questions into a structured security check.

This tool performs a set of system audits that are commonly part of basic security assessments. It collects system information, inspects open ports, reviews SSH configuration, checks firewall status, enumerates user accounts, and looks for risky file permissions such as world writable files or SUID binaries. It also inspects running services and identifies available package updates that might contain security patches.

What made this project interesting was designing it as a modular scanner. Each security check is treated as its own module, so scans can run individually or as part of a full system audit. This makes it easier to extend later with additional checks such as CVE lookups, Docker scanning, or kernel vulnerability analysis.

Another focus was usability. Security tools are most useful when their output is readable, so the scanner produces a structured CLI report with clear sections and warning indicators. Instead of raw command outputs, the results are organized into human readable summaries that highlight potential issues quickly.

At the end of the scan, the tool generates a concise security overview and can optionally export the findings as a JSON report for further analysis or automation workflows.

Projects like this help reinforce how many security insights come directly from the operating system itself. Linux already exposes a lot of valuable signals through logs, configuration files, and system commands. The challenge is collecting and presenting them in a meaningful way.

Building small security utilities like this is a great way to understand how real auditing tools work under the hood.

Day by day, the goal is simple: learn by building.

Detailed Code Explanation

vulnscan is a Python-based command-line security auditing tool designed to analyze Linux desktops and servers for common security issues.

It performs several checks including:

  • System information collection
  • Open port discovery
  • SSH configuration audit
  • Firewall status verification
  • User account analysis
  • World-writable file detection
  • SUID binary detection
  • Failed login detection
  • Running service enumeration
  • Package update checks

The results are displayed in a structured CLI interface and can also be exported as JSON reports.


1. Shebang and Script Header

#!/usr/bin/env python3
Enter fullscreen mode Exit fullscreen mode

This line tells Linux to run the script using Python 3 from the system environment.

The header comment explains the tool:

vulnscan - Linux Vulnerability Analyzer
A comprehensive security auditing tool with rich CLI output
Enter fullscreen mode Exit fullscreen mode

This indicates the tool is designed to produce clean terminal output using the Rich library.


2. Importing Required Modules

import subprocess
import argparse
import sys
import os
import json
import datetime
from pathlib import Path
Enter fullscreen mode Exit fullscreen mode

Each module serves a purpose:

Module Purpose
subprocess Run Linux shell commands
argparse Handle CLI arguments
os File permission checks
json Export scan results
datetime Timestamp scans
pathlib File path handling

The scanner relies heavily on Linux commands executed via subprocess.


3. Rich CLI Output Support

The tool attempts to import the Rich library.

from rich.console import Console
from rich.table import Table
from rich.panel import Panel
Enter fullscreen mode Exit fullscreen mode

Rich allows:

  • colored output
  • tables
  • progress spinners
  • formatted panels

If Rich is not installed, the tool falls back to plain text mode.

Example fallback logic:

except ImportError:
    RICH = False
Enter fullscreen mode Exit fullscreen mode

A simple console class replaces Rich output.

This ensures the tool works even on minimal systems.


4. Command Execution Helper

def run(cmd: str) -> str:
Enter fullscreen mode Exit fullscreen mode

This function runs shell commands safely.

Example:

subprocess.run(cmd, shell=True, capture_output=True)
Enter fullscreen mode Exit fullscreen mode

Features:

  • Captures stdout
  • Prevents crashes
  • Timeout protection
  • Always returns output

Example usage:

run("uname -r")
Enter fullscreen mode Exit fullscreen mode

Output:

6.5.0-21-generic
Enter fullscreen mode Exit fullscreen mode

5. Status Tag Generator

def _tag(ok: bool) -> str:
Enter fullscreen mode Exit fullscreen mode

Creates status labels for results.

Examples:

✔ OK
✗ WARN
Enter fullscreen mode Exit fullscreen mode

Used when displaying scan results.


6. Section Header Printer

def _section(title: str)
Enter fullscreen mode Exit fullscreen mode

Creates visual separation between scan sections.

Example output:

────────────────── SSH Security Audit ──────────────────
Enter fullscreen mode Exit fullscreen mode

7. System Information Scan

def system_info()
Enter fullscreen mode Exit fullscreen mode

Collects basic system information.

Commands used:

Command Purpose
grep PRETTY_NAME /etc/os-release OS name
uname -r kernel version
uname -m architecture
hostname system hostname
uptime -p system uptime
free -h RAM
df -h disk usage
who logged in users

Example output:

OS: Ubuntu 22.04
Kernel: 6.2
RAM: 8GB
Disk: 40% used
Enter fullscreen mode Exit fullscreen mode

This helps identify outdated or unsupported systems.


8. Open Port Detection

def open_ports()
Enter fullscreen mode Exit fullscreen mode

Uses:

ss -tuln
Enter fullscreen mode Exit fullscreen mode

This lists:

  • TCP ports
  • UDP ports
  • listening services

Example output:

tcp LISTEN 0.0.0.0:22
tcp LISTEN 0.0.0.0:80
Enter fullscreen mode Exit fullscreen mode

Open ports can expose services to attackers.


9. SSH Security Audit

def ssh_audit()
Enter fullscreen mode Exit fullscreen mode

Analyzes /etc/ssh/sshd_config.

Checks include:

Setting Risk
PermitRootLogin attackers login as root
PasswordAuthentication brute force risk
PermitEmptyPasswords empty password accounts
Protocol insecure SSH v1
MaxAuthTries brute force attempts
LoginGraceTime session hijacking window

Example result:

PermitRootLogin = yes   WARN
PasswordAuthentication = yes   WARN
Protocol = 2   OK
Enter fullscreen mode Exit fullscreen mode

This helps detect weak SSH configurations.


10. Firewall Status Check

def firewall_check()
Enter fullscreen mode Exit fullscreen mode

Checks three firewall systems:

UFW

ufw status
Enter fullscreen mode Exit fullscreen mode

iptables

iptables -L INPUT
Enter fullscreen mode Exit fullscreen mode

firewalld

systemctl is-active firewalld
Enter fullscreen mode Exit fullscreen mode

Example result:

UFW: inactive
iptables rules: 3
firewalld: inactive
Enter fullscreen mode Exit fullscreen mode

A disabled firewall is a major security risk.


11. User Account Audit

def user_audit()
Enter fullscreen mode Exit fullscreen mode

Reads:

/etc/passwd
Enter fullscreen mode Exit fullscreen mode

Extracts:

  • username
  • UID
  • home directory
  • shell

Important checks:

  • interactive shells
  • sudo users
  • root accounts

Example:

user1 uid=1000 shell=/bin/bash
root uid=0 sudo
Enter fullscreen mode Exit fullscreen mode

Privilege escalation often targets misconfigured user accounts.


12. World Writable File Scan

def world_writable()
Enter fullscreen mode Exit fullscreen mode

Runs:

find / -perm -0002
Enter fullscreen mode Exit fullscreen mode

This identifies files any user can modify.

Example:

/tmp/testfile
Enter fullscreen mode Exit fullscreen mode

These files can be abused for privilege escalation.


13. SUID Binary Detection

def suid_files()
Enter fullscreen mode Exit fullscreen mode

Command:

find / -perm -4000
Enter fullscreen mode Exit fullscreen mode

SUID files execute with root privileges.

Example:

/usr/bin/passwd
/usr/bin/sudo
Enter fullscreen mode Exit fullscreen mode

Attackers often exploit vulnerable SUID binaries.


14. Failed Login Detection

def failed_logins()
Enter fullscreen mode Exit fullscreen mode

Checks:

lastb
Enter fullscreen mode Exit fullscreen mode

If unavailable:

journalctl sshd
Enter fullscreen mode Exit fullscreen mode

This identifies brute force attempts.

Example:

Failed password for root from 192.168.1.10
Enter fullscreen mode Exit fullscreen mode

15. Running Services

def running_services()
Enter fullscreen mode Exit fullscreen mode

Uses:

systemctl list-units --type=service
Enter fullscreen mode Exit fullscreen mode

Example output:

ssh.service
nginx.service
mysql.service
Enter fullscreen mode Exit fullscreen mode

Attack surface increases with more running services.


16. Package Update Check

def package_updates()
Enter fullscreen mode Exit fullscreen mode

Detects package manager automatically:

Manager Command
APT apt list --upgradable
DNF/YUM dnf check-update

Example result:

Upgradable packages: 12
Security updates: 3
Enter fullscreen mode Exit fullscreen mode

Outdated packages often contain known CVEs.


17. Display Functions

Several display functions format scan results.

Examples:

display_ports()
display_users()
display_services()
Enter fullscreen mode Exit fullscreen mode

When Rich is enabled, results appear as tables.

Example:

Proto   State     Address
tcp     LISTEN    0.0.0.0:22
Enter fullscreen mode Exit fullscreen mode

18. Scan Summary

def display_summary()
Enter fullscreen mode Exit fullscreen mode

Counts warnings such as:

  • insecure SSH settings
  • world writable files

Example:

Scan completed: 2026-03-06 10:20
Warnings found: 4
Enter fullscreen mode Exit fullscreen mode

19. JSON Export

def export_json()
Enter fullscreen mode Exit fullscreen mode

Allows exporting scan results:

vulnscan --export report.json
Enter fullscreen mode Exit fullscreen mode

Example output file:

{
 "ssh": {...},
 "ports": {...}
}
Enter fullscreen mode Exit fullscreen mode

Useful for:

  • automation
  • SIEM ingestion
  • reporting

20. CLI Argument Parsing

Handled using argparse.

Example commands:

Run full scan

vulnscan
Enter fullscreen mode Exit fullscreen mode

Run specific modules

vulnscan -m ssh firewall ports
Enter fullscreen mode Exit fullscreen mode

Export report

vulnscan --export report.json
Enter fullscreen mode Exit fullscreen mode

List modules

vulnscan --list
Enter fullscreen mode Exit fullscreen mode

Quiet mode

vulnscan -q
Enter fullscreen mode Exit fullscreen mode

21. Module System

Modules are defined in a dictionary:

MODULES = {
    "system": system_info,
    "ports": open_ports
}
Enter fullscreen mode Exit fullscreen mode

This makes the scanner modular and extensible.

Adding new checks becomes easy.


22. Main Function

The main function orchestrates everything:

  1. Parse CLI arguments
  2. Select modules
  3. Run scans
  4. Display results
  5. Export report

Flow:

Parse arguments
↓
Run selected modules
↓
Display results
↓
Export report (optional)
Enter fullscreen mode Exit fullscreen mode

Final Outcome

vulnscan provides a quick security overview of a Linux system.



Capabilities include:

  • System auditing
  • SSH security analysis
  • Firewall detection
  • Port discovery
  • Permission checks
  • User privilege analysis
  • Service enumeration
  • Package update checks

Possible Future Improvements

To make the tool even more powerful:

  • CVE lookup via NVD API
  • Docker container scanning
  • Cron job auditing
  • Kernel vulnerability detection
  • Risk scoring engine
  • HTML security reports
  • CIS benchmark checks

Summary

Tools that analyze Linux security often look similar on the surface, but they are built for very different moments in a security workflow.

My Linux vulnerability analyzer focuses on security auditing and system hygiene. It checks things like SSH configuration, firewall status, open ports, user privileges, file permissions, and available package updates. The goal is to give administrators or learners a clear overview of how securely a system is configured and highlight areas that need improvement.

In contrast, LinPEAS is designed for a completely different scenario. It is used after an attacker or penetration tester already has access to a machine and wants to discover privilege escalation paths. Instead of auditing configuration health, it searches aggressively for ways to gain higher privileges such as sudo misconfigurations, writable services, exposed credentials, or kernel exploits.

So while both tools analyze a Linux system, their goals differ:

  • A vulnerability analyzer helps defenders audit and harden systems.
  • LinPEAS helps attackers or penetration testers find ways to escalate privileges.

Understanding this distinction is important because security is not just about breaking systems, but also about building and maintaining them securely.

Top comments (0)