Удаление power shell для хакеров

PowerShell is a powerful tool for task automation and configuration management, mainly in the Windows operating system. Penetration testers and ethical hackers can use PowerShell scripting to automate many activities.

In simple terms, PowerShell makes it easier to automate and manage tasks on Windows systems, enhancing cybersecurity efforts.

What Is PowerShell?

PowerShell refers to two related Microsoft Windows products: a scripting language and a command-line shell for executing PowerShell scripts. (Microsoft Learn, 2023) First released in 2006, PowerShell was originally developed only for the Windows operating system to replace the Command Prompt. However, it is also available for the macOS and Linux operating systems via the cross-platform PowerShell Core framework.

What Is PowerShell Scripting?

PowerShell is a full-fledged scripting language that supports variables, conditional statements, loops, functions, error handling, and more. This makes it suitable for many use cases (as we’ll see later).

Some Common Use Cases

1. System Administration

  • Creating, modifying, or deleting user accounts and groups in Active Directory.
  • Configuring and managing devices on Windows servers.
  • Creating, deleting, and moving files and folders.
  • Changing Windows Registry keys and values.

2. Task Automation

  • Automating repetitive tasks such as data backup, log deletion, and software installation.
  • Scheduling tasks to run at specific times or after specific intervals.
  • Processing large amounts of files or data in bulk (e.g., moving or renaming all the files in a folder).

3. Configuration Management

It can be used to tweak many aspects of Windows settings and configurations, such as:

  • Defining environment variables, system parameters, and network settings.
  • Applying configurations to multiple users at once using Group Policy.
  • Standardizing Windows configurations across multiple workstations or servers.

4. Monitoring and Reporting

PowerShell scripts can provide visibility into the events within an IT environment. The monitoring and reporting use cases of PowerShell include:

  • Collecting, processing, and analyzing data about system performance.
  • Searching and filtering Windows logs for specific events or anomalies.
  • Automatically generate reports and send them to key decision-makers.

5. Security and Compliance

Last but not least, PowerShell scripting can help organizations ensure that they are properly detecting cybersecurity weaknesses and remaining compliant with laws and regulations:

  • Auditing and securing user credentials (e.g., by enforcing password policies).
  • Conducting IT security scans and vulnerability assessments.
  • Enforcing compliance with data privacy and security regulations and standards.

PowerShell Scripting in Penetration Testing

The role of penetration testers is to probe an IT machine or ecosystem for vulnerabilities by simulating a real cyberattack against it. Penetration testers can use PowerShell scripts to automate many of their activities when scanning for security weaknesses in Windows environments:

  • Reconnaissance: Before conducting a penetration test, pen testers perform surveillance on the target, gathering information such as open ports and running services. PowerShell scripts can automate the reconnaissance task, collecting data to help identify the most promising avenues of attack.
  • Vulnerability scanning: During a simulated attack, penetration testers scan for many vulnerabilities: SQL injection, cross-site scripting (XSS), insecure direct object references (IDOR), and more. Pen testers can write PowerShell scripts that automate scanning using various cybersecurity tools and libraries.
  • Exploitation and privilege escalation: After penetration testers detect security weaknesses, the next step is to exploit them and extend the attacker’s reach throughout the IT ecosystem. PowerShell scripts can help testers escalate privileges, perform lateral movement throughout the network, and exfiltrate sensitive data.
  • Reporting and documentation: Once a penetration test is complete, testers need to report their findings to key decision-makers and make recommendations for resolving any vulnerabilities detected. PowerShell scripting can help gather data from multiple sources and generate reports summarizing the vulnerabilities detected and the extent to which they could be exploited.

References

  1. Microsoft Learn. (2023). Powershell Documentation – Microsoft Learn. https://learn.microsoft.com/en-us/powershell/
  2. Microsoft Learn. (2021). Cmdlet Overview – Microsoft Learn. https://learn.microsoft.com/en-us/powershell/scripting/developer/cmdlet/cmdlet-overview?view=powershell-7.3
  3. Microsoft Learn. (2021). Introducing the Windows PowerShell ISE – PowerShell | Microsoft Learn. https://learn.microsoft.com/en-us/powershell/scripting/windows-powershell/ise/introducing-the-windows-powershell-ise?view=powershell-7.3

Author Bio

David Tidmarsh is a programmer and writer. He’s worked as a software developer at MIT, has a B.A. in history from Yale, and is currently a graduate student in computer science at UT Austin

