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', 'masterpw changeme');
29 # Load the database from the filesystem into a new database instance
30 my $kdbx2 = File::KDBX->load_file('passwords.kdbx', 'masterpw changeme');
32 # Iterate over database entries, print entry titles
33 $kdbx2->entries->each(sub($entry, @) {
34 say 'Entry: ', $entry->title;
37 See "RECIPES" for more examples.
41 File::KDBX provides everything you need to work with KDBX databases. A
42 KDBX database is a hierarchical object database which is commonly used
43 to store secret information securely. It was developed for the KeePass
44 password safe. See "Introduction to KDBX" for more information about
47 This module lets you query entries, create new entries, delete entries,
48 modify entries and more. The distribution also includes various parsers
49 and generators for serializing and persisting databases.
51 The design of this software was influenced by the KeePassXC
52 <https://github.com/keepassxreboot/keepassxc> implementation of KeePass
53 as well as the File::KeePass module. File::KeePass is an alternative
54 module that works well in most cases but has a small backlog of bugs
55 and security issues and also does not work with newer KDBX version 4
56 files. If you're coming here from the File::KeePass world, you might be
57 interested in File::KeePass::KDBX that is a drop-in replacement for
58 File::KeePass that uses File::KDBX for storage.
60 This software is a pre-1.0 release. The interface should be considered
61 pretty stable, but there might be minor changes up until a 1.0 release.
62 Breaking changes will be noted in the Changes file.
66 * ☑ Read and write KDBX version 3 - version 4.1
68 * ☑ Read and write KDB files (requires File::KeePass)
70 * ☑ Unicode character strings
72 * ☑ "Simple Expression" Searching
74 * ☑ Placeholders and field references
76 * ☑ One-time passwords
80 * ☑ "Memory Protection"
82 * ☑ Challenge-response key components, like YubiKey
84 * ☑ Variety of key file types: binary, hexed, hashed, XML v1 and v2
86 * ☑ Pluggable registration of different kinds of ciphers and key
89 * ☑ Built-in database maintenance functions
91 * ☑ Pretty fast, with XS optimizations available
93 * ☒ Database synchronization / merging (not yet)
97 A KDBX database consists of a tree of groups and entries, with a single
98 root group. Entries can contain zero or more key-value pairs of strings
99 and zero or more binaries (i.e. octet strings). Groups, entries,
100 strings and binaries: that's the KDBX vernacular. A small amount of
101 metadata (timestamps, etc.) is associated with each entry, group and
102 the database as a whole.
104 You can think of a KDBX database kind of like a file system, where
105 groups are directories, entries are files, and strings and binaries
106 make up a file's contents.
108 Databases are typically persisted as encrypted, compressed files. They
109 are usually accessed directly (i.e. not over a network). The primary
110 focus of this type of database is data security. It is ideal for
111 storing relatively small amounts of data (strings and binaries) that
112 must remain secret except to such individuals as have the correct
113 master key. Even if the database file were to be "leaked" to the public
114 Internet, it should be virtually impossible to crack with a strong key.
115 The KDBX format is most often used by password managers to store
116 passwords so that users can know a single strong password and not have
117 to reuse passwords across different websites. See "SECURITY" for an
118 overview of security considerations.
138 Hash of UUIDs for objects that have been deleted. This includes groups,
139 entries and even custom icons.
143 Bytes contained within the encrypted layer of a KDBX file. This is only
144 set when using File::KDBX::Loader::Raw.
148 A text string associated with the database stored unencrypted in the
149 file header. 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 in
186 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 an 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: value of "maintenance_history_days", 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 for you by default.
906 $key = $kdbx->key($key);
907 $key = $kdbx->key($primitive);
909 Get or set a File::KDBX::Key. This is the master key (e.g. a password
910 or a key file that can decrypt a database). You can also pass a
911 primitive castable to a Key. See "new" in File::KDBX::Key for an
912 explanation of what the primitive can be.
914 You generally don't need to call this directly because you can provide
915 the key directly to the loader or dumper when loading or dumping a KDBX
920 $key = $kdbx->composite_key($key);
921 $key = $kdbx->composite_key($primitive);
923 Construct a File::KDBX::Key::Composite from a Key or primitive. See
924 "new" in File::KDBX::Key for an explanation of what the primitive can
925 be. If the primitive does not represent a composite key, it will be
928 You generally don't need to call this directly. The loader and dumper
929 use it to transform a master key into a raw encryption key.
933 $kdf = $kdbx->kdf(%options);
934 $kdf = $kdbx->kdf(\%parameters, %options);
936 Get a File::KDBX::KDF (key derivation function).
940 * params - KDF parameters, same as \%parameters (default: value of
945 $cipher = $kdbx->cipher(key => $key);
946 $cipher = $kdbx->cipher(key => $key, iv => $iv, uuid => $uuid);
948 Get a File::KDBX::Cipher capable of encrypting and decrypting the body
951 A key is required. This should be a raw encryption key made up of a
952 fixed number of octets (depending on the cipher), not a File::KDBX::Key
955 If not passed, the UUID comes from $kdbx->headers->{cipher_id} and the
956 encryption IV comes from $kdbx->headers->{encryption_iv}.
958 You generally don't need to call this directly. The loader and dumper
959 use it to decrypt and encrypt KDBX files.
963 $cipher = $kdbx->random_stream;
964 $cipher = $kdbx->random_stream(id => $stream_id, key => $key);
966 Get a File::KDBX::Cipher::Stream for decrypting and encrypting
969 If not passed, the ID and encryption key comes from
970 $kdbx->headers->{inner_random_stream_id} and
971 $kdbx->headers->{inner_random_stream_key} (respectively) for KDBX3
972 files and from $kdbx->inner_headers->{inner_random_stream_key} and
973 $kdbx->inner_headers->{inner_random_stream_id} (respectively) for KDBX4
976 You generally don't need to call this directly. The loader and dumper
977 use it to scramble protected strings.
981 Create a new database
983 my $kdbx = File::KDBX->new;
985 my $group = $kdbx->add_group(name => 'Passwords);
986 my $entry = $group->add_entry(
987 title => 'WayneCorp',
988 username => 'bwayne',
989 password => 'iambatman',
990 url => 'https://example.com/login'
992 $entry->add_auto_type_window_association('WayneCorp - Mozilla Firefox', '{PASSWORD}{ENTER}');
994 $kdbx->dump_file('mypasswords.kdbx', 'master password CHANGEME');
996 Read an existing database
998 my $kdbx = File::KDBX->load_file('mypasswords.kdbx', 'master password CHANGEME');
999 $kdbx->unlock; # cause $entry->password below to be defined
1001 $kdbx->entries->each(sub($entry, @) {
1002 say 'Found password for: ', $entry->title;
1003 say ' Username: ', $entry->username;
1004 say ' Password: ', $entry->password;
1009 my @entries = $kdbx->entries(searching => 1)
1010 ->grep(title => 'WayneCorp')
1011 ->each; # return all matches
1013 The searching option limits results to only entries within groups with
1014 searching enabled. Other options are also available. See "entries".
1016 See "QUERY" for many more query examples.
1018 Search for entries by auto-type window association
1020 my $window_title = 'WayneCorp - Mozilla Firefox';
1022 my $entries = $kdbx->entries(auto_type => 1)
1024 my ($ata) = grep { $_->{window} =~ /\Q$window_title\E/i } @{$_->auto_type_associations};
1025 return [$_, $ata->{keystroke_sequence}] if $ata;
1028 my ($entry, $keys) = @$_;
1029 say 'Entry title: ', $entry->title, ', key sequence: ', $keys;
1034 Entry title: WayneCorp, key sequence: {PASSWORD}{ENTER}
1036 Remove entries from a database
1039 ->grep(notes => {'=~' => qr/too old/i})
1040 ->each(sub { $_->recycle });
1042 Recycle all entries with the string "too old" appearing in the Notes
1047 $kdbx->groups(algorithm => 'dfs')
1048 ->where(-true => 'is_empty')
1051 With the search/iteration algorithm set to "dfs", groups will be
1052 ordered deepest first and the root group will be last. This allows
1053 removing groups that only contain empty groups.
1055 This can also be done with one call to "remove_empty_groups".
1059 One of the biggest threats to your database security is how easily the
1060 encryption key can be brute-forced. Strong brute-force protection
1063 * Using unguessable passwords, passphrases and key files.
1065 * Using a brute-force resistent key derivation function.
1067 The first factor is up to you. This module does not enforce strong
1068 master keys. It is up to you to pick or generate strong keys.
1070 The KDBX format allows for the key derivation function to be tuned. The
1071 idea is that you want each single brute-force attempt to be expensive
1072 (in terms of time, CPU usage or memory usage), so that making a lot of
1073 attempts (which would be required if you have a strong master key) gets
1076 How expensive you want to make each attempt is up to you and can depend
1079 This and other KDBX-related security issues are covered here more in
1080 depth: https://keepass.info/help/base/security.html
1082 Here are other security risks you should be thinking about:
1086 This distribution uses the excellent CryptX and Crypt::Argon2 packages
1087 to handle all crypto-related functions. As such, a lot of the security
1088 depends on the quality of these dependencies. Fortunately these modules
1089 are maintained and appear to have good track records.
1091 The KDBX format has evolved over time to incorporate improved security
1092 practices and cryptographic functions. This package uses the following
1093 functions for authentication, hashing, encryption and random number
1100 * Argon2d & Argon2id
1110 * Salsa20 & ChaCha20
1114 At the time of this writing, I am not aware of any successful attacks
1115 against any of these functions. These are among the most-analyzed and
1116 widely-adopted crypto functions available.
1118 The KDBX format allows the body cipher and key derivation function to
1119 be configured. If a flaw is discovered in one of these functions, you
1120 can hopefully just switch to a better function without needing to
1121 update this software. A later software release may phase out the use of
1122 any functions which are no longer secure.
1126 It is not a good idea to keep secret information unencrypted in system
1127 memory for longer than is needed. The address space of your program can
1128 generally be read by a user with elevated privileges on the system. If
1129 your system is memory-constrained or goes into a hibernation mode, the
1130 contents of your address space could be written to a disk where it
1131 might be persisted for long time.
1133 There might be system-level things you can do to reduce your risk, like
1134 using swap encryption and limiting system access to your program's
1135 address space while your program is running.
1137 File::KDBX helps minimize (but not eliminate) risk by keeping secrets
1138 encrypted in memory until accessed and zeroing out memory that holds
1139 secrets after they're no longer needed, but it's not a silver bullet.
1141 For one thing, the encryption key is stored in the same address space.
1142 If core is dumped, the encryption key is available to be found out. But
1143 at least there is the chance that the encryption key and the encrypted
1144 secrets won't both be paged out together while memory-constrained.
1146 Another problem is that some perls (somewhat notoriously) copy around
1147 memory behind the scenes willy nilly, and it's difficult know when perl
1148 makes a copy of a secret in order to be able to zero it out later. It
1149 might be impossible. The good news is that perls with SvPV
1150 copy-on-write (enabled by default beginning with perl 5.20) are much
1151 better in this regard. With COW, it's mostly possible to know what
1152 operations will cause perl to copy the memory of a scalar string, and
1153 the number of copies will be significantly reduced. There is a unit
1154 test named t/memory-protection.t in this distribution that can be run
1155 on POSIX systems to determine how well File::KDBX memory protection is
1158 Memory protection also depends on how your application handles secrets.
1159 If your app code is handling scalar strings with secret information,
1160 it's up to you to make sure its memory is zeroed out when no longer
1161 needed. "erase" in File::KDBX::Util et al. provide some tools to help
1162 accomplish this. Or if you're not too concerned about the risks memory
1163 protection is meant to mitigate, then maybe don't worry about it. The
1164 security policy of File::KDBX is to try hard to keep secrets protected
1165 while in memory so that your app might claim a high level of security,
1166 in case you care about that.
1168 There are some memory protection strategies that File::KDBX does NOT
1169 use today but could in the future:
1171 Many systems allow programs to mark unswappable pages. Secret
1172 information should ideally be stored in such pages. You could
1173 potentially use mlockall(2) (or equivalent for your system) in your own
1174 application to prevent the entire address space from being swapped.
1176 Some systems provide special syscalls for storing secrets in memory
1177 while keeping the encryption key outside of the program's address
1178 space, like CryptProtectMemory for Windows. This could be a good
1179 option, though unfortunately not portable.
1183 To find things in a KDBX database, you should use a filtered iterator.
1184 If you have an iterator, such as returned by "entries", "groups" or
1185 even "objects" you can filter it using "where" in File::KDBX::Iterator.
1187 my $filtered_entries = $kdbx->entries->where(\&query);
1189 A \&query is just a subroutine that you can either write yourself or
1190 have generated for you from either a "Simple Expression" or
1191 "Declarative Syntax". It's easier to have your query generated, so I'll
1196 A simple expression is mostly compatible with the KeePass 2
1197 implementation described here
1198 <https://keepass.info/help/base/search.html#mode_se>.
1200 An expression is a string with one or more space-separated terms. Terms
1201 with spaces can be enclosed in double quotes. Terms are negated if they
1202 are prefixed with a minus sign. A record must match every term on at
1203 least one of the given fields.
1205 So a simple expression is something like what you might type into a
1206 search engine. You can generate a simple expression query using
1207 "simple_expression_query" in File::KDBX::Util or by passing the simple
1208 expression as a scalar reference to where.
1210 To search for all entries in a database with the word "canyon"
1211 appearing anywhere in the title:
1213 my $entries = $kdbx->entries->where(\'canyon', qw[title]);
1215 Notice the first argument is a scalarref. This disambiguates a simple
1216 expression from other types of queries covered below.
1218 As mentioned, a simple expression can have multiple terms. This simple
1219 expression query matches any entry that has the words "red" and
1220 "canyon" anywhere in the title:
1222 my $entries = $kdbx->entries->where(\'red canyon', qw[title]);
1224 Each term in the simple expression must be found for an entry to match.
1226 To search for entries with "red" in the title but not "canyon", just
1227 prepend "canyon" with a minus sign:
1229 my $entries = $kdbx->entries->where(\'red -canyon', qw[title]);
1231 To search over multiple fields simultaneously, just list them all. To
1232 search for entries with "grocery" (but not "Foodland") in the title or
1235 my $entries = $kdbx->entries->where(\'grocery -Foodland', qw[title notes]);
1237 The default operator is a case-insensitive regexp match, which is fine
1238 for searching text loosely. You can use just about any binary
1239 comparison operator that perl supports. To specify an operator, list it
1240 after the simple expression. For example, to search for any entry that
1241 has been used at least five times:
1243 my $entries = $kdbx->entries->where(\5, '>=', qw[usage_count]);
1245 It helps to read it right-to-left, like "usage_count is greater than or
1248 If you find the disambiguating structures to be distracting or
1249 confusing, you can also use the "simple_expression_query" in
1250 File::KDBX::Util function as a more intuitive alternative. The
1251 following example is equivalent to the previous:
1253 my $entries = $kdbx->entries->where(simple_expression_query(5, '>=', qw[usage_count]));
1257 Structuring a declarative query is similar to "WHERE CLAUSES" in
1258 SQL::Abstract, but you don't have to be familiar with that module. Just
1259 learn by examples here.
1261 To search for all entries in a database titled "My Bank":
1263 my $entries = $kdbx->entries->where({ title => 'My Bank' });
1265 The query here is { title => 'My Bank' }. A hashref can contain
1266 key-value pairs where the key is an attribute of the thing being
1267 searched for (in this case an entry) and the value is what you want the
1268 thing's attribute to be to consider it a match. In this case, the
1269 attribute we're using as our match criteria is "title" in
1270 File::KDBX::Entry, a text field. If an entry has its title attribute
1271 equal to "My Bank", it's a match.
1273 A hashref can contain multiple attributes. The search candidate will be
1274 a match if all of the specified attributes are equal to their
1275 respective values. For example, to search for all entries with a
1276 particular URL AND username:
1278 my $entries = $kdbx->entries->where({
1279 url => 'https://example.com',
1283 To search for entries matching any criteria, just change the hashref to
1284 an arrayref. To search for entries with a particular URL OR username:
1286 my $entries = $kdbx->entries->where([ # <-- Notice the square bracket
1287 url => 'https://example.com',
1291 You can use different operators to test different types of attributes.
1292 The "icon_id" in File::KDBX::Entry attribute is a number, so we should
1293 use a number comparison operator. To find entries using the smartphone
1296 my $entries = $kdbx->entries->where({
1297 icon_id => { '==', ICON_SMARTPHONE },
1300 Note: "ICON_SMARTPHONE" in File::KDBX::Constants is just a constant
1301 from File::KDBX::Constants. It isn't special to this example or to
1302 queries generally. We could have just used a literal number.
1304 The important thing to notice here is how we wrapped the condition in
1305 another hashref with a single key-value pair where the key is the name
1306 of an operator and the value is the thing to match against. The
1307 supported operators are:
1311 * ne - String not equal
1313 * lt - String less than
1315 * gt - String greater than
1317 * le - String less than or equal
1319 * ge - String greater than or equal
1323 * != - Number not equal
1325 * < - Number less than
1327 * > - Number greater than
1329 * <= - Number less than or equal
1331 * >= - Number less than or equal
1333 * =~ - String match regular expression
1335 * !~ - String does not match regular expression
1341 Other special operators:
1343 * -true - Boolean true
1345 * -false - Boolean false
1347 * -not - Boolean false (alias for -false)
1349 * -defined - Is defined
1351 * -undef - Is not defined
1355 * -nonempty - Is not empty
1359 * -and - Logical and
1361 Let's see another example using an explicit operator. To find all
1362 groups except one in particular (identified by its "uuid" in
1363 File::KDBX::Group), we can use the ne (string not equal) operator:
1365 my $groups = $kdbx->groups->where(
1367 'ne' => uuid('596f7520-6172-6520-7370-656369616c2e'),
1371 Note: "uuid" in File::KDBX::Util is a little utility function to
1372 convert a UUID in its pretty form into bytes. This utility function
1373 isn't special to this example or to queries generally. It could have
1374 been written with a literal such as "\x59\x6f\x75\x20\x61...", but
1375 that's harder to read.
1377 Notice we searched for groups this time. Finding groups works exactly
1378 the same as it does for entries.
1380 Notice also that we didn't wrap the query in hashref curly-braces or
1381 arrayref square-braces. Those are optional. By default it will only
1382 match ALL attributes (as if there were curly-braces).
1384 Testing the truthiness of an attribute is a little bit different
1385 because it isn't a binary operation. To find all entries with the
1386 password quality check disabled:
1388 my $entries = $kdbx->entries->where('!' => 'quality_check');
1390 This time the string after the operator is the attribute name rather
1391 than a value to compare the attribute against. To test that a boolean
1392 value is true, use the !! operator (or -true if !! seems a little too
1393 weird for your taste):
1395 my $entries = $kdbx->entries->where('!!' => 'quality_check');
1396 my $entries = $kdbx->entries->where(-true => 'quality_check'); # same thing
1398 Yes, there is also a -false and a -not if you prefer one of those over
1399 !. -false and -not (along with -true) are also special in that you can
1400 use them to invert the logic of a subquery. These are logically
1403 my $entries = $kdbx->entries->where(-not => { title => 'My Bank' });
1404 my $entries = $kdbx->entries->where(title => { 'ne' => 'My Bank' });
1406 These special operators become more useful when combined with two more
1407 special operators: -and and -or. With these, it is possible to
1408 construct more interesting queries with groups of logic. For example:
1410 my $entries = $kdbx->entries->where({
1411 title => { '=~', qr/bank/ },
1414 notes => { '=~', qr/business/ },
1415 icon_id => { '==', ICON_TRASHCAN_FULL },
1420 In English, find entries where the word "bank" appears anywhere in the
1421 title but also do not have either the word "business" in the notes or
1422 are using the full trashcan icon.
1426 Lastly, as mentioned at the top, you can ignore all this and write your
1427 own subroutine. Your subroutine will be called once for each object
1428 being searched over. The subroutine should match the candidate against
1429 whatever criteria you want and return true if it matches or false to
1430 skip. To do this, just pass your subroutine coderef to where.
1432 To review the different types of queries, these are all equivalent to
1433 find all entries in the database titled "My Bank":
1435 my $entries = $kdbx->entries->where(\'"My Bank"', 'eq', qw[title]); # simple expression
1436 my $entries = $kdbx->entries->where(title => 'My Bank'); # declarative syntax
1437 my $entries = $kdbx->entries->where(sub { $_->title eq 'My Bank' }); # subroutine query
1439 This is a trivial example, but of course your subroutine can be
1440 arbitrarily complex.
1442 All of these query mechanisms described in this section are just tools,
1443 each with its own set of limitations. If the tools are getting in your
1444 way, you can of course iterate over the contents of a database and
1445 implement your own query logic, like this:
1447 my $entries = $kdbx->entries;
1448 while (my $entry = $entries->next) {
1449 if (wanted($entry)) {
1450 do_something($entry);
1459 Iterators are the built-in way to navigate or walk the database tree.
1460 You get an iterator from "entries", "groups" and "objects". You can
1461 specify the search algorithm to iterate over objects in different
1462 orders using the algorithm option, which can be one of these constants:
1464 * ITERATION_IDS - Iterative deepening search (default)
1466 * ITERATION_DFS - Depth-first search
1468 * ITERATION_BFS - Breadth-first search
1470 When iterating over objects generically, groups always precede their
1471 direct entries (if any). When the history option is used, current
1472 entries always precede historical entries.
1474 If you have a database tree like this:
1485 * IDS order of groups is: Root, Group1, Group2, Group3
1487 * IDS order of entries is: EntryA, EntryB, EntryC
1489 * IDS order of objects is: Root, Group1, EntryA, Group2, EntryB,
1492 * DFS order of groups is: Group2, Group1, Group3, Root
1494 * DFS order of entries is: EntryB, EntryA, EntryC
1496 * DFS order of objects is: Group2, EntryB, Group1, EntryA, Group3,
1499 * BFS order of groups is: Root, Group1, Group3, Group2
1501 * BFS order of entries is: EntryA, EntryC, EntryB
1503 * BFS order of objects is: Root, Group1, EntryA, Group3, EntryC,
1508 TODO - This is a planned feature, not yet implemented.
1512 Errors in this package are constructed as File::KDBX::Error objects and
1513 propagated using perl's built-in mechanisms. Fatal errors are
1514 propagated using "die LIST" in perlfunc and non-fatal errors (a.k.a.
1515 warnings) are propagated using "warn LIST" in perlfunc while adhering
1516 to perl's warnings system. If you're already familiar with these
1517 mechanisms, you can skip this section.
1519 You can catch fatal errors using "eval BLOCK" in perlfunc (or something
1520 like Try::Tiny) and non-fatal errors using $SIG{__WARN__} (see "%SIG"
1521 in perlvar). Examples:
1523 use File::KDBX::Error qw(error);
1525 my $key = ''; # uh oh
1527 $kdbx->load_file('whatever.kdbx', $key);
1529 if (my $error = error($@)) {
1530 handle_missing_key($error) if $error->type eq 'key.missing';
1537 $kdbx->load_file('whatever.kdbx', $key);
1543 Catching non-fatal errors:
1546 local $SIG{__WARN__} = sub { push @warnings, $_[0] };
1548 $kdbx->load_file('whatever.kdbx', $key);
1550 handle_warnings(@warnings) if @warnings;
1552 By default perl prints warnings to STDERR if you don't catch them. If
1553 you don't want to catch them and also don't want them printed to
1554 STDERR, you can suppress them lexically (perl v5.28 or higher
1558 no warnings 'File::KDBX';
1565 local $File::KDBX::WARNINGS = 0;
1569 or globally in your program:
1571 $File::KDBX::WARNINGS = 0;
1573 You cannot suppress fatal errors, and if you don't catch them your
1578 This software will alter its behavior depending on the value of certain
1579 environment variables:
1581 * PERL_FILE_KDBX_XS - Do not use File::KDBX::XS if false (default:
1584 * PERL_ONLY - Do not use File::KDBX::XS if true (default: false)
1586 * NO_FORK - Do not fork if true (default: false)
1590 * KeePass Password Safe <https://keepass.info/> - The original
1593 * KeePassXC <https://keepassxc.org/> - Cross-Platform Password
1594 Manager written in C++
1596 * File::KeePass has overlapping functionality. It's good but has a
1597 backlog of some pretty critical bugs and lacks support for newer KDBX
1602 Please report any bugs or feature requests on the bugtracker website
1603 https://github.com/chazmcgarvey/File-KDBX/issues
1605 When submitting a bug or request, please include a test-file or a patch
1606 to an existing test-file that illustrates the bug or desired feature.
1610 Charles McGarvey <ccm@cpan.org>
1612 COPYRIGHT AND LICENSE
1614 This software is copyright (c) 2022 by Charles McGarvey.
1616 This is free software; you can redistribute it and/or modify it under
1617 the same terms as the Perl 5 programming language system itself.