]> Dogcows Code - chaz/p5-File-KDBX/blob - lib/File/KDBX.pm
Further expand support for attributes
[chaz/p5-File-KDBX] / lib / File / KDBX.pm
1 package File::KDBX;
2 # ABSTRACT: Encrypted databases to store secret text and files
3
4 use warnings;
5 use strict;
6
7 use Crypt::PRNG qw(random_bytes);
8 use Devel::GlobalDestruction;
9 use File::KDBX::Constants qw(:all);
10 use File::KDBX::Error;
11 use File::KDBX::Safe;
12 use File::KDBX::Util qw(:class :coercion :empty :uuid :search erase simple_expression_query snakify);
13 use Hash::Util::FieldHash qw(fieldhashes);
14 use List::Util qw(any);
15 use Ref::Util qw(is_ref is_arrayref is_plain_hashref);
16 use Scalar::Util qw(blessed);
17 use Time::Piece;
18 use boolean;
19 use namespace::clean;
20
21 our $VERSION = '999.999'; # VERSION
22 our $WARNINGS = 1;
23
24 fieldhashes \my (%SAFE, %KEYS);
25
26 =method new
27
28 $kdbx = File::KDBX->new(%attributes);
29 $kdbx = File::KDBX->new($kdbx); # copy constructor
30
31 Construct a new L<File::KDBX>.
32
33 =cut
34
35 sub new {
36 my $class = shift;
37
38 # copy constructor
39 return $_[0]->clone if @_ == 1 && blessed $_[0] && $_[0]->isa($class);
40
41 my $self = bless {}, $class;
42 $self->init(@_);
43 $self->_set_nonlazy_attributes if empty $self;
44 return $self;
45 }
46
47 sub DESTROY { local ($., $@, $!, $^E, $?); !in_global_destruction and $_[0]->reset }
48
49 =method init
50
51 $kdbx = $kdbx->init(%attributes);
52
53 Initialize a L<File::KDBX> with a new set of attributes. Returns itself to allow method chaining.
54
55 This is called by L</new>.
56
57 =cut
58
59 sub init {
60 my $self = shift;
61 my %args = @_;
62
63 @$self{keys %args} = values %args;
64
65 return $self;
66 }
67
68 =method reset
69
70 $kdbx = $kdbx->reset;
71
72 Set a L<File::KDBX> to an empty state, ready to load a KDBX file or build a new one. Returns itself to allow
73 method chaining.
74
75 =cut
76
77 sub reset {
78 my $self = shift;
79 erase $self->headers->{+HEADER_INNER_RANDOM_STREAM_KEY};
80 erase $self->inner_headers->{+INNER_HEADER_INNER_RANDOM_STREAM_KEY};
81 erase $self->{raw};
82 %$self = ();
83 $self->_remove_safe;
84 return $self;
85 }
86
87 =method clone
88
89 $kdbx_copy = $kdbx->clone;
90 $kdbx_copy = File::KDBX->new($kdbx);
91
92 Clone a L<File::KDBX>. The clone will be an exact copy and completely independent of the original.
93
94 =cut
95
96 sub clone {
97 my $self = shift;
98 require Storable;
99 return Storable::dclone($self);
100 }
101
102 sub STORABLE_freeze {
103 my $self = shift;
104 my $cloning = shift;
105
106 my $copy = {%$self};
107
108 return '', $copy, $KEYS{$self} // (), $SAFE{$self} // ();
109 }
110
111 sub STORABLE_thaw {
112 my $self = shift;
113 my $cloning = shift;
114 shift;
115 my $clone = shift;
116 my $key = shift;
117 my $safe = shift;
118
119 @$self{keys %$clone} = values %$clone;
120 $KEYS{$self} = $key;
121 $SAFE{$self} = $safe;
122
123 # Dualvars aren't cloned as dualvars, so coerce the compression flags.
124 $self->compression_flags($self->compression_flags);
125
126 for my $object (@{$self->all_groups}, @{$self->all_entries(history => 1)}) {
127 $object->kdbx($self);
128 }
129 }
130
131 ##############################################################################
132
133 =method load
134
135 =method load_string
136
137 =method load_file
138
139 =method load_handle
140
141 $kdbx = KDBX::File->load(\$string, $key);
142 $kdbx = KDBX::File->load(*IO, $key);
143 $kdbx = KDBX::File->load($filepath, $key);
144 $kdbx->load(...); # also instance method
145
146 $kdbx = File::KDBX->load_string($string, $key);
147 $kdbx = File::KDBX->load_string(\$string, $key);
148 $kdbx->load_string(...); # also instance method
149
150 $kdbx = File::KDBX->load_file($filepath, $key);
151 $kdbx->load_file(...); # also instance method
152
153 $kdbx = File::KDBX->load_handle($fh, $key);
154 $kdbx = File::KDBX->load_handle(*IO, $key);
155 $kdbx->load_handle(...); # also instance method
156
157 Load a KDBX file from a string buffer, IO handle or file from a filesystem.
158
159 L<File::KDBX::Loader> does the heavy lifting.
160
161 =cut
162
163 sub load { shift->_loader->load(@_) }
164 sub load_string { shift->_loader->load_string(@_) }
165 sub load_file { shift->_loader->load_file(@_) }
166 sub load_handle { shift->_loader->load_handle(@_) }
167
168 sub _loader {
169 my $self = shift;
170 $self = $self->new if !ref $self;
171 require File::KDBX::Loader;
172 File::KDBX::Loader->new(kdbx => $self);
173 }
174
175 =method dump
176
177 =method dump_string
178
179 =method dump_file
180
181 =method dump_handle
182
183 $kdbx->dump(\$string, $key);
184 $kdbx->dump(*IO, $key);
185 $kdbx->dump($filepath, $key);
186
187 $kdbx->dump_string(\$string, $key);
188 \$string = $kdbx->dump_string($key);
189
190 $kdbx->dump_file($filepath, $key);
191
192 $kdbx->dump_handle($fh, $key);
193 $kdbx->dump_handle(*IO, $key);
194
195 Dump a KDBX file to a string buffer, IO handle or file in a filesystem.
196
197 L<File::KDBX::Dumper> does the heavy lifting.
198
199 =cut
200
201 sub dump { shift->_dumper->dump(@_) }
202 sub dump_string { shift->_dumper->dump_string(@_) }
203 sub dump_file { shift->_dumper->dump_file(@_) }
204 sub dump_handle { shift->_dumper->dump_handle(@_) }
205
206 sub _dumper {
207 my $self = shift;
208 $self = $self->new if !ref $self;
209 require File::KDBX::Dumper;
210 File::KDBX::Dumper->new(kdbx => $self);
211 }
212
213 ##############################################################################
214
215 =method user_agent_string
216
217 $string = $kdbx->user_agent_string;
218
219 Get a text string identifying the database client software.
220
221 =cut
222
223 sub user_agent_string {
224 require Config;
225 sprintf('%s/%s (%s/%s; %s/%s; %s)',
226 __PACKAGE__, $VERSION, @Config::Config{qw(package version osname osvers archname)});
227 }
228
229 has sig1 => KDBX_SIG1, coerce => \&to_number;
230 has sig2 => KDBX_SIG2_2, coerce => \&to_number;
231 has version => KDBX_VERSION_3_1, coerce => \&to_number;
232 has headers => {};
233 has inner_headers => {};
234 has meta => {};
235 has binaries => {};
236 has deleted_objects => {};
237 has raw => coerce => \&to_string;
238
239 # HEADERS
240 has 'headers.comment' => '', coerce => \&to_string;
241 has 'headers.cipher_id' => CIPHER_UUID_CHACHA20, coerce => \&to_uuid;
242 has 'headers.compression_flags' => COMPRESSION_GZIP, coerce => \&to_compression_constant;
243 has 'headers.master_seed' => sub { random_bytes(32) }, coerce => \&to_string;
244 has 'headers.encryption_iv' => sub { random_bytes(16) }, coerce => \&to_string;
245 has 'headers.stream_start_bytes' => sub { random_bytes(32) }, coerce => \&to_string;
246 has 'headers.kdf_parameters' => sub {
247 +{
248 KDF_PARAM_UUID() => KDF_UUID_AES,
249 KDF_PARAM_AES_ROUNDS() => $_[0]->headers->{+HEADER_TRANSFORM_ROUNDS} // KDF_DEFAULT_AES_ROUNDS,
250 KDF_PARAM_AES_SEED() => $_[0]->headers->{+HEADER_TRANSFORM_SEED} // random_bytes(32),
251 };
252 };
253 # has 'headers.transform_seed' => sub { random_bytes(32) };
254 # has 'headers.transform_rounds' => 100_000;
255 # has 'headers.inner_random_stream_key' => sub { random_bytes(32) }; # 64 ?
256 # has 'headers.inner_random_stream_id' => STREAM_ID_CHACHA20;
257 # has 'headers.public_custom_data' => {};
258
259 # META
260 has 'meta.generator' => '', coerce => \&to_string;
261 has 'meta.header_hash' => '', coerce => \&to_string;
262 has 'meta.database_name' => '', coerce => \&to_string;
263 has 'meta.database_name_changed' => sub { gmtime }, coerce => \&to_time;
264 has 'meta.database_description' => '', coerce => \&to_string;
265 has 'meta.database_description_changed' => sub { gmtime }, coerce => \&to_time;
266 has 'meta.default_username' => '', coerce => \&to_string;
267 has 'meta.default_username_changed' => sub { gmtime }, coerce => \&to_time;
268 has 'meta.maintenance_history_days' => 0, coerce => \&to_number;
269 has 'meta.color' => '', coerce => \&to_string;
270 has 'meta.master_key_changed' => sub { gmtime }, coerce => \&to_time;
271 has 'meta.master_key_change_rec' => -1, coerce => \&to_number;
272 has 'meta.master_key_change_force' => -1, coerce => \&to_number;
273 # has 'meta.memory_protection' => {};
274 has 'meta.custom_icons' => {};
275 has 'meta.recycle_bin_enabled' => true, coerce => \&to_bool;
276 has 'meta.recycle_bin_uuid' => "\0" x 16, coerce => \&to_uuid;
277 has 'meta.recycle_bin_changed' => sub { gmtime }, coerce => \&to_time;
278 has 'meta.entry_templates_group' => "\0" x 16, coerce => \&to_uuid;
279 has 'meta.entry_templates_group_changed' => sub { gmtime }, coerce => \&to_time;
280 has 'meta.last_selected_group' => "\0" x 16, coerce => \&to_uuid;
281 has 'meta.last_top_visible_group' => "\0" x 16, coerce => \&to_uuid;
282 has 'meta.history_max_items' => HISTORY_DEFAULT_MAX_ITEMS, coerce => \&to_number;
283 has 'meta.history_max_size' => HISTORY_DEFAULT_MAX_SIZE, coerce => \&to_number;
284 has 'meta.settings_changed' => sub { gmtime }, coerce => \&to_time;
285 # has 'meta.binaries' => {};
286 # has 'meta.custom_data' => {};
287
288 has 'memory_protection.protect_title' => false, coerce => \&to_bool;
289 has 'memory_protection.protect_username' => false, coerce => \&to_bool;
290 has 'memory_protection.protect_password' => true, coerce => \&to_bool;
291 has 'memory_protection.protect_url' => false, coerce => \&to_bool;
292 has 'memory_protection.protect_notes' => false, coerce => \&to_bool;
293 # has 'memory_protection.auto_enable_visual_hiding' => false;
294
295 my @ATTRS = (
296 HEADER_TRANSFORM_SEED,
297 HEADER_TRANSFORM_ROUNDS,
298 HEADER_INNER_RANDOM_STREAM_KEY,
299 HEADER_INNER_RANDOM_STREAM_ID,
300 HEADER_PUBLIC_CUSTOM_DATA,
301 );
302 sub _set_nonlazy_attributes {
303 my $self = shift;
304 $self->$_ for list_attributes(ref $self), @ATTRS;
305 }
306
307 =method memory_protection
308
309 \%settings = $kdbx->memory_protection
310 $kdbx->memory_protection(\%settings);
311
312 $bool = $kdbx->memory_protection($string_key);
313 $kdbx->memory_protection($string_key => $bool);
314
315 Get or set memory protection settings. This globally (for the whole database) configures whether and which of
316 the standard strings should be memory-protected. The default setting is to memory-protect only I<Password>
317 strings.
318
319 Memory protection can be toggled individually for each entry string, and individual settings take precedence
320 over these global settings.
321
322 =cut
323
324 sub memory_protection {
325 my $self = shift;
326 $self->{meta}{memory_protection} = shift if @_ == 1 && is_plain_hashref($_[0]);
327 return $self->{meta}{memory_protection} //= {} if !@_;
328
329 my $string_key = shift;
330 my $key = 'protect_' . lc($string_key);
331
332 $self->meta->{memory_protection}{$key} = shift if @_;
333 $self->meta->{memory_protection}{$key};
334 }
335
336 =method minimum_version
337
338 $version = $kdbx->minimum_version;
339
340 Determine the minimum file version required to save a database losslessly. Using certain databases features
341 might increase this value. For example, setting the KDF to Argon2 will increase the minimum version to at
342 least C<KDBX_VERSION_4_0> (i.e. C<0x00040000>) because Argon2 was introduced with KDBX4.
343
344 This method never returns less than C<KDBX_VERSION_3_1> (i.e. C<0x00030001>). That file version is so
345 ubiquitious and well-supported, there are seldom reasons to dump in a lesser format nowadays.
346
347 B<WARNING:> If you dump a database with a minimum version higher than the current L</version>, the dumper will
348 typically issue a warning and automatically upgrade the database. This seems like the safest behavior in order
349 to avoid data loss, but lower versions have the benefit of being compatible with more software. It is possible
350 to prevent auto-upgrades by explicitly telling the dumper which version to use, but you do run the risk of
351 data loss. A database will never be automatically downgraded.
352
353 =cut
354
355 sub minimum_version {
356 my $self = shift;
357
358 return KDBX_VERSION_4_1 if any {
359 nonempty $_->{last_modification_time}
360 } values %{$self->custom_data};
361
362 return KDBX_VERSION_4_1 if any {
363 nonempty $_->{name} || nonempty $_->{last_modification_time}
364 } values %{$self->custom_icons};
365
366 return KDBX_VERSION_4_1 if any {
367 nonempty $_->previous_parent_group || nonempty $_->tags ||
368 any { nonempty $_->{last_modification_time} } values %{$_->custom_data}
369 } @{$self->all_groups};
370
371 return KDBX_VERSION_4_1 if any {
372 nonempty $_->previous_parent_group || (defined $_->quality_check && !$_->quality_check) ||
373 any { nonempty $_->{last_modification_time} } values %{$_->custom_data}
374 } @{$self->all_entries(history => 1)};
375
376 return KDBX_VERSION_4_0 if $self->kdf->uuid ne KDF_UUID_AES;
377
378 return KDBX_VERSION_4_0 if nonempty $self->public_custom_data;
379
380 return KDBX_VERSION_4_0 if any {
381 nonempty $_->custom_data
382 } @{$self->all_groups}, @{$self->all_entries(history => 1)};
383
384 return KDBX_VERSION_3_1;
385 }
386
387 ##############################################################################
388
389 =method add_group
390
391 $kdbx->add_group($group, %options);
392 $kdbx->add_group(%group_attributes, %options);
393
394 Add a group to a database. This is equivalent to identifying a parent group and calling
395 L<File::KDBX::Group/add_group> on the parent group, forwarding the arguments. Available options:
396
397 =for :list
398 * C<group> (aka C<parent>) - Group (object or group UUID) to add the group to (default: root group)
399
400 =cut
401
402 sub add_group {
403 my $self = shift;
404 my $group = @_ % 2 == 1 ? shift : undef;
405 my %args = @_;
406
407 # find the right group to add the group to
408 my $parent = delete $args{group} // delete $args{parent} // $self->root;
409 ($parent) = $self->find_groups({uuid => $parent}) if !ref $parent;
410 $parent or throw 'Invalid group';
411
412 return $parent->add_group(defined $group ? $group : (), %args, kdbx => $self);
413 }
414
415 sub _wrap_group {
416 my $self = shift;
417 my $group = shift;
418 require File::KDBX::Group;
419 return File::KDBX::Group->wrap($group, $self);
420 }
421
422 =method root
423
424 $group = $kdbx->root;
425 $kdbx->root($group);
426
427 Get or set a database's root group. You don't necessarily need to explicitly create or set a root group
428 because it autovivifies when adding entries and groups to the database.
429
430 Every database has only a single root group at a time. Some old KDB files might have multiple root groups.
431 When reading such files, a single implicit root group is created to contain the other explicit groups. When
432 writing to such a format, if the root group looks like it was implicitly created then it won't be written and
433 the resulting file might have multiple root groups. This allows working with older files without changing
434 their written internal structure while still adhering to modern semantics while the database is opened.
435
436 B<WARNING:> The root group of a KDBX database contains all of the database's entries and other groups. If you
437 replace the root group, you are essentially replacing the entire database contents with something else.
438
439 =cut
440
441 sub root {
442 my $self = shift;
443 if (@_) {
444 $self->{root} = $self->_wrap_group(@_);
445 $self->{root}->kdbx($self);
446 }
447 $self->{root} //= $self->_implicit_root;
448 return $self->_wrap_group($self->{root});
449 }
450
451 sub _kpx_groups {
452 my $self = shift;
453 return [] if !$self->{root};
454 return $self->_has_implicit_root ? $self->root->groups : [$self->root];
455 }
456
457 sub _has_implicit_root {
458 my $self = shift;
459 my $root = $self->root;
460 my $temp = __PACKAGE__->_implicit_root;
461 # If an implicit root group has been changed in any significant way, it is no longer implicit.
462 return $root->name eq $temp->name &&
463 $root->is_expanded ^ $temp->is_expanded &&
464 $root->notes eq $temp->notes &&
465 !@{$root->entries} &&
466 !defined $root->custom_icon_uuid &&
467 !keys %{$root->custom_data} &&
468 $root->icon_id == $temp->icon_id &&
469 $root->expires ^ $temp->expires &&
470 $root->default_auto_type_sequence eq $temp->default_auto_type_sequence &&
471 !defined $root->enable_auto_type &&
472 !defined $root->enable_searching;
473 }
474
475 sub _implicit_root {
476 my $self = shift;
477 require File::KDBX::Group;
478 return File::KDBX::Group->new(
479 name => 'Root',
480 is_expanded => true,
481 notes => 'Added as an implicit root group by '.__PACKAGE__.'.',
482 ref $self ? (kdbx => $self) : (),
483 );
484 }
485
486 =method all_groups
487
488 \@groups = $kdbx->all_groups(%options);
489 \@groups = $kdbx->all_groups($base_group, %options);
490
491 Get all groups deeply in a database, or all groups within a specified base group, in a flat array. Supported
492 options:
493
494 =for :list
495 * C<base> - Only include groups within a base group (same as C<$base_group>) (default: root)
496 * C<include_base> - Include the base group in the results (default: true)
497
498 =cut
499
500 sub all_groups {
501 my $self = shift;
502 my %args = @_ % 2 == 0 ? @_ : (base => shift, @_);
503 my $base = $args{base} // $self->root;
504
505 my @groups = $args{include_base} // 1 ? $self->_wrap_group($base) : ();
506
507 for my $subgroup (@{$base->{groups} || []}) {
508 my $more = $self->all_groups($subgroup);
509 push @groups, @$more;
510 }
511
512 return \@groups;
513 }
514
515 =method trace_lineage
516
517 \@lineage = $kdbx->trace_lineage($group);
518 \@lineage = $kdbx->trace_lineage($group, $base_group);
519 \@lineage = $kdbx->trace_lineage($entry);
520 \@lineage = $kdbx->trace_lineage($entry, $base_group);
521
522 Get the direct line of ancestors from C<$base_group> (default: the root group) to a group or entry. The
523 lineage includes the base group but I<not> the target group or entry. Returns C<undef> if the target is not in
524 the database structure.
525
526 =cut
527
528 sub trace_lineage {
529 my $self = shift;
530 my $object = shift;
531 return $object->lineage(@_);
532 }
533
534 sub _trace_lineage {
535 my $self = shift;
536 my $object = shift;
537 my @lineage = @_;
538
539 push @lineage, $self->root if !@lineage;
540 my $base = $lineage[-1] or return [];
541
542 my $uuid = $object->uuid;
543 return \@lineage if any { $_->uuid eq $uuid } @{$base->groups || []}, @{$base->entries || []};
544
545 for my $subgroup (@{$base->groups || []}) {
546 my $result = $self->_trace_lineage($object, @lineage, $subgroup);
547 return $result if $result;
548 }
549 }
550
551 =method find_groups
552
553 @groups = $kdbx->find_groups($query, %options);
554
555 Find all groups deeply that match to a query. Options are the same as for L</all_groups>.
556
557 See L</QUERY> for a description of what C<$query> can be.
558
559 =cut
560
561 sub find_groups {
562 my $self = shift;
563 my $query = shift or throw 'Must provide a query';
564 my %args = @_;
565 my %all_groups = (
566 base => $args{base},
567 include_base => $args{include_base},
568 );
569 return @{search($self->all_groups(%all_groups), is_arrayref($query) ? @$query : $query)};
570 }
571
572 sub remove {
573 my $self = shift;
574 my $object = shift;
575 }
576
577 ##############################################################################
578
579 =method add_entry
580
581 $kdbx->add_entry($entry, %options);
582 $kdbx->add_entry(%entry_attributes, %options);
583
584 Add a entry to a database. This is equivalent to identifying a parent group and calling
585 L<File::KDBX::Group/add_entry> on the parent group, forwarding the arguments. Available options:
586
587 =for :list
588 * C<group> (aka C<parent>) - Group (object or group UUID) to add the entry to (default: root group)
589
590 =cut
591
592 sub add_entry {
593 my $self = shift;
594 my $entry = @_ % 2 == 1 ? shift : undef;
595 my %args = @_;
596
597 # find the right group to add the entry to
598 my $parent = delete $args{group} // delete $args{parent} // $self->root;
599 ($parent) = $self->find_groups({uuid => $parent}) if !ref $parent;
600 $parent or throw 'Invalid group';
601
602 return $parent->add_entry(defined $entry ? $entry : (), %args, kdbx => $self);
603 }
604
605 sub _wrap_entry {
606 my $self = shift;
607 my $entry = shift;
608 require File::KDBX::Entry;
609 return File::KDBX::Entry->wrap($entry, $self);
610 }
611
612 =method all_entries
613
614 \@entries = $kdbx->all_entries(%options);
615 \@entries = $kdbx->all_entries($base_group, %options);
616
617 Get entries deeply in a database, in a flat array. Supported options:
618
619 =for :list
620 * C<base> - Only include entries within a base group (same as C<$base_group>) (default: root)
621 * C<auto_type> - Only include entries with auto-type enabled (default: false, include all)
622 * C<search> - Only include entries within groups with search enabled (default: false, include all)
623 * C<history> - Also include historical entries (default: false, include only active entries)
624
625 =cut
626
627 sub all_entries {
628 my $self = shift;
629 my %args = @_ % 2 == 0 ? @_ : (base => shift, @_);
630
631 my $base = $args{base} // $self->root;
632 my $history = $args{history};
633 my $search = $args{search};
634 my $auto_type = $args{auto_type};
635
636 my $enable_auto_type = $base->{enable_auto_type} // true;
637 my $enable_searching = $base->{enable_searching} // true;
638
639 my @entries;
640 if ((!$search || $enable_searching) && (!$auto_type || $enable_auto_type)) {
641 push @entries,
642 map { $self->_wrap_entry($_) }
643 grep { !$auto_type || $_->{auto_type}{enabled} }
644 map { $_, $history ? @{$_->{history} || []} : () }
645 @{$base->{entries} || []};
646 }
647
648 for my $subgroup (@{$base->{groups} || []}) {
649 my $more = $self->all_entries($subgroup,
650 auto_type => $auto_type,
651 search => $search,
652 history => $history,
653 );
654 push @entries, @$more;
655 }
656
657 return \@entries;
658 }
659
660 =method find_entries
661
662 =method find_entries_simple
663
664 @entries = $kdbx->find_entries($query, %options);
665
666 @entries = $kdbx->find_entries_simple($expression, \@fields, %options);
667 @entries = $kdbx->find_entries_simple($expression, $operator, \@fields, %options);
668
669 Find all entries deeply that match a query. Options are the same as for L</all_entries>.
670
671 See L</QUERY> for a description of what C<$query> can be.
672
673 =cut
674
675 sub find_entries {
676 my $self = shift;
677 my $query = shift or throw 'Must provide a query';
678 my %args = @_;
679 my %all_entries = (
680 base => $args{base},
681 auto_type => $args{auto_type},
682 search => $args{search},
683 history => $args{history},
684 );
685 my $limit = delete $args{limit};
686 if (defined $limit) {
687 return @{search_limited($self->all_entries(%all_entries), is_arrayref($query) ? @$query : $query, $limit)};
688 }
689 else {
690 return @{search($self->all_entries(%all_entries), is_arrayref($query) ? @$query : $query)};
691 }
692 }
693
694 sub find_entries_simple {
695 my $self = shift;
696 my $text = shift;
697 my $op = @_ && !is_ref($_[0]) ? shift : undef;
698 my $fields = shift;
699 is_arrayref($fields) or throw q{Usage: find_entries_simple($expression, [$op,] \@fields)};
700 return $self->find_entries([\$text, $op, $fields], @_);
701 }
702
703 ##############################################################################
704
705 =method custom_icon
706
707 \%icon = $kdbx->custom_icon($uuid);
708 $kdbx->custom_icon($uuid => \%icon);
709 $kdbx->custom_icon(%icon);
710 $kdbx->custom_icon(uuid => $value, %icon);
711
712
713 =cut
714
715 sub custom_icon {
716 my $self = shift;
717 my %args = @_ == 2 ? (uuid => shift, value => shift)
718 : @_ % 2 == 1 ? (uuid => shift, @_) : @_;
719
720 if (!$args{key} && !$args{value}) {
721 my %standard = (key => 1, value => 1, last_modification_time => 1);
722 my @other_keys = grep { !$standard{$_} } keys %args;
723 if (@other_keys == 1) {
724 my $key = $args{key} = $other_keys[0];
725 $args{value} = delete $args{$key};
726 }
727 }
728
729 my $key = $args{key} or throw 'Must provide a custom_icons key to access';
730
731 return $self->{meta}{custom_icons}{$key} = $args{value} if is_plain_hashref($args{value});
732
733 while (my ($field, $value) = each %args) {
734 $self->{meta}{custom_icons}{$key}{$field} = $value;
735 }
736 return $self->{meta}{custom_icons}{$key};
737 }
738
739 =method custom_icon_data
740
741 $image_data = $kdbx->custom_icon_data($uuid);
742
743 Get a custom icon.
744
745 =cut
746
747 sub custom_icon_data {
748 my $self = shift;
749 my $uuid = shift // return;
750 return if !exists $self->custom_icons->{$uuid};
751 return $self->custom_icons->{$uuid}{data};
752 }
753
754 =method add_custom_icon
755
756 $uuid = $kdbx->add_custom_icon($image_data, %attributes);
757
758 Add a custom icon and get its UUID. If not provided, a random UUID will be generated. Possible attributes:
759
760 =for :list
761 * C<uuid> - Icon UUID
762 * C<name> - Name of the icon (text, KDBX4.1+)
763 * C<last_modification_time> - Just what it says (datetime, KDBX4.1+)
764
765 =cut
766
767 sub add_custom_icon {
768 my $self = shift;
769 my $img = shift or throw 'Must provide image data';
770 my %args = @_;
771
772 my $uuid = $args{uuid} // generate_uuid(sub { !$self->custom_icons->{$_} });
773 $self->custom_icons->{$uuid} = {
774 @_,
775 uuid => $uuid,
776 data => $img,
777 };
778 return $uuid;
779 }
780
781 =method remove_custom_icon
782
783 $kdbx->remove_custom_icon($uuid);
784
785 Remove a custom icon.
786
787 =cut
788
789 sub remove_custom_icon {
790 my $self = shift;
791 my $uuid = shift;
792 delete $self->custom_icons->{$uuid};
793 }
794
795 ##############################################################################
796
797 =method custom_data
798
799 \%all_data = $kdbx->custom_data;
800 $kdbx->custom_data(\%all_data);
801
802 \%data = $kdbx->custom_data($key);
803 $kdbx->custom_data($key => \%data);
804 $kdbx->custom_data(%data);
805 $kdbx->custom_data(key => $value, %data);
806
807 Get and set custom data. Custom data is metadata associated with a database.
808
809 Each data item can have a few attributes associated with it.
810
811 =for :list
812 * C<key> - A unique text string identifier used to look up the data item (required)
813 * C<value> - A text string value (required)
814 * C<last_modification_time> (optional, KDBX4.1+)
815
816 =cut
817
818 sub custom_data {
819 my $self = shift;
820 $self->{meta}{custom_data} = shift if @_ == 1 && is_plain_hashref($_[0]);
821 return $self->{meta}{custom_data} //= {} if !@_;
822
823 my %args = @_ == 2 ? (key => shift, value => shift)
824 : @_ % 2 == 1 ? (key => shift, @_) : @_;
825
826 if (!$args{key} && !$args{value}) {
827 my %standard = (key => 1, value => 1, last_modification_time => 1);
828 my @other_keys = grep { !$standard{$_} } keys %args;
829 if (@other_keys == 1) {
830 my $key = $args{key} = $other_keys[0];
831 $args{value} = delete $args{$key};
832 }
833 }
834
835 my $key = $args{key} or throw 'Must provide a custom_data key to access';
836
837 return $self->{meta}{custom_data}{$key} = $args{value} if is_plain_hashref($args{value});
838
839 while (my ($field, $value) = each %args) {
840 $self->{meta}{custom_data}{$key}{$field} = $value;
841 }
842 return $self->{meta}{custom_data}{$key};
843 }
844
845 =method custom_data_value
846
847 $value = $kdbx->custom_data_value($key);
848
849 Exactly the same as L</custom_data> except returns just the custom data's value rather than a structure of
850 attributes. This is a shortcut for:
851
852 my $data = $kdbx->custom_data($key);
853 my $value = defined $data ? $data->{value} : undef;
854
855 =cut
856
857 sub custom_data_value {
858 my $self = shift;
859 my $data = $self->custom_data(@_) // return;
860 return $data->{value};
861 }
862
863 =method public_custom_data
864
865 \%all_data = $kdbx->public_custom_data;
866 $kdbx->public_custom_data(\%all_data);
867
868 $value = $kdbx->public_custom_data($key);
869 $kdbx->public_custom_data($key => $value);
870
871 Get and set public custom data. Public custom data is similar to custom data but different in some important
872 ways. Public custom data:
873
874 =for :list
875 * can store strings, booleans and up to 64-bit integer values (custom data can only store text values)
876 * is NOT encrypted within a KDBX file (hence the "public" part of the name)
877 * is a plain hash/dict of key-value pairs with no other associated fields (like modification times)
878
879 =cut
880
881 sub public_custom_data {
882 my $self = shift;
883 $self->{headers}{+HEADER_PUBLIC_CUSTOM_DATA} = shift if @_ == 1 && is_plain_hashref($_[0]);
884 return $self->{headers}{+HEADER_PUBLIC_CUSTOM_DATA} //= {} if !@_;
885
886 my $key = shift or throw 'Must provide a public_custom_data key to access';
887 $self->{headers}{+HEADER_PUBLIC_CUSTOM_DATA}{$key} = shift if @_;
888 return $self->{headers}{+HEADER_PUBLIC_CUSTOM_DATA}{$key};
889 }
890
891 ##############################################################################
892
893 # TODO
894
895 # sub merge_to {
896 # my $self = shift;
897 # my $other = shift;
898 # my %options = @_; # prefer_old / prefer_new
899 # $other->merge_from($self);
900 # }
901
902 # sub merge_from {
903 # my $self = shift;
904 # my $other = shift;
905
906 # die 'Not implemented';
907 # }
908
909 ##############################################################################
910
911 =method resolve_reference
912
913 $string = $kdbx->resolve_reference($reference);
914 $string = $kdbx->resolve_reference($wanted, $search_in, $expression);
915
916 Resolve a L<field reference|https://keepass.info/help/base/fieldrefs.html>. A field reference is a kind of
917 string placeholder. You can use a field reference to refer directly to a standard field within an entry. Field
918 references are resolved automatically while expanding entry strings (i.e. replacing placeholders), but you can
919 use this method to resolve on-the-fly references that aren't part of any actual string in the database.
920
921 If the reference does not resolve to any field, C<undef> is returned. If the reference resolves to multiple
922 fields, only the first one is returned (in the same order as L</all_entries>). To avoid ambiguity, you can
923 refer to a specific entry by its UUID.
924
925 The syntax of a reference is: C<< {REF:<WantedField>@<SearchIn>:<Text>} >>. C<Text> is a
926 L</"Simple Expression">. C<WantedField> and C<SearchIn> are both single character codes representing a field:
927
928 =for :list
929 * C<T> - Title
930 * C<U> - UserName
931 * C<P> - Password
932 * C<A> - URL
933 * C<N> - Notes
934 * C<I> - UUID
935 * C<O> - Other custom strings
936
937 Since C<O> does not represent any specific field, it cannot be used as the C<WantedField>.
938
939 Examples:
940
941 To get the value of the I<UserName> string of the first entry with "My Bank" in the title:
942
943 my $username = $kdbx->resolve_reference('{REF:U@T:"My Bank"}');
944 # OR the {REF:...} wrapper is optional
945 my $username = $kdbx->resolve_reference('U@T:"My Bank"');
946 # OR separate the arguments
947 my $username = $kdbx->resolve_reference(U => T => '"My Bank"');
948
949 Note how the text is a L</"Simple Expression">, so search terms with spaces must be surrounded in double
950 quotes.
951
952 To get the I<Password> string of a specific entry (identified by its UUID):
953
954 my $password = $kdbx->resolve_reference('{REF:P@I:46C9B1FFBD4ABC4BBB260C6190BAD20C}');
955
956 =cut
957
958 sub resolve_reference {
959 my $self = shift;
960 my $wanted = shift // return;
961 my $search_in = shift;
962 my $text = shift;
963
964 if (!defined $text) {
965 $wanted =~ s/^\{REF:([^\}]+)\}$/$1/i;
966 ($wanted, $search_in, $text) = $wanted =~ /^([TUPANI])\@([TUPANIO]):(.*)$/i;
967 }
968 $wanted && $search_in && nonempty($text) or return;
969
970 my %fields = (
971 T => 'expanded_title',
972 U => 'expanded_username',
973 P => 'expanded_password',
974 A => 'expanded_url',
975 N => 'expanded_notes',
976 I => 'uuid',
977 O => 'other_strings',
978 );
979 $wanted = $fields{$wanted} or return;
980 $search_in = $fields{$search_in} or return;
981
982 my $query = $search_in eq 'uuid' ? query($search_in => uuid($text))
983 : simple_expression_query($text, '=~', $search_in);
984
985 my ($entry) = $self->find_entries($query, limit => 1);
986 $entry or return;
987
988 return $entry->$wanted;
989 }
990
991 our %PLACEHOLDERS = (
992 # placeholder => sub { my ($entry, $arg) = @_; ... };
993 'TITLE' => sub { $_[0]->expanded_title },
994 'USERNAME' => sub { $_[0]->expanded_username },
995 'PASSWORD' => sub { $_[0]->expanded_password },
996 'NOTES' => sub { $_[0]->expanded_notes },
997 'S:' => sub { $_[0]->string_value($_[1]) },
998 'URL' => sub { $_[0]->expanded_url },
999 'URL:RMVSCM' => sub { local $_ = $_[0]->url; s!^[^:/\?\#]+://!!; $_ },
1000 'URL:WITHOUTSCHEME' => sub { local $_ = $_[0]->url; s!^[^:/\?\#]+://!!; $_ },
1001 'URL:SCM' => sub { (split_url($_[0]->url))[0] },
1002 'URL:SCHEME' => sub { (split_url($_[0]->url))[0] }, # non-standard
1003 'URL:HOST' => sub { (split_url($_[0]->url))[2] },
1004 'URL:PORT' => sub { (split_url($_[0]->url))[3] },
1005 'URL:PATH' => sub { (split_url($_[0]->url))[4] },
1006 'URL:QUERY' => sub { (split_url($_[0]->url))[5] },
1007 'URL:HASH' => sub { (split_url($_[0]->url))[6] }, # non-standard
1008 'URL:FRAGMENT' => sub { (split_url($_[0]->url))[6] }, # non-standard
1009 'URL:USERINFO' => sub { (split_url($_[0]->url))[1] },
1010 'URL:USERNAME' => sub { (split_url($_[0]->url))[7] },
1011 'URL:PASSWORD' => sub { (split_url($_[0]->url))[8] },
1012 'UUID' => sub { local $_ = format_uuid($_[0]->uuid); s/-//g; $_ },
1013 'REF:' => sub { $_[0]->kdbx->resolve_reference($_[1]) },
1014 'INTERNETEXPLORER' => sub { load_optional('IPC::Cmd'); IPC::Cmd::can_run('iexplore') },
1015 'FIREFOX' => sub { load_optional('IPC::Cmd'); IPC::Cmd::can_run('firefox') },
1016 'GOOGLECHROME' => sub { load_optional('IPC::Cmd'); IPC::Cmd::can_run('google-chrome') },
1017 'OPERA' => sub { load_optional('IPC::Cmd'); IPC::Cmd::can_run('opera') },
1018 'SAFARI' => sub { load_optional('IPC::Cmd'); IPC::Cmd::can_run('safari') },
1019 'APPDIR' => sub { load_optional('FindBin'); $FindBin::Bin },
1020 'GROUP' => sub { my $p = $_[0]->parent; $p ? $p->name : undef },
1021 'GROUP_PATH' => sub { $_[0]->path },
1022 'GROUP_NOTES' => sub { my $p = $_[0]->parent; $p ? $p->notes : undef },
1023 # 'GROUP_SEL'
1024 # 'GROUP_SEL_PATH'
1025 # 'GROUP_SEL_NOTES'
1026 # 'DB_PATH'
1027 # 'DB_DIR'
1028 # 'DB_NAME'
1029 # 'DB_BASENAME'
1030 # 'DB_EXT'
1031 'ENV:' => sub { $ENV{$_[1]} },
1032 'ENV_DIRSEP' => sub { load_optional('File::Spec')->catfile('', '') },
1033 'ENV_PROGRAMFILES_X86' => sub { $ENV{'ProgramFiles(x86)'} || $ENV{'ProgramFiles'} },
1034 # 'T-REPLACE-RX:'
1035 # 'T-CONV:'
1036 'DT_SIMPLE' => sub { localtime->strftime('%Y%m%d%H%M%S') },
1037 'DT_YEAR' => sub { localtime->strftime('%Y') },
1038 'DT_MONTH' => sub { localtime->strftime('%m') },
1039 'DT_DAY' => sub { localtime->strftime('%d') },
1040 'DT_HOUR' => sub { localtime->strftime('%H') },
1041 'DT_MINUTE' => sub { localtime->strftime('%M') },
1042 'DT_SECOND' => sub { localtime->strftime('%S') },
1043 'DT_UTC_SIMPLE' => sub { gmtime->strftime('%Y%m%d%H%M%S') },
1044 'DT_UTC_YEAR' => sub { gmtime->strftime('%Y') },
1045 'DT_UTC_MONTH' => sub { gmtime->strftime('%m') },
1046 'DT_UTC_DAY' => sub { gmtime->strftime('%d') },
1047 'DT_UTC_HOUR' => sub { gmtime->strftime('%H') },
1048 'DT_UTC_MINUTE' => sub { gmtime->strftime('%M') },
1049 'DT_UTC_SECOND' => sub { gmtime->strftime('%S') },
1050 # 'PICKCHARS'
1051 # 'PICKCHARS:'
1052 # 'PICKFIELD'
1053 # 'NEWPASSWORD'
1054 # 'NEWPASSWORD:'
1055 # 'PASSWORD_ENC'
1056 'HMACOTP' => sub { $_[0]->hmac_otp },
1057 'TIMEOTP' => sub { $_[0]->time_otp },
1058 'C:' => sub { '' }, # comment
1059 # 'BASE'
1060 # 'BASE:'
1061 # 'CLIPBOARD'
1062 # 'CLIPBOARD-SET:'
1063 # 'CMD:'
1064 );
1065
1066 ##############################################################################
1067
1068 =method lock
1069
1070 $kdbx->lock;
1071
1072 Encrypt all protected strings in a database. The encrypted strings are stored in a L<File::KDBX::Safe>
1073 associated with the database and the actual strings will be replaced with C<undef> to indicate their protected
1074 state. Returns itself to allow method chaining.
1075
1076 =cut
1077
1078 sub _safe {
1079 my $self = shift;
1080 $SAFE{$self} = shift if @_;
1081 $SAFE{$self};
1082 }
1083
1084 sub _remove_safe { delete $SAFE{$_[0]} }
1085
1086 sub lock {
1087 my $self = shift;
1088
1089 $self->_safe and return $self;
1090
1091 my @strings;
1092
1093 my $entries = $self->all_entries(history => 1);
1094 for my $entry (@$entries) {
1095 push @strings, grep { $_->{protect} } values %{$entry->{strings} || {}};
1096 }
1097
1098 $self->_safe(File::KDBX::Safe->new(\@strings));
1099
1100 return $self;
1101 }
1102
1103 =method unlock
1104
1105 $kdbx->unlock;
1106
1107 Decrypt all protected strings in a database, replacing C<undef> placeholders with unprotected values. Returns
1108 itself to allow method chaining.
1109
1110 =cut
1111
1112 sub unlock {
1113 my $self = shift;
1114 my $safe = $self->_safe or return $self;
1115
1116 $safe->unlock;
1117 $self->_remove_safe;
1118
1119 return $self;
1120 }
1121
1122 =method unlock_scoped
1123
1124 $guard = $kdbx->unlock_scoped;
1125
1126 Unlock a database temporarily, relocking when the guard is released (typically at the end of a scope). Returns
1127 C<undef> if the database is already unlocked.
1128
1129 See L</lock> and L</unlock>.
1130
1131 =cut
1132
1133 sub unlock_scoped {
1134 throw 'Programmer error: Cannot call unlock_scoped in void context' if !defined wantarray;
1135 my $self = shift;
1136 return if !$self->is_locked;
1137 require Scope::Guard;
1138 my $guard = Scope::Guard->new(sub { $self->lock });
1139 $self->unlock;
1140 return $guard;
1141 }
1142
1143 =method peek
1144
1145 $string = $kdbx->peek(\%string);
1146 $string = $kdbx->peek(\%binary);
1147
1148 Peek at the value of a protected string or binary without unlocking the whole database. The argument can be
1149 a string or binary hashref as returned by L<File::KDBX::Entry/string> or L<File::KDBX::Entry/binary>.
1150
1151 =cut
1152
1153 sub peek {
1154 my $self = shift;
1155 my $string = shift;
1156 my $safe = $self->_safe or return;
1157 return $safe->peek($string);
1158 }
1159
1160 =method is_locked
1161
1162 $bool = $kdbx->is_locked;
1163
1164 Get whether or not a database's strings are memory-protected. If this is true, then some or all of the
1165 protected strings within the database will be unavailable (literally have C<undef> values) until L</unlock> is
1166 called.
1167
1168 =cut
1169
1170 sub is_locked { $_[0]->_safe ? 1 : 0 }
1171
1172 ##############################################################################
1173
1174 =method randomize_seeds
1175
1176 $kdbx->randomize_seeds;
1177
1178 Set various keys, seeds and IVs to random values. These values are used by the cryptographic functions that
1179 secure the database when dumped. The attributes that will be randomized are:
1180
1181 =for :list
1182 * L</encryption_iv>
1183 * L</inner_random_stream_key>
1184 * L</master_seed>
1185 * L</stream_start_bytes>
1186 * L</transform_seed>
1187
1188 Randomizing these values has no effect on a loaded database. These are only used when a database is dumped.
1189 You normally do not need to call this method explicitly because the dumper does it explicitly by default.
1190
1191 =cut
1192
1193 sub randomize_seeds {
1194 my $self = shift;
1195 $self->encryption_iv(random_bytes(16));
1196 $self->inner_random_stream_key(random_bytes(64));
1197 $self->master_seed(random_bytes(32));
1198 $self->stream_start_bytes(random_bytes(32));
1199 $self->transform_seed(random_bytes(32));
1200 }
1201
1202 ##############################################################################
1203
1204 =method key
1205
1206 $key = $kdbx->key;
1207 $key = $kdbx->key($key);
1208 $key = $kdbx->key($primitive);
1209
1210 Get or set a L<File::KDBX::Key>. This is the master key (i.e. a password or a key file that can decrypt
1211 a database). See L<File::KDBX::Key/new> for an explanation of what the primitive can be.
1212
1213 You generally don't need to call this directly because you can provide the key directly to the loader or
1214 dumper when loading or saving a KDBX file.
1215
1216 =cut
1217
1218 sub key {
1219 my $self = shift;
1220 $KEYS{$self} = File::KDBX::Key->new(@_) if @_;
1221 $KEYS{$self};
1222 }
1223
1224 =method composite_key
1225
1226 $key = $kdbx->composite_key($key);
1227 $key = $kdbx->composite_key($primitive);
1228
1229 Construct a L<File::KDBX::Key::Composite> from a primitive. See L<File::KDBX::Key/new> for an explanation of
1230 what the primitive can be. If the primitive does not represent a composite key, it will be wrapped.
1231
1232 You generally don't need to call this directly. The parser and writer use it to transform a master key into
1233 a raw encryption key.
1234
1235 =cut
1236
1237 sub composite_key {
1238 my $self = shift;
1239 require File::KDBX::Key::Composite;
1240 return File::KDBX::Key::Composite->new(@_);
1241 }
1242
1243 =method kdf
1244
1245 $kdf = $kdbx->kdf(%options);
1246 $kdf = $kdbx->kdf(\%parameters, %options);
1247
1248 Get a L<File::KDBX::KDF> (key derivation function).
1249
1250 Options:
1251
1252 =for :list
1253 * C<params> - KDF parameters, same as C<\%parameters> (default: value of L</kdf_parameters>)
1254
1255 =cut
1256
1257 sub kdf {
1258 my $self = shift;
1259 my %args = @_ % 2 == 1 ? (params => shift, @_) : @_;
1260
1261 my $params = $args{params};
1262 my $compat = $args{compatible} // 1;
1263
1264 $params //= $self->kdf_parameters;
1265 $params = {%{$params || {}}};
1266
1267 if (empty $params || !defined $params->{+KDF_PARAM_UUID}) {
1268 $params->{+KDF_PARAM_UUID} = KDF_UUID_AES;
1269 }
1270 if ($params->{+KDF_PARAM_UUID} eq KDF_UUID_AES) {
1271 # AES_CHALLENGE_RESPONSE is equivalent to AES if there are no challenge-response keys, and since
1272 # non-KeePassXC implementations don't support challenge-response keys anyway, there's no problem with
1273 # always using AES_CHALLENGE_RESPONSE for all KDBX4+ databases.
1274 # For compatibility, we should not *write* AES_CHALLENGE_RESPONSE, but the dumper handles that.
1275 if ($self->version >= KDBX_VERSION_4_0) {
1276 $params->{+KDF_PARAM_UUID} = KDF_UUID_AES_CHALLENGE_RESPONSE;
1277 }
1278 $params->{+KDF_PARAM_AES_SEED} //= $self->transform_seed;
1279 $params->{+KDF_PARAM_AES_ROUNDS} //= $self->transform_rounds;
1280 }
1281
1282 require File::KDBX::KDF;
1283 return File::KDBX::KDF->new(%$params);
1284 }
1285
1286 sub transform_seed {
1287 my $self = shift;
1288 $self->headers->{+HEADER_TRANSFORM_SEED} =
1289 $self->headers->{+HEADER_KDF_PARAMETERS}{+KDF_PARAM_AES_SEED} = shift if @_;
1290 $self->headers->{+HEADER_TRANSFORM_SEED} =
1291 $self->headers->{+HEADER_KDF_PARAMETERS}{+KDF_PARAM_AES_SEED} //= random_bytes(32);
1292 }
1293
1294 sub transform_rounds {
1295 my $self = shift;
1296 $self->headers->{+HEADER_TRANSFORM_ROUNDS} =
1297 $self->headers->{+HEADER_KDF_PARAMETERS}{+KDF_PARAM_AES_ROUNDS} = shift if @_;
1298 $self->headers->{+HEADER_TRANSFORM_ROUNDS} =
1299 $self->headers->{+HEADER_KDF_PARAMETERS}{+KDF_PARAM_AES_ROUNDS} //= 100_000;
1300 }
1301
1302 =method cipher
1303
1304 $cipher = $kdbx->cipher(key => $key);
1305 $cipher = $kdbx->cipher(key => $key, iv => $iv, uuid => $uuid);
1306
1307 Get a L<File::KDBX::Cipher> capable of encrypting and decrypting the body of a database file.
1308
1309 A key is required. This should be a raw encryption key made up of a fixed number of octets (depending on the
1310 cipher), not a L<File::KDBX::Key> or primitive.
1311
1312 If not passed, the UUID comes from C<< $kdbx->headers->{cipher_id} >> and the encryption IV comes from
1313 C<< $kdbx->headers->{encryption_iv} >>.
1314
1315 You generally don't need to call this directly. The parser and writer use it to decrypt and encrypt KDBX
1316 files.
1317
1318 =cut
1319
1320 sub cipher {
1321 my $self = shift;
1322 my %args = @_;
1323
1324 $args{uuid} //= $self->headers->{+HEADER_CIPHER_ID};
1325 $args{iv} //= $self->headers->{+HEADER_ENCRYPTION_IV};
1326
1327 require File::KDBX::Cipher;
1328 return File::KDBX::Cipher->new(%args);
1329 }
1330
1331 =method random_stream
1332
1333 $cipher = $kdbx->random_stream;
1334 $cipher = $kdbx->random_stream(id => $stream_id, key => $key);
1335
1336 Get a L<File::KDBX::Cipher::Stream> for decrypting and encrypting protected values.
1337
1338 If not passed, the ID and encryption key comes from C<< $kdbx->headers->{inner_random_stream_id} >> and
1339 C<< $kdbx->headers->{inner_random_stream_key} >> (respectively) for KDBX3 files and from
1340 C<< $kdbx->inner_headers->{inner_random_stream_key} >> and
1341 C<< $kdbx->inner_headers->{inner_random_stream_id} >> (respectively) for KDBX4 files.
1342
1343 You generally don't need to call this directly. The parser and writer use it to scramble protected strings.
1344
1345 =cut
1346
1347 sub random_stream {
1348 my $self = shift;
1349 my %args = @_;
1350
1351 $args{stream_id} //= delete $args{id} // $self->inner_random_stream_id;
1352 $args{key} //= $self->inner_random_stream_key;
1353
1354 require File::KDBX::Cipher;
1355 File::KDBX::Cipher->new(%args);
1356 }
1357
1358 sub inner_random_stream_id {
1359 my $self = shift;
1360 $self->inner_headers->{+INNER_HEADER_INNER_RANDOM_STREAM_ID}
1361 = $self->headers->{+HEADER_INNER_RANDOM_STREAM_ID} = shift if @_;
1362 $self->inner_headers->{+INNER_HEADER_INNER_RANDOM_STREAM_ID}
1363 //= $self->headers->{+HEADER_INNER_RANDOM_STREAM_ID} //= do {
1364 my $version = $self->minimum_version;
1365 $version < KDBX_VERSION_4_0 ? STREAM_ID_SALSA20 : STREAM_ID_CHACHA20;
1366 };
1367 }
1368
1369 sub inner_random_stream_key {
1370 my $self = shift;
1371 if (@_) {
1372 # These are probably the same SvPV so erasing one will CoW, but erasing the second should do the
1373 # trick anyway.
1374 erase \$self->inner_headers->{+INNER_HEADER_INNER_RANDOM_STREAM_KEY};
1375 erase \$self->headers->{+HEADER_INNER_RANDOM_STREAM_KEY};
1376 $self->inner_headers->{+INNER_HEADER_INNER_RANDOM_STREAM_KEY}
1377 = $self->headers->{+HEADER_INNER_RANDOM_STREAM_KEY} = shift;
1378 }
1379 $self->inner_headers->{+INNER_HEADER_INNER_RANDOM_STREAM_KEY}
1380 //= $self->headers->{+HEADER_INNER_RANDOM_STREAM_KEY} //= random_bytes(64); # 32
1381 }
1382
1383 #########################################################################################
1384
1385 sub check {
1386 # - Fixer tool. Can repair inconsistencies, including:
1387 # - Orphaned binaries... not really a thing anymore since we now distribute binaries amongst entries
1388 # - Unused custom icons (OFF, data loss)
1389 # - Duplicate icons
1390 # - All data types are valid
1391 # - date times are correct
1392 # - boolean fields
1393 # - All UUIDs refer to things that exist
1394 # - previous parent group
1395 # - recycle bin
1396 # - last selected group
1397 # - last visible group
1398 # - Enforce history size limits (ON)
1399 # - Check headers/meta (ON)
1400 # - Duplicate deleted objects (ON)
1401 # - Duplicate window associations (OFF)
1402 # - Only one root group (ON)
1403 # - Header UUIDs match known ciphers/KDFs?
1404 }
1405
1406 #########################################################################################
1407
1408 sub _handle_signal {
1409 my $self = shift;
1410 my $object = shift;
1411 my $type = shift;
1412
1413 my %handlers = (
1414 'entry.uuid.changed' => \&_update_entry_uuid,
1415 'group.uuid.changed' => \&_update_group_uuid,
1416 );
1417 my $handler = $handlers{$type} or return;
1418 $self->$handler($object, @_);
1419 }
1420
1421 sub _update_group_uuid {
1422 my $self = shift;
1423 my $object = shift;
1424 my $new_uuid = shift;
1425 my $old_uuid = shift // return;
1426
1427 my $meta = $self->meta;
1428 $self->recycle_bin_uuid($new_uuid) if $old_uuid eq ($meta->{recycle_bin_uuid} // '');
1429 $self->entry_templates_group($new_uuid) if $old_uuid eq ($meta->{entry_templates_group} // '');
1430 $self->last_selected_group($new_uuid) if $old_uuid eq ($meta->{last_selected_group} // '');
1431 $self->last_top_visible_group($new_uuid) if $old_uuid eq ($meta->{last_top_visible_group} // '');
1432
1433 for my $group (@{$self->all_groups}) {
1434 $group->last_top_visible_entry($new_uuid) if $old_uuid eq ($group->{last_top_visible_entry} // '');
1435 $group->previous_parent_group($new_uuid) if $old_uuid eq ($group->{previous_parent_group} // '');
1436 }
1437 for my $entry (@{$self->all_entries}) {
1438 $entry->previous_parent_group($new_uuid) if $old_uuid eq ($entry->{previous_parent_group} // '');
1439 }
1440 }
1441
1442 sub _update_entry_uuid {
1443 my $self = shift;
1444 my $object = shift;
1445 my $new_uuid = shift;
1446 my $old_uuid = shift // return;
1447
1448 my $old_pretty = format_uuid($old_uuid);
1449 my $new_pretty = format_uuid($new_uuid);
1450 my $fieldref_match = qr/\{REF:([TUPANI])\@I:\Q$old_pretty\E\}/is;
1451
1452 for my $entry (@{$self->all_entries}) {
1453 $entry->previous_parent_group($new_uuid) if $old_uuid eq ($entry->{previous_parent_group} // '');
1454
1455 for my $string (values %{$entry->strings}) {
1456 next if !defined $string->{value} || $string->{value} !~ $fieldref_match;
1457 my $txn = $entry->begin_work;
1458 $string->{value} =~ s/$fieldref_match/{REF:$1\@I:$new_pretty}/g;
1459 $txn->commit;
1460 }
1461 }
1462 }
1463
1464 #########################################################################################
1465
1466 =attr comment
1467
1468 A text string associated with the database. Often unset.
1469
1470 =attr cipher_id
1471
1472 The UUID of a cipher used to encrypt the database when stored as a file.
1473
1474 See L</File::KDBX::Cipher>.
1475
1476 =attr compression_flags
1477
1478 Configuration for whether or not and how the database gets compressed. See
1479 L<File::KDBX::Constants/":compression">.
1480
1481 =attr master_seed
1482
1483 The master seed is a string of 32 random bytes that is used as salt in hashing the master key when loading
1484 and saving the database. If a challenge-response key is used in the master key, the master seed is also the
1485 challenge.
1486
1487 The master seed I<should> be changed each time the database is saved to file.
1488
1489 =attr transform_seed
1490
1491 The transform seed is a string of 32 random bytes that is used in the key derivation function, either as the
1492 salt or the key (depending on the algorithm).
1493
1494 The transform seed I<should> be changed each time the database is saved to file.
1495
1496 =attr transform_rounds
1497
1498 The number of rounds or iterations used in the key derivation function. Increasing this number makes loading
1499 and saving the database slower by design in order to make dictionary and brute force attacks more costly.
1500
1501 =attr encryption_iv
1502
1503 The initialization vector used by the cipher.
1504
1505 The encryption IV I<should> be changed each time the database is saved to file.
1506
1507 =attr inner_random_stream_key
1508
1509 The encryption key (possibly including the IV, depending on the cipher) used to encrypt the protected strings
1510 within the database.
1511
1512 =attr stream_start_bytes
1513
1514 A string of 32 random bytes written in the header and encrypted in the body. If the bytes do not match when
1515 loading a file then the wrong master key was used or the file is corrupt. Only KDBX 2 and KDBX 3 files use
1516 this. KDBX 4 files use an improved HMAC method to verify the master key and data integrity of the header and
1517 entire file body.
1518
1519 =attr inner_random_stream_id
1520
1521 A number indicating the cipher algorithm used to encrypt the protected strings within the database, usually
1522 Salsa20 or ChaCha20. See L<File::KDBX::Constants/":random_stream">.
1523
1524 =attr kdf_parameters
1525
1526 A hash/dict of key-value pairs used to configure the key derivation function. This is the KDBX4+ way to
1527 configure the KDF, superceding L</transform_seed> and L</transform_rounds>.
1528
1529 =attr generator
1530
1531 The name of the software used to generate the KDBX file.
1532
1533 =attr header_hash
1534
1535 The header hash used to verify that the file header is not corrupt. (KDBX 2 - KDBX 3.1, removed KDBX 4.0)
1536
1537 =attr database_name
1538
1539 Name of the database.
1540
1541 =attr database_name_changed
1542
1543 Timestamp indicating when the database name was last changed.
1544
1545 =attr database_description
1546
1547 Description of the database
1548
1549 =attr database_description_changed
1550
1551 Timestamp indicating when the database description was last changed.
1552
1553 =attr default_username
1554
1555 When a new entry is created, the I<UserName> string will be populated with this value.
1556
1557 =attr default_username_changed
1558
1559 Timestamp indicating when the default username was last changed.
1560
1561 =attr maintenance_history_days
1562
1563 TODO... not really sure what this is. 😀
1564
1565 =attr color
1566
1567 A color associated with the database (in the form C<#ffffff> where "f" is a hexidecimal digit). Some agents
1568 use this to help users visually distinguish between different databases.
1569
1570 =attr master_key_changed
1571
1572 Timestamp indicating when the master key was last changed.
1573
1574 =attr master_key_change_rec
1575
1576 Number of days until the agent should prompt to recommend changing the master key.
1577
1578 =attr master_key_change_force
1579
1580 Number of days until the agent should prompt to force changing the master key.
1581
1582 Note: This is purely advisory. It is up to the individual agent software to actually enforce it.
1583 C<File::KDBX> does NOT enforce it.
1584
1585 =attr recycle_bin_enabled
1586
1587 Boolean indicating whether removed groups and entries should go to a recycle bin or be immediately deleted.
1588
1589 =attr recycle_bin_uuid
1590
1591 The UUID of a group used to store thrown-away groups and entries.
1592
1593 =attr recycle_bin_changed
1594
1595 Timestamp indicating when the recycle bin was last changed.
1596
1597 =attr entry_templates_group
1598
1599 The UUID of a group containing template entries used when creating new entries.
1600
1601 =attr entry_templates_group_changed
1602
1603 Timestamp indicating when the entry templates group was last changed.
1604
1605 =attr last_selected_group
1606
1607 The UUID of the previously-selected group.
1608
1609 =attr last_top_visible_group
1610
1611 The UUID of the group visible at the top of the list.
1612
1613 =attr history_max_items
1614
1615 The maximum number of historical entries allowed to be saved for each entry.
1616
1617 =attr history_max_size
1618
1619 The maximum total size (in bytes) that each individual entry's history is allowed to grow.
1620
1621 =attr settings_changed
1622
1623 Timestamp indicating when the database settings were last updated.
1624
1625 =attr protect_title
1626
1627 Alias of the L</memory_protection> setting for the I<Title> string.
1628
1629 =attr protect_username
1630
1631 Alias of the L</memory_protection> setting for the I<UserName> string.
1632
1633 =attr protect_password
1634
1635 Alias of the L</memory_protection> setting for the I<Password> string.
1636
1637 =attr protect_url
1638
1639 Alias of the L</memory_protection> setting for the I<URL> string.
1640
1641 =attr protect_notes
1642
1643 Alias of the L</memory_protection> setting for the I<Notes> string.
1644
1645 =cut
1646
1647 #########################################################################################
1648
1649 sub TO_JSON { +{%{$_[0]}} }
1650
1651 1;
1652 __END__
1653
1654 =for Pod::Coverage STORABLE_freeze STORABLE_thaw TO_JSON
1655
1656 =head1 SYNOPSIS
1657
1658 use File::KDBX;
1659
1660 my $kdbx = File::KDBX->new;
1661
1662 my $group = $kdbx->add_group(
1663 name => 'Passwords',
1664 );
1665
1666 my $entry = $group->add_entry(
1667 title => 'My Bank',
1668 password => 's3cr3t',
1669 );
1670
1671 $kdbx->dump_file('passwords.kdbx', 'M@st3rP@ssw0rd!');
1672
1673 $kdbx = File::KDBX->load_file('passwords.kdbx', 'M@st3rP@ssw0rd!');
1674
1675 for my $entry (@{ $kdbx->all_entries }) {
1676 say 'Entry: ', $entry->title;
1677 }
1678
1679 =head1 DESCRIPTION
1680
1681 B<File::KDBX> provides everything you need to work with a KDBX database. A KDBX database is a hierarchical
1682 object database which is commonly used to store secret information securely. It was developed for the KeePass
1683 password safe. See L</"KDBX Introduction"> for more information about KDBX.
1684
1685 This module lets you query entries, create new entries, delete entries and modify entries. The distribution
1686 also includes various parsers and generators for serializing and persisting databases.
1687
1688 This design of this software was influenced by the L<KeePassXC|https://github.com/keepassxreboot/keepassxc>
1689 implementation of KeePass as well as the L<File::KeePass> module. B<File::KeePass> is an alternative module
1690 that works well in most cases but has a small backlog of bugs and security issues and also does not work with
1691 newer KDBX version 4 files. If you're coming here from the B<File::KeePass> world, you might be interested in
1692 L<File::KeePass::KDBX> that is a drop-in replacement for B<File::KeePass> that uses B<File::KDBX> for storage.
1693
1694 =head2 KDBX Introduction
1695
1696 A KDBX database consists of a hierarchical I<group> of I<entries>. Entries can contain zero or more key-value
1697 pairs of I<strings> and zero or more I<binaries> (i.e. octet strings). Groups, entries, strings and binaries:
1698 that's the KDBX vernacular. A small amount of metadata (timestamps, etc.) is associated with each entry, group
1699 and the database as a whole.
1700
1701 You can think of a KDBX database kind of like a file system, where groups are directories, entries are files,
1702 and strings and binaries make up a file's contents.
1703
1704 Databases are typically persisted as a encrypted, compressed files. They are usually accessed directly (i.e.
1705 not over a network). The primary focus of this type of database is data security. It is ideal for storing
1706 relatively small amounts of data (strings and binaries) that must remain secret except to such individuals as
1707 have the correct I<master key>. Even if the database file were to be "leaked" to the public Internet, it
1708 should be virtually impossible to crack with a strong key. See L</SECURITY> for an overview of security
1709 considerations.
1710
1711 =head1 RECIPES
1712
1713 =head2 Create a new database
1714
1715 my $kdbx = File::KDBX->new;
1716
1717 my $group = $kdbx->add_group(name => 'Passwords);
1718 my $entry = $group->add_entry(
1719 title => 'WayneCorp',
1720 username => 'bwayne',
1721 password => 'iambatman',
1722 url => 'https://example.com/login'
1723 );
1724 $entry->add_auto_type_window_association('WayneCorp - Mozilla Firefox', '{PASSWORD}{ENTER}');
1725
1726 $kdbx->dump_file('mypasswords.kdbx', 'master password CHANGEME');
1727
1728 =head2 Read an existing database
1729
1730 my $kdbx = File::KDBX->load_file('mypasswords.kdbx', 'master password CHANGEME');
1731 $kdbx->unlock;
1732
1733 for my $entry (@{ $kdbx->all_entries }) {
1734 say 'Found password for ', $entry->title, ':';
1735 say ' Username: ', $entry->username;
1736 say ' Password: ', $entry->password;
1737 }
1738
1739 =head2 Search for entries
1740
1741 my @entries = $kdbx->find_entries({
1742 title => 'WayneCorp',
1743 }, search => 1);
1744
1745 See L</QUERY> for many more query examples.
1746
1747 =head2 Search for entries by auto-type window association
1748
1749 my @entry_key_sequences = $kdbx->find_entries_for_window('WayneCorp - Mozilla Firefox');
1750 for my $pair (@entry_key_sequences) {
1751 my ($entry, $key_sequence) = @$pair;
1752 say 'Entry title: ', $entry->title, ', key sequence: ', $key_sequence;
1753 }
1754
1755 Example output:
1756
1757 Entry title: WayneCorp, key sequence: {PASSWORD}{ENTER}
1758
1759 =head1 SECURITY
1760
1761 One of the biggest threats to your database security is how easily the encryption key can be brute-forced.
1762 Strong brute-force protection depends on a couple factors:
1763
1764 =for :list
1765 * Using unguessable passwords, passphrases and key files.
1766 * Using a brute-force resistent key derivation function.
1767
1768 The first factor is up to you. This module does not enforce strong master keys. It is up to you to pick or
1769 generate strong keys.
1770
1771 The KDBX format allows for the key derivation function to be tuned. The idea is that you want each single
1772 brute-foce attempt to be expensive (in terms of time, CPU usage or memory usage), so that making a lot of
1773 attempts (which would be required if you have a strong master key) gets I<really> expensive.
1774
1775 How expensive you want to make each attempt is up to you and can depend on the application.
1776
1777 This and other KDBX-related security issues are covered here more in depth:
1778 L<https://keepass.info/help/base/security.html>
1779
1780 Here are other security risks you should be thinking about:
1781
1782 =head2 Cryptography
1783
1784 This distribution uses the excellent L<CryptX> and L<Crypt::Argon2> packages to handle all crypto-related
1785 functions. As such, a lot of the security depends on the quality of these dependencies. Fortunately these
1786 modules are maintained and appear to have good track records.
1787
1788 The KDBX format has evolved over time to incorporate improved security practices and cryptographic functions.
1789 This package uses the following functions for authentication, hashing, encryption and random number
1790 generation:
1791
1792 =for :list
1793 * AES-128 (legacy)
1794 * AES-256
1795 * Argon2d & Argon2id
1796 * CBC block mode
1797 * HMAC-SHA256
1798 * SHA256
1799 * SHA512
1800 * Salsa20 & ChaCha20
1801 * Twofish
1802
1803 At the time of this writing, I am not aware of any successful attacks against any of these functions. These
1804 are among the most-analyzed and widely-adopted crypto functions available.
1805
1806 The KDBX format allows the body cipher and key derivation function to be configured. If a flaw is discovered
1807 in one of these functions, you can hopefully just switch to a better function without needing to update this
1808 software. A later software release may phase out the use of any functions which are no longer secure.
1809
1810 =head2 Memory Protection
1811
1812 It is not a good idea to keep secret information unencrypted in system memory for longer than is needed. The
1813 address space of your program can generally be read by a user with elevated privileges on the system. If your
1814 system is memory-constrained or goes into a hibernation mode, the contents of your address space could be
1815 written to a disk where it might be persisted for long time.
1816
1817 There might be system-level things you can do to reduce your risk, like using swap encryption and limiting
1818 system access to your program's address space while your program is running.
1819
1820 B<File::KDBX> helps minimize (but not eliminate) risk by keeping secrets encrypted in memory until accessed
1821 and zeroing out memory that holds secrets after they're no longer needed, but it's not a silver bullet.
1822
1823 For one thing, the encryption key is stored in the same address space. If core is dumped, the encryption key
1824 is available to be found out. But at least there is the chance that the encryption key and the encrypted
1825 secrets won't both be paged out while memory-constrained.
1826
1827 Another problem is that some perls (somewhat notoriously) copy around memory behind the scenes willy nilly,
1828 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
1829 be impossible. The good news is that perls with SvPV copy-on-write (enabled by default beginning with perl
1830 5.20) are much better in this regard. With COW, it's mostly possible to know what operations will cause perl
1831 to copy the memory of a scalar string, and the number of copies will be significantly reduced. There is a unit
1832 test named F<t/memory-protection.t> in this distribution that can be run on POSIX systems to determine how
1833 well B<File::KDBX> memory protection is working.
1834
1835 Memory protection also depends on how your application handles secrets. If your app code is handling scalar
1836 strings with secret information, it's up to you to make sure its memory is zeroed out when no longer needed.
1837 L<File::KDBX::Util/erase> et al. provide some tools to help accomplish this. Or if you're not too concerned
1838 about the risks memory protection is meant to mitigate, then maybe don't worry about it. The security policy
1839 of B<File::KDBX> is to try hard to keep secrets protected while in memory so that your app might claim a high
1840 level of security, in case you care about that.
1841
1842 There are some memory protection strategies that B<File::KDBX> does NOT use today but could in the future:
1843
1844 Many systems allow programs to mark unswappable pages. Secret information should ideally be stored in such
1845 pages. You could potentially use L<mlockall(2)> (or equivalent for your system) in your own application to
1846 prevent the entire address space from being swapped.
1847
1848 Some systems provide special syscalls for storing secrets in memory while keeping the encryption key outside
1849 of the program's address space, like C<CryptProtectMemory> for Windows. This could be a good option, though
1850 unfortunately not portable.
1851
1852 =head1 QUERY
1853
1854 Several methods take a I<query> as an argument (e.g. L</find_entries>). A query is just a subroutine that you
1855 can either write yourself or have generated for you based on either a simple expression or a declarative
1856 structure. It's easier to have your query generated, so I'll cover that first.
1857
1858 =head2 Simple Expression
1859
1860 A simple expression is mostly compatible with the KeePass 2 implementation
1861 L<described here|https://keepass.info/help/base/search.html#mode_se>.
1862
1863 An expression is a string with one or more space-separated terms. Terms with spaces can be enclosed in double
1864 quotes. Terms are negated if they are prefixed with a minus sign. A record must match every term on at least
1865 one of the given fields.
1866
1867 So a simple expression is something like what you might type into a search engine. You can generate a simple
1868 expression query using L<File::KDBX::Util/simple_expression_query> or by passing the simple expression as
1869 a B<string reference> to search methods like L</find_entries>.
1870
1871 To search for all entries in a database with the word "canyon" appearing anywhere in the title:
1872
1873 my @entries = $kdbx->find_entries([ \'canyon', qw(title) ]);
1874
1875 Notice the first argument is a B<stringref>. This diambiguates a simple expression from other types of queries
1876 covered below.
1877
1878 As mentioned, a simple expression can have multiple terms. This simple expression query matches any entry that
1879 has the words "red" B<and> "canyon" anywhere in the title:
1880
1881 my @entries = $kdbx->find_entries([ \'red canyon', qw(title) ]);
1882
1883 Each term in the simple expression must be found for an entry to match.
1884
1885 To search for entries with "red" in the title but B<not> "canyon", just prepend "canyon" with a minus sign:
1886
1887 my @entries = $kdbx->find_entries([ \'red -canyon', qw(title) ]);
1888
1889 To search over multiple fields simultaneously, just list them. To search for entries with "grocery" in the
1890 title or notes but not "Foodland":
1891
1892 my @entries = $kdbx->find_entries([ \'grocery -Foodland', qw(title notes) ]);
1893
1894 The default operator is a case-insensitive regexp match, which is fine for searching text loosely. You can use
1895 just about any binary comparison operator that perl supports. To specify an operator, list it after the simple
1896 expression. For example, to search for any entry that has been used at least five times:
1897
1898 my @entries = $kdbx->find_entries([ \5, '>=', qw(usage_count) ]);
1899
1900 It helps to read it right-to-left, like "usage_count is >= 5".
1901
1902 If you find the disambiguating structures to be confusing, you can also the L</find_entries_simple> method as
1903 a more intuitive alternative. The following example is equivalent to the previous:
1904
1905 my @entries = $kdbx->find_entries_simple(5, '>=', qw(usage_count));
1906
1907 =head2 Declarative Query
1908
1909 Structuring a declarative query is similar to L<SQL::Abstract/"WHERE CLAUSES">, but you don't have to be
1910 familiar with that module. Just learn by examples.
1911
1912 To search for all entries in a database titled "My Bank":
1913
1914 my @entries = $kdbx->find_entries({ title => 'My Bank' });
1915
1916 The query here is C<< { title => 'My Bank' } >>. A hashref can contain key-value pairs where the key is
1917 a attribute of the thing being searched for (in this case an entry) and the value is what you want the thing's
1918 attribute to be to consider it a match. In this case, the attribute we're using as our match criteria is
1919 L<File::KDBX::Entry/title>, a text field. If an entry has its title attribute equal to "My Bank", it's
1920 a match.
1921
1922 A hashref can contain multiple attributes. The search candidate will be a match if I<all> of the specified
1923 attributes are equal to their respective values. For example, to search for all entries with a particular URL
1924 B<AND> username:
1925
1926 my @entries = $kdbx->find_entries({
1927 url => 'https://example.com',
1928 username => 'neo',
1929 });
1930
1931 To search for entries matching I<any> criteria, just change the hashref to an arrayref. To search for entries
1932 with a particular URL B<OR> a particular username:
1933
1934 my @entries = $kdbx->find_entries([ # <-- square bracket
1935 url => 'https://example.com',
1936 username => 'neo',
1937 ]);
1938
1939 You can user different operators to test different types of attributes. The L<File::KDBX::Entry/icon_id>
1940 attribute is a number, so we should use a number comparison operator. To find entries using the smartphone
1941 icon:
1942
1943 my @entries = $kdbx->find_entries({
1944 icon_id => { '==', ICON_SMARTPHONE },
1945 });
1946
1947 Note: L<File::KDBX::Constants/ICON_SMARTPHONE> is just a constant from L<File::KDBX::Constants>. It isn't
1948 special to this example or to queries generally. We could have just used a literal number.
1949
1950 The important thing to notice here is how we wrapped the condition in another arrayref with a single key-pair
1951 where the key is the name of an operator and the value is the thing to match against. The supported operators
1952 are:
1953
1954 =for :list
1955 * C<eq> - String equal
1956 * C<ne> - String not equal
1957 * C<lt> - String less than
1958 * C<gt> - String greater than
1959 * C<le> - String less than or equal
1960 * C<ge> - String greater than or equal
1961 * C<==> - Number equal
1962 * C<!=> - Number not equal
1963 * C<< < >> - Number less than
1964 * C<< > >>> - Number greater than
1965 * C<< <= >> - Number less than or equal
1966 * C<< >= >> - Number less than or equal
1967 * C<=~> - String match regular expression
1968 * C<!~> - String does not match regular expression
1969 * C<!> - Boolean false
1970 * C<!!> - Boolean true
1971
1972 Other special operators:
1973
1974 =for :list
1975 * C<-true> - Boolean true
1976 * C<-false> - Boolean false
1977 * C<-not> - Boolean false (alias for C<-false>)
1978 * C<-defined> - Is defined
1979 * C<-undef> - Is not d efined
1980 * C<-empty> - Is empty
1981 * C<-nonempty> - Is not empty
1982 * C<-or> - Logical or
1983 * C<-and> - Logical and
1984
1985 Let's see another example using an explicit operator. To find all groups except one in particular (identified
1986 by its L<File::KDBX::Group/uuid>), we can use the C<ne> (string not equal) operator:
1987
1988 my ($group, @other) = $kdbx->find_groups({
1989 uuid => {
1990 'ne' => uuid('596f7520-6172-6520-7370-656369616c2e'),
1991 },
1992 });
1993 if (@other) { say "Problem: there can be only one!" }
1994
1995 Note: L<File::KDBX::Util/uuid> is a little helper function to convert a UUID in its pretty form into octets.
1996 This helper function isn't special to this example or to queries generally. It could have been written with
1997 a literal such as C<"\x59\x6f\x75\x20\x61...">, but that's harder to read.
1998
1999 Notice we searched for groups this time. Finding groups works exactly the same as it does for entries.
2000
2001 Testing the truthiness of an attribute is a little bit different because it isn't a binary operation. To find
2002 all entries with the password quality check disabled:
2003
2004 my @entries = $kdbx->find_entries({ '!' => 'quality_check' });
2005
2006 This time the string after the operator is the attribute name rather than a value to compare the attribute
2007 against. To test that a boolean value is true, use the C<!!> operator (or C<-true> if C<!!> seems a little too
2008 weird for your taste):
2009
2010 my @entries = $kdbx->find_entries({ '!!' => 'quality_check' });
2011 my @entries = $kdbx->find_entries({ -true => 'quality_check' });
2012
2013 Yes, there is also a C<-false> and a C<-not> if you prefer one of those over C<!>. C<-false> and C<-not>
2014 (along with C<-true>) are also special in that you can use them to invert the logic of a subquery. These are
2015 logically equivalent:
2016
2017 my @entries = $kdbx->find_entries([ -not => { title => 'My Bank' } ]);
2018 my @entries = $kdbx->find_entries({ title => { 'ne' => 'My Bank' } });
2019
2020 These special operators become more useful when combined with two more special operators: C<-and> and C<-or>.
2021 With these, it is possible to construct more interesting queries with groups of logic. For example:
2022
2023 my @entries = $kdbx->find_entries({
2024 title => { '=~', qr/bank/ },
2025 -not => {
2026 -or => {
2027 notes => { '=~', qr/business/ },
2028 icon_id => { '==', ICON_TRASHCAN_FULL },
2029 },
2030 },
2031 });
2032
2033 In English, find entries where the word "bank" appears anywhere in the title but also do not have either the
2034 word "business" in the notes or is using the full trashcan icon.
2035
2036 =head2 Subroutine Query
2037
2038 Lastly, as mentioned at the top, you can ignore all this and write your own subroutine. Your subroutine will
2039 be called once for each thing being searched over. The single argument is the search candidate. The subroutine
2040 should match the candidate against whatever criteria you want and return true if it matches. The C<find_*>
2041 methods collect all matching things and return them.
2042
2043 For example, to find all entries in the database titled "My Bank":
2044
2045 my @entries = $kdbx->find_entries(sub { shift->title eq 'My Bank' });
2046 # logically the same as this declarative structure:
2047 my @entries = $kdbx->find_entries({ title => 'My Bank' });
2048 # as well as this simple expression:
2049 my @entries = $kdbx->find_entries([ \'My Bank', 'eq', qw{title} ]);
2050
2051 This is a trivial example, but of course your subroutine can be arbitrarily complex.
2052
2053 All of these query mechanisms described in this section are just tools, each with its own set of limitations.
2054 If the tools are getting in your way, you can of course iterate over the contents of a database and implement
2055 your own query logic, like this:
2056
2057 for my $entry (@{ $kdbx->all_entries }) {
2058 if (wanted($entry)) {
2059 do_something($entry);
2060 }
2061 else {
2062 ...
2063 }
2064 }
2065
2066 =head1 ERRORS
2067
2068 Errors in this package are constructed as L<File::KDBX::Error> objects and propagated using perl's built-in
2069 mechanisms. Fatal errors are propagated using L<functions/die> and non-fatal errors (a.k.a. warnings) are
2070 propagated using L<functions/warn> while adhering to perl's L<warnings> system. If you're already familiar
2071 with these mechanisms, you can skip this section.
2072
2073 You can catch fatal errors using L<functions/eval> (or something like L<Try::Tiny>) and non-fatal errors using
2074 C<$SIG{__WARN__}> (see L<variables/%SIG>). Examples:
2075
2076 use File::KDBX::Error qw(error);
2077
2078 my $key = ''; # uh oh
2079 eval {
2080 $kdbx->load_file('whatever.kdbx', $key);
2081 };
2082 if (my $error = error($@)) {
2083 handle_missing_key($error) if $error->type eq 'key.missing';
2084 $error->throw;
2085 }
2086
2087 or using C<Try::Tiny>:
2088
2089 try {
2090 $kdbx->load_file('whatever.kdbx', $key);
2091 }
2092 catch {
2093 handle_error($_);
2094 };
2095
2096 Catching non-fatal errors:
2097
2098 my @warnings;
2099 local $SIG{__WARN__} = sub { push @warnings, $_[0] };
2100
2101 $kdbx->load_file('whatever.kdbx', $key);
2102
2103 handle_warnings(@warnings) if @warnings;
2104
2105 By default perl prints warnings to C<STDERR> if you don't catch them. If you don't want to catch them and also
2106 don't want them printed to C<STDERR>, you can suppress them lexically (perl v5.28 or higher required):
2107
2108 {
2109 no warnings 'File::KDBX';
2110 ...
2111 }
2112
2113 or locally:
2114
2115 {
2116 local $File::KDBX::WARNINGS = 0;
2117 ...
2118 }
2119
2120 or globally in your program:
2121
2122 $File::KDBX::WARNINGS = 0;
2123
2124 You cannot suppress fatal errors, and if you don't catch them your program will exit.
2125
2126 =head1 ENVIRONMENT
2127
2128 This software will alter its behavior depending on the value of certain environment variables:
2129
2130 =for :list
2131 * C<PERL_FILE_KDBX_XS> - Do not use L<File::KDBX::XS> if false (default: true)
2132 * C<PERL_ONLY> - Do not use L<File::KDBX::XS> if true (default: false)
2133 * C<NO_FORK> - Do not fork if true (default: false)
2134
2135 =head1 CAVEATS
2136
2137 Some features (e.g. parsing) require 64-bit perl. It should be possible and actually pretty easy to make it
2138 work using L<Math::BigInt>, but I need to build a 32-bit perl in order to test it and frankly I'm still
2139 figuring out how. I'm sure it's simple so I'll mark this one "TODO", but for now an exception will be thrown
2140 when trying to use such features with undersized IVs.
2141
2142 =head1 SEE ALSO
2143
2144 L<File::KeePass> is a much older alternative. It's good but has a backlog of bugs and lacks support for newer
2145 KDBX features.
2146
2147 =attr sig1
2148
2149 =attr sig2
2150
2151 =attr version
2152
2153 =attr headers
2154
2155 =attr inner_headers
2156
2157 =attr meta
2158
2159 =attr binaries
2160
2161 =attr deleted_objects
2162
2163 =attr raw
2164
2165 $value = $kdbx->$attr;
2166 $kdbx->$attr($value);
2167
2168 Get and set attributes.
2169
2170 =cut
This page took 0.197488 seconds and 4 git commands to generate.