PowerShell Remoting is a native Windows feature that can be used to take over entire enterprises. It allows you to pivot between machines, automate hacking tasks, and dominate Windows environments while remaining undetected. 

This comprehensive guide will teach you about PowerShell Remoting and how to use it to start interactive sessions, execute remote commands, and run complete PowerShell scripts against multiple machines. 

You’ll also see how it can be used for common penetration testing actions like lateral movement, privilege escalation, and establishing persistence while evading detection.

Let’s jump straight in and learn how to do PSRemoting.

Table Of Contents

What Is PowerShell Remoting?

With a single command or script, you can update software, change configuration settings, or edit services across multiple machines. SOC analysts or responders can also use it to collect logs for analysis or perform remediation actions quickly. 

Remote Command Execution (RCE): Run commands or scripts on remote systems.

Interactive: Start an interactive remote session and run remote commands as if you were in a local PowerShell terminal. 

Script Execution: Execute complete PowerShell scripts as background jobs on multiple machines at once to perform using asynchronous task execution.

Secure: Use encrypted communication channels (WinRM) with Kerberos support and NTLM authentication.

Scalable: Use PowerShell Remoting across hundreds of machines concurrently, allowing you to control and manage fleets of enterprise workstations and servers.

Execute Commands Remotely

PowerShell Remoting allows you to execute commands and scripts on remote systems. This means you don’t need to sit in front of the workstation you’re targeting to perform attacks. Once you’re inside the network, you can attack any network-connected machine. 

Stealth and Evasion

Also, PowerShell Remoting is encrypted. This makes it harder for security operations teams to detect and analyze malicious traffic.

Automated Reconnaissance and Exploitation

PowerShell Remoting allows you to execute entire PowerShell scripts against hundreds of machines at once. This is perfect for automating common reconnaissance and exploitation tasks like scanning network ports, finding vulnerable machines, and performing credential stuffing. Automating saves you time and energy.

Post-Exploitation Activities

After gaining initial access, hackers will perform post-exploitation activities like setting up persistence mechanisms, performing credential harvesting to exfiltrate data, and eventually performing lateral movement. Again, PowerShell Remoting is an excellent tool with its ability to remote code execution, native support in Windows environments, and automation capabilities. 

Set Up and Enable PowerShell Remoting

Set Up and Enable PowerShell Remoting

If you can establish a WMIC connection to the target, you can activate PowerShell Remoting remotely using the Windows Management Instrumentation (WMI) command wmic /node:<RemoteHost> process call create "powershell enable-psremoting -force".

This is all you need if you’re using domain-joined computers to perform PowerShell Remoting. 

However, if you execute remote PowerShell commands from a computer not connected to the same domain as the target machine, your machine is considered an “untrusted host.” For instance, your Kali Linux machine would be an untrusted host.

To ensure PowerShell Remoting works from any machine, you must either add that single machine to the Trusted Hosts list for the machine you’re PowerShell Remoting into or set all hosts as trusted hosts using a wildcard (*):

  • To add your machine, execute the command Set-Item wsman:\localhost\Client\TrustedHosts -Value "<YourComputerName>".
  • To add all hosts, run the command Set-Item wsman: localhostClientTrustedHosts -Value *. Use this command only in controlled testing environments.
Run These Commands
Connect to the Target Machine Using the Winrm Protocol

If successful, you can use PowerShell Remoting to execute PowerShell commands and scripts. 

How to Use PowerShell Remoting

Once PowerShell Remoting has been enabled on the target machine, you can start running remote PowerShell commands. 

Firstly, to establish a PowerShell Remoting session with the target, open a PowerShell terminal on your Kali Linux machine using the dropdown menu at the top of the GUI.

How to Use PowerShell Remoting Commands
Enter-PSSession -ComputerName

Once you’ve established a PowerShell Remoting session, you can interact with the target machine just like you had opened a PowerShell terminal locally. 

PowerShell Remoting Scripts

PowerShell commands are great, but you probably don’t want to run them interactively, one by one every time. 

Good news: PowerShell Remoting allows you to bundle your commands into a script and execute it asynchronously on a target machine to automate tasks.         

PowerShell Remoting Scripts
Use the Invoke-Command cmdlet
To execute a PowerShell script

Here, the host-recon.ps1 script contains the same PowerShell commands as before, just in a script rather than listed individually. Check out PowerSploit for excellent PowerShell hacking scripts to run during a penetration test.

