# CPENT iLab筆記 - Appendix D: PowerShell Scripting
## Exercise 1: Exploring the PowerShell Environment
Objectives
- In this lab, you will work in a Windows environment and practice the methods and techniques of information discovery and enumeration using PowerShell
Lab Duration: 20 Minutes
1. By default Windows Server 2019 machine selected, click Ctrl+Alt+Delete.

2. Click Pa$$w0rd and press Enter to login as Administrator.

3. Click on Search icon lower left corner of the Desktop and type PowerShell in the search field. From the search results right-click on Windows PowerShell and click Run as administrator.

4. Windows PowerShell window appears, click help | more and press Enter. There are many command options to use. To cover all of these is beyond the scope of this manual.

5. First, add a user to the machine. To do this first we will check with the available user accounts. Click net user and press Enter. This will list out the available user accounts in the machine.
6. As shown in the screenshot we can see the available user accounts.

7. Now, we will add a new user to the machine. Click net user cpent password /add and press Enter, or you can use any name of your choice. This command will create a user cpent.

8. Now, lets add newly created user to the Administrators group. Click net localgroup administrators cpent /add and press Enter. To confirm that new user account is created click net user and press Enter. Minimize the PowerShell window.

9. Next, check the Command-line options for the processes. You may use the graphic user interface (GUI) tool Task Manager, but tasklist is a better option. Launch Command Prompt. Type cmd in the search field and from the search results click Command Prompt.

10. In the command prompt click tasklist /? and press Enter. You need not explore all available options.

11. Type tasklist /svc | more and press Enter. This will display the services started by the process. Tracking the services that have been launched is an important early step in memory analysis.

12. Let us say you want to look for a specific process. Type tasklist /svc | findstr svchost.exe | more and press Enter. Use findstr to restrict the output to the string entered as the input, as shown in the screenshot. This allows you to quickly review a specific process and the services that the process has started. Now that you have explored the Command-line. Minimize the Command Prompt window.

13. Switch back to Windows PowerShell. Maximize the PowerShell window. Now lets enable the Execution Policy. Type Get-ExecutionPolicy and press Enter, and note the output.

14. Change the current RemoteSigned setting. Type Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine and press Enter. A warning prompt will appear, type Y and press Enter as shown in the screenshot. By executing this command you are now in an Unrestricted state.

15. Type get-help a* and press Enter to view all cmdlets that start with an “a.” A warning prompt will appear, type Y and press Enter as shown in the screenshot. Once you press Enter the PowerShell will start updating. It may take couple of minutes to update.


