1
mirror of https://github.com/rapid7/metasploit-payloads synced 2024-11-26 17:41:08 +01:00

Include the MSF.Powershell project

This commit is contained in:
OJ 2016-03-22 13:11:49 +10:00
parent d48066c4cf
commit 6e5afca1b3
12 changed files with 1253 additions and 595 deletions

6
powershell/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
*.dll
Debug
Release
*.tlb
*.suo
*.ncb

View File

@ -0,0 +1,52 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{FA166AAC-7D05-4B71-99CE-015C9BD23483}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MSF.Powershell</RootNamespace>
<AssemblyName>MSF.Powershell</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\lib\System.Management.Automation.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Runner.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,28 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.40629.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSF.Powershell", "MSF.Powershell.csproj", "{FA166AAC-7D05-4B71-99CE-015C9BD23483}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSF.PowershellTester", "MSF.PowershellTester\MSF.PowershellTester.csproj", "{E19828C6-E40D-4CAE-8D49-5F4892DFD4B7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FA166AAC-7D05-4B71-99CE-015C9BD23483}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FA166AAC-7D05-4B71-99CE-015C9BD23483}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FA166AAC-7D05-4B71-99CE-015C9BD23483}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FA166AAC-7D05-4B71-99CE-015C9BD23483}.Release|Any CPU.Build.0 = Release|Any CPU
{E19828C6-E40D-4CAE-8D49-5F4892DFD4B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E19828C6-E40D-4CAE-8D49-5F4892DFD4B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E19828C6-E40D-4CAE-8D49-5F4892DFD4B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E19828C6-E40D-4CAE-8D49-5F4892DFD4B7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v2.0.50727"/></startup>
</configuration>

View File

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{E19828C6-E40D-4CAE-8D49-5F4892DFD4B7}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MSF.PowershellTester</RootNamespace>
<AssemblyName>MSF.PowershellTester</AssemblyName>
<TargetFrameworkVersion>v2.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MSF.Powershell.csproj">
<Project>{fa166aac-7d05-4b71-99ce-015c9bd23483}</Project>
<Name>MSF.Powershell</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace MSF.PowershellTester
{
class Program
{
static void Main(string[] args)
{
var x = MSF.Powershell.Runner.Get("Default");
System.Console.Write(x.Execute("$x = $(whoami)"));
System.Console.Write(x.Execute("$x"));
MSF.Powershell.Runner.Remove("Default");
}
}
}

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MSF.PowershellTester")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MSF.PowershellTester")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2e110f97-a562-43a8-9ba3-25dfa7d73b9d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MSF.Powershell")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MSF.Powershell")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("90b5c30b-96da-4b94-941a-3fb826c50509")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,360 @@
using System;
using System.Collections.Generic;
using System.Management.Automation.Host;
using System.Management.Automation.Runspaces;
using System.Text;
namespace MSF.Powershell
{
public class Runner : IDisposable
{
// We use a dictionary of runners based on ID, this means that we can maintain
// separate sessions if we want to.
private static Dictionary<string, Runner> _runners;
private InitialSessionState _state;
private CustomPSHost _host = null;
private Runspace _runspace = null;
private string _id;
static Runner()
{
System.Diagnostics.Debug.Write("Static constructor called");
_runners = new Dictionary<string, Runner>();
}
public static string Execute(string id, string ps)
{
System.Diagnostics.Debug.Write(string.Format("Executing command on session {0}", id));
if (!_runners.ContainsKey(id))
{
_runners.Add(id, new Runner(id));
}
var runner = _runners[id];
return runner.Execute(ps);
}
public static Runner Get(string id)
{
if (!_runners.ContainsKey(id))
{
_runners.Add(id, new Runner(id));
}
return _runners[id];
}
public static void Remove(string id)
{
if (_runners.ContainsKey(id))
{
_runners[id].Dispose();
_runners.Remove(id);
}
}
public Runner(string id)
{
_id = id;
_state = InitialSessionState.CreateDefault();
_state.AuthorizationManager = null;
_host = new CustomPSHost();
_runspace = RunspaceFactory.CreateRunspace(_host, _state);
_runspace.Open();
}
public string Execute(string ps)
{
using (Pipeline pipeline = _runspace.CreatePipeline())
{
pipeline.Commands.AddScript(ps);
pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
pipeline.Commands.Add("out-default");
pipeline.Invoke();
}
return _host.GetAndFlushOutput();
}
public void Dispose()
{
if (_runspace != null)
{
_runspace.Close();
_runspace.Dispose();
}
}
private class CustomPSHost : PSHost
{
private Guid _hostId;
private CustomPSHostUserInterface _ui = null;
public CustomPSHost()
{
_hostId = Guid.NewGuid();
_ui = new CustomPSHostUserInterface();
}
public string GetAndFlushOutput()
{
var output = _ui.ToString();
_ui.Clear();
return output;
}
public override System.Globalization.CultureInfo CurrentCulture
{
get { return System.Threading.Thread.CurrentThread.CurrentCulture; }
}
public override System.Globalization.CultureInfo CurrentUICulture
{
get { return System.Threading.Thread.CurrentThread.CurrentUICulture; }
}
public override void EnterNestedPrompt()
{
}
public override void ExitNestedPrompt()
{
}
public override Guid InstanceId
{
get { return _hostId; }
}
public override string Name
{
get { return "MSFConsole"; }
}
public override void NotifyBeginApplication()
{
}
public override void NotifyEndApplication()
{
}
public override void SetShouldExit(int exitCode)
{
}
public override PSHostUserInterface UI
{
get { return _ui; }
}
public override Version Version
{
get { return new Version(0, 1); }
}
}
private class CustomPSHostUserInterface : PSHostUserInterface
{
private StringBuilder _buffer;
private CustomPSHostRawUserInterface _rawUI;
public CustomPSHostUserInterface()
{
_buffer = new StringBuilder();
_rawUI = new CustomPSHostRawUserInterface();
}
public override string ToString()
{
return _buffer.ToString();
}
public void Clear()
{
_buffer.Remove(0, _buffer.Length);
}
public override Dictionary<string, System.Management.Automation.PSObject> Prompt(string caption, string message, System.Collections.ObjectModel.Collection<FieldDescription> descriptions)
{
return new Dictionary<string, System.Management.Automation.PSObject>();
}
public override int PromptForChoice(string caption, string message, System.Collections.ObjectModel.Collection<ChoiceDescription> choices, int defaultChoice)
{
return 0;
}
public override System.Management.Automation.PSCredential PromptForCredential(string caption, string message, string userName, string targetName, System.Management.Automation.PSCredentialTypes allowedCredentialTypes, System.Management.Automation.PSCredentialUIOptions options)
{
return null;
}
public override System.Management.Automation.PSCredential PromptForCredential(string caption, string message, string userName, string targetName)
{
return null;
}
public override PSHostRawUserInterface RawUI
{
get { return _rawUI; }
}
public override string ReadLine()
{
return string.Empty;
}
public override System.Security.SecureString ReadLineAsSecureString()
{
return new System.Security.SecureString();
}
public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
{
_buffer.Append(value);
}
public override void Write(string value)
{
_buffer.Append(value);
}
public override void WriteDebugLine(string message)
{
_buffer.Append("DEBUG: ");
_buffer.AppendLine(message);
}
public override void WriteErrorLine(string value)
{
_buffer.Append("ERROR: ");
_buffer.AppendLine(value);
}
public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
{
_buffer.AppendLine(value);
}
public override void WriteLine(string value)
{
_buffer.AppendLine(value);
}
public override void WriteLine()
{
_buffer.AppendLine();
}
public override void WriteProgress(long sourceId, System.Management.Automation.ProgressRecord record)
{
}
public override void WriteVerboseLine(string message)
{
_buffer.Append("VERBOSE: ");
_buffer.AppendLine(message);
}
public override void WriteWarningLine(string message)
{
_buffer.Append("WARNING: ");
_buffer.AppendLine(message);
}
}
private class CustomPSHostRawUserInterface : PSHostRawUserInterface
{
public override ConsoleColor BackgroundColor
{
get { return ConsoleColor.Black; }
set { }
}
public override Size BufferSize
{
get { return new Size(120, 100); }
set { }
}
public override Coordinates CursorPosition
{
get { return new Coordinates(0, 0); }
set { }
}
public override int CursorSize
{
get { return 1; }
set { }
}
public override void FlushInputBuffer()
{
}
public override ConsoleColor ForegroundColor
{
get { return ConsoleColor.White; }
set { }
}
public override BufferCell[,] GetBufferContents(Rectangle rectangle)
{
return new BufferCell[0,0];
}
public override bool KeyAvailable
{
get { return false; }
}
public override Size MaxPhysicalWindowSize
{
get { return new Size(int.MaxValue, int.MaxValue); }
}
public override Size MaxWindowSize
{
get { return new Size(120, 100); }
}
public override KeyInfo ReadKey(ReadKeyOptions options)
{
return new KeyInfo();
}
public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
{
}
public override void SetBufferContents(Rectangle rectangle, BufferCell fill)
{
}
public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
{
}
public override Coordinates WindowPosition
{
get { return new Coordinates(-200, -200); }
set { }
}
public override Size WindowSize
{
get { return new Size(120, 100); }
set { }
}
public override string WindowTitle
{
get { return string.Empty; }
set { }
}
}
}
}