PowerShell Remoting Session Management

You just saw how the Enter-PSSession cmdlet can create an interactive session, and New-PSSession creates a session you can use to execute commands. These are PowerShell Remoting session management cmdlets used to manage sessions. Here is a summary of all the session management cmdlets you can use:

CmdletDescriptionExample
Enter-PSSessionStarts an interactive session with a remote computer where you can run commands directly.Enter-PSSession -ComputerName <RemoteComputerName>
Exit-PSSessionEnds an interactive session started with Enter-PSSession.Exit-PSSession
New-PSSessionCreates persistent remote connections to one or more computers so you can run multiple commands simultaneously.$session = New-PSSession -ComputerName RemoteComputerName
Remove-PSSessionCloses one or more remote sessions created by New-PSSession.Remove-PSSession -Session $session
Get-PSSessionRetrieves the PowerShell sessions that are currently available on your local machine. Get-PSSession

Malicious actors can use PowerShell Remoting to perform lateral movement, escalate their privileges, install persistence mechanisms, and evade detection. 

:/>  Как отключить Автозапуск флешек и дисков? — пк-ГИД

Let’s explore how you can do this during a penetration test.

PowerShell Remoting for Lateral Movement

Lateral movement is a key step in any penetration test, and PowerShell Remoting can make it very easy. 

You just need to steal credentials from a compromised system using a tool like Mimikatz or Meterpreter. Then, use these credentials to authenticate to other systems using PowerShell Remoting. 

PowerShell Remoting for Hackers

PowerShell Remoting for Privilege Escalation

PowerShell Remoting can also be used to elevate your privileges on a target machine by executing arbitrary PowerShell commands. 

You can run specific commands to check for privilege escalation opportunities or entire scripts that automatically escalate your privileges

For instance, many post-exploitation activities during a penetration test require elevated privileges, such as checking for misconfigurations, installing persistence mechanisms, or exfiltrating sensitive data. 

PowerShell Remoting for Privilege Escalation
Meterpreter command is successful

The commands demonstrated here run against a Windows 10 machine with Microsoft Windows Defender and Smart Screen disabled.

PowerShell Remoting for Persistence

You can use various persistence mechanisms, such as creating a Windows Startup folder script that connects to your command and control (C2) server, installing a malicious service, or using a registry run key. 

PowerShell Remoting for Persistence

Avoiding Detection

As mentioned, lateral movement is a key step in any penetration test. However, usually, this requires you to use a C2 framework like PowerShell Empire and install a C2 agent on each machine you move to so you can interact with it. 

If this sounds like a lot of work, don’t worry: this is where PowerShell Remoting shines. In fact, your PowerShell Remoting sessions, commands, and scripts run entirely in memory. 

This means common detection techniques like signature-based scanning won’t detect your post-exploitation activities, and you can perform lateral movement without disruption. 

Additionally, because PowerShell Remoting is so common in enterprise environments, your actions will likely go unnoticed by defenders, unlike with a tool like PsExec

PsExec is not pre-installed on most workstations or servers, so your chances of blending into the target environment are lower than PowerShell Remoting.

One way to use PowerShell Remoting to remain undetected is to download and execute PowerShell scripts completely in memory on a target machine. 

PowerShell Download Cradle to Download

The Meterpreter reverse shell is downloaded from the attacker machine (10.0.200.17) and executed on the target machine without touching the disk, evading on-disk detection mechanisms. A fully interactive shell connects back to your attack machine.

The Meterpreter Reverse Shell is Downloaded From the Attacker Machine

However, before getting ahead of yourself, remember that PowerShell Remoting has some limitations, especially if Constrained Language Mode is enabled. 

PowerShell scripts must be allowed to execute on the Windows system you’re attacking to download and execute them in memory. You can enable this by changing the Set-Execution policy parameter.

Constrained Language Mode

You can execute the PowerShell command $ExecutionContext.SessionState.LanguageMode to detect if CLM is enabled.

You Can Execute the Powershell Command

This will return the language mode for the current system:

  • FullLanguage: This is the default mode. It provides full scripting capabilities without any restrictions. All cmdlets, language features, and .NET types are available.
  • RestrictedLanguage: This option limits you to basic cmdlets and expressions. It doesn’t allow complex language scripts, constructs, or .NET types.
  • NoLanguage: Here, script execution is completely disabled, and only basic command execution is allowed.
  • ConstrainedLanguage: In this mode, basic scripting is allowed, but access to advanced features and .NET types is restricted. This language only allows you to perform basic administrative tasks.

