3 File::KDBX - Encrypted database to store secret text and files
13 # Create a new database from scratch
14 my $kdbx = File::KDBX->new;
16 # Add some objects to the database
17 my $group = $kdbx->add_group(
20 my $entry = $group->add_entry(
22 username => 'mreynolds',
26 # Save the database to the filesystem
27 $kdbx->dump_file('passwords.kdbx', 'M@st3rP@ssw0rd!');
29 # Load the database from the filesystem into a new database instance
30 my $kdbx2 = File::KDBX->load_file('passwords.kdbx', 'M@st3rP@ssw0rd!');
32 # Iterate over database entries, print entry titles
33 $kdbx2->entries->each(sub {
35 say 'Entry: ', $entry->title;
38 See "RECIPES" for more examples.
42 File::KDBX provides everything you need to work with KDBX databases. A
43 KDBX database is a hierarchical object database which is commonly used
44 to store secret information securely. It was developed for the KeePass
45 password safe. See "Introduction to KDBX" for more information about
48 This module lets you query entries, create new entries, delete entries,
49 modify entries and more. The distribution also includes various parsers
50 and generators for serializing and persisting databases.
52 The design of this software was influenced by the KeePassXC
53 <https://github.com/keepassxreboot/keepassxc> implementation of KeePass
54 as well as the File::KeePass module. File::KeePass is an alternative
55 module that works well in most cases but has a small backlog of bugs
56 and security issues and also does not work with newer KDBX version 4
57 files. If you're coming here from the File::KeePass world, you might be
58 interested in File::KeePass::KDBX that is a drop-in replacement for
59 File::KeePass that uses File::KDBX for storage.
61 This software is a pre-1.0 release. The interface should be considered
62 pretty stable, but there might be minor changes up until a 1.0 release.
63 Breaking changes will be noted in the Changes file.
67 * ☑ Read and write KDBX version 3 - version 4.1
69 * ☑ Read and write KDB files (requires File::KeePass)
71 * ☑ Unicode character strings
73 * ☑ "Simple Expression" Searching
75 * ☑ Placeholders and field references
77 * ☑ One-time passwords
81 * ☑ "Memory Protection"
83 * ☑ Challenge-response key components, like YubiKey
85 * ☑ Variety of key file types: binary, hexed, hashed, XML v1 and v2
87 * ☑ Pluggable registration of different kinds of ciphers and key
90 * ☑ Built-in database maintenance functions
92 * ☑ Pretty fast, with XS optimizations available
94 * ☒ Database synchronization / merging (not yet)
98 A KDBX database consists of a tree of groups and entries, with a single
99 root group. Entries can contain zero or more key-value pairs of strings
100 and zero or more binaries (i.e. octet strings). Groups, entries,
101 strings and binaries: that's the KDBX vernacular. A small amount of
102 metadata (timestamps, etc.) is associated with each entry, group and
103 the database as a whole.
105 You can think of a KDBX database kind of like a file system, where
106 groups are directories, entries are files, and strings and binaries
107 make up a file's contents.
109 Databases are typically persisted as encrypted, compressed files. They
110 are usually accessed directly (i.e. not over a network). The primary
111 focus of this type of database is data security. It is ideal for
112 storing relatively small amounts of data (strings and binaries) that
113 must remain secret except to such individuals as have the correct
114 master key. Even if the database file were to be "leaked" to the public
115 Internet, it should be virtually impossible to crack with a strong key.
116 The KDBX format is most often used by password managers to store
117 passwords so that users can know a single strong password and not have
118 to reuse passwords across different websites. See "SECURITY" for an
119 overview of security considerations.
139 Hash of UUIDs for objects that have been deleted. This includes groups,
140 entries and even custom icons.
144 Bytes contained within the encrypted layer of a KDBX file. This is only
145 set when using File::KDBX::Loader::Raw.
149 A text string associated with the database. Often unset.
153 The UUID of a cipher used to encrypt the database when stored as a
156 See File::KDBX::Cipher.
160 Configuration for whether or not and how the database gets compressed.
161 See ":compression" in File::KDBX::Constants.
165 The master seed is a string of 32 random bytes that is used as salt in
166 hashing the master key when loading and saving the database. If a
167 challenge-response key is used in the master key, the master seed is
170 The master seed should be changed each time the database is saved to
175 The transform seed is a string of 32 random bytes that is used in the
176 key derivation function, either as the salt or the key (depending on
179 The transform seed should be changed each time the database is saved to
184 The number of rounds or iterations used in the key derivation function.
185 Increasing this number makes loading and saving the database slower by
186 design in order to make dictionary and brute force attacks more costly.
190 The initialization vector used by the cipher.
192 The encryption IV should be changed each time the database is saved to
195 inner_random_stream_key
197 The encryption key (possibly including the IV, depending on the cipher)
198 used to encrypt the protected strings within the database.
202 A string of 32 random bytes written in the header and encrypted in the
203 body. If the bytes do not match when loading a file then the wrong
204 master key was used or the file is corrupt. Only KDBX 2 and KDBX 3
205 files use this. KDBX 4 files use an improved HMAC method to verify the
206 master key and data integrity of the header and entire file body.
208 inner_random_stream_id
210 A number indicating the cipher algorithm used to encrypt the protected
211 strings within the database, usually Salsa20 or ChaCha20. See
212 ":random_stream" in File::KDBX::Constants.
216 A hash/dict of key-value pairs used to configure the key derivation
217 function. This is the KDBX4+ way to configure the KDF, superceding
218 "transform_seed" and "transform_rounds".
222 The name of the software used to generate the KDBX file.
226 The header hash used to verify that the file header is not corrupt.
227 (KDBX 2 - KDBX 3.1, removed KDBX 4.0)
231 Name of the database.
233 database_name_changed
235 Timestamp indicating when the database name was last changed.
239 Description of the database
241 database_description_changed
243 Timestamp indicating when the database description was last changed.
247 When a new entry is created, the UserName string will be populated with
250 default_username_changed
252 Timestamp indicating when the default username was last changed.
256 A color associated with the database (in the form #ffffff where "f" is
257 a hexidecimal digit). Some agents use this to help users visually
258 distinguish between different databases.
262 Timestamp indicating when the master key was last changed.
264 master_key_change_rec
266 Number of days until the agent should prompt to recommend changing the
269 master_key_change_force
271 Number of days until the agent should prompt to force changing the
274 Note: This is purely advisory. It is up to the individual agent
275 software to actually enforce it. File::KDBX does NOT enforce it.
279 Array of custom icons that can be associated with groups and entries.
281 This list can be managed with the methods "add_custom_icon" and
282 "remove_custom_icon".
286 Boolean indicating whether removed groups and entries should go to a
287 recycle bin or be immediately deleted.
291 The UUID of a group used to store thrown-away groups and entries.
295 Timestamp indicating when the recycle bin group was last changed.
297 entry_templates_group
299 The UUID of a group containing template entries used when creating new
302 entry_templates_group_changed
304 Timestamp indicating when the entry templates group was last changed.
308 The UUID of the previously-selected group.
310 last_top_visible_group
312 The UUID of the group visible at the top of the list.
316 The maximum number of historical entries that should be kept for each
317 entry. Default is 10.
321 The maximum total size (in bytes) that each individual entry's history
322 is allowed to grow. Default is 6 MiB.
324 maintenance_history_days
326 The maximum age (in days) historical entries should be kept. Default it
331 Timestamp indicating when the database settings were last updated.
335 Alias of the "memory_protection" setting for the Title string.
339 Alias of the "memory_protection" setting for the UserName string.
343 Alias of the "memory_protection" setting for the Password string.
347 Alias of the "memory_protection" setting for the URL string.
351 Alias of the "memory_protection" setting for the Notes string.
357 $kdbx = File::KDBX->new(%attributes);
358 $kdbx = File::KDBX->new($kdbx); # copy constructor
360 Construct a new File::KDBX.
364 $kdbx = $kdbx->init(%attributes);
366 Initialize a File::KDBX with a set of attributes. Returns itself to
367 allow method chaining.
369 This is called by "new".
373 $kdbx = $kdbx->reset;
375 Set a File::KDBX to an empty state, ready to load a KDBX file or build
376 a new one. Returns itself to allow method chaining.
380 $kdbx_copy = $kdbx->clone;
381 $kdbx_copy = File::KDBX->new($kdbx);
383 Clone a File::KDBX. The clone will be an exact copy and completely
384 independent of the original.
394 $kdbx = KDBX::File->load(\$string, $key);
395 $kdbx = KDBX::File->load(*IO, $key);
396 $kdbx = KDBX::File->load($filepath, $key);
397 $kdbx->load(...); # also instance method
399 $kdbx = File::KDBX->load_string($string, $key);
400 $kdbx = File::KDBX->load_string(\$string, $key);
401 $kdbx->load_string(...); # also instance method
403 $kdbx = File::KDBX->load_file($filepath, $key);
404 $kdbx->load_file(...); # also instance method
406 $kdbx = File::KDBX->load_handle($fh, $key);
407 $kdbx = File::KDBX->load_handle(*IO, $key);
408 $kdbx->load_handle(...); # also instance method
410 Load a KDBX file from a string buffer, IO handle or file from a
413 File::KDBX::Loader does the heavy lifting.
423 $kdbx->dump(\$string, $key);
424 $kdbx->dump(*IO, $key);
425 $kdbx->dump($filepath, $key);
427 $kdbx->dump_string(\$string, $key);
428 \$string = $kdbx->dump_string($key);
430 $kdbx->dump_file($filepath, $key);
432 $kdbx->dump_handle($fh, $key);
433 $kdbx->dump_handle(*IO, $key);
435 Dump a KDBX file to a string buffer, IO handle or file in a filesystem.
437 File::KDBX::Dumper does the heavy lifting.
441 $string = $kdbx->user_agent_string;
443 Get a text string identifying the database client software.
447 \%settings = $kdbx->memory_protection
448 $kdbx->memory_protection(\%settings);
450 $bool = $kdbx->memory_protection($string_key);
451 $kdbx->memory_protection($string_key => $bool);
453 Get or set memory protection settings. This globally (for the whole
454 database) configures whether and which of the standard strings should
455 be memory-protected. The default setting is to memory-protect only
458 Memory protection can be toggled individually for each entry string,
459 and individual settings take precedence over these global settings.
463 $version = $kdbx->minimum_version;
465 Determine the minimum file version required to save a database
466 losslessly. Using certain databases features might increase this value.
467 For example, setting the KDF to Argon2 will increase the minimum
468 version to at least KDBX_VERSION_4_0 (i.e. 0x00040000) because Argon2
469 was introduced with KDBX4.
471 This method never returns less than KDBX_VERSION_3_1 (i.e. 0x00030001).
472 That file version is so ubiquitous and well-supported, there are seldom
473 reasons to dump in a lesser format nowadays.
475 WARNING: If you dump a database with a minimum version higher than the
476 current "version", the dumper will typically issue a warning and
477 automatically upgrade the database. This seems like the safest behavior
478 in order to avoid data loss, but lower versions have the benefit of
479 being compatible with more software. It is possible to prevent
480 auto-upgrades by explicitly telling the dumper which version to use,
481 but you do run the risk of data loss. A database will never be
482 automatically downgraded.
486 $group = $kdbx->root;
489 Get or set a database's root group. You don't necessarily need to
490 explicitly create or set a root group because it autovivifies when
491 adding entries and groups to the database.
493 Every database has only a single root group at a time. Some old KDB
494 files might have multiple root groups. When reading such files, a
495 single implicit root group is created to contain the actual root
496 groups. When writing to such a format, if the root group looks like it
497 was implicitly created then it won't be written and the resulting file
498 might have multiple root groups, as it was before loading. This allows
499 working with older files without changing their written internal
500 structure while still adhering to modern semantics while the database
503 The root group of a KDBX database contains all of the database's
504 entries and other groups. If you replace the root group, you are
505 essentially replacing the entire database contents with something else.
509 \@lineage = $kdbx->trace_lineage($group);
510 \@lineage = $kdbx->trace_lineage($group, $base_group);
511 \@lineage = $kdbx->trace_lineage($entry);
512 \@lineage = $kdbx->trace_lineage($entry, $base_group);
514 Get the direct line of ancestors from $base_group (default: the root
515 group) to a group or entry. The lineage includes the base group but not
516 the target group or entry. Returns undef if the target is not in the
521 $group = $kdbx->recycle_bin;
522 $kdbx->recycle_bin($group);
524 Get or set the recycle bin group. Returns undef if there is no recycle
525 bin and "recycle_bin_enabled" is false, otherwise the current recycle
526 bin or an autovivified recycle bin group is returned.
530 $group = $kdbx->entry_templates;
531 $kdbx->entry_templates($group);
533 Get or set the entry templates group. May return undef if unset.
537 $group = $kdbx->last_selected;
538 $kdbx->last_selected($group);
540 Get or set the last selected group. May return undef if unset.
544 $group = $kdbx->last_top_visible;
545 $kdbx->last_top_visible($group);
547 Get or set the last top visible group. May return undef if unset.
551 $kdbx->add_group($group);
552 $kdbx->add_group(%group_attributes, %options);
554 Add a group to a database. This is equivalent to identifying a parent
555 group and calling "add_group" in File::KDBX::Group on the parent group,
556 forwarding the arguments. Available options:
558 * group - Group object or group UUID to add the group to (default:
563 \&iterator = $kdbx->groups(%options);
564 \&iterator = $kdbx->groups($base_group, %options);
566 Get an File::KDBX::Iterator over groups within a database. Options:
568 * base - Only include groups within a base group (same as
569 $base_group) (default: "root")
571 * inclusive - Include the base group in the results (default: true)
573 * algorithm - Search algorithm, one of ids, bfs or dfs (default: ids)
577 $kdbx->add_entry($entry, %options);
578 $kdbx->add_entry(%entry_attributes, %options);
580 Add a entry to a database. This is equivalent to identifying a parent
581 group and calling "add_entry" in File::KDBX::Group on the parent group,
582 forwarding the arguments. Available options:
584 * group - Group object or group UUID to add the entry to (default:
589 \&iterator = $kdbx->entries(%options);
590 \&iterator = $kdbx->entries($base_group, %options);
592 Get an File::KDBX::Iterator over entries within a database. Supports
593 the same options as "groups", plus some new ones:
595 * auto_type - Only include entries with auto-type enabled (default:
598 * searching - Only include entries within groups with searching
599 enabled (default: false, include all)
601 * history - Also include historical entries (default: false, include
602 only current entries)
606 \&iterator = $kdbx->objects(%options);
607 \&iterator = $kdbx->objects($base_group, %options);
609 Get an File::KDBX::Iterator over objects within a database. Groups and
610 entries are considered objects, so this is essentially a combination of
611 "groups" and "entries". This won't often be useful, but it can be
612 convenient for maintenance tasks. This method takes the same options as
613 "groups" and "entries".
617 \%icon = $kdbx->custom_icon($uuid);
618 $kdbx->custom_icon($uuid => \%icon);
619 $kdbx->custom_icon(%icon);
620 $kdbx->custom_icon(uuid => $value, %icon);
622 Get or set custom icons.
626 $image_data = $kdbx->custom_icon_data($uuid);
628 Get a custom icon image data.
632 $uuid = $kdbx->add_custom_icon($image_data, %attributes);
633 $uuid = $kdbx->add_custom_icon(%attributes);
635 Add a custom icon and get its UUID. If not provided, a random UUID will
636 be generated. Possible attributes:
638 * uuid - Icon UUID (default: autogenerated)
640 * data - Image data (same as $image_data)
642 * name - Name of the icon (text, KDBX4.1+)
644 * last_modification_time - Just what it says (datetime, KDBX4.1+)
648 $kdbx->remove_custom_icon($uuid);
650 Remove a custom icon.
654 \%all_data = $kdbx->custom_data;
655 $kdbx->custom_data(\%all_data);
657 \%data = $kdbx->custom_data($key);
658 $kdbx->custom_data($key => \%data);
659 $kdbx->custom_data(%data);
660 $kdbx->custom_data(key => $value, %data);
662 Get and set custom data. Custom data is metadata associated with a
665 Each data item can have a few attributes associated with it.
667 * key - A unique text string identifier used to look up the data item
670 * value - A text string value (required)
672 * last_modification_time (optional, KDBX4.1+)
676 $value = $kdbx->custom_data_value($key);
678 Exactly the same as "custom_data" except returns just the custom data's
679 value rather than a structure of attributes. This is a shortcut for:
681 my $data = $kdbx->custom_data($key);
682 my $value = defined $data ? $data->{value} : undef;
686 \%all_data = $kdbx->public_custom_data;
687 $kdbx->public_custom_data(\%all_data);
689 $value = $kdbx->public_custom_data($key);
690 $kdbx->public_custom_data($key => $value);
692 Get and set public custom data. Public custom data is similar to custom
693 data but different in some important ways. Public custom data:
695 * can store strings, booleans and up to 64-bit integer values (custom
696 data can only store text values)
698 * is NOT encrypted within a KDBX file (hence the "public" part of the
701 * is a plain hash/dict of key-value pairs with no other associated
702 fields (like modification times)
706 $kdbx->add_deleted_object($uuid);
708 Add a UUID to the deleted objects list. This list is used to support
709 automatic database merging.
711 You typically do not need to call this yourself because the list will
712 be populated automatically as objects are removed.
714 remove_deleted_object
716 $kdbx->remove_deleted_object($uuid);
718 Remove a UUID from the deleted objects list. This list is used to
719 support automatic database merging.
721 You typically do not need to call this yourself because the list will
722 be maintained automatically as objects are added.
724 clear_deleted_objects
726 Remove all UUIDs from the deleted objects list. This list is used to
727 support automatic database merging, but if you don't need merging then
728 you can clear deleted objects to reduce the database file size.
732 $string = $kdbx->resolve_reference($reference);
733 $string = $kdbx->resolve_reference($wanted, $search_in, $expression);
735 Resolve a field reference
736 <https://keepass.info/help/base/fieldrefs.html>. A field reference is a
737 kind of string placeholder. You can use a field reference to refer
738 directly to a standard field within an entry. Field references are
739 resolved automatically while expanding entry strings (i.e. replacing
740 placeholders), but you can use this method to resolve on-the-fly
741 references that aren't part of any actual string in the database.
743 If the reference does not resolve to any field, undef is returned. If
744 the reference resolves to multiple fields, only the first one is
745 returned (in the same order as iterated by "entries"). To avoid
746 ambiguity, you can refer to a specific entry by its UUID.
748 The syntax of a reference is: {REF:<WantedField>@<SearchIn>:<Text>}.
749 Text is a "Simple Expression". WantedField and SearchIn are both single
750 character codes representing a field:
764 * O - Other custom strings
766 Since O does not represent any specific field, it cannot be used as the
771 To get the value of the UserName string of the first entry with "My
774 my $username = $kdbx->resolve_reference('{REF:U@T:"My Bank"}');
775 # OR the {REF:...} wrapper is optional
776 my $username = $kdbx->resolve_reference('U@T:"My Bank"');
777 # OR separate the arguments
778 my $username = $kdbx->resolve_reference(U => T => '"My Bank"');
780 Note how the text is a "Simple Expression", so search terms with spaces
781 must be surrounded in double quotes.
783 To get the Password string of a specific entry (identified by its
786 my $password = $kdbx->resolve_reference('{REF:P@I:46C9B1FFBD4ABC4BBB260C6190BAD20C}');
792 Encrypt all protected strings and binaries in a database. The encrypted
793 data is stored in a File::KDBX::Safe associated with the database and
794 the actual values will be replaced with undef to indicate their
795 protected state. Returns itself to allow method chaining.
797 You can call lock on an already-locked database to memory-protect any
798 unprotected strings and binaries added after the last time the database
805 Decrypt all protected strings and binaries in a database, replacing
806 undef value placeholders with their actual, unprotected values. Returns
807 itself to allow method chaining.
811 $guard = $kdbx->unlock_scoped;
813 Unlock a database temporarily, relocking when the guard is released
814 (typically at the end of a scope). Returns undef if the database is
817 See "lock" and "unlock".
822 my $guard = $kdbx->unlock_scoped;
825 # $kdbx is now memory-locked
829 $string = $kdbx->peek(\%string);
830 $string = $kdbx->peek(\%binary);
832 Peek at the value of a protected string or binary without unlocking the
833 whole database. The argument can be a string or binary hashref as
834 returned by "string" in File::KDBX::Entry or "binary" in
839 $bool = $kdbx->is_locked;
841 Get whether or not a database's contents are in a locked (i.e.
842 memory-protected) state. If this is true, then some or all of the
843 protected strings and binaries within the database will be unavailable
844 (literally have undef values) until "unlock" is called.
848 $kdbx->remove_empty_groups;
850 Remove groups with no subgroups and no entries.
854 $kdbx->remove_unused_icons;
856 Remove icons that are not associated with any entry or group in the
859 remove_duplicate_icons
861 $kdbx->remove_duplicate_icons;
863 Remove duplicate icons as determined by hashing the icon data.
867 $kdbx->prune_history(%options);
869 Remove just as many older historical entries as necessary to get under
872 * max_items - Maximum number of historical entries to keep (default:
873 value of "history_max_items", no limit: -1)
875 * max_size - Maximum total size (in bytes) of historical entries to
876 keep (default: value of "history_max_size", no limit: -1)
878 * max_age - Maximum age (in days) of historical entries to keep
879 (default: 365, no limit: -1)
883 $kdbx->randomize_seeds;
885 Set various keys, seeds and IVs to random values. These values are used
886 by the cryptographic functions that secure the database when dumped.
887 The attributes that will be randomized are:
891 * "inner_random_stream_key"
895 * "stream_start_bytes"
899 Randomizing these values has no effect on a loaded database. These are
900 only used when a database is dumped. You normally do not need to call
901 this method explicitly because the dumper does it explicitly by
907 $key = $kdbx->key($key);
908 $key = $kdbx->key($primitive);
910 Get or set a File::KDBX::Key. This is the master key (e.g. a password
911 or a key file that can decrypt a database). You can also pass a
912 primitive castable to a Key. See "new" in File::KDBX::Key for an
913 explanation of what the primitive can be.
915 You generally don't need to call this directly because you can provide
916 the key directly to the loader or dumper when loading or dumping a KDBX
921 $key = $kdbx->composite_key($key);
922 $key = $kdbx->composite_key($primitive);
924 Construct a File::KDBX::Key::Composite from a Key or primitive. See
925 "new" in File::KDBX::Key for an explanation of what the primitive can
926 be. If the primitive does not represent a composite key, it will be
929 You generally don't need to call this directly. The loader and dumper
930 use it to transform a master key into a raw encryption key.
934 $kdf = $kdbx->kdf(%options);
935 $kdf = $kdbx->kdf(\%parameters, %options);
937 Get a File::KDBX::KDF (key derivation function).
941 * params - KDF parameters, same as \%parameters (default: value of
946 $cipher = $kdbx->cipher(key => $key);
947 $cipher = $kdbx->cipher(key => $key, iv => $iv, uuid => $uuid);
949 Get a File::KDBX::Cipher capable of encrypting and decrypting the body
952 A key is required. This should be a raw encryption key made up of a
953 fixed number of octets (depending on the cipher), not a File::KDBX::Key
956 If not passed, the UUID comes from $kdbx->headers->{cipher_id} and the
957 encryption IV comes from $kdbx->headers->{encryption_iv}.
959 You generally don't need to call this directly. The loader and dumper
960 use it to decrypt and encrypt KDBX files.
964 $cipher = $kdbx->random_stream;
965 $cipher = $kdbx->random_stream(id => $stream_id, key => $key);
967 Get a File::KDBX::Cipher::Stream for decrypting and encrypting
970 If not passed, the ID and encryption key comes from
971 $kdbx->headers->{inner_random_stream_id} and
972 $kdbx->headers->{inner_random_stream_key} (respectively) for KDBX3
973 files and from $kdbx->inner_headers->{inner_random_stream_key} and
974 $kdbx->inner_headers->{inner_random_stream_id} (respectively) for KDBX4
977 You generally don't need to call this directly. The loader and dumper
978 use it to scramble protected strings.
982 Create a new database
984 my $kdbx = File::KDBX->new;
986 my $group = $kdbx->add_group(name => 'Passwords);
987 my $entry = $group->add_entry(
988 title => 'WayneCorp',
989 username => 'bwayne',
990 password => 'iambatman',
991 url => 'https://example.com/login'
993 $entry->add_auto_type_window_association('WayneCorp - Mozilla Firefox', '{PASSWORD}{ENTER}');
995 $kdbx->dump_file('mypasswords.kdbx', 'master password CHANGEME');
997 Read an existing database
999 my $kdbx = File::KDBX->load_file('mypasswords.kdbx', 'master password CHANGEME');
1000 $kdbx->unlock; # cause $entry->password below to be defined
1002 $kdbx->entries->each(sub {
1004 say 'Found password for: ', $entry->title;
1005 say ' Username: ', $entry->username;
1006 say ' Password: ', $entry->password;
1011 my @entries = $kdbx->entries(searching => 1)
1012 ->grep(title => 'WayneCorp')
1013 ->each; # return all matches
1015 The searching option limits results to only entries within groups with
1016 searching enabled. Other options are also available. See "entries".
1018 See "QUERY" for many more query examples.
1020 Search for entries by auto-type window association
1022 my $window_title = 'WayneCorp - Mozilla Firefox';
1024 my $entries = $kdbx->entries(auto_type => 1)
1026 my ($ata) = grep { $_->{window} =~ /\Q$window_title\E/i } @{$_->auto_type_associations};
1027 return [$_, $ata->{keystroke_sequence}] if $ata;
1030 my ($entry, $keys) = @$_;
1031 say 'Entry title: ', $entry->title, ', key sequence: ', $keys;
1036 Entry title: WayneCorp, key sequence: {PASSWORD}{ENTER}
1038 Remove entries from a database
1041 ->grep(notes => {'=~' => qr/too old/i})
1042 ->each(sub { $_->recycle });
1044 Recycle all entries with the string "too old" appearing in the Notes
1049 $kdbx->groups(algorithm => 'dfs')
1050 ->where(-true => 'is_empty')
1053 With the search/iteration algorithm set to "dfs", groups will be
1054 ordered deepest first and the root group will be last. This allows
1055 removing groups that only contain empty groups.
1057 This can also be done with one call to "remove_empty_groups".
1061 One of the biggest threats to your database security is how easily the
1062 encryption key can be brute-forced. Strong brute-force protection
1065 * Using unguessable passwords, passphrases and key files.
1067 * Using a brute-force resistent key derivation function.
1069 The first factor is up to you. This module does not enforce strong
1070 master keys. It is up to you to pick or generate strong keys.
1072 The KDBX format allows for the key derivation function to be tuned. The
1073 idea is that you want each single brute-foce attempt to be expensive
1074 (in terms of time, CPU usage or memory usage), so that making a lot of
1075 attempts (which would be required if you have a strong master key) gets
1078 How expensive you want to make each attempt is up to you and can depend
1081 This and other KDBX-related security issues are covered here more in
1082 depth: https://keepass.info/help/base/security.html
1084 Here are other security risks you should be thinking about:
1088 This distribution uses the excellent CryptX and Crypt::Argon2 packages
1089 to handle all crypto-related functions. As such, a lot of the security
1090 depends on the quality of these dependencies. Fortunately these modules
1091 are maintained and appear to have good track records.
1093 The KDBX format has evolved over time to incorporate improved security
1094 practices and cryptographic functions. This package uses the following
1095 functions for authentication, hashing, encryption and random number
1102 * Argon2d & Argon2id
1112 * Salsa20 & ChaCha20
1116 At the time of this writing, I am not aware of any successful attacks
1117 against any of these functions. These are among the most-analyzed and
1118 widely-adopted crypto functions available.
1120 The KDBX format allows the body cipher and key derivation function to
1121 be configured. If a flaw is discovered in one of these functions, you
1122 can hopefully just switch to a better function without needing to
1123 update this software. A later software release may phase out the use of
1124 any functions which are no longer secure.
1128 It is not a good idea to keep secret information unencrypted in system
1129 memory for longer than is needed. The address space of your program can
1130 generally be read by a user with elevated privileges on the system. If
1131 your system is memory-constrained or goes into a hibernation mode, the
1132 contents of your address space could be written to a disk where it
1133 might be persisted for long time.
1135 There might be system-level things you can do to reduce your risk, like
1136 using swap encryption and limiting system access to your program's
1137 address space while your program is running.
1139 File::KDBX helps minimize (but not eliminate) risk by keeping secrets
1140 encrypted in memory until accessed and zeroing out memory that holds
1141 secrets after they're no longer needed, but it's not a silver bullet.
1143 For one thing, the encryption key is stored in the same address space.
1144 If core is dumped, the encryption key is available to be found out. But
1145 at least there is the chance that the encryption key and the encrypted
1146 secrets won't both be paged out together while memory-constrained.
1148 Another problem is that some perls (somewhat notoriously) copy around
1149 memory behind the scenes willy nilly, and it's difficult know when perl
1150 makes a copy of a secret in order to be able to zero it out later. It
1151 might be impossible. The good news is that perls with SvPV
1152 copy-on-write (enabled by default beginning with perl 5.20) are much
1153 better in this regard. With COW, it's mostly possible to know what
1154 operations will cause perl to copy the memory of a scalar string, and
1155 the number of copies will be significantly reduced. There is a unit
1156 test named t/memory-protection.t in this distribution that can be run
1157 on POSIX systems to determine how well File::KDBX memory protection is
1160 Memory protection also depends on how your application handles secrets.
1161 If your app code is handling scalar strings with secret information,
1162 it's up to you to make sure its memory is zeroed out when no longer
1163 needed. "erase" in File::KDBX::Util et al. provide some tools to help
1164 accomplish this. Or if you're not too concerned about the risks memory
1165 protection is meant to mitigate, then maybe don't worry about it. The
1166 security policy of File::KDBX is to try hard to keep secrets protected
1167 while in memory so that your app might claim a high level of security,
1168 in case you care about that.
1170 There are some memory protection strategies that File::KDBX does NOT
1171 use today but could in the future:
1173 Many systems allow programs to mark unswappable pages. Secret
1174 information should ideally be stored in such pages. You could
1175 potentially use mlockall(2) (or equivalent for your system) in your own
1176 application to prevent the entire address space from being swapped.
1178 Some systems provide special syscalls for storing secrets in memory
1179 while keeping the encryption key outside of the program's address
1180 space, like CryptProtectMemory for Windows. This could be a good
1181 option, though unfortunately not portable.
1185 To find things in a KDBX database, you should use a filtered iterator.
1186 If you have an iterator, such as returned by "entries", "groups" or
1187 even "objects" you can filter it using "where" in File::KDBX::Iterator.
1189 my $filtered_entries = $kdbx->entries->where(\&query);
1191 A \&query is just a subroutine that you can either write yourself or
1192 have generated for you from either a "Simple Expression" or
1193 "Declarative Syntax". It's easier to have your query generated, so I'll
1198 A simple expression is mostly compatible with the KeePass 2
1199 implementation described here
1200 <https://keepass.info/help/base/search.html#mode_se>.
1202 An expression is a string with one or more space-separated terms. Terms
1203 with spaces can be enclosed in double quotes. Terms are negated if they
1204 are prefixed with a minus sign. A record must match every term on at
1205 least one of the given fields.
1207 So a simple expression is something like what you might type into a
1208 search engine. You can generate a simple expression query using
1209 "simple_expression_query" in File::KDBX::Util or by passing the simple
1210 expression as a scalar reference to where.
1212 To search for all entries in a database with the word "canyon"
1213 appearing anywhere in the title:
1215 my $entries = $kdbx->entries->where(\'canyon', qw[title]);
1217 Notice the first argument is a scalarref. This disambiguates a simple
1218 expression from other types of queries covered below.
1220 As mentioned, a simple expression can have multiple terms. This simple
1221 expression query matches any entry that has the words "red" and
1222 "canyon" anywhere in the title:
1224 my $entries = $kdbx->entries->where(\'red canyon', qw[title]);
1226 Each term in the simple expression must be found for an entry to match.
1228 To search for entries with "red" in the title but not "canyon", just
1229 prepend "canyon" with a minus sign:
1231 my $entries = $kdbx->entries->where(\'red -canyon', qw[title]);
1233 To search over multiple fields simultaneously, just list them all. To
1234 search for entries with "grocery" (but not "Foodland") in the title or
1237 my $entries = $kdbx->entries->where(\'grocery -Foodland', qw[title notes]);
1239 The default operator is a case-insensitive regexp match, which is fine
1240 for searching text loosely. You can use just about any binary
1241 comparison operator that perl supports. To specify an operator, list it
1242 after the simple expression. For example, to search for any entry that
1243 has been used at least five times:
1245 my $entries = $kdbx->entries->where(\5, '>=', qw[usage_count]);
1247 It helps to read it right-to-left, like "usage_count is greater than or
1250 If you find the disambiguating structures to be distracting or
1251 confusing, you can also the "simple_expression_query" in
1252 File::KDBX::Util function as a more intuitive alternative. The
1253 following example is equivalent to the previous:
1255 my $entries = $kdbx->entries->where(simple_expression_query(5, '>=', qw[usage_count]));
1259 Structuring a declarative query is similar to "WHERE CLAUSES" in
1260 SQL::Abstract, but you don't have to be familiar with that module. Just
1261 learn by examples here.
1263 To search for all entries in a database titled "My Bank":
1265 my $entries = $kdbx->entries->where({ title => 'My Bank' });
1267 The query here is { title => 'My Bank' }. A hashref can contain
1268 key-value pairs where the key is an attribute of the thing being
1269 searched for (in this case an entry) and the value is what you want the
1270 thing's attribute to be to consider it a match. In this case, the
1271 attribute we're using as our match criteria is "title" in
1272 File::KDBX::Entry, a text field. If an entry has its title attribute
1273 equal to "My Bank", it's a match.
1275 A hashref can contain multiple attributes. The search candidate will be
1276 a match if all of the specified attributes are equal to their
1277 respective values. For example, to search for all entries with a
1278 particular URL AND username:
1280 my $entries = $kdbx->entries->where({
1281 url => 'https://example.com',
1285 To search for entries matching any criteria, just change the hashref to
1286 an arrayref. To search for entries with a particular URL OR username:
1288 my $entries = $kdbx->entries->where([ # <-- Notice the square bracket
1289 url => 'https://example.com',
1293 You can use different operators to test different types of attributes.
1294 The "icon_id" in File::KDBX::Entry attribute is a number, so we should
1295 use a number comparison operator. To find entries using the smartphone
1298 my $entries = $kdbx->entries->where({
1299 icon_id => { '==', ICON_SMARTPHONE },
1302 Note: "ICON_SMARTPHONE" in File::KDBX::Constants is just a constant
1303 from File::KDBX::Constants. It isn't special to this example or to
1304 queries generally. We could have just used a literal number.
1306 The important thing to notice here is how we wrapped the condition in
1307 another arrayref with a single key-value pair where the key is the name
1308 of an operator and the value is the thing to match against. The
1309 supported operators are:
1313 * ne - String not equal
1315 * lt - String less than
1317 * gt - String greater than
1319 * le - String less than or equal
1321 * ge - String greater than or equal
1325 * != - Number not equal
1327 * < - Number less than
1329 * > - Number greater than
1331 * <= - Number less than or equal
1333 * >= - Number less than or equal
1335 * =~ - String match regular expression
1337 * !~ - String does not match regular expression
1343 Other special operators:
1345 * -true - Boolean true
1347 * -false - Boolean false
1349 * -not - Boolean false (alias for -false)
1351 * -defined - Is defined
1353 * -undef - Is not defined
1357 * -nonempty - Is not empty
1361 * -and - Logical and
1363 Let's see another example using an explicit operator. To find all
1364 groups except one in particular (identified by its "uuid" in
1365 File::KDBX::Group), we can use the ne (string not equal) operator:
1367 my $groups = $kdbx->groups->where(
1369 'ne' => uuid('596f7520-6172-6520-7370-656369616c2e'),
1373 Note: "uuid" in File::KDBX::Util is a little utility function to
1374 convert a UUID in its pretty form into bytes. This utility function
1375 isn't special to this example or to queries generally. It could have
1376 been written with a literal such as "\x59\x6f\x75\x20\x61...", but
1377 that's harder to read.
1379 Notice we searched for groups this time. Finding groups works exactly
1380 the same as it does for entries.
1382 Notice also that we didn't wrap the query in hashref curly-braces or
1383 arrayref square-braces. Those are optional. By default it will only
1384 match ALL attributes (as if there were curly-braces).
1386 Testing the truthiness of an attribute is a little bit different
1387 because it isn't a binary operation. To find all entries with the
1388 password quality check disabled:
1390 my $entries = $kdbx->entries->where('!' => 'quality_check');
1392 This time the string after the operator is the attribute name rather
1393 than a value to compare the attribute against. To test that a boolean
1394 value is true, use the !! operator (or -true if !! seems a little too
1395 weird for your taste):
1397 my $entries = $kdbx->entries->where('!!' => 'quality_check');
1398 my $entries = $kdbx->entries->where(-true => 'quality_check'); # same thing
1400 Yes, there is also a -false and a -not if you prefer one of those over
1401 !. -false and -not (along with -true) are also special in that you can
1402 use them to invert the logic of a subquery. These are logically
1405 my $entries = $kdbx->entries->where(-not => { title => 'My Bank' });
1406 my $entries = $kdbx->entries->where(title => { 'ne' => 'My Bank' });
1408 These special operators become more useful when combined with two more
1409 special operators: -and and -or. With these, it is possible to
1410 construct more interesting queries with groups of logic. For example:
1412 my $entries = $kdbx->entries->where({
1413 title => { '=~', qr/bank/ },
1416 notes => { '=~', qr/business/ },
1417 icon_id => { '==', ICON_TRASHCAN_FULL },
1422 In English, find entries where the word "bank" appears anywhere in the
1423 title but also do not have either the word "business" in the notes or
1424 are using the full trashcan icon.
1428 Lastly, as mentioned at the top, you can ignore all this and write your
1429 own subroutine. Your subroutine will be called once for each object
1430 being searched over. The subroutine should match the candidate against
1431 whatever criteria you want and return true if it matches or false to
1432 skip. To do this, just pass your subroutine coderef to where.
1434 To review the different types of queries, these are all equivalent to
1435 find all entries in the database titled "My Bank":
1437 my $entries = $kdbx->entries->where(\'"My Bank"', 'eq', qw[title]); # simple expression
1438 my $entries = $kdbx->entries->where(title => 'My Bank'); # declarative syntax
1439 my $entries = $kdbx->entries->where(sub { $_->title eq 'My Bank' }); # subroutine query
1441 This is a trivial example, but of course your subroutine can be
1442 arbitrarily complex.
1444 All of these query mechanisms described in this section are just tools,
1445 each with its own set of limitations. If the tools are getting in your
1446 way, you can of course iterate over the contents of a database and
1447 implement your own query logic, like this:
1449 my $entries = $kdbx->entries;
1450 while (my $entry = $entries->next) {
1451 if (wanted($entry)) {
1452 do_something($entry);
1461 Iterators are the built-in way to navigate or walk the database tree.
1462 You get an iterator from "entries", "groups" and "objects". You can
1463 specify the search algorithm to iterate over objects in different
1464 orders using the algorithm option, which can be one of these constants:
1466 * ITERATION_IDS - Iterative deepening search (default)
1468 * ITERATION_DFS - Depth-first search
1470 * ITERATION_BFS - Breadth-first search
1472 When iterating over objects generically, groups always precede their
1473 direct entries (if any). When the history option is used, current
1474 entries always precede historical entries.
1476 If you have a database tree like this:
1487 * IDS order of groups is: Root, Group1, Group2, Group3
1489 * IDS order of entries is: EntryA, EntryB, EntryC
1491 * IDS order of objects is: Root, Group1, EntryA, Group2, EntryB,
1494 * DFS order of groups is: Group2, Group1, Group3, Root
1496 * DFS order of entries is: EntryB, EntryA, EntryC
1498 * DFS order of objects is: Group2, EntryB, Group1, EntryA, Group3,
1501 * BFS order of groups is: Root, Group1, Group3, Group2
1503 * BFS order of entries is: EntryA, EntryC, EntryB
1505 * BFS order of objects is: Root, Group1, EntryA, Group3, EntryC,
1510 TODO - This is a planned feature, not yet implemented.
1514 Errors in this package are constructed as File::KDBX::Error objects and
1515 propagated using perl's built-in mechanisms. Fatal errors are
1516 propagated using "die LIST" in perlfunc and non-fatal errors (a.k.a.
1517 warnings) are propagated using "warn LIST" in perlfunc while adhering
1518 to perl's warnings system. If you're already familiar with these
1519 mechanisms, you can skip this section.
1521 You can catch fatal errors using "eval BLOCK" in perlfunc (or something
1522 like Try::Tiny) and non-fatal errors using $SIG{__WARN__} (see "%SIG"
1523 in perlvar). Examples:
1525 use File::KDBX::Error qw(error);
1527 my $key = ''; # uh oh
1529 $kdbx->load_file('whatever.kdbx', $key);
1531 if (my $error = error($@)) {
1532 handle_missing_key($error) if $error->type eq 'key.missing';
1539 $kdbx->load_file('whatever.kdbx', $key);
1545 Catching non-fatal errors:
1548 local $SIG{__WARN__} = sub { push @warnings, $_[0] };
1550 $kdbx->load_file('whatever.kdbx', $key);
1552 handle_warnings(@warnings) if @warnings;
1554 By default perl prints warnings to STDERR if you don't catch them. If
1555 you don't want to catch them and also don't want them printed to
1556 STDERR, you can suppress them lexically (perl v5.28 or higher
1560 no warnings 'File::KDBX';
1567 local $File::KDBX::WARNINGS = 0;
1571 or globally in your program:
1573 $File::KDBX::WARNINGS = 0;
1575 You cannot suppress fatal errors, and if you don't catch them your
1580 This software will alter its behavior depending on the value of certain
1581 environment variables:
1583 * PERL_FILE_KDBX_XS - Do not use File::KDBX::XS if false (default:
1586 * PERL_ONLY - Do not use File::KDBX::XS if true (default: false)
1588 * NO_FORK - Do not fork if true (default: false)
1592 * KeePass Password Safe <https://keepass.info/> - The original
1595 * KeePassXC <https://keepassxc.org/> - Cross-Platform Password
1596 Manager written in C++
1598 * File::KeePass has overlapping functionality. It's good but has a
1599 backlog of some pretty critical bugs and lacks support for newer KDBX
1604 Please report any bugs or feature requests on the bugtracker website
1605 https://github.com/chazmcgarvey/File-KDBX/issues
1607 When submitting a bug or request, please include a test-file or a patch
1608 to an existing test-file that illustrates the bug or desired feature.
1612 Charles McGarvey <ccm@cpan.org>
1614 COPYRIGHT AND LICENSE
1616 This software is copyright (c) 2022 by Charles McGarvey.
1618 This is free software; you can redistribute it and/or modify it under
1619 the same terms as the Perl 5 programming language system itself.