-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathpswRecovery4Moz.c
2943 lines (2844 loc) · 114 KB
/
pswRecovery4Moz.c
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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// pswRecovery4Moz
// Copyright (C) 2011-11-30 by Philipp Schmidt (ph i lipp (AT]
// ps ch mi dt.it, w/o spaces and (AT] replaced)
//
// This Program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// It is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this source files. If not, see
// <http://www.gnu.org/licenses/>.
// Credits:
// Credits go to Dr Stephen Henson for his research for "Netscape Key Databases"
// (see http://www.drh-consultancy.demon.co.uk/key3.html)
// Hopefully I didn't forget anybody else who reserves credits (but drop a mail
// if that would be the case)
// Of course sources from the OpenSSL libraries were also taken into account
// Thanks for that stuff too,bros
// Instructions:
// compile this file w/ the command:
// gcc pswRecovery4Moz.c -ldl # -o pswRecovery4Moz
//
// more instuctions under: http://www.pschmidt.it/?a=:e%20pswRecovery4Moz.txt
// Contribution/Report bugs:
// Don't hesitate to contribute to this tool.Contributors wanted!
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <string.h>
#include <sys/stat.h> /* declare the 'stat' structure */
#include <dlfcn.h>
#include <ctype.h>
#define VERSION "0.1"
#define PROGRAM "pswRecovery4Moz"
#define BUF_MAX_SMALL 256
#define BUF_MAX 500
#define BUF_MAX_LARGE 2000
#define BUF_MAX_HUGE 8192
#define RAW_OUTPUT 0 // Do not show additional status notification,hide unneeded details (iff 1)
#define GS_LENGTH 20
#define PK_DEFAULT_LENGTH 0x93
#define PASSWORD_CHECK_LENGTH 16 // Fixed length of global salt
#define PASSWORD_CHECK_SEARCH "password-check"
#define KEY3_SEARCH "global-salt"
#define KEY_NULL_PREFIX "00 "
#define KEY3_HEADER_SIZE 3
#define CONVERSION_LENGTH 20 // Fixed sized used in SHA1-HMAC etc conversion (e.g. for padding)
#define MOZ_KEY_SIZE 24
#define MOZ_IV_SIZE 8
#define PATH_DELIMITER '/'
#define PATHS_DELIMITER ':'
#define MOZ_LOGIN_TOKEN_NAME "NSS Certificate DB"
#define SQLITE_OPEN_READONLY 0x00000001
#define SHA1CircularShift(bits,word)((((word)<<(bits))&0xFFFFFFFF)|((word)>>(32-(bits))))
// ASN1 CONSTANTS
const char*ASN1_NAMES[]={/*1*/"BOOLEAN","INTEGER","BIT STRING","OCTET STRING","NULL","OBJECT IDENTIFIER",
"OBJECT DESCRIPTOR","EXTERNAL",/*9*/"REAL","ENUMERATED","EMBEDDED PDV","UTF8String","RELATIVE-OID","",
"",/*16*/"SEQUENCE","SET","NUMERIC STRING","PRINTABLE STRING","","VIDEOTEXT STRING","IA5String",
"UTC STRING","GENERALIZED TIME","GRAPHIC STRING",/*26*/"VISIBLE STRING","GENERAL STRING","UNIVERSAL STRING",
"CHARACTER STRING","BMP STRING",/*omit*/"","","","","","","","","","","","","","","","","",/*48*/"SEQUENCE"};
#define ASN1_INDENTATION 4
#define ASN1_SEQUENCE 48
#define ASN1_BOOLEAN 1
#define ASN1_NULL 9
#define ASN1_DEFAULT_NAME 18 // Character string
#define NSS_LIBRARY_NAME "libnss3.so"
#define SQLITE_LIBRARY_NAME "libsqlite3.so"
#define SQLITE_NAME_ADD_SUFFIX ".0"
#define MOZ_SIGNONS "signons.sqlite"
#define MOZ_SIGNONS_QUERY "SELECT hostname,httpRealm,encryptedUsername,encryptedPassword FROM moz_logins;"
#define MOZ_KEY3DB "key3.db"
#define MOZ_DEFAULT_LIB_PATH "/usr/lib/:/usr/lib/x86_64-linux-gnu/:/usr/lib/x86_64/:/usr/lib/x86_64-linux/: \
/usr/lib64/:/usr/lib32/"
#define FF_USER_PATH "/.mozilla/firefox/"
#define TB_USER_PATH "/.thunderbird/"
#define TB_PATH_SEARCH "thunderbird"
#define MOZ_INI_NAME "profiles.ini"
#define MOZ_DEFAULT_PASSWORD ""
//Following key is used as entry key to get the private key from key3.db (NOTHING special,nor any secret key whatsoever)
//We do NOT even need to hard-code it since it can be either extracted from signons.sqlite OR we have the private key
//directly specified as command line argument (=> forget it)
//#define MOZ_DEFAULT_KEYID "f8 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01"
// some global variables (we can somehow omit also those if you really insist,but who cares)
unsigned int cmdline_raw=0;
int isNSSInitialized=0;
// libs
void*libnss=NULL;
void*libsqlite=NULL;
void*libtmp=NULL;
// some typedefs
typedef enum SECItemType {
Buffer=0,
ClearDataBuffer=1,
CipherDataBuffer=2,
DERCertBuffer=3,
EncodedCertBuffer=4,
DERNameBuffer=5,
EncodedNameBuffer=6,
AsciiNameString=7,
AsciiString=8,
DEROID=9,
UnsignedInteger=10,
UTCTime=11,
GeneralizedTime=12
}SECItemType;
struct SECItem {
SECItemType type;
unsigned char*data;
unsigned int len;
};
typedef enum SECStatus {
SECWouldBlock=-2,
SECFailure=-1,
SECSuccess=0
}SECStatus;
typedef struct rsaEncryption {
char*keyID;
char*key;
struct rsaEncryption*next;
}rsaEncryptionNode;
typedef struct PK11SlotInfoStr PK11SlotInfo;
typedef SECStatus (*NSS_Init)(const char *configdir);
typedef SECStatus (*NSS_Shutdown)(void);
typedef PK11SlotInfo*(*PK11_GetInternalKeySlot)(void);
typedef int (*PK11_NeedLogin)(PK11SlotInfo*slot);
typedef char* (*PK11_GetTokenName)(PK11SlotInfo*slot);
typedef SECStatus (*PK11_Authenticate)(PK11SlotInfo*slot,int cert,void*pass);
typedef SECStatus (*PK11_CheckUserPassword)(PK11SlotInfo*slot,char*pass);
typedef SECStatus (*PK11SDR_Decrypt)(struct SECItem*data,struct SECItem*result,void*cx);
typedef void (*PK11_FreeSlot)(PK11SlotInfo*slot);
typedef int (*SQLite_Open)(const char*file,void**db,int,const char*vfs);
typedef int (*SQLite_Close)(void*db);
typedef int (*SQLite_Get_Table)(void*db,const char*query,char***res,int*rows,int*columns,char**errorMsg);
typedef int (*SQLite_Free_Table)(char**table);
NSS_Init NSSInit=NULL;
NSS_Shutdown NSSShutdown=NULL;
PK11_GetInternalKeySlot PK11GetInternalKeySlot=NULL;
PK11_CheckUserPassword PK11CheckUserPassword=NULL;
PK11_NeedLogin PK11NeedLogin=NULL;
PK11_GetTokenName PK11GetTokenName=NULL;
PK11_Authenticate PK11Authenticate=NULL;
PK11SDR_Decrypt PK11SDRDecrypt=NULL;
PK11_FreeSlot PK11FreeSlot=NULL;
SQLite_Open SQLiteOpen=NULL;
SQLite_Close SQLiteClose=NULL;
SQLite_Get_Table SQLiteGetTable=NULL;
SQLite_Free_Table SQLiteFreeTable=NULL;
// helper functions
void str2lower(char*str) {
int i,n=strlen(str);
for(i=0;i<n;i++) {
if (str[i]>=65&&str[i]<=90) {
str[i]+=32;
}
}
}
int testOpenFile(const char*filePath) {
FILE*tmpFile=fopen(filePath,"r");
if (tmpFile==NULL) {
return 1;
}
fclose(tmpFile);
return 0;
}
int fileExists(char*path) {
struct stat stat_p;
stat(path,&stat_p);
return S_ISREG(stat_p.st_mode)&&!testOpenFile(path);
}
int dirExists(char*path) {
struct stat stat_p;
stat(path,&stat_p);
return S_ISDIR(stat_p.st_mode);
}
char*getMozProfilePath(int print,const char*path) {
char profilePath[BUF_MAX_SMALL];
char profileFile[BUF_MAX_SMALL];
char line[1024];
unsigned long pathSize=BUF_MAX_SMALL;
char *finalProfilePath;
int isDefaultFound=0;
char userPath[BUF_MAX];
strcpy(userPath,getenv("HOME"));
if (userPath==NULL||strlen(userPath)<0) {
struct passwd*pw=getpwuid(getuid());
if (pw) {
strcpy(userPath,pw->pw_dir);
} else {
if (print) {
printf("[-] Failed to get user home path\n");
}
return NULL;
}
}
strcat(userPath,path);
strcpy(profilePath,userPath);
strcpy(profileFile,userPath);
strcat(profileFile,MOZ_INI_NAME);
FILE*profile=fopen(profileFile,"r");
if (!profile) {
if (print) {
printf("[-] Failed to open/find profile file: %s\n",profileFile);
}
return NULL;
}
while(fgets(line,1024,profile)) {
str2lower(line);
if (!isDefaultFound&&(strstr(line,"name=default")!=NULL)) {
isDefaultFound=1;
continue;
}
if (isDefaultFound) {
if (strstr(line,"path=")!=NULL) {
char *slash=strstr(line,"/");
if (slash!=NULL) {
*slash='\\';
}
line[strlen(line)-1]=0;
char*start=strstr(line,"=");
int totalLen=strlen(profilePath)+strlen(start)+3;
finalProfilePath=(char*)malloc(totalLen);
if (finalProfilePath) {
strcpy(finalProfilePath,profilePath);
strcat(finalProfilePath,start+1);
if (print&&!cmdline_raw) {
printf("[i] Profile path: %s\n",finalProfilePath);
}
}
break;
}
}
}
fclose(profile);
return finalProfilePath;
}
void*loadLibrary(char*mozDir,const char*libName) {
char loadPath[BUF_MAX_HUGE]="";
if (mozDir==NULL||libName==NULL||strlen(mozDir)<1) {
printf("[-] Please specify a library path (-l)\n");
return 0;
}
char*dirPtr=mozDir,*lastPtr=mozDir,*foundPtr=NULL;
do {
foundPtr=strchr(dirPtr,PATHS_DELIMITER);
if (foundPtr&&foundPtr!=lastPtr) {
if (lastPtr!=mozDir) {
strncpy(loadPath,dirPtr,foundPtr-lastPtr-1);
loadPath[foundPtr-lastPtr-1]='\0';
} else {
strncpy(loadPath,dirPtr,foundPtr-lastPtr);
loadPath[foundPtr-lastPtr]='\0';
}
} else {
strcpy(loadPath,dirPtr);
}
strcat(loadPath,"/");
strcat(loadPath,libName);
if (fileExists(loadPath)) {
// Finally load the library and exit loop
libtmp=dlopen(loadPath,RTLD_LAZY);
break;
}
// just try to do the same with a default suffix e.g. [libname.so].0
strcat(loadPath,SQLITE_NAME_ADD_SUFFIX);
if (fileExists(loadPath)) {
// Finally load the library and exit loop
libtmp=dlopen(loadPath,RTLD_LAZY);
break;
}
if (foundPtr&&foundPtr!=lastPtr) {
dirPtr+=foundPtr-dirPtr+1;
} else {
break;
}
lastPtr=foundPtr;
} while (foundPtr);
if (!libtmp) {
return 0;
}
return libtmp;
}
void NSSUnload() {
if (isNSSInitialized&&NULL!=NSSShutdown) {
(*NSSShutdown)();
}
if (libnss!=NULL) {
dlclose(libnss);
}
}
int initNSSLibrary(char*profilePath) {
isNSSInitialized=0;
if ((*NSSInit)(profilePath)!=SECSuccess) {
NSSUnload();
return 1;
} else {
isNSSInitialized=1;
}
return 0;
}
int base64Decode(const char*encoded,char**decoded,int*decodedLen) {
if (decoded==NULL||encoded==NULL) {
return 1;
}
unsigned char in[4],out[3],v;
char temp[3],chars[]="|$$$}rstuvwxyz{$$$$$$$>?@ABCDEFGHIJKLMNOPQRSTUVW$$$$$$XYZ[\\]^_`abcdefghijklmnopq";
unsigned int i,j=0,pos,length=strlen(encoded);
(*decodedLen)=0;
*decoded=(char*)malloc(sizeof(char)*BUF_MAX_HUGE);
strcpy((*decoded),"");
int isNullTerminator=0;
unsigned int numNullTerminators=0;
unsigned nullTerminators[length];
while (j<=length) {
for (pos=0,i=0;i<4&&j<=length;i++) {
v=0;
while (j<=length&&v==0) {
v=(unsigned char)encoded[j++];
v=(unsigned char)((v<43||v>122)?0:chars[v-43]);
if (v) {
v=(unsigned char)((v=='$')?0:v-61);
}
}
if (j<=length) {
pos++;
if (v) {
in[i]=(unsigned char)(v-1);
}
} else {
in[i]=0;
}
}
if (pos) {
out[0]=(unsigned char)(in[0]<<2|in[1]>>4);
out[1]=(unsigned char)(in[1]<<4|in[2]>>2);
out[2]=(unsigned char)(((in[2]<<6)&0xc0)|in[3]);
for (i=0;i<pos-1;i++) {
if (out[i]!='\0') {
sprintf(temp,"%c",out[i]);
strcat(*decoded,temp);
while (isNullTerminator) {
strcat(*decoded,temp);
isNullTerminator--;
}
} else {
isNullTerminator++;
nullTerminators[numNullTerminators++]=*decodedLen+i;
}
}
(*decodedLen)+=i;
}
}
for (i=0;i<numNullTerminators;i++) {
(*decoded)[nullTerminators[i]]='\0';
}
int correction=0;
if (encoded[length-1]=='=') {
correction++;
if (encoded[length-2]=='=') {
correction++;
}
}
(*decodedLen)=(length*3)/4-correction;
return 0;
}
int PK11Decrypt(char*decodeData,int decodeLen,char**clearData,int*finalLen,const char*master) {
SECStatus status;
struct SECItem request;
struct SECItem reply;
PK11SlotInfo*slot=(*PK11GetInternalKeySlot)(); // Get a token
if (!slot) {
return 1;
}
// Decrypt the string
// Can be done similar to what was is explained here https://wiki.mozilla.org/NSS_Shared_DB
if ((*PK11NeedLogin)(slot)) {
if (master==NULL||strlen(master)<1) {
printf("[-] A master password is required (specify one with -m)\n");
//return 1; // not so clever if we fail once,don't retry
(*PK11FreeSlot)(slot);
exit(1);
}
if (!strcmp(((*PK11GetTokenName)(slot)),MOZ_LOGIN_TOKEN_NAME)) {
status=(*PK11CheckUserPassword)(slot,(char*)master);
if (status!=SECSuccess) {
(*PK11FreeSlot)(slot);
return 1;
}
}
}
request.data=(unsigned char*)decodeData;
request.len=decodeLen;
reply.data=0;
reply.len=0;
status=(*PK11SDRDecrypt)(&request,&reply,NULL);
if (status!=SECSuccess) {
(*PK11FreeSlot)(slot);
return 1;
}
*clearData=(char*)reply.data;
*finalLen=reply.len;
(*PK11FreeSlot)(slot); // free the slot
return 0;
}
int decryptStr(const char*cryptData,char**clearData,const char*master) {
int decodeLen=0;
int finalLen=0;
char*decodeData=NULL;
char*finalData=NULL;
if (cryptData[0]) {
if (base64Decode(cryptData,&decodeData,&decodeLen)||decodeData==NULL) {
if (decodeData) {
free(decodeData);
}
return 1;
}
if (PK11Decrypt(decodeData,decodeLen,&finalData,&finalLen,master)||finalData==NULL) {
return 1;
}
free(decodeData);
*clearData=(char*)malloc(finalLen+1);
if (*clearData==NULL) { // malloc failed
return 1;
}
memcpy(*clearData,finalData,finalLen);
*(*clearData+finalLen)=0;
if (finalData) {
free(finalData);
}
return 0;
}
if (base64Decode(cryptData,clearData,&decodeLen)) {
return 1;
}
return 0;
}
char*getMozLibPath() {
// Logic missing, but needed (if even possible in linux)
unsigned long pathSize=BUF_MAX_SMALL;
const char*path=MOZ_DEFAULT_LIB_PATH;
char*mozDir=(char*)malloc(strlen(path)+1);
if (mozDir) {
strcpy(mozDir,path);
}
return mozDir;
}
void initLib(const char*name,char*dir,void**libref,const char*lib) {
if (!(*libref)) {
if (dir==NULL||strlen(dir)<1) {
dir=getMozLibPath();
}
if (!((*libref)=loadLibrary(dir,lib))) {
printf("[-] Failed to load %s library\n",name);
exit(1);
}
}
}
int initMozLibs(char*mozDir) {
libnss=NULL;
if (mozDir!=NULL) {
if (libsqlite=loadLibrary(mozDir,SQLITE_LIBRARY_NAME)) {
libnss=loadLibrary(mozDir,NSS_LIBRARY_NAME);
}
}
if (!libnss) { // try it w/o full path or fail
libnss=dlopen(NSS_LIBRARY_NAME,RTLD_LAZY);
if (!libnss) {
printf("[-] The library libnss could NOT be initialized\n");
return 0;
}
}
if (!libsqlite) {
return 0;
}
NSSInit=(NSS_Init)dlsym(libnss,"NSS_Init");
NSSShutdown=(NSS_Shutdown)dlsym(libnss,"NSS_Shutdown");
PK11GetInternalKeySlot=(PK11_GetInternalKeySlot)dlsym(libnss,"PK11_GetInternalKeySlot");
PK11NeedLogin=(PK11_NeedLogin)dlsym(libnss,"PK11_NeedLogin");
PK11GetTokenName=(PK11_GetTokenName)dlsym(libnss,"PK11_GetTokenName");
PK11Authenticate=(PK11_Authenticate) dlsym(libnss,"PK11_Authenticate");
PK11CheckUserPassword=(PK11_CheckUserPassword)dlsym(libnss,"PK11_CheckUserPassword");
PK11SDRDecrypt=(PK11SDR_Decrypt) dlsym(libnss,"PK11SDR_Decrypt");
PK11FreeSlot=(PK11_FreeSlot)dlsym(libnss,"PK11_FreeSlot");
if (!NSSInit||!NSSShutdown||!PK11GetInternalKeySlot||!PK11NeedLogin||!PK11Authenticate||!PK11SDRDecrypt||
!PK11FreeSlot||!PK11CheckUserPassword) {
if (!cmdline_raw) {
printf("[-] Not all library functions could be found\n");
}
NSSUnload();
return 0;
}
return 1;
}
int decryptCmdLine(const char*user,const char*pass,const char*master) {
char*clearData;
if (!decryptStr(user,&clearData,master)==1) {
if (!cmdline_raw) {
printf("[i] Username: ");
}
printf("%s\n",clearData);
if (clearData) {
free(clearData);
}
}
if (!decryptStr(pass,&clearData,master)==1) {
if (!cmdline_raw) {
printf("[i] Password: ");
}
printf("%s\n",clearData);
if (clearData) {
free(clearData);
}
}
return 0;
}
char**getSQLiteContent(char*signonFile,char***dst,unsigned int*retNum,unsigned int*retCols) {
char**retArray;
(*retNum)=0;
(*retCols)=0;
// you could do similar things w/ -lsqlite instead of -ldl of course (but who really cares?)
SQLiteOpen=(SQLite_Open)dlsym(libsqlite,"sqlite3_open_v2");
SQLiteGetTable=(SQLite_Get_Table)dlsym(libsqlite,"sqlite3_get_table");
SQLiteFreeTable=(SQLite_Free_Table)dlsym(libsqlite,"sqlite3_free_table");
SQLiteClose=(SQLite_Close)dlsym(libsqlite,"sqlite3_close");
if (signonFile==NULL||testOpenFile(signonFile)) {
return 0;
}
void*sqliteDB;
if (!SQLiteOpen(signonFile,&sqliteDB,SQLITE_OPEN_READONLY,NULL)) {
int rows,columns;
char**tuples;
char*errorMsg;
const char*query=MOZ_SIGNONS_QUERY;
if (!SQLiteGetTable(sqliteDB,query,&tuples,&rows,&columns,&errorMsg)) {
(*retCols)=columns;
retArray=(char**)malloc((rows*columns)*sizeof(char*));
int i,j;
for (i=1;i<=rows;i++) {
for (j=0;j<columns;j++) {
retArray[(i-1)*columns+j]=(char*)malloc(sizeof(char)*BUF_MAX);
if (tuples[i*columns+j]) {
strcpy(retArray[(i-1)*columns+j],tuples[i*columns+j]);
} else {
strcpy(retArray[(i-1)*columns+j],"");
}
}
(*retNum)++;
}
SQLiteFreeTable(tuples);
}
SQLiteClose(sqliteDB);
}
*dst=retArray;
return retArray;
}
int decryptSQLite(const char*signonFile,const char*master) {
char*clearData;
SQLiteOpen=(SQLite_Open)dlsym(libsqlite,"sqlite3_open_v2");
SQLiteGetTable=(SQLite_Get_Table)dlsym(libsqlite,"sqlite3_get_table");
SQLiteFreeTable=(SQLite_Free_Table)dlsym(libsqlite,"sqlite3_free_table");
SQLiteClose=(SQLite_Close)dlsym(libsqlite,"sqlite3_close");
if (signonFile==NULL||testOpenFile(signonFile)) {
return 1;
}
if (!cmdline_raw) {
printf("[i] Source file: %s\n",signonFile);
}
void*sqliteDB;
int ret=SQLiteOpen(signonFile,&sqliteDB,SQLITE_OPEN_READONLY,NULL);
if (!ret) {
int rows,columns;
char**tuples;
char*errorMsg;
const char*query=MOZ_SIGNONS_QUERY;
ret=SQLiteGetTable(sqliteDB,query,&tuples,&rows,&columns,&errorMsg);
if (!ret) {
int i,ii;
for (i=1,ii=0;i<=rows;i++,ii=0) {
if (!cmdline_raw) {
printf("\n");
// Those two info are NOT so important,skip in raw output
printf("[i] URL: %s\n",tuples[i*columns+(ii++)]);
printf("[i] Target: %s\n",tuples[i*columns+(ii++)]);
} else {
ii+=2; // this will be done always (either with 2x ii++ or here)
}
if (!decryptStr(tuples[i*columns+(ii++)],&clearData,master)==1) {
if (!cmdline_raw) {
printf("[i] Username: ");
}
printf("%s\n",clearData);
if (clearData) {
free(clearData);
}
}
if (!decryptStr(tuples[i*columns+ii],&clearData,master)==1) {
if (!cmdline_raw) {
printf("==> Password: ");
}
printf("%s\n",clearData);
if (clearData) {
free(clearData);
}
}
}
ret=SQLiteFreeTable(tuples);
}
SQLiteClose(sqliteDB);
}
return ret;
}
// HMAC for SHA1
// SHA1 helper functions
typedef struct SHA1Context {
unsigned Message_Digest[5]; // Message Digest (output)
unsigned Length_Low; // Message length in bits
unsigned Length_High; // Message length in bits
unsigned char Message_Block[64]; // 512-bit message blocks
int Message_Block_Index; // Index into message block array
int Computed; // Is the digest computed?
int Corrupted; // Is the message digest corruped?
} SHA1Context;
void SHA1Reset(SHA1Context*context) {
context->Length_Low =0;
context->Length_High =0;
context->Message_Block_Index=0;
context->Message_Digest[0] =0x67452301;
context->Message_Digest[1] =0xEFCDAB89;
context->Message_Digest[2] =0x98BADCFE;
context->Message_Digest[3] =0x10325476;
context->Message_Digest[4] =0xC3D2E1F0;
context->Computed=0;
context->Corrupted=0;
}
void SHA1ProcessMessageBlock(SHA1Context*context) {
const unsigned K[]={0x5A827999,0x6ED9EBA1,0x8F1BBCDC,0xCA62C1D6};
unsigned temp;
unsigned W[80];
unsigned A,B,C,D,E;
int t;
// Initialize the first 16 words in the array W
for (t=0;t<16;t++) {
W[t]=((unsigned)context->Message_Block[t*4])<<24;
W[t]|=((unsigned)context->Message_Block[t*4+1])<<16;
W[t]|=((unsigned)context->Message_Block[t*4+2])<<8;
W[t]|=((unsigned)context->Message_Block[t*4+3]);
}
for (t=16;t<80;t++) {
W[t]=SHA1CircularShift(1,W[t-3]^W[t-8]^W[t-14]^W[t-16]);
}
A=context->Message_Digest[0];
B=context->Message_Digest[1];
C=context->Message_Digest[2];
D=context->Message_Digest[3];
E=context->Message_Digest[4];
for (t=0;t<20;t++) {
temp=SHA1CircularShift(5,A)+((B&C)|((~B)&D))+E+W[t]+K[0];
temp&=0xFFFFFFFF;
E=D;
D=C;
C=SHA1CircularShift(30,B);
B=A;
A=temp;
}
for (t=20;t<40;t++) {
temp=SHA1CircularShift(5,A)+(B^C^D)+E+W[t]+K[1];
temp&=0xFFFFFFFF;
E=D;
D=C;
C=SHA1CircularShift(30,B);
B=A;
A=temp;
}
for (t=40;t<60;t++) {
temp=SHA1CircularShift(5,A)+((B&C)|(B&D)|(C&D))+E+W[t]+K[2];
temp&=0xFFFFFFFF;
E=D;
D=C;
C=SHA1CircularShift(30,B);
B=A;
A=temp;
}
for (t=60;t<80;t++) {
temp=SHA1CircularShift(5,A)+(B^C^D)+E+W[t]+K[3];
temp&=0xFFFFFFFF;
E=D;
D=C;
C=SHA1CircularShift(30,B);
B=A;
A=temp;
}
context->Message_Digest[0]=(context->Message_Digest[0]+A)&0xFFFFFFFF;
context->Message_Digest[1]=(context->Message_Digest[1]+B)&0xFFFFFFFF;
context->Message_Digest[2]=(context->Message_Digest[2]+C)&0xFFFFFFFF;
context->Message_Digest[3]=(context->Message_Digest[3]+D)&0xFFFFFFFF;
context->Message_Digest[4]=(context->Message_Digest[4]+E)&0xFFFFFFFF;
context->Message_Block_Index=0;
}
void SHA1PadMessage(SHA1Context*context) {
if (context->Message_Block_Index>55) {
context->Message_Block[context->Message_Block_Index++]=0x80;
while (context->Message_Block_Index<64) {
context->Message_Block[context->Message_Block_Index++]=0;
}
SHA1ProcessMessageBlock(context);
while (context->Message_Block_Index<56) {
context->Message_Block[context->Message_Block_Index++]=0;
}
} else {
context->Message_Block[context->Message_Block_Index++]=0x80;
while (context->Message_Block_Index<56) {
context->Message_Block[context->Message_Block_Index++]=0;
}
}
context->Message_Block[56]=(context->Length_High>>24)&0xFF;
context->Message_Block[57]=(context->Length_High>>16)&0xFF;
context->Message_Block[58]=(context->Length_High>>8)&0xFF;
context->Message_Block[59]=(context->Length_High)&0xFF;
context->Message_Block[60]=(context->Length_Low>>24)&0xFF;
context->Message_Block[61]=(context->Length_Low>>16)&0xFF;
context->Message_Block[62]=(context->Length_Low>>8)&0xFF;
context->Message_Block[63]=(context->Length_Low)&0xFF;
SHA1ProcessMessageBlock(context);
}
int SHA1Result(SHA1Context*context) {
if (context->Corrupted) {
return 0;
}
if (!context->Computed) {
SHA1PadMessage(context);
context->Computed=1;
}
return 1;
}
void SHA1Input(SHA1Context*context,char*message_array,unsigned length) {
if (!length) {
return;
}
if (context->Computed||context->Corrupted) {
context->Corrupted=1;
return;
}
while (length-- && !context->Corrupted) {
context->Message_Block[context->Message_Block_Index++]=(*message_array&0xFF);
context->Length_Low+=8;
context->Length_Low&=0xFFFFFFFF; // Low 32 bits
if (context->Length_Low==0) {
context->Length_High++;
context->Length_High&=0xFFFFFFFF; // High 32 bits
if (context->Length_High==0) {
context->Corrupted=1; // too long
}
}
if (context->Message_Block_Index==64) {
SHA1ProcessMessageBlock(context);
}
message_array++;
}
}
void usage(char*cmd) {
printf("%s v.%s by pschmidt (philipp(>_AT_<)pschmidt.it)\n",PROGRAM,VERSION);
printf("\n");
printf("Usage: %s MODE OPT [OPT ...]\n",cmd);
printf("\n");
printf("Description:\n");
printf(" This program will decrypt the mozilla database (signons.sqlite,key3.db)\n");
printf(" where username and password of logins are stored.\n");
printf("\n");
printf("MODE:\n");
printf(" -n - Normal mode using libnss (DEFAULT)\n");
printf(" -f - Special mode w/o libnss (use %s and %s directly)\n",MOZ_KEY3DB,MOZ_SIGNONS);
printf(" -s - Just calculate SHA1-HMAC for key (-k) and text (-t)\n");
printf(" -a - Invoke minimalistic ASN.1 parser for hexadecimal text specified by -a option\n");
printf("\n");
printf("OPT:\n");
printf(" -r - Enable raw output (output w/o description)\n");
printf(" -k - Key to use for SHA1-HMAC generation (see -s and -t)\n");
printf(" -t - Text/message to use for SHA1-HMAC generation (see -s and -k)\n");
printf(" -g - Global salt in hex format (e.g \"01 ef 64 ...\") for des3 decryption \n");
printf(" -e - Entry salt in hex format (e.g \"63 53 64 ...\") for des3 decryption\n");
printf(" -m - Master key mozilla password\n");
printf(" -u - Encrypted username string (base64 encoded)\n");
printf(" -p - Encrypted password string (base64 encoded)! NOT the MASTER password (see -m)\n");
printf(" -R - Private key entry (RSA key,see -f)\n");
printf(" -P - Mozilla profile path\n");
printf(" -l - Mozilla (or OS) library path\n");
printf(" -a - Hexadecimal string (e.g. 30 59 01 ...) to be tested with the minimalistic ASN.1 parser (\n");
printf("\n");
printf("Example usage:\n");
printf(" %s\n",cmd);
printf(" %s -n -m \"pAsSw0rd\"\n",cmd);
printf(" %s -f\n",cmd);
printf(" %s -f -g \"3b 28 75 c2 a9 0d 40 2b 84 b6 83 e0 de a5 41 49 55 07 f3 d4\" \\\n",cmd);
printf(" -e \"32 73 a0 bf e4 03 39 86 13 33 9e ff 24 cc 26 4b c2 ef 7c 1a\" (use this together w/ -R)\n");
printf(" %s -a \"30 13 02 01 05 16 0e 41 6e 79 62 6f 64 79 20 74 68 65 72 65 3f\"\n",cmd);
printf(" %s -s -t \"15 96 bb 81 12 65 2a 43 e7 bd fb 2f dc 87 99 e5 00 00 00 00\" \\\n",cmd);
printf(" -k \"8e 1e 3a 52 36 ab c3 44 55 2d 6e 1a 00 67 1a ed 69 2d 48 25\"\n");
printf("\n");
printf("CREDITS:\n");
printf(" ...go especially to Dr Stephen Henson from drh-consultancy who did some research on key3.db which\n");
printf(" was very useful for me to get started (see http://www.drh-consultancy.demon.co.uk/key3.html)\n");
printf("\n");
printf("KNOWN DEFICIENCIES/PROBLEMS/BUGS:\n");
printf(" Since this tool was designed in a very restricted amount of time, it lacks of a good design.\n");
printf(" There may be some borderline cases (e.g if you supply malicious/unexpected input etc.) where the tool failes/crashes\n");
printf(" The project was more about the research of how Mozilla encrypts passwords and not so much on the tool itself\n");
printf(" Use of more secure functions (as snprintf,strncpy,strncmp etc) would be great, but you know as of know it is a\n");
printf(" quick-done tool\n");
printf("\n");
printf("AUTHORS/CONTRIBUTORS/CONTACT:\n");
printf(" Please contact me at ph i lipp (AT] ps ch mi dt.it, w/o spaces and (AT] replaced\n");
printf(" Contributors wanted\n");
printf(" Please just drop me a mail if you find this tool useful and if you use this (or some of this) code\n");
printf(" (for any purpose whatsoever,except malicious)\n");
printf(" Also fixes and other suggestions are VERY welcome. Since the testing phase was NOT so ample,there may be some problems\n");
printf(" that we can encounter and (hopefully easily) FIX.\n");
}
// e.g. 50 68 69 6C => Phil
char*atohx(char*dst,const char*src,const unsigned int spacing) {
char*ret=dst;
const char*srcPtr=src;
const unsigned int length=strlen(srcPtr);
int lsb,msb;
for (lsb=0,msb=0;*src;src+=2+spacing) {
if ((src+1+spacing)>srcPtr+length&&src-srcPtr) {
break;
}
msb=tolower(*src);
lsb=tolower(*(src+1));
msb-=isdigit(msb)?0x30:0x57;
lsb-=isdigit(lsb)?0x30:0x57;
if((msb<0x0||msb>0xf)||(lsb<0x0||lsb>0xf)) {
*ret=0;
return NULL;
}
*dst++=(char)(lsb|(msb<<4));
}
*dst=0;
return ret;
}
char*hxtoa(char*dst,const char*src,const unsigned int padding) {
int src1=src[0];
const char*chars="0123456789abcdef";
char*ret=dst,temp[3],temp2[strlen(ret)];
unsigned int division;
strcpy(ret,"");
if (src1<0) {
src1+=256;
}
while (1) {
division=src1/16;
if (division>0) {
sprintf(temp,"%c",chars[division]);
strcat(ret,temp);
src1-=(16*division);
} else {
sprintf(temp,"%c",chars[src1%16]);
strcat(ret,temp);
break;
}
}
if (ret==NULL||strlen(ret)<1) {
strcpy(ret,"00");
}
while (strlen(ret)<padding) {
strcpy(temp2,ret);
strcpy(ret,"0");
strcat(ret,temp2);
}
return ret;
}
// e.g. Phil => 50 68 69 6C
char*hxtostr(char*dst,const char*src,unsigned int length,const char*delimiter,const unsigned int delSize,const unsigned int padding) {
char*ret=dst;
int i,j;
strcpy(ret,"");
char temp[4];
for (i=0;i<length;i++) {
if (i!=0&&delimiter!=NULL) {
for (j=0;j<delSize;j++) {
strcat(ret,delimiter);
}
}
hxtoa(temp,src+i,padding);
strcat(ret,temp);
}
return ret;
}
char*getTransTable(char*dst,const unsigned int transMod) {
char*table=dst;
char temp[3];
int i;
int isNullTerminator=0;
unsigned int numNullTerminators=0;
unsigned nullTerminators[255];
strcpy(dst,"");
for (i=0;i<256;i++) {
if ((i^transMod)!=0) {
sprintf(temp,"%c",i^transMod);
strcat(table,temp);
while (isNullTerminator) {
strcat(table,temp);
isNullTerminator--;
}
} else {
isNullTerminator++;
nullTerminators[numNullTerminators++]=i;
}
}
for (i=0;i<numNullTerminators;i++) {
table[nullTerminators[i]]='\0';
}
return table;
}
char*translate(char*dst,const char*target,const unsigned int size,const char*table) {
char hxtostrTemp[BUF_MAX_HUGE];
char output[BUF_MAX_HUGE];
char*ret=dst;
strcpy(ret,"");
char temp[3];
int i,j;
// copy string byte per byte (instead of using strdup <-avoid)
for (i=0;i<size;i++) {
ret[i]=target[i];
}
// do translate
for (i=0;i<256;i++) {
if ((int)(table[i])!=i&&((int)(table[i])>0||(255+(int)(table[i]))!=i)) {
for (j=0;j<size;j++) {
if ((int)target[j]==i||(256+(int)target[j])==i) {
ret[j]=table[i];
}
}
}
}
return ret;
}
char*getRawDigest(SHA1Context sha,char*dst,unsigned int*length) {
char*ret=dst;
strcpy(ret,"");
(*length)=0;
int i,j,blocksize=8,maxSize=sizeof(sha.Message_Digest)/sizeof(*sha.Message_Digest);