If you find CLM is enabled on the machine you’re PowerShell Remoting to, you can try several bypass methods. 

The easiest way to bypass CLM is to downgrade your PowerShell remote session to a previous PowerShell version. For instance, you can downgrade to PowerShell version 2.0 with the command powershell -version 2.

Windows PowerShell

Downgrading to an older PowerShell version requires that version to have already been installed on your target machine. If this isn’t the case, there are other CLM bypasses, including: 

  • Make the path where you execute your scripts contain system32, as discussed here.
  • PowerShell CLM bypass scripts.
  • Using PowerShell Runspaces to bypass CLM.

Let’s see how PowerShell Remoting compares to another tool commonly used for lateral movement in Windows environments.

PowerShell Remoting vs PsExec

PsExec is another popular tool frequently used by threat actors to perform lateral movement, escalate privileges, and execute remote code. 

However, unlike PowerShell Remoting, PsExec is designed for quick, ad-hoc tasks like running simple commands or non-PowerShell executables. 

You can’t use it to automate complex tasks like executing complete scripts, running commands against multiple machines, or creating an interactive session. It only shines when performing single tasks with minimal configuration. 

PowerShell Remoting is the way to go if you want a more robust solution. The only issues are whether it’s configured in the environment you’re targeting and whether you can bypass any PowerShell protections like CLM. 

Conclusion

PowerShell Remoting is a powerful Windows feature that allows you to perform lateral movement, escalate privilege, and install persistence mechanisms. 

This guide demonstrated how to use it to start interactive sessions, run ad-hoc commands, and execute entire PowerShell scripts that can automate many hacking tasks. 

You’ve also seen how to use PowerShell Remoting to evade detection, discovered tips on bypassing PowerShell’s Constrained Language Mode (CLM), and learned how PowerShell Remoting stacks up against PsExec. 

We encourage you to set up your hacking lab and play with this Windows feature’s awesome capabilities.

Here are some of the courses available:

Frequently Asked Questions

How do you tell if PowerShell remoting is enabled?

There are several ways of enabling PowerShell Remoting on a target machine. For instance, you can use a hacking tool like evil-winrm to check if you can establish a session. Otherwise, you can use the Test-WSMan cmdlet to test the availability of the WS-Management (WinRM) service on a local or remote computer. You can also use the Get-WSManInstance cmdlet to check the configuration settings of the WinRM service. Lastly, if you have local access to the machine, you can use the Get-Service -Name WinRM command to check the service status or Enable-PSRemoting -Force command to enable PowerShell Remoting.

Is it safe to enable PowerShell remoting?

What is PowerShell remoting used for?

How can PowerShell remoting be used for malicious purposes?

Level Up in Cyber Security: Join Our Membership Today!

Understanding PowerShell

Before we delve into the ways in which hackers leverage PowerShell, let’s first gain a basic understanding of what It is and how it has evolved over time. PowerShell is a command-line shell and scripting language built on Microsoft’s .NET framework. It was first introduced in 2006 and has undergone several significant updates and advancements.

What is PowerShell?

The Evolution of PowerShell

Over the years, PowerShell has evolved from a simple command-line shell to a full-fledged scripting language. Microsoft has introduced new features and enhancements with each new version, making PowerShell even more powerful and flexible.

The Attraction of PowerShell for Hackers

There are several reasons why hackers are increasingly turning to PowerShell as their weapon of choice:

The Versatility of PowerShell

PowerShell’s versatility is one of the main reasons it has become a favorite tool for hackers. Its rich set of cmdlets (commandlets) and its ability to interact with other Windows components and APIs make it suitable for various malicious activities.

With its extensive capabilities, PowerShell provides hackers with a powerful toolkit to carry out their nefarious activities. Whether reconnaissance, exploitation, or maintaining control over compromised systems, PowerShell offers a wide range of options to achieve their malicious objectives.

PowerShell’s Accessibility and Ubiquity

Another factor contributing to PowerShell’s popularity among hackers is its accessibility and ubiquity. PowerShell has been an integral part of Windows operating systems since Windows 7, making it readily available on most Windows-based systems.

This widespread adoption makes it easier for hackers to leverage PowerShell for their malicious activities, as they can assume that their targets will have PowerShell installed by default.

