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