]> Dogcows Code - chaz/p5-File-KDBX/blob - lib/File/KDBX/Loader.pm
6d289be0f091e94973de72a0bfedb9d3e9cbbbe4
[chaz/p5-File-KDBX] / lib / File / KDBX / Loader.pm
1 package File::KDBX::Loader;
2 # ABSTRACT: Load KDBX files
3
4 use warnings;
5 use strict;
6
7 use File::KDBX::Constants qw(:magic :header :version);
8 use File::KDBX::Error;
9 use File::KDBX::Util qw(:class :io);
10 use File::KDBX;
11 use IO::Handle;
12 use Module::Load ();
13 use Ref::Util qw(is_ref is_scalarref);
14 use Scalar::Util qw(looks_like_number openhandle);
15 use namespace::clean;
16
17 our $VERSION = '999.999'; # VERSION
18
19 =method new
20
21 $loader = File::KDBX::Loader->new(%attributes);
22
23 Construct a new L<File::KDBX::Loader>.
24
25 =cut
26
27 sub new {
28 my $class = shift;
29 my $self = bless {}, $class;
30 $self->init(@_);
31 }
32
33 =method init
34
35 $loader = $loader->init(%attributes);
36
37 Initialize a L<File::KDBX::Loader> with a new set of attributes.
38
39 This is called by L</new>.
40
41 =cut
42
43 sub init {
44 my $self = shift;
45 my %args = @_;
46
47 @$self{keys %args} = values %args;
48
49 return $self;
50 }
51
52 sub _rebless {
53 my $self = shift;
54 my $format = shift // $self->format;
55
56 my $sig2 = $self->kdbx->sig2;
57 my $version = $self->kdbx->version;
58
59 my $subclass;
60
61 if (defined $format) {
62 $subclass = $format;
63 }
64 elsif (defined $sig2 && $sig2 == KDBX_SIG2_1) {
65 $subclass = 'KDB';
66 }
67 elsif (looks_like_number($version)) {
68 my $major = $version & KDBX_VERSION_MAJOR_MASK;
69 my %subclasses = (
70 KDBX_VERSION_2_0() => 'V3',
71 KDBX_VERSION_3_0() => 'V3',
72 KDBX_VERSION_4_0() => 'V4',
73 );
74 $subclass = $subclasses{$major}
75 or throw sprintf('Unsupported KDBX file version: %x', $version), version => $version;
76 }
77 else {
78 throw sprintf('Unknown file version: %s', $version), version => $version;
79 }
80
81 Module::Load::load "File::KDBX::Loader::$subclass";
82 bless $self, "File::KDBX::Loader::$subclass";
83 }
84
85 =method reset
86
87 $loader = $loader->reset;
88
89 Set a L<File::KDBX::Loader> to a blank state, ready to load another KDBX file.
90
91 =cut
92
93 sub reset {
94 my $self = shift;
95 %$self = ();
96 return $self;
97 }
98
99 =method load
100
101 $kdbx = File::KDBX::Loader->load(\$string, $key);
102 $kdbx = File::KDBX::Loader->load(*IO, $key);
103 $kdbx = File::KDBX::Loader->load($filepath, $key);
104 $kdbx = $loader->load(...); # also instance method
105
106 Load a KDBX file.
107
108 The C<$key> is either a L<File::KDBX::Key> or a primitive that can be converted to a Key object.
109
110 =cut
111
112 sub load {
113 my $self = shift;
114 my $src = shift;
115 return $self->load_handle($src, @_) if openhandle($src) || $src eq '-';
116 return $self->load_string($src, @_) if is_scalarref($src);
117 return $self->load_file($src, @_) if !is_ref($src) && defined $src;
118 throw 'Programmer error: Must pass a stringref, filepath or IO handle to read';
119 }
120
121 =method load_string
122
123 $kdbx = File::KDBX::Loader->load_string($string, $key);
124 $kdbx = File::KDBX::Loader->load_string(\$string, $key);
125 $kdbx = $loader->load_string(...); # also instance method
126
127 Load a KDBX file from a string / memory buffer.
128
129 =cut
130
131 sub load_string {
132 my $self = shift;
133 my $str = shift or throw 'Expected string to load';
134 my %args = @_ % 2 == 0 ? @_ : (key => shift, @_);
135
136 my $key = delete $args{key};
137 $args{kdbx} //= $self->kdbx;
138
139 my $ref = is_scalarref($str) ? $str : \$str;
140
141 open(my $fh, '<', $ref) or throw "Failed to open string buffer: $!";
142
143 $self = $self->new if !ref $self;
144 $self->init(%args, fh => $fh)->_read($fh, $key);
145 return $args{kdbx};
146 }
147
148 =method load_file
149
150 $kdbx = File::KDBX::Loader->load_file($filepath, $key);
151 $kdbx = $loader->load_file(...); # also instance method
152
153 Read a KDBX file from a filesystem.
154
155 =cut
156
157 sub load_file {
158 my $self = shift;
159 my $filepath = shift;
160 my %args = @_ % 2 == 0 ? @_ : (key => shift, @_);
161
162 my $key = delete $args{key};
163 $args{kdbx} //= $self->kdbx;
164
165 open(my $fh, '<:raw', $filepath) or throw 'Open file failed', filepath => $filepath;
166
167 $self = $self->new if !ref $self;
168 $self->init(%args, fh => $fh, filepath => $filepath)->_read($fh, $key);
169 return $args{kdbx};
170 }
171
172 =method load_handle
173
174 $kdbx = File::KDBX::Loader->load_handle($fh, $key);
175 $kdbx = File::KDBX::Loader->load_handle(*IO, $key);
176 $kdbx->load_handle(...); # also instance method
177
178 Read a KDBX file from an input stream / file handle.
179
180 =cut
181
182 sub load_handle {
183 my $self = shift;
184 my $fh = shift;
185 my %args = @_ % 2 == 0 ? @_ : (key => shift, @_);
186
187 $fh = *STDIN if $fh eq '-';
188
189 my $key = delete $args{key};
190 $args{kdbx} //= $self->kdbx;
191
192 $self = $self->new if !ref $self;
193 $self->init(%args, fh => $fh)->_read($fh, $key);
194 return $args{kdbx};
195 }
196
197 =attr kdbx
198
199 $kdbx = $loader->kdbx;
200 $loader->kdbx($kdbx);
201
202 Get or set the L<File::KDBX> instance for storing the loaded data into.
203
204 =cut
205
206 sub kdbx {
207 my $self = shift;
208 return File::KDBX->new if !ref $self;
209 $self->{kdbx} = shift if @_;
210 $self->{kdbx} //= File::KDBX->new;
211 }
212
213 =attr format
214
215 Get the file format used for reading the database. Normally the format is auto-detected from the data stream.
216 This auto-detection works well, so there's not really a good reason to explicitly specify the format.
217 Possible formats:
218
219 =for :list
220 * C<V3>
221 * C<V4>
222 * C<KDB>
223 * C<XML>
224 * C<Raw>
225
226 =attr inner_format
227
228 Get the format of the data inside the KDBX envelope. This only applies to C<V3> and C<V4> formats. Possible
229 formats:
230
231 =for :list
232 * C<XML> - Read the database groups and entries as XML (default)
233 * C<Raw> - Read parsing and store the result in L<File::KDBX/raw>
234
235 =cut
236
237 has format => undef, is => 'ro';
238 has inner_format => 'XML', is => 'ro';
239
240 =method min_version
241
242 $min_version = File::KDBX::Loader->min_version;
243
244 Get the minimum KDBX file version supported, which is 3.0 or C<0x00030000> as
245 it is encoded.
246
247 To read older KDBX files unsupported by this module, try L<File::KeePass>.
248
249 =cut
250
251 sub min_version { KDBX_VERSION_OLDEST }
252
253 =method read_magic_numbers
254
255 $magic = File::KDBX::Loader->read_magic_numbers($fh);
256 ($sig1, $sig2, $version, $magic) = File::KDBX::Loader->read_magic_numbers($fh);
257
258 $magic = $loader->read_magic_numbers($fh);
259 ($sig1, $sig2, $version, $magic) = $loader->read_magic_numbers($fh);
260
261 Read exactly 12 bytes from an IO handle and parse them into the three magic numbers that begin
262 a KDBX file. This is a quick way to determine if a file is actually a KDBX file.
263
264 C<$sig1> should always be C<KDBX_SIG1> if reading an actual KDB or KDBX file.
265
266 C<$sig2> should be C<KDBX_SIG2_1> for KeePass 1 files and C<KDBX_SIG2_2> for KeePass 2 files.
267
268 C<$version> is the file version (e.g. C<0x00040001>).
269
270 C<$magic> is the raw 12 bytes read from the IO handle.
271
272 If called on an instance, the C<sig1>, C<sig2> and C<version> attributes will be set in the L</kdbx>
273 and the instance will be blessed into the correct loader subclass.
274
275 =cut
276
277 sub read_magic_numbers {
278 my $self = shift;
279 my $fh = shift;
280 my $kdbx = shift // $self->kdbx;
281
282 read_all $fh, my $magic, 12 or throw 'Failed to read file signature';
283
284 my ($sig1, $sig2, $version) = unpack('L<3', $magic);
285
286 if ($kdbx) {
287 $kdbx->sig1($sig1);
288 $kdbx->sig2($sig2);
289 $kdbx->version($version);
290 $self->_rebless if ref $self;
291 }
292
293 return wantarray ? ($sig1, $sig2, $version, $magic) : $magic;
294 }
295
296 sub _fh { $_[0]->{fh} or throw 'IO handle not set' }
297
298 sub _read {
299 my $self = shift;
300 my $fh = shift;
301 my $key = shift;
302
303 my $kdbx = $self->kdbx;
304 $key //= $kdbx->key ? $kdbx->key->reload : undef;
305 $kdbx->reset;
306
307 read_all $fh, my $buf, 1 or throw 'Failed to read the first byte', type => 'parser';
308 my $first = ord($buf);
309 $fh->ungetc($first);
310 if ($first != KDBX_SIG1_FIRST_BYTE) {
311 # not a KDBX file... try skipping the outer layer
312 return $self->_read_inner_body($fh);
313 }
314
315 my $magic = $self->read_magic_numbers($fh, $kdbx);
316 $kdbx->sig1 == KDBX_SIG1 or throw 'Invalid file signature', type => 'parser', sig1 => $kdbx->sig1;
317
318 if (ref($self) =~ /::(?:KDB|V[34])$/) {
319 defined $key or throw 'Must provide a master key', type => 'key.missing';
320 }
321
322 my $headers = $self->_read_headers($fh);
323
324 eval {
325 $self->_read_body($fh, $key, "$magic$headers");
326 };
327 if (my $err = $@) {
328 throw "Failed to load KDBX file: $err",
329 error => $err,
330 compression_error => $IO::Uncompress::Gunzip::GunzipError,
331 crypt_error => $File::KDBX::IO::Crypt::ERROR,
332 hash_error => $File::KDBX::IO::HashBLock::ERROR,
333 hmac_error => $File::KDBX::IO::HmacBLock::ERROR;
334 }
335 }
336
337 sub _read_headers {
338 my $self = shift;
339 my $fh = shift;
340
341 my $headers = $self->kdbx->headers;
342 my $all_raw = '';
343
344 while (my ($type, $val, $raw) = $self->_read_header($fh)) {
345 $all_raw .= $raw;
346 last if $type == HEADER_END;
347 $headers->{$type} = $val;
348 }
349
350 return $all_raw;
351 }
352
353 sub _read_body { die "Not implemented" }
354
355 sub _read_inner_body {
356 my $self = shift;
357
358 my $current_pkg = ref $self;
359 require Scope::Guard;
360 my $guard = Scope::Guard->new(sub { bless $self, $current_pkg });
361
362 $self->_rebless($self->inner_format);
363 $self->_read_inner_body(@_);
364 }
365
366 1;
367 __END__
368
369 =head1 DESCRIPTION
370
371
372 =cut
This page took 0.049299 seconds and 3 git commands to generate.