PowerShell’s integration with the Windows ecosystem allows hackers to seamlessly blend their activities with legitimate system processes, making it harder for security measures to detect and mitigate their actions. By exploiting PowerShell’s trusted status within the operating system, hackers can evade detection and maintain persistence within compromised networks.

PowerShell’s ubiquity extends beyond Windows systems. With the introduction of PowerShell Core, a cross-platform version of PowerShell, hackers can now target Windows, Linux, and macOS systems, broadening their reach and potential impact.

Common PowerShell Exploits in Cyber Attacks

Now that we understand why hackers are drawn to PowerShell, let’s take a closer look at some of the common ways in which they exploit this powerful tool:

:/>  Пропали ядра cpu где включить обратно

Section Image

Scripting Attacks with PowerShell

By leveraging PowerShell’s flexibility and capabilities, hackers can create sophisticated scripts that bypass traditional security measures and remain undetected by antivirus software. These scripts can be designed to evade detection using obfuscation techniques, making it even more challenging for security professionals to identify and mitigate the threat.

Remote Access Trojans (RATs) and PowerShell

The combination of PowerShell and Remote Access Trojans (RATs) has become a potent weapon for hackers. RATs are malicious programs that provide attackers remote access and control over a compromised system. By leveraging PowerShell, hackers can execute RATs stealthily and remotely, allowing them to maintain persistent access to the compromised system.

Let’s consider a scenario where an attacker gains access to a corporate network through a phishing attack. Once inside, they can use PowerShell to deploy a RAT that establishes a backdoor, granting them unrestricted access to the network. From there, the attacker can move laterally, escalate privileges, and exfiltrate sensitive data without arousing suspicion.

For example, the notorious banking Trojan, TrickBot, has been known to use PowerShell to download additional payloads and establish command-and-control channels with its operators. This combination of PowerShell and RATs enables attackers to operate discreetly, making it difficult for security teams to detect and respond to the threat in a timely manner.

As cybercriminals evolve tactics, organizations must stay vigilant and implement robust security measures to protect against PowerShell exploits. Regular security awareness training, strong access controls, and up-to-date threat intelligence can help organizations defend against these sophisticated attacks.

Detecting and Preventing PowerShell Attacks

As PowerShell continues to be exploited by hackers, it is crucial for organizations to implement effective measures to detect and prevent these attacks. Here are some strategies that can help:

Signs of a PowerShell Attack

Identifying the signs of a PowerShell attack is the first step in detecting and mitigating the damage caused by such an attack. Some common indicators include unusual PowerShell process activity, suspicious PowerShell scripts or commands being executed, and the presence of unauthorized PowerShell modules or plugins.

Best Practices for Preventing PowerShell Exploits

Restrict PowerShell execution to authorized users and systems.

Implement strong access controls and regularly review permissions.

Strong access controls are essential to prevent unauthorized access to PowerShell. Regularly reviewing permissions ensures that only the necessary individuals have access, reducing the chances of a malicious actor gaining control over PowerShell and using it as a tool for their nefarious activities.

Keep PowerShell and other software up-to-date with the latest security patches.

Regularly updating PowerShell and other software with the latest security patches is crucial in preventing exploitation. Hackers often take advantage of known vulnerabilities in outdated software, so staying up-to-date with patches ensures these vulnerabilities are addressed and closed off, making it harder for attackers to gain a foothold.

Enable PowerShell logging and monitoring to detect suspicious activities.

Enabling PowerShell logging and monitoring allows organizations to monitor PowerShell activities closely and detect suspicious behavior. Organizations can quickly identify potential attacks and take appropriate action to mitigate the damage by analyzing logs and monitoring for unusual patterns or commands.

Regularly conduct security awareness training to educate employees about the risks of PowerShell attacks.

Employee education and awareness play a crucial role in preventing PowerShell attacks. Regular security awareness training sessions can help employees understand the risks associated with PowerShell and teach them how to identify and report suspicious activities. By empowering employees with knowledge, organizations can create a strong human firewall against potential attacks.

The Future of PowerShell and Cybersecurity

As the battle between hackers and cybersecurity professionals continues to escalate, the future of PowerShell and its role in cyber attacks remains uncertain. However, there are ongoing efforts to enhance the security of PowerShell and mitigate its exploitation by malicious actors.

Advancements in PowerShell Security

