]> Dogcows Code - chaz/p5-File-KDBX/blob - README.md
Release File-KDBX 0.902
[chaz/p5-File-KDBX] / README.md
1 [![Linux](https://github.com/chazmcgarvey/File-KDBX/actions/workflows/linux.yml/badge.svg)](https://github.com/chazmcgarvey/File-KDBX/actions/workflows/linux.yml)
2 [![macOS](https://github.com/chazmcgarvey/File-KDBX/actions/workflows/macos.yml/badge.svg)](https://github.com/chazmcgarvey/File-KDBX/actions/workflows/macos.yml)
3 [![Windows](https://github.com/chazmcgarvey/File-KDBX/actions/workflows/windows.yml/badge.svg)](https://github.com/chazmcgarvey/File-KDBX/actions/workflows/windows.yml)
4
5 # NAME
6
7 File::KDBX - Encrypted database to store secret text and files
8
9 # VERSION
10
11 version 0.902
12
13 # SYNOPSIS
14
15 ```perl
16 use File::KDBX;
17
18 # Create a new database from scratch
19 my $kdbx = File::KDBX->new;
20
21 # Add some objects to the database
22 my $group = $kdbx->add_group(
23 name => 'Passwords',
24 );
25 my $entry = $group->add_entry(
26 title => 'My Bank',
27 username => 'mreynolds',
28 password => 's3cr3t',
29 );
30
31 # Save the database to the filesystem
32 $kdbx->dump_file('passwords.kdbx', 'M@st3rP@ssw0rd!');
33
34 # Load the database from the filesystem into a new database instance
35 my $kdbx2 = File::KDBX->load_file('passwords.kdbx', 'M@st3rP@ssw0rd!');
36
37 # Iterate over database entries, print entry titles
38 $kdbx2->entries->each(sub {
39 my ($entry) = @_;
40 say 'Entry: ', $entry->title;
41 });
42 ```
43
44 See ["RECIPES"](#recipes) for more examples.
45
46 # DESCRIPTION
47
48 **File::KDBX** provides everything you need to work with KDBX databases. A KDBX database is a hierarchical
49 object database which is commonly used to store secret information securely. It was developed for the KeePass
50 password safe. See ["Introduction to KDBX"](#introduction-to-kdbx) for more information about KDBX.
51
52 This module lets you query entries, create new entries, delete entries, modify entries and more. The
53 distribution also includes various parsers and generators for serializing and persisting databases.
54
55 The design of this software was influenced by the [KeePassXC](https://github.com/keepassxreboot/keepassxc)
56 implementation of KeePass as well as the [File::KeePass](https://metacpan.org/pod/File%3A%3AKeePass) module. **File::KeePass** is an alternative module
57 that works well in most cases but has a small backlog of bugs and security issues and also does not work with
58 newer KDBX version 4 files. If you're coming here from the **File::KeePass** world, you might be interested in
59 [File::KeePass::KDBX](https://metacpan.org/pod/File%3A%3AKeePass%3A%3AKDBX) that is a drop-in replacement for **File::KeePass** that uses **File::KDBX** for storage.
60
61 This software is a **pre-1.0 release**. The interface should be considered pretty stable, but there might be
62 minor changes up until a 1.0 release. Breaking changes will be noted in the `Changes` file.
63
64 ## Features
65
66 - ☑ Read and write KDBX version 3 - version 4.1
67 - ☑ Read and write KDB files (requires [File::KeePass](https://metacpan.org/pod/File%3A%3AKeePass))
68 - ☑ Unicode character strings
69 - ☑ ["Simple Expression"](#simple-expression) Searching
70 - ☑ [Placeholders](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AEntry#Placeholders) and [field references](#resolve_reference)
71 - ☑ [One-time passwords](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AEntry#One-time-Passwords)
72 - ☑ [Very secure](#security)
73 - ☑ ["Memory Protection"](#memory-protection)
74 - ☑ Challenge-response key components, like [YubiKey](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AKey%3A%3AYubiKey)
75 - ☑ Variety of [key file](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AKey%3A%3AFile) types: binary, hexed, hashed, XML v1 and v2
76 - ☑ Pluggable registration of different kinds of ciphers and key derivation functions
77 - ☑ Built-in database maintenance functions
78 - ☑ Pretty fast, with [XS optimizations](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AXS) available
79 - ☒ Database synchronization / merging (not yet)
80
81 ## Introduction to KDBX
82
83 A KDBX database consists of a tree of _groups_ and _entries_, with a single _root_ group. Entries can
84 contain zero or more key-value pairs of _strings_ and zero or more _binaries_ (i.e. octet strings). Groups,
85 entries, strings and binaries: that's the KDBX vernacular. A small amount of metadata (timestamps, etc.) is
86 associated with each entry, group and the database as a whole.
87
88 You can think of a KDBX database kind of like a file system, where groups are directories, entries are files,
89 and strings and binaries make up a file's contents.
90
91 Databases are typically persisted as encrypted, compressed files. They are usually accessed directly (i.e.
92 not over a network). The primary focus of this type of database is data security. It is ideal for storing
93 relatively small amounts of data (strings and binaries) that must remain secret except to such individuals as
94 have the correct _master key_. Even if the database file were to be "leaked" to the public Internet, it
95 should be virtually impossible to crack with a strong key. The KDBX format is most often used by password
96 managers to store passwords so that users can know a single strong password and not have to reuse passwords
97 across different websites. See ["SECURITY"](#security) for an overview of security considerations.
98
99 # ATTRIBUTES
100
101 ## sig1
102
103 ## sig2
104
105 ## version
106
107 ## headers
108
109 ## inner\_headers
110
111 ## meta
112
113 ## binaries
114
115 ## deleted\_objects
116
117 Hash of UUIDs for objects that have been deleted. This includes groups, entries and even custom icons.
118
119 ## raw
120
121 Bytes contained within the encrypted layer of a KDBX file. This is only set when using
122 [File::KDBX::Loader::Raw](https://metacpan.org/pod/File%3A%3AKDBX%3A%3ALoader%3A%3ARaw).
123
124 ## comment
125
126 A text string associated with the database. Often unset.
127
128 ## cipher\_id
129
130 The UUID of a cipher used to encrypt the database when stored as a file.
131
132 See [File::KDBX::Cipher](https://metacpan.org/pod/File%3A%3AKDBX%3A%3ACipher).
133
134 ## compression\_flags
135
136 Configuration for whether or not and how the database gets compressed. See
137 [":compression" in File::KDBX::Constants](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AConstants#compression).
138
139 ## master\_seed
140
141 The master seed is a string of 32 random bytes that is used as salt in hashing the master key when loading
142 and saving the database. If a challenge-response key is used in the master key, the master seed is also the
143 challenge.
144
145 The master seed _should_ be changed each time the database is saved to file.
146
147 ## transform\_seed
148
149 The transform seed is a string of 32 random bytes that is used in the key derivation function, either as the
150 salt or the key (depending on the algorithm).
151
152 The transform seed _should_ be changed each time the database is saved to file.
153
154 ## transform\_rounds
155
156 The number of rounds or iterations used in the key derivation function. Increasing this number makes loading
157 and saving the database slower by design in order to make dictionary and brute force attacks more costly.
158
159 ## encryption\_iv
160
161 The initialization vector used by the cipher.
162
163 The encryption IV _should_ be changed each time the database is saved to file.
164
165 ## inner\_random\_stream\_key
166
167 The encryption key (possibly including the IV, depending on the cipher) used to encrypt the protected strings
168 within the database.
169
170 ## stream\_start\_bytes
171
172 A string of 32 random bytes written in the header and encrypted in the body. If the bytes do not match when
173 loading a file then the wrong master key was used or the file is corrupt. Only KDBX 2 and KDBX 3 files use
174 this. KDBX 4 files use an improved HMAC method to verify the master key and data integrity of the header and
175 entire file body.
176
177 ## inner\_random\_stream\_id
178
179 A number indicating the cipher algorithm used to encrypt the protected strings within the database, usually
180 Salsa20 or ChaCha20. See [":random\_stream" in File::KDBX::Constants](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AConstants#random_stream).
181
182 ## kdf\_parameters
183
184 A hash/dict of key-value pairs used to configure the key derivation function. This is the KDBX4+ way to
185 configure the KDF, superceding ["transform\_seed"](#transform_seed) and ["transform\_rounds"](#transform_rounds).
186
187 ## generator
188
189 The name of the software used to generate the KDBX file.
190
191 ## header\_hash
192
193 The header hash used to verify that the file header is not corrupt. (KDBX 2 - KDBX 3.1, removed KDBX 4.0)
194
195 ## database\_name
196
197 Name of the database.
198
199 ## database\_name\_changed
200
201 Timestamp indicating when the database name was last changed.
202
203 ## database\_description
204
205 Description of the database
206
207 ## database\_description\_changed
208
209 Timestamp indicating when the database description was last changed.
210
211 ## default\_username
212
213 When a new entry is created, the _UserName_ string will be populated with this value.
214
215 ## default\_username\_changed
216
217 Timestamp indicating when the default username was last changed.
218
219 ## color
220
221 A color associated with the database (in the form `#ffffff` where "f" is a hexidecimal digit). Some agents
222 use this to help users visually distinguish between different databases.
223
224 ## master\_key\_changed
225
226 Timestamp indicating when the master key was last changed.
227
228 ## master\_key\_change\_rec
229
230 Number of days until the agent should prompt to recommend changing the master key.
231
232 ## master\_key\_change\_force
233
234 Number of days until the agent should prompt to force changing the master key.
235
236 Note: This is purely advisory. It is up to the individual agent software to actually enforce it.
237 **File::KDBX** does NOT enforce it.
238
239 ## custom\_icons
240
241 Array of custom icons that can be associated with groups and entries.
242
243 This list can be managed with the methods ["add\_custom\_icon"](#add_custom_icon) and ["remove\_custom\_icon"](#remove_custom_icon).
244
245 ## recycle\_bin\_enabled
246
247 Boolean indicating whether removed groups and entries should go to a recycle bin or be immediately deleted.
248
249 ## recycle\_bin\_uuid
250
251 The UUID of a group used to store thrown-away groups and entries.
252
253 ## recycle\_bin\_changed
254
255 Timestamp indicating when the recycle bin group was last changed.
256
257 ## entry\_templates\_group
258
259 The UUID of a group containing template entries used when creating new entries.
260
261 ## entry\_templates\_group\_changed
262
263 Timestamp indicating when the entry templates group was last changed.
264
265 ## last\_selected\_group
266
267 The UUID of the previously-selected group.
268
269 ## last\_top\_visible\_group
270
271 The UUID of the group visible at the top of the list.
272
273 ## history\_max\_items
274
275 The maximum number of historical entries that should be kept for each entry. Default is 10.
276
277 ## history\_max\_size
278
279 The maximum total size (in bytes) that each individual entry's history is allowed to grow. Default is 6 MiB.
280
281 ## maintenance\_history\_days
282
283 The maximum age (in days) historical entries should be kept. Default it 365.
284
285 ## settings\_changed
286
287 Timestamp indicating when the database settings were last updated.
288
289 ## protect\_title
290
291 Alias of the ["memory\_protection"](#memory_protection) setting for the _Title_ string.
292
293 ## protect\_username
294
295 Alias of the ["memory\_protection"](#memory_protection) setting for the _UserName_ string.
296
297 ## protect\_password
298
299 Alias of the ["memory\_protection"](#memory_protection) setting for the _Password_ string.
300
301 ## protect\_url
302
303 Alias of the ["memory\_protection"](#memory_protection) setting for the _URL_ string.
304
305 ## protect\_notes
306
307 Alias of the ["memory\_protection"](#memory_protection) setting for the _Notes_ string.
308
309 # METHODS
310
311 ## new
312
313 ```
314 $kdbx = File::KDBX->new(%attributes);
315 $kdbx = File::KDBX->new($kdbx); # copy constructor
316 ```
317
318 Construct a new [File::KDBX](https://metacpan.org/pod/File%3A%3AKDBX).
319
320 ## init
321
322 ```
323 $kdbx = $kdbx->init(%attributes);
324 ```
325
326 Initialize a [File::KDBX](https://metacpan.org/pod/File%3A%3AKDBX) with a set of attributes. Returns itself to allow method chaining.
327
328 This is called by ["new"](#new).
329
330 ## reset
331
332 ```
333 $kdbx = $kdbx->reset;
334 ```
335
336 Set a [File::KDBX](https://metacpan.org/pod/File%3A%3AKDBX) to an empty state, ready to load a KDBX file or build a new one. Returns itself to allow
337 method chaining.
338
339 ## clone
340
341 ```
342 $kdbx_copy = $kdbx->clone;
343 $kdbx_copy = File::KDBX->new($kdbx);
344 ```
345
346 Clone a [File::KDBX](https://metacpan.org/pod/File%3A%3AKDBX). The clone will be an exact copy and completely independent of the original.
347
348 ## load
349
350 ## load\_string
351
352 ## load\_file
353
354 ## load\_handle
355
356 ```
357 $kdbx = KDBX::File->load(\$string, $key);
358 $kdbx = KDBX::File->load(*IO, $key);
359 $kdbx = KDBX::File->load($filepath, $key);
360 $kdbx->load(...); # also instance method
361
362 $kdbx = File::KDBX->load_string($string, $key);
363 $kdbx = File::KDBX->load_string(\$string, $key);
364 $kdbx->load_string(...); # also instance method
365
366 $kdbx = File::KDBX->load_file($filepath, $key);
367 $kdbx->load_file(...); # also instance method
368
369 $kdbx = File::KDBX->load_handle($fh, $key);
370 $kdbx = File::KDBX->load_handle(*IO, $key);
371 $kdbx->load_handle(...); # also instance method
372 ```
373
374 Load a KDBX file from a string buffer, IO handle or file from a filesystem.
375
376 [File::KDBX::Loader](https://metacpan.org/pod/File%3A%3AKDBX%3A%3ALoader) does the heavy lifting.
377
378 ## dump
379
380 ## dump\_string
381
382 ## dump\_file
383
384 ## dump\_handle
385
386 ```
387 $kdbx->dump(\$string, $key);
388 $kdbx->dump(*IO, $key);
389 $kdbx->dump($filepath, $key);
390
391 $kdbx->dump_string(\$string, $key);
392 \$string = $kdbx->dump_string($key);
393
394 $kdbx->dump_file($filepath, $key);
395
396 $kdbx->dump_handle($fh, $key);
397 $kdbx->dump_handle(*IO, $key);
398 ```
399
400 Dump a KDBX file to a string buffer, IO handle or file in a filesystem.
401
402 [File::KDBX::Dumper](https://metacpan.org/pod/File%3A%3AKDBX%3A%3ADumper) does the heavy lifting.
403
404 ## user\_agent\_string
405
406 ```perl
407 $string = $kdbx->user_agent_string;
408 ```
409
410 Get a text string identifying the database client software.
411
412 ## memory\_protection
413
414 ```perl
415 \%settings = $kdbx->memory_protection
416 $kdbx->memory_protection(\%settings);
417
418 $bool = $kdbx->memory_protection($string_key);
419 $kdbx->memory_protection($string_key => $bool);
420 ```
421
422 Get or set memory protection settings. This globally (for the whole database) configures whether and which of
423 the standard strings should be memory-protected. The default setting is to memory-protect only _Password_
424 strings.
425
426 Memory protection can be toggled individually for each entry string, and individual settings take precedence
427 over these global settings.
428
429 ## minimum\_version
430
431 ```
432 $version = $kdbx->minimum_version;
433 ```
434
435 Determine the minimum file version required to save a database losslessly. Using certain databases features
436 might increase this value. For example, setting the KDF to Argon2 will increase the minimum version to at
437 least `KDBX_VERSION_4_0` (i.e. `0x00040000`) because Argon2 was introduced with KDBX4.
438
439 This method never returns less than `KDBX_VERSION_3_1` (i.e. `0x00030001`). That file version is so
440 ubiquitous and well-supported, there are seldom reasons to dump in a lesser format nowadays.
441
442 **WARNING:** If you dump a database with a minimum version higher than the current ["version"](#version), the dumper will
443 typically issue a warning and automatically upgrade the database. This seems like the safest behavior in order
444 to avoid data loss, but lower versions have the benefit of being compatible with more software. It is possible
445 to prevent auto-upgrades by explicitly telling the dumper which version to use, but you do run the risk of
446 data loss. A database will never be automatically downgraded.
447
448 ## root
449
450 ```
451 $group = $kdbx->root;
452 $kdbx->root($group);
453 ```
454
455 Get or set a database's root group. You don't necessarily need to explicitly create or set a root group
456 because it autovivifies when adding entries and groups to the database.
457
458 Every database has only a single root group at a time. Some old KDB files might have multiple root groups.
459 When reading such files, a single implicit root group is created to contain the actual root groups. When
460 writing to such a format, if the root group looks like it was implicitly created then it won't be written and
461 the resulting file might have multiple root groups, as it was before loading. This allows working with older
462 files without changing their written internal structure while still adhering to modern semantics while the
463 database is opened.
464
465 The root group of a KDBX database contains all of the database's entries and other groups. If you replace the
466 root group, you are essentially replacing the entire database contents with something else.
467
468 ## trace\_lineage
469
470 ```
471 \@lineage = $kdbx->trace_lineage($group);
472 \@lineage = $kdbx->trace_lineage($group, $base_group);
473 \@lineage = $kdbx->trace_lineage($entry);
474 \@lineage = $kdbx->trace_lineage($entry, $base_group);
475 ```
476
477 Get the direct line of ancestors from `$base_group` (default: the root group) to a group or entry. The
478 lineage includes the base group but _not_ the target group or entry. Returns `undef` if the target is not in
479 the database structure.
480
481 ## recycle\_bin
482
483 ```
484 $group = $kdbx->recycle_bin;
485 $kdbx->recycle_bin($group);
486 ```
487
488 Get or set the recycle bin group. Returns `undef` if there is no recycle bin and ["recycle\_bin\_enabled"](#recycle_bin_enabled) is
489 false, otherwise the current recycle bin or an autovivified recycle bin group is returned.
490
491 ## entry\_templates
492
493 ```
494 $group = $kdbx->entry_templates;
495 $kdbx->entry_templates($group);
496 ```
497
498 Get or set the entry templates group. May return `undef` if unset.
499
500 ## last\_selected
501
502 ```
503 $group = $kdbx->last_selected;
504 $kdbx->last_selected($group);
505 ```
506
507 Get or set the last selected group. May return `undef` if unset.
508
509 ## last\_top\_visible
510
511 ```
512 $group = $kdbx->last_top_visible;
513 $kdbx->last_top_visible($group);
514 ```
515
516 Get or set the last top visible group. May return `undef` if unset.
517
518 ## add\_group
519
520 ```
521 $kdbx->add_group($group);
522 $kdbx->add_group(%group_attributes, %options);
523 ```
524
525 Add a group to a database. This is equivalent to identifying a parent group and calling
526 ["add\_group" in File::KDBX::Group](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AGroup#add_group) on the parent group, forwarding the arguments. Available options:
527
528 - `group` - Group object or group UUID to add the group to (default: root group)
529
530 ## groups
531
532 ```
533 \&iterator = $kdbx->groups(%options);
534 \&iterator = $kdbx->groups($base_group, %options);
535 ```
536
537 Get an [File::KDBX::Iterator](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AIterator) over _groups_ within a database. Options:
538
539 - `base` - Only include groups within a base group (same as `$base_group`) (default: ["root"](#root))
540 - `inclusive` - Include the base group in the results (default: true)
541 - `algorithm` - Search algorithm, one of `ids`, `bfs` or `dfs` (default: `ids`)
542
543 ## add\_entry
544
545 ```
546 $kdbx->add_entry($entry, %options);
547 $kdbx->add_entry(%entry_attributes, %options);
548 ```
549
550 Add a entry to a database. This is equivalent to identifying a parent group and calling
551 ["add\_entry" in File::KDBX::Group](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AGroup#add_entry) on the parent group, forwarding the arguments. Available options:
552
553 - `group` - Group object or group UUID to add the entry to (default: root group)
554
555 ## entries
556
557 ```
558 \&iterator = $kdbx->entries(%options);
559 \&iterator = $kdbx->entries($base_group, %options);
560 ```
561
562 Get an [File::KDBX::Iterator](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AIterator) over _entries_ within a database. Supports the same options as ["groups"](#groups),
563 plus some new ones:
564
565 - `auto_type` - Only include entries with auto-type enabled (default: false, include all)
566 - `searching` - Only include entries within groups with searching enabled (default: false, include all)
567 - `history` - Also include historical entries (default: false, include only current entries)
568
569 ## objects
570
571 ```
572 \&iterator = $kdbx->objects(%options);
573 \&iterator = $kdbx->objects($base_group, %options);
574 ```
575
576 Get an [File::KDBX::Iterator](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AIterator) over _objects_ within a database. Groups and entries are considered objects,
577 so this is essentially a combination of ["groups"](#groups) and ["entries"](#entries). This won't often be useful, but it can be
578 convenient for maintenance tasks. This method takes the same options as ["groups"](#groups) and ["entries"](#entries).
579
580 ## custom\_icon
581
582 ```perl
583 \%icon = $kdbx->custom_icon($uuid);
584 $kdbx->custom_icon($uuid => \%icon);
585 $kdbx->custom_icon(%icon);
586 $kdbx->custom_icon(uuid => $value, %icon);
587 ```
588
589 Get or set custom icons.
590
591 ## custom\_icon\_data
592
593 ```
594 $image_data = $kdbx->custom_icon_data($uuid);
595 ```
596
597 Get a custom icon image data.
598
599 ## add\_custom\_icon
600
601 ```
602 $uuid = $kdbx->add_custom_icon($image_data, %attributes);
603 $uuid = $kdbx->add_custom_icon(%attributes);
604 ```
605
606 Add a custom icon and get its UUID. If not provided, a random UUID will be generated. Possible attributes:
607
608 - `uuid` - Icon UUID (default: autogenerated)
609 - `data` - Image data (same as `$image_data`)
610 - `name` - Name of the icon (text, KDBX4.1+)
611 - `last_modification_time` - Just what it says (datetime, KDBX4.1+)
612
613 ## remove\_custom\_icon
614
615 ```
616 $kdbx->remove_custom_icon($uuid);
617 ```
618
619 Remove a custom icon.
620
621 ## custom\_data
622
623 ```perl
624 \%all_data = $kdbx->custom_data;
625 $kdbx->custom_data(\%all_data);
626
627 \%data = $kdbx->custom_data($key);
628 $kdbx->custom_data($key => \%data);
629 $kdbx->custom_data(%data);
630 $kdbx->custom_data(key => $value, %data);
631 ```
632
633 Get and set custom data. Custom data is metadata associated with a database.
634
635 Each data item can have a few attributes associated with it.
636
637 - `key` - A unique text string identifier used to look up the data item (required)
638 - `value` - A text string value (required)
639 - `last_modification_time` (optional, KDBX4.1+)
640
641 ## custom\_data\_value
642
643 ```
644 $value = $kdbx->custom_data_value($key);
645 ```
646
647 Exactly the same as ["custom\_data"](#custom_data) except returns just the custom data's value rather than a structure of
648 attributes. This is a shortcut for:
649
650 ```perl
651 my $data = $kdbx->custom_data($key);
652 my $value = defined $data ? $data->{value} : undef;
653 ```
654
655 ## public\_custom\_data
656
657 ```perl
658 \%all_data = $kdbx->public_custom_data;
659 $kdbx->public_custom_data(\%all_data);
660
661 $value = $kdbx->public_custom_data($key);
662 $kdbx->public_custom_data($key => $value);
663 ```
664
665 Get and set public custom data. Public custom data is similar to custom data but different in some important
666 ways. Public custom data:
667
668 - can store strings, booleans and up to 64-bit integer values (custom data can only store text values)
669 - is NOT encrypted within a KDBX file (hence the "public" part of the name)
670 - is a plain hash/dict of key-value pairs with no other associated fields (like modification times)
671
672 ## add\_deleted\_object
673
674 ```
675 $kdbx->add_deleted_object($uuid);
676 ```
677
678 Add a UUID to the deleted objects list. This list is used to support automatic database merging.
679
680 You typically do not need to call this yourself because the list will be populated automatically as objects
681 are removed.
682
683 ## remove\_deleted\_object
684
685 ```
686 $kdbx->remove_deleted_object($uuid);
687 ```
688
689 Remove a UUID from the deleted objects list. This list is used to support automatic database merging.
690
691 You typically do not need to call this yourself because the list will be maintained automatically as objects
692 are added.
693
694 ## clear\_deleted\_objects
695
696 Remove all UUIDs from the deleted objects list. This list is used to support automatic database merging, but
697 if you don't need merging then you can clear deleted objects to reduce the database file size.
698
699 ## resolve\_reference
700
701 ```
702 $string = $kdbx->resolve_reference($reference);
703 $string = $kdbx->resolve_reference($wanted, $search_in, $expression);
704 ```
705
706 Resolve a [field reference](https://keepass.info/help/base/fieldrefs.html). A field reference is a kind of
707 string placeholder. You can use a field reference to refer directly to a standard field within an entry. Field
708 references are resolved automatically while expanding entry strings (i.e. replacing placeholders), but you can
709 use this method to resolve on-the-fly references that aren't part of any actual string in the database.
710
711 If the reference does not resolve to any field, `undef` is returned. If the reference resolves to multiple
712 fields, only the first one is returned (in the same order as iterated by ["entries"](#entries)). To avoid ambiguity, you
713 can refer to a specific entry by its UUID.
714
715 The syntax of a reference is: `{REF:<WantedField>@<SearchIn>:<Text>}`. `Text` is a
716 ["Simple Expression"](#simple-expression). `WantedField` and `SearchIn` are both single character codes representing a field:
717
718 - `T` - Title
719 - `U` - UserName
720 - `P` - Password
721 - `A` - URL
722 - `N` - Notes
723 - `I` - UUID
724 - `O` - Other custom strings
725
726 Since `O` does not represent any specific field, it cannot be used as the `WantedField`.
727
728 Examples:
729
730 To get the value of the _UserName_ string of the first entry with "My Bank" in the title:
731
732 ```perl
733 my $username = $kdbx->resolve_reference('{REF:U@T:"My Bank"}');
734 # OR the {REF:...} wrapper is optional
735 my $username = $kdbx->resolve_reference('U@T:"My Bank"');
736 # OR separate the arguments
737 my $username = $kdbx->resolve_reference(U => T => '"My Bank"');
738 ```
739
740 Note how the text is a ["Simple Expression"](#simple-expression), so search terms with spaces must be surrounded in double
741 quotes.
742
743 To get the _Password_ string of a specific entry (identified by its UUID):
744
745 ```perl
746 my $password = $kdbx->resolve_reference('{REF:P@I:46C9B1FFBD4ABC4BBB260C6190BAD20C}');
747 ```
748
749 ## lock
750
751 ```
752 $kdbx->lock;
753 ```
754
755 Encrypt all protected strings and binaries in a database. The encrypted data is stored in
756 a [File::KDBX::Safe](https://metacpan.org/pod/File%3A%3AKDBX%3A%3ASafe) associated with the database and the actual values will be replaced with `undef` to
757 indicate their protected state. Returns itself to allow method chaining.
758
759 You can call `lock` on an already-locked database to memory-protect any unprotected strings and binaries
760 added after the last time the database was locked.
761
762 ## unlock
763
764 ```
765 $kdbx->unlock;
766 ```
767
768 Decrypt all protected strings and binaries in a database, replacing `undef` value placeholders with their
769 actual, unprotected values. Returns itself to allow method chaining.
770
771 ## unlock\_scoped
772
773 ```
774 $guard = $kdbx->unlock_scoped;
775 ```
776
777 Unlock a database temporarily, relocking when the guard is released (typically at the end of a scope). Returns
778 `undef` if the database is already unlocked.
779
780 See ["lock"](#lock) and ["unlock"](#unlock).
781
782 Example:
783
784 ```perl
785 {
786 my $guard = $kdbx->unlock_scoped;
787 ...;
788 }
789 # $kdbx is now memory-locked
790 ```
791
792 ## peek
793
794 ```
795 $string = $kdbx->peek(\%string);
796 $string = $kdbx->peek(\%binary);
797 ```
798
799 Peek at the value of a protected string or binary without unlocking the whole database. The argument can be
800 a string or binary hashref as returned by ["string" in File::KDBX::Entry](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AEntry#string) or ["binary" in File::KDBX::Entry](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AEntry#binary).
801
802 ## is\_locked
803
804 ```
805 $bool = $kdbx->is_locked;
806 ```
807
808 Get whether or not a database's contents are in a locked (i.e. memory-protected) state. If this is true, then
809 some or all of the protected strings and binaries within the database will be unavailable (literally have
810 `undef` values) until ["unlock"](#unlock) is called.
811
812 ## remove\_empty\_groups
813
814 ```
815 $kdbx->remove_empty_groups;
816 ```
817
818 Remove groups with no subgroups and no entries.
819
820 ## remove\_unused\_icons
821
822 ```perl
823 $kdbx->remove_unused_icons;
824 ```
825
826 Remove icons that are not associated with any entry or group in the database.
827
828 ## remove\_duplicate\_icons
829
830 ```
831 $kdbx->remove_duplicate_icons;
832 ```
833
834 Remove duplicate icons as determined by hashing the icon data.
835
836 ## prune\_history
837
838 ```
839 $kdbx->prune_history(%options);
840 ```
841
842 Remove just as many older historical entries as necessary to get under certain limits.
843
844 - `max_items` - Maximum number of historical entries to keep (default: value of ["history\_max\_items"](#history_max_items), no limit: -1)
845 - `max_size` - Maximum total size (in bytes) of historical entries to keep (default: value of ["history\_max\_size"](#history_max_size), no limit: -1)
846 - `max_age` - Maximum age (in days) of historical entries to keep (default: 365, no limit: -1)
847
848 ## randomize\_seeds
849
850 ```
851 $kdbx->randomize_seeds;
852 ```
853
854 Set various keys, seeds and IVs to random values. These values are used by the cryptographic functions that
855 secure the database when dumped. The attributes that will be randomized are:
856
857 - ["encryption\_iv"](#encryption_iv)
858 - ["inner\_random\_stream\_key"](#inner_random_stream_key)
859 - ["master\_seed"](#master_seed)
860 - ["stream\_start\_bytes"](#stream_start_bytes)
861 - ["transform\_seed"](#transform_seed)
862
863 Randomizing these values has no effect on a loaded database. These are only used when a database is dumped.
864 You normally do not need to call this method explicitly because the dumper does it explicitly by default.
865
866 ## key
867
868 ```
869 $key = $kdbx->key;
870 $key = $kdbx->key($key);
871 $key = $kdbx->key($primitive);
872 ```
873
874 Get or set a [File::KDBX::Key](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AKey). This is the master key (e.g. a password or a key file that can decrypt
875 a database). You can also pass a primitive castable to a **Key**. See ["new" in File::KDBX::Key](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AKey#new) for an explanation
876 of what the primitive can be.
877
878 You generally don't need to call this directly because you can provide the key directly to the loader or
879 dumper when loading or dumping a KDBX file.
880
881 ## composite\_key
882
883 ```
884 $key = $kdbx->composite_key($key);
885 $key = $kdbx->composite_key($primitive);
886 ```
887
888 Construct a [File::KDBX::Key::Composite](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AKey%3A%3AComposite) from a **Key** or primitive. See ["new" in File::KDBX::Key](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AKey#new) for an
889 explanation of what the primitive can be. If the primitive does not represent a composite key, it will be
890 wrapped.
891
892 You generally don't need to call this directly. The loader and dumper use it to transform a master key into
893 a raw encryption key.
894
895 ## kdf
896
897 ```
898 $kdf = $kdbx->kdf(%options);
899 $kdf = $kdbx->kdf(\%parameters, %options);
900 ```
901
902 Get a [File::KDBX::KDF](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AKDF) (key derivation function).
903
904 Options:
905
906 - `params` - KDF parameters, same as `\%parameters` (default: value of ["kdf\_parameters"](#kdf_parameters))
907
908 ## cipher
909
910 ```perl
911 $cipher = $kdbx->cipher(key => $key);
912 $cipher = $kdbx->cipher(key => $key, iv => $iv, uuid => $uuid);
913 ```
914
915 Get a [File::KDBX::Cipher](https://metacpan.org/pod/File%3A%3AKDBX%3A%3ACipher) capable of encrypting and decrypting the body of a database file.
916
917 A key is required. This should be a raw encryption key made up of a fixed number of octets (depending on the
918 cipher), not a [File::KDBX::Key](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AKey) or primitive.
919
920 If not passed, the UUID comes from `$kdbx->headers->{cipher_id}` and the encryption IV comes from
921 `$kdbx->headers->{encryption_iv}`.
922
923 You generally don't need to call this directly. The loader and dumper use it to decrypt and encrypt KDBX
924 files.
925
926 ## random\_stream
927
928 ```perl
929 $cipher = $kdbx->random_stream;
930 $cipher = $kdbx->random_stream(id => $stream_id, key => $key);
931 ```
932
933 Get a [File::KDBX::Cipher::Stream](https://metacpan.org/pod/File%3A%3AKDBX%3A%3ACipher%3A%3AStream) for decrypting and encrypting protected values.
934
935 If not passed, the ID and encryption key comes from `$kdbx->headers->{inner_random_stream_id}` and
936 `$kdbx->headers->{inner_random_stream_key}` (respectively) for KDBX3 files and from
937 `$kdbx->inner_headers->{inner_random_stream_key}` and
938 `$kdbx->inner_headers->{inner_random_stream_id}` (respectively) for KDBX4 files.
939
940 You generally don't need to call this directly. The loader and dumper use it to scramble protected strings.
941
942 # RECIPES
943
944 ## Create a new database
945
946 ```perl
947 my $kdbx = File::KDBX->new;
948
949 my $group = $kdbx->add_group(name => 'Passwords);
950 my $entry = $group->add_entry(
951 title => 'WayneCorp',
952 username => 'bwayne',
953 password => 'iambatman',
954 url => 'https://example.com/login'
955 );
956 $entry->add_auto_type_window_association('WayneCorp - Mozilla Firefox', '{PASSWORD}{ENTER}');
957
958 $kdbx->dump_file('mypasswords.kdbx', 'master password CHANGEME');
959 ```
960
961 ## Read an existing database
962
963 ```perl
964 my $kdbx = File::KDBX->load_file('mypasswords.kdbx', 'master password CHANGEME');
965 $kdbx->unlock; # cause $entry->password below to be defined
966
967 $kdbx->entries->each(sub {
968 my ($entry) = @_;
969 say 'Found password for: ', $entry->title;
970 say ' Username: ', $entry->username;
971 say ' Password: ', $entry->password;
972 });
973 ```
974
975 ## Search for entries
976
977 ```perl
978 my @entries = $kdbx->entries(searching => 1)
979 ->grep(title => 'WayneCorp')
980 ->each; # return all matches
981 ```
982
983 The `searching` option limits results to only entries within groups with searching enabled. Other options are
984 also available. See ["entries"](#entries).
985
986 See ["QUERY"](#query) for many more query examples.
987
988 ## Search for entries by auto-type window association
989
990 ```perl
991 my $window_title = 'WayneCorp - Mozilla Firefox';
992
993 my $entries = $kdbx->entries(auto_type => 1)
994 ->filter(sub {
995 my ($ata) = grep { $_->{window} =~ /\Q$window_title\E/i } @{$_->auto_type_associations};
996 return [$_, $ata->{keystroke_sequence}] if $ata;
997 })
998 ->each(sub {
999 my ($entry, $keys) = @$_;
1000 say 'Entry title: ', $entry->title, ', key sequence: ', $keys;
1001 });
1002 ```
1003
1004 Example output:
1005
1006 ```
1007 Entry title: WayneCorp, key sequence: {PASSWORD}{ENTER}
1008 ```
1009
1010 ## Remove entries from a database
1011
1012 ```perl
1013 $kdbx->entries
1014 ->grep(notes => {'=~' => qr/too old/i})
1015 ->each(sub { $_->recycle });
1016 ```
1017
1018 Recycle all entries with the string "too old" appearing in the **Notes** string.
1019
1020 ## Remove empty groups
1021
1022 ```perl
1023 $kdbx->groups(algorithm => 'dfs')
1024 ->where(-true => 'is_empty')
1025 ->each('remove');
1026 ```
1027
1028 With the search/iteration `algorithm` set to "dfs", groups will be ordered deepest first and the root group
1029 will be last. This allows removing groups that only contain empty groups.
1030
1031 This can also be done with one call to ["remove\_empty\_groups"](#remove_empty_groups).
1032
1033 # SECURITY
1034
1035 One of the biggest threats to your database security is how easily the encryption key can be brute-forced.
1036 Strong brute-force protection depends on:
1037
1038 - Using unguessable passwords, passphrases and key files.
1039 - Using a brute-force resistent key derivation function.
1040
1041 The first factor is up to you. This module does not enforce strong master keys. It is up to you to pick or
1042 generate strong keys.
1043
1044 The KDBX format allows for the key derivation function to be tuned. The idea is that you want each single
1045 brute-foce attempt to be expensive (in terms of time, CPU usage or memory usage), so that making a lot of
1046 attempts (which would be required if you have a strong master key) gets _really_ expensive.
1047
1048 How expensive you want to make each attempt is up to you and can depend on the application.
1049
1050 This and other KDBX-related security issues are covered here more in depth:
1051 [https://keepass.info/help/base/security.html](https://keepass.info/help/base/security.html)
1052
1053 Here are other security risks you should be thinking about:
1054
1055 ## Cryptography
1056
1057 This distribution uses the excellent [CryptX](https://metacpan.org/pod/CryptX) and [Crypt::Argon2](https://metacpan.org/pod/Crypt%3A%3AArgon2) packages to handle all crypto-related
1058 functions. As such, a lot of the security depends on the quality of these dependencies. Fortunately these
1059 modules are maintained and appear to have good track records.
1060
1061 The KDBX format has evolved over time to incorporate improved security practices and cryptographic functions.
1062 This package uses the following functions for authentication, hashing, encryption and random number
1063 generation:
1064
1065 - AES-128 (legacy)
1066 - AES-256
1067 - Argon2d & Argon2id
1068 - CBC block mode
1069 - HMAC-SHA256
1070 - SHA256
1071 - SHA512
1072 - Salsa20 & ChaCha20
1073 - Twofish
1074
1075 At the time of this writing, I am not aware of any successful attacks against any of these functions. These
1076 are among the most-analyzed and widely-adopted crypto functions available.
1077
1078 The KDBX format allows the body cipher and key derivation function to be configured. If a flaw is discovered
1079 in one of these functions, you can hopefully just switch to a better function without needing to update this
1080 software. A later software release may phase out the use of any functions which are no longer secure.
1081
1082 ## Memory Protection
1083
1084 It is not a good idea to keep secret information unencrypted in system memory for longer than is needed. The
1085 address space of your program can generally be read by a user with elevated privileges on the system. If your
1086 system is memory-constrained or goes into a hibernation mode, the contents of your address space could be
1087 written to a disk where it might be persisted for long time.
1088
1089 There might be system-level things you can do to reduce your risk, like using swap encryption and limiting
1090 system access to your program's address space while your program is running.
1091
1092 **File::KDBX** helps minimize (but not eliminate) risk by keeping secrets encrypted in memory until accessed
1093 and zeroing out memory that holds secrets after they're no longer needed, but it's not a silver bullet.
1094
1095 For one thing, the encryption key is stored in the same address space. If core is dumped, the encryption key
1096 is available to be found out. But at least there is the chance that the encryption key and the encrypted
1097 secrets won't both be paged out together while memory-constrained.
1098
1099 Another problem is that some perls (somewhat notoriously) copy around memory behind the scenes willy nilly,
1100 and it's difficult know when perl makes a copy of a secret in order to be able to zero it out later. It might
1101 be impossible. The good news is that perls with SvPV copy-on-write (enabled by default beginning with perl
1102 5.20) are much better in this regard. With COW, it's mostly possible to know what operations will cause perl
1103 to copy the memory of a scalar string, and the number of copies will be significantly reduced. There is a unit
1104 test named `t/memory-protection.t` in this distribution that can be run on POSIX systems to determine how
1105 well **File::KDBX** memory protection is working.
1106
1107 Memory protection also depends on how your application handles secrets. If your app code is handling scalar
1108 strings with secret information, it's up to you to make sure its memory is zeroed out when no longer needed.
1109 ["erase" in File::KDBX::Util](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AUtil#erase) et al. provide some tools to help accomplish this. Or if you're not too concerned
1110 about the risks memory protection is meant to mitigate, then maybe don't worry about it. The security policy
1111 of **File::KDBX** is to try hard to keep secrets protected while in memory so that your app might claim a high
1112 level of security, in case you care about that.
1113
1114 There are some memory protection strategies that **File::KDBX** does NOT use today but could in the future:
1115
1116 Many systems allow programs to mark unswappable pages. Secret information should ideally be stored in such
1117 pages. You could potentially use [mlockall(2)](http://man.he.net/man2/mlockall) (or equivalent for your system) in your own application to
1118 prevent the entire address space from being swapped.
1119
1120 Some systems provide special syscalls for storing secrets in memory while keeping the encryption key outside
1121 of the program's address space, like `CryptProtectMemory` for Windows. This could be a good option, though
1122 unfortunately not portable.
1123
1124 # QUERY
1125
1126 To find things in a KDBX database, you should use a filtered iterator. If you have an iterator, such as
1127 returned by ["entries"](#entries), ["groups"](#groups) or even ["objects"](#objects) you can filter it using ["where" in File::KDBX::Iterator](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AIterator#where).
1128
1129 ```perl
1130 my $filtered_entries = $kdbx->entries->where(\&query);
1131 ```
1132
1133 A `\&query` is just a subroutine that you can either write yourself or have generated for you from either
1134 a ["Simple Expression"](#simple-expression) or ["Declarative Syntax"](#declarative-syntax). It's easier to have your query generated, so I'll cover
1135 that first.
1136
1137 ## Simple Expression
1138
1139 A simple expression is mostly compatible with the KeePass 2 implementation
1140 [described here](https://keepass.info/help/base/search.html#mode_se).
1141
1142 An expression is a string with one or more space-separated terms. Terms with spaces can be enclosed in double
1143 quotes. Terms are negated if they are prefixed with a minus sign. A record must match every term on at least
1144 one of the given fields.
1145
1146 So a simple expression is something like what you might type into a search engine. You can generate a simple
1147 expression query using ["simple\_expression\_query" in File::KDBX::Util](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AUtil#simple_expression_query) or by passing the simple expression as
1148 a **scalar reference** to `where`.
1149
1150 To search for all entries in a database with the word "canyon" appearing anywhere in the title:
1151
1152 ```perl
1153 my $entries = $kdbx->entries->where(\'canyon', qw[title]);
1154 ```
1155
1156 Notice the first argument is a **scalarref**. This disambiguates a simple expression from other types of
1157 queries covered below.
1158
1159 As mentioned, a simple expression can have multiple terms. This simple expression query matches any entry that
1160 has the words "red" **and** "canyon" anywhere in the title:
1161
1162 ```perl
1163 my $entries = $kdbx->entries->where(\'red canyon', qw[title]);
1164 ```
1165
1166 Each term in the simple expression must be found for an entry to match.
1167
1168 To search for entries with "red" in the title but **not** "canyon", just prepend "canyon" with a minus sign:
1169
1170 ```perl
1171 my $entries = $kdbx->entries->where(\'red -canyon', qw[title]);
1172 ```
1173
1174 To search over multiple fields simultaneously, just list them all. To search for entries with "grocery" (but
1175 not "Foodland") in the title or notes:
1176
1177 ```perl
1178 my $entries = $kdbx->entries->where(\'grocery -Foodland', qw[title notes]);
1179 ```
1180
1181 The default operator is a case-insensitive regexp match, which is fine for searching text loosely. You can use
1182 just about any binary comparison operator that perl supports. To specify an operator, list it after the simple
1183 expression. For example, to search for any entry that has been used at least five times:
1184
1185 ```perl
1186 my $entries = $kdbx->entries->where(\5, '>=', qw[usage_count]);
1187 ```
1188
1189 It helps to read it right-to-left, like "usage\_count is greater than or equal to 5".
1190
1191 If you find the disambiguating structures to be distracting or confusing, you can also the
1192 ["simple\_expression\_query" in File::KDBX::Util](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AUtil#simple_expression_query) function as a more intuitive alternative. The following example is
1193 equivalent to the previous:
1194
1195 ```perl
1196 my $entries = $kdbx->entries->where(simple_expression_query(5, '>=', qw[usage_count]));
1197 ```
1198
1199 ## Declarative Syntax
1200
1201 Structuring a declarative query is similar to ["WHERE CLAUSES" in SQL::Abstract](https://metacpan.org/pod/SQL%3A%3AAbstract#WHERE-CLAUSES), but you don't have to be
1202 familiar with that module. Just learn by examples here.
1203
1204 To search for all entries in a database titled "My Bank":
1205
1206 ```perl
1207 my $entries = $kdbx->entries->where({ title => 'My Bank' });
1208 ```
1209
1210 The query here is `{ title => 'My Bank' }`. A hashref can contain key-value pairs where the key is an
1211 attribute of the thing being searched for (in this case an entry) and the value is what you want the thing's
1212 attribute to be to consider it a match. In this case, the attribute we're using as our match criteria is
1213 ["title" in File::KDBX::Entry](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AEntry#title), a text field. If an entry has its title attribute equal to "My Bank", it's
1214 a match.
1215
1216 A hashref can contain multiple attributes. The search candidate will be a match if _all_ of the specified
1217 attributes are equal to their respective values. For example, to search for all entries with a particular URL
1218 **AND** username:
1219
1220 ```perl
1221 my $entries = $kdbx->entries->where({
1222 url => 'https://example.com',
1223 username => 'neo',
1224 });
1225 ```
1226
1227 To search for entries matching _any_ criteria, just change the hashref to an arrayref. To search for entries
1228 with a particular URL **OR** username:
1229
1230 ```perl
1231 my $entries = $kdbx->entries->where([ # <-- Notice the square bracket
1232 url => 'https://example.com',
1233 username => 'neo',
1234 ]);
1235 ```
1236
1237 You can use different operators to test different types of attributes. The ["icon\_id" in File::KDBX::Entry](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AEntry#icon_id)
1238 attribute is a number, so we should use a number comparison operator. To find entries using the smartphone
1239 icon:
1240
1241 ```perl
1242 my $entries = $kdbx->entries->where({
1243 icon_id => { '==', ICON_SMARTPHONE },
1244 });
1245 ```
1246
1247 Note: ["ICON\_SMARTPHONE" in File::KDBX::Constants](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AConstants#ICON_SMARTPHONE) is just a constant from [File::KDBX::Constants](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AConstants). It isn't
1248 special to this example or to queries generally. We could have just used a literal number.
1249
1250 The important thing to notice here is how we wrapped the condition in another arrayref with a single key-value
1251 pair where the key is the name of an operator and the value is the thing to match against. The supported
1252 operators are:
1253
1254 - `eq` - String equal
1255 - `ne` - String not equal
1256 - `lt` - String less than
1257 - `gt` - String greater than
1258 - `le` - String less than or equal
1259 - `ge` - String greater than or equal
1260 - `==` - Number equal
1261 - `!=` - Number not equal
1262 - `<` - Number less than
1263 - `>` - Number greater than
1264 - `<=` - Number less than or equal
1265 - `>=` - Number less than or equal
1266 - `=~` - String match regular expression
1267 - `!~` - String does not match regular expression
1268 - `!` - Boolean false
1269 - `!!` - Boolean true
1270
1271 Other special operators:
1272
1273 - `-true` - Boolean true
1274 - `-false` - Boolean false
1275 - `-not` - Boolean false (alias for `-false`)
1276 - `-defined` - Is defined
1277 - `-undef` - Is not defined
1278 - `-empty` - Is empty
1279 - `-nonempty` - Is not empty
1280 - `-or` - Logical or
1281 - `-and` - Logical and
1282
1283 Let's see another example using an explicit operator. To find all groups except one in particular (identified
1284 by its ["uuid" in File::KDBX::Group](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AGroup#uuid)), we can use the `ne` (string not equal) operator:
1285
1286 ```perl
1287 my $groups = $kdbx->groups->where(
1288 uuid => {
1289 'ne' => uuid('596f7520-6172-6520-7370-656369616c2e'),
1290 },
1291 );
1292 ```
1293
1294 Note: ["uuid" in File::KDBX::Util](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AUtil#uuid) is a little utility function to convert a UUID in its pretty form into bytes.
1295 This utility function isn't special to this example or to queries generally. It could have been written with
1296 a literal such as `"\x59\x6f\x75\x20\x61..."`, but that's harder to read.
1297
1298 Notice we searched for groups this time. Finding groups works exactly the same as it does for entries.
1299
1300 Notice also that we didn't wrap the query in hashref curly-braces or arrayref square-braces. Those are
1301 optional. By default it will only match ALL attributes (as if there were curly-braces).
1302
1303 Testing the truthiness of an attribute is a little bit different because it isn't a binary operation. To find
1304 all entries with the password quality check disabled:
1305
1306 ```perl
1307 my $entries = $kdbx->entries->where('!' => 'quality_check');
1308 ```
1309
1310 This time the string after the operator is the attribute name rather than a value to compare the attribute
1311 against. To test that a boolean value is true, use the `!!` operator (or `-true` if `!!` seems a little too
1312 weird for your taste):
1313
1314 ```perl
1315 my $entries = $kdbx->entries->where('!!' => 'quality_check');
1316 my $entries = $kdbx->entries->where(-true => 'quality_check'); # same thing
1317 ```
1318
1319 Yes, there is also a `-false` and a `-not` if you prefer one of those over `!`. `-false` and `-not`
1320 (along with `-true`) are also special in that you can use them to invert the logic of a subquery. These are
1321 logically equivalent:
1322
1323 ```perl
1324 my $entries = $kdbx->entries->where(-not => { title => 'My Bank' });
1325 my $entries = $kdbx->entries->where(title => { 'ne' => 'My Bank' });
1326 ```
1327
1328 These special operators become more useful when combined with two more special operators: `-and` and `-or`.
1329 With these, it is possible to construct more interesting queries with groups of logic. For example:
1330
1331 ```perl
1332 my $entries = $kdbx->entries->where({
1333 title => { '=~', qr/bank/ },
1334 -not => {
1335 -or => {
1336 notes => { '=~', qr/business/ },
1337 icon_id => { '==', ICON_TRASHCAN_FULL },
1338 },
1339 },
1340 });
1341 ```
1342
1343 In English, find entries where the word "bank" appears anywhere in the title but also do not have either the
1344 word "business" in the notes or are using the full trashcan icon.
1345
1346 ## Subroutine Query
1347
1348 Lastly, as mentioned at the top, you can ignore all this and write your own subroutine. Your subroutine will
1349 be called once for each object being searched over. The subroutine should match the candidate against whatever
1350 criteria you want and return true if it matches or false to skip. To do this, just pass your subroutine
1351 coderef to `where`.
1352
1353 To review the different types of queries, these are all equivalent to find all entries in the database titled
1354 "My Bank":
1355
1356 ```perl
1357 my $entries = $kdbx->entries->where(\'"My Bank"', 'eq', qw[title]); # simple expression
1358 my $entries = $kdbx->entries->where(title => 'My Bank'); # declarative syntax
1359 my $entries = $kdbx->entries->where(sub { $_->title eq 'My Bank' }); # subroutine query
1360 ```
1361
1362 This is a trivial example, but of course your subroutine can be arbitrarily complex.
1363
1364 All of these query mechanisms described in this section are just tools, each with its own set of limitations.
1365 If the tools are getting in your way, you can of course iterate over the contents of a database and implement
1366 your own query logic, like this:
1367
1368 ```perl
1369 my $entries = $kdbx->entries;
1370 while (my $entry = $entries->next) {
1371 if (wanted($entry)) {
1372 do_something($entry);
1373 }
1374 else {
1375 ...
1376 }
1377 }
1378 ```
1379
1380 ## Iteration
1381
1382 Iterators are the built-in way to navigate or walk the database tree. You get an iterator from ["entries"](#entries),
1383 ["groups"](#groups) and ["objects"](#objects). You can specify the search algorithm to iterate over objects in different orders
1384 using the `algorithm` option, which can be one of these [constants](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AConstants#iteration):
1385
1386 - `ITERATION_IDS` - Iterative deepening search (default)
1387 - `ITERATION_DFS` - Depth-first search
1388 - `ITERATION_BFS` - Breadth-first search
1389
1390 When iterating over objects generically, groups always precede their direct entries (if any). When the
1391 `history` option is used, current entries always precede historical entries.
1392
1393 If you have a database tree like this:
1394
1395 ```
1396 Database
1397 - Root
1398 - Group1
1399 - EntryA
1400 - Group2
1401 - EntryB
1402 - Group3
1403 - EntryC
1404 ```
1405
1406 - IDS order of groups is: Root, Group1, Group2, Group3
1407 - IDS order of entries is: EntryA, EntryB, EntryC
1408 - IDS order of objects is: Root, Group1, EntryA, Group2, EntryB, Group3, EntryC
1409 - DFS order of groups is: Group2, Group1, Group3, Root
1410 - DFS order of entries is: EntryB, EntryA, EntryC
1411 - DFS order of objects is: Group2, EntryB, Group1, EntryA, Group3, EntryC, Root
1412 - BFS order of groups is: Root, Group1, Group3, Group2
1413 - BFS order of entries is: EntryA, EntryC, EntryB
1414 - BFS order of objects is: Root, Group1, EntryA, Group3, EntryC, Group2, EntryB
1415
1416 # SYNCHRONIZING
1417
1418 **TODO** - This is a planned feature, not yet implemented.
1419
1420 # ERRORS
1421
1422 Errors in this package are constructed as [File::KDBX::Error](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AError) objects and propagated using perl's built-in
1423 mechanisms. Fatal errors are propagated using ["die LIST" in perlfunc](https://metacpan.org/pod/perlfunc#die-LIST) and non-fatal errors (a.k.a. warnings)
1424 are propagated using ["warn LIST" in perlfunc](https://metacpan.org/pod/perlfunc#warn-LIST) while adhering to perl's [warnings](https://metacpan.org/pod/warnings) system. If you're already
1425 familiar with these mechanisms, you can skip this section.
1426
1427 You can catch fatal errors using ["eval BLOCK" in perlfunc](https://metacpan.org/pod/perlfunc#eval-BLOCK) (or something like [Try::Tiny](https://metacpan.org/pod/Try%3A%3ATiny)) and non-fatal
1428 errors using `$SIG{__WARN__}` (see ["%SIG" in perlvar](https://metacpan.org/pod/perlvar#SIG)). Examples:
1429
1430 ```perl
1431 use File::KDBX::Error qw(error);
1432
1433 my $key = ''; # uh oh
1434 eval {
1435 $kdbx->load_file('whatever.kdbx', $key);
1436 };
1437 if (my $error = error($@)) {
1438 handle_missing_key($error) if $error->type eq 'key.missing';
1439 $error->throw;
1440 }
1441 ```
1442
1443 or using `Try::Tiny`:
1444
1445 ```perl
1446 try {
1447 $kdbx->load_file('whatever.kdbx', $key);
1448 }
1449 catch {
1450 handle_error($_);
1451 };
1452 ```
1453
1454 Catching non-fatal errors:
1455
1456 ```perl
1457 my @warnings;
1458 local $SIG{__WARN__} = sub { push @warnings, $_[0] };
1459
1460 $kdbx->load_file('whatever.kdbx', $key);
1461
1462 handle_warnings(@warnings) if @warnings;
1463 ```
1464
1465 By default perl prints warnings to `STDERR` if you don't catch them. If you don't want to catch them and also
1466 don't want them printed to `STDERR`, you can suppress them lexically (perl v5.28 or higher required):
1467
1468 ```
1469 {
1470 no warnings 'File::KDBX';
1471 ...
1472 }
1473 ```
1474
1475 or locally:
1476
1477 ```
1478 {
1479 local $File::KDBX::WARNINGS = 0;
1480 ...
1481 }
1482 ```
1483
1484 or globally in your program:
1485
1486 ```
1487 $File::KDBX::WARNINGS = 0;
1488 ```
1489
1490 You cannot suppress fatal errors, and if you don't catch them your program will exit.
1491
1492 # ENVIRONMENT
1493
1494 This software will alter its behavior depending on the value of certain environment variables:
1495
1496 - `PERL_FILE_KDBX_XS` - Do not use [File::KDBX::XS](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AXS) if false (default: true)
1497 - `PERL_ONLY` - Do not use [File::KDBX::XS](https://metacpan.org/pod/File%3A%3AKDBX%3A%3AXS) if true (default: false)
1498 - `NO_FORK` - Do not fork if true (default: false)
1499
1500 # SEE ALSO
1501
1502 - [KeePass Password Safe](https://keepass.info/) - The original KeePass
1503 - [KeePassXC](https://keepassxc.org/) - Cross-Platform Password Manager written in C++
1504 - [File::KeePass](https://metacpan.org/pod/File%3A%3AKeePass) has overlapping functionality. It's good but has a backlog of some pretty critical bugs and lacks support for newer KDBX features.
1505
1506 # BUGS
1507
1508 Please report any bugs or feature requests on the bugtracker website
1509 [https://github.com/chazmcgarvey/File-KDBX/issues](https://github.com/chazmcgarvey/File-KDBX/issues)
1510
1511 When submitting a bug or request, please include a test-file or a
1512 patch to an existing test-file that illustrates the bug or desired
1513 feature.
1514
1515 # AUTHOR
1516
1517 Charles McGarvey <ccm@cpan.org>
1518
1519 # COPYRIGHT AND LICENSE
1520
1521 This software is copyright (c) 2022 by Charles McGarvey.
1522
1523 This is free software; you can redistribute it and/or modify it under
1524 the same terms as the Perl 5 programming language system itself.
This page took 0.108422 seconds and 4 git commands to generate.