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
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.
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"
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
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
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:
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:
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
After confirmation, scripts will run normally, including your profile file.
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:
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.
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.
Self-hosted blind XSS hunter via Docker. Deploy xsshunterβexpress in five minutes to capture stealthy XSS payloads with screenshots, DOM dumps, and full context.
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:
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.
gobusterdir-uhttp://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.
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:
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.
Insecure Password Storage: Passwords are hashed using MD5 (md5($_GET['password'])), which is cryptographically weak and easily cracked.
$password = md5($_GET['password']);
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.
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): ?> <divclass="message"><?phpecho$success_message; ?></div><?php endif; ?><?php if ($error_message): ?> <divclass="error-message"><?phpecho$error_message; ?></div><?php endif; ?>
Weak Input Validation: The regex (/[+*{}β,;<>()\\[\\]\\/\\:]/) in contains_forbidden_content is too permissive, allowing potential XSS or SQL injection bypasses.
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
The service running on port 3000 is the Gitea web interface.
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.
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.
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 [β¦]
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
Pwned vulnhub challenge is an easy boot2root machine. One of the key take away from this machine is how you can escalate your privileges using Dockers. This blog post is about how I exploited this