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