1File::KeePass(3)      User Contributed Perl Documentation     File::KeePass(3)
2
3
4

NAME

6       File::KeePass - Interface to KeePass V1 and V2 database files
7

SYNOPSIS

9           use File::KeePass;
10           use Data::Dumper qw(Dumper);
11
12           my $k = File::KeePass->new;
13
14           # read a version 1 or version 2 database
15           $k->load_db($file, $master_pass); # errors die
16
17           print Dumper $k->header;
18           print Dumper $k->groups; # passwords are locked
19
20           $k->unlock;
21           print Dumper $k->groups; # passwords are now visible
22
23           $k->clear; # delete current db from memory
24
25
26           my $group = $k->add_group({
27               title => 'Foo',
28           }); # root level group
29           my $gid = $group->{'id'};
30
31           my $group = $k->find_group({id => $gid});
32           # OR
33           my $group = $k->find_group({title => 'Foo'});
34
35
36           my $group2 = $k->add_group({
37               title => 'Bar',
38               group => $gid,
39               # OR group => $group,
40           }); # nested group
41
42
43           my $e = $k->add_entry({
44               title    => 'Something',
45               username => 'someuser',
46               password => 'somepass',
47               group    => $gid,
48               # OR group => $group,
49           });
50           my $eid = $e->{'id'};
51
52           my $e = $k->find_entry({id => $eid});
53           # OR
54           my $e = $k->find_entry({title => 'Something'});
55
56           $k->lock;
57           print $e->{'password'}; # eq undef
58           print $k->locked_entry_password($e); # eq 'somepass'
59
60           $k->unlock;
61           print $e->{'password'}; # eq 'somepass'
62
63
64           # save out a version 1 database
65           $k->save_db("/some/file/location.kdb", $master_pass);
66
67           # save out a version 2 database
68           $k->save_db("/some/file/location.kdbx", $master_pass);
69
70           # save out a version 1 database using a password and key file
71           $k->save_db("/some/file/location.kdb", [$master_pass, $key_filename]);
72
73
74           # read database from a file
75           $k->parse_db($pass_db_string, $pass);
76
77           # generate a keepass version 1 database string
78           my $pass_db_string = $k->gen_db($pass);
79
80           # generate a keepass version 2 database string
81           my $pass_db_string = $k->gen_db($pass);
82

DESCRIPTION

84       File::KeePass gives access to KeePass version 1 (kdb) and version 2
85       (kdbx) databases.
86
87       The version 1 and version 2 databases are very different in
88       construction, but the majority of information overlaps and many
89       algorithms are similar.  File::KeePass attempts to iron out as many of
90       the differences.
91
92       File::KeePass gives nearly raw data access.  There are a few utility
93       methods for manipulating groups and entries.  More advanced
94       manipulation can easily be layered on top by other modules.
95
96       File::KeePass is only used for reading and writing databases and for
97       keeping passwords scrambled while in memory.  Programs dealing with UI
98       or using of auto-type features are the domain of other modules on CPAN.
99       File::KeePass::Agent is one example.
100

METHODS

