File: Loader.pm

package info (click to toggle)
libfile-kdbx-perl 0.906-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,052 kB
  • sloc: perl: 10,607; makefile: 2
file content (446 lines) | stat: -rw-r--r-- 10,461 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
package File::KDBX::Loader;
# ABSTRACT: Load KDBX files

use warnings;
use strict;

use File::KDBX::Constants qw(:magic :header :version);
use File::KDBX::Error;
use File::KDBX::Util qw(:class :io);
use File::KDBX;
use IO::Handle;
use Module::Load ();
use Ref::Util qw(is_ref is_scalarref);
use Scalar::Util qw(looks_like_number openhandle);
use namespace::clean;

our $VERSION = '0.906'; # VERSION


sub new {
    my $class = shift;
    my $self = bless {}, $class;
    $self->init(@_);
}


sub init {
    my $self = shift;
    my %args = @_;

    @$self{keys %args} = values %args;

    return $self;
}

sub _rebless {
    my $self    = shift;
    my $format  = shift // $self->format;

    my $sig2    = $self->kdbx->sig2;
    my $version = $self->kdbx->version;

    my $subclass;

    if (defined $format) {
        $subclass = $format;
    }
    elsif (defined $sig2 && $sig2 == KDBX_SIG2_1) {
        $subclass = 'KDB';
    }
    elsif (looks_like_number($version)) {
        my $major = $version & KDBX_VERSION_MAJOR_MASK;
        my %subclasses = (
            KDBX_VERSION_2_0() => 'V3',
            KDBX_VERSION_3_0() => 'V3',
            KDBX_VERSION_4_0() => 'V4',
        );
        $subclass = $subclasses{$major}
            or throw sprintf('Unsupported KDBX file version: %x', $version), version => $version;
    }
    else {
        throw sprintf('Unknown file version: %s', $version), version => $version;
    }

    Module::Load::load "File::KDBX::Loader::$subclass";
    bless $self, "File::KDBX::Loader::$subclass";
}


sub reset {
    my $self = shift;
    %$self = ();
    return $self;
}


sub load {
    my $self = shift;
    my $src  = shift;
    return $self->load_handle($src, @_) if openhandle($src) || $src eq '-';
    return $self->load_string($src, @_) if is_scalarref($src);
    return $self->load_file($src, @_)   if !is_ref($src) && defined $src;
    throw 'Programmer error: Must pass a stringref, filepath or IO handle to read';
}


sub load_string {
    my $self = shift;
    my $str  = shift or throw 'Expected string to load';
    my %args = @_ % 2 == 0 ? @_ : (key => shift, @_);

    my $key = delete $args{key};
    $args{kdbx} //= $self->kdbx;

    my $ref = is_scalarref($str) ? $str : \$str;

    open(my $fh, '<', $ref) or throw "Failed to open string buffer: $!";

    $self = $self->new if !ref $self;
    $self->init(%args, fh => $fh)->_read($fh, $key);
    return $args{kdbx};
}


sub load_file {
    my $self     = shift;
    my $filepath = shift;
    my %args     = @_ % 2 == 0 ? @_ : (key => shift, @_);

    my $key = delete $args{key};
    $args{kdbx} //= $self->kdbx;

    open(my $fh, '<:raw', $filepath) or throw 'Open file failed', filepath => $filepath;

    $self = $self->new if !ref $self;
    $self->init(%args, fh => $fh, filepath => $filepath)->_read($fh, $key);
    return $args{kdbx};
}


sub load_handle {
    my $self = shift;
    my $fh   = shift;
    my %args     = @_ % 2 == 0 ? @_ : (key => shift, @_);

    $fh = *STDIN if $fh eq '-';

    my $key = delete $args{key};
    $args{kdbx} //= $self->kdbx;

    $self = $self->new if !ref $self;
    $self->init(%args, fh => $fh)->_read($fh, $key);
    return $args{kdbx};
}


