Debian Codegraph @

README

raw
1 NAME
2 File::KeePass - Interface to KeePass V1 and V2 database files
3
4 SYNOPSIS
5 use File::KeePass;
6 use Data::Dumper qw(Dumper);
7
8 my $k = File::KeePass->new;
9
10 # read a version 1 or version 2 database
11 $k->load_db($file, $master_pass); # errors die
12
13 print Dumper $k->header;
14 print Dumper $k->groups; # passwords are locked
15
16 $k->unlock;
17 print Dumper $k->groups; # passwords are now visible
18
19 $k->clear; # delete current db from memory
20
21
22 my $group = $k->add_group({
23 title => 'Foo',
24 }); # root level group
25 my $gid = $group->{'id'};
26
27 my $group = $k->find_group({id => $gid});
28 # OR
29 my $group = $k->find_group({title => 'Foo'});
30
31
32 my $group2 = $k->add_group({
33 title => 'Bar',
34 group => $gid,
35 # OR group => $group,
36 }); # nested group
37
38
39 my $e = $k->add_entry({
40 title => 'Something',
41 username => 'someuser',
42 password => 'somepass',
43 group => $gid,
44 # OR group => $group,
45 });
46 my $eid = $e->{'id'};
47
48 my $e = $k->find_entry({id => $eid});
49 # OR
50 my $e = $k->find_entry({title => 'Something'});
51
52 $k->lock;
53 print $e->{'password'}; # eq undef
54 print $k->locked_entry_password($e); # eq 'somepass'
55
56 $k->unlock;
57 print $e->{'password'}; # eq 'somepass'
58
59
60 # save out a version 1 database
61 $k->save_db("/some/file/location.kdb", $master_pass);
62
63 # save out a version 2 database
64 $k->save_db("/some/file/location.kdbx", $master_pass);
65
66 # save out a version 1 database using a password and key file
67 $k->save_db("/some/file/location.kdb", [$master_pass, $key_filename]);
68
69
70 # read database from a file
71 $k->parse_db($pass_db_string, $pass);
72
73 # generate a keepass version 1 database string
74 my $pass_db_string = $k->gen_db($pass);
75
76 # generate a keepass version 2 database string
77 my $pass_db_string = $k->gen_db($pass);
78
79 DESCRIPTION
80 File::KeePass gives access to KeePass version 1 (kdb) and version 2
81 (kdbx) databases.
82
83 The version 1 and version 2 databases are very different in
84 construction, but the majority of information overlaps and many
85 algorithms are similar. File::KeePass attempts to iron out as many of
86 the differences.
87
88 File::KeePass gives nearly raw data access. There are a few utility
89 methods for manipulating groups and entries. More advanced manipulation
90 can easily be layered on top by other modules.
91
92 File::KeePass is only used for reading and writing databases and for
93 keeping passwords scrambled while in memory. Programs dealing with UI or
94 using of auto-type features are the domain of other modules on CPAN.
95 File::KeePass::Agent is one example.
96
97 METHODS
98 new Takes a hashref or hash of arguments. Returns a new File::KeePass
99 object. Any named arguments are added to self.
100
101 load_db
102 Takes a kdb filename, a master password, and an optional argument
103 hashref. Returns the File::KeePass object on success (can be called
104 as a class method). Errors die. The resulting database can be
105 accessed via various methods including $k->groups.
106
107 my $k = File::KeePass->new;
108 $k->load_db($file, $pwd);
109
110 my $k = File::KeePass->load_db($file, $pwd);
111
112 my $k = File::KeePass->load_db($file, $pwd, {auto_lock => 0});
113
114 The contents are read from file and passed to parse_db.
115
116 The password passed to load_db may be a composite key in any of the
117 following forms:
118
119 "password" # password only
120 ["password"] # same
121 ["password", "keyfilename"] # password and key file
122 [undef, "keyfilename"] # key file only
123 ["password", \"keycontent"] # password and reference to key file content
124 [undef, \"keycontent"] # reference to key file content only
125
126 The key file is optional. It may be passed as a filename, or as a
127 scalar reference to the contents of the key file. If a filename is
128 passed it will be read in. The key file can contain any of the
129 following three types:
130
131 length 32 # treated as raw key
132 length 64 # must be 64 hexidecimal characters
133 any-other-length # a SHA256 sum will be taken of the data
134
135 save_db
136 Takes a kdb filename and a master password. Stores out the current
137 groups in the object. Writes attempt to write first to
138 $file.new.$epoch and are then renamed into the correct location.
139
140 You will need to unlock the db via $k->unlock before calling this
141 method if the database is currently locked.
142
143 The same master password types passed to load_db can be used here.
144
145 parse_db
146 Takes a string or a reference to a string containting an encrypted
147 kdb database, a master password, and an optional argument hashref.
148 Returns the File::KeePass object on success (can be called as a
149 class method). Errors die. The resulting database can be accessed
150 via various methods including $k->groups.
151
152 my $k = File::KeePass->new;
153 $k->parse_db($loaded_kdb, $pwd);
154
155 my $k = File::KeePass->parse_db($kdb_buffer, $pwd);
156
157 my $k = File::KeePass->parse_db($kdb_buffer, $pwd, {auto_lock => 0});
158
159 The same master password types passed to load_db can be used here.
160
161 parse_header
162 Used by parse_db. Reads just the header information. Can be used as
163 a basic KeePass file check. The returned hash will contain version
164 => 1 or version => 2 depending upon which type of header is found.
165 Can be called as a class method.
166
167 my $head = File::KeePass->parse_header($kdb_buffer); # errors die
168 printf "This is a version %d database\n", $head->{'version'};
169
170 gen_db
171 Takes a master password. Optionally takes a "groups" arrayref and a
172 "headers" hashref. If groups are not passed, it defaults to using
173 the currently loaded groups. If headers are not passed, a fresh set
174 of headers are generated based on the groups and the master
175 password. The headers can be passed in to test round trip
176 portability.
177
178 You will need to unlock the db via $k->unlock before calling this
179 method if the database is currently locked.
180
181 The same master password types passed to load_db can be used here.
182
183 header
184 Returns a hashref representing the combined current header and meta
185 information for the currently loaded database.
186
187 The following fields are present in both version 1 and version 2
188 style databases (from the header):
189
190 enc_iv => "123456789123456", # rand
191 enc_type => "rijndael",
192 header_size => 222,
193 seed_key => "1234567890123456", # rand (32 bytes on v2)
194 seed_rand => "12345678901234567890123456789012", # rand
195 rounds => 6000,
196 sig1 => "2594363651",
197 sig2 => "3041655655", # indicates db version
198 ver => 196608,
199 version => 1, # or 2
200
201 The following keys will be present after the reading of a version 2
202 database (from the header):
203
204 cipher => "aes",
205 compression => 1,
206 protected_stream => "salsa20",
207 protected_stream_key => "12345678901234567890123456789012", # rand
208 start_bytes => "12345678901234567890123456789012", # rand
209
210 Additionally, items parsed from the Meta section of a version 2
211 database will be added. The following are the available fields.
212
213 color => "#4FFF00",
214 custom_data => {key1 => "val1"},
215 database_description => "database desc",
216 database_description_changed => "2012-08-17 00:30:56",
217 database_name => "database name",
218 database_name_changed => "2012-08-17 00:30:56",
219 default_user_name => "",
220 default_user_name_changed => "2012-08-17 00:30:34",
221 entry_templates_group => "VL5nOpzlFUevGhqL71/OTA==",
222 entry_templates_group_changed => "2012-08-21 14:05:32",
223 generator => "KeePass",
224 history_max_items => 10,
225 history_max_size => 6291456, # bytes
226 last_selected_group => "SUgL30QQqUK3tOWuNKUYJA==",
227 last_top_visible_group => "dC1sQ1NO80W7klmRhfEUVw==",
228 maintenance_history_days => 365,
229 master_key_change_force => -1,
230 master_key_change_rec => -1,
231 master_key_changed => "2012-08-17 00:30:34",
232 protect_notes => 0,
233 protect_password => 1,
234 protect_title => 0,
235 protect_url => 0,
236 protect_username => 0
237 recycle_bin_changed => "2012-08-17 00:30:34",
238 recycle_bin_enabled => 1,
239 recycle_bin_uuid => "SUgL30QQqUK3tOWuNKUYJA=="
240
241 When writing a database via either save_db or gen_db, these fields
242 can be set and passed along. Optionally, it is possible to pass
243 along a key called reuse_header to let calls to save_db and gen_db
244 automatically use the contents of the previous header.
245
246 clear
247 Clears any currently loaded database.
248
249 auto_lock
250 Default true. If true, passwords are automatically hidden when a
251 database loaded via parse_db or load_db.
252
253 $k->auto_lock(0); # turn off auto locking
254
255 is_locked
256 Returns true if the current database is locked.
257
258 lock
259 Locks the database. This moves all passwords into a protected, in
260 memory, encrypted storage location. Returns 1 on success. Returns 2
261 if the db is already locked. If a database is loaded via parse_db or
262 load_db and auto_lock is true, the newly loaded database will start
263 out locked.
264
265 unlock
266 Unlocks a previously locked database. You will need to unlock a
267 database before calling save_db or gen_db.
268
269 GROUP/ENTRY METHODS
270 dump_groups
271 Returns a simplified string representation of the currently loaded
272 database.
273
274 print $k->dump_groups;
275
276 You can optionally pass a match argument hashref. Only entries
277 matching the criteria will be returned.
278
279 groups
280 Returns an arrayref of groups from the currently loaded database.
281 Groups returned will be hierarchal. Note, groups simply returns a
282 reference to all of the data. It makes no attempts at cleaning up
283 the data (find_groups will make sure the data is groomed).
284
285 my $g = $k->groups;
286
287 Groups will look similar to the following:
288
289 $g = [{
290 expanded => 0,
291 icon => 0,
292 id => 234234234, # under v1 this is a 32 bit int, under v2 it is a 16 char id
293 title => 'Foo',
294 level => 0,
295 entries => [{
296 accessed => "2010-06-24 15:09:19",
297 comment => "",
298 created => "2010-06-24 15:09:19",
299 expires => "2999-12-31 23:23:59",
300 icon => 0,
301 modified => "2010-06-24 15:09:19",
302 title => "Something",
303 password => 'somepass', # will be hidden if the database is locked
304 url => "",
305 username => "someuser",
306 id => "0a55ac30af68149f", # v1 is any hex char, v2 is any 16 char
307 }],
308 groups => [{
309 expanded => 0,
310 icon => 0,
311 id => 994414667,
312 level => 1,
313 title => "Bar"
314 }],
315 }];
316
317 add_group
318 Adds a new group to the database. Returns a reference to the new
319 group. If a database isn't loaded, it begins a new one. Takes a
320 hashref of arguments for the new entry including title, icon,
321 expanded. A new random group id will be generated. An optional group
322 argument can be passed. If a group is passed the new group will be
323 added under that parent group.
324
325 my $group = $k->add_group({title => 'Foo'});
326 my $gid = $group->{'id'};
327
328 my $group2 = $k->add_group({title => 'Bar', group => $gid});
329
330 The group argument's value may also be a reference to a group - such
331 as that returned by find_group.
332
333 finder_tests {
334 Used by find_groups and find_entries. Takes a hashref of arguments
335 and returns a list of test code refs.
336
337 {title => 'Foo'} # will check if title equals Foo
338 {'title !' => 'Foo'} # will check if title does not equal Foo
339 {'title =~' => qr{^Foo$}} # will check if title does matches the regex
340 {'title !~' => qr{^Foo$}} # will check if title does not match the regex
341
342 find_groups
343 Takes a hashref of search criteria and returns all matching groups.
344 Can be passed id, title, icon, and level. Search arguments will be
345 parsed by finder_tests.
346
347 my @groups = $k->find_groups({title => 'Foo'});
348
349 my @all_groups_flattened = $k->find_groups({});
350
351 The find_groups method also checks to make sure group ids are unique
352 and that all needed values are defined.
353
354 find_group
355 Calls find_groups and returns the first group found. Dies if
356 multiple results are found. In scalar context it returns only the
357 group. In list context it returns the group, and its the arrayref in
358 which it is stored (either the root level group or a sub groups
359 group item).
360
361 delete_group
362 Passes arguments to find_group to find the group to delete. Then
363 deletes the group. Returns the group that was just deleted.
364
365 add_entry
366 Adds a new entry to the database. Returns a reference to the new
367 entry. An optional group argument can be passed. If a group is not
368 passed, the entry will be added to the first group in the database.
369 A new entry id will be created if one is not passed or if it
370 conflicts with an existing group.
371
372 The following fields can be passed to both v1 and v2 databases.
373
374 accessed => "2010-06-24 15:09:19", # last accessed date
375 auto_type => [{keys => "{USERNAME}{TAB}{PASSWORD}{ENTER}", window => "Foo*"}],
376 binary => {foo => 'content'}; # hashref of filename/content pairs
377 comment => "", # a comment for the system - auto-type info is normally here
378 created => "2010-06-24 15:09:19", # entry creation date
379 expires => "2999-12-31 23:23:59", # date entry expires
380 icon => 0, # icon number for use with agents
381 modified => "2010-06-24 15:09:19", # last modified
382 title => "Something",
383 password => 'somepass', # will be hidden if the database is locked
384 url => "http://",
385 username => "someuser",
386 id => "0a55ac30af68149f", # auto generated if needed, v1 is any hex char, v2 is any 16 char
387 group => $gid, # which group to add the entry to
388
389 For compatibility with earlier versions of File::KeePass, it is
390 possible to pass in a binary and binary_name when creating an entry.
391 They will be automatically converted to the hashref of
392 filename/content pairs
393
394 binary_name => "foo", # description of the stored binary - typically a filename
395 binary => "content", # raw data to be stored in the system - typically a file
396
397 # results in
398 binary => {"foo" => "content"}
399
400 Typically, version 1 databases store their Auto-Type information
401 inside of the comment. They are also limited to having only one key
402 sequence per entry. File::KeePass 2+ will automatically parse
403 Auto-Type values passed in the entry comment and store them out as
404 the auto_type arrayref. This arrayref is serialized back into the
405 comment section when saving as a version 1 database. Version 2
406 databases have a separate storage mechanism for Auto-Type.
407
408 If you passed in:
409 comment => "
410 Auto-Type: {USERNAME}{TAB}{PASSWORD}{ENTER}
411 Auto-Type-Window: Foo*
412 Auto-Type-Window: Bar*
413 ",
414
415 Will result in:
416 auto_type => [{
417 keys => "{USERNAME}{TAB}{PASSWORD}{ENTER}",
418 window => "Foo*"
419 }, {
420 keys => "{USERNAME}{TAB}{PASSWORD}{ENTER}",
421 window => "Bar*"
422 }],
423
424 The group argument value may be either an existing group id, or a
425 reference to a group - such as that returned by find_group.
426
427 When using a version 2 database, the following additional fields are
428 also available:
429
430 expires_enabled => 0,
431 location_changed => "2012-08-05 12:12:12",
432 usage_count => 0,
433 tags => {},
434 background_color => '#ff0000',
435 foreground_color => '#ffffff',
436 custom_icon_uuid => '234242342aa',
437 history => [], # arrayref of previous entry changes
438 override_url => $node->{'OverrideURL'},
439 auto_type_enabled => 1,
440 auto_type_munge => 0, # whether or not to attempt two channel auto typing
441 protected => {password => 1}, # indicating which strings were/should be salsa20 protected
442 strings => {'other key' => 'other value'},
443
444 find_entries
445 Takes a hashref of search criteria and returns all matching groups.
446 Can be passed an entry id, title, username, comment, url, active,
447 group_id, group_title, or any other entry property. Search arguments
448 will be parsed by finder_tests.
449
450 my @entries = $k->find_entries({title => 'Something'});
451
452 my @all_entries_flattened = $k->find_entries({});
453
454 find_entry
455 Calls find_entries and returns the first entry found. Dies if
456 multiple results are found. In scalar context it returns only the
457 entry. In list context it returns the entry, and its group.
458
459 delete_entry
460 Passes arguments to find_entry to find the entry to delete. Then
461 deletes the entry. Returns the entry that was just deleted.
462
463 locked_entry_password
464 Allows access to individual passwords for a database that is locked.
465 Dies if the database is not locked.
466
467 UTILITY METHODS
468 The following methods are general purpose methods used during the
469 parsing and generating of kdb databases.
470
471 now Returns the current localtime datetime stamp.
472
473 default_exp
474 Returns the string representing the default expires time of an
475 entry. Will use $self->{'default_exp'} or fails to the string
476 '2999-12-31 23:23:59'.
477
478 decrypt_rijndael_cbc
479 Takes an encrypted string, a key, and an encryption_iv string.
480 Returns a plaintext string.
481
482 encrypt_rijndael_cbc
483 Takes a plaintext string, a key, and an encryption_iv string.
484 Returns an encrypted string.
485
486 decode_base64
487 Loads the MIME::Base64 library and decodes the passed string.
488
489 encode_base64
490 Loads the MIME::Base64 library and encodes the passed string.
491
492 unchunksum
493 Parses and reassembles a buffer, reading in lengths, and checksums
494 of chunks.
495
496 decompress
497 Loads the Compress::Raw::Zlib library and inflates the contents.
498
499 compress
500 Loads the Compress::Raw::Zlib library and deflates the contents.
501
502 parse_xml
503 Loads the XML::Parser library and sets up a basic parser that can
504 call hooks at various events. Without the hooks, it runs similarly
505 to XML::Simple::parse.
506
507 my $data = $self->parse_xml($buffer, {
508 top => 'KeePassFile',
509 force_array => {Group => 1, Entry => 1},
510 start_handlers => {Group => sub { $level++ }},
511 end_handlers => {Group => sub { $level-- }},
512 });
513
514 gen_xml
515 Generates XML from the passed data structure. The output of
516 parse_xml can be passed as is. Additionally hints such as __sort__
517 can be used to order the tags of a node and __attr__ can be used to
518 indicate which items of a node are attributes.
519
520 salsa20
521 Takes a hashref containing a salsa20 key string (length 32 or 16), a
522 salsa20 iv string (length 8), number of salsa20 rounds (8, 12, or 20
523 - default 20), and an optional data string. The key and iv are used
524 to initialize the salsa20 encryption.
525
526 If a data string is passed, the string is salsa20 encrypted and
527 returned.
528
529 If no data string is passed a salsa20 encrypting coderef is
530 returned.
531
532 my $encoded = $self->salsa20({key => $key, iv => $iv, data => $data});
533 my $uncoded = $self->salsa20({key => $key, iv => $iv, data => $encoded});
534 # $data eq $uncoded
535
536 my $encoder = $self->salsa20({key => $key, iv => $Iv}); # no data
537 my $encoded = $encoder->($data);
538 my $part2 = $encoder->($more_data); # continues from previous state
539
540 salsa20_stream
541 Takes a hashref that will be passed to salsa20. Uses the resulting
542 encoder to generate a more continuous encoded stream. The salsa20
543 method encodes in chunks of 64 bytes. If a string is not a multiple
544 of 64, then some of the xor bytes are unused. The salsa20_stream
545 method maintains a buffer of xor bytes to ensure that none are
546 wasted.
547
548 my $encoder = $self->salsa20_stream({key => $key, iv => $Iv}); # no data
549 my $encoded = $encoder->("1234"); # calls salsa20->()
550 my $part2 = $encoder->("1234"); # uses the same pad until 64 bytes are used
551
552 OTHER METHODS
553 _parse_v1_header
554 _parse_v1_body
555 _parse_v1_groups
556 _parse_v1_entries
557 _parse_v1_date
558 Utilities used for parsing version 1 type databases.
559
560 _parse_v2_header
561 _parse_v2_body
562 _parse_v2_date
563 Utilities used for parsing version 2 type databases.
564
565 _gen_v1_db
566 _gen_v1_header
567 _gen_v1_date
568 Utilities used to generate version 1 type databases.
569
570 _gen_v2_db
571 _gen_v2_header
572 _gen_v2_date
573 Utilities used to generate version 2 type databases.
574
575 _master_key
576 Takes the password and parsed headers. Returns the master key based
577 on database type.
578
579 ONE LINERS
580 (Long one liners)
581
582 Here is a version 1 to version 2, or version 2 to version 1 converter.
583 Simply change the extension of the two files. Someday we will include a
584 kdb2kdbx utility to do this for you.
585
586 perl -MFile::KeePass -e 'use IO::Prompt; $p="".prompt("Pass:",-e=>"*",-tty); File::KeePass->load_db(+shift,$p,{auto_lock=>0})->save_db(+shift,$p)' ~/test.kdb ~/test.kdbx
587
588 # OR using graphical prompt
589 perl -MFile::KeePass -e 'chop($p=`zenity --password`); File::KeePass->load_db(+shift,$p,{auto_lock=>0})->save_db(+shift,$p)' ~/test.kdbx ~/test.kdb
590
591 # OR using pure perl (but echoes password)
592 perl -MFile::KeePass -e 'print "Pass:"; chop($p=<STDIN>); File::KeePass->load_db(+shift,$p,{auto_lock=>0})->save_db(+shift,$p)' ~/test.kdbx ~/test.kdb
593
594 Dumping the XML from a version 2 database.
595
596 perl -MFile::KeePass -e 'chop($p=`zenity --password`); print File::KeePass->load_db(+shift,$p,{keep_xml=>1})->{xml_in},"\n"' ~/test.kdbx
597
598 Outlining group information.
599
600 perl -MFile::KeePass -e 'chop($p=`zenity --password`); print File::KeePass->load_db(+shift,$p)->dump_groups' ~/test.kdbx
601
602 Dumping header information
603
604 perl -MFile::KeePass -MData::Dumper -e 'chop($p=`zenity --password`); print Dumper +File::KeePass->load_db(+shift,$p)->header' ~/test.kdbx
605
606 BUGS
607 Only Rijndael is supported when using v1 databases.
608
609 This module makes no attempt to act as a password agent. That is the job
610 of File::KeePass::Agent. This isn't really a bug but some people will
611 think it is.
612
613 Groups and entries don't have true objects associated with them. At the
614 moment this is by design. The data is kept as plain boring data.
615
616 SOURCES
617 Knowledge about the algorithms necessary to decode a KeePass DB v1
618 format was gleaned from the source code of keepassx-0.4.3. That source
619 code is published under the GPL2 license. KeePassX 0.4.3 bears the
620 copyright of
621
622 Copyright (C) 2005-2008 Tarek Saidi <[email protected]>
623 Copyright (C) 2007-2009 Felix Geyer <debfx-keepassx {at} fobos.de>
624
625 Knowledge about the algorithms necessary to decode a KeePass DB v2
626 format was gleaned from the source code of keepassx-2.0-alpha1. That
627 source code is published under the GPL2 or GPL3 license. KeePassX
628 2.0-alpha1 bears the copyright of
629
630 Copyright: 2010-2012, Felix Geyer <[email protected]>
631 2011-2012, Florian Geyer <[email protected]>
632
633 The salsa20 algorithm is based on
634 http://cr.yp.to/snuffle/salsa20/regs/salsa20.c which is listed as Public
635 domain (D. J. Bernstein).
636
637 The ordering and layering of encryption/decryption algorithms of
638 File::KeePass are of derivative nature from KeePassX and could not have
639 been created without this insight - though the perl code is from
640 scratch.
641
642 AUTHOR
643 Paul Seamons <[email protected]>
644
645 LICENSE
646 This module may be distributed under the same terms as Perl itself.
647