API

Main Interaction

This part of the documentation covers the primary API for interacting with the keepass database.

Database

The database classes provide the primary API for loading and saving KeePass 1.x databases, in addition to creating new groups and entries.

class keepassdb.db.Database(dbfile=None, password=None, keyfile=None, readonly=False, new=False)[source]

This class represents the KeePass 1.x database.

Variables:
  • root – The group-like virtual root object (not actually part of database).
  • groups – The flat list of groups (keepassdb.model.Group) in this database.
  • entries – The flat list of entries (keepassdb.model.Entry) in this database.
  • readonly – Whether database was opened read-only.
  • filepath – The path to the database that is opened or will be written (if specified).
  • password – The passphrase to use to encrypt the database.
  • keyfile – A path to a keyfile that can be used instead or in combination with passphrase.
  • header – The database header struct (keepassdb.structs.HeaderStruct).
close()[source]

Closes the database, performs any necessary cleanup functions.

create_default_group()[source]

Create a default ‘Internet’ group on an empty database.

Returns:The new ‘Internet’ group.
Return type:keepassdb.model.Group
create_entry(group, **kwargs)[source]

Create a new Entry object.

The group which should hold the entry is needed.

image must be an unsigned int >0, group a Group.

Parameters:
  • group – The associated group.
  • title
  • icon
  • url
  • username
  • password
  • notes
  • expires (datetime) – Expiration date (if None, entry will never expire).
Returns:

The new entry.

Return type:

keepassdb.model.Entry

create_group(title, parent=None, icon=1, expires=None)[source]

This method creates a new group.

A group title is needed or no group will be created.

If a parent is given, the group will be created as a sub-group.

title must be a string, image an unsigned int >0 and parent a Group.

Returns:The newly created group.
Return type:keepassdb.model.Group
filepath[source]

Property for retrieving current filepath (or None if db not loaded from file)

load(dbfile, password=None, keyfile=None, readonly=False)[source]

Load the database from file/stream.

Parameters:
  • dbfile (str or file-like object) – The database file path/stream.
  • password (str) – The password for the database.
  • keyfile (str or file-like object) – Path to a keyfile (or a stream) that can be used instead of or in conjunction with password for database.
  • readonly (bool) – Whether to open the database read-only.
load_from_buffer(buf, password=None, keyfile=None, readonly=False)[source]

Load a database from passed-in buffer (bytes).

Parameters:
  • buf (str) – A string (bytes) of the database contents.
  • password (str) – The password for the database.
  • keyfile (str or file-like object) – Path to a keyfile (or a stream) that can be used instead of or in conjunction with password for database.
  • readonly (bool) – Whether to open the database read-only.
move_entry(entry, group, index=None)[source]

Move an entry to another group.

Parameters:
  • entry (keepassdb.model.Entry) – The Entry object to move.
  • group (keepassdb.model.Group) – The new parent Group object for the entry.
  • index (int) – The 0-based index within the parent (defaults to appending group to end of parent’s children).
move_group(group, parent, index=None)[source]

Move group to be a child of new parent.

Parameters:
  • group (keepassdb.model.Group) – The group to move.
  • parent (keepassdb.model.Group) – The new parent for the group.
  • index (int) – The 0-based index within the parent (defaults to appending group to end of parent’s children).
remove_entry(entry)[source]

Remove specified entry.

Parameters:entry (keepassdb.model.Entry) – The Entry object to remove.
remove_group(group)[source]

Remove the specified group.

save(dbfile=None, password=None, keyfile=None)[source]

Save the database to specified file/stream with password and/or keyfile.

Parameters:
  • dbfile (The path to the database file or a file-like object.) – The path to the file we wish to save.
  • password (str) – The password to use for the database encryption key.
  • keyfile (str or file-like object) – The path to keyfile (or a stream) to use instead of or in conjunction with password for encryption key.
Raises keepassdb.exc.ReadOnlyDatabase:
 

If database was opened with readonly flag.

class keepassdb.db.LockingDatabase(dbfile=None, password=None, keyfile=None, readonly=False, new=False)[source]

A convenience subclass that adds automatic file locking (if db not opened read-only).

The lock is only acquired when the filepath is specified to a load() or save() operation. The close() method will also release the lock.

acquire_lock(force=False)[source]

Takes out a lock (creates a <dbname>.lock file) for the database.

Parameters:force (bool) – Whether to force taking “ownership” of the lock file.
Raises :keepassdb.exc.DatabaseAlreadyLocked - If the database is already locked (and force not set to True).
close()[source]

