3 File::KDBX - Encrypted database to store secret text and files
13 my $kdbx = File::KDBX->new;
15 my $group = $kdbx->add_group(
19 my $entry = $group->add_entry(
24 $kdbx->dump_file('passwords.kdbx', 'M@st3rP@ssw0rd!');
26 $kdbx = File::KDBX->load_file('passwords.kdbx', 'M@st3rP@ssw0rd!');
28 $kdbx->entries->each(sub {
30 say 'Entry: ', $entry->title;
33 See "RECIPES" for more examples.
37 File::KDBX provides everything you need to work with KDBX databases. A
38 KDBX database is a hierarchical object database which is commonly used
39 to store secret information securely. It was developed for the KeePass
40 password safe. See "Introduction to KDBX" for more information about
43 This module lets you query entries, create new entries, delete entries,
44 modify entries and more. The distribution also includes various parsers
45 and generators for serializing and persisting databases.
47 The design of this software was influenced by the KeePassXC
48 <https://github.com/keepassxreboot/keepassxc> implementation of KeePass
49 as well as the File::KeePass module. File::KeePass is an alternative
50 module that works well in most cases but has a small backlog of bugs
51 and security issues and also does not work with newer KDBX version 4
52 files. If you're coming here from the File::KeePass world, you might be
53 interested in File::KeePass::KDBX that is a drop-in replacement for
54 File::KeePass that uses File::KDBX for storage.
56 This software is a pre-1.0 release. The interface should be considered
57 pretty stable, but there might be minor changes up until a 1.0 release.
58 Breaking changes will be noted in the Changes file.
62 * ☑ Read and write KDBX version 3 - version 4.1
64 * ☑ Read and write KDB files (requires File::KeePass)
66 * ☑ Unicode character strings
68 * ☑ "Simple Expression" Searching
70 * ☑ Placeholders and field references
72 * ☑ One-time passwords
76 * ☑ "Memory Protection"
78 * ☑ Challenge-response key components, like YubiKey
80 * ☑ Variety of key file types: binary, hexed, hashed, XML v1 and v2
82 * ☑ Pluggable registration of different kinds of ciphers and key
85 * ☑ Built-in database maintenance functions
87 * ☑ Pretty fast, with XS optimizations available
89 * ☒ Database synchronization / merging (not yet)
93 A KDBX database consists of a tree of groups and entries, with a single
94 root group. Entries can contain zero or more key-value pairs of strings
95 and zero or more binaries (i.e. octet strings). Groups, entries,
96 strings and binaries: that's the KDBX vernacular. A small amount of
97 metadata (timestamps, etc.) is associated with each entry, group and
98 the database as a whole.
100 You can think of a KDBX database kind of like a file system, where
101 groups are directories, entries are files, and strings and binaries
102 make up a file's contents.
104 Databases are typically persisted as encrypted, compressed files. They
105 are usually accessed directly (i.e. not over a network). The primary
106 focus of this type of database is data security. It is ideal for
107 storing relatively small amounts of data (strings and binaries) that
108 must remain secret except to such individuals as have the correct
109 master key. Even if the database file were to be "leaked" to the public
110 Internet, it should be virtually impossible to crack with a strong key.
111 The KDBX format is most often used by password managers to store
112 passwords so that users can know a single strong password and not have
113 to reuse passwords across different websites. See "SECURITY" for an
114 overview of security considerations.
134 Hash of UUIDs for objects that have been deleted. This includes groups,
135 entries and even custom icons.
139 Bytes contained within the encrypted layer of a KDBX file. This is only
140 set when using File::KDBX::Loader::Raw.
144 A text string associated with the database. Often unset.
148 The UUID of a cipher used to encrypt the database when stored as a
151 See "File::KDBX::Cipher".
155 Configuration for whether or not and how the database gets compressed.
156 See ":compression" in File::KDBX::Constants.
160 The master seed is a string of 32 random bytes that is used as salt in
161 hashing the master key when loading and saving the database. If a
162 challenge-response key is used in the master key, the master seed is
165 The master seed should be changed each time the database is saved to
170 The transform seed is a string of 32 random bytes that is used in the
171 key derivation function, either as the salt or the key (depending on
174 The transform seed should be changed each time the database is saved to
179 The number of rounds or iterations used in the key derivation function.
180 Increasing this number makes loading and saving the database slower by
181 design in order to make dictionary and brute force attacks more costly.
185 The initialization vector used by the cipher.
187 The encryption IV should be changed each time the database is saved to
190 inner_random_stream_key
192 The encryption key (possibly including the IV, depending on the cipher)
193 used to encrypt the protected strings within the database.
197 A string of 32 random bytes written in the header and encrypted in the
198 body. If the bytes do not match when loading a file then the wrong
199 master key was used or the file is corrupt. Only KDBX 2 and KDBX 3
200 files use this. KDBX 4 files use an improved HMAC method to verify the
201 master key and data integrity of the header and entire file body.
203 inner_random_stream_id
205 A number indicating the cipher algorithm used to encrypt the protected
206 strings within the database, usually Salsa20 or ChaCha20. See
207 ":random_stream" in File::KDBX::Constants.
211 A hash/dict of key-value pairs used to configure the key derivation
212 function. This is the KDBX4+ way to configure the KDF, superceding
213 "transform_seed" and "transform_rounds".
217 The name of the software used to generate the KDBX file.
221 The header hash used to verify that the file header is not corrupt.
222 (KDBX 2 - KDBX 3.1, removed KDBX 4.0)
226 Name of the database.
228 database_name_changed
230 Timestamp indicating when the database name was last changed.
234 Description of the database
236 database_description_changed
238 Timestamp indicating when the database description was last changed.
242 When a new entry is created, the UserName string will be populated with
245 default_username_changed
247 Timestamp indicating when the default username was last changed.
251 A color associated with the database (in the form #ffffff where "f" is
252 a hexidecimal digit). Some agents use this to help users visually
253 distinguish between different databases.
257 Timestamp indicating when the master key was last changed.
259 master_key_change_rec
261 Number of days until the agent should prompt to recommend changing the
264 master_key_change_force
266 Number of days until the agent should prompt to force changing the
269 Note: This is purely advisory. It is up to the individual agent
270 software to actually enforce it. File::KDBX does NOT enforce it.
274 Array of custom icons that can be associated with groups and entries.
276 This list can be managed with the methods "add_custom_icon" and
277 "remove_custom_icon".
281 Boolean indicating whether removed groups and entries should go to a
282 recycle bin or be immediately deleted.
286 The UUID of a group used to store thrown-away groups and entries.
290 Timestamp indicating when the recycle bin group was last changed.
292 entry_templates_group
294 The UUID of a group containing template entries used when creating new
297 entry_templates_group_changed
299 Timestamp indicating when the entry templates group was last changed.
303 The UUID of the previously-selected group.
305 last_top_visible_group
307 The UUID of the group visible at the top of the list.
311 The maximum number of historical entries that should be kept for each
312 entry. Default is 10.
316 The maximum total size (in bytes) that each individual entry's history
317 is allowed to grow. Default is 6 MiB.
319 maintenance_history_days
321 The maximum age (in days) historical entries should be kept. Default it
326 Timestamp indicating when the database settings were last updated.
330 Alias of the "memory_protection" setting for the Title string.
334 Alias of the "memory_protection" setting for the UserName string.
338 Alias of the "memory_protection" setting for the Password string.
342 Alias of the "memory_protection" setting for the URL string.
346 Alias of the "memory_protection" setting for the Notes string.
352 $kdbx = File::KDBX->new(%attributes);
353 $kdbx = File::KDBX->new($kdbx); # copy constructor
355 Construct a new File::KDBX.
359 $kdbx = $kdbx->init(%attributes);
361 Initialize a File::KDBX with a set of attributes. Returns itself to
362 allow method chaining.
364 This is called by "new".
368 $kdbx = $kdbx->reset;
370 Set a File::KDBX to an empty state, ready to load a KDBX file or build
371 a new one. Returns itself to allow method chaining.
375 $kdbx_copy = $kdbx->clone;
376 $kdbx_copy = File::KDBX->new($kdbx);
378 Clone a File::KDBX. The clone will be an exact copy and completely
379 independent of the original.
389 $kdbx = KDBX::File->load(\$string, $key);
390 $kdbx = KDBX::File->load(*IO, $key);
391 $kdbx = KDBX::File->load($filepath, $key);
392 $kdbx->load(...); # also instance method
394 $kdbx = File::KDBX->load_string($string, $key);
395 $kdbx = File::KDBX->load_string(\$string, $key);
396 $kdbx->load_string(...); # also instance method
398 $kdbx = File::KDBX->load_file($filepath, $key);
399 $kdbx->load_file(...); # also instance method
401 $kdbx = File::KDBX->load_handle($fh, $key);
402 $kdbx = File::KDBX->load_handle(*IO, $key);
403 $kdbx->load_handle(...); # also instance method
405 Load a KDBX file from a string buffer, IO handle or file from a
408 File::KDBX::Loader does the heavy lifting.
418 $kdbx->dump(\$string, $key);
419 $kdbx->dump(*IO, $key);
420 $kdbx->dump($filepath, $key);
422 $kdbx->dump_string(\$string, $key);
423 \$string = $kdbx->dump_string($key);
425 $kdbx->dump_file($filepath, $key);
427 $kdbx->dump_handle($fh, $key);
428 $kdbx->dump_handle(*IO, $key);
430 Dump a KDBX file to a string buffer, IO handle or file in a filesystem.
432 File::KDBX::Dumper does the heavy lifting.
436 $string = $kdbx->user_agent_string;
438 Get a text string identifying the database client software.
442 \%settings = $kdbx->memory_protection
443 $kdbx->memory_protection(\%settings);
445 $bool = $kdbx->memory_protection($string_key);
446 $kdbx->memory_protection($string_key => $bool);
448 Get or set memory protection settings. This globally (for the whole
449 database) configures whether and which of the standard strings should
450 be memory-protected. The default setting is to memory-protect only
453 Memory protection can be toggled individually for each entry string,
454 and individual settings take precedence over these global settings.
458 $version = $kdbx->minimum_version;
460 Determine the minimum file version required to save a database
461 losslessly. Using certain databases features might increase this value.
462 For example, setting the KDF to Argon2 will increase the minimum
463 version to at least KDBX_VERSION_4_0 (i.e. 0x00040000) because Argon2
464 was introduced with KDBX4.
466 This method never returns less than KDBX_VERSION_3_1 (i.e. 0x00030001).
467 That file version is so ubiquitious and well-supported, there are
468 seldom reasons to dump in a lesser format nowadays.
470 WARNING: If you dump a database with a minimum version higher than the
471 current "version", the dumper will typically issue a warning and
472 automatically upgrade the database. This seems like the safest behavior
473 in order to avoid data loss, but lower versions have the benefit of
474 being compatible with more software. It is possible to prevent
475 auto-upgrades by explicitly telling the dumper which version to use,
476 but you do run the risk of data loss. A database will never be
477 automatically downgraded.
481 $group = $kdbx->root;
484 Get or set a database's root group. You don't necessarily need to
485 explicitly create or set a root group because it autovivifies when
486 adding entries and groups to the database.
488 Every database has only a single root group at a time. Some old KDB
489 files might have multiple root groups. When reading such files, a
490 single implicit root group is created to contain the actual root
491 groups. When writing to such a format, if the root group looks like it
492 was implicitly created then it won't be written and the resulting file
493 might have multiple root groups, as it was before loading. This allows
494 working with older files without changing their written internal
495 structure while still adhering to modern semantics while the database
498 The root group of a KDBX database contains all of the database's
499 entries and other groups. If you replace the root group, you are
500 essentially replacing the entire database contents with something else.
504 \@lineage = $kdbx->trace_lineage($group);
505 \@lineage = $kdbx->trace_lineage($group, $base_group);
506 \@lineage = $kdbx->trace_lineage($entry);
507 \@lineage = $kdbx->trace_lineage($entry, $base_group);
509 Get the direct line of ancestors from $base_group (default: the root
510 group) to a group or entry. The lineage includes the base group but not
511 the target group or entry. Returns undef if the target is not in the
516 $group = $kdbx->recycle_bin;
517 $kdbx->recycle_bin($group);
519 Get or set the recycle bin group. Returns undef if there is no recycle
520 bin and "recycle_bin_enabled" is false, otherwise the current recycle
521 bin or an autovivified recycle bin group is returned.
525 $group = $kdbx->entry_templates;
526 $kdbx->entry_templates($group);
528 Get or set the entry templates group. May return undef if unset.
532 $group = $kdbx->last_selected;
533 $kdbx->last_selected($group);
535 Get or set the last selected group. May return undef if unset.
539 $group = $kdbx->last_top_visible;
540 $kdbx->last_top_visible($group);
542 Get or set the last top visible group. May return undef if unset.
546 $kdbx->add_group($group);
547 $kdbx->add_group(%group_attributes, %options);
549 Add a group to a database. This is equivalent to identifying a parent
550 group and calling "add_group" in File::KDBX::Group on the parent group,
551 forwarding the arguments. Available options:
553 * group - Group object or group UUID to add the group to (default:
558 \&iterator = $kdbx->groups(%options);
559 \&iterator = $kdbx->groups($base_group, %options);
561 Get an File::KDBX::Iterator over groups within a database. Options:
563 * base - Only include groups within a base group (same as
564 $base_group) (default: "root")
566 * inclusive - Include the base group in the results (default: true)
568 * algorithm - Search algorithm, one of ids, bfs or dfs (default: ids)
572 $kdbx->add_entry($entry, %options);
573 $kdbx->add_entry(%entry_attributes, %options);
575 Add a entry to a database. This is equivalent to identifying a parent
576 group and calling "add_entry" in File::KDBX::Group on the parent group,
577 forwarding the arguments. Available options:
579 * group - Group object or group UUID to add the entry to (default:
584 \&iterator = $kdbx->entries(%options);
585 \&iterator = $kdbx->entries($base_group, %options);
587 Get an File::KDBX::Iterator over entries within a database. Supports
588 the same options as "groups", plus some new ones:
590 * auto_type - Only include entries with auto-type enabled (default:
593 * searching - Only include entries within groups with searching
594 enabled (default: false, include all)
596 * history - Also include historical entries (default: false, include
597 only current entries)
601 \&iterator = $kdbx->objects(%options);
602 \&iterator = $kdbx->objects($base_group, %options);
604 Get an File::KDBX::Iterator over objects within a database. Groups and
605 entries are considered objects, so this is essentially a combination of
606 "groups" and "entries". This won't often be useful, but it can be
607 convenient for maintenance tasks. This method takes the same options as
608 "groups" and "entries".
612 \%icon = $kdbx->custom_icon($uuid);
613 $kdbx->custom_icon($uuid => \%icon);
614 $kdbx->custom_icon(%icon);
615 $kdbx->custom_icon(uuid => $value, %icon);
617 Get or set custom icons.
621 $image_data = $kdbx->custom_icon_data($uuid);
623 Get a custom icon image data.
627 $uuid = $kdbx->add_custom_icon($image_data, %attributes);
628 $uuid = $kdbx->add_custom_icon(%attributes);
630 Add a custom icon and get its UUID. If not provided, a random UUID will
631 be generated. Possible attributes:
633 * uuid - Icon UUID (default: autogenerated)
635 * data - Image data (same as $image_data)
637 * name - Name of the icon (text, KDBX4.1+)
639 * last_modification_time - Just what it says (datetime, KDBX4.1+)
643 $kdbx->remove_custom_icon($uuid);
645 Remove a custom icon.
649 \%all_data = $kdbx->custom_data;
650 $kdbx->custom_data(\%all_data);
652 \%data = $kdbx->custom_data($key);
653 $kdbx->custom_data($key => \%data);
654 $kdbx->custom_data(%data);
655 $kdbx->custom_data(key => $value, %data);
657 Get and set custom data. Custom data is metadata associated with a
660 Each data item can have a few attributes associated with it.
662 * key - A unique text string identifier used to look up the data item
665 * value - A text string value (required)
667 * last_modification_time (optional, KDBX4.1+)
671 $value = $kdbx->custom_data_value($key);
673 Exactly the same as "custom_data" except returns just the custom data's
674 value rather than a structure of attributes. This is a shortcut for:
676 my $data = $kdbx->custom_data($key);
677 my $value = defined $data ? $data->{value} : undef;
681 \%all_data = $kdbx->public_custom_data;
682 $kdbx->public_custom_data(\%all_data);
684 $value = $kdbx->public_custom_data($key);
685 $kdbx->public_custom_data($key => $value);
687 Get and set public custom data. Public custom data is similar to custom
688 data but different in some important ways. Public custom data:
690 * can store strings, booleans and up to 64-bit integer values (custom
691 data can only store text values)
693 * is NOT encrypted within a KDBX file (hence the "public" part of the
696 * is a plain hash/dict of key-value pairs with no other associated
697 fields (like modification times)
701 $kdbx->add_deleted_object($uuid);
703 Add a UUID to the deleted objects list. This list is used to support
704 automatic database merging.
706 You typically do not need to call this yourself because the list will
707 be populated automatically as objects are removed.
709 remove_deleted_object
711 $kdbx->remove_deleted_object($uuid);
713 Remove a UUID from the deleted objects list. This list is used to
714 support automatic database merging.
716 You typically do not need to call this yourself because the list will
717 be maintained automatically as objects are added.
719 clear_deleted_objects
721 Remove all UUIDs from the deleted objects list. This list is used to
722 support automatic database merging, but if you don't need merging then
723 you can clear deleted objects to reduce the database file size.
727 $string = $kdbx->resolve_reference($reference);
728 $string = $kdbx->resolve_reference($wanted, $search_in, $expression);
730 Resolve a field reference
731 <https://keepass.info/help/base/fieldrefs.html>. A field reference is a
732 kind of string placeholder. You can use a field reference to refer
733 directly to a standard field within an entry. Field references are
734 resolved automatically while expanding entry strings (i.e. replacing
735 placeholders), but you can use this method to resolve on-the-fly
736 references that aren't part of any actual string in the database.
738 If the reference does not resolve to any field, undef is returned. If
739 the reference resolves to multiple fields, only the first one is
740 returned (in the same order as iterated by "entries"). To avoid
741 ambiguity, you can refer to a specific entry by its UUID.
743 The syntax of a reference is: {REF:<WantedField>@<SearchIn>:<Text>}.
744 Text is a "Simple Expression". WantedField and SearchIn are both single
745 character codes representing a field:
759 * O - Other custom strings
761 Since O does not represent any specific field, it cannot be used as the
766 To get the value of the UserName string of the first entry with "My
769 my $username = $kdbx->resolve_reference('{REF:U@T:"My Bank"}');
770 # OR the {REF:...} wrapper is optional
771 my $username = $kdbx->resolve_reference('U@T:"My Bank"');
772 # OR separate the arguments
773 my $username = $kdbx->resolve_reference(U => T => '"My Bank"');
775 Note how the text is a "Simple Expression", so search terms with spaces
776 must be surrounded in double quotes.
778 To get the Password string of a specific entry (identified by its
781 my $password = $kdbx->resolve_reference('{REF:P@I:46C9B1FFBD4ABC4BBB260C6190BAD20C}');
787 Encrypt all protected strings and binaries in a database. The encrypted
788 data is stored in a File::KDBX::Safe associated with the database and
789 the actual values will be replaced with undef to indicate their
790 protected state. Returns itself to allow method chaining.
792 You can call lock on an already-locked database to memory-protect any
793 unprotected strings and binaries added after the last time the database
800 Decrypt all protected strings and binaries in a database, replacing
801 undef value placeholders with their actual, unprotected values. Returns
802 itself to allow method chaining.
806 $guard = $kdbx->unlock_scoped;
808 Unlock a database temporarily, relocking when the guard is released
809 (typically at the end of a scope). Returns undef if the database is
812 See "lock" and "unlock".
817 my $guard = $kdbx->unlock_scoped;
820 # $kdbx is now memory-locked
824 $string = $kdbx->peek(\%string);
825 $string = $kdbx->peek(\%binary);
827 Peek at the value of a protected string or binary without unlocking the
828 whole database. The argument can be a string or binary hashref as
829 returned by "string" in File::KDBX::Entry or "binary" in
834 $bool = $kdbx->is_locked;
836 Get whether or not a database's contents are in a locked (i.e.
837 memory-protected) state. If this is true, then some or all of the
838 protected strings and binaries within the database will be unavailable
839 (literally have undef values) until "unlock" is called.
843 $kdbx->remove_empty_groups;
845 Remove groups with no subgroups and no entries.
849 $kdbx->remove_unused_icons;
851 Remove icons that are not associated with any entry or group in the
854 remove_duplicate_icons
856 $kdbx->remove_duplicate_icons;
858 Remove duplicate icons as determined by hashing the icon data.
862 $kdbx->prune_history(%options);
864 Remove just as many older historical entries as necessary to get under
867 * max_items - Maximum number of historical entries to keep (default:
868 value of "history_max_items", no limit: -1)
870 * max_size - Maximum total size (in bytes) of historical entries to
871 keep (default: value of "history_max_size", no limit: -1)
873 * max_age - Maximum age (in days) of historical entries to keep
874 (default: 365, no limit: -1)
878 $kdbx->randomize_seeds;
880 Set various keys, seeds and IVs to random values. These values are used
881 by the cryptographic functions that secure the database when dumped.
882 The attributes that will be randomized are:
886 * "inner_random_stream_key"
890 * "stream_start_bytes"
894 Randomizing these values has no effect on a loaded database. These are
895 only used when a database is dumped. You normally do not need to call
896 this method explicitly because the dumper does it explicitly by
902 $key = $kdbx->key($key);
903 $key = $kdbx->key($primitive);
905 Get or set a File::KDBX::Key. This is the master key (e.g. a password
906 or a key file that can decrypt a database). You can also pass a
907 primitive castable to a Key. See "new" in File::KDBX::Key for an
908 explanation of what the primitive can be.
910 You generally don't need to call this directly because you can provide
911 the key directly to the loader or dumper when loading or dumping a KDBX
916 $key = $kdbx->composite_key($key);
917 $key = $kdbx->composite_key($primitive);
919 Construct a File::KDBX::Key::Composite from a Key or primitive. See
920 "new" in File::KDBX::Key for an explanation of what the primitive can
921 be. If the primitive does not represent a composite key, it will be
924 You generally don't need to call this directly. The loader and dumper
925 use it to transform a master key into a raw encryption key.
929 $kdf = $kdbx->kdf(%options);
930 $kdf = $kdbx->kdf(\%parameters, %options);
932 Get a File::KDBX::KDF (key derivation function).
936 * params - KDF parameters, same as \%parameters (default: value of
941 $cipher = $kdbx->cipher(key => $key);
942 $cipher = $kdbx->cipher(key => $key, iv => $iv, uuid => $uuid);
944 Get a File::KDBX::Cipher capable of encrypting and decrypting the body
947 A key is required. This should be a raw encryption key made up of a
948 fixed number of octets (depending on the cipher), not a File::KDBX::Key
951 If not passed, the UUID comes from $kdbx->headers->{cipher_id} and the
952 encryption IV comes from $kdbx->headers->{encryption_iv}.
954 You generally don't need to call this directly. The loader and dumper
955 use it to decrypt and encrypt KDBX files.
959 $cipher = $kdbx->random_stream;
960 $cipher = $kdbx->random_stream(id => $stream_id, key => $key);
962 Get a File::KDBX::Cipher::Stream for decrypting and encrypting
965 If not passed, the ID and encryption key comes from
966 $kdbx->headers->{inner_random_stream_id} and
967 $kdbx->headers->{inner_random_stream_key} (respectively) for KDBX3
968 files and from $kdbx->inner_headers->{inner_random_stream_key} and
969 $kdbx->inner_headers->{inner_random_stream_id} (respectively) for KDBX4
972 You generally don't need to call this directly. The loader and dumper
973 use it to scramble protected strings.
977 Create a new database
979 my $kdbx = File::KDBX->new;
981 my $group = $kdbx->add_group(name => 'Passwords);
982 my $entry = $group->add_entry(
983 title => 'WayneCorp',
984 username => 'bwayne',
985 password => 'iambatman',
986 url => 'https://example.com/login'
988 $entry->add_auto_type_window_association('WayneCorp - Mozilla Firefox', '{PASSWORD}{ENTER}');
990 $kdbx->dump_file('mypasswords.kdbx', 'master password CHANGEME');
992 Read an existing database
994 my $kdbx = File::KDBX->load_file('mypasswords.kdbx', 'master password CHANGEME');
995 $kdbx->unlock; # cause $entry->password below to be defined
997 $kdbx->entries->each(sub {
999 say 'Found password for: ', $entry->title;
1000 say ' Username: ', $entry->username;
1001 say ' Password: ', $entry->password;
1006 my @entries = $kdbx->entries(searching => 1)
1007 ->grep(title => 'WayneCorp')
1008 ->each; # return all matches
1010 The searching option limits results to only entries within groups with
1011 searching enabled. Other options are also available. See "entries".
1013 See "QUERY" for many more query examples.
1015 Search for entries by auto-type window association
1017 my $window_title = 'WayneCorp - Mozilla Firefox';
1019 my $entries = $kdbx->entries(auto_type => 1)
1021 my ($ata) = grep { $_->{window} =~ /\Q$window_title\E/i } @{$_->auto_type_associations};
1022 return [$_, $ata->{keystroke_sequence}] if $ata;
1025 my ($entry, $keys) = @$_;
1026 say 'Entry title: ', $entry->title, ', key sequence: ', $keys;
1031 Entry title: WayneCorp, key sequence: {PASSWORD}{ENTER}
1033 Remove entries from a database
1036 ->grep(notes => {'=~' => qr/too old/i})
1037 ->each(sub { $_->recycle });
1039 Recycle all entries with the string "too old" appearing in the Notes
1044 $kdbx->groups(algorithm => 'dfs')
1045 ->where(-true => 'is_empty')
1048 With the search/iteration algorithm set to "dfs", groups will be
1049 ordered deepest first and the root group will be last. This allows
1050 removing groups that only contain empty groups.
1052 This can also be done with one call to "remove_empty_groups".
1056 One of the biggest threats to your database security is how easily the
1057 encryption key can be brute-forced. Strong brute-force protection
1060 * Using unguessable passwords, passphrases and key files.
1062 * Using a brute-force resistent key derivation function.
1064 The first factor is up to you. This module does not enforce strong
1065 master keys. It is up to you to pick or generate strong keys.
1067 The KDBX format allows for the key derivation function to be tuned. The
1068 idea is that you want each single brute-foce attempt to be expensive
1069 (in terms of time, CPU usage or memory usage), so that making a lot of
1070 attempts (which would be required if you have a strong master key) gets
1073 How expensive you want to make each attempt is up to you and can depend
1076 This and other KDBX-related security issues are covered here more in
1077 depth: https://keepass.info/help/base/security.html
1079 Here are other security risks you should be thinking about:
1083 This distribution uses the excellent CryptX and Crypt::Argon2 packages
1084 to handle all crypto-related functions. As such, a lot of the security
1085 depends on the quality of these dependencies. Fortunately these modules
1086 are maintained and appear to have good track records.
1088 The KDBX format has evolved over time to incorporate improved security
1089 practices and cryptographic functions. This package uses the following
1090 functions for authentication, hashing, encryption and random number
1097 * Argon2d & Argon2id
1107 * Salsa20 & ChaCha20
1111 At the time of this writing, I am not aware of any successful attacks
1112 against any of these functions. These are among the most-analyzed and
1113 widely-adopted crypto functions available.
1115 The KDBX format allows the body cipher and key derivation function to
1116 be configured. If a flaw is discovered in one of these functions, you
1117 can hopefully just switch to a better function without needing to
1118 update this software. A later software release may phase out the use of
1119 any functions which are no longer secure.
1123 It is not a good idea to keep secret information unencrypted in system
1124 memory for longer than is needed. The address space of your program can
1125 generally be read by a user with elevated privileges on the system. If
1126 your system is memory-constrained or goes into a hibernation mode, the
1127 contents of your address space could be written to a disk where it
1128 might be persisted for long time.
1130 There might be system-level things you can do to reduce your risk, like
1131 using swap encryption and limiting system access to your program's
1132 address space while your program is running.
1134 File::KDBX helps minimize (but not eliminate) risk by keeping secrets
1135 encrypted in memory until accessed and zeroing out memory that holds
1136 secrets after they're no longer needed, but it's not a silver bullet.
1138 For one thing, the encryption key is stored in the same address space.
1139 If core is dumped, the encryption key is available to be found out. But
1140 at least there is the chance that the encryption key and the encrypted
1141 secrets won't both be paged out together while memory-constrained.
1143 Another problem is that some perls (somewhat notoriously) copy around
1144 memory behind the scenes willy nilly, and it's difficult know when perl
1145 makes a copy of a secret in order to be able to zero it out later. It
1146 might be impossible. The good news is that perls with SvPV
1147 copy-on-write (enabled by default beginning with perl 5.20) are much
1148 better in this regard. With COW, it's mostly possible to know what
1149 operations will cause perl to copy the memory of a scalar string, and
1150 the number of copies will be significantly reduced. There is a unit
1151 test named t/memory-protection.t in this distribution that can be run
1152 on POSIX systems to determine how well File::KDBX memory protection is
1155 Memory protection also depends on how your application handles secrets.
1156 If your app code is handling scalar strings with secret information,
1157 it's up to you to make sure its memory is zeroed out when no longer
1158 needed. "erase" in File::KDBX::Util et al. provide some tools to help
1159 accomplish this. Or if you're not too concerned about the risks memory
1160 protection is meant to mitigate, then maybe don't worry about it. The
1161 security policy of File::KDBX is to try hard to keep secrets protected
1162 while in memory so that your app might claim a high level of security,
1163 in case you care about that.
1165 There are some memory protection strategies that File::KDBX does NOT
1166 use today but could in the future:
1168 Many systems allow programs to mark unswappable pages. Secret
1169 information should ideally be stored in such pages. You could
1170 potentially use mlockall(2) (or equivalent for your system) in your own
1171 application to prevent the entire address space from being swapped.
1173 Some systems provide special syscalls for storing secrets in memory
1174 while keeping the encryption key outside of the program's address
1175 space, like CryptProtectMemory for Windows. This could be a good
1176 option, though unfortunately not portable.
1180 To find things in a KDBX database, you should use a filtered iterator.
1181 If you have an iterator, such as returned by "entries", "groups" or
1182 even "objects" you can filter it using "where" in File::KDBX::Iterator.
1184 my $filtered_entries = $kdbx->entries->where(\&query);
1186 A \&query is just a subroutine that you can either write yourself or
1187 have generated for you from either a "Simple Expression" or
1188 "Declarative Syntax". It's easier to have your query generated, so I'll
1193 A simple expression is mostly compatible with the KeePass 2
1194 implementation described here
1195 <https://keepass.info/help/base/search.html#mode_se>.
1197 An expression is a string with one or more space-separated terms. Terms
1198 with spaces can be enclosed in double quotes. Terms are negated if they
1199 are prefixed with a minus sign. A record must match every term on at
1200 least one of the given fields.
1202 So a simple expression is something like what you might type into a
1203 search engine. You can generate a simple expression query using
1204 "simple_expression_query" in File::KDBX::Util or by passing the simple
1205 expression as a scalar reference to where.
1207 To search for all entries in a database with the word "canyon"
1208 appearing anywhere in the title:
1210 my $entries = $kdbx->entries->where(\'canyon', qw[title]);
1212 Notice the first argument is a scalarref. This disambiguates a simple
1213 expression from other types of queries covered below.
1215 As mentioned, a simple expression can have multiple terms. This simple
1216 expression query matches any entry that has the words "red" and
1217 "canyon" anywhere in the title:
1219 my $entries = $kdbx->entries->where(\'red canyon', qw[title]);
1221 Each term in the simple expression must be found for an entry to match.
1223 To search for entries with "red" in the title but not "canyon", just
1224 prepend "canyon" with a minus sign:
1226 my $entries = $kdbx->entries->where(\'red -canyon', qw[title]);
1228 To search over multiple fields simultaneously, just list them all. To
1229 search for entries with "grocery" (but not "Foodland") in the title or
1232 my $entries = $kdbx->entries->where(\'grocery -Foodland', qw[title notes]);
1234 The default operator is a case-insensitive regexp match, which is fine
1235 for searching text loosely. You can use just about any binary
1236 comparison operator that perl supports. To specify an operator, list it
1237 after the simple expression. For example, to search for any entry that
1238 has been used at least five times:
1240 my $entries = $kdbx->entries->where(\5, '>=', qw[usage_count]);
1242 It helps to read it right-to-left, like "usage_count is greater than or
1245 If you find the disambiguating structures to be distracting or
1246 confusing, you can also the "simple_expression_query" in
1247 File::KDBX::Util function as a more intuitive alternative. The
1248 following example is equivalent to the previous:
1250 my $entries = $kdbx->entries->where(simple_expression_query(5, '>=', qw[usage_count]));
1254 Structuring a declarative query is similar to "WHERE CLAUSES" in
1255 SQL::Abstract, but you don't have to be familiar with that module. Just
1256 learn by examples here.
1258 To search for all entries in a database titled "My Bank":
1260 my $entries = $kdbx->entries->where({ title => 'My Bank' });
1262 The query here is { title => 'My Bank' }. A hashref can contain
1263 key-value pairs where the key is an attribute of the thing being
1264 searched for (in this case an entry) and the value is what you want the
1265 thing's attribute to be to consider it a match. In this case, the
1266 attribute we're using as our match criteria is "title" in
1267 File::KDBX::Entry, a text field. If an entry has its title attribute
1268 equal to "My Bank", it's a match.
1270 A hashref can contain multiple attributes. The search candidate will be
1271 a match if all of the specified attributes are equal to their
1272 respective values. For example, to search for all entries with a
1273 particular URL AND username:
1275 my $entries = $kdbx->entries->where({
1276 url => 'https://example.com',
1280 To search for entries matching any criteria, just change the hashref to
1281 an arrayref. To search for entries with a particular URL OR username:
1283 my $entries = $kdbx->entries->where([ # <-- Notice the square bracket
1284 url => 'https://example.com',
1288 You can use different operators to test different types of attributes.
1289 The "icon_id" in File::KDBX::Entry attribute is a number, so we should
1290 use a number comparison operator. To find entries using the smartphone
1293 my $entries = $kdbx->entries->where({
1294 icon_id => { '==', ICON_SMARTPHONE },
1297 Note: "ICON_SMARTPHONE" in File::KDBX::Constants is just a constant
1298 from File::KDBX::Constants. It isn't special to this example or to
1299 queries generally. We could have just used a literal number.
1301 The important thing to notice here is how we wrapped the condition in
1302 another arrayref with a single key-value pair where the key is the name
1303 of an operator and the value is the thing to match against. The
1304 supported operators are:
1308 * ne - String not equal
1310 * lt - String less than
1312 * gt - String greater than
1314 * le - String less than or equal
1316 * ge - String greater than or equal
1320 * != - Number not equal
1322 * < - Number less than
1324 * > - Number greater than
1326 * <= - Number less than or equal
1328 * >= - Number less than or equal
1330 * =~ - String match regular expression
1332 * !~ - String does not match regular expression
1338 Other special operators:
1340 * -true - Boolean true
1342 * -false - Boolean false
1344 * -not - Boolean false (alias for -false)
1346 * -defined - Is defined
1348 * -undef - Is not defined
1352 * -nonempty - Is not empty
1356 * -and - Logical and
1358 Let's see another example using an explicit operator. To find all
1359 groups except one in particular (identified by its "uuid" in
1360 File::KDBX::Group), we can use the ne (string not equal) operator:
1362 my $groups = $kdbx->groups->where(
1364 'ne' => uuid('596f7520-6172-6520-7370-656369616c2e'),
1368 Note: "uuid" in File::KDBX::Util is a little utility function to
1369 convert a UUID in its pretty form into bytes. This utility function
1370 isn't special to this example or to queries generally. It could have
1371 been written with a literal such as "\x59\x6f\x75\x20\x61...", but
1372 that's harder to read.
1374 Notice we searched for groups this time. Finding groups works exactly
1375 the same as it does for entries.
1377 Notice also that we didn't wrap the query in hashref curly-braces or
1378 arrayref square-braces. Those are optional. By default it will only
1379 match ALL attributes (as if there were curly-braces).
1381 Testing the truthiness of an attribute is a little bit different
1382 because it isn't a binary operation. To find all entries with the
1383 password quality check disabled:
1385 my $entries = $kdbx->entries->where('!' => 'quality_check');
1387 This time the string after the operator is the attribute name rather
1388 than a value to compare the attribute against. To test that a boolean
1389 value is true, use the !! operator (or -true if !! seems a little too
1390 weird for your taste):
1392 my $entries = $kdbx->entries->where('!!' => 'quality_check');
1393 my $entries = $kdbx->entries->where(-true => 'quality_check'); # same thing
1395 Yes, there is also a -false and a -not if you prefer one of those over
1396 !. -false and -not (along with -true) are also special in that you can
1397 use them to invert the logic of a subquery. These are logically
1400 my $entries = $kdbx->entries->where(-not => { title => 'My Bank' });
1401 my $entries = $kdbx->entries->where(title => { 'ne' => 'My Bank' });
1403 These special operators become more useful when combined with two more
1404 special operators: -and and -or. With these, it is possible to
1405 construct more interesting queries with groups of logic. For example:
1407 my $entries = $kdbx->entries->where({
1408 title => { '=~', qr/bank/ },
1411 notes => { '=~', qr/business/ },
1412 icon_id => { '==', ICON_TRASHCAN_FULL },
1417 In English, find entries where the word "bank" appears anywhere in the
1418 title but also do not have either the word "business" in the notes or
1419 are using the full trashcan icon.
1423 Lastly, as mentioned at the top, you can ignore all this and write your
1424 own subroutine. Your subroutine will be called once for each object
1425 being searched over. The subroutine should match the candidate against
1426 whatever criteria you want and return true if it matches or false to
1427 skip. To do this, just pass your subroutine coderef to where.
1429 To review the different types of queries, these are all equivalent to
1430 find all entries in the database titled "My Bank":
1432 my $entries = $kdbx->entries->where(\'"My Bank"', 'eq', qw[title]); # simple expression
1433 my $entries = $kdbx->entries->where(title => 'My Bank'); # declarative syntax
1434 my $entries = $kdbx->entries->where(sub { $_->title eq 'My Bank' }); # subroutine query
1436 This is a trivial example, but of course your subroutine can be
1437 arbitrarily complex.
1439 All of these query mechanisms described in this section are just tools,
1440 each with its own set of limitations. If the tools are getting in your
1441 way, you can of course iterate over the contents of a database and
1442 implement your own query logic, like this:
1444 my $entries = $kdbx->entries;
1445 while (my $entry = $entries->next) {
1446 if (wanted($entry)) {
1447 do_something($entry);
1456 Iterators are the built-in way to navigate or walk the database tree.
1457 You get an iterator from "entries", "groups" and "objects". You can
1458 specify the search algorithm to iterate over objects in different
1459 orders using the algorith option, which can be one of these constants:
1461 * ITERATION_IDS - Iterative deepening search (default)
1463 * ITERATION_DFS - Depth-first search
1465 * ITERATION_BFS - Breadth-first search
1467 When iterating over objects generically, groups always precede their
1468 direct entries (if any). When the history option is used, current
1469 entries always precede historical entries.
1471 If you have a database tree like this:
1482 * IDS order of groups is: Root, Group1, Group2, Group3
1484 * IDS order of entries is: EntryA, EntryB, EntryC
1486 * IDS order of objects is: Root, Group1, EntryA, Group2, EntryB,
1489 * DFS order of groups is: Group2, Group1, Group3, Root
1491 * DFS order of entries is: EntryB, EntryA, EntryC
1493 * DFS order of objects is: Group2, EntryB, Group1, EntryA, Group3,
1496 * BFS order of groups is: Root, Group1, Group3, Group2
1498 * BFS order of entries is: EntryA, EntryC, EntryB
1500 * BFS order of objects is: Root, Group1, EntryA, Group3, EntryC,
1505 TODO - This is a planned feature, not yet implemented.
1509 Errors in this package are constructed as File::KDBX::Error objects and
1510 propagated using perl's built-in mechanisms. Fatal errors are
1511 propagated using "die LIST" in perlfunc and non-fatal errors (a.k.a.
1512 warnings) are propagated using "warn LIST" in perlfunc while adhering
1513 to perl's warnings system. If you're already familiar with these
1514 mechanisms, you can skip this section.
1516 You can catch fatal errors using "eval BLOCK" in perlfunc (or something
1517 like Try::Tiny) and non-fatal errors using $SIG{__WARN__} (see "%SIG"
1518 in perlvar). Examples:
1520 use File::KDBX::Error qw(error);
1522 my $key = ''; # uh oh
1524 $kdbx->load_file('whatever.kdbx', $key);
1526 if (my $error = error($@)) {
1527 handle_missing_key($error) if $error->type eq 'key.missing';
1534 $kdbx->load_file('whatever.kdbx', $key);
1540 Catching non-fatal errors:
1543 local $SIG{__WARN__} = sub { push @warnings, $_[0] };
1545 $kdbx->load_file('whatever.kdbx', $key);
1547 handle_warnings(@warnings) if @warnings;
1549 By default perl prints warnings to STDERR if you don't catch them. If
1550 you don't want to catch them and also don't want them printed to
1551 STDERR, you can suppress them lexically (perl v5.28 or higher
1555 no warnings 'File::KDBX';
1562 local $File::KDBX::WARNINGS = 0;
1566 or globally in your program:
1568 $File::KDBX::WARNINGS = 0;
1570 You cannot suppress fatal errors, and if you don't catch them your
1575 This software will alter its behavior depending on the value of certain
1576 environment variables:
1578 * PERL_FILE_KDBX_XS - Do not use File::KDBX::XS if false (default:
1581 * PERL_ONLY - Do not use File::KDBX::XS if true (default: false)
1583 * NO_FORK - Do not fork if true (default: false)
1587 Some features (e.g. parsing) require 64-bit perl. It should be possible
1588 and actually pretty easy to make it work using Math::BigInt, but I need
1589 to build a 32-bit perl in order to test it and frankly I'm still
1590 figuring out how. I'm sure it's simple so I'll mark this one "TODO",
1591 but for now an exception will be thrown when trying to use such
1592 features with undersized IVs.
1596 * KeePass Password Safe <https://keepass.info/> - The original
1599 * KeePassXC <https://keepassxc.org/> - Cross-Platform Password
1600 Manager written in C++
1602 * File::KeePass has overlapping functionality. It's good but has a
1603 backlog of some pretty critical bugs and lacks support for newer KDBX
1608 Please report any bugs or feature requests on the bugtracker website
1609 https://github.com/chazmcgarvey/File-KDBX/issues
1611 When submitting a bug or request, please include a test-file or a patch
1612 to an existing test-file that illustrates the bug or desired feature.
1616 Charles McGarvey <ccm@cpan.org>
1618 COPYRIGHT AND LICENSE
1620 This software is copyright (c) 2022 by Charles McGarvey.
1622 This is free software; you can redistribute it and/or modify it under
1623 the same terms as the Perl 5 programming language system itself.