58
powershell/build/generate.py Executable file
View File

@ -0,0 +1,58 @@
#!/usr/bin/env python
import os
bin_path = os.path.join('..', 'MSF.Powershell', 'bin', 'Release', 'MSF.Powershell.dll')
target_path = os.path.join('..', '..', 'c', 'meterpreter', 'source', 'extensions', 'powershell')
size_var = 'PSHRUNNER_DLL_LEN'
def read_all(path):
with open(path, 'rb') as f:
return f.read()
def write_all(path, content):
if os.path.isfile(path):
os.remove(path)
with open(path, 'wb') as f:
f.write(content)
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i + n]
binary = read_all(bin_path)
header = ''
header += '/*!\n'
header += ' * @file powershell_runner.h\n'
header += ' * @brief This file is generated, do not modify directly.\n'
header += ' */\n\n'
header += '#ifndef _METERPRETER_SOURCE_EXTENSION_POWERSHELL_RUNNER_H\n'
header += '#define _METERPRETER_SOURCE_EXTENSION_POWERSHELL_RUNNER_H\n\n'
header += '#define {0} {1}\n\n'.format(size_var, len(binary))
header += 'extern unsigned char PowerShellRunnerDll[{0}];\n\n'.format(size_var)
header += '#endif\n'
source = ''
source += '/*!\n'
source += ' * @file powershell_runner.cpp\n'
source += ' * @brief This file is generated, do not modify directly.\n'
source += ' */\n\n'
source += '#include "powershell_runner.h"\n\n'
source += '#pragma message("Compiling PowerShellRunner into app. Size: {0}")\n\n'.format(len(binary))
source += 'unsigned char PowerShellRunnerDll[{0}] =\n'.format(size_var)
source += '{\n\t'
blobs = []
for c in chunks(binary, 12):
blobs += [', '.join(['0x' + b.encode('hex') for b in c])]
source += ',\n\t'.join(blobs)
source += '\n};\n\n'
header_path = os.path.join(target_path, 'powershell_runner.h')
source_path = os.path.join(target_path, 'powershell_runner.cpp')
write_all(header_path, header)
write_all(source_path, source)
print "[!] Content written. .NET Binary is {0} bytes".format(len(binary))

Binary file not shown.