Skip to content

Commit

Permalink
Start using dependency injection
Browse files Browse the repository at this point in the history
  • Loading branch information
riskydissonance committed Mar 4, 2022
1 parent cf87150 commit 4c4282a
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 53 deletions.
1 change: 1 addition & 0 deletions SharpSocksCommon/Encryption/RijndaelCBCCryptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public class RijndaelCBCCryptor : IEncryptionHelper

public RijndaelCBCCryptor(string base64Key)
{
Console.WriteLine("[*] Using Rijndael CBC encryption");
_key.AddRange(Convert.FromBase64String(base64Key));
}

Expand Down
23 changes: 11 additions & 12 deletions SharpSocksServer/Config/SharpSocksConfig.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System;
using System.Security.Cryptography;
using McMaster.Extensions.CommandLineUtils;
using SharpSocksServer.Logging;

namespace SharpSocksServer.Config
{
Expand All @@ -21,11 +20,11 @@ public class SharpSocksConfig
public ushort CommandLimit { get; private init; }
public bool WaitOnConnect { get; private init; }

private static string ValidateHttpServer(ILogOutput logger, string serverUri)
private static string ValidateHttpServer(string serverUri)
{
if (string.IsNullOrWhiteSpace(serverUri))
{
logger.LogMessage("URI to listen is blank defaulting to http://127.0.0.1:8081");
Console.WriteLine("[*] URI to listen is blank defaulting to http://127.0.0.1:8081");
serverUri = "http://127.0.0.1:8081";
}

Expand All @@ -34,25 +33,25 @@ private static string ValidateHttpServer(ILogOutput logger, string serverUri)
return serverUri;
}

private static string ValidateCmdChannelId(ILogOutput logger, string commandChannelId)
private static string ValidateCmdChannelId(string commandChannelId)
{
if (!string.IsNullOrWhiteSpace(commandChannelId)) return commandChannelId;
logger.LogMessage($"Command Channel Id is blank defaulting to {DEFAULT_COMMAND_CHANNEL_ID}");
Console.WriteLine($"[*] Command Channel Id is blank defaulting to {DEFAULT_COMMAND_CHANNEL_ID}");
return string.IsNullOrWhiteSpace(commandChannelId) ? DEFAULT_COMMAND_CHANNEL_ID : commandChannelId;
}

private static string ValidateEncryptionKey(ILogOutput logger, string encryptionKey)
private static string ValidateEncryptionKey(string encryptionKey)
{
if (!string.IsNullOrWhiteSpace(encryptionKey))
return encryptionKey;
var aes = Aes.Create();
aes.GenerateKey();
var base64String = Convert.ToBase64String(aes.Key);
logger.LogMessage($"Using encryption key (base64'd) {base64String}");
Console.WriteLine($"[*] Using encryption key (base64'd) {base64String}");
return base64String;
}

public static SharpSocksConfig LoadConfig(ILogOutput logger, CommandOption optSocksServerUri, CommandOption optSocketTimeout, CommandOption optCmdChannelId,
public static SharpSocksConfig LoadConfig(CommandOption optSocksServerUri, CommandOption optSocketTimeout, CommandOption optCmdChannelId,
CommandOption optEncKey, CommandOption optSessionCookie, CommandOption optPayloadCookie, CommandOption optVerbose, CommandOption optHttpServer)
{
var socksHostPort = !optSocksServerUri.HasValue() || string.IsNullOrWhiteSpace(optSocksServerUri.Value()) ? "*:43334" : optSocksServerUri.Value();
Expand Down Expand Up @@ -80,7 +79,7 @@ public static SharpSocksConfig LoadConfig(ILogOutput logger, CommandOption optSo
if (!convertedSuccessfully)
{
timeout = 30U;
logger.LogMessage($"Defaulting Socket Timeout to {timeout}s");
Console.WriteLine($"[*] Defaulting Socket Timeout to {timeout}s");
}

timeout *= 1000U;
Expand All @@ -89,13 +88,13 @@ public static SharpSocksConfig LoadConfig(ILogOutput logger, CommandOption optSo
{
SocksIP = socksIpToListen,
SocksPort = socksPort,
CommandChannelId = ValidateCmdChannelId(logger, optCmdChannelId.Value()),
EncryptionKey = ValidateEncryptionKey(logger, optEncKey.Value()),
CommandChannelId = ValidateCmdChannelId(optCmdChannelId.Value()),
EncryptionKey = ValidateEncryptionKey(optEncKey.Value()),
SessionCookieName = optSessionCookie.Value() ?? "ASP.NET_SessionId",
PayloadCookieName = optPayloadCookie.Value() ?? "__RequestVerificationToken",
SocketTimeout = timeout,
Verbose = optVerbose.HasValue(),
HttpServerURI = ValidateHttpServer(logger, optHttpServer.Value()),
HttpServerURI = ValidateHttpServer(optHttpServer.Value()),
WaitOnConnect = true,
CommandLimit = 20
};
Expand Down
11 changes: 7 additions & 4 deletions SharpSocksServer/HttpServer/HttpServerController.cs
Original file line number Diff line number Diff line change
@@ -1,32 +1,35 @@
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using SharpSocksServer.Config;
using SharpSocksServer.ImplantComms;
using SharpSocksServer.Logging;

namespace SharpSocksServer.HttpServer
{
public class HttpServerController
{
public HttpServerController(ILogOutput logger, EncryptedC2RequestProcessor requestProcessor)
public HttpServerController(ILogOutput logger, EncryptedC2RequestProcessor requestProcessor, SharpSocksConfig config)
{
Logger = logger;
RequestProcessor = requestProcessor;
Config = config;
}

private ILogOutput Logger { get; }
private EncryptedC2RequestProcessor RequestProcessor { get; }
private SharpSocksConfig Config { get; }

public void StartHttp(string httpServerUri)
public void StartHttp()
{
var httpAsyncListener = new HttpAsyncListener(RequestProcessor, Logger);
httpAsyncListener.CreateListener(new Dictionary<string, X509Certificate2>
{
{
httpServerUri,
Config.HttpServerURI,
null
}
});
Logger.LogMessage($"C2 HTTP processor listening on {httpServerUri}");
Logger.LogMessage($"C2 HTTP processor listening on {Config.HttpServerURI}");
}
}
}
15 changes: 8 additions & 7 deletions SharpSocksServer/Logging/ConsoleOutput.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
using System;
using SharpSocksServer.Config;

namespace SharpSocksServer.Logging
{
public class ConsoleOutput : ILogOutput
{
private bool _verbose;
private readonly bool _verbose;

public ConsoleOutput(SharpSocksConfig config)
{
_verbose = config.Verbose;
}

public void LogError(string errorMessage)
{
Expand All @@ -26,17 +32,12 @@ public void LogMessage(string message)

public void LogImportantMessage(string message)
{
Console.WriteLine($"[{DateTime.Now}][!] {message}");
Console.WriteLine($"[{DateTime.Now}][!][!] {message} [!][!]");
}

public bool IsVerboseOn()
{
return _verbose;
}

public void SetVerboseOn()
{
_verbose = true;
}
}
}
38 changes: 21 additions & 17 deletions SharpSocksServer/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using McMaster.Extensions.CommandLineUtils;
using Microsoft.Extensions.DependencyInjection;
using SharpSocksCommon.Encryption;
using SharpSocksServer.Config;
using SharpSocksServer.HttpServer;
Expand All @@ -11,46 +12,49 @@ namespace SharpSocksServer
{
internal static class Program
{
private static readonly ConsoleOutput LOGGER = new();
private static CommandLineApplication _app;

private static void Main(string[] args)
{
Console.WriteLine("SharpSocks Server\r\n=================\n");
try
{
Console.WriteLine("[*] Initialising...");
var config = ParseArgs(args);

if (config.Verbose)
LOGGER.SetVerboseOn();
var services = new ServiceCollection()
.AddSingleton(config)
.AddSingleton<IEncryptionHelper>(new RijndaelCBCCryptor(config.EncryptionKey))
.AddSingleton<EncryptedC2RequestProcessor>()
.AddSingleton<HttpServerController>()
.AddSingleton<ServerController>()
.AddSingleton<ILogOutput, ConsoleOutput>();

SocksProxy.Logger = LOGGER;
var serviceProvider = services.BuildServiceProvider();

var cryptor = new RijndaelCBCCryptor(config.EncryptionKey);
LOGGER.LogMessage("Using Rijndael CBC encryption");
var logger = serviceProvider.GetRequiredService<ILogOutput>();
SocksProxy.Logger = logger;

var requestProcessor = new EncryptedC2RequestProcessor(LOGGER, cryptor, config);
var httpServerController = new HttpServerController(LOGGER, requestProcessor);
var socksServerController = new ServerController(LOGGER, config, requestProcessor);
var httpServerController = serviceProvider.GetRequiredService<HttpServerController>();
var serverController = serviceProvider.GetRequiredService<ServerController>();
Console.WriteLine("[*] Initialised");

httpServerController.StartHttp();
serverController.StartSocks();

httpServerController.StartHttp(config.HttpServerURI);
socksServerController.StartSocks(config.SocksIP, config.SocksPort);
logger.LogImportantMessage("Press x to quit");

LOGGER.LogMessage("Press x to quit\r\n");
while ("x" != Console.ReadLine())
{
}
}
catch (Exception e)
{
LOGGER.LogError(e);
Console.WriteLine($"[-] Fatal Error: {e}");
}
}

private static SharpSocksConfig ParseArgs(string[] args)
{
_app = new CommandLineApplication();
var _app = new CommandLineApplication();
_app.HelpOption();
var optSocksServerUri = _app.Option("-s|--socksserveruri", "IP:Port for SOCKS to listen on, default is *:43334", CommandOptionType.SingleValue);
var optCmdChannelId = _app.Option("-c|--cmdid", "Command Channel Identifier, needs to be shared with the server", CommandOptionType.SingleValue);
Expand All @@ -64,7 +68,7 @@ private static SharpSocksConfig ParseArgs(string[] args)
SharpSocksConfig config = null;
_app.OnExecute(() =>
{
config = SharpSocksConfig.LoadConfig(LOGGER, optSocksServerUri, optSocketTimeout, optCmdChannelId, optEncKey, optSessionCookie, optPayloadCookie,
config = SharpSocksConfig.LoadConfig(optSocksServerUri, optSocketTimeout, optCmdChannelId, optEncKey, optSessionCookie, optPayloadCookie,
optVerbose, optHttpServer);
});
_app.Execute(args);
Expand Down
5 changes: 3 additions & 2 deletions SharpSocksServer/SharpSocksServer.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<OutputType>Exe</OutputType>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<RootNamespace>SharpSocksServer</RootNamespace>
Expand Down Expand Up @@ -31,11 +31,12 @@
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SharpSocksCommon\SharpSocksCommon.csproj"/>
<ProjectReference Include="..\SharpSocksCommon\SharpSocksCommon.csproj"/>
</ItemGroup>
<ItemGroup>
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="4.0.0-beta.74"/>
<PackageReference Include="Microsoft.CSharp" Version="4.7.0"/>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0-preview.1.22076.8"/>
<PackageReference Include="System.CodeDom" Version="6.0.0-rc.2.21480.5"/>
<PackageReference Include="System.ComponentModel.Annotations" Version="6.0.0-preview.4.21253.7"/>
<PackageReference Include="System.Data.DataSetExtensions" Version="4.6.0-preview3.19128.7"/>
Expand Down
20 changes: 9 additions & 11 deletions SharpSocksServer/SocksServer/SocksServerController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,28 @@ public class ServerController
public ServerController(ILogOutput logger, SharpSocksConfig config, EncryptedC2RequestProcessor requestProcessor)
{
Logger = logger;
WaitOnConnect = config.WaitOnConnect;
SocketTimeout = config.SocketTimeout;
Config = config;
RequestProcessor = requestProcessor;
}

private ILogOutput Logger { get; }
private bool WaitOnConnect { get; }
private uint SocketTimeout { get; }
private SharpSocksConfig Config { get; }
private EncryptedC2RequestProcessor RequestProcessor { get; }

public void StartSocks(string ipToListen, ushort localPort)
public void StartSocks()
{
Logger.LogMessage($"Wait for Implant TCP Connect before SOCKS Proxy response is {(WaitOnConnect ? "on" : "off")}");
Logger.LogMessage($"Wait for Implant TCP Connect before SOCKS Proxy response is {(Config.WaitOnConnect ? "on" : "off")}");
if (RequestProcessor.CmdChannelRunningEvent == null)
{
StartSocksInternal(ipToListen, localPort);
StartSocksInternal(Config.SocksIP, Config.SocksPort);
return;
}

Task.Factory.StartNew((Action)(() =>
{
Logger.LogMessage("Waiting for command channel before starting SOCKS proxy");
Logger.LogImportantMessage("Waiting for command channel before starting SOCKS proxy");
RequestProcessor.CmdChannelRunningEvent.WaitOne();
StartSocksInternal(ipToListen, localPort);
StartSocksInternal(Config.SocksIP, Config.SocksPort);
}));
}

Expand Down Expand Up @@ -86,9 +84,9 @@ private void AcceptTcpClient(IAsyncResult asyncResult)
Logger.LogMessage($"[Client -> SOCKS Server] New request from to {tcpListener.LocalEndpoint} from {tcpClient.Client.RemoteEndPoint}");
new SocksProxy
{
TotalSocketTimeout = SocketTimeout,
TotalSocketTimeout = Config.SocketTimeout,
SocketComms = RequestProcessor
}.ProcessRequest(tcpClient, WaitOnConnect);
}.ProcessRequest(tcpClient, Config.WaitOnConnect);
}
catch (Exception e)
{
Expand Down

0 comments on commit 4c4282a

Please sign in to comment.