16. You can create and customize a variety of different queries—for example. Type get-service |where { $_.Status -eq "running" } | select-object -last 10 and press Enter.
- Consider the above example: “get-service” is a collection of services
- Use “|” to query the collection
- Inside where “$_” collection variable as in LINQ (C#); the query is to find running services out of the collection
- Take only the last 10 items (services) in the filtered collection (running services)
17. An example of the get-service command in use is shown in the screenshot.
Note: Use the command New-LocalUser to add a user. For the syntax of the command, enter New-LocalUser /?. Enter the information requested in the prompt that appears.

18. PowerShell has multiple help options. Type Get-Help copy-item and press Enter, which produces one level of help.

19. The next level of help is the detailed command. Type Get-Help Copy-Item -detailed | more and press Enter.

20. Next, explore the full option. Type Get-Help Copy-Item -full | more and press Enter.

21. Another great assist is the ability to see the syntax for a command. Type Get-Help Copy-Item -Example and press Enter. The output from this command is shown in the screenshot.

22. The PowerShell cmdlets are highly capable and good for practice. This concludes the lab exercise.
---------------------
## Exercise 2: Leveraging PowerShell
Objectives
In this lab, you will work from the Command-line and explore PowerShell to familiarize yourself with its power
Lab Duration: 20 Minutes
1. By default Windows Server 2019 machine selected, click Ctrl+Alt+Delete.
Note: If you are already logged in skip to step 4.

2. Click Pa$$w0rd and press Enter to login as Administrator.

3. Click on Search icon lower left corner of the Desktop and type PowerShell in the search field. From the search results right-click on Windows PowerShell and click Run as administrator.

4. Owing to the numerous attacks leveraging PowerShell, setup your system to use remote administration. type winrm quickconfig and press Enter. Make these changes? warning appears, type y and press Enter.
Notice: If you receive a message stating that WinRM firewall exception is enabled, then you must change the firewall setting, so your connection is not “Public.” This is another protection mechanism in Windows. Disable the firewall.


5. Most corporate network machines are configured to a private or domain setting, which is advantageous.
6. Without the GUI, use the Command-line for a different method. Type Set-NetConnectionProfile -NetworkCategory Private and press Enter.

7. Since this is a setup now, Type the following commands:
```shell=
winrm set winrm/config/service/auth ‘@{Basic="true"}’
```

```shell=
winrm set winrm/config/client/auth ‘@{Basic="true"}’
```

```shell=
winrm set winrm/config/service ‘@{AllowUnencrypted="true"}’
```

```shell=
Set-Item WSMan:\localhost\Client\TrustedHosts -value "*" -Force
```

8. To test the configuration, type winrm get winrm/config | more and press Enter. A partial example is shown in the screenshot.

9. Extract the TrustedHost directly, type Get-Item WSMan:\localhost\Client\TrustedHosts and press Enter.

10. To verify if the connection is ready. Type Get-NetTCPConnection | Where-Object -Property LocalPort -EQ 5985 and press Enter. The output from this command is shown in the screenshot.
Notice: If you are trying to connect from another Windows machine, use the command $Session = New-PSSession -ComputerName .

11. Finally verify the configuration. Type winrm get winrm/config | more and press Enter. A partial example is shown in the screenshot. Minimize all the windows.

12. Switch to UbuntuWeb-PS machine. Click Student profile and then type password in the Password field and press Enter.
Note: If the machine is locked, scroll your mouse cursor in upside direction.

13. Click Show Applications icon lower left corner of the Desktop. In the Search field type text editor and from the search results click Text Editor to launch.
You can choose any text editor of your choice.

14. Type the following code in the text editor as shown in the screenshot:
Note: 192.168.177.20 is the IP address of Windows Server 2019 machine.

15. Click Save. Save As window appears, type the file name as testingrm.py and choose the location to save the file and then click Save. In this Exercise we are choosing Desktop as the location. Minimize the text editor window.


16. Switch to Windows Server 2019 machine, and double-click Wireshark shortcut icon on Desktop to launch the application.
Note: If Software Update window appears, click Skip this version or Remind me later.
17. Double-click on the Interface to start capturing the network traffic (here, Ethernet2).

18. Switch to UbuntuWeb-PS and launch a Terminal, and change the Directory to Desktop by typing cd Desktop and Enter.

19. In the terminal, type python testingrm.py and press Enter. If the machine name appears as the output, the step has been successful. You have remotely pulled data using the winrm python module.

20. Switch to Windows Server 2019 and stop the Wireshark capture by clicking on Red Color button.

21. Now, choose any packet as shown in the screenshot. Right-click on the packer and click Follow | TCP Stream (here, Packet #70).

22. You can review the data in Wireshark as shown in the screenshot. Close the all the windows in Windows Server 2019 machine. The User-Agent is Python WinRm on Basic Authorization.

23. Now, switch to UbuntuWeb-PS and modify our script code to provide us more information. Add the following code to the script section of the script and save the file. Maximize the testingrm.py text editor and add the highlighted code as shown in the screenshot, and click Save from the File menu. Minimize the text editor window.

24. Now, in the terminal type python3 testingrm.py and press Enter. You have now extracted the Process ID information from the machine. You may run any command, since you have access to the machine. Your output might not be as clean as the image, but the data are still there.

25. Let us look at the event logs. Switch to Text Editor and type the highlighted code as shown in the screenshot, and Save the text editor.

26. Switch to terminal and python3 testingrm.py and press Enter. You have now extracted the events from the logs using the ForEach-Object cmdlet. This cmdlet will take each output line from the preceding command, and then perform an action on it. In this example, you have instructed it to list the newest 10 items from the event log that it found from the list. This should retrieve the latest 10 events from each log in the event log.

This concludes the lab exercise.
-------------------
## Exercise 3: Attempting Powershell Execution Bypass
Objectives
- In this lab, you will work from the Command-line and explore PowerShell
Lab Duration: 20 Minutes
Check if you can bypass a PowerShell execution policy if you gain access to a machine that is appropriately set up. Note that this manual uses PowerShell 5, and not PowerShell 7, which was not installed by default. In the latter, you will inevitably run into more challenges. According to Microsoft, the execution policy is part of the security strategy of PowerShell. It determines whether you can load configuration files (including your PowerShell profile) and run scripts; it determines which scripts, if any, must be digitally signed before running. It should be noted that Microsoft claims the ExecutionPolicy was never intended to be a security control.
1. By default Windows Server 2019 machine selected, click Ctrl+Alt+Delete.
Note: If you are already logged in skip to step 4.

2. Click Pa$$w0rd and press Enter to login as Administrator.

3. Click on Search icon lower left corner of the Desktop and type PowerShell in the search field. From the search results right-click on Windows PowerShell and click Run as administrator.

4. Next, change the execution policy. Type Set-ExecutionPolicy -ExecutionPolicy Restricted and press Enter. A warning prompt appears, type Y and press Enter.

5. You now have basic low privilege access to a Windows machine. Upgrade your shell to something more stable, or to add. Verify that you have successfully set the setting. Type Get-ExecutionPolicy and press Enter.

6. Review the list of policies. Type Get-ExecutionPolicy -List | Format-Table -AutoSize and press Enter. Minimize the Windows PowerShell.

7. Create a simple script for your testing. In the Search field type Notepad++ and click Notepad++ from the search result.
Note: If Notepad++ update pop-up appears, click No.

8. In the Notepad++ type the below simple code:
```
Write-Host "Testing Execution Bypass"
calc.exe
```

9. Click Save. Save As window appears, type test.ps1 in the File name field, choose the desired location and click Save. In this we are saving the file on Desktop. Minimize the Notepad++ window.

10. In the above script, you are only writing a string, and then running the calculator program. Now, maximize the PowerShell window, and change the Directory location Desktop. Type cd Desktop and press Enter.
11. Now, run the script. Type test.ps1 and press Enter.

12. You cannot run the script because of the setting. Try to change the execution policy. Type Set-ExecutionPolicy Unrestricted and press Enter. A warning prompt appears, type Y and press Enter.

13. Verify that you have successfully set the setting. Type Get-ExecutionPolicy and press Enter.

14. However, you cannot change the policy from a low privileged shell. Attempt to run the command directly. In the PowerShell type Write-Host “This is a bypass test” and press Enter. Next, type calc.exe and press Enter. Close the Calc.exe program that opens.

15. Next, type in the commands directly to bypass it. Pipe the script, type Get-Content ./test.ps1 | powershell.exe -noprofile – and press Enter. Close the Calc.exe program that opens.

16. Download the script from the URL (Remote and Local) and execute with the Invoke Expression. Type the following code as shown in the screenshot and press Enter:
```shell=
powershell -nop -c “iex(New-Object Net.WebClient).DownloadString(‘test.ps1’)”
```
17. Close the Calc.exe program that opens.

18. Next, try the command switch. Type powershell -command “Write-Host ‘This is a bypass test’ ; calc.exe” and press Enter. Close the Calc.exe program that opens.

19. You will find that this command works for the bypass.
20. Next, use the Invoke Expression command. Type Get-Content .\test.ps1 | Invoke-Expression and press Enter. Close the Calc.exe program that opens.

21. Now, type powershell -ExecutionPolicy Bypass -File .\test.ps1 and press Enter. Close the Calc.exe program that opens.

22. This command works as well and has been noted as a reason that the ExecutionPolicy is not a security feature. Another method is to set the Scope. Type Set-ExecutionPolicy Bypass -Scope Process and press Enter. A warning prompt appears, type Y and press Enter.

23. To check if it worked, re-check the policy. Type Get-ExecutionPolicy -List | Format-Table -AutoSize and press Enter.

24. Now, type .\test.ps1 and press Enter.

25. You are not familiar with multiple ways to bypass the ExecutionPolicy. This manual uses Windows Server 2019. This concludes the lab exercise.