steamguard-cli 0.4.0

A command line utility to generate Steam 2FA codes and respond to confirmations.
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
using Newtonsoft.Json;
using SteamAuth;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace SteamGuard
{
	public class Manifest
	{
		private const int PBKDF2_ITERATIONS = 50000; //Set to 50k to make program not unbearably slow. May increase in future.
		private const int SALT_LENGTH = 8;
		private const int KEY_SIZE_BYTES = 32;
		private const int IV_LENGTH = 16;

		[JsonProperty("encrypted")]
		public bool Encrypted { get; set; }

		[JsonProperty("first_run")]
		public bool FirstRun { get; set; } = true;

		[JsonProperty("entries")]
		public List<ManifestEntry> Entries { get; set; }

		[JsonProperty("periodic_checking")]
		public bool PeriodicChecking { get; set; } = false;

		[JsonProperty("periodic_checking_interval")]
		public int PeriodicCheckingInterval { get; set; } = 5;

		[JsonProperty("periodic_checking_checkall")]
		public bool CheckAllAccounts { get; set; } = false;

		[JsonProperty("auto_confirm_market_transactions")]
		public bool AutoConfirmMarketTransactions { get; set; } = false;

		[JsonProperty("auto_confirm_trades")]
		public bool AutoConfirmTrades { get; set; } = false;

		private static Manifest _manifest { get; set; }

		public static Manifest GetManifest(bool forceLoad = false)
		{
			// Check if already staticly loaded
			if (_manifest != null && !forceLoad)
			{
				return _manifest;
			}

			// Find config dir and manifest file
			string maFile = Path.Combine(Program.SteamGuardPath, "manifest.json");

			// If there's no config dir, create it
			if (!Directory.Exists(Program.SteamGuardPath))
			{
				_manifest = _generateNewManifest();
				return _manifest;
			}

			// If there's no manifest, create it
			if (!File.Exists(maFile))
			{
				Utils.Verbose("warn: No manifest file found at {0}", maFile);
				bool? createNewManifest = Program.SteamGuardPath ==
										  Program.defaultSteamGuardPath.Replace("~", Environment.GetEnvironmentVariable("HOME")) ? true : (bool?) null;
				while (createNewManifest == null)
				{
					Console.Write($"Generate new manifest.json in {Program.SteamGuardPath}? [Y/n]");
					var answer = Console.ReadLine();
					if (answer != null)
						createNewManifest = !answer.StartsWith("n") && !answer.StartsWith("N");
				}
				if ((bool) createNewManifest)
				{
					_manifest = _generateNewManifest(true);
					return _manifest;
				}
				return null;
			}

			try
			{
				string manifestContents = File.ReadAllText(maFile);
				_manifest = JsonConvert.DeserializeObject<Manifest>(manifestContents);

				if (_manifest.Encrypted && _manifest.Entries.Count == 0)
				{
					_manifest.Encrypted = false;
					_manifest.Save();
				}

				_manifest.RecomputeExistingEntries();

				Utils.Verbose($"{_manifest.Entries.Count} accounts loaded");
				return _manifest;
			}
			catch (Exception ex)
			{
				Console.WriteLine("error: Could not open manifest file: {0}", ex.ToString());
				return null;
			}
		}

		private static Manifest _generateNewManifest(bool scanDir = false)
		{
			Utils.Verbose("Generating new manifest...");

			// No directory means no manifest file anyways.
			Manifest newManifest = new Manifest();
			newManifest.Encrypted = false;
			newManifest.PeriodicCheckingInterval = 5;
			newManifest.PeriodicChecking = false;
			newManifest.AutoConfirmMarketTransactions = false;
			newManifest.AutoConfirmTrades = false;
			newManifest.Entries = new List<ManifestEntry>();
			newManifest.FirstRun = true;

			// Take a pre-manifest version and generate a manifest for it.
			if (scanDir)
			{
				if (Directory.Exists(Program.SteamGuardPath))
				{
					DirectoryInfo dir = new DirectoryInfo(Program.SteamGuardPath);
					var files = dir.GetFiles();

					foreach (var file in files)
					{
						if (file.Extension != ".maFile") continue;

						string contents = File.ReadAllText(file.FullName);
						try
						{
							SteamGuardAccount account = JsonConvert.DeserializeObject<SteamGuardAccount>(contents);
							ManifestEntry newEntry = new ManifestEntry()
							{
								Filename = file.Name,
								SteamID = account.Session.SteamID
							};
							newManifest.Entries.Add(newEntry);
						}
						catch (Exception ex)
						{
							Utils.Verbose("warn: {0}", ex.Message);
						}
					}

					if (newManifest.Entries.Count > 0)
					{
						newManifest.Save();
						newManifest.PromptSetupPassKey(true);
					}
				}
			}

			if (newManifest.Save())
			{
				return newManifest;
			}

			return null;
		}

		public class IncorrectPassKeyException : Exception { }
		public class ManifestNotEncryptedException : Exception { }

		// TODO: move PromptForPassKey to Program.cs
		// TODO: make PromptForPassKey more secure
		public string PromptForPassKey()
		{
			if (!this.Encrypted)
			{
				throw new ManifestNotEncryptedException();
			}

			bool passKeyValid = false;
			string passKey = "";
			while (!passKeyValid)
			{
				Console.WriteLine("Please enter encryption password: ");
				passKey = Utils.ReadLineSecure();
				if (passKey == "")
					continue;
				passKeyValid = this.VerifyPasskey(passKey);
				if (!passKeyValid)
				{
					Console.WriteLine("Incorrect.");
				}
			}
			return passKey;
		}

		// TODO: move PromptSetupPassKey to Program.cs
		public string PromptSetupPassKey(bool inAccountSetupProcess = false)
		{
			if (inAccountSetupProcess)
			{
				Console.Write("Would you like to use encryption? [Y/n] ");
				string doEncryptAnswer = Console.ReadLine();
				if (doEncryptAnswer == "n" || doEncryptAnswer == "N")
				{
					Console.WriteLine("WARNING: You chose to not encrypt your files. Doing so imposes a security risk for yourself. If an attacker were to gain access to your computer, they could completely lock you out of your account and steal all your items.");
					Console.WriteLine("You may add encryption later using the --encrypt argument.");
					return null;
				}
			}

			string newPassKey = "";
			string confirmPassKey = "";
			do
			{
				Console.Write("Enter" + (inAccountSetupProcess ? " " : " new ") + "passkey: ");
				newPassKey = Utils.ReadLineSecure();
				Console.Write("Confirm" + (inAccountSetupProcess ? " " : " new ") + "passkey: ");
				confirmPassKey = Utils.ReadLineSecure();

				if (newPassKey != confirmPassKey)
				{
					Console.WriteLine("Passkeys do not match.");
				}
			} while (newPassKey != confirmPassKey || newPassKey == "");

			return newPassKey;
		}

		public SteamAuth.SteamGuardAccount[] GetAllAccounts(string passKey = null, int limit = -1)
		{
			if (passKey == null && this.Encrypted) return new SteamGuardAccount[0];

			List<SteamAuth.SteamGuardAccount> accounts = new List<SteamAuth.SteamGuardAccount>();
			foreach (var entry in this.Entries)
			{
				var account = GetAccount(entry, passKey);
				if (account == null) continue;
				accounts.Add(account);

				if (limit != -1 && limit >= accounts.Count)
					break;
			}

			return accounts.ToArray();
		}

		public SteamGuardAccount GetAccount(ManifestEntry entry, string passKey = null)
		{
			string fileText = "";
			Stream stream = null;
			RijndaelManaged aes256;

			string filename = Path.Combine(Program.SteamGuardPath, entry.Filename);
			if (this.Encrypted)
			{
				MemoryStream ms = new MemoryStream(Convert.FromBase64String(File.ReadAllText(filename)));
				byte[] key = GetEncryptionKey(passKey, entry.Salt);

				aes256 = new RijndaelManaged
				{
					IV = Convert.FromBase64String(entry.IV),
					Key = key,
					Padding = PaddingMode.PKCS7,
					Mode = CipherMode.CBC
				};

				ICryptoTransform decryptor = aes256.CreateDecryptor(aes256.Key, aes256.IV);
				stream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
				Utils.Verbose($"Decrypting {filename}...");
			}
			else
			{
				FileStream fileStream = File.OpenRead(filename);
				stream = fileStream;
			}

			using (StreamReader reader = new StreamReader(stream))
			{
				fileText = reader.ReadToEnd();
			}
			stream.Close();

			return JsonConvert.DeserializeObject<SteamAuth.SteamGuardAccount>(fileText);
		}

		public bool VerifyPasskey(string passkey)
		{
			if (!this.Encrypted || this.Entries.Count == 0) return true;

			var accounts = this.GetAllAccounts(passkey, 1);
			return accounts != null && accounts.Length == 1;
		}

		public bool RemoveAccount(SteamGuardAccount account, bool deleteMaFile = true)
		{
			ManifestEntry entry = (from e in this.Entries where e.SteamID == account.Session.SteamID select e).FirstOrDefault();
			if (entry == null) return true; // If something never existed, did you do what they asked?

			string filename = Path.Combine(Program.SteamGuardPath, entry.Filename);
			this.Entries.Remove(entry);

			if (this.Entries.Count == 0)
			{
				this.Encrypted = false;
			}

			if (this.Save() && deleteMaFile)
			{
				try
				{
					File.Delete(filename);
					return true;
				}
				catch (Exception)
				{
					return false;
				}
			}

			return false;
		}

		public bool SaveAccount(SteamGuardAccount account, bool encrypt, string passKey = null, string salt = null, string iV = null)
		{
			if (encrypt && (String.IsNullOrEmpty(passKey) || String.IsNullOrEmpty(salt) || String.IsNullOrEmpty(iV))) return false;

			string jsonAccount = JsonConvert.SerializeObject(account);

			string filename = account.Session.SteamID.ToString() + ".maFile";
			Utils.Verbose($"Saving account {account.AccountName} to {filename}...");

			ManifestEntry newEntry = new ManifestEntry()
			{
				SteamID = account.Session.SteamID,
				IV = iV,
				Salt = salt,
				Filename = filename
			};

			bool foundExistingEntry = false;
			for (int i = 0; i < this.Entries.Count; i++)
			{
				if (this.Entries[i].SteamID == account.Session.SteamID)
				{
					this.Entries[i] = newEntry;
					foundExistingEntry = true;
					break;
				}
			}

			if (!foundExistingEntry)
			{
				this.Entries.Add(newEntry);
			}

			bool wasEncrypted = this.Encrypted;
			this.Encrypted = encrypt;

			if (!this.Save())
			{
				this.Encrypted = wasEncrypted;
				return false;
			}

			try
			{
				Stream stream = null;
				MemoryStream ms = null;
				RijndaelManaged aes256;

				if (encrypt)
				{
					ms = new MemoryStream();
					byte[] key = GetEncryptionKey(passKey, newEntry.Salt);

					aes256 = new RijndaelManaged
					{
						IV = Convert.FromBase64String(newEntry.IV),
						Key = key,
						Padding = PaddingMode.PKCS7,
						Mode = CipherMode.CBC
					};

					ICryptoTransform encryptor = aes256.CreateEncryptor(aes256.Key, aes256.IV);
					stream = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
				}
				else
				{
					// An unencrypted maFile is shorter than the encrypted version,
					// so when an unencrypted maFile gets written this way, the file does not get wiped
					// leaving encrypted text after the final } bracket. Deleting and recreating the file fixes this.
					File.Delete(Path.Combine(Program.SteamGuardPath, newEntry.Filename));
					stream = File.OpenWrite(Path.Combine(Program.SteamGuardPath, newEntry.Filename)); // open or create
				}

				using (StreamWriter writer = new StreamWriter(stream))
				{
					writer.Write(jsonAccount);
				}

				if (encrypt)
				{
					File.WriteAllText(Path.Combine(Program.SteamGuardPath, newEntry.Filename), Convert.ToBase64String(ms.ToArray()));
				}

				stream.Close();
				return true;
			}
			catch (Exception ex)
			{
				Utils.Verbose("error: {0}", ex.ToString());
				return false;
			}
		}

		public bool Save()
		{
			string filename = Path.Combine(Program.SteamGuardPath, "manifest.json");
			if (!Directory.Exists(Program.SteamGuardPath))
			{
				try
				{
					Utils.Verbose("Creating {0}", Program.SteamGuardPath);
					Directory.CreateDirectory(Program.SteamGuardPath);
				}
				catch (Exception ex)
				{
					Utils.Verbose($"error: {ex.Message}");
					return false;
				}
			}

			try
			{
				string contents = JsonConvert.SerializeObject(this);
				File.WriteAllText(filename, contents);
				return true;
			}
			catch (Exception ex)
			{
				Utils.Verbose($"error: {ex.Message}");
				return false;
			}
		}

		private void RecomputeExistingEntries()
		{
			List<ManifestEntry> newEntries = new List<ManifestEntry>();

			foreach (var entry in this.Entries)
			{
				string filename = Path.Combine(Program.SteamGuardPath, entry.Filename);

				if (File.Exists(filename))
				{
					newEntries.Add(entry);
				}
			}

			this.Entries = newEntries;

			if (this.Entries.Count == 0)
			{
				this.Encrypted = false;
			}
		}

		public void MoveEntry(int from, int to)
		{
			if (from < 0 || to < 0 || from > Entries.Count || to > Entries.Count - 1) return;
			ManifestEntry sel = Entries[from];
			Entries.RemoveAt(from);
			Entries.Insert(to, sel);
			Save();
		}

		public class ManifestEntry
		{
			[JsonProperty("encryption_iv")]
			public string IV { get; set; }

			[JsonProperty("encryption_salt")]
			public string Salt { get; set; }

			[JsonProperty("filename")]
			public string Filename { get; set; }

			[JsonProperty("steamid")]
			public ulong SteamID { get; set; }
		}

		/*
		 Crypto Functions
		*/

		/// <summary>
		/// Returns an 8-byte cryptographically random salt in base64 encoding
		/// </summary>
		/// <returns></returns>
		public static string GetRandomSalt()
		{
			byte[] salt = new byte[SALT_LENGTH];
			using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
			{
				rng.GetBytes(salt);
			}
			return Convert.ToBase64String(salt);
		}

		/// <summary>
		/// Returns a 16-byte cryptographically random initialization vector (IV) in base64 encoding
		/// </summary>
		/// <returns></returns>
		public static string GetInitializationVector()
		{
			byte[] IV = new byte[IV_LENGTH];
			using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
			{
				rng.GetBytes(IV);
			}
			return Convert.ToBase64String(IV);
		}

		/// <summary>
		/// Generates an encryption key derived using a password, a random salt, and specified number of rounds of PBKDF2
		/// </summary>
		/// <param name="password"></param>
		/// <param name="salt"></param>
		/// <returns></returns>
		private static byte[] GetEncryptionKey(string password, string salt)
		{
			if (string.IsNullOrEmpty(password))
			{
				throw new ArgumentException("Password is empty");
			}
			if (string.IsNullOrEmpty(salt))
			{
				throw new ArgumentException("Salt is empty");
			}
			using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, Convert.FromBase64String(salt), PBKDF2_ITERATIONS))
			{
				return pbkdf2.GetBytes(KEY_SIZE_BYTES);
			}
		}
	}
}