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. Often unset.
152 The UUID of a cipher used to encrypt the database when stored as a
155 See File::KDBX::Cipher.
159 Configuration for whether or not and how the database gets compressed.
160 See ":compression" in File::KDBX::Constants.
164 The master seed is a string of 32 random bytes that is used as salt in
165 hashing the master key when loading and saving the database. If a
166 challenge-response key is used in the master key, the master seed is
169 The master seed should be changed each time the database is saved to
174 The transform seed is a string of 32 random bytes that is used in the
175 key derivation function, either as the salt or the key (depending on
178 The transform seed should be changed each time the database is saved to
183 The number of rounds or iterations used in the key derivation function.
184 Increasing this number makes loading and saving the database slower by
185 design in order to make dictionary and brute force attacks more costly.
189 The initialization vector used by the cipher.
191 The encryption IV should be changed each time the database is saved to
194 inner_random_stream_key
196 The encryption key (possibly including the IV, depending on the cipher)
197 used to encrypt the protected strings within the database.
201 A string of 32 random bytes written in the header and encrypted in the
202 body. If the bytes do not match when loading a file then the wrong
203 master key was used or the file is corrupt. Only KDBX 2 and KDBX 3
204 files use this. KDBX 4 files use an improved HMAC method to verify the
205 master key and data integrity of the header and entire file body.
207 inner_random_stream_id
209 A number indicating the cipher algorithm used to encrypt the protected
210 strings within the database, usually Salsa20 or ChaCha20. See
211 ":random_stream" in File::KDBX::Constants.
215 A hash/dict of key-value pairs used to configure the key derivation
216 function. This is the KDBX4+ way to configure the KDF, superceding
217 "transform_seed" and "transform_rounds".
221 The name of the software used to generate the KDBX file.
225 The header hash used to verify that the file header is not corrupt.
226 (KDBX 2 - KDBX 3.1, removed KDBX 4.0)
230 Name of the database.
232 database_name_changed
234 Timestamp indicating when the database name was last changed.
238 Description of the database
240 database_description_changed
242 Timestamp indicating when the database description was last changed.
246 When a new entry is created, the UserName string will be populated with
249 default_username_changed
251 Timestamp indicating when the default username was last changed.
255 A color associated with the database (in the form #ffffff where "f" is
256 a hexidecimal digit). Some agents use this to help users visually
257 distinguish between different databases.
261 Timestamp indicating when the master key was last changed.
263 master_key_change_rec
265 Number of days until the agent should prompt to recommend changing the
268 master_key_change_force
270 Number of days until the agent should prompt to force changing the
273 Note: This is purely advisory. It is up to the individual agent
274 software to actually enforce it. File::KDBX does NOT enforce it.
278 Array of custom icons that can be associated with groups and entries.
280 This list can be managed with the methods "add_custom_icon" and
281 "remove_custom_icon".
285 Boolean indicating whether removed groups and entries should go to a
286 recycle bin or be immediately deleted.
290 The UUID of a group used to store thrown-away groups and entries.
294 Timestamp indicating when the recycle bin group was last changed.
296 entry_templates_group
298 The UUID of a group containing template entries used when creating new
301 entry_templates_group_changed
303 Timestamp indicating when the entry templates group was last changed.
307 The UUID of the previously-selected group.
309 last_top_visible_group
311 The UUID of the group visible at the top of the list.
315 The maximum number of historical entries that should be kept for each
316 entry. Default is 10.
320 The maximum total size (in bytes) that each individual entry's history
321 is allowed to grow. Default is 6 MiB.
323 maintenance_history_days
325 The maximum age (in days) historical entries should be kept. Default it
330 Timestamp indicating when the database settings were last updated.
334 Alias of the "memory_protection" setting for the Title string.
338 Alias of the "memory_protection" setting for the UserName string.
342 Alias of the "memory_protection" setting for the Password string.
346 Alias of the "memory_protection" setting for the URL string.
350 Alias of the "memory_protection" setting for the Notes string.
356 $kdbx = File::KDBX->new(%attributes);
357 $kdbx = File::KDBX->new($kdbx); # copy constructor
359 Construct a new File::KDBX.
363 $kdbx = $kdbx->init(%attributes);
365 Initialize a File::KDBX with a set of attributes. Returns itself to
366 allow method chaining.
368 This is called by "new".
372 $kdbx = $kdbx->reset;
374 Set a File::KDBX to an empty state, ready to load a KDBX file or build
375 a new one. Returns itself to allow method chaining.
379 $kdbx_copy = $kdbx->clone;
380 $kdbx_copy = File::KDBX->new($kdbx);
382 Clone a File::KDBX. The clone will be an exact copy and completely
383 independent of the original.
393 $kdbx = KDBX::File->load(\$string, $key);
394 $kdbx = KDBX::File->load(*IO, $key);
395 $kdbx = KDBX::File->load($filepath, $key);
396 $kdbx->load(...); # also instance method
398 $kdbx = File::KDBX->load_string($string, $key);
399 $kdbx = File::KDBX->load_string(\$string, $key);
400 $kdbx->load_string(...); # also instance method
402 $kdbx = File::KDBX->load_file($filepath, $key);
403 $kdbx->load_file(...); # also instance method
405 $kdbx = File::KDBX->load_handle($fh, $key);
406 $kdbx = File::KDBX->load_handle(*IO, $key);
407 $kdbx->load_handle(...); # also instance method
409 Load a KDBX file from a string buffer, IO handle or file from a
412 File::KDBX::Loader does the heavy lifting.
422 $kdbx->dump(\$string, $key);
423 $kdbx->dump(*IO, $key);
424 $kdbx->dump($filepath, $key);
426 $kdbx->dump_string(\$string, $key);
427 \$string = $kdbx->dump_string($key);
429 $kdbx->dump_file($filepath, $key);
431 $kdbx->dump_handle($fh, $key);
432 $kdbx->dump_handle(*IO, $key);
434 Dump a KDBX file to a string buffer, IO handle or file in a filesystem.
436 File::KDBX::Dumper does the heavy lifting.
440 $string = $kdbx->user_agent_string;
442 Get a text string identifying the database client software.
446 \%settings = $kdbx->memory_protection
447 $kdbx->memory_protection(\%settings);
449 $bool = $kdbx->memory_protection($string_key);
450 $kdbx->memory_protection($string_key => $bool);
452 Get or set memory protection settings. This globally (for the whole
453 database) configures whether and which of the standard strings should
454 be memory-protected. The default setting is to memory-protect only
457 Memory protection can be toggled individually for each entry string,
458 and individual settings take precedence over these global settings.
462 $version = $kdbx->minimum_version;
464 Determine the minimum file version required to save a database
465 losslessly. Using certain databases features might increase this value.
466 For example, setting the KDF to Argon2 will increase the minimum
467 version to at least KDBX_VERSION_4_0 (i.e. 0x00040000) because Argon2
468 was introduced with KDBX4.
470 This method never returns less than KDBX_VERSION_3_1 (i.e. 0x00030001).
471 That file version is so ubiquitous and well-supported, there are seldom
472 reasons to dump in a lesser format nowadays.
474 WARNING: If you dump a database with a minimum version higher than the
475 current "version", the dumper will typically issue a warning and
476 automatically upgrade the database. This seems like the safest behavior
477 in order to avoid data loss, but lower versions have the benefit of
478 being compatible with more software. It is possible to prevent
479 auto-upgrades by explicitly telling the dumper which version to use,
480 but you do run the risk of data loss. A database will never be
481 automatically downgraded.
485 $group = $kdbx->root;
488 Get or set a database's root group. You don't necessarily need to
489 explicitly create or set a root group because it autovivifies when
490 adding entries and groups to the database.
492 Every database has only a single root group at a time. Some old KDB
493 files might have multiple root groups. When reading such files, a
494 single implicit root group is created to contain the actual root
495 groups. When writing to such a format, if the root group looks like it
496 was implicitly created then it won't be written and the resulting file
497 might have multiple root groups, as it was before loading. This allows
498 working with older files without changing their written internal
499 structure while still adhering to modern semantics while the database
502 The root group of a KDBX database contains all of the database's
503 entries and other groups. If you replace the root group, you are
504 essentially replacing the entire database contents with something else.
508 \@lineage = $kdbx->trace_lineage($group);
509 \@lineage = $kdbx->trace_lineage($group, $base_group);
510 \@lineage = $kdbx->trace_lineage($entry);
511 \@lineage = $kdbx->trace_lineage($entry, $base_group);
513 Get the direct line of ancestors from $base_group (default: the root
514 group) to a group or entry. The lineage includes the base group but not
515 the target group or entry. Returns undef if the target is not in the
520 $group = $kdbx->recycle_bin;
521 $kdbx->recycle_bin($group);
523 Get or set the recycle bin group. Returns undef if there is no recycle
524 bin and "recycle_bin_enabled" is false, otherwise the current recycle
525 bin or an autovivified recycle bin group is returned.
529 $group = $kdbx->entry_templates;
530 $kdbx->entry_templates($group);
532 Get or set the entry templates group. May return undef if unset.
536 $group = $kdbx->last_selected;
537 $kdbx->last_selected($group);
539 Get or set the last selected group. May return undef if unset.
543 $group = $kdbx->last_top_visible;
544 $kdbx->last_top_visible($group);
546 Get or set the last top visible group. May return undef if unset.
550 $kdbx->add_group($group);
551 $kdbx->add_group(%group_attributes, %options);
553 Add a group to a database. This is equivalent to identifying a parent
554 group and calling "add_group" in File::KDBX::Group on the parent group,
555 forwarding the arguments. Available options:
557 * group - Group object or group UUID to add the group to (default:
562 \&iterator = $kdbx->groups(%options);
563 \&iterator = $kdbx->groups($base_group, %options);
565 Get an File::KDBX::Iterator over groups within a database. Options:
567 * base - Only include groups within a base group (same as
568 $base_group) (default: "root")
570 * inclusive - Include the base group in the results (default: true)
572 * algorithm - Search algorithm, one of ids, bfs or dfs (default: ids)
576 $kdbx->add_entry($entry, %options);
577 $kdbx->add_entry(%entry_attributes, %options);
579 Add an entry to a database. This is equivalent to identifying a parent
580 group and calling "add_entry" in File::KDBX::Group on the parent group,
581 forwarding the arguments. Available options:
583 * group - Group object or group UUID to add the entry to (default:
588 \&iterator = $kdbx->entries(%options);
589 \&iterator = $kdbx->entries($base_group, %options);
591 Get an File::KDBX::Iterator over entries within a database. Supports
592 the same options as "groups", plus some new ones:
594 * auto_type - Only include entries with auto-type enabled (default:
597 * searching - Only include entries within groups with searching
598 enabled (default: false, include all)
600 * history - Also include historical entries (default: false, include
601 only current entries)
605 \&iterator = $kdbx->objects(%options);
606 \&iterator = $kdbx->objects($base_group, %options);
608 Get an File::KDBX::Iterator over objects within a database. Groups and
609 entries are considered objects, so this is essentially a combination of
610 "groups" and "entries". This won't often be useful, but it can be
611 convenient for maintenance tasks. This method takes the same options as
612 "groups" and "entries".
616 \%icon = $kdbx->custom_icon($uuid);
617 $kdbx->custom_icon($uuid => \%icon);
618 $kdbx->custom_icon(%icon);
619 $kdbx->custom_icon(uuid => $value, %icon);
621 Get or set custom icons.
625 $image_data = $kdbx->custom_icon_data($uuid);
627 Get a custom icon image data.
631 $uuid = $kdbx->add_custom_icon($image_data, %attributes);
632 $uuid = $kdbx->add_custom_icon(%attributes);
634 Add a custom icon and get its UUID. If not provided, a random UUID will
635 be generated. Possible attributes:
637 * uuid - Icon UUID (default: autogenerated)
639 * data - Image data (same as $image_data)
641 * name - Name of the icon (text, KDBX4.1+)
643 * last_modification_time - Just what it says (datetime, KDBX4.1+)
647 $kdbx->remove_custom_icon($uuid);
649 Remove a custom icon.
653 \%all_data = $kdbx->custom_data;
654 $kdbx->custom_data(\%all_data);
656 \%data = $kdbx->custom_data($key);
657 $kdbx->custom_data($key => \%data);
658 $kdbx->custom_data(%data);
659 $kdbx->custom_data(key => $value, %data);
661 Get and set custom data. Custom data is metadata associated with a
664 Each data item can have a few attributes associated with it.
666 * key - A unique text string identifier used to look up the data item
669 * value - A text string value (required)
671 * last_modification_time (optional, KDBX4.1+)
675 $value = $kdbx->custom_data_value($key);
677 Exactly the same as "custom_data" except returns just the custom data's
678 value rather than a structure of attributes. This is a shortcut for:
680 my $data = $kdbx->custom_data($key);
681 my $value = defined $data ? $data->{value} : undef;
685 \%all_data = $kdbx->public_custom_data;
686 $kdbx->public_custom_data(\%all_data);
688 $value = $kdbx->public_custom_data($key);
689 $kdbx->public_custom_data($key => $value);
691 Get and set public custom data. Public custom data is similar to custom
692 data but different in some important ways. Public custom data:
694 * can store strings, booleans and up to 64-bit integer values (custom
695 data can only store text values)
697 * is NOT encrypted within a KDBX file (hence the "public" part of the
700 * is a plain hash/dict of key-value pairs with no other associated
701 fields (like modification times)
705 $kdbx->add_deleted_object($uuid);
707 Add a UUID to the deleted objects list. This list is used to support
708 automatic database merging.
710 You typically do not need to call this yourself because the list will
711 be populated automatically as objects are removed.
713 remove_deleted_object
715 $kdbx->remove_deleted_object($uuid);
717 Remove a UUID from the deleted objects list. This list is used to
718 support automatic database merging.
720 You typically do not need to call this yourself because the list will
721 be maintained automatically as objects are added.
723 clear_deleted_objects
725 Remove all UUIDs from the deleted objects list. This list is used to
726 support automatic database merging, but if you don't need merging then
727 you can clear deleted objects to reduce the database file size.
731 $string = $kdbx->resolve_reference($reference);
732 $string = $kdbx->resolve_reference($wanted, $search_in, $expression);
734 Resolve a field reference
735 <https://keepass.info/help/base/fieldrefs.html>. A field reference is a
736 kind of string placeholder. You can use a field reference to refer
737 directly to a standard field within an entry. Field references are
738 resolved automatically while expanding entry strings (i.e. replacing
739 placeholders), but you can use this method to resolve on-the-fly
740 references that aren't part of any actual string in the database.
742 If the reference does not resolve to any field, undef is returned. If
743 the reference resolves to multiple fields, only the first one is
744 returned (in the same order as iterated by "entries"). To avoid
745 ambiguity, you can refer to a specific entry by its UUID.
747 The syntax of a reference is: {REF:<WantedField>@<SearchIn>:<Text>}.
748 Text is a "Simple Expression". WantedField and SearchIn are both single
749 character codes representing a field:
763 * O - Other custom strings
765 Since O does not represent any specific field, it cannot be used as the
770 To get the value of the UserName string of the first entry with "My
773 my $username = $kdbx->resolve_reference('{REF:U@T:"My Bank"}');
774 # OR the {REF:...} wrapper is optional
775 my $username = $kdbx->resolve_reference('U@T:"My Bank"');
776 # OR separate the arguments
777 my $username = $kdbx->resolve_reference(U => T => '"My Bank"');
779 Note how the text is a "Simple Expression", so search terms with spaces
780 must be surrounded in double quotes.
782 To get the Password string of a specific entry (identified by its
785 my $password = $kdbx->resolve_reference('{REF:P@I:46C9B1FFBD4ABC4BBB260C6190BAD20C}');
791 Encrypt all protected strings and binaries in a database. The encrypted
792 data is stored in a File::KDBX::Safe associated with the database and
793 the actual values will be replaced with undef to indicate their
794 protected state. Returns itself to allow method chaining.
796 You can call lock on an already-locked database to memory-protect any
797 unprotected strings and binaries added after the last time the database
804 Decrypt all protected strings and binaries in a database, replacing
805 undef value placeholders with their actual, unprotected values. Returns
806 itself to allow method chaining.
810 $guard = $kdbx->unlock_scoped;
812 Unlock a database temporarily, relocking when the guard is released
813 (typically at the end of a scope). Returns undef if the database is
816 See "lock" and "unlock".
821 my $guard = $kdbx->unlock_scoped;
824 # $kdbx is now memory-locked
828 $string = $kdbx->peek(\%string);
829 $string = $kdbx->peek(\%binary);
831 Peek at the value of a protected string or binary without unlocking the
832 whole database. The argument can be a string or binary hashref as
833 returned by "string" in File::KDBX::Entry or "binary" in
838 $bool = $kdbx->is_locked;
840 Get whether or not a database's contents are in a locked (i.e.
841 memory-protected) state. If this is true, then some or all of the
842 protected strings and binaries within the database will be unavailable
843 (literally have undef values) until "unlock" is called.
847 $kdbx->remove_empty_groups;
849 Remove groups with no subgroups and no entries.
853 $kdbx->remove_unused_icons;
855 Remove icons that are not associated with any entry or group in the
858 remove_duplicate_icons
860 $kdbx->remove_duplicate_icons;
862 Remove duplicate icons as determined by hashing the icon data.
866 $kdbx->prune_history(%options);
868 Remove just as many older historical entries as necessary to get under
871 * max_items - Maximum number of historical entries to keep (default:
872 value of "history_max_items", no limit: -1)
874 * max_size - Maximum total size (in bytes) of historical entries to
875 keep (default: value of "history_max_size", no limit: -1)
877 * max_age - Maximum age (in days) of historical entries to keep
878 (default: value of "maintenance_history_days", no limit: -1)
882 $kdbx->randomize_seeds;
884 Set various keys, seeds and IVs to random values. These values are used
885 by the cryptographic functions that secure the database when dumped.
886 The attributes that will be randomized are:
890 * "inner_random_stream_key"
894 * "stream_start_bytes"
898 Randomizing these values has no effect on a loaded database. These are
899 only used when a database is dumped. You normally do not need to call
900 this method explicitly because the dumper does it for you by default.
905 $key = $kdbx->key($key);
906 $key = $kdbx->key($primitive);
908 Get or set a File::KDBX::Key. This is the master key (e.g. a password
909 or a key file that can decrypt a database). You can also pass a
910 primitive castable to a Key. See "new" in File::KDBX::Key for an
911 explanation of what the primitive can be.
913 You generally don't need to call this directly because you can provide
914 the key directly to the loader or dumper when loading or dumping a KDBX
919 $key = $kdbx->composite_key($key);
920 $key = $kdbx->composite_key($primitive);
922 Construct a File::KDBX::Key::Composite from a Key or primitive. See
923 "new" in File::KDBX::Key for an explanation of what the primitive can
924 be. If the primitive does not represent a composite key, it will be
927 You generally don't need to call this directly. The loader and dumper
928 use it to transform a master key into a raw encryption key.
932 $kdf = $kdbx->kdf(%options);
933 $kdf = $kdbx->kdf(\%parameters, %options);
935 Get a File::KDBX::KDF (key derivation function).
939 * params - KDF parameters, same as \%parameters (default: value of
944 $cipher = $kdbx->cipher(key => $key);
945 $cipher = $kdbx->cipher(key => $key, iv => $iv, uuid => $uuid);
947 Get a File::KDBX::Cipher capable of encrypting and decrypting the body
950 A key is required. This should be a raw encryption key made up of a
951 fixed number of octets (depending on the cipher), not a File::KDBX::Key
954 If not passed, the UUID comes from $kdbx->headers->{cipher_id} and the
955 encryption IV comes from $kdbx->headers->{encryption_iv}.
957 You generally don't need to call this directly. The loader and dumper
958 use it to decrypt and encrypt KDBX files.
962 $cipher = $kdbx->random_stream;
963 $cipher = $kdbx->random_stream(id => $stream_id, key => $key);
965 Get a File::KDBX::Cipher::Stream for decrypting and encrypting
968 If not passed, the ID and encryption key comes from
969 $kdbx->headers->{inner_random_stream_id} and
970 $kdbx->headers->{inner_random_stream_key} (respectively) for KDBX3
971 files and from $kdbx->inner_headers->{inner_random_stream_key} and
972 $kdbx->inner_headers->{inner_random_stream_id} (respectively) for KDBX4
975 You generally don't need to call this directly. The loader and dumper
976 use it to scramble protected strings.
980 Create a new database
982 my $kdbx = File::KDBX->new;
984 my $group = $kdbx->add_group(name => 'Passwords);
985 my $entry = $group->add_entry(
986 title => 'WayneCorp',
987 username => 'bwayne',
988 password => 'iambatman',
989 url => 'https://example.com/login'
991 $entry->add_auto_type_window_association('WayneCorp - Mozilla Firefox', '{PASSWORD}{ENTER}');
993 $kdbx->dump_file('mypasswords.kdbx', 'master password CHANGEME');
995 Read an existing database
997 my $kdbx = File::KDBX->load_file('mypasswords.kdbx', 'master password CHANGEME');
998 $kdbx->unlock; # cause $entry->password below to be defined
1000 $kdbx->entries->each(sub($entry, @) {
1001 say 'Found password for: ', $entry->title;
1002 say ' Username: ', $entry->username;
1003 say ' Password: ', $entry->password;
1008 my @entries = $kdbx->entries(searching => 1)
1009 ->grep(title => 'WayneCorp')
1010 ->each; # return all matches
1012 The searching option limits results to only entries within groups with
1013 searching enabled. Other options are also available. See "entries".
1015 See "QUERY" for many more query examples.
1017 Search for entries by auto-type window association
1019 my $window_title = 'WayneCorp - Mozilla Firefox';
1021 my $entries = $kdbx->entries(auto_type => 1)
1023 my ($ata) = grep { $_->{window} =~ /\Q$window_title\E/i } @{$_->auto_type_associations};
1024 return [$_, $ata->{keystroke_sequence}] if $ata;
1027 my ($entry, $keys) = @$_;
1028 say 'Entry title: ', $entry->title, ', key sequence: ', $keys;
1033 Entry title: WayneCorp, key sequence: {PASSWORD}{ENTER}
1035 Remove entries from a database
1038 ->grep(notes => {'=~' => qr/too old/i})
1039 ->each(sub { $_->recycle });
1041 Recycle all entries with the string "too old" appearing in the Notes
1046 $kdbx->groups(algorithm => 'dfs')
1047 ->where(-true => 'is_empty')
1050 With the search/iteration algorithm set to "dfs", groups will be
1051 ordered deepest first and the root group will be last. This allows
1052 removing groups that only contain empty groups.
1054 This can also be done with one call to "remove_empty_groups".
1058 One of the biggest threats to your database security is how easily the
1059 encryption key can be brute-forced. Strong brute-force protection
1062 * Using unguessable passwords, passphrases and key files.
1064 * Using a brute-force resistent key derivation function.
1066 The first factor is up to you. This module does not enforce strong
1067 master keys. It is up to you to pick or generate strong keys.
1069 The KDBX format allows for the key derivation function to be tuned. The
1070 idea is that you want each single brute-force attempt to be expensive
1071 (in terms of time, CPU usage or memory usage), so that making a lot of
1072 attempts (which would be required if you have a strong master key) gets
1075 How expensive you want to make each attempt is up to you and can depend
1078 This and other KDBX-related security issues are covered here more in
1079 depth: https://keepass.info/help/base/security.html
1081 Here are other security risks you should be thinking about:
1085 This distribution uses the excellent CryptX and Crypt::Argon2 packages
1086 to handle all crypto-related functions. As such, a lot of the security
1087 depends on the quality of these dependencies. Fortunately these modules
1088 are maintained and appear to have good track records.
1090 The KDBX format has evolved over time to incorporate improved security
1091 practices and cryptographic functions. This package uses the following
1092 functions for authentication, hashing, encryption and random number
1099 * Argon2d & Argon2id
1109 * Salsa20 & ChaCha20
1113 At the time of this writing, I am not aware of any successful attacks
1114 against any of these functions. These are among the most-analyzed and
1115 widely-adopted crypto functions available.
1117 The KDBX format allows the body cipher and key derivation function to
1118 be configured. If a flaw is discovered in one of these functions, you
1119 can hopefully just switch to a better function without needing to
1120 update this software. A later software release may phase out the use of
1121 any functions which are no longer secure.
1125 It is not a good idea to keep secret information unencrypted in system
1126 memory for longer than is needed. The address space of your program can
1127 generally be read by a user with elevated privileges on the system. If
1128 your system is memory-constrained or goes into a hibernation mode, the
1129 contents of your address space could be written to a disk where it
1130 might be persisted for long time.
1132 There might be system-level things you can do to reduce your risk, like
1133 using swap encryption and limiting system access to your program's
1134 address space while your program is running.
1136 File::KDBX helps minimize (but not eliminate) risk by keeping secrets
1137 encrypted in memory until accessed and zeroing out memory that holds
1138 secrets after they're no longer needed, but it's not a silver bullet.
1140 For one thing, the encryption key is stored in the same address space.
1141 If core is dumped, the encryption key is available to be found out. But
1142 at least there is the chance that the encryption key and the encrypted
1143 secrets won't both be paged out together while memory-constrained.
1145 Another problem is that some perls (somewhat notoriously) copy around
1146 memory behind the scenes willy nilly, and it's difficult know when perl
1147 makes a copy of a secret in order to be able to zero it out later. It
1148 might be impossible. The good news is that perls with SvPV
1149 copy-on-write (enabled by default beginning with perl 5.20) are much
1150 better in this regard. With COW, it's mostly possible to know what
1151 operations will cause perl to copy the memory of a scalar string, and
1152 the number of copies will be significantly reduced. There is a unit
1153 test named t/memory-protection.t in this distribution that can be run
1154 on POSIX systems to determine how well File::KDBX memory protection is
1157 Memory protection also depends on how your application handles secrets.
1158 If your app code is handling scalar strings with secret information,
1159 it's up to you to make sure its memory is zeroed out when no longer
1160 needed. "erase" in File::KDBX::Util et al. provide some tools to help
1161 accomplish this. Or if you're not too concerned about the risks memory
1162 protection is meant to mitigate, then maybe don't worry about it. The
1163 security policy of File::KDBX is to try hard to keep secrets protected
1164 while in memory so that your app might claim a high level of security,
1165 in case you care about that.
1167 There are some memory protection strategies that File::KDBX does NOT
1168 use today but could in the future:
1170 Many systems allow programs to mark unswappable pages. Secret
1171 information should ideally be stored in such pages. You could
1172 potentially use mlockall(2) (or equivalent for your system) in your own
1173 application to prevent the entire address space from being swapped.
1175 Some systems provide special syscalls for storing secrets in memory
1176 while keeping the encryption key outside of the program's address
1177 space, like CryptProtectMemory for Windows. This could be a good
1178 option, though unfortunately not portable.
1182 To find things in a KDBX database, you should use a filtered iterator.
1183 If you have an iterator, such as returned by "entries", "groups" or
1184 even "objects" you can filter it using "where" in File::KDBX::Iterator.
1186 my $filtered_entries = $kdbx->entries->where(\&query);
1188 A \&query is just a subroutine that you can either write yourself or
1189 have generated for you from either a "Simple Expression" or
1190 "Declarative Syntax". It's easier to have your query generated, so I'll
1195 A simple expression is mostly compatible with the KeePass 2
1196 implementation described here
1197 <https://keepass.info/help/base/search.html#mode_se>.
1199 An expression is a string with one or more space-separated terms. Terms
1200 with spaces can be enclosed in double quotes. Terms are negated if they
1201 are prefixed with a minus sign. A record must match every term on at
1202 least one of the given fields.
1204 So a simple expression is something like what you might type into a
1205 search engine. You can generate a simple expression query using
1206 "simple_expression_query" in File::KDBX::Util or by passing the simple
1207 expression as a scalar reference to where.
1209 To search for all entries in a database with the word "canyon"
1210 appearing anywhere in the title:
1212 my $entries = $kdbx->entries->where(\'canyon', qw[title]);
1214 Notice the first argument is a scalarref. This disambiguates a simple
1215 expression from other types of queries covered below.
1217 As mentioned, a simple expression can have multiple terms. This simple
1218 expression query matches any entry that has the words "red" and
1219 "canyon" anywhere in the title:
1221 my $entries = $kdbx->entries->where(\'red canyon', qw[title]);
1223 Each term in the simple expression must be found for an entry to match.
1225 To search for entries with "red" in the title but not "canyon", just
1226 prepend "canyon" with a minus sign:
1228 my $entries = $kdbx->entries->where(\'red -canyon', qw[title]);
1230 To search over multiple fields simultaneously, just list them all. To
1231 search for entries with "grocery" (but not "Foodland") in the title or
1234 my $entries = $kdbx->entries->where(\'grocery -Foodland', qw[title notes]);
1236 The default operator is a case-insensitive regexp match, which is fine
1237 for searching text loosely. You can use just about any binary
1238 comparison operator that perl supports. To specify an operator, list it
1239 after the simple expression. For example, to search for any entry that
1240 has been used at least five times:
1242 my $entries = $kdbx->entries->where(\5, '>=', qw[usage_count]);
1244 It helps to read it right-to-left, like "usage_count is greater than or
1247 If you find the disambiguating structures to be distracting or
1248 confusing, you can also use the "simple_expression_query" in
1249 File::KDBX::Util function as a more intuitive alternative. The
1250 following example is equivalent to the previous:
1252 my $entries = $kdbx->entries->where(simple_expression_query(5, '>=', qw[usage_count]));
1256 Structuring a declarative query is similar to "WHERE CLAUSES" in
1257 SQL::Abstract, but you don't have to be familiar with that module. Just
1258 learn by examples here.
1260 To search for all entries in a database titled "My Bank":
1262 my $entries = $kdbx->entries->where({ title => 'My Bank' });
1264 The query here is { title => 'My Bank' }. A hashref can contain
1265 key-value pairs where the key is an attribute of the thing being
1266 searched for (in this case an entry) and the value is what you want the
1267 thing's attribute to be to consider it a match. In this case, the
1268 attribute we're using as our match criteria is "title" in
1269 File::KDBX::Entry, a text field. If an entry has its title attribute
1270 equal to "My Bank", it's a match.
1272 A hashref can contain multiple attributes. The search candidate will be
1273 a match if all of the specified attributes are equal to their
1274 respective values. For example, to search for all entries with a
1275 particular URL AND username:
1277 my $entries = $kdbx->entries->where({
1278 url => 'https://example.com',
1282 To search for entries matching any criteria, just change the hashref to
1283 an arrayref. To search for entries with a particular URL OR username:
1285 my $entries = $kdbx->entries->where([ # <-- Notice the square bracket
1286 url => 'https://example.com',
1290 You can use different operators to test different types of attributes.
1291 The "icon_id" in File::KDBX::Entry attribute is a number, so we should
1292 use a number comparison operator. To find entries using the smartphone
1295 my $entries = $kdbx->entries->where({
1296 icon_id => { '==', ICON_SMARTPHONE },
1299 Note: "ICON_SMARTPHONE" in File::KDBX::Constants is just a constant
1300 from File::KDBX::Constants. It isn't special to this example or to
1301 queries generally. We could have just used a literal number.
1303 The important thing to notice here is how we wrapped the condition in
1304 another hashref with a single key-value pair where the key is the name
1305 of an operator and the value is the thing to match against. The
1306 supported operators are:
1310 * ne - String not equal
1312 * lt - String less than
1314 * gt - String greater than
1316 * le - String less than or equal
1318 * ge - String greater than or equal
1322 * != - Number not equal
1324 * < - Number less than
1326 * > - Number greater than
1328 * <= - Number less than or equal
1330 * >= - Number less than or equal
1332 * =~ - String match regular expression
1334 * !~ - String does not match regular expression
1340 Other special operators:
1342 * -true - Boolean true
1344 * -false - Boolean false
1346 * -not - Boolean false (alias for -false)
1348 * -defined - Is defined
1350 * -undef - Is not defined
1354 * -nonempty - Is not empty
1358 * -and - Logical and
1360 Let's see another example using an explicit operator. To find all
1361 groups except one in particular (identified by its "uuid" in
1362 File::KDBX::Group), we can use the ne (string not equal) operator:
1364 my $groups = $kdbx->groups->where(
1366 'ne' => uuid('596f7520-6172-6520-7370-656369616c2e'),
1370 Note: "uuid" in File::KDBX::Util is a little utility function to
1371 convert a UUID in its pretty form into bytes. This utility function
1372 isn't special to this example or to queries generally. It could have
1373 been written with a literal such as "\x59\x6f\x75\x20\x61...", but
1374 that's harder to read.
1376 Notice we searched for groups this time. Finding groups works exactly
1377 the same as it does for entries.
1379 Notice also that we didn't wrap the query in hashref curly-braces or
1380 arrayref square-braces. Those are optional. By default it will only
1381 match ALL attributes (as if there were curly-braces).
1383 Testing the truthiness of an attribute is a little bit different
1384 because it isn't a binary operation. To find all entries with the
1385 password quality check disabled:
1387 my $entries = $kdbx->entries->where('!' => 'quality_check');
1389 This time the string after the operator is the attribute name rather
1390 than a value to compare the attribute against. To test that a boolean
1391 value is true, use the !! operator (or -true if !! seems a little too
1392 weird for your taste):
1394 my $entries = $kdbx->entries->where('!!' => 'quality_check');
1395 my $entries = $kdbx->entries->where(-true => 'quality_check'); # same thing
1397 Yes, there is also a -false and a -not if you prefer one of those over
1398 !. -false and -not (along with -true) are also special in that you can
1399 use them to invert the logic of a subquery. These are logically
1402 my $entries = $kdbx->entries->where(-not => { title => 'My Bank' });
1403 my $entries = $kdbx->entries->where(title => { 'ne' => 'My Bank' });
1405 These special operators become more useful when combined with two more
1406 special operators: -and and -or. With these, it is possible to
1407 construct more interesting queries with groups of logic. For example:
1409 my $entries = $kdbx->entries->where({
1410 title => { '=~', qr/bank/ },
1413 notes => { '=~', qr/business/ },
1414 icon_id => { '==', ICON_TRASHCAN_FULL },
1419 In English, find entries where the word "bank" appears anywhere in the
1420 title but also do not have either the word "business" in the notes or
1421 are using the full trashcan icon.
1425 Lastly, as mentioned at the top, you can ignore all this and write your
1426 own subroutine. Your subroutine will be called once for each object
1427 being searched over. The subroutine should match the candidate against
1428 whatever criteria you want and return true if it matches or false to
1429 skip. To do this, just pass your subroutine coderef to where.
1431 To review the different types of queries, these are all equivalent to
1432 find all entries in the database titled "My Bank":
1434 my $entries = $kdbx->entries->where(\'"My Bank"', 'eq', qw[title]); # simple expression
1435 my $entries = $kdbx->entries->where(title => 'My Bank'); # declarative syntax
1436 my $entries = $kdbx->entries->where(sub { $_->title eq 'My Bank' }); # subroutine query
1438 This is a trivial example, but of course your subroutine can be
1439 arbitrarily complex.
1441 All of these query mechanisms described in this section are just tools,
1442 each with its own set of limitations. If the tools are getting in your
1443 way, you can of course iterate over the contents of a database and
1444 implement your own query logic, like this:
1446 my $entries = $kdbx->entries;
1447 while (my $entry = $entries->next) {
1448 if (wanted($entry)) {
1449 do_something($entry);
1458 Iterators are the built-in way to navigate or walk the database tree.
1459 You get an iterator from "entries", "groups" and "objects". You can
1460 specify the search algorithm to iterate over objects in different
1461 orders using the algorithm option, which can be one of these constants:
1463 * ITERATION_IDS - Iterative deepening search (default)
1465 * ITERATION_DFS - Depth-first search
1467 * ITERATION_BFS - Breadth-first search
1469 When iterating over objects generically, groups always precede their
1470 direct entries (if any). When the history option is used, current
1471 entries always precede historical entries.
1473 If you have a database tree like this:
1484 * IDS order of groups is: Root, Group1, Group2, Group3
1486 * IDS order of entries is: EntryA, EntryB, EntryC
1488 * IDS order of objects is: Root, Group1, EntryA, Group2, EntryB,
1491 * DFS order of groups is: Group2, Group1, Group3, Root
1493 * DFS order of entries is: EntryB, EntryA, EntryC
1495 * DFS order of objects is: Group2, EntryB, Group1, EntryA, Group3,
1498 * BFS order of groups is: Root, Group1, Group3, Group2
1500 * BFS order of entries is: EntryA, EntryC, EntryB
1502 * BFS order of objects is: Root, Group1, EntryA, Group3, EntryC,
1507 TODO - This is a planned feature, not yet implemented.
1511 Errors in this package are constructed as File::KDBX::Error objects and
1512 propagated using perl's built-in mechanisms. Fatal errors are
1513 propagated using "die LIST" in perlfunc and non-fatal errors (a.k.a.
1514 warnings) are propagated using "warn LIST" in perlfunc while adhering
1515 to perl's warnings system. If you're already familiar with these
1516 mechanisms, you can skip this section.
1518 You can catch fatal errors using "eval BLOCK" in perlfunc (or something
1519 like Try::Tiny) and non-fatal errors using $SIG{__WARN__} (see "%SIG"
1520 in perlvar). Examples:
1522 use File::KDBX::Error qw(error);
1524 my $key = ''; # uh oh
1526 $kdbx->load_file('whatever.kdbx', $key);
1528 if (my $error = error($@)) {
1529 handle_missing_key($error) if $error->type eq 'key.missing';
1536 $kdbx->load_file('whatever.kdbx', $key);
1542 Catching non-fatal errors:
1545 local $SIG{__WARN__} = sub { push @warnings, $_[0] };
1547 $kdbx->load_file('whatever.kdbx', $key);
1549 handle_warnings(@warnings) if @warnings;
1551 By default perl prints warnings to STDERR if you don't catch them. If
1552 you don't want to catch them and also don't want them printed to
1553 STDERR, you can suppress them lexically (perl v5.28 or higher
1557 no warnings 'File::KDBX';
1564 local $File::KDBX::WARNINGS = 0;
1568 or globally in your program:
1570 $File::KDBX::WARNINGS = 0;
1572 You cannot suppress fatal errors, and if you don't catch them your
1577 This software will alter its behavior depending on the value of certain
1578 environment variables:
1580 * PERL_FILE_KDBX_XS - Do not use File::KDBX::XS if false (default:
1583 * PERL_ONLY - Do not use File::KDBX::XS if true (default: false)
1585 * NO_FORK - Do not fork if true (default: false)
1589 * KeePass Password Safe <https://keepass.info/> - The original
1592 * KeePassXC <https://keepassxc.org/> - Cross-Platform Password
1593 Manager written in C++
1595 * File::KeePass has overlapping functionality. It's good but has a
1596 backlog of some pretty critical bugs and lacks support for newer KDBX
1601 Please report any bugs or feature requests on the bugtracker website
1602 https://github.com/chazmcgarvey/File-KDBX/issues
1604 When submitting a bug or request, please include a test-file or a patch
1605 to an existing test-file that illustrates the bug or desired feature.
1609 Charles McGarvey <ccm@cpan.org>
1611 COPYRIGHT AND LICENSE
1613 This software is copyright (c) 2022 by Charles McGarvey.
1615 This is free software; you can redistribute it and/or modify it under
1616 the same terms as the Perl 5 programming language system itself.