Closes the database, releasing lock.

filepath[source]

Property for retrieving current filepath (or None if db not loaded from file)

release_lock(force=False)[source]

Releases the lock (deletes the <dbname>.lock file) if it was acquired by this class or force is set to True.

Parameters:force (bool) – Whether to force releasing the lock (e.g. if it was not acquired during this session).

Model

The model consists of the Group and Entity classes that together make up the contents of the database. These classes are directly related to their keepassdb.structs counterparts; however, they also track the hierarchy of the database, track modification times, and provide convenience methods to perform create and move operations.

class keepassdb.model.Entry(uuid=None, group_id=None, group=None, icon=None, title=None, url=None, username=None, password=None, notes=None, created=None, modified=None, accessed=None, expires=None, binary_desc=None, binary=None)[source]

Entry represents a simple entry of a KeePass 1.x database.

Variables:
  • uuid – The ID for the entry.
  • group_id – The numeric ID for the group.
  • group – The group object that this entity is related to.
  • icon – The icon identifier.
  • title – The title for the entry.
  • username – The username.
  • password – The password
  • url – The entry URL.
  • notes – Notes/comment for the entry.
  • created – When entry was created (default: now)
  • modified – When entry was last modified (default: now)
  • accessed – When the entry was last accessed (default: now)
  • expires – When the entry (password) expires. Default will be keepassdb.const.NEVER.
  • binary_desc – Description/metadata for the binary column.
  • binary – Binary contents.
change_index(index)[source]

This method moves the entry to another position in the group.

move(group, index=None)[source]

This method moves the entry to another group.

remove()[source]

This method removes this entry.

struct_type

alias of EntryStruct

class keepassdb.model.Group(id=None, title=None, icon=None, level=None, created=None, modified=None, accessed=None, expires=None, flags=None, parent=None, db=None)[source]

Represents a single group of a KeePass 1.x database.

Variables:
  • db – The parent database (keepassdb.db.Database)
  • id – The group numeric id (unsigned int)
  • title – The group title (string)
  • level – The hierarchy level / depth in tree (unsigned int)
  • icon – The group icon identifier used in KeePassX (unsigned int)
  • parent – The parent group (keepassdb.model.Group)
  • children – List of children groups (keepassdb.model.Group)
  • entries – List of member entries (keepassdb.model.Entry)
change_index(index)[source]

Move the group to the new 0-based index within the same parent.

Parameters:index (int) – The 0-based index for the new position within parent group. Note that this index will be evaluated after the group has been removed from the list.
create_entry(**kwargs)[source]

This method creates an entry in this group.

Parameters:
  • title
  • icon
  • url
  • username
  • password
  • notes
  • expires (datetime) – Expiration date (if None, entry will never expire).
move(parent, index=None)[source]

Move this group to a new parent.

Parameters:
  • parent (keepassdb.model.Group) – The new parent group; if None will be root group.
  • index (int) – The 0-based index within the parent (defaults to appending group to end of parent’s children).
remove()[source]

This method calls remove_group of the holding db

struct_type

alias of GroupStruct

class keepassdb.model.RootGroup[source]

A group-like object that serves as the root node of the tree.

This is the root attribute of the keepassdb.db.Database instance.

This object is not written to the database; it simply exists to provide a virtual node from which to make the top-level groups children.

Variables:
  • title – The title for the group (‘Root Group’)
  • level – The hierarchy level / depth in tree; This is -1 for root group.
  • children – List of children groups (keepassdb.model.Group)

Export

The export package contains classes for exporting the database.

Support for exporting database to KeePassX XML format.

class keepassdb.export.xml.XmlExporter(include_comment=False, prettyprint=True)[source]

Class for exporting database to KeePassX XML format.

Variables:
  • include_comment – Whether to include a ‘generated-by’ comment in the header.
  • prettyprint – Whether to generate pretty-printed XML (indent, etc.).
export(db)[source]

Export the dbnode to KeePassX XML format.

Parameters:db (keepassdb.db.Database) – The database to export.

Errors

The exception classes raised by the library.

exception keepassdb.exc.AuthenticationError[source]

Exception raised when (encrypted) contents cannot be verified against signature.

exception keepassdb.exc.DatabaseAlreadyLocked[source]

Raised when the database is already locked.

exception keepassdb.exc.IncorrectKey[source]

Exception raised when contents cannot be decrypted with specified key.

exception keepassdb.exc.InvalidDatabase[source]

Error raised when database appears to be invalid. :)

exception keepassdb.exc.KPError[source]

