1 /***************************************************************************
2 * Copyright (C) 2005-2008 by Tarek Saidi *
3 * tarek.saidi@arcor.de *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; version 2 of the License. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
18 ***************************************************************************/
20 #include "Kdb3Database.h"
22 #include "crypto/twoclass.h"
26 #define UNEXP_ERROR error=QString("Unexpected error in: %1, Line:%2").arg(__FILE__).arg(__LINE__);
28 const QDateTime Date_Never(QDate(2999,12,28),QTime(23,59,59));
31 bool Kdb3Database::EntryHandleLessThan(const IEntryHandle* This,const IEntryHandle* Other){
32 if(!This->isValid() && Other->isValid())return true;
33 if(This->isValid() && !Other->isValid())return false;
34 if(!This->isValid() && !Other->isValid())return false;
35 return This->visualIndex()<Other->visualIndex();
38 bool Kdb3Database::EntryHandleLessThanStd(const IEntryHandle* This,const IEntryHandle* Other){
39 int comp = This->title().compare(Other->title());
40 if (comp < 0) return true;
41 else if (comp > 0) return false;
43 comp = This->username().compare(Other->username());
44 if (comp < 0) return true;
45 else if (comp > 0) return false;
50 bool Kdb3Database::StdEntryLessThan(const Kdb3Database::StdEntry& This,const Kdb3Database::StdEntry& Other){
51 return This.Index<Other.Index;
55 Kdb3Database::Kdb3Database() : RawMasterKey(32), RawMasterKey_CP1252(32),
56 RawMasterKey_Latin1(32), RawMasterKey_UTF8(32), MasterKey(32){
59 QString Kdb3Database::getError(){
63 void Kdb3Database::addIcon(const QPixmap& icon){
68 QPixmap& Kdb3Database::icon(int i){
69 if(i>=builtinIcons()+CustomIcons.size())
73 return CustomIcons[i-builtinIcons()];
76 void Kdb3Database::removeIcon(int id){
79 if(id >= CustomIcons.size()) return;
80 CustomIcons.removeAt(id); // .isNull()==true
81 for(int i=0;i<Entries.size();i++){
82 if(Entries[i].Image == id+builtinIcons())
84 if(Entries[i].Image>id+builtinIcons())
87 for(int i=0;i<Groups.size();i++){
88 if(Groups[i].Image == id+builtinIcons())
90 if(Groups[i].Image>id+builtinIcons())
96 void Kdb3Database::replaceIcon(int id,const QPixmap& icon){
97 if(id<builtinIcons())return;
98 CustomIcons[id-builtinIcons()]=icon;
102 int Kdb3Database::numIcons(){
103 return builtinIcons()+CustomIcons.size();
106 bool Kdb3Database::parseMetaStream(const StdEntry& entry){
108 qDebug("Found Metastream: %s", CSTR(entry.Comment));
110 if(entry.Comment=="KPX_GROUP_TREE_STATE"){
111 parseGroupTreeStateMetaStream(entry.Binary);
114 else if(entry.Comment=="KPX_CUSTOM_ICONS_4"){
115 parseCustomIconsMetaStream(entry.Binary);
118 else if(entry.Comment=="KPX_CUSTOM_ICONS_3"){
119 if (!hasV4IconMetaStream)
120 parseCustomIconsMetaStreamV3(entry.Binary);
123 else if(entry.Comment=="KPX_CUSTOM_ICONS_2"){
124 qDebug("Removed old CuIcMeSt v2");
127 else if(entry.Comment=="KPX_CUSTOM_ICONS"){
128 qDebug("Removed old CuIcMeSt v1");
132 return false; //unknown MetaStream
135 bool Kdb3Database::isMetaStream(StdEntry& p){
136 if(p.Binary.isNull()) return false;
137 if(p.Comment == "") return false;
138 if(p.BinaryDesc != "bin-stream") return false;
139 if(p.Title != "Meta-Info") return false;
140 if(p.Username != "SYSTEM") return false;
141 if(p.Url != "$") return false;
142 if(p.Image != 0) return false;
146 void Kdb3Database::parseCustomIconsMetaStream(const QByteArray& dta){
147 //Rev 4 (KeePassX 0.3.2)
148 quint32 NumIcons,NumEntries,NumGroups,offset;
149 memcpyFromLEnd32(&NumIcons,dta.data());
150 memcpyFromLEnd32(&NumEntries,dta.data()+4);
151 memcpyFromLEnd32(&NumGroups,dta.data()+8);
154 for(int i=0;i<NumIcons;i++){
155 CustomIcons << QPixmap();
157 memcpyFromLEnd32(&Size,dta.data()+offset);
158 if(offset+Size > dta.size()){
160 qWarning("Discarded metastream KPX_CUSTOM_ICONS_4 because of a parsing error.");
164 if(!CustomIcons.back().loadFromData((const unsigned char*)dta.data()+offset,Size,"PNG")){
166 qWarning("Discarded metastream KPX_CUSTOM_ICONS_4 because of a parsing error.");
170 if(offset > dta.size()){
172 qWarning("Discarded metastream KPX_CUSTOM_ICONS_4 because of a parsing error.");
176 for(int i=0;i<NumEntries;i++){
179 EntryUuid.fromRaw(dta.data()+offset);
181 memcpyFromLEnd32(&Icon,dta.data()+offset);
183 StdEntry* entry=getEntry(EntryUuid);
185 entry->Image=Icon+BUILTIN_ICONS;
187 for(int i=0;i<NumGroups;i++){
188 quint32 GroupId,Icon;
189 memcpyFromLEnd32(&GroupId,dta.data()+offset);
191 memcpyFromLEnd32(&Icon,dta.data()+offset);
193 StdGroup* Group=getGroup(GroupId);
195 Group->Image=Icon+BUILTIN_ICONS;
200 void Kdb3Database::parseCustomIconsMetaStreamV3(const QByteArray& dta){
202 quint32 NumIcons,NumEntries,NumGroups,offset;
203 memcpyFromLEnd32(&NumIcons,dta.data());
204 memcpyFromLEnd32(&NumEntries,dta.data()+4);
205 memcpyFromLEnd32(&NumGroups,dta.data()+8);
208 for(int i=0;i<NumIcons;i++){
209 CustomIcons << QPixmap();
211 memcpyFromLEnd32(&Size,dta.data()+offset);
212 if(offset+Size > dta.size()){
214 qWarning("Discarded metastream KPX_CUSTOM_ICONS_3 because of a parsing error.");
218 if(!CustomIcons.back().loadFromData((const unsigned char*)dta.data()+offset,Size,"PNG")){
220 qWarning("Discarded metastream KPX_CUSTOM_ICONS_3 because of a parsing error.");
224 if(offset > dta.size()){
226 qWarning("Discarded metastream KPX_CUSTOM_ICONS_3 because of a parsing error.");
230 for(int i=0;i<NumEntries;i++){
233 EntryUuid.fromRaw(dta.data()+offset);
235 memcpyFromLEnd32(&Icon,dta.data()+offset);
237 StdEntry* entry=getEntry(EntryUuid);
240 entry->Image=Icon+4; // Since v0.3.2 the BUILTIN_ICONS number has increased by 4
245 for(int i=0;i<NumGroups;i++){
246 quint32 GroupId,Icon;
247 memcpyFromLEnd32(&GroupId,dta.data()+offset);
249 memcpyFromLEnd32(&Icon,dta.data()+offset);
251 StdGroup* Group=getGroup(GroupId);
253 if (Group->Image>=65)
254 Group->Image=Icon+4; // Since v0.3.2 the BUILTIN_ICONS number has increased by 4
262 void Kdb3Database::parseGroupTreeStateMetaStream(const QByteArray& dta){
264 qWarning("Discarded metastream KPX_GROUP_TREE_STATE because of a parsing error.");
268 memcpyFromLEnd32(&Num,dta.data());
269 if(Num*5!=dta.size()-4){
270 qWarning("Discarded metastream KPX_GROUP_TREE_STATE because of a parsing error.");
273 TreeStateMetaStream.clear();
274 for(int i=0;i<Num;i++){
277 memcpyFromLEnd32(&GroupID,dta.data()+4+5*i);
278 memcpy(&IsExpanded,dta.data()+8+5*i,1);
279 TreeStateMetaStream.insert(GroupID,(bool)IsExpanded);
284 void Kdb3Database::createGroupTreeStateMetaStream(StdEntry* e){
285 e->BinaryDesc="bin-stream";
286 e->Title="Meta-Info";
287 e->Username="SYSTEM";
288 e->Comment="KPX_GROUP_TREE_STATE";
291 if(Groups.size())e->GroupId=Groups[0].Id;
293 quint32 Num=Groups.size();
295 memcpyToLEnd32(bin.data(),&Num);
296 for(int i=0;i<Num;i++){
297 memcpyToLEnd32(bin.data()+4+5*i,&Groups[i].Id);
298 if(Groups[i].IsExpanded)
306 Kdb3Database::StdEntry* Kdb3Database::getEntry(const KpxUuid& uuid){
307 for(int i=0; i<Entries.size();i++)
308 if(Entries[i].Uuid==uuid)return &Entries[i];
312 Kdb3Database::StdGroup* Kdb3Database::getGroup(quint32 Id){
313 for(int i=0; i<Groups.size();i++)
314 if(Groups[i].Id==Id)return &Groups[i];
319 //! Extracts one entry from raw decrypted data.
320 bool Kdb3Database::readEntryField(StdEntry* entry, quint16 FieldType, quint32 FieldSize, quint8 *pData){
327 entry->Uuid=KpxUuid(pData);
330 memcpyFromLEnd32(&entry->GroupId, (char*)pData);
333 memcpyFromLEnd32(&entry->Image, (char*)pData);
336 entry->Title=QString::fromUtf8((char*)pData);
339 entry->Url=QString::fromUtf8((char*)pData);
342 entry->Username=QString::fromUtf8((char*)pData);
345 QString s=QString::fromUtf8((char*)pData);
346 entry->Password.setString(s,true);
349 entry->Comment=QString::fromUtf8((char*)pData);
352 entry->Creation=dateFromPackedStruct5(pData);
355 entry->LastMod=dateFromPackedStruct5(pData);
358 entry->LastAccess=dateFromPackedStruct5(pData);
361 entry->Expire=dateFromPackedStruct5(pData);
364 entry->BinaryDesc=QString::fromUtf8((char*)pData);
368 entry->Binary=QByteArray((char*)pData,FieldSize);
370 entry->Binary=QByteArray();
380 //! Extracts one group from raw decrypted data.
381 bool Kdb3Database::readGroupField(StdGroup* group,QList<quint32>& Levels,quint16 FieldType, quint8 *pData)
389 memcpyFromLEnd32(&group->Id, (char*)pData);
392 group->Title=QString::fromUtf8((char*)pData);
394 case 0x0003: //not longer used by KeePassX but part of the KDB format
396 case 0x0004: //not longer used by KeePassX but part of the KDB format
398 case 0x0005: //not longer used by KeePassX but part of the KDB format
400 case 0x0006: //not longer used by KeePassX but part of the KDB format
403 memcpyFromLEnd32(&group->Image, (char*)pData);
407 memcpyFromLEnd16(&Level, (char*)pData);
408 Levels.append(Level);
411 //not used by KeePassX but part of the KDB format
412 //memcpyFromLEnd32(&Flags, (char*)pData);
417 return false; // Field unsupported
420 return true; // Field supported
423 bool Kdb3Database::createGroupTree(QList<quint32>& Levels){
424 if(Levels[0]!=0) return false;
425 //find the parent for every group
426 for(int i=0;i<Groups.size();i++){
428 Groups[i].Parent=&RootGroup;
429 Groups[i].Index=RootGroup.Children.size();
430 RootGroup.Children.append(&Groups[i]);
434 //the first item with a lower level is the parent
436 if(Levels[j]<Levels[i]){
437 if(Levels[i]-Levels[j]!=1)return false;
440 if(j==0)return false; //No parent found
442 Groups[i].Parent=&Groups[j];
443 Groups[i].Index=Groups[j].Children.size();
444 Groups[i].Parent->Children.append(&Groups[i]);
447 QList<int> EntryIndexCounter;
448 for(int i=0;i<Groups.size();i++)EntryIndexCounter << 0;
450 for(int e=0;e<Entries.size();e++){
451 for(int g=0;g<Groups.size();g++){
452 if(Entries[e].GroupId==Groups[g].Id){
453 Groups[g].Entries.append(&Entries[e]);
454 Entries[e].Group=&Groups[g];
455 Entries[e].Index=EntryIndexCounter[g];
456 EntryIndexCounter[g]++;
464 void Kdb3Database::createHandles(){
465 for(int i=0;i<Groups.size();i++){
466 GroupHandles.append(GroupHandle(this));
467 Groups[i].Handle=&GroupHandles.back();
468 GroupHandles.back().Group=&Groups[i];
470 for(int i=0;i<Entries.size();i++){
471 EntryHandles.append(EntryHandle(this));
472 Entries[i].Handle=&EntryHandles.back();
473 EntryHandles.back().Entry=&Entries[i];
477 void Kdb3Database::restoreGroupTreeState(){
478 switch (config->groupTreeState()){
479 case KpxConfig::RestoreLast:
480 for(int i=0;i<Groups.size();i++){
481 if(TreeStateMetaStream.contains(Groups[i].Id))
482 Groups[i].IsExpanded=TreeStateMetaStream.value(Groups[i].Id);
486 case KpxConfig::ExpandAll:
487 for(int i=0;i<Groups.size();i++)
488 Groups[i].IsExpanded=true;
491 case KpxConfig::DoNothing:
496 bool Kdb3Database::load(QString identifier, bool readOnly){
497 return loadReal(identifier, readOnly, false);
500 #define LOAD_RETURN_CLEANUP \
506 bool Kdb3Database::loadReal(QString filename, bool readOnly, bool differentEncoding) {
507 unsigned long total_size,crypto_size;
508 quint32 Signature1,Signature2,Version,NumGroups,NumEntries,Flags;
509 quint8 FinalRandomSeed[16];
510 quint8 ContentsHash[32];
511 quint8 EncryptionIV[16];
513 File = new QFile(filename);
515 if(!File->open(QIODevice::ReadOnly)){
516 error=tr("Could not open file.");
523 if(!File->open(QIODevice::ReadWrite)){
524 if(!File->open(QIODevice::ReadOnly)){
525 error=tr("Could not open file.");
536 total_size=File->size();
537 char* buffer = new char[total_size];
538 File->read(buffer,total_size);
540 if(total_size < DB_HEADER_SIZE){
541 error=tr("Unexpected file size (DB_TOTAL_SIZE < DB_HEADER_SIZE)");
545 memcpyFromLEnd32(&Signature1,buffer);
546 memcpyFromLEnd32(&Signature2,buffer+4);
547 memcpyFromLEnd32(&Flags,buffer+8);
548 memcpyFromLEnd32(&Version,buffer+12);
549 memcpy(FinalRandomSeed,buffer+16,16);
550 memcpy(EncryptionIV,buffer+32,16);
551 memcpyFromLEnd32(&NumGroups,buffer+48);
552 memcpyFromLEnd32(&NumEntries,buffer+52);
553 memcpy(ContentsHash,buffer+56,32);
554 memcpy(TransfRandomSeed,buffer+88,32);
555 memcpyFromLEnd32(&KeyTransfRounds,buffer+120);
557 if((Signature1!=PWM_DBSIG_1) || (Signature2!=PWM_DBSIG_2)){
558 error=tr("Wrong Signature");
562 if((Version & 0xFFFFFF00) != (PWM_DBVER_DW & 0xFFFFFF00)){
563 error=tr("Unsupported File Version.");
567 if (Flags & PWM_FLAG_RIJNDAEL)
568 Algorithm = Rijndael_Cipher;
569 else if (Flags & PWM_FLAG_TWOFISH)
570 Algorithm = Twofish_Cipher;
572 error=tr("Unknown Encryption Algorithm.");
576 RawMasterKey.unlock();
578 KeyTransform::transform(*RawMasterKey,*MasterKey,TransfRandomSeed,KeyTransfRounds);
583 sha.update(FinalRandomSeed,16);
584 sha.update(*MasterKey,32);
585 sha.finish(FinalKey);
590 if(Algorithm == Rijndael_Cipher){
592 aes.key256(FinalKey);
593 aes.cbc_decrypt((unsigned char*)buffer+DB_HEADER_SIZE,(unsigned char*)buffer+DB_HEADER_SIZE,total_size-DB_HEADER_SIZE,(unsigned char*)EncryptionIV);
594 crypto_size=total_size-((quint8*)buffer)[total_size-1]-DB_HEADER_SIZE;
596 else if(Algorithm == Twofish_Cipher){
598 if (twofish.init(FinalKey, 32, EncryptionIV) != true){
599 error=tr("Unable to initialize the twofish algorithm.");
602 crypto_size = (unsigned long)twofish.padDecrypt((quint8 *)buffer + DB_HEADER_SIZE,
603 total_size - DB_HEADER_SIZE, (quint8 *)buffer + DB_HEADER_SIZE);
606 error=tr("Unknown encryption algorithm.");
610 if ((crypto_size > 2147483446) || (!crypto_size && NumGroups)){
611 error=tr("Decryption failed.\nThe key is wrong or the file is damaged.");
614 SHA256::hashBuffer(buffer+DB_HEADER_SIZE,FinalKey,crypto_size);
616 if(memcmp(ContentsHash, FinalKey, 32) != 0){
617 if(PotentialEncodingIssueLatin1){
622 RawMasterKey.copyData(RawMasterKey_Latin1);
623 PotentialEncodingIssueLatin1 = false;
624 qDebug("Decryption failed. Retrying with Latin-1.");
625 return loadReal(filename, readOnly, true); // second try
627 if(PotentialEncodingIssueUTF8){
632 RawMasterKey.copyData(RawMasterKey_UTF8);
633 PotentialEncodingIssueUTF8 = false;
634 qDebug("Decryption failed. Retrying with UTF-8.");
635 return loadReal(filename, readOnly, true); // second/third try
637 error=tr("Hash test failed.\nThe key is wrong or the file is damaged.");
642 unsigned long pos = DB_HEADER_SIZE;
648 QList<quint32> Levels;
649 RootGroup.Title="$ROOT$";
650 RootGroup.Parent=NULL;
651 RootGroup.Handle=NULL;
653 for(unsigned long CurGroup = 0; CurGroup < NumGroups; )
657 memcpyFromLEnd16(&FieldType, pField);
658 pField += 2; pos += 2;
659 if (pos >= total_size){
660 error=tr("Unexpected error: Offset is out of range.").append(" [G1]");
664 memcpyFromLEnd32(&FieldSize, pField);
665 pField += 4; pos += 4;
666 if (pos >= (total_size + FieldSize)){
667 error=tr("Unexpected error: Offset is out of range.").append(" [G2]");
671 bRet = readGroupField(&group,Levels, FieldType, (quint8 *)pField);
672 if ((FieldType == 0xFFFF) && (bRet == true)){
674 CurGroup++; // Now and ONLY now the counter gets increased
678 if (pos >= total_size){
679 error=tr("Unexpected error: Offset is out of range.").append(" [G1]");
686 for (unsigned long CurEntry = 0; CurEntry < NumEntries;)
690 memcpyFromLEnd16(&FieldType, pField);
691 pField += 2; pos += 2;
692 if(pos >= total_size){
693 error=tr("Unexpected error: Offset is out of range.").append(" [E1]");
697 memcpyFromLEnd32(&FieldSize, pField);
698 pField += 4; pos += 4;
699 if (pos >= (total_size + FieldSize)){
700 error=tr("Unexpected error: Offset is out of range.").append(" [E2]");
704 bRet = readEntryField(&entry,FieldType,FieldSize,(quint8*)pField);
706 if((FieldType == 0xFFFF) && (bRet == true)){
709 qDebug("NULL: %i, '%s'", (int)CurEntry, (char*)entry.Title.toUtf8().data());
715 if (pos >= total_size){
716 error=tr("Unexpected error: Offset is out of range.").append(" [E3]");
721 if(!createGroupTree(Levels)){
722 error=tr("Invalid group tree.");
728 hasV4IconMetaStream = false;
729 for(int i=0;i<Entries.size();i++){
730 if(isMetaStream(Entries[i]) && Entries[i].Comment=="KPX_CUSTOM_ICONS_4"){
731 hasV4IconMetaStream = true;
736 //Remove the metastreams from the entry list
737 for(int i=0;i<Entries.size();i++){
738 if(isMetaStream(Entries[i])){
739 if(!parseMetaStream(Entries[i]))
740 UnknownMetaStreams << Entries[i];
746 int* EntryIndices=new int[Groups.size()];
747 for(int i=0;i<Groups.size();i++)EntryIndices[i]=0;
749 for(int g=0;g<Groups.size();g++){
750 for(int e=0;e<Entries.size();e++){
751 if(Entries[e].GroupId==Groups[g].Id){
752 Entries[e].Index=EntryIndices[g];
757 delete [] EntryIndices;
759 restoreGroupTreeState();
761 passwordEncodingChanged = differentEncoding;
762 if (differentEncoding) {
763 RawMasterKey.copyData(RawMasterKey_CP1252);
770 QDateTime Kdb3Database::dateFromPackedStruct5(const unsigned char* pBytes){
771 quint32 dw1, dw2, dw3, dw4, dw5;
772 dw1 = (quint32)pBytes[0]; dw2 = (quint32)pBytes[1]; dw3 = (quint32)pBytes[2];
773 dw4 = (quint32)pBytes[3]; dw5 = (quint32)pBytes[4];
774 int y = (dw1 << 6) | (dw2 >> 2);
775 int mon = ((dw2 & 0x00000003) << 2) | (dw3 >> 6);
776 int d = (dw3 >> 1) & 0x0000001F;
777 int h = ((dw3 & 0x00000001) << 4) | (dw4 >> 4);
778 int min = ((dw4 & 0x0000000F) << 2) | (dw5 >> 6);
779 int s = dw5 & 0x0000003F;
780 return QDateTime(QDate(y,mon,d),QTime(h,min,s));
784 void Kdb3Database::dateToPackedStruct5(const QDateTime& d,unsigned char* pBytes){
785 pBytes[0] = (quint8)(((quint32)d.date().year() >> 6) & 0x0000003F);
786 pBytes[1] = (quint8)((((quint32)d.date().year() & 0x0000003F) << 2) | (((quint32)d.date().month() >> 2) & 0x00000003));
787 pBytes[2] = (quint8)((((quint32)d.date().month() & 0x00000003) << 6) | (((quint32)d.date().day() & 0x0000001F) << 1) | (((quint32)d.time().hour() >> 4) & 0x00000001));
788 pBytes[3] = (quint8)((((quint32)d.time().hour() & 0x0000000F) << 4) | (((quint32)d.time().minute() >> 2) & 0x0000000F));
789 pBytes[4] = (quint8)((((quint32)d.time().minute() & 0x00000003) << 6) | ((quint32)d.time().second() & 0x0000003F));
793 int Kdb3Database::numGroups(){
794 return Groups.size();
797 int Kdb3Database::numEntries(){
798 return Entries.size();
801 void Kdb3Database::deleteGroup(StdGroup* group){
803 while(group->Children.size())
804 deleteGroup(group->Children.front());
806 QList<IEntryHandle*> GroupEntries;
807 GroupEntries=entries(group->Handle);
808 deleteEntries(GroupEntries);
810 Q_ASSERT(group==group->Parent->Children[group->Index]);
811 group->Parent->Children.removeAt(group->Index);
812 for(int i=group->Index;i<group->Parent->Children.size();i++){
813 group->Parent->Children[i]->Index--;
815 group->Handle->invalidate();
817 for(int i=0;i<Groups.size();i++){
818 if(&Groups[i]==group){
827 void Kdb3Database::deleteGroup(IGroupHandle* group){
828 deleteGroup(((GroupHandle*)group)->Group);
832 void Kdb3Database::GroupHandle::setIndex(int index){
833 quint32 ParentId=((GroupHandle*)parent())->Id;
834 int Pos=pDB->getGroupListIndex(this);
836 // Move the group to the new position in the list
838 NewPos=pDB->getGroupListIndex((GroupHandle*)parent());
841 pDB->Groups.move(Pos,NewPos+1);
843 pDB->Groups.move(Pos,NewPos);
846 for(NewPos;NewPos<pDB->Groups.size();NewPos++){
847 if(pDB->Groups[NewPos].ParentId==ParentId && pDB->Groups[NewPos].Index+1==index)
850 //skip the children of the found sibling
851 for(NewPos;NewPos<Groups.size();NewPos++){
853 pDB->Groups.move(Pos,NewPos);
857 // adjust the indices
859 for(int i=0;i<pDB->Groups.size();i++){
860 if(pDB->Groups[i].ParentId==ParentId){
861 pDB->Groups[i].Index=NewIndex;
868 bool Kdb3Database::convHexToBinaryKey(char* HexKey, char* dst){
869 QString hex=QString::fromAscii(HexKey,64);
870 for(int i=0; i<64; i+=2){
873 bin=hex.mid(i,2).toUInt(&err,16);
874 if(!err)return false;
875 memcpy(dst+(i/2),&bin,1);
880 bool Kdb3Database::setKey(const QString& password,const QString& keyfile){
881 if(!password.isEmpty() && !keyfile.isEmpty())
882 return setCompositeKey(password,keyfile);
883 if(!password.isEmpty())
884 return setPasswordKey(password);
885 if(!keyfile.isEmpty())
886 return setFileKey(keyfile);
891 bool Kdb3Database::setPasswordKey(const QString& Password){
892 Q_ASSERT(Password.size());
893 QTextCodec* codec=QTextCodec::codecForName("Windows-1252");
894 QByteArray Password_CP1252 = codec->fromUnicode(Password);
895 RawMasterKey_CP1252.unlock();
896 SHA256::hashBuffer(Password_CP1252.data(),*RawMasterKey_CP1252,Password_CP1252.size());
897 RawMasterKey_CP1252.lock();
898 RawMasterKey.copyData(RawMasterKey_CP1252);
900 QByteArray Password_Latin1 = Password.toLatin1();
901 QByteArray Password_UTF8 = Password.toUtf8();
902 PotentialEncodingIssueLatin1 = false;
903 PotentialEncodingIssueUTF8 = false;
905 if (Password_Latin1 != Password_CP1252){
906 // KeePassX used Latin-1 encoding for passwords until version 0.3.1
907 // but KeePass/Win32 uses Windows Codepage 1252.
908 // To stay compatible with databases created with KeePassX <= 0.3.1
909 // the loading function gives both encodings a try.
910 PotentialEncodingIssueLatin1 = true;
911 RawMasterKey_Latin1.unlock();
912 SHA256::hashBuffer(Password_Latin1.data(),*RawMasterKey_Latin1,Password_Latin1.size());
913 RawMasterKey_Latin1.lock();
916 if (Password_UTF8 != Password_CP1252){
917 // KeePassX used UTF-8 encoding for passwords until version 0.2.2
918 // but KeePass/Win32 uses Windows Codepage 1252.
919 // To stay compatible with databases created with KeePassX <= 0.2.2
920 // the loading function gives both encodings a try.
921 PotentialEncodingIssueUTF8 = true;
922 RawMasterKey_UTF8.unlock();
923 SHA256::hashBuffer(Password_UTF8.data(),*RawMasterKey_UTF8,Password_UTF8.size());
924 RawMasterKey_UTF8.lock();
930 bool Kdb3Database::setFileKey(const QString& filename){
931 QFile file(filename);
932 if(!file.open(QIODevice::ReadOnly|QIODevice::Unbuffered)){
933 error=decodeFileError(file.error());
936 qint64 FileSize=file.size();
938 error=tr("Key file is empty.");
941 RawMasterKey.unlock();
943 if(file.read((char*)(*RawMasterKey),32) != 32){
944 error=decodeFileError(file.error());
953 if(file.read(hex,64) != 64){
954 error=decodeFileError(file.error());
958 if (convHexToBinaryKey(hex,(char*)(*RawMasterKey))){
964 unsigned char* buffer[2048];
967 read = file.read((char*)buffer,2048);
969 sha.update(buffer,read);
970 } while (read == 2048);
971 sha.finish(*RawMasterKey);
976 bool Kdb3Database::setCompositeKey(const QString& Password,const QString& filename){
979 setPasswordKey(Password);
980 RawMasterKey.unlock();
981 sha.update(*RawMasterKey,32);
984 if(!setFileKey(filename))return false;
985 RawMasterKey.unlock();
986 sha.update(*RawMasterKey,32);
987 sha.finish(*RawMasterKey);
993 QList<IEntryHandle*> Kdb3Database::entries(){
994 QList<IEntryHandle*> handles;
995 for(int i=0; i<EntryHandles.size(); i++){
996 if(EntryHandles[i].isValid())handles.append(&EntryHandles[i]);
1001 QList<IEntryHandle*> Kdb3Database::expiredEntries(){
1002 QList<IEntryHandle*> handles;
1003 for(int i=0; i<EntryHandles.size(); i++){
1004 if(EntryHandles[i].isValid() &&
1005 (EntryHandles[i].expire()<=QDateTime::currentDateTime()) &&
1006 (EntryHandles[i].expire()!=Date_Never))
1007 handles.append(&EntryHandles[i]);
1012 QList<IEntryHandle*> Kdb3Database::entries(IGroupHandle* Group){
1013 QList<IEntryHandle*> handles;
1014 for(int i=0; i<EntryHandles.size(); i++){
1015 if(EntryHandles[i].isValid() && (EntryHandles[i].group()==Group))
1016 handles.append(&EntryHandles[i]);
1018 qSort(handles.begin(),handles.end(),EntryHandleLessThan);
1023 QList<IEntryHandle*> Kdb3Database::entriesSortedStd(IGroupHandle* Group){
1024 QList<IEntryHandle*> handles;
1025 for(int i=0; i<EntryHandles.size(); i++){
1026 if(EntryHandles[i].isValid() && (EntryHandles[i].group()==Group))
1027 handles.append(&EntryHandles[i]);
1029 qSort(handles.begin(),handles.end(),EntryHandleLessThanStd);
1034 void Kdb3Database::deleteEntry(IEntryHandle* entry){
1037 for(j=0;j<Entries.size();j++){
1038 if(&Entries[j]==((EntryHandle*)entry)->Entry)
1041 Entries[j].Handle->invalidate();
1042 Entries.removeAt(j);
1045 void Kdb3Database::moveEntry(IEntryHandle* entry, IGroupHandle* group){
1046 ((EntryHandle*)entry)->Entry->GroupId=((GroupHandle*)group)->Group->Id;
1047 ((EntryHandle*)entry)->Entry->Group=((GroupHandle*)group)->Group;
1051 void Kdb3Database::deleteEntries(QList<IEntryHandle*> entries){
1052 if(!entries.size())return;
1053 StdGroup* Group=((EntryHandle*)entries[0])->Entry->Group;
1054 for(int i=0;i<entries.size();i++){
1056 for(j=0;j<Entries.size();j++){
1057 if(&Entries[j]==((EntryHandle*)entries[i])->Entry)
1060 Group->Children.removeAt(Entries[j].Index);
1061 Entries[j].Handle->invalidate();
1062 Entries.removeAt(j);
1065 for(int i=0;i<Group->Children.size();i++){
1066 Group->Children[i]->Index=i;
1070 QList<IGroupHandle*> Kdb3Database::groups(){
1071 QList<IGroupHandle*> handles;
1072 for(int i=0; i<GroupHandles.size(); i++){
1073 if(GroupHandles[i].isValid())handles.append(&GroupHandles[i]);
1078 quint32 Kdb3Database::getNewGroupId(){
1084 if(!id)continue; //group IDs must not be 0
1085 for(int j=0;j<Groups.size();j++){
1086 if(Groups[j].Id==id){
1095 IGroupHandle* Kdb3Database::addGroup(const CGroup* group,IGroupHandle* ParentHandle){
1096 GroupHandles.append(GroupHandle(this));
1097 Groups.append(*group);
1098 Groups.back().Id=getNewGroupId();
1099 Groups.back().Handle=&GroupHandles.back();
1100 GroupHandles.back().Group=&Groups.back();
1102 Groups.back().Parent=((GroupHandle*)ParentHandle)->Group;
1103 Groups.back().Index=Groups.back().Parent->Children.size();
1104 Groups.back().Parent->Children.append(&Groups.back());
1107 Groups.back().Parent=&RootGroup;
1108 Groups.back().Index=RootGroup.Children.size();
1109 if (group->Title!="Backup" && RootGroup.Children.size() && RootGroup.Children.last()->Title=="Backup"){
1110 RootGroup.Children.last()->Index = Groups.back().Index;
1111 Groups.back().Index--;
1113 Groups.back().Parent->Children.append(&Groups.back());
1115 return &GroupHandles.back();
1118 IGroupHandle* Kdb3Database::backupGroup(bool create){
1119 IGroupHandle* group = NULL;
1120 QList<IGroupHandle*> allGroups = groups();
1121 for (int i=0; i<allGroups.size(); i++){
1122 if (allGroups[i]->parent()==NULL && allGroups[i]->title()=="Backup"){
1123 group = allGroups[i];
1128 if (group==NULL && create){
1130 newGroup.Title = "Backup";
1132 group = addGroup(&newGroup, NULL);
1138 Kdb3Database::StdGroup::StdGroup(const CGroup& other){
1145 void Kdb3Database::EntryHandle::setTitle(const QString& Title){Entry->Title=Title; }
1146 void Kdb3Database::EntryHandle::setUsername(const QString& Username){Entry->Username=Username;}
1147 void Kdb3Database::EntryHandle::setUrl(const QString& Url){Entry->Url=Url;}
1148 void Kdb3Database::EntryHandle::setPassword(const SecString& Password){Entry->Password=Password;}
1149 void Kdb3Database::EntryHandle::setExpire(const KpxDateTime& s){Entry->Expire=s;}
1150 void Kdb3Database::EntryHandle::setCreation(const KpxDateTime& s){Entry->Creation=s;}
1151 void Kdb3Database::EntryHandle::setLastAccess(const KpxDateTime& s){Entry->LastAccess=s;}
1152 void Kdb3Database::EntryHandle::setLastMod(const KpxDateTime& s){Entry->LastMod=s;}
1153 void Kdb3Database::EntryHandle::setBinaryDesc(const QString& s){Entry->BinaryDesc=s;}
1154 void Kdb3Database::EntryHandle::setComment(const QString& s){Entry->Comment=s;}
1155 void Kdb3Database::EntryHandle::setBinary(const QByteArray& s){Entry->Binary=s;}
1156 void Kdb3Database::EntryHandle::setImage(const quint32& s){Entry->Image=s;}
1157 KpxUuid Kdb3Database::EntryHandle::uuid()const{return Entry->Uuid;}
1158 IGroupHandle* Kdb3Database::EntryHandle::group()const{return Entry->Group->Handle;}
1159 quint32 Kdb3Database::EntryHandle::image()const{return Entry->Image;}
1160 QString Kdb3Database::EntryHandle::title()const{return Entry->Title;}
1161 QString Kdb3Database::EntryHandle::url()const{return Entry->Url;}
1162 QString Kdb3Database::EntryHandle::username()const{return Entry->Username;}
1163 SecString Kdb3Database::EntryHandle::password()const{return Entry->Password;}
1164 QString Kdb3Database::EntryHandle::comment()const{return Entry->Comment;}
1165 QString Kdb3Database::EntryHandle::binaryDesc()const{return Entry->BinaryDesc;}
1166 KpxDateTime Kdb3Database::EntryHandle::creation()const{return Entry->Creation;}
1167 KpxDateTime Kdb3Database::EntryHandle::lastMod()const{return Entry->LastMod;}
1168 KpxDateTime Kdb3Database::EntryHandle::lastAccess()const{return Entry->LastAccess;}
1169 KpxDateTime Kdb3Database::EntryHandle::expire()const{return Entry->Expire;}
1170 QByteArray Kdb3Database::EntryHandle::binary()const{return Entry->Binary;}
1171 quint32 Kdb3Database::EntryHandle::binarySize()const{return Entry->Binary.size();}
1173 QString Kdb3Database::EntryHandle::friendlySize()const
1175 quint32 binsize = binarySize();
1188 if (binsize < 1048576)
1194 if (binsize < 1073741824)
1202 faktor = 1073741824;
1206 return (QString::number((float)binsize / (float)faktor, 'f', prec) + " " + unit);
1209 int Kdb3Database::EntryHandle::visualIndex()const{return Entry->Index;}
1210 void Kdb3Database::EntryHandle::setVisualIndexDirectly(int i){Entry->Index=i;}
1211 bool Kdb3Database::EntryHandle::isValid()const{return valid;}
1213 CEntry Kdb3Database::EntryHandle::data()const{
1214 return *this->Entry;
1217 void Kdb3Database::EntryHandle::setVisualIndex(int index){
1218 QList<IEntryHandle*>Entries=pDB->entries(Entry->Group->Handle);
1219 Entries.move(visualIndex(),index);
1220 for(int i=0;i<Entries.size();i++){
1221 dynamic_cast<Kdb3Database::EntryHandle*>(Entries[i])->Entry->Index=index;
1225 Kdb3Database::EntryHandle::EntryHandle(Kdb3Database* db){
1231 bool Kdb3Database::GroupHandle::isValid(){return valid;}
1232 QString Kdb3Database::GroupHandle::title(){return Group->Title;}
1233 quint32 Kdb3Database::GroupHandle::image(){return Group->Image;}
1234 int Kdb3Database::GroupHandle::index(){return Group->Index;}
1235 void Kdb3Database::GroupHandle::setTitle(const QString& Title){Group->Title=Title;}
1236 void Kdb3Database::GroupHandle::setExpanded(bool IsExpanded){Group->IsExpanded=IsExpanded;}
1237 bool Kdb3Database::GroupHandle::expanded(){return Group->IsExpanded;}
1238 void Kdb3Database::GroupHandle::setImage(const quint32& New){Group->Image=New;}
1241 Kdb3Database::GroupHandle::GroupHandle(Kdb3Database* db){
1247 IGroupHandle* Kdb3Database::GroupHandle::parent(){
1248 return (IGroupHandle*)Group->Parent->Handle;
1251 int Kdb3Database::GroupHandle::level(){
1253 StdGroup* group=Group;
1254 while(group->Parent){
1255 group=group->Parent;
1263 QList<IGroupHandle*> Kdb3Database::GroupHandle::children(){
1264 QList<IGroupHandle*> children;
1265 for(int i=0; i < Group->Children.size(); i++){
1266 children.append(Group->Children[i]->Handle);
1272 void memcpyFromLEnd32(quint32* dst,const char* src){
1273 if (QSysInfo::ByteOrder==QSysInfo::BigEndian){
1274 memcpy(((char*)dst)+3,src+0,1);
1275 memcpy(((char*)dst)+2,src+1,1);
1276 memcpy(((char*)dst)+1,src+2,1);
1277 memcpy(((char*)dst)+0,src+3,1);
1284 void memcpyFromLEnd16(quint16* dst,const char* src){
1285 if (QSysInfo::ByteOrder==QSysInfo::BigEndian){
1286 memcpy(((char*)dst)+1,src+0,1);
1287 memcpy(((char*)dst)+0,src+1,1);
1294 void memcpyToLEnd32(char* dst,const quint32* src){
1295 if (QSysInfo::ByteOrder==QSysInfo::BigEndian){
1296 memcpy(dst+0,((char*)src)+3,1);
1297 memcpy(dst+1,((char*)src)+2,1);
1298 memcpy(dst+2,((char*)src)+1,1);
1299 memcpy(dst+3,((char*)src)+0,1);
1306 void memcpyToLEnd16(char* dst,const quint16* src){
1307 if (QSysInfo::ByteOrder==QSysInfo::BigEndian){
1308 memcpy(dst+0,((char*)src)+1,1);
1309 memcpy(dst+1,((char*)src)+0,1);
1316 bool Kdb3Database::save(){
1318 error=tr("The database must contain at least one group.");
1322 //Delete old backup entries
1323 if (config->backup() && config->backupDelete() && config->backupDeleteAfter()>0 && backupGroup()){
1324 QDateTime time = QDateTime::currentDateTime().addDays(-config->backupDeleteAfter());
1325 QList<IEntryHandle*> backupEntries = entries(backupGroup());
1326 for (int i=0; i<backupEntries.size(); i++){
1327 if (backupEntries[i]->lastMod()<time)
1328 deleteEntry(backupEntries[i]);
1332 quint32 NumGroups,NumEntries,Signature1,Signature2,Flags,Version;
1333 quint8 FinalRandomSeed[16];
1334 quint8 ContentsHash[32];
1335 quint8 EncryptionIV[16];
1337 if(!(File->openMode() & QIODevice::WriteOnly)){
1338 error = tr("The database has been opened read-only.");
1342 unsigned int FileSize;
1344 QList<StdEntry> MetaStreams;
1345 MetaStreams << StdEntry();
1346 createCustomIconsMetaStream(&MetaStreams.back());
1347 MetaStreams << StdEntry();
1348 createGroupTreeStateMetaStream(&MetaStreams.back());
1350 FileSize=DB_HEADER_SIZE;
1351 // Get the size of all groups (94 Byte + length of the name string)
1352 for(int i = 0; i < Groups.size(); i++){
1353 FileSize += 94 + Groups[i].Title.toUtf8().length()+1;
1355 // Get the size of all entries
1356 for(int i = 0; i < Entries.size(); i++){
1359 +Entries[i].Title.toUtf8().length()+1
1360 +Entries[i].Username.toUtf8().length()+1
1361 +Entries[i].Url.toUtf8().length()+1
1362 +Entries[i].Password.length()+1
1363 +Entries[i].Comment.toUtf8().length()+1
1364 +Entries[i].BinaryDesc.toUtf8().length()+1
1365 +Entries[i].Binary.length();
1368 for(int i=0; i < UnknownMetaStreams.size(); i++){
1371 +UnknownMetaStreams[i].Comment.toUtf8().length()+1
1372 +UnknownMetaStreams[i].Binary.length();
1375 for(int i=0; i < MetaStreams.size(); i++){
1378 +MetaStreams[i].Comment.toUtf8().length()+1
1379 +MetaStreams[i].Binary.length();
1383 // Round up filesize to 16-byte boundary for Rijndael/Twofish
1384 FileSize = (FileSize + 16) - (FileSize % 16);
1385 char* buffer=new char[FileSize+16];
1387 Signature1 = PWM_DBSIG_1;
1388 Signature2 = PWM_DBSIG_2;
1389 Flags = PWM_FLAG_SHA2;
1390 if(Algorithm == Rijndael_Cipher) Flags |= PWM_FLAG_RIJNDAEL;
1391 else if(Algorithm == Twofish_Cipher) Flags |= PWM_FLAG_TWOFISH;
1392 Version = PWM_DBVER_DW;
1393 NumGroups = Groups.size();
1394 NumEntries = Entries.size()+UnknownMetaStreams.size()+MetaStreams.size();
1396 QList<StdEntry> saveEntries = Entries;
1397 qSort(saveEntries.begin(),saveEntries.end(),StdEntryLessThan);
1399 randomize(FinalRandomSeed,16);
1400 randomize(EncryptionIV,16);
1402 unsigned int pos=DB_HEADER_SIZE; // Skip the header, it will be written later
1404 serializeGroups(buffer,pos);
1405 serializeEntries(saveEntries,buffer,pos);
1406 serializeEntries(UnknownMetaStreams,buffer,pos);
1407 serializeEntries(MetaStreams,buffer,pos);
1408 SHA256::hashBuffer(buffer+DB_HEADER_SIZE,ContentsHash,pos-DB_HEADER_SIZE);
1409 memcpyToLEnd32(buffer,&Signature1);
1410 memcpyToLEnd32(buffer+4,&Signature2);
1411 memcpyToLEnd32(buffer+8,&Flags);
1412 memcpyToLEnd32(buffer+12,&Version);
1413 memcpy(buffer+16,FinalRandomSeed,16);
1414 memcpy(buffer+32,EncryptionIV,16);
1415 memcpyToLEnd32(buffer+48,&NumGroups);
1416 memcpyToLEnd32(buffer+52,&NumEntries);
1417 memcpy(buffer+56,ContentsHash,32);
1418 memcpy(buffer+88,TransfRandomSeed,32);
1419 memcpyToLEnd32(buffer+120,&KeyTransfRounds);
1420 quint8 FinalKey[32];
1423 sha.update(FinalRandomSeed,16);
1425 sha.update(*MasterKey,32);
1427 sha.finish(FinalKey);
1429 unsigned long EncryptedPartSize;
1431 if(Algorithm == Rijndael_Cipher){
1432 EncryptedPartSize=((pos-DB_HEADER_SIZE)/16+1)*16;
1433 quint8 PadLen=EncryptedPartSize-(pos-DB_HEADER_SIZE);
1434 for(int i=0;i<PadLen;i++)
1435 ((quint8*)buffer)[DB_HEADER_SIZE+EncryptedPartSize-1-i]=PadLen;
1437 aes.key256(FinalKey);
1438 aes.cbc_encrypt((unsigned char*)buffer+DB_HEADER_SIZE,(unsigned char*)buffer+DB_HEADER_SIZE,EncryptedPartSize,(unsigned char*)EncryptionIV);
1440 else{ // Algorithm == Twofish_Cipher
1442 if(twofish.init(FinalKey, 32, EncryptionIV) == false){
1447 EncryptedPartSize = (unsigned long)twofish.padEncrypt((quint8*)buffer+DB_HEADER_SIZE,
1448 pos - DB_HEADER_SIZE,(quint8*)buffer+DB_HEADER_SIZE);
1450 if((EncryptedPartSize > (0xFFFFFFE - 202)) || (!EncryptedPartSize && Groups.size())){
1456 int size = EncryptedPartSize+DB_HEADER_SIZE;
1458 if (!File->resize(size)){
1459 // only recreate file if the new database is smaller
1460 if (File->size() > size) {
1461 qDebug("Unable to resize, trying to recreate file");
1462 if (!File->remove() || !File->open(QIODevice::ReadWrite)) {
1464 error=decodeFileError(File->error());
1470 if (File->write(buffer,size)!=size){
1472 error=decodeFileError(File->error());
1475 if (!syncFile(File))
1476 qWarning("Unable to flush file to disk");
1479 //if(SearchGroupID!=-1)Groups.push_back(SearchGroup);
1483 void Kdb3Database::createCustomIconsMetaStream(StdEntry* e){
1485 e->BinaryDesc="bin-stream";
1486 e->Title="Meta-Info";
1487 e->Username="SYSTEM";
1488 e->Comment="KPX_CUSTOM_ICONS_4";
1490 if(Groups.size())e->GroupId=Groups[0].Id;
1492 quint32 NumEntries=0;
1493 for(quint32 i=0;i<Entries.size();i++){
1494 if (Entries[i].Image>=BUILTIN_ICONS)
1497 quint32 NumGroups=0;
1498 for(quint32 i=0;i<Groups.size();i++){
1499 if (Groups[i].Image>=BUILTIN_ICONS)
1502 Size+=8*NumGroups+20*NumEntries;
1503 Size+=CustomIcons.size()*1000; // 1KB
1504 e->Binary.reserve(Size);
1505 e->Binary.resize(12);
1506 quint32 NumIcons=CustomIcons.size();
1508 memcpyToLEnd32(e->Binary.data(),&NumIcons);
1509 memcpyToLEnd32(e->Binary.data()+4,&NumEntries);
1510 memcpyToLEnd32(e->Binary.data()+8,&NumGroups);
1511 for(int i=0;i<CustomIcons.size();i++){
1516 QBuffer buffer(&png);
1517 CustomIcons[i].save(&buffer,"PNG",0);
1519 memcpyToLEnd32(ImgSizeBin,&ImgSize);
1520 e->Binary.append(QByteArray::fromRawData(ImgSizeBin,4));
1521 e->Binary.append(png);
1524 for(quint32 i=0;i<Entries.size();i++){
1525 if (Entries[i].Image>=BUILTIN_ICONS){
1527 Entries[i].Uuid.toRaw(Bin);
1528 quint32 id=Entries[i].Image-BUILTIN_ICONS;
1529 memcpyToLEnd32(Bin+16,&id);
1530 e->Binary.append(QByteArray::fromRawData(Bin,20));
1533 for(quint32 i=0;i<Groups.size();i++){
1534 if (Groups[i].Image>=BUILTIN_ICONS){
1536 memcpyToLEnd32(Bin,&Groups[i].Id);
1537 quint32 id=Groups[i].Image-BUILTIN_ICONS;
1538 memcpyToLEnd32(Bin+4,&id);
1539 e->Binary.append(QByteArray::fromRawData(Bin,8));
1544 QList<IGroupHandle*> Kdb3Database::sortedGroups(){
1545 QList<IGroupHandle*> SortedGroups;
1546 appendChildrenToGroupList(SortedGroups,RootGroup);
1547 return SortedGroups;
1551 void Kdb3Database::appendChildrenToGroupList(QList<IGroupHandle*>& list,StdGroup& group){
1552 for(int i=0;i<group.Children.size();i++){
1553 list << group.Children[i]->Handle;
1554 appendChildrenToGroupList(list,*group.Children[i]);
1559 void Kdb3Database::appendChildrenToGroupList(QList<StdGroup*>& list,StdGroup& group){
1560 for(int i=0;i<group.Children.size();i++){
1561 list << group.Children[i];
1562 appendChildrenToGroupList(list,*group.Children[i]);
1567 void Kdb3Database::serializeGroups(char* buffer,unsigned int& pos){
1570 quint32 Flags=0; //unused
1571 QList<StdGroup*>SortedGroups;
1572 appendChildrenToGroupList(SortedGroups,RootGroup);
1574 for(int i=0; i < SortedGroups.size(); i++){
1575 unsigned char Date[5];
1576 dateToPackedStruct5(Date_Never,Date);
1578 StdGroup* group=SortedGroups[i];
1579 while(group->Parent){
1581 group=group->Parent;
1585 FieldType = 0x0001; FieldSize = 4;
1586 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1587 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1588 memcpyToLEnd32(buffer+pos, &SortedGroups[i]->Id); pos += 4;
1590 FieldType = 0x0002; FieldSize = SortedGroups[i]->Title.toUtf8().length() + 1;
1591 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1592 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1593 memcpy(buffer+pos, SortedGroups[i]->Title.toUtf8(),FieldSize); pos += FieldSize;
1595 FieldType = 0x0003; FieldSize = 5; //Creation
1596 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1597 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1598 memcpy(buffer+pos, Date,5); pos+=5;
1600 FieldType = 0x0004; FieldSize = 5; //LastMod
1601 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1602 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1603 memcpy(buffer+pos, Date,5); pos+=5;
1605 FieldType = 0x0005; FieldSize = 5; //LastAccess
1606 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1607 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1608 memcpy(buffer+pos, Date,5); pos+=5;
1610 FieldType = 0x0006; FieldSize = 5; //Expire
1611 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1612 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1613 memcpy(buffer+pos, Date,5); pos+=5;
1615 FieldType = 0x0007; FieldSize = 4;
1616 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1617 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1618 memcpyToLEnd32(buffer+pos, &SortedGroups[i]->Image); pos += 4;
1620 FieldType = 0x0008; FieldSize = 2;
1621 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1622 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1623 memcpyToLEnd16(buffer+pos, &Level); pos += 2;
1625 FieldType = 0x0009; FieldSize = 4;
1626 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1627 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1628 memcpyToLEnd32(buffer+pos, &Flags); pos += 4;
1630 FieldType = 0xFFFF; FieldSize = 0;
1631 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1632 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1638 void Kdb3Database::serializeEntries(QList<StdEntry>& EntryList,char* buffer,unsigned int& pos){
1641 for(int i = 0; i < EntryList.size(); i++){
1642 FieldType = 0x0001; FieldSize = 16;
1643 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1644 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1645 EntryList[i].Uuid.toRaw(buffer+pos); pos += 16;
1647 FieldType = 0x0002; FieldSize = 4;
1648 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1649 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1650 memcpyToLEnd32(buffer+pos, &EntryList[i].GroupId); pos += 4;
1652 FieldType = 0x0003; FieldSize = 4;
1653 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1654 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1655 memcpyToLEnd32(buffer+pos,&EntryList[i].Image); pos += 4;
1659 FieldSize = EntryList[i].Title.toUtf8().length() + 1; // Add terminating NULL character space
1660 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1661 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1662 memcpy(buffer+pos, EntryList[i].Title.toUtf8(),FieldSize); pos += FieldSize;
1665 FieldSize = EntryList[i].Url.toUtf8().length() + 1; // Add terminating NULL character space
1666 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1667 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1668 memcpy(buffer+pos, EntryList[i].Url.toUtf8(),FieldSize); pos += FieldSize;
1671 FieldSize = EntryList[i].Username.toUtf8().length() + 1; // Add terminating NULL character space
1672 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1673 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1674 memcpy(buffer+pos, EntryList[i].Username.toUtf8(),FieldSize); pos += FieldSize;
1677 FieldSize = EntryList[i].Password.length() + 1; // Add terminating NULL character space
1678 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1679 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1680 EntryList[i].Password.unlock();
1681 memcpy(buffer+pos, EntryList[i].Password.string().toUtf8(),FieldSize); pos += FieldSize;
1682 EntryList[i].Password.lock();
1685 FieldSize = EntryList[i].Comment.toUtf8().length() + 1; // Add terminating NULL character space
1686 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1687 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1688 memcpy(buffer+pos, EntryList[i].Comment.toUtf8(),FieldSize); pos += FieldSize;
1690 FieldType = 0x0009; FieldSize = 5;
1691 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1692 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1693 dateToPackedStruct5(EntryList[i].Creation,(unsigned char*)buffer+pos); pos+=5;
1696 FieldType = 0x000A; FieldSize = 5;
1697 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1698 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1699 dateToPackedStruct5(EntryList[i].LastMod,(unsigned char*)buffer+pos); pos+=5;
1701 FieldType = 0x000B; FieldSize = 5;
1702 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1703 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1704 dateToPackedStruct5(EntryList[i].LastAccess,(unsigned char*)buffer+pos); pos+=5;
1706 FieldType = 0x000C; FieldSize = 5;
1707 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1708 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1709 dateToPackedStruct5(EntryList[i].Expire,(unsigned char*)buffer+pos); pos+=5;
1712 FieldSize = EntryList[i].BinaryDesc.toUtf8().length() + 1; // Add terminating NULL character space
1713 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1714 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1715 memcpy(buffer+pos, EntryList[i].BinaryDesc.toUtf8(),FieldSize); pos += FieldSize;
1717 FieldType = 0x000E; FieldSize = EntryList[i].Binary.length();
1718 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1719 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1720 if((!EntryList[i].Binary.isNull()) && (FieldSize != 0))
1721 memcpy(buffer+pos, EntryList[i].Binary.data(), FieldSize);
1724 FieldType = 0xFFFF; FieldSize = 0;
1725 memcpyToLEnd16(buffer+pos, &FieldType); pos += 2;
1726 memcpyToLEnd32(buffer+pos, &FieldSize); pos += 4;
1730 bool Kdb3Database::close(){
1736 void Kdb3Database::create(){
1738 RootGroup.Title="$ROOT$";
1739 RootGroup.Parent=NULL;
1740 RootGroup.Handle=NULL;
1741 Algorithm=Rijndael_Cipher;
1742 KeyTransfRounds=50000;
1746 bool Kdb3Database::isKeyError(){
1755 IEntryHandle* Kdb3Database::cloneEntry(const IEntryHandle* entry){
1757 dolly=*((EntryHandle*)entry)->Entry;
1758 dolly.Uuid.generate();
1759 Entries.append(dolly);
1760 EntryHandles.append(EntryHandle(this));
1761 EntryHandles.back().Entry=&Entries.back();
1762 Entries.back().Handle=&EntryHandles.back();
1763 return &EntryHandles.back();
1766 IEntryHandle* Kdb3Database::newEntry(IGroupHandle* group){
1768 Entry.Uuid.generate();
1769 Entry.Group=((GroupHandle*)group)->Group;
1770 Entry.GroupId=Entry.Group->Id;
1771 Entries.append(Entry);
1772 EntryHandles.append(EntryHandle(this));
1773 EntryHandles.back().Entry=&Entries.back();
1774 Entries.back().Handle=&EntryHandles.back();
1775 return &EntryHandles.back();
1778 IEntryHandle* Kdb3Database::addEntry(const CEntry* NewEntry, IGroupHandle* Group){
1779 StdEntry Entry(*((StdEntry*)NewEntry));
1780 Entry.Uuid.generate();
1781 Entry.Group=((GroupHandle*)Group)->Group;
1782 Entry.GroupId=Entry.Group->Id;
1783 Entries.append(Entry);
1784 EntryHandles.append(EntryHandle(this));
1785 EntryHandles.back().Entry=&Entries.back();
1786 Entries.back().Handle=&EntryHandles.back();
1787 return &EntryHandles.back();
1790 void Kdb3Database::deleteLastEntry(){
1791 Entries.removeAt(Entries.size()-1);
1792 EntryHandles.back().invalidate();
1795 bool Kdb3Database::isParent(IGroupHandle* parent, IGroupHandle* child){
1796 StdGroup* group=((GroupHandle*)child)->Group;
1797 while(group->Parent!=&RootGroup){
1798 if(group->Parent==((GroupHandle*)parent)->Group)return true;
1799 group=group->Parent;
1806 void Kdb3Database::cleanUpHandles(){}
1808 bool Kdb3Database::searchStringContains(const QString& search, const QString& string,bool Cs, bool RegExp){
1810 QRegExp exp(search,Cs ? Qt::CaseSensitive : Qt::CaseInsensitive);
1811 if(string.contains(exp)==0)return false;}
1813 if(string.contains(search,Cs ? Qt::CaseSensitive : Qt::CaseInsensitive)==0)return false;
1818 void Kdb3Database::getEntriesRecursive(IGroupHandle* Group, QList<IEntryHandle*>& EntryList){
1819 EntryList<<entries(Group);
1820 for(int i=0;i<((GroupHandle*)Group)->Group->Children.size(); i++){
1821 getEntriesRecursive(((GroupHandle*)Group)->Group->Children[i]->Handle,EntryList);
1825 QList<IEntryHandle*> Kdb3Database::search(IGroupHandle* Group,const QString& search, bool CaseSensitive, bool RegExp, bool Recursive,bool* Fields){
1826 bool fields[6]={true,true,true,false,true,true};
1829 QList<IEntryHandle*> SearchEntries;
1830 if(search==QString())return Group ? entries(Group) : entries();
1833 getEntriesRecursive(Group,SearchEntries);
1835 SearchEntries=entries(Group);
1838 SearchEntries=entries();
1840 IGroupHandle* bGroup = backupGroup();
1842 QList<IEntryHandle*> ResultEntries;
1843 for(int i=0; i<SearchEntries.size(); i++){
1844 IGroupHandle* entryGroup = SearchEntries[i]->group();
1845 while (entryGroup->parent())
1846 entryGroup = entryGroup->parent();
1847 if (entryGroup == bGroup)
1851 if(Fields[0])match=match||searchStringContains(search,SearchEntries[i]->title(),CaseSensitive,RegExp);
1852 if(Fields[1])match=match||searchStringContains(search,SearchEntries[i]->username(),CaseSensitive,RegExp);
1853 if(Fields[2])match=match||searchStringContains(search,SearchEntries[i]->url(),CaseSensitive,RegExp);
1854 SecString Password=SearchEntries[i]->password();
1856 if(Fields[3])match=match||searchStringContains(search,Password.string(),CaseSensitive,RegExp);
1858 if(Fields[4])match=match||searchStringContains(search,SearchEntries[i]->comment(),CaseSensitive,RegExp);
1859 if(Fields[5])match=match||searchStringContains(search,SearchEntries[i]->binaryDesc(),CaseSensitive,RegExp);
1861 ResultEntries << SearchEntries[i];
1864 return ResultEntries;
1867 void Kdb3Database::rebuildIndices(QList<StdGroup*>& list){
1868 for(int i=0;i<list.size();i++){
1874 void Kdb3Database::moveGroup(IGroupHandle* groupHandle,IGroupHandle* NewParent,int Pos){
1876 StdGroup* Group=((GroupHandle*)groupHandle)->Group;
1878 Parent=((GroupHandle*)NewParent)->Group;
1881 Group->Parent->Children.removeAt(Group->Index);
1882 rebuildIndices(Group->Parent->Children);
1883 Group->Parent=Parent;
1885 Parent->Children.append(Group);
1889 Q_ASSERT(Parent->Children.size()>=Pos);
1890 Parent->Children.insert(Pos,Group);
1892 rebuildIndices(Parent->Children);
1895 bool Kdb3Database::changeFile(const QString& filename){
1896 QFile* tmpFile = new QFile(filename);
1897 if(!tmpFile->open(QIODevice::ReadWrite)){
1898 error = decodeFileError(File->error());
1911 void Kdb3Database::generateMasterKey(){
1912 randomize(TransfRandomSeed,32);
1913 RawMasterKey.unlock();
1915 KeyTransform::transform(*RawMasterKey,*MasterKey,TransfRandomSeed,KeyTransfRounds);
1916 RawMasterKey.lock();
1920 /*void Kdb3Database::copyTree(Kdb3Database* db, GroupHandle* orgGroup, IGroupHandle* parent) {
1921 IGroupHandle* newParent = db->addGroup(orgGroup->Group, parent);
1923 QList<IEntryHandle*> entryList = entries(orgGroup);
1924 for (int i=0; i<entryList.size(); i++) {
1925 EntryHandle* entry = static_cast<EntryHandle*>(entryList[i]);
1926 db->addEntry(entry->Entry, newParent);
1929 QList<IGroupHandle*> children = orgGroup->children();
1930 for (int i=0; i<children.size(); i++) {
1931 GroupHandle* child = static_cast<GroupHandle*>(children[i]);
1932 copyTree(db, child, newParent);
1936 IDatabase* Kdb3Database::groupToNewDb(IGroupHandle* group){
1937 Kdb3Database* db = new Kdb3Database();
1939 copyTree(db, static_cast<GroupHandle*>(group), NULL);
1941 db->changeFile("/ramtmp/test.kdb");
1943 qWarning("%s", CSTR(db->error));
1949 void KeyTransform::transform(quint8* src, quint8* dst, quint8* KeySeed, int rounds){
1950 KeyTransform* ktLeft = new KeyTransform(&src[0], &dst[0], KeySeed, rounds);
1951 KeyTransform* ktRight = new KeyTransform(&src[16], &dst[16], KeySeed, rounds);
1956 SHA256::hashBuffer(dst,dst,32);
1961 KeyTransform::KeyTransform(quint8* pSrc, quint8* pDst, quint8* pKeySeed, int pRounds){
1968 void KeyTransform::run(){
1970 aes.key256(KeySeed);
1972 for (int i=0; i<rounds; i++){
1973 aes.ecb_encrypt(dst,dst,16);
1978 int KeyTransformBenchmark::benchmark(int pMSecs){
1979 KeyTransformBenchmark* ktbLeft = new KeyTransformBenchmark(pMSecs);
1980 KeyTransformBenchmark* ktbRight = new KeyTransformBenchmark(pMSecs);
1985 int num = std::min(ktbLeft->rounds, ktbRight->rounds);
1992 KeyTransformBenchmark::KeyTransformBenchmark(int pMSecs){
1997 void KeyTransformBenchmark::run(){
1999 memset(KeySeed, 0x4B, 32);
2001 memset(dst, 0x7E, 16);
2007 aes.key256(KeySeed);
2010 for (int i=0; i<64; i++){
2011 aes.ecb_encrypt(dst,dst,16);
2014 } while (t.elapsed() < msecs);