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