Constrained Language Mode is a powerful security feature that restricts the functionality of PowerShell to prevent the execution of potentially dangerous commands. By enforcing strict language constraints, attackers find it much more difficult to leverage PowerShell for malicious purposes. This feature has proven effective in reducing the attack surface and minimizing the impact of PowerShell-based cyber attacks.

The Ongoing Battle Against PowerShell Exploits

While advancements in PowerShell security are promising, it’s important to acknowledge that hackers constantly evolve their techniques to bypass security measures. Organizations must stay vigilant and continuously update their defenses to counter emerging PowerShell exploits and other evolving threats.

Real-world examples, such as the highly publicized NotPetya ransomware attack in 2017, underscore the need for robust security measures and proactive threat detection. NotPetya, which exploited vulnerabilities in PowerShell, caused widespread disruption and financial losses. This incident served as a wake-up call for organizations worldwide, highlighting the urgent need to strengthen their defenses against PowerShell-based attacks.

Conclusion

As the cybersecurity landscape continues to evolve, it is clear that PowerShell will remain a significant tool in the arsenal of both attackers and defenders. The future of PowerShell and its role in cyber attacks will depend on the collective efforts of cybersecurity professionals, developers, and organizations to stay ahead of emerging threats. Continued collaboration and knowledge sharing will be crucial in shaping the future of PowerShell and ensuring a safer computing environment for all.

Austindwarner

Basic Powershell Commands

What is the location of the file “interesting-file.txt”

But we should know what these flags actually mean:

-Path: Path we are looking for. C;\ for the entire disk

-Include: The name of the file.

-File: File only

-Recurse: Recursive search

-ErrorAction SilentlyContinue: Ignore error

Answer: C:\Program Files

Specify the contents of this file

You will need to read the content of the file using this command: Get-Content “C:\Program Files\interesting-file.txt.txt”

  • Get-Content: This is a PowerShell cmdlet used to retrieve the content of a file. It is commonly used to read the contents of text files.
  • “C:\Program Files\interesting-file.txt.txt”: This is the path to the file whose content you want to retrieve. In this case, it specifies a file located at C:\Program Files\interesting-file.txt.txt.

How many cmdlets are installed on the system(only cmdlets, not functions and aliases)?

  1. Get-Command: Get information about commands in PowerShell.
  2. | (Pipeline): Pass the list of commands to the next action.
  3. Where-Object -Parameter CommandType -eq Cmdlet: Filter the list to only include commands of type “Cmdlet.”
  4. | (Pipeline): Pass the filtered list of Cmdlets to the next action.
  5. Measure-Object: Count how many Cmdlets are in the filtered list.

Putting it all together, the command is finding and counting the number of Cmdlets in PowerShell. If you run this command, the result will tell you how many Cmdlets are available in your PowerShell environment.

Get the MD5 hash of interesting-file.txt

Easy one here: Get-Filehash -Path “c:\Program Files\interesting-file.txt.txt”

What is the command to get the current working directory?

You get this one from the reading

So use the Get-Location cmdlt with this path:

err means its not there

What command would you use to make a request to a web server?

This one is trying to get you used to finding the full list of operators the link included in the reading: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/where-object?view=powershell-7.4&viewFallbackFrom=powershell-6

Type web in the search bar

Base64 decode the file b64.txt on Windows.

First lets get the path of the file using: Get-ChildItem -Path C:/ -Include b64.txt -Recurse -File

  • certutil: A command-line utility in Windows.
  • -decode: An option that tells certutil to perform decoding.
  • “C:\Users\Administrator\Desktop\b64.txt”: The path to the Base64-encoded file you want to decode.
  • decoded.txt: The name of the file where the decoded content will be saved

Now lets read the file to get the answer: Get-Content .\decoded.txt

Or, you can declare a variable and ask for the SID and compare to the question using the syntex:

Basically who doesn’t have a password

How many local groups exist?

What command did you use to get the IP address info?

Remember to use the link above to find commands you don’t know.

How many ports are listed as listening?

What is the remote address of the local port listening on port 445?

Get-NetTCPconnection -State Listen -LocalPort 445

  • Get-NetTCPConnection: Get information about TCP connections.
  • -State Listen: Include only connections that are in the “Listen” state, meaning they are waiting for incoming connections.
  • -LocalPort 445: Include only connections that are listening on port 445.

How many patches have been applied?

When was the patch with ID KB4023834 installed?