102       new Takes a hashref or hash of arguments.  Returns a new File::KeePass
103           object.  Any named arguments are added to self.
104
105       load_db
106           Takes a kdb filename, a master password, and an optional argument
107           hashref.  Returns the File::KeePass object on success (can be
108           called as a class method).  Errors die.  The resulting database can
109           be accessed via various methods including $k->groups.
110
111               my $k = File::KeePass->new;
112               $k->load_db($file, $pwd);
113
114               my $k = File::KeePass->load_db($file, $pwd);
115
116               my $k = File::KeePass->load_db($file, $pwd, {auto_lock => 0});
117
118           The contents are read from file and passed to parse_db.
119
120           The password passed to load_db may be a composite key in any of the
121           following forms:
122
123               "password"                   # password only
124               ["password"]                 # same
125               ["password", "keyfilename"]  # password and key file
126               [undef, "keyfilename"]       # key file only
127               ["password", \"keycontent"]  # password and reference to key file content
128               [undef, \"keycontent"]       # reference to key file content only
129
130           The key file is optional.  It may be passed as a filename, or as a
131           scalar reference to the contents of the key file.  If a filename is
132           passed it will be read in.  The key file can contain any of the
133           following three types:
134
135               length 32         # treated as raw key
136               length 64         # must be 64 hexidecimal characters
137               any-other-length  # a SHA256 sum will be taken of the data
138
139       save_db
140           Takes a kdb filename and a master password.  Stores out the current
141           groups in the object.  Writes attempt to write first to
142           $file.new.$epoch and are then renamed into the correct location.
143
144           You will need to unlock the db via $k->unlock before calling this
145           method if the database is currently locked.
146
147           The same master password types passed to load_db can be used here.
148
149       parse_db
150           Takes a string or a reference to a string containting an encrypted
151           kdb database, a master password, and an optional argument hashref.
152           Returns the File::KeePass object on success (can be called as a
153           class method).  Errors die.  The resulting database can be accessed
154           via various methods including $k->groups.
155
156               my $k = File::KeePass->new;
157               $k->parse_db($loaded_kdb, $pwd);
158
159               my $k = File::KeePass->parse_db($kdb_buffer, $pwd);
160
161               my $k = File::KeePass->parse_db($kdb_buffer, $pwd, {auto_lock => 0});
162
163           The same master password types passed to load_db can be used here.
164
165       parse_header
166           Used by parse_db.  Reads just the header information.  Can be used
167           as a basic KeePass file check.  The returned hash will contain
168           version => 1 or version => 2 depending upon which type of header is
169           found.  Can be called as a class method.
170
171               my $head = File::KeePass->parse_header($kdb_buffer); # errors die
172               printf "This is a version %d database\n", $head->{'version'};
173
174       gen_db
175           Takes a master password.  Optionally takes a "groups" arrayref and
176           a "headers" hashref.  If groups are not passed, it defaults to
177           using the currently loaded groups.  If headers are not passed, a
178           fresh set of headers are generated based on the groups and the
179           master password.  The headers can be passed in to test round trip
180           portability.
181
182           You will need to unlock the db via $k->unlock before calling this
183           method if the database is currently locked.
184
185           The same master password types passed to load_db can be used here.
186
187       header
188           Returns a hashref representing the combined current header and meta
189           information for the currently loaded database.
190
191           The following fields are present in both version 1 and version 2
192           style databases (from the header):
193
194               enc_iv               => "123456789123456", # rand
195               enc_type             => "rijndael",
196               header_size          => 222,
197               seed_key             => "1234567890123456", # rand (32 bytes on v2)
198               seed_rand            => "12345678901234567890123456789012", # rand
199               rounds               => 6000,
200               sig1                 => "2594363651",
201               sig2                 => "3041655655", # indicates db version
202               ver                  => 196608,
203               version              => 1, # or 2
204
205           The following keys will be present after the reading of a version 2
206           database (from the header):
207
208               cipher               => "aes",
209               compression          => 1,
210               protected_stream     => "salsa20",
211               protected_stream_key => "12345678901234567890123456789012", # rand
212               start_bytes          => "12345678901234567890123456789012", # rand
213
214           Additionally, items parsed from the Meta section of a version 2
215           database will be added.  The following are the available fields.
216
217               color                         => "#4FFF00",
218               custom_data                   => {key1 => "val1"},
219               database_description          => "database desc",
220               database_description_changed  => "2012-08-17 00:30:56",
221               database_name                 => "database name",
222               database_name_changed         => "2012-08-17 00:30:56",
223               default_user_name             => "",
224               default_user_name_changed     => "2012-08-17 00:30:34",
225               entry_templates_group         => "VL5nOpzlFUevGhqL71/OTA==",
226               entry_templates_group_changed => "2012-08-21 14:05:32",
227               generator                     => "KeePass",
228               history_max_items             => 10,
229               history_max_size              => 6291456, # bytes
230               last_selected_group           => "SUgL30QQqUK3tOWuNKUYJA==",
231               last_top_visible_group        => "dC1sQ1NO80W7klmRhfEUVw==",
232               maintenance_history_days      => 365,
233               master_key_change_force       => -1,
234               master_key_change_rec         => -1,
235               master_key_changed            => "2012-08-17 00:30:34",
236               protect_notes                 => 0,
237               protect_password              => 1,
238               protect_title                 => 0,
239               protect_url                   => 0,
240               protect_username              => 0
241               recycle_bin_changed           => "2012-08-17 00:30:34",
242               recycle_bin_enabled           => 1,
243               recycle_bin_uuid              => "SUgL30QQqUK3tOWuNKUYJA=="
244
245           When writing a database via either save_db or gen_db, these fields
246           can be set and passed along.  Optionally, it is possible to pass
247           along a key called reuse_header to let calls to save_db and gen_db
248           automatically use the contents of the previous header.
249
250       clear
251           Clears any currently loaded database.
252
253       auto_lock
254           Default true.  If true, passwords are automatically hidden when a
255           database loaded via parse_db or load_db.
256
257               $k->auto_lock(0); # turn off auto locking
258
259       is_locked
260           Returns true if the current database is locked.
261
262       lock
263           Locks the database.  This moves all passwords into a protected, in
264           memory, encrypted storage location.  Returns 1 on success.  Returns
265           2 if the db is already locked.  If a database is loaded via
266           parse_db or load_db and auto_lock is true, the newly loaded
267           database will start out locked.
268
269       unlock
270           Unlocks a previously locked database.  You will need to unlock a
271           database before calling save_db or gen_db.
272