sub kdbx {
    my $self = shift;
    return File::KDBX->new if !ref $self;
    $self->{kdbx} = shift if @_;
    $self->{kdbx} //= File::KDBX->new;
}


has format          => undef, is => 'ro';
has inner_format    => 'XML', is => 'ro';


sub read_magic_numbers {
    my $self = shift;
    my $fh   = shift;
    my $kdbx = shift // $self->kdbx;

    read_all $fh, my $magic, 12 or throw 'Failed to read file signature';

    my ($sig1, $sig2, $version) = unpack('L<3', $magic);

    if ($kdbx) {
        $kdbx->sig1($sig1);
        $kdbx->sig2($sig2);
        $kdbx->version($version);
        $self->_rebless if ref $self;
    }

    return wantarray ? ($sig1, $sig2, $version, $magic) : $magic;
}

sub _fh { $_[0]->{fh} or throw 'IO handle not set' }

sub _read {
    my $self = shift;
    my $fh   = shift;
    my $key  = shift;

    my $kdbx = $self->kdbx;
    $key //= $kdbx->key ? $kdbx->key->reload : undef;
    $kdbx->reset;

    read_all $fh, my $buf, 1 or throw 'Failed to read the first byte', type => 'parser';
    my $first = ord($buf);
    $fh->ungetc($first);
    if ($first != KDBX_SIG1_FIRST_BYTE) {
        # not a KDBX file... try skipping the outer layer
        return $self->_read_inner_body($fh);
    }

    my $magic = $self->read_magic_numbers($fh, $kdbx);
    $kdbx->sig1 == KDBX_SIG1 or throw 'Invalid file signature', type => 'parser', sig1 => $kdbx->sig1;

    if (ref($self) =~ /::(?:KDB|V[34])$/) {
        defined $key or throw 'Must provide a master key', type => 'key.missing';
    }

    my $headers = $self->_read_headers($fh);

    eval {
        $self->_read_body($fh, $key, "$magic$headers");
    };
    if (my $err = $@) {
        throw "Failed to load KDBX file: $err",
            error               => $err,
            compression_error   => $IO::Uncompress::Gunzip::GunzipError,
            crypt_error         => $File::KDBX::IO::Crypt::ERROR,
            hash_error          => $File::KDBX::IO::HashBLock::ERROR,
            hmac_error          => $File::KDBX::IO::HmacBLock::ERROR;
    }
}

sub _read_headers {
    my $self = shift;
    my $fh   = shift;

    my $headers = $self->kdbx->headers;
    my $all_raw = '';

    while (my ($type, $val, $raw) = $self->_read_header($fh)) {
        $all_raw .= $raw;
        last if $type == HEADER_END;
        $headers->{$type} = $val;
    }

    return $all_raw;
}

sub _read_body { die "Not implemented" }

sub _read_inner_body {
    my $self = shift;

    my $current_pkg = ref $self;
    require Scope::Guard;
    my $guard = Scope::Guard->new(sub { bless $self, $current_pkg });

    $self->_rebless($self->inner_format);
    $self->_read_inner_body(@_);
}

1;

__END__

=pod

=encoding UTF-8

=head1 NAME

File::KDBX::Loader - Load KDBX files

=head1 VERSION

version 0.906

=head1 DESCRIPTION

=head1 ATTRIBUTES

=head2 kdbx

    $kdbx = $loader->kdbx;
    $loader->kdbx($kdbx);

Get or set the L<File::KDBX> instance for storing the loaded data into.

=head2 format

Get the file format used for reading the database. Normally the format is auto-detected from the data stream.
This auto-detection works well, so there's not really a good reason to explicitly specify the format.
Possible formats:

=over 4

=item *

C<V3>

=item *

C<V4>

=item *

C<KDB>

=item *

C<XML>

=item *

C<Raw>

=back

=head2 inner_format

Get the format of the data inside the KDBX envelope. This only applies to C<V3> and C<V4> formats. Possible
formats:

=over 4

=item *

