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 a KDBX database. 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 and modify entries. The distribution also includes various parsers and
45 generators for serializing and persisting databases.
47 This 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 This implementation of KDBX supports a lot of features:
64 * ☑ Read and write KDBX version 3 - version 4.1
66 * ☑ Read and write KDB files (requires File::KeePass)
68 * ☑ Unicode character strings
70 * ☑ "Simple Expression" Searching
72 * ☑ Placeholders and field references
74 * ☑ One-time passwords
78 * ☑ "Memory Protection"
80 * ☑ Challenge-response key components, like YubiKey
82 * ☑ Variety of key file types: binary, hexed, hashed, XML v1 and v2
84 * ☑ Pluggable registration of different kinds of ciphers and key
87 * ☑ Built-in database maintenance functions
89 * ☑ Pretty fast, with XS optimizations available
91 * ☒ Database synchronization / merging (not yet)
95 A KDBX database consists of a tree of groups and entries, with a single
96 root group. Entries can contain zero or more key-value pairs of strings
97 and zero or more binaries (i.e. octet strings). Groups, entries,
98 strings and binaries: that's the KDBX vernacular. A small amount of
99 metadata (timestamps, etc.) is associated with each entry, group and
100 the database as a whole.
102 You can think of a KDBX database kind of like a file system, where
103 groups are directories, entries are files, and strings and binaries
104 make up a file's contents.
106 Databases are typically persisted as a encrypted, compressed files.
107 They are usually accessed directly (i.e. not over a network). The
108 primary focus of this type of database is data security. It is ideal
109 for storing relatively small amounts of data (strings and binaries)
110 that must remain secret except to such individuals as have the correct
111 master key. Even if the database file were to be "leaked" to the public
112 Internet, it should be virtually impossible to crack with a strong key.
113 The KDBX format is most often used by password managers to store
114 passwords so that users can know a single strong password and not have
115 to reuse passwords across different websites. See "SECURITY" for an
116 overview of security considerations.
136 Hash of UUIDs for objects that have been deleted. This includes groups,
137 entries and even custom icons.
141 Bytes contained within the encrypted layer of a KDBX file. This is only
142 set when using File::KDBX::Loader::Raw.
146 A text string associated with the database. Often unset.
150 The UUID of a cipher used to encrypt the database when stored as a
153 See "File::KDBX::Cipher".
157 Configuration for whether or not and how the database gets compressed.
158 See ":compression" in File::KDBX::Constants.
162 The master seed is a string of 32 random bytes that is used as salt in
163 hashing the master key when loading and saving the database. If a
164 challenge-response key is used in the master key, the master seed is
167 The master seed should be changed each time the database is saved to
172 The transform seed is a string of 32 random bytes that is used in the
173 key derivation function, either as the salt or the key (depending on
176 The transform seed should be changed each time the database is saved to
181 The number of rounds or iterations used in the key derivation function.
182 Increasing this number makes loading and saving the database slower by
183 design in order to make dictionary and brute force attacks more costly.
187 The initialization vector used by the cipher.
189 The encryption IV should be changed each time the database is saved to
192 inner_random_stream_key
194 The encryption key (possibly including the IV, depending on the cipher)
195 used to encrypt the protected strings within the database.
199 A string of 32 random bytes written in the header and encrypted in the
200 body. If the bytes do not match when loading a file then the wrong
201 master key was used or the file is corrupt. Only KDBX 2 and KDBX 3
202 files use this. KDBX 4 files use an improved HMAC method to verify the
203 master key and data integrity of the header and entire file body.
205 inner_random_stream_id
207 A number indicating the cipher algorithm used to encrypt the protected
208 strings within the database, usually Salsa20 or ChaCha20. See
209 ":random_stream" in File::KDBX::Constants.
213 A hash/dict of key-value pairs used to configure the key derivation
214 function. This is the KDBX4+ way to configure the KDF, superceding
215 "transform_seed" and "transform_rounds".
219 The name of the software used to generate the KDBX file.
223 The header hash used to verify that the file header is not corrupt.
224 (KDBX 2 - KDBX 3.1, removed KDBX 4.0)
228 Name of the database.
230 database_name_changed
232 Timestamp indicating when the database name was last changed.
236 Description of the database
238 database_description_changed
240 Timestamp indicating when the database description was last changed.
244 When a new entry is created, the UserName string will be populated with
247 default_username_changed
249 Timestamp indicating when the default username was last changed.
251 maintenance_history_days
253 TODO... not really sure what this is. 😀
257 A color associated with the database (in the form #ffffff where "f" is
258 a hexidecimal digit). Some agents use this to help users visually
259 distinguish between different databases.
263 Timestamp indicating when the master key was last changed.
265 master_key_change_rec
267 Number of days until the agent should prompt to recommend changing the
270 master_key_change_force
272 Number of days until the agent should prompt to force changing the
275 Note: This is purely advisory. It is up to the individual agent
276 software to actually enforce it. File::KDBX does NOT enforce it.
280 Array of custom icons that can be associated with groups and entries.
282 This list can be managed with the methods "add_custom_icon" and
283 "remove_custom_icon".
287 Boolean indicating whether removed groups and entries should go to a
288 recycle bin or be immediately deleted.
292 The UUID of a group used to store thrown-away groups and entries.
296 Timestamp indicating when the recycle bin was last changed.
298 entry_templates_group
300 The UUID of a group containing template entries used when creating new
303 entry_templates_group_changed
305 Timestamp indicating when the entry templates group was last changed.
309 The UUID of the previously-selected group.
311 last_top_visible_group
313 The UUID of the group visible at the top of the list.
317 The maximum number of historical entries allowed to be saved for each
322 The maximum total size (in bytes) that each individual entry's history
327 Timestamp indicating when the database settings were last updated.
331 Alias of the "memory_protection" setting for the Title string.
335 Alias of the "memory_protection" setting for the UserName string.
339 Alias of the "memory_protection" setting for the Password string.
343 Alias of the "memory_protection" setting for the URL string.
347 Alias of the "memory_protection" setting for the Notes string.
353 $kdbx = File::KDBX->new(%attributes);
354 $kdbx = File::KDBX->new($kdbx); # copy constructor
356 Construct a new File::KDBX.
360 $kdbx = $kdbx->init(%attributes);
362 Initialize a File::KDBX with a set of attributes. Returns itself to
363 allow method chaining.
365 This is called by "new".
369 $kdbx = $kdbx->reset;
371 Set a File::KDBX to an empty state, ready to load a KDBX file or build
372 a new one. Returns itself to allow method chaining.
376 $kdbx_copy = $kdbx->clone;
377 $kdbx_copy = File::KDBX->new($kdbx);
379 Clone a File::KDBX. The clone will be an exact copy and completely
380 independent of the original.
390 $kdbx = KDBX::File->load(\$string, $key);
391 $kdbx = KDBX::File->load(*IO, $key);
392 $kdbx = KDBX::File->load($filepath, $key);
393 $kdbx->load(...); # also instance method
395 $kdbx = File::KDBX->load_string($string, $key);
396 $kdbx = File::KDBX->load_string(\$string, $key);
397 $kdbx->load_string(...); # also instance method
399 $kdbx = File::KDBX->load_file($filepath, $key);
400 $kdbx->load_file(...); # also instance method
402 $kdbx = File::KDBX->load_handle($fh, $key);
403 $kdbx = File::KDBX->load_handle(*IO, $key);
404 $kdbx->load_handle(...); # also instance method
406 Load a KDBX file from a string buffer, IO handle or file from a
409 File::KDBX::Loader does the heavy lifting.
419 $kdbx->dump(\$string, $key);
420 $kdbx->dump(*IO, $key);
421 $kdbx->dump($filepath, $key);
423 $kdbx->dump_string(\$string, $key);
424 \$string = $kdbx->dump_string($key);
426 $kdbx->dump_file($filepath, $key);
428 $kdbx->dump_handle($fh, $key);
429 $kdbx->dump_handle(*IO, $key);
431 Dump a KDBX file to a string buffer, IO handle or file in a filesystem.
433 File::KDBX::Dumper does the heavy lifting.
437 $string = $kdbx->user_agent_string;
439 Get a text string identifying the database client software.
443 \%settings = $kdbx->memory_protection
444 $kdbx->memory_protection(\%settings);
446 $bool = $kdbx->memory_protection($string_key);
447 $kdbx->memory_protection($string_key => $bool);
449 Get or set memory protection settings. This globally (for the whole
450 database) configures whether and which of the standard strings should
451 be memory-protected. The default setting is to memory-protect only
454 Memory protection can be toggled individually for each entry string,
455 and individual settings take precedence over these global settings.
459 $version = $kdbx->minimum_version;
461 Determine the minimum file version required to save a database
462 losslessly. Using certain databases features might increase this value.
463 For example, setting the KDF to Argon2 will increase the minimum
464 version to at least KDBX_VERSION_4_0 (i.e. 0x00040000) because Argon2
465 was introduced with KDBX4.
467 This method never returns less than KDBX_VERSION_3_1 (i.e. 0x00030001).
468 That file version is so ubiquitious and well-supported, there are
469 seldom reasons to dump in a lesser format nowadays.
471 WARNING: If you dump a database with a minimum version higher than the
472 current "version", the dumper will typically issue a warning and
473 automatically upgrade the database. This seems like the safest behavior
474 in order to avoid data loss, but lower versions have the benefit of
475 being compatible with more software. It is possible to prevent
476 auto-upgrades by explicitly telling the dumper which version to use,
477 but you do run the risk of data loss. A database will never be
478 automatically downgraded.
482 $group = $kdbx->root;
485 Get or set a database's root group. You don't necessarily need to
486 explicitly create or set a root group because it autovivifies when
487 adding entries and groups to the database.
489 Every database has only a single root group at a time. Some old KDB
490 files might have multiple root groups. When reading such files, a
491 single implicit root group is created to contain the actual root
492 groups. When writing to such a format, if the root group looks like it
493 was implicitly created then it won't be written and the resulting file
494 might have multiple root groups. This allows working with older files
495 without changing their written internal structure while still adhering
496 to modern semantics while the database is opened.
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 (aka parent) - Group object or group UUID to add the group to
554 (default: root group)
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 (aka parent) - Group object or group UUID to add the entry to
580 (default: root group)
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 binaries strings in a database. The encrypted
788 strings are stored in a File::KDBX::Safe associated with the database
789 and the actual strings will be replaced with undef to indicate their
790 protected state. Returns itself to allow method chaining.
792 You can call code 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 in a database, replacing undef
801 placeholders with unprotected values. Returns itself to allow method
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".
816 $string = $kdbx->peek(\%string);
817 $string = $kdbx->peek(\%binary);
819 Peek at the value of a protected string or binary without unlocking the
820 whole database. The argument can be a string or binary hashref as
821 returned by "string" in File::KDBX::Entry or "binary" in
826 $bool = $kdbx->is_locked;
828 Get whether or not a database's strings are memory-protected. If this
829 is true, then some or all of the protected strings within the database
830 will be unavailable (literally have undef values) until "unlock" is
835 $kdbx->remove_empty_groups;
837 Remove groups with no subgroups and no entries.
841 $kdbx->remove_unused_icons;
843 Remove icons that are not associated with any entry or group in the
846 remove_duplicate_icons
848 $kdbx->remove_duplicate_icons;
850 Remove duplicate icons as determined by hashing the icon data.
854 $kdbx->prune_history(%options);
856 Remove just as many older historical entries as necessary to get under
859 * max_items - Maximum number of historical entries to keep (default:
860 value of "history_max_items", no limit: -1)
862 * max_size - Maximum total size (in bytes) of historical entries to
863 keep (default: value of "history_max_size", no limit: -1)
865 * max_age - Maximum age (in days) of historical entries to keep
866 (default: 365, no limit: -1)
870 $kdbx->randomize_seeds;
872 Set various keys, seeds and IVs to random values. These values are used
873 by the cryptographic functions that secure the database when dumped.
874 The attributes that will be randomized are:
878 * "inner_random_stream_key"
882 * "stream_start_bytes"
886 Randomizing these values has no effect on a loaded database. These are
887 only used when a database is dumped. You normally do not need to call
888 this method explicitly because the dumper does it explicitly by
894 $key = $kdbx->key($key);
895 $key = $kdbx->key($primitive);
897 Get or set a File::KDBX::Key. This is the master key (e.g. a password
898 or a key file that can decrypt a database). See "new" in
899 File::KDBX::Key for an explanation of what the primitive can be.
901 You generally don't need to call this directly because you can provide
902 the key directly to the loader or dumper when loading or dumping a KDBX
907 $key = $kdbx->composite_key($key);
908 $key = $kdbx->composite_key($primitive);
910 Construct a File::KDBX::Key::Composite from a primitive. See "new" in
911 File::KDBX::Key for an explanation of what the primitive can be. If the
912 primitive does not represent a composite key, it will be wrapped.
914 You generally don't need to call this directly. The parser and writer
915 use it to transform a master key into a raw encryption key.
919 $kdf = $kdbx->kdf(%options);
920 $kdf = $kdbx->kdf(\%parameters, %options);
922 Get a File::KDBX::KDF (key derivation function).
926 * params - KDF parameters, same as \%parameters (default: value of
931 $cipher = $kdbx->cipher(key => $key);
932 $cipher = $kdbx->cipher(key => $key, iv => $iv, uuid => $uuid);
934 Get a File::KDBX::Cipher capable of encrypting and decrypting the body
937 A key is required. This should be a raw encryption key made up of a
938 fixed number of octets (depending on the cipher), not a File::KDBX::Key
941 If not passed, the UUID comes from $kdbx->headers->{cipher_id} and the
942 encryption IV comes from $kdbx->headers->{encryption_iv}.
944 You generally don't need to call this directly. The parser and writer
945 use it to decrypt and encrypt KDBX files.
949 $cipher = $kdbx->random_stream;
950 $cipher = $kdbx->random_stream(id => $stream_id, key => $key);
952 Get a File::KDBX::Cipher::Stream for decrypting and encrypting
955 If not passed, the ID and encryption key comes from
956 $kdbx->headers->{inner_random_stream_id} and
957 $kdbx->headers->{inner_random_stream_key} (respectively) for KDBX3
958 files and from $kdbx->inner_headers->{inner_random_stream_key} and
959 $kdbx->inner_headers->{inner_random_stream_id} (respectively) for KDBX4
962 You generally don't need to call this directly. The parser and writer
963 use it to scramble protected strings.
967 Create a new database
969 my $kdbx = File::KDBX->new;
971 my $group = $kdbx->add_group(name => 'Passwords);
972 my $entry = $group->add_entry(
973 title => 'WayneCorp',
974 username => 'bwayne',
975 password => 'iambatman',
976 url => 'https://example.com/login'
978 $entry->add_auto_type_window_association('WayneCorp - Mozilla Firefox', '{PASSWORD}{ENTER}');
980 $kdbx->dump_file('mypasswords.kdbx', 'master password CHANGEME');
982 Read an existing database
984 my $kdbx = File::KDBX->load_file('mypasswords.kdbx', 'master password CHANGEME');
985 $kdbx->unlock; # cause $entry->password below to be defined
987 $kdbx->entries->each(sub {
989 say 'Found password for: ', $entry->title;
990 say ' Username: ', $entry->username;
991 say ' Password: ', $entry->password;
996 my @entries = $kdbx->entries(searching => 1)
997 ->grep(title => 'WayneCorp')
998 ->each; # return all matches
1000 The searching option limits results to only entries within groups with
1001 searching enabled. Other options are also available. See "entries".
1003 See "QUERY" for many more query examples.
1005 Search for entries by auto-type window association
1007 my $window_title = 'WayneCorp - Mozilla Firefox';
1009 my $entries = $kdbx->entries(auto_type => 1)
1011 my ($ata) = grep { $_->{window} =~ /\Q$window_title\E/i } @{$_->auto_type_associations};
1012 return [$_, $ata->{keystroke_sequence}] if $ata;
1015 my ($entry, $keys) = @$_;
1016 say 'Entry title: ', $entry->title, ', key sequence: ', $keys;
1021 Entry title: WayneCorp, key sequence: {PASSWORD}{ENTER}
1023 Remove entries from a database
1026 ->grep(notes => {'=~' => qr/too old/i})
1027 ->each(sub { $_->recycle });
1029 Recycle all entries with the string "too old" appearing in the Notes
1034 $kdbx->groups(algorithm => 'dfs')
1035 ->where(-true => 'is_empty')
1038 With the search/iteration algorithm set to "dfs", groups will be
1039 ordered deepest first and the root group will be last. This allows
1040 removing groups that only contain empty groups.
1042 This can also be done with one call to "remove_empty_groups".
1046 One of the biggest threats to your database security is how easily the
1047 encryption key can be brute-forced. Strong brute-force protection
1050 * Using unguessable passwords, passphrases and key files.
1052 * Using a brute-force resistent key derivation function.
1054 The first factor is up to you. This module does not enforce strong
1055 master keys. It is up to you to pick or generate strong keys.
1057 The KDBX format allows for the key derivation function to be tuned. The
1058 idea is that you want each single brute-foce attempt to be expensive
1059 (in terms of time, CPU usage or memory usage), so that making a lot of
1060 attempts (which would be required if you have a strong master key) gets
1063 How expensive you want to make each attempt is up to you and can depend
1066 This and other KDBX-related security issues are covered here more in
1067 depth: https://keepass.info/help/base/security.html
1069 Here are other security risks you should be thinking about:
1073 This distribution uses the excellent CryptX and Crypt::Argon2 packages
1074 to handle all crypto-related functions. As such, a lot of the security
1075 depends on the quality of these dependencies. Fortunately these modules
1076 are maintained and appear to have good track records.
1078 The KDBX format has evolved over time to incorporate improved security
1079 practices and cryptographic functions. This package uses the following
1080 functions for authentication, hashing, encryption and random number
1087 * Argon2d & Argon2id
1097 * Salsa20 & ChaCha20
1101 At the time of this writing, I am not aware of any successful attacks
1102 against any of these functions. These are among the most-analyzed and
1103 widely-adopted crypto functions available.
1105 The KDBX format allows the body cipher and key derivation function to
1106 be configured. If a flaw is discovered in one of these functions, you
1107 can hopefully just switch to a better function without needing to
1108 update this software. A later software release may phase out the use of
1109 any functions which are no longer secure.
1113 It is not a good idea to keep secret information unencrypted in system
1114 memory for longer than is needed. The address space of your program can
1115 generally be read by a user with elevated privileges on the system. If
1116 your system is memory-constrained or goes into a hibernation mode, the
1117 contents of your address space could be written to a disk where it
1118 might be persisted for long time.
1120 There might be system-level things you can do to reduce your risk, like
1121 using swap encryption and limiting system access to your program's
1122 address space while your program is running.
1124 File::KDBX helps minimize (but not eliminate) risk by keeping secrets
1125 encrypted in memory until accessed and zeroing out memory that holds
1126 secrets after they're no longer needed, but it's not a silver bullet.
1128 For one thing, the encryption key is stored in the same address space.
1129 If core is dumped, the encryption key is available to be found out. But
1130 at least there is the chance that the encryption key and the encrypted
1131 secrets won't both be paged out together while memory-constrained.
1133 Another problem is that some perls (somewhat notoriously) copy around
1134 memory behind the scenes willy nilly, and it's difficult know when perl
1135 makes a copy of a secret in order to be able to zero it out later. It
1136 might be impossible. The good news is that perls with SvPV
1137 copy-on-write (enabled by default beginning with perl 5.20) are much
1138 better in this regard. With COW, it's mostly possible to know what
1139 operations will cause perl to copy the memory of a scalar string, and
1140 the number of copies will be significantly reduced. There is a unit
1141 test named t/memory-protection.t in this distribution that can be run
1142 on POSIX systems to determine how well File::KDBX memory protection is
1145 Memory protection also depends on how your application handles secrets.
1146 If your app code is handling scalar strings with secret information,
1147 it's up to you to make sure its memory is zeroed out when no longer
1148 needed. "erase" in File::KDBX::Util et al. provide some tools to help
1149 accomplish this. Or if you're not too concerned about the risks memory
1150 protection is meant to mitigate, then maybe don't worry about it. The
1151 security policy of File::KDBX is to try hard to keep secrets protected
1152 while in memory so that your app might claim a high level of security,
1153 in case you care about that.
1155 There are some memory protection strategies that File::KDBX does NOT
1156 use today but could in the future:
1158 Many systems allow programs to mark unswappable pages. Secret
1159 information should ideally be stored in such pages. You could
1160 potentially use mlockall(2) (or equivalent for your system) in your own
1161 application to prevent the entire address space from being swapped.
1163 Some systems provide special syscalls for storing secrets in memory
1164 while keeping the encryption key outside of the program's address
1165 space, like CryptProtectMemory for Windows. This could be a good
1166 option, though unfortunately not portable.
1170 To find things in a KDBX database, you should use a filtered iterator.
1171 If you have an iterator, such as returned by "entries", "groups" or
1172 even "objects" you can filter it using "where" in File::KDBX::Iterator.
1174 my $filtered_entries = $kdbx->entries->where($query);
1176 A $query is just a subroutine that you can either write yourself or
1177 have generated for you from either a "Simple Expression" or
1178 "Declarative Syntax". It's easier to have your query generated, so I'll
1183 A simple expression is mostly compatible with the KeePass 2
1184 implementation described here
1185 <https://keepass.info/help/base/search.html#mode_se>.
1187 An expression is a string with one or more space-separated terms. Terms
1188 with spaces can be enclosed in double quotes. Terms are negated if they
1189 are prefixed with a minus sign. A record must match every term on at
1190 least one of the given fields.
1192 So a simple expression is something like what you might type into a
1193 search engine. You can generate a simple expression query using
1194 "simple_expression_query" in File::KDBX::Util or by passing the simple
1195 expression as a scalar reference to where.
1197 To search for all entries in a database with the word "canyon"
1198 appearing anywhere in the title:
1200 my $entries = $kdbx->entries->where(\'canyon', qw[title]);
1202 Notice the first argument is a scalarref. This disambiguates a simple
1203 expression from other types of queries covered below.
1205 As mentioned, a simple expression can have multiple terms. This simple
1206 expression query matches any entry that has the words "red" and
1207 "canyon" anywhere in the title:
1209 my $entries = $kdbx->entries->where(\'red canyon', qw[title]);
1211 Each term in the simple expression must be found for an entry to match.
1213 To search for entries with "red" in the title but not "canyon", just
1214 prepend "canyon" with a minus sign:
1216 my $entries = $kdbx->entries->where(\'red -canyon', qw[title]);
1218 To search over multiple fields simultaneously, just list them all. To
1219 search for entries with "grocery" (but not "Foodland") in the title or
1222 my $entries = $kdbx->entries->where(\'grocery -Foodland', qw[title notes]);
1224 The default operator is a case-insensitive regexp match, which is fine
1225 for searching text loosely. You can use just about any binary
1226 comparison operator that perl supports. To specify an operator, list it
1227 after the simple expression. For example, to search for any entry that
1228 has been used at least five times:
1230 my $entries = $kdbx->entries->where(\5, '>=', qw[usage_count]);
1232 It helps to read it right-to-left, like "usage_count is greater than or
1235 If you find the disambiguating structures to be distracting or
1236 confusing, you can also the "simple_expression_query" in
1237 File::KDBX::Util function as a more intuitive alternative. The
1238 following example is equivalent to the previous:
1240 my $entries = $kdbx->entries->where(simple_expression_query(5, '>=', qw[usage_count]));
1244 Structuring a declarative query is similar to "WHERE CLAUSES" in
1245 SQL::Abstract, but you don't have to be familiar with that module. Just
1246 learn by examples here.
1248 To search for all entries in a database titled "My Bank":
1250 my $entries = $kdbx->entries->where({ title => 'My Bank' });
1252 The query here is { title => 'My Bank' }. A hashref can contain
1253 key-value pairs where the key is an attribute of the thing being
1254 searched for (in this case an entry) and the value is what you want the
1255 thing's attribute to be to consider it a match. In this case, the
1256 attribute we're using as our match criteria is "title" in
1257 File::KDBX::Entry, a text field. If an entry has its title attribute
1258 equal to "My Bank", it's a match.
1260 A hashref can contain multiple attributes. The search candidate will be
1261 a match if all of the specified attributes are equal to their
1262 respective values. For example, to search for all entries with a
1263 particular URL AND username:
1265 my $entries = $kdbx->entries->where({
1266 url => 'https://example.com',
1270 To search for entries matching any criteria, just change the hashref to
1271 an arrayref. To search for entries with a particular URL OR username:
1273 my $entries = $kdbx->entries->where([ # <-- Notice the square bracket
1274 url => 'https://example.com',
1278 You can use different operators to test different types of attributes.
1279 The "icon_id" in File::KDBX::Entry attribute is a number, so we should
1280 use a number comparison operator. To find entries using the smartphone
1283 my $entries = $kdbx->entries->where({
1284 icon_id => { '==', ICON_SMARTPHONE },
1287 Note: "ICON_SMARTPHONE" in File::KDBX::Constants is just a constant
1288 from File::KDBX::Constants. It isn't special to this example or to
1289 queries generally. We could have just used a literal number.
1291 The important thing to notice here is how we wrapped the condition in
1292 another arrayref with a single key-value pair where the key is the name
1293 of an operator and the value is the thing to match against. The
1294 supported operators are:
1298 * ne - String not equal
1300 * lt - String less than
1302 * gt - String greater than
1304 * le - String less than or equal
1306 * ge - String greater than or equal
1310 * != - Number not equal
1312 * < - Number less than
1314 * >> - Number greater than
1316 * <= - Number less than or equal
1318 * >= - Number less than or equal
1320 * =~ - String match regular expression
1322 * !~ - String does not match regular expression
1328 Other special operators:
1330 * -true - Boolean true
1332 * -false - Boolean false
1334 * -not - Boolean false (alias for -false)
1336 * -defined - Is defined
1338 * -undef - Is not defined
1342 * -nonempty - Is not empty
1346 * -and - Logical and
1348 Let's see another example using an explicit operator. To find all
1349 groups except one in particular (identified by its "uuid" in
1350 File::KDBX::Group), we can use the ne (string not equal) operator:
1352 my $groups = $kdbx->groups->where(
1354 'ne' => uuid('596f7520-6172-6520-7370-656369616c2e'),
1358 Note: "uuid" in File::KDBX::Util is a little utility function to
1359 convert a UUID in its pretty form into bytes. This utility function
1360 isn't special to this example or to queries generally. It could have
1361 been written with a literal such as "\x59\x6f\x75\x20\x61...", but
1362 that's harder to read.
1364 Notice we searched for groups this time. Finding groups works exactly
1365 the same as it does for entries.
1367 Notice also that we didn't wrap the query in hashref curly-braces or
1368 arrayref square-braces. Those are optional. By default it will only
1369 match ALL attributes (as if there were curly-braces).
1371 Testing the truthiness of an attribute is a little bit different
1372 because it isn't a binary operation. To find all entries with the
1373 password quality check disabled:
1375 my $entries = $kdbx->entries->where('!' => 'quality_check');
1377 This time the string after the operator is the attribute name rather
1378 than a value to compare the attribute against. To test that a boolean
1379 value is true, use the !! operator (or -true if !! seems a little too
1380 weird for your taste):
1382 my $entries = $kdbx->entries->where('!!' => 'quality_check');
1383 my $entries = $kdbx->entries->where(-true => 'quality_check'); # same thing
1385 Yes, there is also a -false and a -not if you prefer one of those over
1386 !. -false and -not (along with -true) are also special in that you can
1387 use them to invert the logic of a subquery. These are logically
1390 my $entries = $kdbx->entries->where(-not => { title => 'My Bank' });
1391 my $entries = $kdbx->entries->where(title => { 'ne' => 'My Bank' });
1393 These special operators become more useful when combined with two more
1394 special operators: -and and -or. With these, it is possible to
1395 construct more interesting queries with groups of logic. For example:
1397 my $entries = $kdbx->entries->where({
1398 title => { '=~', qr/bank/ },
1401 notes => { '=~', qr/business/ },
1402 icon_id => { '==', ICON_TRASHCAN_FULL },
1407 In English, find entries where the word "bank" appears anywhere in the
1408 title but also do not have either the word "business" in the notes or
1409 are using the full trashcan icon.
1413 Lastly, as mentioned at the top, you can ignore all this and write your
1414 own subroutine. Your subroutine will be called once for each object
1415 being searched over. The subroutine should match the candidate against
1416 whatever criteria you want and return true if it matches or false to
1417 skip. To do this, just pass your subroutine coderef to where.
1419 To review the different types of queries, these are all equivalent to
1420 find all entries in the database titled "My Bank":
1422 my $entries = $kdbx->entries->where(\'"My Bank"', 'eq', qw[title]); # simple expression
1423 my $entries = $kdbx->entries->where(title => 'My Bank'); # declarative syntax
1424 my $entries = $kdbx->entries->where(sub { $_->title eq 'My Bank' }); # subroutine query
1426 This is a trivial example, but of course your subroutine can be
1427 arbitrarily complex.
1429 All of these query mechanisms described in this section are just tools,
1430 each with its own set of limitations. If the tools are getting in your
1431 way, you can of course iterate over the contents of a database and
1432 implement your own query logic, like this:
1434 my $entries = $kdbx->entries;
1435 while (my $entry = $entries->next) {
1436 if (wanted($entry)) {
1437 do_something($entry);
1446 Iterators are the built-in way to navigate or walk the database tree.
1447 You get an iterator from "entries", "groups" and "objects". You can
1448 specify the search algorithm to iterate over objects in different
1449 orders using the algorith option, which can be one of these constants:
1451 * ITERATION_IDS - Iterative deepening search (default)
1453 * ITERATION_DFS - Depth-first search
1455 * ITERATION_BFS - Breadth-first search
1457 When iterating over objects generically, groups always precede their
1458 direct entries (if any). When the history option is used, current
1459 entries always precede historical entries.
1461 If you have a database tree like this:
1472 IDS order of groups is: Root, Group1, Group2, Group3 IDS order of
1473 entries is: EntryA, EntryB, EntryC IDS order of objects is: Root,
1474 Group1, EntryA, Group2, EntryB, Group3, EntryC
1476 DFS order of groups is: Group2, Group1, Group3, Root DFS order of
1477 entries is: EntryB, EntryA, EntryC DFS order of objects is: Group2,
1478 EntryB, Group1, EntryA, Group3, EntryC, Root
1480 BFS order of groups is: Root, Group1, Group3, Group2 BFS order of
1481 entries is: EntryA, EntryC, EntryB BFS order of objects is: Root,
1482 Group1, EntryA, Group3, EntryC, Group2, EntryB
1486 TODO - This is a planned feature, not yet implemented.
1490 Errors in this package are constructed as File::KDBX::Error objects and
1491 propagated using perl's built-in mechanisms. Fatal errors are
1492 propagated using "die" in functions and non-fatal errors (a.k.a.
1493 warnings) are propagated using "warn" in functions while adhering to
1494 perl's warnings system. If you're already familiar with these
1495 mechanisms, you can skip this section.
1497 You can catch fatal errors using "eval" in functions (or something like
1498 Try::Tiny) and non-fatal errors using $SIG{__WARN__} (see "%SIG" in
1499 variables). Examples:
1501 use File::KDBX::Error qw(error);
1503 my $key = ''; # uh oh
1505 $kdbx->load_file('whatever.kdbx', $key);
1507 if (my $error = error($@)) {
1508 handle_missing_key($error) if $error->type eq 'key.missing';
1515 $kdbx->load_file('whatever.kdbx', $key);
1521 Catching non-fatal errors:
1524 local $SIG{__WARN__} = sub { push @warnings, $_[0] };
1526 $kdbx->load_file('whatever.kdbx', $key);
1528 handle_warnings(@warnings) if @warnings;
1530 By default perl prints warnings to STDERR if you don't catch them. If
1531 you don't want to catch them and also don't want them printed to
1532 STDERR, you can suppress them lexically (perl v5.28 or higher
1536 no warnings 'File::KDBX';
1543 local $File::KDBX::WARNINGS = 0;
1547 or globally in your program:
1549 $File::KDBX::WARNINGS = 0;
1551 You cannot suppress fatal errors, and if you don't catch them your
1556 This software will alter its behavior depending on the value of certain
1557 environment variables:
1559 * PERL_FILE_KDBX_XS - Do not use File::KDBX::XS if false (default:
1562 * PERL_ONLY - Do not use File::KDBX::XS if true (default: false)
1564 * NO_FORK - Do not fork if true (default: false)
1568 Some features (e.g. parsing) require 64-bit perl. It should be possible
1569 and actually pretty easy to make it work using Math::BigInt, but I need
1570 to build a 32-bit perl in order to test it and frankly I'm still
1571 figuring out how. I'm sure it's simple so I'll mark this one "TODO",
1572 but for now an exception will be thrown when trying to use such
1573 features with undersized IVs.
1577 * KeePass Password Safe <https://keepass.info/> - The original
1580 * KeePassXC <https://keepassxc.org/> - Cross-Platform Password
1581 Manager written in C++
1583 * File::KeePass has overlapping functionality. It's good but has a
1584 backlog of some pretty critical bugs and lacks support for newer KDBX
1589 Please report any bugs or feature requests on the bugtracker website
1590 https://github.com/chazmcgarvey/File-KDBX/issues
1592 When submitting a bug or request, please include a test-file or a patch
1593 to an existing test-file that illustrates the bug or desired feature.
1597 Charles McGarvey <ccm@cpan.org>
1599 COPYRIGHT AND LICENSE
1601 This software is copyright (c) 2022 by Charles McGarvey.
1603 This is free software; you can redistribute it and/or modify it under
1604 the same terms as the Perl 5 programming language system itself.