GROUP/ENTRY METHODS

274       dump_groups
275           Returns a simplified string representation of the currently loaded
276           database.
277
278               print $k->dump_groups;
279
280           You can optionally pass a match argument hashref.  Only entries
281           matching the criteria will be returned.
282
283       groups
284           Returns an arrayref of groups from the currently loaded database.
285           Groups returned will be hierarchal.  Note, groups simply returns a
286           reference to all of the data.  It makes no attempts at cleaning up
287           the data (find_groups will make sure the data is groomed).
288
289               my $g = $k->groups;
290
291           Groups will look similar to the following:
292
293               $g = [{
294                    expanded => 0,
295                    icon     => 0,
296                    id       => 234234234, # under v1 this is a 32 bit int, under v2 it is a 16 char id
297                    title    => 'Foo',
298                    level    => 0,
299                    entries => [{
300                        accessed => "2010-06-24 15:09:19",
301                        comment  => "",
302                        created  => "2010-06-24 15:09:19",
303                        expires  => "2999-12-31 23:23:59",
304                        icon     => 0,
305                        modified => "2010-06-24 15:09:19",
306                        title    => "Something",
307                        password => 'somepass', # will be hidden if the database is locked
308                        url      => "",
309                        username => "someuser",
310                        id       => "0a55ac30af68149f", # v1 is any hex char, v2 is any 16 char
311                    }],
312                    groups => [{
313                        expanded => 0,
314                        icon     => 0,
315                        id       => 994414667,
316                        level    => 1,
317                        title    => "Bar"
318                    }],
319                }];
320
321       add_group
322           Adds a new group to the database.  Returns a reference to the new
323           group.  If a database isn't loaded, it begins a new one.  Takes a
324           hashref of arguments for the new entry including title, icon,
325           expanded.  A new random group id will be generated.  An optional
326           group argument can be passed.  If a group is passed the new group
327           will be added under that parent group.
328
329               my $group = $k->add_group({title => 'Foo'});
330               my $gid = $group->{'id'};
331
332               my $group2 = $k->add_group({title => 'Bar', group => $gid});
333
334           The group argument's value may also be a reference to a group -
335           such as that returned by find_group.
336
337       finder_tests {
338           Used by find_groups and find_entries.  Takes a hashref of arguments
339           and returns a list of test code refs.
340
341               {title => 'Foo'} # will check if title equals Foo
342               {'title !' => 'Foo'} # will check if title does not equal Foo
343               {'title =~' => qr{^Foo$}} # will check if title does matches the regex
344               {'title !~' => qr{^Foo$}} # will check if title does not match the regex
345
346       find_groups
347           Takes a hashref of search criteria and returns all matching groups.
348           Can be passed id, title, icon, and level.  Search arguments will be
349           parsed by finder_tests.
350
351               my @groups = $k->find_groups({title => 'Foo'});
352
353               my @all_groups_flattened = $k->find_groups({});
354
355           The find_groups method also checks to make sure group ids are
356           unique and that all needed values are defined.
357
358       find_group
359           Calls find_groups and returns the first group found.  Dies if
360           multiple results are found.  In scalar context it returns only the
361           group.  In list context it returns the group, and its the arrayref
362           in which it is stored (either the root level group or a sub groups
363           group item).
364
365       delete_group
366           Passes arguments to find_group to find the group to delete.  Then
367           deletes the group.  Returns the group that was just deleted.
368
369       add_entry
370           Adds a new entry to the database.  Returns a reference to the new
371           entry.  An optional group argument can be passed.  If a group is
372           not passed, the entry will be added to the first group in the
373           database.  A new entry id will be created if one is not passed or
374           if it conflicts with an existing group.
375
376           The following fields can be passed to both v1 and v2 databases.
377
378               accessed => "2010-06-24 15:09:19", # last accessed date
379               auto_type => [{keys => "{USERNAME}{TAB}{PASSWORD}{ENTER}", window => "Foo*"}],
380               binary   => {foo => 'content'}; # hashref of filename/content pairs
381               comment  => "", # a comment for the system - auto-type info is normally here
382               created  => "2010-06-24 15:09:19", # entry creation date
383               expires  => "2999-12-31 23:23:59", # date entry expires
384               icon     => 0, # icon number for use with agents
385               modified => "2010-06-24 15:09:19", # last modified
386               title    => "Something",
387               password => 'somepass', # will be hidden if the database is locked
388               url      => "http://",
389               username => "someuser",
390               id       => "0a55ac30af68149f", # auto generated if needed, v1 is any hex char, v2 is any 16 char
391               group    => $gid, # which group to add the entry to
392
393           For compatibility with earlier versions of File::KeePass, it is
394           possible to pass in a binary and binary_name when creating an
395           entry.  They will be automatically converted to the hashref of
396           filename/content pairs
397
398               binary_name => "foo", # description of the stored binary - typically a filename
399               binary   => "content", # raw data to be stored in the system - typically a file
400
401               # results in
402               binary => {"foo" => "content"}
403
404           Typically, version 1 databases store their Auto-Type information
405           inside of the comment.  They are also limited to having only one
406           key sequence per entry.  File::KeePass 2+ will automatically parse
407           Auto-Type values passed in the entry comment and store them out as
408           the auto_type arrayref.  This arrayref is serialized back into the
409           comment section when saving as a version 1 database.  Version 2
410           databases have a separate storage mechanism for Auto-Type.
411
412               If you passed in:
413               comment => "
414                  Auto-Type: {USERNAME}{TAB}{PASSWORD}{ENTER}
415                  Auto-Type-Window: Foo*
416                  Auto-Type-Window: Bar*
417               ",
418
419               Will result in:
420               auto_type => [{
421                   keys => "{USERNAME}{TAB}{PASSWORD}{ENTER}",
422                   window => "Foo*"
423                }, {
424                   keys => "{USERNAME}{TAB}{PASSWORD}{ENTER}",
425                   window => "Bar*"
426                }],
427
428           The group argument value may be either an existing group id, or a
429           reference to a group - such as that returned by find_group.
430
431           When using a version 2 database, the following additional fields
432           are also available:
433
434               expires_enabled   => 0,
435               location_changed  => "2012-08-05 12:12:12",
436               usage_count       => 0,
437               tags              => {},
438               background_color  => '#ff0000',
439               foreground_color  => '#ffffff',
440               custom_icon_uuid  => '234242342aa',
441               history           => [], # arrayref of previous entry changes
442               override_url      => $node->{'OverrideURL'},
443               auto_type_enabled => 1,
444               auto_type_munge   => 0, # whether or not to attempt two channel auto typing
445               protected         => {password => 1}, # indicating which strings were/should be salsa20 protected
446               strings           => {'other key' => 'other value'},
447
448       find_entries
449           Takes a hashref of search criteria and returns all matching groups.
450           Can be passed an entry id, title, username, comment, url, active,
451           group_id, group_title, or any other entry property.  Search
452           arguments will be parsed by finder_tests.
453
454               my @entries = $k->find_entries({title => 'Something'});
455
456               my @all_entries_flattened = $k->find_entries({});
457
458       find_entry
459           Calls find_entries and returns the first entry found.  Dies if
460           multiple results are found.  In scalar context it returns only the
461           entry.  In list context it returns the entry, and its group.
462
463       delete_entry
464           Passes arguments to find_entry to find the entry to delete.  Then
465           deletes the entry.  Returns the entry that was just deleted.
466
467       locked_entry_password
468           Allows access to individual passwords for a database that is
469           locked.  Dies if the database is not locked.
470

UTILITY METHODS

472       The following methods are general purpose methods used during the
473       parsing and generating of kdb databases.
474
475       now Returns the current localtime datetime stamp.
476
477       default_exp
478           Returns the string representing the default expires time of an
479           entry.  Will use $self->{'default_exp'} or fails to the string
480           '2999-12-31 23:23:59'.
481
482       decrypt_rijndael_cbc
483           Takes an encrypted string, a key, and an encryption_iv string.
484           Returns a plaintext string.
485
486       encrypt_rijndael_cbc
487           Takes a plaintext string, a key, and an encryption_iv string.
488           Returns an encrypted string.
489
490       decode_base64
491           Loads the MIME::Base64 library and decodes the passed string.
492
493       encode_base64
494           Loads the MIME::Base64 library and encodes the passed string.
495
496       unchunksum
497           Parses and reassembles a buffer, reading in lengths, and checksums
498           of chunks.
499
500       decompress
501           Loads the Compress::Raw::Zlib library and inflates the contents.
502
503       compress
504           Loads the Compress::Raw::Zlib library and deflates the contents.
505
506       parse_xml
507           Loads the XML::Parser library and sets up a basic parser that can
508           call hooks at various events.  Without the hooks, it runs similarly
509           to XML::Simple::parse.
510
511               my $data = $self->parse_xml($buffer, {
512                   top            => 'KeePassFile',
513                   force_array    => {Group => 1, Entry => 1},
514                   start_handlers => {Group => sub { $level++ }},
515                   end_handlers   => {Group => sub { $level-- }},
516               });
517
518       gen_xml
519           Generates XML from the passed data structure.  The output of
520           parse_xml can be passed as is.  Additionally hints such as __sort__
521           can be used to order the tags of a node and __attr__ can be used to
522           indicate which items of a node are attributes.
523
524       salsa20
525           Takes a hashref containing a salsa20 key string (length 32 or 16),
526           a salsa20 iv string (length 8), number of salsa20 rounds (8, 12, or
527           20 - default 20), and an optional data string.  The key and iv are
528           used to initialize the salsa20 encryption.
529
530           If a data string is passed, the string is salsa20 encrypted and
531           returned.
532
533           If no data string is passed a salsa20 encrypting coderef is
534           returned.
535
536               my $encoded = $self->salsa20({key => $key, iv => $iv, data => $data});
537               my $uncoded = $self->salsa20({key => $key, iv => $iv, data => $encoded});
538               # $data eq $uncoded
539
540               my $encoder = $self->salsa20({key => $key, iv => $Iv}); # no data
541               my $encoded = $encoder->($data);
542               my $part2   = $encoder->($more_data); # continues from previous state
543
544       salsa20_stream
545           Takes a hashref that will be passed to salsa20.  Uses the resulting
546           encoder to generate a more continuous encoded stream.  The salsa20
547           method encodes in chunks of 64 bytes.  If a string is not a
548           multiple of 64, then some of the xor bytes are unused.  The
549           salsa20_stream method maintains a buffer of xor bytes to ensure
550           that none are wasted.
551
552               my $encoder = $self->salsa20_stream({key => $key, iv => $Iv}); # no data
553               my $encoded = $encoder->("1234");   # calls salsa20->()
554               my $part2   = $encoder->("1234");   # uses the same pad until 64 bytes are used
555

OTHER METHODS

557       _parse_v1_header
558       _parse_v1_body
559       _parse_v1_groups
560       _parse_v1_entries
561       _parse_v1_date
562           Utilities used for parsing version 1 type databases.
563
564       _parse_v2_header
565       _parse_v2_body
566       _parse_v2_date
567           Utilities used for parsing version 2 type databases.
568
569       _gen_v1_db
570       _gen_v1_header
571       _gen_v1_date
572           Utilities used to generate version 1 type databases.
573
574       _gen_v2_db
575       _gen_v2_header
576       _gen_v2_date
577           Utilities used to generate version 2 type databases.
578
579       _master_key
580           Takes the password and parsed headers.  Returns the master key
581           based on database type.
582

ONE LINERS

584       (Long one liners)
585
586       Here is a version 1 to version 2, or version 2 to version 1 converter.
587       Simply change the extension of the two files.  Someday we will include
588       a kdb2kdbx utility to do this for you.
589
590           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
591
592           # OR using graphical prompt
593           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
594
595           # OR using pure perl (but echoes password)
596           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
597
598       Dumping the XML from a version 2 database.
599
600           perl -MFile::KeePass -e 'chop($p=`zenity --password`); print File::KeePass->load_db(+shift,$p,{keep_xml=>1})->{xml_in},"\n"' ~/test.kdbx
601
602       Outlining group information.
603
604           perl -MFile::KeePass -e 'chop($p=`zenity --password`); print File::KeePass->load_db(+shift,$p)->dump_groups' ~/test.kdbx
605
606       Dumping header information
607
608           perl -MFile::KeePass -MData::Dumper -e 'chop($p=`zenity --password`); print Dumper +File::KeePass->load_db(+shift,$p)->header' ~/test.kdbx
609

BUGS

611       Only Rijndael is supported when using v1 databases.
612
613       This module makes no attempt to act as a password agent.  That is the
614       job of File::KeePass::Agent.  This isn't really a bug but some people
615       will think it is.
616
617       Groups and entries don't have true objects associated with them.  At
618       the moment this is by design.  The data is kept as plain boring data.
619

SOURCES

621       Knowledge about the algorithms necessary to decode a KeePass DB v1
622       format was gleaned from the source code of keepassx-0.4.3.  That source
623       code is published under the GPL2 license.  KeePassX 0.4.3 bears the
624       copyright of
625
626           Copyright (C) 2005-2008 Tarek Saidi <tarek.saidi@arcor.de>
627           Copyright (C) 2007-2009 Felix Geyer <debfx-keepassx {at} fobos.de>
628
629       Knowledge about the algorithms necessary to decode a KeePass DB v2
630       format was gleaned from the source code of keepassx-2.0-alpha1.  That
631       source code is published under the GPL2 or GPL3 license.  KeePassX
632       2.0-alpha1 bears the copyright of
633
634           Copyright: 2010-2012, Felix Geyer <debfx@fobos.de>
635                      2011-2012, Florian Geyer <blueice@fobos.de>
636
637       The salsa20 algorithm is based on
638       http://cr.yp.to/snuffle/salsa20/regs/salsa20.c which is listed as
639       Public domain (D. J. Bernstein).
640
641       The ordering and layering of encryption/decryption algorithms of
642       File::KeePass are of derivative nature from KeePassX and could not have
643       been created without this insight - though the perl code is from
644       scratch.
645

AUTHOR

647       Paul Seamons <paul@seamons.com>
648

LICENSE

650       This module may be distributed under the same terms as Perl itself.
651
652
653
654perl v5.36.0                      2023-01-20                  File::KeePass(3)
Impressum