So, since your provided the patch id you can use this command: Get-Hotfix -Id KB4023834

Answer: 6/15/2017 12:00:00 AM

Find the contents of a backup file.

So this one is a bit tough the backup files usually end in .bak but for some reason it’s a .txt file so we need to use a wild card to filter that: Get-ChildItem -Path C:\ -Include *.bak* -File -Recurse -ErrorAction SilentlyContinue

  1. Get-ChildItem: Retrieve files and folders.
  2. -Path C:\: Start searching from the C drive.
  3. -Include *.bak*: Look for items with names containing “.bak”.
  4. -File: Include only files, not folders.
  5. -Recurse: Search in subfolders as well.
  6. -ErrorAction SilentlyContinue: If there are errors (e.g., access issues), continue without displaying error messages.
:/>  Как зарегистрировать библиотеку dll в Windows 10 | Настройка оборудования

Now lets read the content: Get-Content “C:\Program Files (x86)\Internet Explorer\passwords.bak.txt”

Search for all files containing API_KEY

  • Get-ChildItem -Recurse: This part gets a list of all files in the current directory and its subdirectories.
  • |: This symbol, called the pipe, passes the list of files to the next command.
  • Select-String “API_KEY”: This part searches through the content of each file for the text “API_KEY” and displays the lines containing this text, along with file information.

In simpler terms, it’s like saying, “Find all files and look inside them. If you see any line with the text ‘API_KEY’, show me where and in which file.”

What command do you do to list all the running processes?

What is the path of the scheduled task called new-sched-task?

Syntex: Get-ScheduledTask -TaskName “YourTaskName”

Command: Get-Scheduledtask -TaskName new-sched-task

Who is the owner of the C:\

Command: Get-Acl C:\

  • Get-Acl: Retrieve Access Control List (ACL) information.
  • C:\: This is the location (in this case, the root of the C drive) for which you want to see the permissions and security settings.

Basic Scripting Challenge

So for this section your definitly going to want some programming experience TryHackme does a very brief overview but I feel like they rush into scripting a little early regadless.

What file contains the password?

Open up ISE and lets begin:

$pass_var = ‘password’

  1. $path = ‘C:\Users\Administrator\Desktop\emails\*’: Set the path variable to search for all items (files and folders) in a specific directory and its subdirectories.
  2. $pass_var = ‘password’: Set another variable to the string ‘password’.
  3. $exe = Get-ChildItem $path -Recurse | Select-String -Pattern $pass_var: Find files and folders in the specified directory and subdirectories, then look for occurrences of the string ‘password’ in their content. Store the results in a variable called $exe.
  4. echo $exe: Output the content of the variable $exe

What is the password?

The same output has the answer as well

What files contains an HTTPS link?

Change the $pass_var decleration to ‘http’

Why don’t you try writing a simple port scanner using Powershell? Here’s the general approach to use:

  • Determine IP ranges to scan(in this case it will be localhost) and you can provide the input in any way you want
  • Determine the port ranges to scan
  • Determine the type of scan to run(in this case it will be a simple TCP Connect Scan)

How many open ports did you find between 130 and 140(inclusive of those two)

$targetComputer = “localhost”

$startingPort = 130

$endingPort = 140

$port = $_

$result = Test-NetConnection -ComputerName $targetComputer -Port $port -InformationLevel Quiet

Write-Host “Port $port is open.”

Write-Host “Port $port is closed.”

Replace “localhost” with the target computer’s name or IP address if you want to check the ports on a remote machine. Save the script with a .ps1 extension, and you can run it in the PowerShell ISE or a PowerShell console.

rootshellace

System Weakness

Sometimes, when you get access to a vulnerable machine, you might want to immediately run some predefined popular scripts, written in languages as Python. But you might have the surprise to not have it installed. This is why it’s important to be used to the command line, like PowerShell or Bash.

To perform this, we will use a similar command, Get-NetFirewallProfile, to retrieve the values for Domain, Private and Public. You can simply run it without any other parameters and you will get the result. I added some things for a better formatted output.

On your screen, you should see a similar outcome:

Name    Enabled
---- -------
Domain True
Private True
Public True

This means you have your firewall enabled for all 3. Now, let’s change it. We must add 2 parameters: Profile and Enabled. The first is to know which one you want to set, and the second one is for the status. So, in case we need to disable the public firewall, we will execute:

