Parse more of the kdb4 header.

This commit is contained in:
Brian Pellin committed 2010-04-25 14:43:46 -05:00
1 parent b815a4de07
commit d26008f50d
13 files changed
+214 -39

No files matched your search

+1
View File
@@ -131,6 +131,7 @@
<string name="search_hint">Entry title/description</string>
<string name="search_label">Search</string>
<string name="show_password">Show password</string>
<string name="unsupported_db_version">Unsupported database version.</string>
<string-array name="clipboard_timeout_options">
<item>30 seconds</item>
+7 -6
View File
@@ -38,6 +38,7 @@ import com.keepassdroid.database.PwDatabaseV3;
import com.keepassdroid.database.PwEntryV3;
import com.keepassdroid.database.PwGroupV3;
import com.keepassdroid.database.exception.InvalidDBSignatureException;
import com.keepassdroid.database.exception.InvalidDBVersionException;
import com.keepassdroid.database.exception.InvalidKeyFileException;
import com.keepassdroid.database.exception.InvalidPasswordException;
import com.keepassdroid.database.exception.Kdb4Exception;
@@ -72,19 +73,19 @@ public class Database {
loaded = true;
}
public void LoadData(Context ctx, InputStream is, String password, String keyfile) throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception {
public void LoadData(Context ctx, InputStream is, String password, String keyfile) throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception, InvalidDBVersionException {
LoadData(ctx, is, password, keyfile, new UpdateStatus(), !Importer.DEBUG);
}
public void LoadData(Context ctx, String filename, String password, String keyfile) throws IOException, InvalidKeyFileException, FileNotFoundException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception {
public void LoadData(Context ctx, String filename, String password, String keyfile) throws IOException, InvalidKeyFileException, FileNotFoundException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception, InvalidDBVersionException {
LoadData(ctx, filename, password, keyfile, new UpdateStatus(), !Importer.DEBUG);
}
public void LoadData(Context ctx, String filename, String password, String keyfile, UpdateStatus status) throws IOException, InvalidKeyFileException, FileNotFoundException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception {
public void LoadData(Context ctx, String filename, String password, String keyfile, UpdateStatus status) throws IOException, InvalidKeyFileException, FileNotFoundException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception, InvalidDBVersionException {
LoadData(ctx, filename, password, keyfile, status, !Importer.DEBUG);
}
public void LoadData(Context ctx, String filename, String password, String keyfile, UpdateStatus status, boolean debug) throws IOException, InvalidKeyFileException, FileNotFoundException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception {
public void LoadData(Context ctx, String filename, String password, String keyfile, UpdateStatus status, boolean debug) throws IOException, InvalidKeyFileException, FileNotFoundException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception, InvalidDBVersionException {
FileInputStream fis;
fis = new FileInputStream(filename);
@@ -93,11 +94,11 @@ public class Database {
mFilename = filename;
}
public void LoadData(Context ctx, InputStream is, String password, String keyfile, boolean debug) throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception {
public void LoadData(Context ctx, InputStream is, String password, String keyfile, boolean debug) throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception, InvalidDBVersionException {
LoadData(ctx, is, password, keyfile, new UpdateStatus(), debug);
}
public void LoadData(Context ctx, InputStream is, String password, String keyfile, UpdateStatus status, boolean debug) throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception {
public void LoadData(Context ctx, InputStream is, String password, String keyfile, UpdateStatus status, boolean debug) throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException, Kdb4Exception, InvalidDBVersionException {
BufferedInputStream bis = new BufferedInputStream(is);
@@ -0,0 +1,31 @@
/*
* Copyright 2010 Brian Pellin.
*
* This file is part of KeePassDroid.
*
* KeePassDroid 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 2 of the License, or
* (at your option) any later version.
*
* KeePassDroid 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 KeePassDroid. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.keepassdroid.database;
public class PwCompressionAlgorithm {
// Note: We can get away with using int's to store unsigned 32-bit ints
// since we won't do arithmetic on these values (also unlikely to
// reach
public static final int None = 0;
public static final int Gzip = 1;
public static final int Count = 2;
}
@@ -22,5 +22,11 @@ package com.keepassdroid.database;
public abstract class PwDbHeader {
public static final int PWM_DBSIG_1 = 0x9AA2D903;
/** Seed that gets hashed with the userkey to form the final key */
public byte mMasterSeed[];
/** Used for the dwKeyEncRounds AES transformations */
public byte mTransformSeed[];
}
@@ -51,8 +51,6 @@ public class PwDbHeaderV3 extends PwDbHeader {
public int flags;
public int version;
/** Seed that gets hashed with the userkey to form the final key */
public byte masterSeed[] = new byte[16];
/** IV used for content encryption */
public byte encryptionIV[] = new byte[16];
@@ -64,21 +62,19 @@ public class PwDbHeaderV3 extends PwDbHeader {
/** SHA-256 hash of the database, used for integrity check */
public byte contentsHash[] = new byte[32];
/** Used for the dwKeyEncRounds AES transformations */
public byte masterSeed2[] = new byte[32];
public int numKeyEncRounds;
/**
* Parse given buf, as read from file.
* @param buf
*/
public PwDbHeaderV3( byte buf[], int offset ) {
public void loadFromFile( byte buf[], int offset ) {
signature1 = Types.readInt( buf, offset + 0 );
signature2 = Types.readInt( buf, offset + 4 );
flags = Types.readInt( buf, offset + 8 );
version = Types.readInt( buf, offset + 12 );
System.arraycopy( buf, offset + 16, masterSeed, 0, 16 );
System.arraycopy( buf, offset + 16, mMasterSeed, 0, 16 );
System.arraycopy( buf, offset + 32, encryptionIV, 0, 16 );
numGroups = Types.readInt( buf, offset + 48 );
@@ -86,12 +82,13 @@ public class PwDbHeaderV3 extends PwDbHeader {
System.arraycopy( buf, offset + 56, contentsHash, 0, 32 );
System.arraycopy( buf, offset + 88, masterSeed2, 0, 32 );
System.arraycopy( buf, offset + 88, mTransformSeed, 0, 32 );
numKeyEncRounds = Types.readInt( buf, offset + 120 );
}
public PwDbHeaderV3() {
mMasterSeed = new byte[16];
mTransformSeed = new byte[32];
}
public static boolean matchesHeader(int sig1, int sig2) {
+113 -2
View File
@@ -1,5 +1,5 @@
/*
* Copyright 2009 Brian Pellin.
* Copyright 2010 Brian Pellin.
*
* This file is part of KeePassDroid.
*
@@ -19,16 +19,127 @@
*/
package com.keepassdroid.database;
import java.io.IOException;
import java.io.InputStream;
import com.keepassdroid.database.exception.InvalidDBVersionException;
import com.keepassdroid.utils.Types;
public class PwDbHeaderV4 extends PwDbHeader {
public static final int DBSIG_PRE2 = 0xB54BFB66;
public static final int DBSIG_2 = 0xB54BFB67;
private static final int FILE_VERSION_CRITICAL_MASK = 0xFFFF0000;
private static final int FILE_VERSION_32 = 0x00020000;
private class PwDbHeaderV4Fields {
public static final byte EndOfHeader = 0;
public static final byte Comment = 1;
public static final byte CipherID = 2;
public static final byte CompressionFlags = 3;
public static final byte MasterSeed = 4;
public static final byte TransformSeed = 5;
public static final byte TransformRounds = 6;
public static final byte EncryptionIV = 7;
public static final byte ProtectedStreamKey = 8;
public static final byte StreamStartBytes = 8;
public static final byte InnerRandomStreamID = 9;
}
private PwDatabaseV4 mDb;
public PwDbHeaderV4(PwDatabaseV4 db) {
mDb = db;
}
/** Assumes the input stream is at the beginning of the .kdbx file
* @param is
* @throws IOException
* @throws InvalidDBVersionException
*/
public PwDbHeaderV4(InputStream is) {
public void loadFromFile(InputStream is) throws IOException, InvalidDBVersionException {
long version = Types.readUInt(is);
if ( ! validVersion(version) ) {
throw new InvalidDBVersionException();
}
boolean done = false;
while ( ! done ) {
done = readHeaderField(is);
}
}
private boolean readHeaderField(InputStream is) throws IOException {
byte fieldID = (byte) is.read();
int fieldSize = Types.readShort(is);
byte[] fieldData = null;
if ( fieldSize > 0 ) {
fieldData = new byte[fieldSize];
int readSize = is.read(fieldData);
if ( readSize != fieldSize ) {
throw new IOException("Header ended early.");
}
}
switch ( fieldID ) {
case PwDbHeaderV4Fields.EndOfHeader:
return true;
case PwDbHeaderV4Fields.CipherID:
setCipher(fieldData);
case PwDbHeaderV4Fields.CompressionFlags:
setCompressionFlags(fieldData);
case PwDbHeaderV4Fields.MasterSeed:
mMasterSeed = fieldData;
case PwDbHeaderV4Fields.TransformSeed:
mTransformSeed = fieldData;
case PwDbHeaderV4Fields.TransformRounds:
}
return false;
}
private void setCipher(byte[] pbId) throws IOException {
if ( pbId == null || pbId.length != 16 ) {
throw new IOException("Invalid cipher ID.");
}
mDb.mDataCipher = Types.bytestoUUID(pbId);
}
private void setCompressionFlags(byte[] pbFlags) throws IOException {
if ( pbFlags == null || pbFlags.length != 4 ) {
throw new IOException("Invalid compression flags.");
}
int flag = Types.readInt(pbFlags, 0);
if ( flag >= PwCompressionAlgorithm.Count ) {
throw new IOException("Unrecognized compression flag.");
}
mDb.mCompression = flag;
}
/** Determines if this is a supported version.
*
* A long is needed here to represent the unsigned int since we perform
* arithmetic on it.
* @param version
* @return
*/
private boolean validVersion(long version) {
return ! ((version & FILE_VERSION_CRITICAL_MASK) > (FILE_VERSION_32 & FILE_VERSION_CRITICAL_MASK));
}
@@ -29,6 +29,7 @@ import android.preference.PreferenceManager;
import com.android.keepass.R;
import com.keepassdroid.Database;
import com.keepassdroid.database.exception.InvalidDBSignatureException;
import com.keepassdroid.database.exception.InvalidDBVersionException;
import com.keepassdroid.database.exception.InvalidKeyFileException;
import com.keepassdroid.database.exception.InvalidPasswordException;
import com.keepassdroid.database.exception.Kdb4Exception;
@@ -80,6 +81,9 @@ public class LoadDB extends RunnableOnFinish {
} catch (Kdb4Exception e) {
finish(false, mCtx.getString(R.string.error_kdb4));
return;
} catch (InvalidDBVersionException e) {
finish(false, mCtx.getString(R.string.unsupported_db_version));
return;
}
finish(true);
@@ -25,6 +25,7 @@ import java.io.InputStream;
import com.keepassdroid.UpdateStatus;
import com.keepassdroid.database.PwDatabase;
import com.keepassdroid.database.exception.InvalidDBSignatureException;
import com.keepassdroid.database.exception.InvalidDBVersionException;
import com.keepassdroid.database.exception.InvalidKeyFileException;
import com.keepassdroid.database.exception.InvalidPasswordException;
@@ -42,10 +43,10 @@ public abstract class Importer {
}
public abstract PwDatabase openDatabase( InputStream inStream, String password, String keyfile )
throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException;
throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException, InvalidDBVersionException;
public abstract PwDatabase openDatabase( InputStream inStream, String password, String keyfile, UpdateStatus status )
throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException;
throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException, InvalidDBVersionException;
}
@@ -42,7 +42,6 @@ import javax.crypto.ShortBufferException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Log;
import com.android.keepass.R;
@@ -52,10 +51,12 @@ import com.keepassdroid.crypto.finalkey.FinalKey;
import com.keepassdroid.crypto.finalkey.FinalKeyFactory;
import com.keepassdroid.database.PwDatabaseV3;
import com.keepassdroid.database.PwDate;
import com.keepassdroid.database.PwDbHeader;
import com.keepassdroid.database.PwDbHeaderV3;
import com.keepassdroid.database.PwEntryV3;
import com.keepassdroid.database.PwGroupV3;
import com.keepassdroid.database.exception.InvalidDBSignatureException;
import com.keepassdroid.database.exception.InvalidDBVersionException;
import com.keepassdroid.database.exception.InvalidKeyFileException;
import com.keepassdroid.database.exception.InvalidPasswordException;
import com.keepassdroid.database.save.NullOutputStream;
@@ -91,6 +92,7 @@ public class ImporterV3 extends Importer {
* @throws InvalidPasswordException
* @throws InvalidPasswordException on a decryption error, or possible internal bug.
* @throws InvalidDBSignatureException
* @throws InvalidDBVersionException
* @throws IllegalBlockSizeException on a decryption error, or possible internal bug.
* @throws BadPaddingException on a decryption error, or possible internal bug.
* @throws NoSuchAlgorithmException on a decryption error, or possible internal bug.
@@ -99,13 +101,13 @@ public class ImporterV3 extends Importer {
* @throws ShortBufferException if error decrypting main file body.
*/
public PwDatabaseV3 openDatabase( InputStream inStream, String password, String keyfile )
throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException
throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException, InvalidDBVersionException
{
return openDatabase(inStream, password, keyfile, new UpdateStatus());
}
public PwDatabaseV3 openDatabase( InputStream inStream, String password, String keyfile, UpdateStatus status )
throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException
throws IOException, InvalidKeyFileException, InvalidPasswordException, InvalidDBSignatureException, InvalidDBVersionException
{
PwDatabaseV3 newManager;
byte[] finalKey;
@@ -119,14 +121,15 @@ public class ImporterV3 extends Importer {
// Parse header (unencrypted)
if( filebuf.length < PwDbHeaderV3.BUF_SIZE )
throw new IOException( "File too short for header" );
PwDbHeaderV3 hdr = new PwDbHeaderV3( filebuf, 0 );
PwDbHeaderV3 hdr = new PwDbHeaderV3();
hdr.loadFromFile(filebuf, 0 );
if( (hdr.signature1 != PwDbHeaderV3.PWM_DBSIG_1) || (hdr.signature2 != PwDbHeaderV3.DBSIG_2) ) {
if( (hdr.signature1 != PwDbHeader.PWM_DBSIG_1) || (hdr.signature2 != PwDbHeaderV3.DBSIG_2) ) {
throw new InvalidDBSignatureException();
}
if( hdr.version != PwDbHeaderV3.DBVER_DW ) {
//throw new IOException( "Bad database file version" );
throw new InvalidDBVersionException();
}
status.updateMessage(R.string.creating_db_key);
@@ -154,7 +157,7 @@ public class ImporterV3 extends Importer {
newManager.name = "KeePass Password Manager";
// Generate transformedMasterKey from masterKey
finalKey = makeFinalKey(hdr.masterSeed, hdr.masterSeed2, newManager.masterKey, newManager.numKeyEncRounds);
finalKey = makeFinalKey(hdr.mMasterSeed, hdr.mTransformSeed, newManager.masterKey, newManager.numKeyEncRounds);
newManager.finalKey = new byte[finalKey.length];
System.arraycopy(finalKey, 0, newManager.finalKey, 0, finalKey.length);
@@ -40,12 +40,12 @@ public class PwDbHeaderOutput {
mOS.write(Types.writeInt(mHeader.signature2));
mOS.write(Types.writeInt(mHeader.flags));
mOS.write(Types.writeInt(mHeader.version));
mOS.write(mHeader.masterSeed);
mOS.write(mHeader.mMasterSeed);
mOS.write(mHeader.encryptionIV);
mOS.write(Types.writeInt(mHeader.numGroups));
mOS.write(Types.writeInt(mHeader.numEntries));
mOS.write(mHeader.contentsHash);
mOS.write(mHeader.masterSeed2);
mOS.write(mHeader.mTransformSeed);
mOS.write(Types.writeInt(mHeader.numKeyEncRounds));
}
@@ -38,6 +38,7 @@ import javax.crypto.spec.SecretKeySpec;
import com.keepassdroid.crypto.AESProvider;
import com.keepassdroid.database.PwDatabaseV3;
import com.keepassdroid.database.PwDbHeader;
import com.keepassdroid.database.PwDbHeaderV3;
import com.keepassdroid.database.PwEntryV3;
import com.keepassdroid.database.PwGroupV3;
@@ -62,17 +63,17 @@ public class PwDbV3Output {
mDebug = debug;
}
public byte[] getFinalKey(PwDbHeaderV3 header) throws PwDbOutputException {
public byte[] getFinalKey(PwDbHeader header) throws PwDbOutputException {
try {
return ImporterV3.makeFinalKey(header.masterSeed, header.masterSeed2, mPM.masterKey, mPM.numKeyEncRounds);
return ImporterV3.makeFinalKey(header.mMasterSeed, header.mTransformSeed, mPM.masterKey, mPM.numKeyEncRounds);
} catch (IOException e) {
throw new PwDbOutputException("Key creation failed: " + e.getMessage());
}
}
public byte[] getFinalKey2(PwDbHeaderV3 header) throws PwDbOutputException {
public byte[] getFinalKey2(PwDbHeader header) throws PwDbOutputException {
try {
return ImporterV3.makeFinalKey(header.masterSeed, header.masterSeed2, mPM.masterKey, mPM.numKeyEncRounds);
return ImporterV3.makeFinalKey(header.mMasterSeed, header.mTransformSeed, mPM.masterKey, mPM.numKeyEncRounds);
} catch (IOException e) {
throw new PwDbOutputException("Key creation failed: " + e.getMessage());
}
@@ -114,7 +115,7 @@ public class PwDbV3Output {
public PwDbHeaderV3 outputHeader(OutputStream os) throws PwDbOutputException {
// Build header
PwDbHeaderV3 header = new PwDbHeaderV3();
header.signature1 = PwDbHeaderV3.PWM_DBSIG_1;
header.signature1 = PwDbHeader.PWM_DBSIG_1;
header.signature2 = PwDbHeaderV3.DBSIG_2;
header.flags = PwDbHeaderV3.FLAG_SHA2;
@@ -135,8 +136,8 @@ public class PwDbV3Output {
// Reuse random values to test equivalence in debug mode
if ( mDebug ) {
System.arraycopy(mPM.dbHeader.encryptionIV, 0, header.encryptionIV, 0, mPM.dbHeader.encryptionIV.length);
System.arraycopy(mPM.dbHeader.masterSeed, 0, header.masterSeed, 0, mPM.dbHeader.masterSeed.length);
System.arraycopy(mPM.dbHeader.masterSeed2, 0, header.masterSeed2, 0, mPM.dbHeader.masterSeed2.length);
System.arraycopy(mPM.dbHeader.mMasterSeed, 0, header.mMasterSeed, 0, mPM.dbHeader.mMasterSeed.length);
System.arraycopy(mPM.dbHeader.mTransformSeed, 0, header.mTransformSeed, 0, mPM.dbHeader.mTransformSeed.length);
} else {
SecureRandom random;
try {
@@ -145,8 +146,8 @@ public class PwDbV3Output {
throw new PwDbOutputException("Does not support secure random number generation.");
}
random.nextBytes(header.encryptionIV);
random.nextBytes(header.masterSeed);
random.nextBytes(header.masterSeed2);
random.nextBytes(header.mMasterSeed);
random.nextBytes(header.mTransformSeed);
}
// Write checksum Checksum
+18
View File
@@ -37,6 +37,8 @@ import java.util.UUID;
*/
public class Types {
private static final long INT_TO_LONG_MASK = 0xffffffffL;
/*
public static long readUInt(byte buf[], int offset) {
int firstByte = 0;
@@ -80,6 +82,10 @@ public class Types {
return (buf[offset + 0] & 0xFF) + ((buf[offset + 1] & 0xFF) << 8) + ((buf[offset + 2] & 0xFF) << 16)
+ ((buf[offset + 3] & 0xFF) << 24);
}
public static long readUInt( byte buf[], int offset ) {
return (readInt(buf, offset) & INT_TO_LONG_MASK);
}
public static int readInt(InputStream is) throws IOException {
byte[] buf = new byte[4];
@@ -88,6 +94,10 @@ public class Types {
return Types.readInt(buf, 0);
}
public static long readUInt(InputStream is) throws IOException {
return (readInt(is) & INT_TO_LONG_MASK);
}
/**
@@ -122,6 +132,14 @@ public class Types {
return (buf[offset + 0] & 0xFF) + ((buf[offset + 1] & 0xFF) << 8);
}
public static int readShort(InputStream is) throws IOException {
byte[] buf = new byte[2];
is.read(buf, 0, 2);
return readShort(buf, 0);
}
/** Write an unsigned 16-bit value
*
* @param val
@@ -34,6 +34,7 @@ import android.content.res.AssetManager;
import android.test.AndroidTestCase;
import com.keepassdroid.database.PwDatabaseV3;
import com.keepassdroid.database.PwDbHeader;
import com.keepassdroid.database.PwDbHeaderV3;
import com.keepassdroid.database.exception.PwDbOutputException;
import com.keepassdroid.database.save.NullOutputStream;
@@ -88,8 +89,8 @@ public class PwManagerOutputTest extends AndroidTestCase {
assertEquals("Version unequal", expected.version, actual.version);
assertArrayEquals("Hash unequal", expected.contentsHash, actual.contentsHash);
assertArrayEquals("IV unequal", expected.encryptionIV, actual.encryptionIV);
assertArrayEquals("Seed unequal", expected.masterSeed, actual.masterSeed);
assertArrayEquals("Seed2 unequal", expected.masterSeed2, actual.masterSeed2);
assertArrayEquals("Seed unequal", expected.mMasterSeed, actual.mMasterSeed);
assertArrayEquals("Seed2 unequal", expected.mTransformSeed, actual.mTransformSeed);
}
public void testHeader() throws PwDbOutputException, IOException {
@@ -109,7 +110,7 @@ public class PwManagerOutputTest extends AndroidTestCase {
public void testFinalKey() throws PwDbOutputException {
ByteArrayOutputStream bActual = new ByteArrayOutputStream();
PwDbV3Output pActual = new PwDbV3Output(mPM, bActual, PwDbV3Output.DEBUG);
PwDbHeaderV3 hActual = pActual.outputHeader(bActual);
PwDbHeader hActual = pActual.outputHeader(bActual);
byte[] finalKey = pActual.getFinalKey2(hActual);
assertArrayEquals("Keys mismatched", mPM.finalKey, finalKey);