KPError is the base exception class to handle exception raised by keepassdb.

exception keepassdb.exc.ParseError[source]

Exception raised when unable to parse database structure.

exception keepassdb.exc.ReadOnlyDatabase[source]

Error when database was opened read-only.

exception keepassdb.exc.UnboundModelError[source]

Exception raised when referencing a group or entity that hasn’t been bound to the database.

exception keepassdb.exc.UnsupportedDatabaseVersion[source]

Error raised when attempting to open a database version that is newer (e.g. KeePass2).

Under-the-Hood

This part of the documentation describes the under-the-hood of the database parsing and serialization code.

Parsing

Support for reading and writing the structures that comprise the keepass database.

This module is derived from the elegant parsing improvements Brett Viren <brett.viren@gmail.com> introduced in the python-keepass project.

class keepassdb.structs.EntryStruct(buf=None)[source]
One entry: [FIELDTYPE(FT)][FIELDSIZE(FS)][FIELDDATA(FD)]
[FT+FS+(FD)][FT+FS+(FD)][FT+FS+(FD)][FT+FS+(FD)][FT+FS+(FD)]...

Basic structure:

  • [ 2 bytes] FIELDTYPE
  • [ 4 bytes] FIELDSIZE, size of FIELDDATA in bytes
  • [ n bytes] FIELDDATA, n = FIELDSIZE

Notes:

  • Strings are stored in UTF-8 encoded form and are null-terminated.
  • FIELDTYPE can be one of the following identifiers:
  • 0000: Invalid or comment block, block is ignored

  • 0001: UUID, uniquely identifying an entry, FIELDSIZE must be 16

  • 0002: Group ID, identifying the group of the entry, FIELDSIZE = 4

    It can be any 32-bit value except 0 and 0xFFFFFFFF

  • 0003: Image ID, identifying the image/icon of the entry, FIELDSIZE = 4

  • 0004: Title of the entry, FIELDDATA is an UTF-8 encoded string

  • 0005: URL string, FIELDDATA is an UTF-8 encoded string

  • 0006: UserName string, FIELDDATA is an UTF-8 encoded string

  • 0007: Password string, FIELDDATA is an UTF-8 encoded string

  • 0008: Notes string, FIELDDATA is an UTF-8 encoded string

  • 0009: Creation time, FIELDSIZE = 5, FIELDDATA = packed date/time

  • 000A: Last modification time, FIELDSIZE = 5, FIELDDATA = packed date/time

  • 000B: Last access time, FIELDSIZE = 5, FIELDDATA = packed date/time

  • 000C: Expiration time, FIELDSIZE = 5, FIELDDATA = packed date/time

  • 000D: Binary description UTF-8 encoded string

  • 000E: Binary data

  • FFFF: Entry terminator, FIELDSIZE must be 0

class keepassdb.structs.GroupStruct(buf=None)[source]

Structure representing a single group.

Basic structure: [FIELDTYPE(FT)][FIELDSIZE(FS)][FIELDDATA(FD)]
[FT+FS+(FD)][FT+FS+(FD)][FT+FS+(FD)][FT+FS+(FD)][FT+FS+(FD)]...

General structure:

  • [ 2 bytes] FIELDTYPE
  • [ 4 bytes] FIELDSIZE, size of FIELDDATA in bytes
  • [ n bytes] FIELDDATA, n = FIELDSIZE

Notes:

  • Strings are stored in UTF-8 encoded form and are null-terminated.
  • FIELDTYPE can be one of the following identifiers:
  • 0000: Invalid or comment block, block is ignored

  • 0001: Group ID, FIELDSIZE must be 4 bytes

    It can be any 32-bit value except 0 and 0xFFFFFFFF

  • 0002: Group name, FIELDDATA is an UTF-8 encoded string

  • 0003: Creation time, FIELDSIZE = 5, FIELDDATA = packed date/time

  • 0004: Last modification time, FIELDSIZE = 5, FIELDDATA = packed date/time

  • 0005: Last access time, FIELDSIZE = 5, FIELDDATA = packed date/time

  • 0006: Expiration time, FIELDSIZE = 5, FIELDDATA = packed date/time

  • 0007: Image ID, FIELDSIZE must be 4 bytes

  • 0008: Level, FIELDSIZE = 2

  • 0009: Flags, 32-bit value, FIELDSIZE = 4

  • FFFF: Group entry terminator, FIELDSIZE must be 0

class keepassdb.structs.HeaderStruct(buf=None)[source]

The keepass file header.