C<XML> - Read the database groups and entries as XML (default)

=item *

C<Raw> - Read and store the result in L<File::KDBX/raw> without parsing

=back

=head1 METHODS

=head2 new

    $loader = File::KDBX::Loader->new(%attributes);

Construct a new L<File::KDBX::Loader>.

=head2 init

    $loader = $loader->init(%attributes);

Initialize a L<File::KDBX::Loader> with a new set of attributes.

This is called by L</new>.

=head2 reset

    $loader = $loader->reset;

Set a L<File::KDBX::Loader> to a blank state, ready to load another KDBX file.

=head2 load

    $kdbx = File::KDBX::Loader->load(\$string, %options);
    $kdbx = File::KDBX::Loader->load(\$string, $key);
    $kdbx = File::KDBX::Loader->load(*IO, %options);
    $kdbx = File::KDBX::Loader->load(*IO, $key);
    $kdbx = File::KDBX::Loader->load($filepath, %options);
    $kdbx = File::KDBX::Loader->load($filepath, $key);

Load a KDBX file. This works as an instance or a class method. The C<$key> is either
a L<File::KDBX::Key> or a primitive castable to a Key object. Available options:

=over 4

=item *

C<key> - Alternative way to specify C<$key>

=back

=head2 load_string

    $kdbx = File::KDBX::Loader->load_string($string, %options);
    $kdbx = File::KDBX::Loader->load_string($string, $key);
    $kdbx = File::KDBX::Loader->load_string(\$string, %options);
    $kdbx = File::KDBX::Loader->load_string(\$string, $key);

Load a KDBX file from a string / memory buffer. This works as an instance or class method. Available options:

=over 4

=item *

C<key> - Alternative way to specify C<$key>

=back

=head2 load_file

    $kdbx = File::KDBX::Loader->load_file($filepath, %options);
    $kdbx = File::KDBX::Loader->load_file($filepath, $key);

Read a KDBX file from a filesystem. This works as an instance or class method. Available options:

=over 4

=item *

C<key> - Alternative way to specify C<$key>

=back

=head2 load_handle

    $kdbx = File::KDBX::Loader->load_handle($fh, %options);
    $kdbx = File::KDBX::Loader->load_handle($fh, $key);
    $kdbx = File::KDBX::Loader->load_handle(*IO, %options);
    $kdbx = File::KDBX::Loader->load_handle(*IO, $key);

Read a KDBX file from an input stream / file handle. This works as an instance or class method. Available
options:

=over 4

=item *

C<key> - Alternative way to specify C<$key>

=back

=head2 read_magic_numbers

    $magic = File::KDBX::Loader->read_magic_numbers($fh);
    ($sig1, $sig2, $version, $magic) = File::KDBX::Loader->read_magic_numbers($fh);

    $magic = $loader->read_magic_numbers($fh);
    ($sig1, $sig2, $version, $magic) = $loader->read_magic_numbers($fh);

Read exactly 12 bytes from an IO handle and parse them into the three magic numbers that begin
a KDBX file. This is a quick way to determine if a file is actually a KDBX file.

C<$sig1> should always be C<KDBX_SIG1> if reading an actual KDB or KDBX file.

C<$sig2> should be C<KDBX_SIG2_1> for KeePass 1 files and C<KDBX_SIG2_2> for KeePass 2 files.

C<$version> is the file version (e.g. C<0x00040001>).

C<$magic> is the raw 12 bytes read from the IO handle.

If called on an instance, the C<sig1>, C<sig2> and C<version> attributes will be set in the L</kdbx>
and the instance will be blessed into the correct loader subclass.

=head1 BUGS

Please report any bugs or feature requests on the bugtracker website
L<https://github.com/chazmcgarvey/File-KDBX/issues>

When submitting a bug or request, please include a test-file or a
patch to an existing test-file that illustrates the bug or desired
feature.

=head1 AUTHOR

Charles McGarvey <ccm@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2022 by Charles McGarvey.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut