-
Notifications
You must be signed in to change notification settings - Fork 1
/
Program.cs
689 lines (557 loc) · 21.3 KB
/
Program.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
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.IdentityModel.JsonWebTokens;
using QRCoder;
using Spectre.Console;
using SteamKit2;
using SteamKit2.Authentication;
#pragma warning disable CA1031 // Do not catch general exception types
[assembly: CLSCompliant(false)]
namespace SteamTokenDumper;
internal static class Program
{
private static SteamClient steamClient;
private static CallbackManager manager;
private static SteamUser steamUser;
private static bool licenseListReceived;
private static bool isAskingForInput;
private static bool suggestedQrCode;
private static readonly CancellationTokenSource ExitToken = new();
private static string pass;
private static SavedCredentials savedCredentials = new();
private static AuthSession authSession;
private static int reconnectCount;
private static readonly Configuration Configuration = new();
private static readonly ApiClient ApiClient = new();
private static readonly Payload Payload = new();
private static KnownDepotIds KnownDepotIds;
private static string RememberCredentialsFile;
public static string AppPath { get; private set; }
public static bool IsConnected => steamClient.IsConnected;
public static TaskCompletionSource<bool> ReconnectEvent { get; private set; } = new();
public static async Task Main()
{
WindowsDisableConsoleQuickEdit.Disable();
Console.Title = "SteamDB Token Dumper";
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
AppPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName);
RememberCredentialsFile = Path.Combine(AppPath, "SteamTokenDumper.credentials.bin");
KnownDepotIds = new();
try
{
var sentryHashFile = Path.Combine(AppPath, "SteamTokenDumper.sentryhash.bin");
if (File.Exists(sentryHashFile))
{
AnsiConsole.WriteLine("Deleting stored credentials from previous token dumper version.");
File.Delete(sentryHashFile);
File.Delete(RememberCredentialsFile);
}
}
catch
{
// don't care
}
AnsiConsole.Write(new FigletText("SteamDB").Color(Color.BlueViolet));
AnsiConsole.Write(
new Panel(new Markup("Read [link]https://steamdb.info/tokendumper/[/] before using this\n\nTake a look at the '[u]SteamTokenDumper.config.ini[/]' file for possible options.", new Style(Color.Blue)))
.BorderColor(Color.BlueViolet)
.RoundedBorder()
);
AnsiConsole.Write(
new Panel(new Text("If you are in a closed or limited beta, have a non disclosure agreement,\nor otherwise do not want to leak private information, do not use this program.", new Style(Color.Yellow)))
.BorderColor(Color.GreenYellow)
.RoundedBorder()
);
AnsiConsole.WriteLine();
await ReadConfiguration();
AnsiConsole.WriteLine();
if (Configuration.UserConsentBeforeRun)
{
SinkUnreadKeys();
if (!AnsiConsole.Confirm("Are you sure you want to continue?", false))
{
AnsiConsole.WriteLine("Press any key to exit...");
Console.ReadKey();
return;
}
}
if (!await ApiClient.IsUpToDate())
{
AnsiConsole.WriteLine("Press any key to exit...");
Console.ReadKey();
return;
}
await KnownDepotIds.Load(ApiClient);
if (!Configuration.SkipAutoGrant)
{
AnsiConsole.WriteLine();
try
{
SteamClientData.ReadFromSteamClient(Payload, KnownDepotIds);
}
catch (Exception e)
{
AnsiConsole.Write(
new Panel(new Text($"Failed to read Steam client data: {e}", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
}
AnsiConsole.WriteLine();
if (savedCredentials.RefreshToken != null)
{
AnsiConsole.Write(
new Panel(new Markup($"Logging in using previously remembered login.\nDelete '[u]{Markup.Escape(Path.GetFileName(RememberCredentialsFile))}[/]' file if you want it forgotten.", new Style(Color.Green)))
.BorderColor(Color.Green)
.RoundedBorder()
);
AnsiConsole.WriteLine();
await InitializeSteamKit();
}
else
{
suggestedQrCode = true;
AnsiConsole.Write(
new Panel(new Markup($"Logging in means this program can do a thorough dump, as getting tokens from Steam files only works for installed games.\n\nEnter \"[bold]qr[/]\" into the username field if you would like to scan a QR code with your Steam mobile app.", new Style(Color.Green)))
.BorderColor(Color.Green)
.RoundedBorder()
);
AnsiConsole.WriteLine();
SinkUnreadKeys();
savedCredentials.Username = AnsiConsole.Prompt(new TextPrompt<string>("Enter your Steam username:")
{
AllowEmpty = true
});
if (string.IsNullOrEmpty(savedCredentials.Username))
{
AnsiConsole.WriteLine("Doing an anonymous dump.");
Payload.SteamID = new SteamID((uint)Random.Shared.Next(), EUniverse.Public, EAccountType.AnonUser).Render();
await ApiClient.SendTokens(Payload, Configuration);
}
else if (savedCredentials.Username is not "anonymous" and not "qr")
{
pass = AnsiConsole.Prompt(new TextPrompt<string>("Enter your Steam password:")
{
IsSecret = true
});
await InitializeSteamKit();
}
else
{
await InitializeSteamKit();
}
}
SinkUnreadKeys();
AnsiConsole.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static async Task ReadConfiguration()
{
try
{
await Configuration.Load();
}
catch (FileNotFoundException e)
{
AnsiConsole.Write(
new Panel(new Text(e.Message, new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
catch (Exception e)
{
AnsiConsole.Write(
new Panel(new Text($"Failed to read config: {e}", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
try
{
await ReadCredentials();
}
catch (Exception e)
{
AnsiConsole.Write(
new Panel(new Text($"Failed to read stored credentials: {e}", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
}
private static async Task ReadCredentials()
{
if (!Configuration.RememberLogin)
{
return;
}
if (!File.Exists(RememberCredentialsFile))
{
return;
}
var encryptedBytes = await File.ReadAllBytesAsync(RememberCredentialsFile);
var decryptedData = CryptoHelper.SymmetricDecrypt(encryptedBytes);
savedCredentials = JsonSerializer.Deserialize(decryptedData, SavedCredentialsJsonContext.Default.SavedCredentials);
if (savedCredentials.Version != SavedCredentials.CurrentVersion)
{
savedCredentials = new();
throw new InvalidDataException($"Got incorrect saved credentials version.");
}
}
private static async Task SaveCredentials()
{
if (!Configuration.RememberLogin)
{
return;
}
try
{
var json = JsonSerializer.SerializeToUtf8Bytes(savedCredentials, new SavedCredentialsJsonContext(new JsonSerializerOptions
{
WriteIndented = true,
}).SavedCredentials);
var encryptedData = CryptoHelper.SymmetricEncrypt(json);
await File.WriteAllBytesAsync(RememberCredentialsFile, encryptedData);
}
catch (Exception e)
{
AnsiConsole.Write(
new Panel(new Text($"Failed to save credentials: {e}", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
}
private static void ReadCredentialsAgain()
{
isAskingForInput = true;
steamClient.Disconnect();
if (!suggestedQrCode)
{
suggestedQrCode = true;
AnsiConsole.WriteLine();
AnsiConsole.WriteLine("Enter \"qr\" into the username field if you would like to scan a QR code with your Steam mobile app.");
}
AnsiConsole.WriteLine();
SinkUnreadKeys();
savedCredentials.Username = AnsiConsole.Ask("Enter your Steam username:", savedCredentials.Username ?? string.Empty);
if (savedCredentials.Username is not "anonymous" and not "qr")
{
pass = AnsiConsole.Prompt(new TextPrompt<string>("Enter your Steam password:")
{
IsSecret = true
});
}
isAskingForInput = false;
steamClient.Connect();
}
private static async Task InitializeSteamKit()
{
DebugLog.AddListener(new SteamKitLogger());
DebugLog.Enabled = Configuration.Debug;
var config = SteamConfiguration.Create(b => b
.WithProtocolTypes(ProtocolTypes.WebSocket)
);
steamClient = new SteamClient(config, "Dumper");
manager = new CallbackManager(steamClient);
steamUser = steamClient.GetHandler<SteamUser>();
manager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
manager.Subscribe<SteamClient.DisconnectedCallback>(OnDisconnected);
manager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
manager.Subscribe<SteamApps.LicenseListCallback>(OnLicenseList);
AnsiConsole.WriteLine("Connecting to Steam...");
steamClient.Connect();
try
{
while (!ExitToken.IsCancellationRequested)
{
await manager.RunWaitCallbackAsync(ExitToken.Token);
}
}
catch (OperationCanceledException)
{
//
}
}
private static async void OnConnected(SteamClient.ConnectedCallback callback)
{
AnsiConsole.WriteLine("Connected to Steam");
if (savedCredentials.Username == "anonymous")
{
steamUser.LogOnAnonymous();
return;
}
if (authSession == null)
{
try
{
if (savedCredentials.Username == "qr")
{
var qrAuthSession = await steamClient.Authentication.BeginAuthSessionViaQRAsync(new AuthSessionDetails
{
DeviceFriendlyName = nameof(SteamTokenDumper),
});
qrAuthSession.ChallengeURLChanged = () => DrawQRCode(qrAuthSession);
DrawQRCode(qrAuthSession);
authSession = qrAuthSession;
}
else if (savedCredentials.RefreshToken == null)
{
authSession = await steamClient.Authentication.BeginAuthSessionViaCredentialsAsync(new AuthSessionDetails
{
Password = pass,
Username = savedCredentials.Username,
IsPersistentSession = Configuration.RememberLogin,
DeviceFriendlyName = nameof(SteamTokenDumper),
Authenticator = new ConsoleAuthenticator(),
});
}
}
catch (AuthenticationException e)
{
isAskingForInput = true;
AnsiConsole.Write(
new Panel(new Text(
e.Result == EResult.InvalidPassword ?
"You have entered an invalid username or password." :
$"Something went wrong trying to begin authentication ({e.Result})",
new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
ReadCredentialsAgain();
return;
}
}
if (authSession != null)
{
try
{
var pollResponse = await authSession.PollingWaitForResultAsync();
savedCredentials.Username = pollResponse.AccountName;
savedCredentials.RefreshToken = pollResponse.RefreshToken;
}
catch (TaskCanceledException)
{
AnsiConsole.WriteLine("Previous authentication polling was cancelled.");
return;
}
await SaveCredentials();
}
authSession = null;
pass = null; // Password should not be needed
AnsiConsole.WriteLine("Logging in...");
steamUser.LogOn(new SteamUser.LogOnDetails
{
LoginID = 0x44_55_4D_50, // "DUMP"
Username = savedCredentials.Username,
Password = savedCredentials.RefreshToken == null ? pass : null,
AccessToken = savedCredentials.RefreshToken,
ShouldRememberPassword = Configuration.RememberLogin,
});
}
private static void DrawQRCode(QrAuthSession authSession)
{
using var qrGenerator = new QRCodeGenerator();
var qrCodeData = qrGenerator.CreateQrCode(authSession.ChallengeURL, QRCodeGenerator.ECCLevel.L);
const int QuietZone = 6;
const int QuietZoneOffset = QuietZone / 2;
var size = qrCodeData.ModuleMatrix.Count - QuietZone;
var canvas = new Canvas(size, size)
{
Scale = false,
};
for (var y = 0; y < size; y++)
{
for (var x = 0; x < size; x++)
{
var module = qrCodeData.ModuleMatrix[y + QuietZoneOffset][x + QuietZoneOffset];
canvas.SetPixel(x, y, module ? Color.Gold1 : Color.Black);
}
}
AnsiConsole.WriteLine();
AnsiConsole.Write(new Panel(canvas)
{
Header = new(" Use the Steam Mobile App to sign in via QR code ", Justify.Center)
}.RoundedBorder());
}
private static void OnDisconnected(SteamClient.DisconnectedCallback callback)
{
if (ExitToken.IsCancellationRequested)
{
AnsiConsole.WriteLine("Disconnected from Steam, exiting...");
return;
}
if (isAskingForInput || callback.UserInitiated)
{
AnsiConsole.WriteLine($"Disconnected from Steam, waiting for user input to finish...");
return;
}
var sleep = (1 << reconnectCount) * 1000;
reconnectCount++;
if (sleep < 5_000)
{
sleep = 5_000;
}
else if (sleep > 120_000)
{
sleep = 120_000;
}
sleep += Random.Shared.Next(1001);
AnsiConsole.WriteLine($"Disconnected from Steam, reconnecting in {sleep / 1000} seconds...");
Thread.Sleep(sleep);
steamClient.Connect();
}
private static void OnLoggedOn(SteamUser.LoggedOnCallback callback)
{
if (callback.Result != EResult.OK)
{
if (callback.Result is EResult.ServiceUnavailable or EResult.TryAnotherCM)
{
AnsiConsole.Write(
new Panel(new Text($"Steam is currently having issues ({callback.Result})...", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
else if (callback.Result
is EResult.InvalidPassword
or EResult.InvalidSignature
or EResult.AccessDenied
or EResult.Expired
or EResult.Revoked)
{
isAskingForInput = true;
reconnectCount = 0;
if (savedCredentials.RefreshToken != null)
{
savedCredentials.RefreshToken = null;
AnsiConsole.Write(
new Panel(new Text($"Stored credentials are invalid. ({callback.Result})", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
Task.Run(SaveCredentials);
}
else
{
AnsiConsole.Write(
new Panel(new Text("You have entered an invalid username or password.", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
}
ReadCredentialsAgain();
}
else
{
AnsiConsole.Write(
new Panel(new Text($"Unable to logon to Steam: {callback.Result} ({callback.ExtendedResult})", new Style(Color.Red)))
.BorderColor(Color.Red)
.RoundedBorder()
);
ExitToken.Cancel();
}
return;
}
reconnectCount = 0;
if (licenseListReceived)
{
AnsiConsole.WriteLine("Logged on, continuing...");
ReconnectEvent.SetResult(true);
ReconnectEvent = new();
return;
}
Task.Run(RenewRefreshTokenIfRequired);
var steamid = callback.ClientSteamID ?? new SteamID(0, EUniverse.Public, EAccountType.Invalid);
Payload.SteamID = steamid.Render();
if (steamid.AccountType == EAccountType.AnonUser)
{
AnsiConsole.WriteLine("Logged on, requesting package for anonymous users...");
const uint ANONYMOUS_PACKAGE = 17906;
var requester = new Requester(Payload, steamClient.GetHandler<SteamApps>(), KnownDepotIds, Configuration);
Task.Run(async () =>
{
var tokenJob = await steamClient.GetHandler<SteamApps>().PICSGetAccessTokens(null, ANONYMOUS_PACKAGE);
tokenJob.PackageTokens.TryGetValue(ANONYMOUS_PACKAGE, out var token);
await DoRequest(requester,
[
new(ANONYMOUS_PACKAGE, token)
]);
});
}
else
{
AnsiConsole.WriteLine("Logged on, waiting for licenses...");
}
}
private static async Task RenewRefreshTokenIfRequired()
{
if (!Configuration.RememberLogin || savedCredentials.RefreshToken == null)
{
return;
}
try
{
var token = new JsonWebToken(savedCredentials.RefreshToken);
AnsiConsole.WriteLine($"Refresh token is valid until {token.ValidTo:yyyy-MM-dd HH:mm:ss}");
if (DateTime.UtcNow.Add(TimeSpan.FromDays(30)) >= token.ValidTo)
{
var newToken = await steamClient.Authentication.GenerateAccessTokenForAppAsync(steamClient.SteamID, savedCredentials.RefreshToken, allowRenewal: true);
if (!string.IsNullOrEmpty(newToken.RefreshToken))
{
AnsiConsole.WriteLine("Renewed the refresh token");
savedCredentials.RefreshToken = newToken.RefreshToken;
await SaveCredentials();
}
}
}
catch (Exception)
{
//
}
}
private static void OnLicenseList(SteamApps.LicenseListCallback licenseList)
{
if (licenseListReceived)
{
return;
}
licenseListReceived = true;
var requester = new Requester(Payload, steamClient.GetHandler<SteamApps>(), KnownDepotIds, Configuration);
var packages = requester.ProcessLicenseList(licenseList);
Task.Factory.StartNew(
async () => await DoRequest(requester, packages),
CancellationToken.None,
TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning,
TaskScheduler.Default
);
}
private static async Task DoRequest(Requester requester, List<SteamApps.PICSRequest> packages)
{
await requester.ProcessPackages(packages);
var success = await ApiClient.SendTokens(Payload, Configuration);
if (success)
{
await KnownDepotIds.SaveKnownDepotIds();
}
await ExitToken.CancelAsync();
steamUser.LogOff();
}
private static void SinkUnreadKeys()
{
while (Console.KeyAvailable)
{
Console.ReadKey(true);
}
}
}