From the KeePass doc:

Database header:

  • [ 4 bytes] DWORD dwSignature1 = 0x9AA2D903

  • [ 4 bytes] DWORD dwSignature2 = 0xB54BFB65

  • [ 4 bytes] DWORD dwFlags

  • [ 4 bytes] DWORD dwVersion { Ve.Ve.Mj.Mj:Mn.Mn.Bl.Bl }

  • [16 bytes] BYTE{16} aMasterSeed

  • [16 bytes] BYTE{16} aEncryptionIV

  • [ 4 bytes] DWORD dwGroups Number of groups in database

  • [ 4 bytes] DWORD dwEntries Number of entries in database

  • [32 bytes] BYTE{32} aContentsHash SHA-256 hash value of the plain contents

  • [32 bytes] BYTE{32} aMasterSeed2 Used for the dwKeyEncRounds AES

    master key transformations

  • [ 4 bytes] DWORD dwKeyEncRounds See above; number of transformations

Notes:

  • dwFlags is a bitmap, which can include: * PWM_FLAG_SHA2 (1) for SHA-2. * PWM_FLAG_RIJNDAEL (2) for AES (Rijndael). * PWM_FLAG_ARCFOUR (4) for ARC4. * PWM_FLAG_TWOFISH (8) for Twofish.
  • aMasterSeed is a salt that gets hashed with the transformed user master key to form the final database data encryption/decryption key. * FinalKey = SHA-256(aMasterSeed, TransformedUserMasterKey)
  • aEncryptionIV is the initialization vector used by AES/Twofish for encrypting/decrypting the database data.
  • aContentsHash: “plain contents” refers to the database file, minus the database header, decrypted by FinalKey. * PlainContents = Decrypt_with_FinalKey(DatabaseFile - DatabaseHeader)
decode(buf)[source]

Set object attributes from binary string buffer.

Parameters:buf (bytes) – The binary string representation of this struct from database.
encode()[source]

Returns binary string representation of this struct.

Returns:Structure encoded as binary string for keepass database.
Return type:bytes
class keepassdb.structs.Marshall[source]

Abstract base class for the marshall implementations.

decode(buf)[source]

Decode value from database’s binary string representation to something that will be useful for library consumers.

encode(val)[source]

Encode the specified value as the binary string representation needed for the database.

Return type:str
class keepassdb.structs.MarshallAscii[source]

Encode/decode values by converting to hex notation.

decode(buf)[source]

Decode the specified value by hex encoding the input string.

Parameters:buf (str) – The the byte value to encode.
Returns:hexlified / base-16-encoded value.
Return type:str
encode(val)[source]

Encode the specified value by hex decoding the input string.

Parameters:val (str) – The hex-encoded input string.
Returns:unhexlified / base-16-decoded byte value.
Return type:str
class keepassdb.structs.MarshallDate[source]

Marshall the date format needed for keepass db to/from python datetime objects.

decode(buf)[source]

Decodes the date field into a python datetime object.

Returns:The decoded datetime object.
Return type:datetime.datetime
encode(val)[source]

Encode the python datetime value into the bytes needed for database format.

Parameters:val (datetime.datetime) – The datetime object.
Returns:Bytes for data.
Return type:str
class keepassdb.structs.MarshallInt[source]

Encode/decode int/long values.

class keepassdb.structs.MarshallNone[source]

A None-returning dummy marshaller.

class keepassdb.structs.MarshallPass[source]

Pass-through marshall implemenatation (e.g. for binary data).

class keepassdb.structs.MarshallShort[source]

Encode/decode short int values.

class keepassdb.structs.MarshallString[source]

Encode/decode unicode or string values.

decode(buf)[source]

Decode buffer (UTF-8 bytes) to unicode string and remove null termination byte.

Parameters:buf (str) – The bytes.
Return type:unicode
encode(val)[source]

Encode specified unicode value as UTF-8 string with null-byte termination.

Parameters:val (unicode) – The unicode (or str) input value.
Return type:str
class keepassdb.structs.StructBase(buf=None)[source]

Abstract base class for the struct representations.

attributes()[source]

Returns a dict of all this structures attributes and values, skipping any attributes that start with an underscore (assumed they should be ignored).

decode(buf)[source]

Set object attributes from binary string representation.

Parameters:buf (str) – The binary string representation of this object in database.
Raises :keepassdb.exc.ParseError - If errors encountered parsing struct.
encode()[source]

Return binary string representation of object.

Return type:str

Table Of Contents

Previous topic

Exporting

This Page