Set-NetFirewallProfile -Profile Public -Enabled False

The key’s name is EnableLUA. Normally, its expected value is 1. To get UAC deactivated, it must be changed to 0.

Three parameters are required in this situation: Path, Name and Value. Our registry key is found in a specific path (check it on your computer! 😉), for the other two, I think you already know what it takes 😄.

Set-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System -Name EnableLUA -Value 0

Once it’s executed, only a restart stands between you and the desired effect.

Our final instance will show us how to add an exception in Windows Defender. This is quite simple, we only need one parameter, the path we want to exclude from scanning. Let’s consider a case where you want to ignore directory C:\MyPrivateTools. Just run:

Add-MpPreference -ExclusionPath C:\MyPrivateTools

That’s it! As simple as that! If, after a while, you change your mind and want this exception removed, you must execute:

Remove-MpPreference -ExclusionPath C:\MyPrivateTools

In case you want to see a demo on how these 3 cmdlets are executed and what is their effect, for instance, allowing you to run malicious programs, check my video below! 👇

This article is for educational purposes only. Attacking targets without prior mutual consent is illegal. I take no responsibility for any misuse or damage caused due to the usage of the information provided here.

If you got here, I want to thank you for the time you took to read my article. I hope you enjoyed it and also learned something from it. Why not take a look at some of my other articles? Or, maybe, watch one of my YouTube videos?

Rich

TL;DR walkthrough of the Hacking with PowerShell TryHackMe room.

A full list of our TryHackMe walkthroughs and cheatsheets are here.

Hacking with PowerShell is a good general practice room that will get one familiar with querying, piping, attributes, and basic loops along with if/else statements.

Let’s get to the questions. As always start with:

— — Task 2 — –

What is the command to get a new object?

— — Task 3 — –

What is the location of the file “interesting-file.txt”

Get-ChildItem “*interesting-file*” -Path C:\ -Recurse -ErrorAction SilentlyContinue

Specify the contents of this file

How many cmdlets are installed on the system(only cmdlets, not functions and aliases)?

Get the MD5 hash of interesting-file.txt

What is the command to get the current working directory?

What command would you use to make a request to a web server?

Base64 decode the file b64.txt on Windows.

“this is the flag — ihopeyoudidthisonwindows”

The method I used initially is for decoding the types of Bas64 attackers use for obfuscated PowerShell commands.

— — Task 4 — –

How many local groups exist?

What command did you use to get the IP address info?

How many ports are listed as listening?

What is the remote address of the local port listening on port 445?

How many patches have been applied?

When was the patch with ID KB4023834 installed?

We only get the format specified by THM if we do:

6/15/2017 12:00:00 AM

Find the contents of a backup file.

Search for all files containing API_KEY

The specific answer THM wants is:

What command do you do to list all the running processes?

What is the path of the scheduled task called new-sched-task?

Who is the owner of the C:\

(Get-Acl -Path “C:\”).Owner

Please note that you have to be very specific with the syntax of that query, otherwise you get NT AUTHORITY\SYSTEM like I did initially.

— — Task 5 — –

What file contains the password?

Desktop\emails\john\Doc3.txt:6:I got some errors trying to access my passwords file — is there any way you can help? Here is the output I got

Desktop\emails\martha\Doc3M.txt:6:I managed to fix the corrupted file to get the output, but the password is buried somewhere in these logs:

Desktop\emails\martha\Doc3M.txt:106:password is johnisalegend99

Nice, 2 answers in one query. The filename for the answer is:

What is the password?

What files contains an HTTPS link?

The answer is of course:

— — Task 6 — –

How many open ports did you find between 130 and 140(inclusive of those two)?

After assuming that THM meant TcpTestSucceeded, only gettings ports 135 and 139 open, and THM telling me that I was wrong I went with ports that responded to either ping or TCP.

Once I did that I got all 11, which THM liked as an answer.

Task 6 was really odd. If I query with Get-NetRCPConnection I only get ports 135 and 139 listed as open.

Other than that oddity it was a good room and good practice. Task 5 didn’t require any scripting, just pipe Get-ChildItem to Select-String, which is basically the PowerShell method of grep.

We wrapped up the Cyber Defense pathway recently which also wrapped up the CPEs I need for now, hence we’re just doing general practice for now.

Find text in a file: https://devblogs.microsoft.com/scripting/use-an-easy-powershell-command-to-search-files-for-information/

Оставьте комментарий