From 4c2997c61077a282c35cc235052ea84282fa753d Mon Sep 17 00:00:00 2001 From: Brian Pellin Date: Wed, 23 Jan 2013 22:30:49 -0600 Subject: [PATCH] First version of database saving that runs without crashing Although, probably not correct --- src/com/keepassdroid/database/BinaryPool.java | 2 +- .../keepassdroid/database/GroupHandler.java | 1 + .../keepassdroid/database/PwDbHeaderV4.java | 1 - src/com/keepassdroid/database/PwEntryV4.java | 38 ++- .../database/load/ImporterV4.java | 2 - .../database/save/PwDbOutput.java | 3 +- .../database/save/PwDbV4Output.java | 322 +++++++++++++++++- .../com/keepassdroid/tests/database/Kdb4.java | 24 ++ 8 files changed, 366 insertions(+), 27 deletions(-) diff --git a/src/com/keepassdroid/database/BinaryPool.java b/src/com/keepassdroid/database/BinaryPool.java index e18d6c8ab..d9b1a13c6 100644 --- a/src/com/keepassdroid/database/BinaryPool.java +++ b/src/com/keepassdroid/database/BinaryPool.java @@ -79,7 +79,7 @@ public class BinaryPool { pool.put(String.valueOf(pool.size()), pb); } - private String poolFind(ProtectedBinary pb) { + public String poolFind(ProtectedBinary pb) { for (Entry pair : pool.entrySet()) { if (pair.getValue().equals(pb)) return pair.getKey(); } diff --git a/src/com/keepassdroid/database/GroupHandler.java b/src/com/keepassdroid/database/GroupHandler.java index fdcd08624..e6999dd0b 100644 --- a/src/com/keepassdroid/database/GroupHandler.java +++ b/src/com/keepassdroid/database/GroupHandler.java @@ -19,6 +19,7 @@ */ package com.keepassdroid.database; + /** "Delegate" class for operating on each group when traversing all of * them * @author bpellin diff --git a/src/com/keepassdroid/database/PwDbHeaderV4.java b/src/com/keepassdroid/database/PwDbHeaderV4.java index f4973ce16..69b95449b 100644 --- a/src/com/keepassdroid/database/PwDbHeaderV4.java +++ b/src/com/keepassdroid/database/PwDbHeaderV4.java @@ -38,7 +38,6 @@ public class PwDbHeaderV4 extends PwDbHeader { public class PwDbHeaderV4Fields { public static final byte EndOfHeader = 0; - @SuppressWarnings("unused") public static final byte Comment = 1; public static final byte CipherID = 2; public static final byte CompressionFlags = 3; diff --git a/src/com/keepassdroid/database/PwEntryV4.java b/src/com/keepassdroid/database/PwEntryV4.java index 3233b7ffb..b39a60556 100644 --- a/src/com/keepassdroid/database/PwEntryV4.java +++ b/src/com/keepassdroid/database/PwEntryV4.java @@ -24,6 +24,8 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; import java.util.UUID; import com.keepassdroid.database.security.ProtectedBinary; @@ -37,37 +39,43 @@ public class PwEntryV4 extends PwEntry implements ITimeLogger { private static final String STR_NOTES = "Notes"; public PwGroupV4 parent; - public UUID uuid; + public UUID uuid = PwDatabaseV4.UUID_ZERO; public Map strings = new HashMap(); public Map binaries = new HashMap(); public PwIconCustom customIcon = PwIconCustom.ZERO; - public String foregroundColor; - public String backgroupColor; - public String overrideURL; + public String foregroundColor = ""; + public String backgroupColor = ""; + public String overrideURL = ""; public AutoType autoType = new AutoType(); public List history = new ArrayList(); - private Date parentGroupLastMod; - private Date creation; - private Date lastMod; - private Date lastAccess; - private Date expireDate; + private Date parentGroupLastMod = PwDatabaseV4.DEFAULT_NOW; + private Date creation = PwDatabaseV4.DEFAULT_NOW; + private Date lastMod = PwDatabaseV4.DEFAULT_NOW; + private Date lastAccess = PwDatabaseV4.DEFAULT_NOW; + private Date expireDate = PwDatabaseV4.DEFAULT_NOW; private boolean expires = false; private long usageCount = 0; - public String url; - public String additional; - public String tags; + public String url = ""; + public String additional = ""; + public String tags = ""; public class AutoType { - public boolean enabled; - public long obfuscationOptions; - public String defaultSequence; + private static final long OBF_OPT_NONE = 0; + + public boolean enabled = true; + public long obfuscationOptions = OBF_OPT_NONE; + public String defaultSequence = ""; private Map windowSeqPairs = new HashMap(); public void put(String key, String value) { windowSeqPairs.put(key, value); } + + public Set> entrySet() { + return windowSeqPairs.entrySet(); + } } diff --git a/src/com/keepassdroid/database/load/ImporterV4.java b/src/com/keepassdroid/database/load/ImporterV4.java index 80728e997..c07189628 100644 --- a/src/com/keepassdroid/database/load/ImporterV4.java +++ b/src/com/keepassdroid/database/load/ImporterV4.java @@ -21,8 +21,6 @@ package com.keepassdroid.database.load; import static com.keepassdroid.database.PwDatabaseV4XML.*; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; diff --git a/src/com/keepassdroid/database/save/PwDbOutput.java b/src/com/keepassdroid/database/save/PwDbOutput.java index 377cac4ff..36dcca35d 100644 --- a/src/com/keepassdroid/database/save/PwDbOutput.java +++ b/src/com/keepassdroid/database/save/PwDbOutput.java @@ -37,8 +37,7 @@ public abstract class PwDbOutput { if ( pm instanceof PwDatabaseV3 ) { return new PwDbV3Output((PwDatabaseV3)pm, os); } else if ( pm instanceof PwDatabaseV4 ) { - // TODO: Implement me - throw new RuntimeException(".kdbx output not yet supported."); + return new PwDbV4Output((PwDatabaseV4)pm, os); } return null; diff --git a/src/com/keepassdroid/database/save/PwDbV4Output.java b/src/com/keepassdroid/database/save/PwDbV4Output.java index 3572180ba..f1e9d4bb5 100644 --- a/src/com/keepassdroid/database/save/PwDbV4Output.java +++ b/src/com/keepassdroid/database/save/PwDbV4Output.java @@ -28,6 +28,7 @@ import java.util.Date; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Stack; import java.util.UUID; import java.util.zip.GZIPOutputStream; @@ -44,12 +45,19 @@ import com.keepassdroid.crypto.CipherFactory; import com.keepassdroid.crypto.PwStreamCipherFactory; import com.keepassdroid.database.BinaryPool; import com.keepassdroid.database.CrsAlgorithm; +import com.keepassdroid.database.EntryHandler; +import com.keepassdroid.database.GroupHandler; +import com.keepassdroid.database.ITimeLogger; import com.keepassdroid.database.PwCompressionAlgorithm; import com.keepassdroid.database.PwDatabaseV4; import com.keepassdroid.database.PwDatabaseV4.MemoryProtectionConfig; import com.keepassdroid.database.PwDatabaseV4XML; import com.keepassdroid.database.PwDbHeader; import com.keepassdroid.database.PwDbHeaderV4; +import com.keepassdroid.database.PwDefsV4; +import com.keepassdroid.database.PwDeletedObject; +import com.keepassdroid.database.PwEntryV4; +import com.keepassdroid.database.PwEntryV4.AutoType; import com.keepassdroid.database.PwGroupV4; import com.keepassdroid.database.PwIconCustom; import com.keepassdroid.database.exception.PwDbOutputException; @@ -111,6 +119,54 @@ public class PwDbV4Output extends PwDbOutput { } } + private class GroupWriter extends GroupHandler { + private Stack groupStack; + + public GroupWriter(Stack gs) { + groupStack = gs; + } + + @Override + public boolean operate(PwGroupV4 group) { + assert(group != null); + + while(true) { + try { + if (group.parent == groupStack.peek()) { + groupStack.push(group); + startGroup(group); + break; + } else { + groupStack.pop(); + if (groupStack.size() <= 0) return false; + endGroup(); + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + return true; + } + } + + private class EntryWriter extends EntryHandler { + + @Override + public boolean operate(PwEntryV4 entry) { + assert(entry != null); + + try { + writeEntry(entry, false); + } catch (IOException e) { + throw new RuntimeException(e); + } + + return true; + } + + } + private void outputDatabase(OutputStream os) throws IllegalArgumentException, IllegalStateException, IOException { binPool = new BinaryPool((PwGroupV4)mPM.rootGroup); @@ -123,6 +179,25 @@ public class PwDbV4Output extends PwDbOutput { writeMeta(); + PwGroupV4 root = (PwGroupV4) mPM.rootGroup; + xml.startTag(null, ElemRoot); + startGroup(root); + Stack groupStack = new Stack(); + groupStack.push(root); + + if (!root.preOrderTraverseTree(new GroupWriter(groupStack), new EntryWriter())) throw new RuntimeException("Writing groups failed"); + + while (groupStack.size() > 1) { + xml.endTag(null, ElemGroup); + groupStack.pop(); + } + + endGroup(); + + writeList(ElemDeletedObjects, mPM.deletedObjects); + + xml.endTag(null, ElemRoot); + xml.endTag(null, ElemDocNode); xml.endDocument(); @@ -222,15 +297,98 @@ public class PwDbV4Output extends PwDbOutput { return header; } + private void startGroup(PwGroupV4 group) throws IllegalArgumentException, IllegalStateException, IOException { + xml.startTag(null, ElemGroup); + writeObject(ElemUuid, group.uuid); + writeObject(ElemName, group.name); + writeObject(ElemNotes, group.notes); + writeObject(ElemIcon, group.icon.iconId); + + if (!group.customIcon.equals(PwIconCustom.ZERO)) { + writeObject(ElemCustomIconID, group.customIcon.uuid); + } + + writeList(ElemTimes, group); + writeObject(ElemIsExpanded, group.isExpanded); + writeObject(ElemGroupDefaultAutoTypeSeq, group.defaultAutoTypeSequence); + writeObject(ElemEnableAutoType, group.enableAutoType); + writeObject(ElemEnableSearching, group.enableSearching); + writeObject(ElemLastTopVisibleEntry, group.lastTopVisibleEntry); + + } + + private void endGroup() throws IllegalArgumentException, IllegalStateException, IOException { + xml.endTag(null, ElemGroup); + } + + private void writeEntry(PwEntryV4 entry, boolean isHistory) throws IllegalArgumentException, IllegalStateException, IOException { + assert(entry != null); + + xml.startTag(null, ElemEntry); + + writeObject(ElemUuid, entry.uuid); + writeObject(ElemIcon, entry.icon.iconId); + + if (entry.customIcon.equals(PwIconCustom.ZERO)) { + writeObject(ElemCustomIconID, entry.customIcon.uuid); + } + + writeObject(ElemFgColor, entry.foregroundColor); + writeObject(ElemBgColor, entry.backgroupColor); + writeObject(ElemOverrideUrl, entry.overrideURL); + writeObject(ElemTags, entry.tags); + + writeList(ElemTimes, entry); + + writeList(entry.strings, true); + writeList(entry.binaries); + writeList(ElemAutoType, entry.autoType); + + if (!isHistory) { + writeList(ElemHistory, entry.history, true); + } else { + assert(entry.history.size() == 0); + } + + xml.endTag(null, ElemEntry); + } + + + private void writeObject(String key, ProtectedBinary value, boolean allowRef) throws IllegalArgumentException, IllegalStateException, IOException { + assert(key != null && value != null); + + xml.startTag(null, ElemBinary); + xml.startTag(null, ElemKey); + xml.text(safeXmlString(key)); + xml.endTag(null, ElemKey); + + xml.startTag(null, ElemValue); + String strRef = null; + if (allowRef) { + strRef = binPool.poolFind(value); + } + + if (strRef != null) { + xml.attribute(null, AttrRef, strRef); + } + else { + subWriteValue(value); + } + + xml.endTag(null, ElemBinary); + } + private void subWriteValue(ProtectedBinary value) throws IllegalArgumentException, IllegalStateException, IOException { if (value.isProtected()) { xml.attribute(null, AttrProtected, ValTrue); int valLength = value.length(); - byte[] encoded = new byte[valLength]; - randomStream.processBytes(value.getData(), 0, valLength, encoded, 0); - - xml.text(String.valueOf(Base64Coder.encode(encoded))); + if (valLength > 0) { + byte[] encoded = new byte[valLength]; + randomStream.processBytes(value.getData(), 0, valLength, encoded, 0); + + xml.text(String.valueOf(Base64Coder.encode(encoded))); + } } else { if (mPM.compressionAlgorithm == PwCompressionAlgorithm.Gzip) { @@ -270,8 +428,19 @@ public class PwDbV4Output extends PwDbOutput { writeObject(name, String.valueOf(value)); } - private void writeObject(String name, boolean value) throws IllegalArgumentException, IllegalStateException, IOException { - writeObject(name, value ? ValTrue : ValFalse); + private void writeObject(String name, Boolean value) throws IllegalArgumentException, IllegalStateException, IOException { + String text; + if (value == null) { + text = "null"; + } + else if (value) { + text = ValTrue; + } + else { + text = ValFalse; + } + + writeObject(name, text); } private void writeObject(String name, UUID uuid) throws IllegalArgumentException, IllegalStateException, IOException { @@ -293,6 +462,118 @@ public class PwDbV4Output extends PwDbOutput { xml.endTag(null, name); } + private void writeList(String name, AutoType autoType) throws IllegalArgumentException, IllegalStateException, IOException { + assert(name != null && autoType != null); + + xml.startTag(null, name); + + writeObject(ElemAutoTypeEnabled, autoType.enabled); + writeObject(ElemAutoTypeObfuscation, autoType.obfuscationOptions); + + if (autoType.defaultSequence.length() > 0) { + writeObject(ElemAutoTypeDefaultSeq, autoType.defaultSequence, true); + } + + for (Entry pair : autoType.entrySet()) { + writeObject(ElemAutoTypeItem, ElemWindow, pair.getKey(), ElemKeystrokeSequence, pair.getValue()); + } + + xml.endTag(null, name); + + } + + private void writeList(Map strings, boolean isEntryString) throws IllegalArgumentException, IllegalStateException, IOException { + assert (strings != null); + + for (Entry pair : strings.entrySet()) { + writeObject(pair.getKey(), pair.getValue(), isEntryString); + + } + + } + + private void writeObject(String key, ProtectedString value, boolean isEntryString) throws IllegalArgumentException, IllegalStateException, IOException { + assert(key !=null && value != null); + + xml.startTag(null, ElemString); + xml.startTag(null, ElemKey); + xml.text(safeXmlString(key)); + xml.endTag(null, ElemKey); + + xml.startTag(null, ElemValue); + boolean protect = value.isProtected(); + if (isEntryString) { + if (key.equals(PwDefsV4.TITLE_FIELD)) { + protect = mPM.memoryProtection.protectTitle; + } + else if (key.equals(PwDefsV4.USERNAME_FIELD)) { + protect = mPM.memoryProtection.protectUserName; + } + else if (key.equals(PwDefsV4.PASSWORD_FIELD)) { + protect = mPM.memoryProtection.protectPassword; + } + else if (key.equals(PwDefsV4.URL_FIELD)) { + protect = mPM.memoryProtection.protectUrl; + } + else if (key.equals(PwDefsV4.NOTES_FIELD)) { + protect = mPM.memoryProtection.protectNotes; + } + } + + if (protect) { + xml.attribute(null, AttrProtected, ValTrue); + + byte[] data = value.toString().getBytes("UTF-8"); + int valLength = data.length; + + if (valLength > 0) { + byte[] encoded = new byte[valLength]; + randomStream.processBytes(data, 0, valLength, encoded, 0); + xml.text(String.valueOf(Base64Coder.encode(encoded))); + } + else { + xml.text(value.toString()); + } + } + + xml.endTag(null, ElemValue); + xml.endTag(null, ElemString); + + } + + private void writeObject(String name, PwDeletedObject value) throws IllegalArgumentException, IllegalStateException, IOException { + assert(name != null && value != null); + + xml.startTag(null, name); + + writeObject(ElemUuid, value.uuid); + writeObject(ElemDeletionTime, value.getDeletionTime()); + + xml.endTag(null, name); + } + + private void writeList(Map binaries) throws IllegalArgumentException, IllegalStateException, IOException { + assert(binaries != null); + + for (Entry pair : binaries.entrySet()) { + writeObject(pair.getKey(), pair.getValue(), true); + } + } + + + private void writeList(String name, List value) throws IllegalArgumentException, IllegalStateException, IOException { + assert(name != null && value != null); + + xml.startTag(null, name); + + for (PwDeletedObject pdo : value) { + writeObject(ElemDeletedObject, pdo); + } + + xml.endTag(null, name); + + } + private void writeList(String name, MemoryProtectionConfig value) throws IllegalArgumentException, IllegalStateException, IOException { assert(name != null && value != null); @@ -321,6 +602,35 @@ public class PwDbV4Output extends PwDbOutput { xml.endTag(null, name); } + + private void writeList(String name, ITimeLogger it) throws IllegalArgumentException, IllegalStateException, IOException { + assert(name != null && it != null); + + xml.startTag(null, name); + + writeObject(ElemLastModTime, it.getLastModificationTime()); + writeObject(ElemCreationTime, it.getCreationTime()); + writeObject(ElemLastAccessTime, it.getLastAccessTime()); + writeObject(ElemExpiryTime, it.getExpiryTime()); + writeObject(ElemExpires, it.expires()); + writeObject(ElemUsageCount, it.getUsageCount()); + writeObject(ElemLocationChanged, it.getLocationChanged()); + + xml.endTag(null, name); + } + + private void writeList(String name, List value, boolean isHistory) throws IllegalArgumentException, IllegalStateException, IOException { + assert(name != null && value != null); + + xml.startTag(null, name); + + for (PwEntryV4 entry : value) { + writeEntry(entry, isHistory); + } + + xml.endTag(null, name); + + } private void writeCustomIconList() throws IllegalArgumentException, IllegalStateException, IOException { List customIcons = mPM.customIcons; diff --git a/tests/src/com/keepassdroid/tests/database/Kdb4.java b/tests/src/com/keepassdroid/tests/database/Kdb4.java index 5e411bef6..8084c35e7 100644 --- a/tests/src/com/keepassdroid/tests/database/Kdb4.java +++ b/tests/src/com/keepassdroid/tests/database/Kdb4.java @@ -19,6 +19,7 @@ */ package com.keepassdroid.tests.database; +import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; @@ -26,10 +27,14 @@ import android.content.Context; import android.content.res.AssetManager; import android.test.AndroidTestCase; +import com.keepassdroid.database.PwDatabaseV4; import com.keepassdroid.database.exception.InvalidDBException; +import com.keepassdroid.database.exception.PwDbOutputException; import com.keepassdroid.database.load.Importer; import com.keepassdroid.database.load.ImporterFactory; import com.keepassdroid.database.load.ImporterV4; +import com.keepassdroid.database.save.PwDbOutput; +import com.keepassdroid.database.save.PwDbV4Output; import com.keepassdroid.tests.TestUtil; public class Kdb4 extends AndroidTestCase { @@ -59,6 +64,25 @@ public class Kdb4 extends AndroidTestCase { is.close(); + } + + public void testSaving() throws IOException, InvalidDBException, PwDbOutputException { + Context ctx = getContext(); + + AssetManager am = ctx.getAssets(); + InputStream is = am.open("test.kdbx", AssetManager.ACCESS_STREAMING); + + ImporterV4 importer = new ImporterV4(); + PwDatabaseV4 db = importer.openDatabase(is, "12345", ""); + is.close(); + + FileOutputStream fos = new FileOutputStream("/sdcard/test-out.kdbx", false); + + PwDbV4Output output = (PwDbV4Output) PwDbOutput.getInstance(db, fos); + output.output(); + fos.close(); + + } @Override