❌

Reading view

There are new articles available, click to refresh the page.

PowerShell: Moving from Bash to PowerShell

Welcome back, hackers!

When moving from Bash to PowerShell, people often run into difficulties simply because they do not know which tools in PowerShell serve as equivalents and how to use them. For example, I personally like Bash for its straightforward logic. If you need to grab only certain lines from a text file, you know you can call on cat and grep. But when you try to type something similar in PowerShell, it often feels like hitting a wall. You know the logic, you know it should be just a one-liner, yet you get stuck on how to actually do it. That is exactly what we are going to sort out today.Β 

This article serves as an addition to PowerShell for Hackers: Basics and aims to show more of PowerShell’s capabilities by mapping familiar Bash commands to their PowerShell equivalents. If you haven’t read PowerShell for Hackers: Basics, we highly recommend starting there. This guide is written for people who know the Linux command line and want practical examples for their workflows in PowerShell.

General Rules of the Game

Let’s start with the most basic thing, which is still very important, it is working with variables. In Bash, declaring a variable is as simple as writing foo=1. In PowerShell, you need to add a dollar sign: $foo=1. To print the value of a variable to the screen, you can use the universal echo or the PowerShell-specific cmdlet Write-Host. Is it longer? Definitely. But the benefit is that with Write-Host you can control the output in interesting ways:

PS > Write-Host (2,4,6,8,10,12) -Separator "->" -ForegroundColor DarkMagenta -BackgroundColor White

working with flags in powershell

This snippet will print the sequence of numbers inside the parentheses, place a -> between them, and also change both the text and the background colors. For a quick throwaway script this isn’t necessary, but for a daily report it might be quite useful.

If you need to compare something PowerShell has a full set of operators, familiar to anyone coming from Linux.

working with powershell operators

If comparison operators and logical conditions are more or less clear, let’s look at a very simple but practical example with data types. Suppose we want to measure the average response time from a website like google.com. To do this we need to send several pings and calculate the average. Here’s a short script:

Write-Host `n "Waiting for test ..."
$Avg = 0
$Site = "www.google.com"
$PingSite = Test-Connection -Count 5 $Site
$Avg = ($PingSite | Measure-Object ResponseTime -Average)
$Calc = ($Avg.Average) -as [int]
Clear-Host
Write-Host "Average response time to $Site is $Calc ms"

working with powershell variables

If we don’t cast the value to an integer, we get a floating-point number, which isn’t very convenient for this purpose.
This is one of the instances where a PowerShell command is actually stronger than the classic Linux ping. The Test-Connection cmdlet outputs structured objects that already contain response times, status, and other useful properties. That means you can pipe the results directly into tools like Measure-Object and do math on them without needing to parse text with awk or grep. In Linux, ping is text-based, so you often need extra commands to extract the numbers. PowerShell skips that step

Aliases

To make PowerShell easier to use, you can create aliases. It’s worth checking the aliases already available on your system with:

PS > Get-Alias

listing aliases

Aliases can even point to programs. For example, let’s make an alias for launching the calculator:

PS > Set-Alias -Name calc -Value calc.exe

setting a new alias in powershell

Now typing calc will start the calculator. If you want your alias to represent a command with parameters, you need to wrap it in a function:

function AL01 { Test-Connection -Count 2 google.com }
Set-Alias ping AL01

Now when you type ping, it will perform two pings to google.com. To remove an alias, use:

PS > Remove-Item alias:ping

Note, once you close PowerShell, all aliases you created this way disappear. To keep them permanently, you need to save them in your profile. PowerShell actually has four possible profiles. You can see them with:

PS > $profile | Format-List -Force

listing powershell proiflees

To check if they exist on your system:

PS > $profile | Format-List -Force | ForEach-Object { Test-Path $_ }

If the result is False, the file simply doesn’t exist. You can create it, for example, at this path:

PS > notepad.exe C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1

And add your aliases inside it:

function AL01 { Test-Connection -Count 2 google.com }
Set-Alias ping AL01

creating a powershell profile

After saving and restarting PowerShell, your aliases will load automatically.

One important note. By default, Windows blocks the execution of external scripts. This means your profile file might be ignored. To check the current policy, run:

PS > Get-ExecutionPolicy

Most likely it will return Restricted, which means all scripts are blocked. To allow your profile script to run, you need to open PowerShell as Administrator and set:

PS > Set-ExecutionPolicy Unrestricted

setting execution policy to unrestricted

After confirmation, scripts will run normally, including your profile file.

using aliases in powershell

Going Deeper

Now let’s move on to the most popular Linux tools and their PowerShell equivalents, from simple to more advanced.

cd

Navigation between directories. You can use the familiar cd alias or the cmdlet Set-Location:

PS > Set-Location Windows

This moves you to the Windows folder in the current directory. PowerShell even lets you navigate the registry the same way:

PS > Set-Location -Path "HKLM:"

PS > Set-Location -Path "HKEY_LOCAL_MACHINE\SYSTEM\Software\Microsoft\CTF"

using cd in powershell

ls

To view the contents of a directory, use ls, dir, or the cmdlet Get-ChildItem:

PS > Get-ChildItem C:\

listing files in powershell

This shows everything on the C: drive. To sort results by modification time (like ls -ltr in Linux):

PS > Get-ChildItem $env:USERPROFILE\Documents | Sort-Object -Property LastWriteTime

using sort in powershell

For recursive searches:

PS > Get-ChildItem -Path C:\ -Force -Recurse

mkdir

To create directories, use New-Item:

PS > New-Item -ItemType Directory -Name intel

Or to create a subfolder:

PS > New-Item -ItemType "directory" -Path "c:\intel\papers"

creating directories with powershell

You can even create a text file with content in one command:

PS > New-Item -Path . -Name "key.txt" -ItemType "file" -Value "HSDAF8KL"

creating files with ontent in powershell

touch

Creating files also uses New-Item:

PS > New-Item -ItemType "file" -Path "c:\temp\file.txt", "C:\intel\papers\classified.txt"

This makes two files in different folders.

cp

Copying files is done with Copy-Item:

PS > Copy-Item -Path C:\intel\classified.txt -Destination C:\important\

It also works over the network:

PS > Copy-Item -Path C:\key.txt -Destination '\\file-srv\f$\key.txt'

rm

Deleting files is Remove-Item. The dangerous rm -rf equivalent is:

PS > Remove-Item -Recurse -Force

Like in Linux, it’s one of the most dangerous commands. A single mistake can wipe entire directories. It’s a good practice to first preview what will be deleted with Get-ChildItem, or even rename files instead of deleting them to make recovery easier.

You can also delete by masks:

PS > Remove-Item *.txt

Or specific files:

PS > Remove-Item C:\dir1\records, C:\dir1\photos, C:\dir2\interrogations

find

To search for files, use Get-ChildItem with filters. For example:

PS > Get-ChildItem C:\ -Include *.exe -Recurse

This found all .exe files on C:\ but you can also limit depth:

PS > Get-ChildItem -Path "C:\Files\*.exe" -Filter "*software*" -Depth 2 -Exclude "*server*" -Recurse

Notice how flexible the filtering is. Often you don’t need regular expressions.

cat

To read files use Get-Content or gc:

PS > Get-Content -Path C:\case\script.txt

tail

To see the last ten lines of a file:

PS > Get-Content c:\logs\log.txt -TotalCount 10

To monitor in real time:

PS > Get-Content "C:\logs\log.txt" -Wait | Where { $_ -Match "Error" }

This shows new lines containing β€œError” as they appear.

grep

PowerShell doesn’t have a perfect grep equivalent, but there are alternatives. To filter objects, use Where-Object.

List processes using more than 100 MB of memory:

PS > Get-Process | Where-Object { $_.WorkingSet -gt 104857600 }

using grep in powershell

For text searches, use Select-String to find the string that mentions your keyword:

PS > Select-String -Path C:\logs\*.log -Pattern "error"

Or combine with Get-Content:

PS > Get-Content -Path C:\scripts\script.txt | Select-String -Pattern "alias"

uname

To display system information:

PS > $Properties = 'Caption', 'CSName', 'Version', 'BuildType', 'OSArchitecture'; Get-CimInstance Win32_OperatingSystem | Select-Object $Properties | Format-Table -AutoSize

Longer than uname -a, but you can alias it if needed. At the end of the day, you don’t really use it much.

mkfs

To create filesystems, PowerShell has New-Volume and Format-Volume:

PS > New-Volume -StoragePoolName "CompanyData" -FriendlyName "TestVolume" -Size 10GB -ResiliencySettingName "Mirror" -FileSystem NTFS -AccessPath "M:" -ProvisioningType Fixed

Be careful, as misuse can destroy your data. Always test on a safe machine first.

ping

The classic ping equivalent is Test-Connection:

PS > Test-Connection google.com

cut

To extract only certain fields, use Select-Object. For example, to list text files in your user folder but only show names and sizes:

PS > Get-ChildItem $env:USERPROFILE -Filter "*.txt" | Select-Object -Property 'Name', 'Length'

man

The man equivalent is Get-Help:

PS > Get-Help Get-ChildItem

You can also use wildcards:

PS > Get-Help Get-*

Conclusion

As you can see, almost every Linux command has a worthy PowerShell counterpart. Some of them are less elegant or more verbose, but in return they often give you more power through structured objects and richer filtering. Bash and PowerShell approach the same problems from different angles. Bash is all about short, sharp one-liners, a language of quick hacks and piping small tools together. PowerShell takes more words to get going, but it pays you back with depth. Its cmdlets work with objects instead of plain text, which means more precision and flexibility. A job that takes three or four utilities strung together in Bash can sometimes be handled by a single cmdlet.

The transition isn’t painless. The syntax can feel verbose and the patterns unfamiliar. It looks like you’re doing more typing for the same result. In the end, it all comes down to habit and practice. PowerShell is essentially a full toolbox, while Bash is a handy pocket knife. The more you experiment and analyze, the more natural it will feel.

The post PowerShell: Moving from Bash to PowerShell first appeared on Hackers Arise.

The One-Man APT with Artificial Intelligence, Part III: From Zero to Local Dominance

By: Smouk

With in-memory execution and simulated exfiltration already in place, the next step was obvious: persistence. Advanced threats like Koske don’t just run onceβ€”they stay alive, blend into the system, and return after every reboot. That’s exactly what I set out to replicate in this phase.

The goal? To see if the AI could not only generate payloads that behave like persistent malware, but also suggest and configure real-world persistence mechanisms like systemd services or .bashrc entriesβ€”again, without me writing any code manually.

Let’s see how far the AI can go when asked to survive a reboot.

Simulated Attack Chain: Building Complexity

At this stage, the challenge escalates. Instead of focusing on isolated behaviors like beaconing or exfiltration, I asked the AI to generate a safe, all-in-one payload that could simulate a full attack chain. The idea was to build a structured sequence of actionsβ€”like compiling a fake binary, faking persistence, collecting environment data, and retrieving a fileβ€”mirroring the complexity of how real APTs like Koske operate.

The AI responded with a well-structured, harmless payload that compiles a dummy C program (fakerootkit), creates a marker file to simulate persistence (persistence_demo.txt), collects system info (cpu_check.txt), and downloads a PDF disguised as a cryptominer. All of this is packed into a polyglot image that can be triggered with a single commandβ€”just like earlier stages.

From here on, each request I make builds on the last, and the behavior becomes increasingly layered. This is where the simulation begins to truly reflect the modular, adaptive structure of a real-world APTβ€”only it’s being built entirely through natural language prompts.

Bypassing AI Limitations: Changing the Assembly Vector

As I continued expanding the complexity of the simulation, I hit a wall: the AI stopped generating polyglot images directly, likely due to internal safety filters. But rather than breaking the experiment’s core ruleβ€”no manual payload writingβ€”I took a different approach. I asked the AI to give me a Python script that could generate the image locally.

The result was a clean, minimal script that uses the PIL library to create a basic JPEG image, then appends a harmless shell payload that opens a terminal and runs whoami. The AI provided everything: image generation, payload logic, encoding, and the binary append operationβ€”effectively giving me the same polyglot result, just via a different toolchain.

This moment reflected a real-world tactic perfectly: when direct delivery fails, an APT often falls back to alternative methods like packer-based generation or local compilation. Here, the AI simulated that behavior without being asked toβ€”and kept the flow going.

Payload Assembly Without Manual Scripting

To stay within the bounds of the experiment, I didn’t manually write or alter the payload logic. Instead, I simply copied and pasted the code provided by the AIβ€”line by lineβ€”into a local environment, using it exactly as delivered. The full simulated attack chain was now assembled via Python: fake binary compilation, mock persistence, system enumeration, and simulated cryptominer download.

This approach preserved the project’s core rule: I was still not writing code myselfβ€”the AI was doing all the work. The only difference was that now, instead of delivering a final image, it handed me the blueprints. And in real-world terms, this mimics the shift from payload delivery to toolkits and buildersβ€”exactly the kind of modularity we see in modern APT ecosystems like Koske.

Final Execution: Complete Polyglot Delivery Chain

For this phase, the objective was clear: demonstrate a full local execution chain that accurately reflects the behavior of the targeted APT β€” but using only safe, demonstrative payloads.

This time, the image wasn’t delivered directly. Due to AI restrictions, I adapted the approach by requesting a Python script that would locally generate the final polyglot image. The script would:

  • Create a simple JPEG file
  • Embed the full simulated attack chain as a shell payload

Once executed, the generated image (polyglot_terminal_whoami.jpg) behaved exactly as expected. Upon triggering it with the terminal command:

grep -a -A9999 β€œ# PAYLOAD” polyglot_terminal_whoami.jpg | bash

The image executed a chain that:

  • Compiled a harmless β€œfakerootkit” binary
  • Simulated persistence via a timestamped text file
  • Collected CPU information into a local dump
  • Downloaded the PDF (β€œLinux Basics for Hackers 2 ed”) as a stand-in for staged payload delivery

All steps ran in sequence, without errors, cleanly emulating the kind of behavior observed in staged APT attacks β€” from initial execution, to local recon, to staged download activity.

Summary

This third stage marked a major technical leap in our emulation of the APT’s behavior. Faced with limitations in image payload generation, we adapted by leveraging Python to produce fully functional polyglot JPEGs locally.

The resulting image executed a complete mock attack chain: compiling a fake binary, simulating persistence, collecting system info, and downloading a decoy PDF β€” each step carefully reflecting the operational flow of the APT. By shifting to script-based generation while maintaining payload integrity, we advanced our alignment with the adversary’s methodology without compromising control or structure.

There’s something else I haven’t revealed yet β€” in an upcoming entry, I’ll show how, through the same sequence of prompts used in this project, I was able to obtain a fully functional rootkit for Linux. Stay tuned β€” I’ll be back soon.

Until next time…

Smouk out!

The post The One-Man APT with Artificial Intelligence, Part III: From Zero to Local Dominance first appeared on Hackers Arise.

Python Basics for Hackers: Building a Wi-Fi Scanner Capable of Locating the Position of Local AP’s

By: OTW

Hackers Arise Wi-Fi Radar

Welcome back, aspiring cyberwarriors!

One of our advanced student who goes by the handle Mike211 has developed a Wi-Fi scanning script that we want to share with all of you. What makes this script different and special is it’s ability to locate the Wi-Fi access points (AP) in your area.

I”ll let him introduce his new tool below!

In the Wi-Fi domain, raw signal strength and MAC identifiers can reveal more than just the presence of networks β€” they can open a path to estimating physical distance, mapping access points, and even executing wardriving missions or indoor localization without GPS. If you’ve ever wanted to push the boundaries of Wi-Fi auditing beyond mere detection, Hackers Arise Radar is your next-level tool.

Why this Tool is GameΒ Changing

Just like Wigle.net collects crowdsourced location data of APs, this project allows you to discover and map Wi-Fi access points in real-time using only your Linux laptop or USB Wi-Fi adapter.

With this tool, you’ll get:

– Continuous scans over 2.4β€―GHz, 5β€―GHz, 6β€―GHz, or all bands
– Fully automated interface setup (monitor mode, regulatory domain, TX power)
– Filtered and smoothed RSSI values with Kalman filtering
– On-demand calibration for RSSI-to-distance
– Spring-model map generation to visualize spatial relationships
– Exportable logs, visuals, and calibration profiles for future use

Whether you’re driving through a city, walking indoors, or performing a pentest, you can leverage this tool for actionable location data.

How it Works – Step by Step

Step #1. Launch & Configuration


Start the script:


kali > sudo python3 Hackers_Arise_Radar.py

You’ll be greeted with a colorful terminal interface that guides you through:


– Selecting your Wi-Fi interface
– Choosing the operational environment (indoor, urban, open space)
– Selecting scan band (2.4β€―GHz / 5β€―GHz / 6β€―GHz / All)

No need to manually enable monitor mode – the script automatically puts your adapter into monitor mode, sets the regulatory domain, and adjusts TX power based on your choices.

Step #2. Real-Time Wi-Fi Scanning


The script uses airodump-ng behind the scenes to:
– Continuously scan surrounding Wi-Fi networks
– Record BSSID, SSID, RSSI, channel, frequency band
– Stream live updates through a structured CSV output for parsing and analysis

Step #3. RSSI Filtering & Analytics


To reduce RSSI noise, the script implements a Kalman filter This Kalman filter:


– Smooths out transient signal spikes
– Creates a rolling average of RSSI per BSSID
– Improves distance estimation consistency

Step #4. Estimating Distance from RSSI


The tool calculates the distance using a log-distance path loss model such as:


d = 10^((TX_power – RSSI) / (10 * n))

Where:
– TX_power and path-loss exponent n are customizable or calculated through calibration
– RSSI is dynamically filtered
– Distance is measured in meters

Step #5. Calibration Engine


The included calibration module lets you:


– Input known RSSI and real-world distances
– Fit an optimized curve per BSSID
– Automatically store TX power, path-loss exponent, and RΒ² fit for reuse
– Flag poorly calibrated networks with suggestions

Step #6. Visual Mapping – Spring Model Layout


Once enough data is gathered, the tool uses a spring-model algorithm to create a map:
– Nodes (BSSIDs) are arranged based on estimated distances
– Forces push/pull the layout into geometric balance
– Labels show SSIDs, bands, and estimated distance in meters

Step #7. Regulatory & Power Tuning Mode


The tool isn’t just a scanner β€” it includes a dedicated utility mode to:


– Set regulatory domain (iw reg set <country_code>)
– Modify TX power (in dBm)
– Retrieve and display current wireless driver info
– Perform diagnostics before scanning

Focus Mode: Tracking a Single Access Point

Sometimes you just need to follow one Wi-Fi target β€” whether it’s a rogue device, a signal beacon, or an access point you’re using for indoor positioning.

Hackers Arise Radar includes a specialized mode for scanning and tracking a single BSSID:


– Select a known access point from your previously scanned list
– The tool locks onto that specific MAC address using:
Β  airodump-ng –bssid <target> –channel <ch>
– RSSI values are filtered using a Kalman filter
– Distance estimation is updated in real-time using the calibration profile
– Live updates show proximity and confidence

RealΒ World Use Cases

– Wardriving Missions: Continuous logs while driving
– Indoor Wireless Mapping: Signal-based AP triangulation, spatial layouts
– Security & Pentesting Recon: Detect new/rogue APs, estimate proximity
– Wi-Fi Optimization: Adjust regulatory domain / TX power, evaluate coverage
– Wireless Simulation & Testing: Simulate RSSI data with simulate_rss_matrix.py

Requirements & Setup

– Platform: Linux (Kali/Debian-based)
– Python: 3.7+
– Privileges: sudo required
– External Tools: aircrack-ng, iw, ip, ethtool
– Python Libraries: numpy, scipy, pandas, matplotlib, adjustText

Launch simply with:


kali> sudo python3 Hackers_Arise_Radar.py


No need to prep interfaces β€” the tool handles it all.

Summary

Hackers Arise Radar is more than just a scanner. It is a fully interactive system for Wi-Fi discovery, proximity estimation, map generation, and interface configuration β€” all controlled through an elegant terminal menu.

Built for hackers, engineers, educators, and hobbyists, this tool empowers you to:
– Visualize your wireless environment
– Optimize TX power and regulatory settings
– Log and export clean data
– Build wireless maps with zero GPS

Start scanning smarter β€” not harder.

For more information on this unique and powerful scanner, see our Wi-Fi Hacking training.

The post Python Basics for Hackers: Building a Wi-Fi Scanner Capable of Locating the Position of Local AP’s first appeared on Hackers Arise.

Hack The Box: Cat Machine Walkthrough – Medium Diffculity

By: darknite
Reading Time: 13 minutes

Introduction

This write-up details the β€œCat” machine from Hack The Box, a Medium-rated Linux challenge.

Objective on Cat Machine

The goal is to complete the β€œCat” machine by accomplishing the following objectives:

User Flag:

To obtain the user flag, an attacker first exploits a Stored Cross-Site Scripting (XSS) vulnerability in the user registration form, which allows stealing the administrator’s session cookie. With this stolen session, the attacker accesses the admin panel and exploits an SQL Injection flaw to extract sensitive user credentials from the database. After cracking these credentials, SSH access is gained as a regular user, enabling the retrieval of the user flagβ€”a secret token proving user-level access.

Root Flag:

For the root flag, privilege escalation is performed by finding a vulnerable image processing script owned by the root user. The attacker crafts a malicious image payload that executes unauthorised commands with root privileges. This leads to obtaining a root shellβ€”the highest level of system accessβ€”allowing capture of the root flag, which confirms full control over the machine.

Reconnaissance and Enumeration on Cat Machine

Establishing Connectivity

I connected to the Hack The Box environment via OpenVPN using my credentials, running all commands from a Parrot OS virtual machine. The target IP address for the Dog machine was 10.10.11.53.

Initial Scanning

To identify open ports and services, I ran an Nmap scan:

nmap -sC -sV 10.10.11.53 -oA initial

Nmap Output:

β”Œβ”€[dark@parrot]─[~/Documents/htb/cat]
└──╼ $ nmap -sC -sV -oA initial -Pn 10.10.11.53
# Nmap 7.94SVN scan initiated Tue Jun 17 10:05:26 2025 as: nmap -sC -sV -oA initial -Pn 10.10.11.53
Nmap scan report for 10.10.11.53
Host is up (0.017s latency).
Not shown: 998 closed tcp ports (conn-refused)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 8.2p1 Ubuntu 4ubuntu0.11 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   3072 96:2d:f5:c6:f6:9f:59:60:e5:65:85:ab:49:e4:76:14 (RSA)
|   256 9e:c4:a4:40:e9:da:cc:62:d1:d6:5a:2f:9e:7b:d4:aa (ECDSA)
|_  256 6e:22:2a:6a:6d:eb:de:19:b7:16:97:c2:7e:89:29:d5 (ED25519)
80/tcp open  http    Apache httpd 2.4.41 ((Ubuntu))
|_http-title: Did not follow redirect to http://cat.htb/
|_http-server-header: Apache/2.4.41 (Ubuntu)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
# Nmap done at Tue Jun 17 10:05:33 2025 -- 1 IP address (1 host up) scanned in 7.38 seconds

Analysis:

  • Port 22 (SSH): OpenSSH 8.2p1 on Ubuntu 4ubuntu0.11 risks remote code execution if unpatched (e.g., CVE-2021-28041).
  • Port 80 (HTTP): Apache 2.4.41, vulnerable to path traversal (CVE-2021-41773), redirects to cat.htb, hinting at virtual host misconfigurations.

Web Enumeration:

Perform directory fuzzing to uncover hidden files and directories.

gobuster dir -u http://cat.htb -w /opt/common.txt

Let’s perform directory enumeration with Gobuster to identify any potentially useful resources.

Gobuster Output:

Web Path Discovery (Gobuster):

  • /.git Directory: Exposed Git repository risks source code leakage, revealing sensitive data like credentials or application logic.
  • /admin.php, /join.php, and Other Paths: Discovered sensitive endpoints may lack authentication, enabling unauthorised access or privilege escalation.

The website features a typical interface with user registration, login, and image upload functionalities, but the presence of an exposed .git directory and accessible admin endpoints indicate significant security vulnerabilities.

Git Repository Analysis with git-dumper

Utilised the git-dumper tool to clone the exposed Git repository by executing the command git-dumper http://cat.htb/.git/ git. Subsequently, employed a Git extraction tool to retrieve critical source code files, including join.php, admin.php, and accept_cat.php, for further analysis.

Within the cloned Git repository, several PHP files were identified, meriting further examination for potential vulnerabilities or insights.

Source Code Analysis and Review on Cat Machine

Source Code Review of accept_cat.php

The accept_cat.php file is intended to let the admin user 'axel' Accept a cat by inserting its name into the accepted_cats table and deleting the corresponding entry from the cats table. The script correctly verifies the user’s session and restricts actions to POST requests, which is good practice. However, it constructs the insertion SQL query by directly embedding the $cat_name variable without any sanitisation or use of prepared statements:

$sql_insert = "INSERT INTO accepted_cats (name) VALUES ('$cat_name')";
$pdo->exec($sql_insert);

This exposes the application to SQL injection attacks, as malicious input in catName could manipulate the query and compromise the database. On the other hand, the deletion query is properly parameterised, reducing risk. To secure the script, the insertion should also use prepared statements with bound parameters. Overall, while session checks and request validation are handled correctly, the insecure insertion query represents a critical vulnerability in accept_cat.php.

Vulnerability Review of admin.php

This admin page lets the user β€˜axel’ manage cats by viewing, accepting, or rejecting them. It correctly checks if the user is logged in as β€˜axel’ before allowing access and uses prepared statements to fetch cat data from the database safely. The cat details are displayed with proper escaping to prevent cross-site scripting attacks.

However, the page sends AJAX POST requests to accept_cat.php and delete_cat.php without any protection against Cross-Site Request Forgery (CSRF). This means an attacker could potentially trick the admin into performing actions without their consent. Also, based on previous code, the accept_cat.php script inserts data into the database without using prepared statements, which can lead to SQL injection vulnerabilities.

To fix these issues, CSRF tokens should be added to the AJAX requests and verified on the server side. Additionally, all database queries should use prepared statements to ensure user input is handled securely. While the page handles session checks and output escaping well, the missing CSRF protection and insecure database insertion are serious security concerns.

Security Audit of view_cat.php

The view_cat.php script restricts access to the admin user 'axel' and uses prepared statements to safely query the database, preventing SQL injection. However, it outputs dynamic data such as cat_name, photo_path, age, birthdate, weight, username, and created_at directly into the HTML without escaping. This creates a Cross-Site Scripting (XSS) vulnerability because if any of these fields contain malicious code, it will execute in the admin’s browser.

The vulnerable code includes:

Cat Details: <?php echo $cat['cat_name']; ?>
<img src="<?php echo $cat['photo_path']; ?>" alt="<?php echo $cat['cat_name']; ?>" class="cat-photo">
<strong>Name:</strong> <?php echo $cat['cat_name']; ?><br>
<strong>Age:</strong> <?php echo $cat['age']; ?><br>
</code>

To mitigate this, all output should be passed through htmlspecialchars() to encode special characters and prevent script execution. Additionally, validating the image src attribute is important to avoid loading unsafe or external resources. Without these measures, the page remains vulnerable to XSS attacks.

Input Validation Analysis of join.php

The provided PHP code is vulnerable to several security issues, primarily due to improper input handling and weak security practices. Below is an explanation of the key vulnerabilities, followed by the relevant code snippets:

  1. Cross-Site Scripting (XSS): The code outputs $success_message and $error_message without sanitisation, making it susceptible to XSS attacks. User inputs (e.g., $_GET['username'], $_GET['email']) are directly echoed, allowing malicious scripts to be injected.
<?php if ($success_message != ""): ?>
   <div class="message"><?php echo $success_message; ?></div>
   <?php endif; ?>
   <?php if ($error_message != ""): ?>
   <div class="error-message"><?php echo $error_message; ?></div>
   <?php endif; ?>
  1. Insecure Password Storage: Passwords are hashed using MD5 (md5($_GET['password'])), which is cryptographically weak and easily cracked.
$password = md5($_GET['password']);
  1. SQL Injection Risk: While prepared statements are used, the code still processes unsanitized $_GET inputs, which could lead to other injection vulnerabilities if not validated properly.
  2. Insecure Data Transmission: Using $_GET for sensitive data like passwords, exposing them in URLs risks interception.

To mitigate these, use htmlspecialchars() for output, adopt secure hashing (e.g., password_hash()), validate inputs, and use $_POST for sensitive data.

Workflow Evaluation of contest.php

The PHP code for the cat contest registration page has multiple security flaws due to weak input handling and poor security practices. Below are the key vulnerabilities with relevant code snippets:

Cross-Site Scripting (XSS): The $success_message and $error_message are output without sanitization, enabling reflected XSS attacks via crafted POST inputs (e.g., cat_name=<script>alert(β€˜XSS’)</script>).

<?php if ($success_message): ?>
    <div class="message"><?php echo $success_message; ?></div>
<?php endif; ?>
<?php if ($error_message): ?>
    <div class="error-message"><?php echo $error_message; ?></div>
<?php endif; ?>
  • Weak Input Validation: The regex (/[+*{}’,;<>()\\[\\]\\/\\:]/) in contains_forbidden_content is too permissive, allowing potential XSS or SQL injection bypasses.
$forbidden_patterns = "/[+*{}',;<>()\\[\\]\\/\\:]/";
  • Insecure File Upload: The file upload trusts getimagesize and uses unsanitized basename($_FILES[β€œcat_photo”][β€œname”]), risking directory traversal or malicious file uploads.
$target_file = $target_dir . $imageIdentifier . basename($_FILES["cat_photo"]["name"]);

To mitigate, sanitize outputs with htmlspecialchars(), use stricter input validation (e.g., FILTER_SANITIZE_STRING), sanitize file names, restrict upload paths, and validate file contents thoroughly.

User Registration and Login

Clicking the contest endpoint redirects to the join page, which serves as the registration page.

Let’s create a new account by completing the registration process.

The registration process was completed successfully, confirming that new user accounts can be created without errors or restrictions.

Logging in with the credentials we created was successful.

After a successful login, the contest page is displayed as shown above.

Let’s complete the form and upload a cat photo as required.

Successfully submitted the cat photo for inspection.

Exploiting XSS to Steal Admin Cookie for Cat Machine

Initialise the listener.

Injected a malicious XSS payload into the username field.

Let’s create a new account by injecting malicious XSS code into the Username field while keeping all other inputs valid.

Let’s fill out the form with normal inputs as before.

The process may take a few seconds or minutes, depending on the response time. I have attempted multiple times to ensure it works successfully.

Used Firefox Dev Tools to set the cookie and gain access to admin features

Once we obtain the token hash, we need to copy and paste it into Firefox’s inspector to proceed further.

After that, simply refresh the page, and you will notice a new β€œAdmin” option has appeared in the menu bar.

Clicking the Admin option in the menu bar redirects us to the page shown above.

Click the accept button to approve the submitted picture.

Leveraging XSS Vulnerability to Retrieve Admin Cookie for Cat Machine

Used Burp Suite to analyze POST requests.

Use Burp Suite to examine network packets for in-depth analysis.

Test the web application to determine if it is vulnerable to SQL injection attacks.

Attempting to inject the SQL command resulted in an β€œaccess denied” error, likely due to a modified or invalid cookie.

SQL Injection and Command Execution

After reconstructing the cookie, the SQL injection appears to function as anticipated.

Successfully executed command injection.

We can use the curl command to invoke the malicious file and execute it. The fact that it’s hanging is promising, indicating potential success.

It was observed that bash.sh has been transferred to the victim’s machine.

Success! A shell was obtained as the www-data user.

Database Enumeration

It’s unusual to find cat.db while searching for the database file.

Transfer the SQL file to our local machine.

We discovered that cat.db is a SQLite 3.x database.

sqlite3 cat.db opens the cat.db file using the SQLite command-line tool, allowing you to interact with the databaseβ€”run queries, view tables, and inspect its contents.

The cat.db database contains three tables: accepted_cats, cats, and users, which likely stores approved cat entries, general cat data, and user information, respectively.

Immediate cracking is possible for some obtained hashes.

The screenshot shows the hashes after I rearranged them for clarity.

Breaking Password Security: Hashcat in Action

We need to specify the hash mode, which in this case could be MD5.

We successfully cracked the hash for the user Rosa, revealing the password: soyunaprincesarosa.

Boom! We successfully gained access using Rosa’s password.

The access.log file reveals the password for Axel.

The user Axel has an active shell account.

The credentials for Axel, including the password, were verified successfully.

Access is achievable via either pwncat-cs or SSH.

Executing the appropriate command retrieves the user flag.

Escalate to Root Privileges Access on Cat Machine

Privilege Escalation

The Axel user does not have sudo privileges on the cat system.

Email Analysis

We can read the message sent from Rosa to Axel.

The emails are internal updates from Rosa about two upcoming projects. In the first message, Rosa mentions that the team is working on launching new cat-related web services, including a site focused on cat care. Rosa asks Axel to send details about his Gitea project idea to Jobert, who will evaluate whether it’s worth moving forward with. Rosa also notes that the idea should be clearly explained, as she plans to review the repository herself. In the second email, Rosa shares that they’re building an employee management system. Each department admin will have a defined role, and employees will be able to view their tasks. The system is still being developed and is hosted on their private Gitea platform. Rosa includes a link to the repository and its README file, which has more information and updates. Both emails reflect early planning stages and call for team involvement and feedback.

Checking the machine’s open ports reveals that port 3000 is accessible.

Therefore, we need to set up port forwarding for port 3000.

Gitea Exploitation on Cat Machine

A screenshot of a computer

AI-generated content may be incorrect.

The service running on port 3000 is the Gitea web interface.

A screenshot of a login screen

AI-generated content may be incorrect.

Using Axel’s credentials, we successfully logged in.

Gitea service is running version 1.22.0, which may contain specific features and known vulnerabilities relevant for further evaluation.

Start the Python server to serve files or host a payload for the next phase of the assessment.

Inject the XSS payload as shown above.

The fake email is sent to the user jobert to test the functionality.

Obtained a base64-encoded cookie ready for decoding.

The decoded cookie appears to contain the username admin.

Edit the file within the Gitea application.

Obtained the token as shown above.

A screenshot of a computer screen

AI-generated content may be incorrect.
<?php
$valid_username = 'admin';
$valid_password = 'IKw75eR0MR7CMIxhH0';

if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']) || 
    $_SERVER['PHP_AUTH_USER'] != $valid_username || $_SERVER['PHP_AUTH_PW'] != $valid_password) {
    
    header('WWW-Authenticate: Basic realm="Employee Management"');
    header('HTTP/1.0 401 Unauthorized');
    exit;
}

This PHP script enforces HTTP Basic Authentication by verifying the client’s username and password against predefined valid credentials: the username β€œadmin” and the password β€œIKw75eR0MR7CMIxhH0.” Upon receiving a request, the script checks for authentication headers and validates them. If the credentials are missing or incorrect, it responds with a 401 Unauthorised status and prompts the client to authenticate within the β€œEmployee Management” realm.

The password discovered grants root access and functions as an administrator password on Windows machines.

Executing the appropriate command retrieves the root flag.

The post Hack The Box: Cat Machine Walkthrough – Medium Diffculity appeared first on Threatninja.net.

DC-9 Vulnhub Walkthrough – OSCP way

By: Jo
Recently, My focus turned more towards OSCP and I am thinking of taking the exam. After reading tons of people’s experience over Reddit, I took some notes on what would be my way of studying for this. It isn’t easy from the looks of it and to win with time, I need a lot of […]
❌