-
Notifications
You must be signed in to change notification settings - Fork 5
/
kpcli.pl
executable file
·5168 lines (4722 loc) · 178 KB
/
kpcli.pl
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/perl
###########################################################################
#
# kpcli - KeePass Command Line Interface
#
# Author: Lester Hightower <hightowe at cpan dot org>
#
# This program was inspired by "kedpm -c" and resulted despite illness
# (or more likely because of it) over the USA Thanksgiving holiday in
# late November of 2010. As a long-time user of the Ked Password Manager
# I really missed a command line interface after getting an Android cell
# phone and switching to KeePass, so that I could access my password
# database on my phone. This program scratches that itch.
#
###########################################################################
# The required perl modules
use strict; # core
use version; # core
use File::Spec; # core
use FileHandle; # core
use Getopt::Long; # core
use File::Basename; # core
use Digest::file; # core
use Digest::MD5; # core
use Digest::SHA qw(sha256); # core
use Data::Dumper qw(Dumper); # core
use Term::ANSIColor; # core
use Carp qw(longmess); # core
use English qw(-no_match_vars); # core
use Time::HiRes qw(gettimeofday tv_interval); # core
use Time::Local qw(timegm); # core
use Clone qw(clone); # core
use POSIX; # core, required for unsafe signal handling
use Crypt::Rijndael; # non-core, libcrypt-rijndael-perl on Ubuntu
use Sort::Naturally; # non-core, libsort-naturally-perl on Ubuntu
use Term::ReadKey; # non-core, libterm-readkey-perl on Ubuntu
use Term::ShellUI; # non-core, libterm-shellui-perl on Ubuntu
use File::KeePass 0.03; # non-core, libfile-keepass-perl on Ubuntu
# - >=v0.03 needed due critical bug fixes
# A developer convenience to force using a particular Term::ReadLine module
our $FORCED_READLINE = undef; # Auto-select
#our $FORCED_READLINE = 'Term::ReadLine::Gnu';
#our $FORCED_READLINE = 'Term::ReadLine::Perl';
#our $FORCED_READLINE = 'Term::ReadLine::Perl5';
# Pull in optional perl modules with run-time loading
my %OPTIONAL_PM=();
# Data::Password is needed for the pwck command (check password quality).
if (runtime_load_module(\%OPTIONAL_PM,'Data::Password',[qw(IsBadPassword)])) {
no warnings 'once';
$Data::Password::MINLEN = 8;
$Data::Password::MAXLEN = 0;
}
# Capture::Tiny is needed to safely optionally-load Clipboard.
# Clipboard is needed by the clipboard copy commands (xw, xu, xp, and xx).
if (runtime_load_module(\%OPTIONAL_PM,'Capture::Tiny',[qw(capture)])) {
# Clipboard tests its dependencies at import() and writes warnings to STDERR.
# Tiny::Capture is used to catch those warnings and we silently hold them
# until and unless someone tries to use dependant functions.
my ($out, $err, @result) = capture(
sub { runtime_load_module(\%OPTIONAL_PM,'Clipboard',undef); } );
if (length($err)) {
# Cleanup the error message for for better viewing by the user
$err =~ s/^\s+//g; $err =~ s/\s+$//g; $err =~ s/^(.*)$/ > $1/mg;
$OPTIONAL_PM{'Clipboard'}->{error} = $err;
}
} else {
# If we didn't get Capture::Tiny, also mark Clipboard as not loaded.
$OPTIONAL_PM{'Clipboard'}->{loaded} = 0;
}
# Win32::Console::ANSI is needed to emulate ANSI colors on Windows
if (lc($OSNAME) =~ m/^mswin/) {
if (! runtime_load_module(\%OPTIONAL_PM,'Win32::Console::ANSI',undef)) {
# If we don't have Win32::Console::ANSI then we want to override
# &main::color() and colored() from Term::ANSIColor with NOOPs.
no strict 'refs';
*color = sub { my $color = shift @_; return ''; };
*colored = sub { my $color = shift @_; my $text=shift @_; return $text; };
}
}
runtime_load_module(\%OPTIONAL_PM,'Sub::Install',undef);
$|=1; # flush immediately after writes or prints to STDOUT
my $DEBUG=0;
$Data::Dumper::Useqq = 1; # Have Dumper escape special chars (like \0)
my $DEFAULT_PASSWD_LEN = 20; # Default length of generated passwords.
my $DEFAULT_PASSWD_MIN = 1; # Minimum length of generated passwords.
my $DEFAULT_PASSWD_MAX = 50; # Maximum length of generated passwords.
my $DEFAULT_ENTRY_ICON = 0; # In keepassx, icon 0 is a golden key
my $DEfAULT_GROUP_ICON = 49; # In keepassx, icon 49 is an opened file folder
my $DEfAULT_BAKUP_ICON = 2; # In keepassx, icon 2 is a warning sign
my $FOUND_DIR = '_found'; # The find command's results go in /_found/
my $MAX_ATTACH_SIZE = 2*1024**2; # Maximum size of entry file attachments
# Application name and version
my $APP_NAME = basename($0); $APP_NAME =~ s/\.(pl|exe)$//;
my $VERSION = "3.0";
our $HISTORY_FILE = ""; # Gets set in the MyGetOpts() function
my $opts=MyGetOpts(); # Will only return with options we think we can use
my $doc_passwd_gen =
"For password generation, the \"g\" method produces a\n" .
"string of random characters, the \"w\" method creates a\n" .
"4-word string inspired by \"correct horse battery staple\"\n" .
"(http://xkcd.com/936/), and the \"i\" method provides an\n" .
"interactive user interface to the \"g\" and \"w\" methods.\n" .
"\n" .
"By default, the \"g\" and \"i\" methods generate passwords that\n" .
"are $DEFAULT_PASSWD_LEN characters long. " .
"That can be controlled by providing an\n" .
"integer immediately after the \"g|i\" in the range of "
. "$DEFAULT_PASSWD_MIN-$DEFAULT_PASSWD_MAX.\n" .
"For example, \"g17\" will generate a 17 character password.\n" .
"";
# Setup our Term::ShellUI object
my $term = new Term::ShellUI(
app => $APP_NAME,
term => get_readline_term(\%OPTIONAL_PM, $APP_NAME),
history_file => $HISTORY_FILE,
keep_quotes => 0,
commands => {
"ver" => {
desc => "Print the version of this program",
doc => "\n" .
"Add the -v option to get an inventory of the versions\n" .
"of the various dependencies being used. Please provide\n" .
"that information in any bug reports filed.\n" .
"",
method => \&cli_version,
minargs => 0, maxargs => 1,
exclude_from_history => 1,
timeout_exempt => 1,
},
"version" => { alias => "ver",
exclude_from_completion=>1, exclude_from_history => 1,
timeout_exempt => 1,
},
"vers" => {
desc => "Same as \"ver -v\"",
minargs => 0, maxargs => 0,
method => sub { cli_version(shift, { args => ['-v'] }); },
exclude_from_completion=>1, exclude_from_history => 1,
timeout_exempt => 1,
},
"versions" => { alias => "vers",
exclude_from_completion=>1, exclude_from_history => 1,
timeout_exempt => 1,
},
"help" => {
desc => "Print helpful information",
args => sub { shift->help_args(undef, @_); },
method => sub { my_help_call(@_); },
exclude_from_history => 1,
timeout_exempt => 1,
#method => sub { shift->help_call(undef, @_); }
},
"h" => { alias => "help",
exclude_from_completion=>1, exclude_from_history => 1,
timeout_exempt => 1,
},
"?" => { alias => "help",
exclude_from_completion=>1, exclude_from_history => 1,
timeout_exempt => 1,
},
"cls" => {
desc => 'Clear screen ("clear" command also works)',
doc => "\n" .
"Clear the screen, which is useful when guests arrive.\n",
maxargs => 0,
method => \&cli_cls,
exclude_from_history => 1,
timeout_exempt => 1,
},
"clear" => { alias => "cls", exclude_from_history => 1,
timeout_exempt => 1, },
"quit" => {
desc => "Quit this program (EOF and exit also work)",
maxargs => 0,
method => sub { run_no_TSTP(\&cli_quit, @_); },
exclude_from_history => 1,
timeout_exempt => 1,
},
"exit" => { alias => "quit", exclude_from_history => 1,
timeout_exempt => 1, },
# Generally, commands above here are timeout_exempt
#"" => { args => sub { shift->complete_history(@_) } },
"history" => { desc => "Prints the command history",
doc => "\nSpecify a number to list the last N lines of history.\n" .
"Pass -c to clear the command history.\n" .
"Pass -d NUM to delete a single item.\n",
args => "[-c] [-d] [number]",
method => sub { shift->history_call(@_) },
exclude_from_history => 1,
},
"cd" => {
desc => "Change directory (path to a group)",
doc => "\n" .
"Change the pwd to an absolute or relative path.\n" .
"Slashes in names are escaped with backslashes:\n" .
"(i.e. \"cd /personal/Comcast\\/Xfinity\").\n",
maxargs => 1,
args => \&complete_groups,
method => \&cli_cd,
},
"chdir" => { alias => 'cd' },
"cl" => {
desc => "Change directory and list entries (cd+ls)",
doc => "\n" .
"Change the pwd to an absolute or relative path\n" .
"and list the entries there. This is a useful way\n" .
"to quickly navigate to a path and have the entries\n" .
"listed in preparation to run the show command.\n",
maxargs => 1,
args => \&complete_groups,
method => sub { if(cli_cd(@_) == 0) { cli_ls() } },
},
"saveas" => {
desc => "Save to a specific filename " .
"(saveas <file.kdb> [<file.key>])",
minargs => 1, maxargs => 2,
args => [\&Term::ShellUI::complete_files,
\&Term::ShellUI::complete_files],
proc => sub { run_no_TSTP(\&cli_saveas, @_); },
},
"export" => {
desc => "Export entries to a new KeePass DB " .
"(export <file.kdb> [<file.key>])",
doc => "\n" .
"Use this command to export the full tree of groups\n" .
"and entries to another KeePass database file on disk,\n" .
"starting at your current path (pwd).\n" .
"\n" .
"This is also a \"safer\" way to change your database\n" .
"password. Export from /, verify that the new file is\n" .
"good, and then remove your original file.\n",
minargs => 1, maxargs => 2,
args => [\&Term::ShellUI::complete_files,
\&Term::ShellUI::complete_files],
proc => sub { run_no_TSTP(\&cli_export, @_); },
},
"import" => {
desc => "Import a password database " .
"(import <file> <path> [<file.key>])",
doc => "\n" .
"Use this command to import an entire password DB\n" .
"specified by <file> into a new group at <path>.\n" .
"Supported file types are KeePass v1 and v2, and\n" .
"Password Safe v3 (http://passwordsafe.sf.net).\n",
minargs => 2, maxargs => 3,
args => [\&Term::ShellUI::complete_files,\&complete_groups,
\&Term::ShellUI::complete_files],
proc => sub { run_no_TSTP(\&cli_import, @_); },
},
"open" => {
desc => "Open a KeePass database file " .
"(open <file.kdb> [<file.key>])",
minargs => 1, maxargs => 2,
args => [\&Term::ShellUI::complete_files,
\&Term::ShellUI::complete_files],
proc => sub { run_no_TSTP(\&cli_open, @_); },
},
"mkdir" => {
desc => "Create a new group (mkdir <group_name>)",
minargs => 1, maxargs => 1,
args => \&complete_groups,
method => \&cli_mkdir,
},
"rmdir" => {
desc => "Delete a group (rmdir <group_name>)",
minargs => 1, maxargs => 1,
args => \&complete_groups,
method => \&cli_rmdir,
},
"dir" => { alias => "ls", },
"ls" => {
desc => "Lists items in the pwd or specified paths " .
"(\"dir\" also works)",
minargs => 0, maxargs => 99,
args => \&complete_groups_and_entries,
method => \&cli_ls,
},
"new" => {
desc => "Create a new entry: new <optional path&|title>",
doc => "\n" .
"The new command is used to create a new entry.\n" .
"\n" .
"Usage is straightforward.\n" .
"\n" .
$doc_passwd_gen .
"",
minargs => 0, maxargs => 1,
args => [\&complete_groups],
method => sub { run_no_TSTP(\&cli_new, @_); },
},
"rm" => {
desc => "Remove an entry: rm <path to entry|entry number>",
minargs => 1, maxargs => 1,
args => \&complete_groups_and_entries,
method => \&cli_rm,
},
"xu" => {
desc => "Copy username to clipboard: xu <entry path|number>",
minargs => 1, maxargs => 1,
args => \&complete_groups_and_entries,
method => sub { cli_xN('xu', @_); }
},
"xw" => {
desc => "Copy URL (www) to clipboard: xw <entry path|number>",
minargs => 1, maxargs => 1,
args => \&complete_groups_and_entries,
method => sub { cli_xN('xw', @_); }
},
"xp" => {
desc => "Copy password to clipboard: xp <entry path|number>",
minargs => 1, maxargs => 1,
args => \&complete_groups_and_entries,
method => sub { cli_xN('xp', @_); }
},
"xx" => {
desc => "Clear the clipboard: xx",
minargs => 0, maxargs => 0,
method => sub { cli_xN('xx'); }
},
"pwck" => {
desc => "Check password quality: pwck <entry|group>",
doc => "\n" .
"The pwck command test password quality for entries.\n" .
"You can check an individual entry or all entries inside\n" .
"of a group, recursively. To check every password in your\n" .
"database, use: pwck /\n" .
"",
minargs => 1, maxargs => 1,
args => \&complete_groups_and_entries,
method => \&cli_pwck,
},
"stats" => {
desc => "Prints statistics about the open KeePass file",
method => \&cli_stats,
},
"show" => {
desc => "Show an entry: show [-f] [-a] <entry path|entry number>",
doc => "\n" .
"The show command tries to intelligently determine\n" .
"what you want to see and to make it easy to display.\n" .
"Show can take a path to an entry as its argument or\n" .
"an entry number as shown by the ls command.\n" .
"\n" .
"When using entry numbers, they will refer to the last\n" .
"path when an ls was performed or pwd if ls has not\n" .
"yet been run.\n" .
"\n" .
"By default, passwords are \"hidden\" by being displayed as\n" .
"\"red on red\" where they can be copied to the clip board\n" .
"but not seen. Provide the -f option to show passwords.\n" .
"Use the -a option to see create and modified times, and\n" .
"the index of the icon set for the entry.\n" .
"",
minargs => 1, maxargs => 3,
args => \&complete_groups_and_entries,
method => \&cli_show,
},
"edit" => {
desc => "Edit an entry: edit <path to entry|entry number>",
doc => "\n" .
"The edit command is used to modify an entry.\n" .
"\n" .
"Usage is straightforward.\n" .
"\n" .
$doc_passwd_gen .
"",
minargs => 1, maxargs => 1,
args => \&complete_groups_and_entries,
method => sub { run_no_TSTP(\&cli_edit, @_); },
},
"attach" => {
desc => "Manage attachments: attach <path to entry|entry number>",
doc => "\n" .
"The attach command provided an interactive user interface\n" .
"for managing file attachments on an entry.\n" .
"",
minargs => 1, maxargs => 1,
args => \&complete_groups_and_entries,
method => sub { run_no_TSTP(\&cli_attach, @_); },
},
"mv" => {
desc => "Move an item: mv <path to a group|or entries> <path to group>",
minargs => 2, maxargs => 2,
args => [\&complete_groups_and_entries, \&complete_groups],
method => \&cli_mv,
},
"rename" => {
desc => "Rename a group: rename <path to group>",
minargs => 1, maxargs => 1,
args => \&complete_groups,
method => \&cli_rename,
},
"copy" => {
desc => "Copy an entry: copy <path to entry> <path to new entry>",
minargs => 2, maxargs => 2,
args => [\&complete_groups_and_entries,
\&complete_groups_and_entries],
method => \&cli_copy,
},
"cp" => { alias => "copy", },
"clone" => {
desc =>"Clone an entry: clone <path to entry> <path to new entry>",
doc => "\n" .
"Clones an entry for you to edit. Similar to doing\n" .
"\"cp foo bar; edit bar\" if that were possible.\n" .
"\n",
minargs => 2, maxargs => 2,
args => [\&complete_groups_and_entries,
\&complete_groups_and_entries],
method => sub { run_no_TSTP(\&cli_clone, @_); },
},
"save" => {
desc => "Save the database to disk",
minargs => 0, maxargs => 0, args => "",
method => sub { run_no_TSTP(\&cli_save, @_); },
},
"close" => {
desc => "Close the currently opened database",
minargs => 0, maxargs => 0, args => "",
method => sub { run_no_TSTP(\&cli_close, @_); },
},
"find" => {
desc => "Finds entries by Title",
doc => "\n" .
"Searches for entries with the given search term\n" .
"in their title and places matches into \"/$FOUND_DIR/\".\n" .
"\n" .
"Add -a to search data fields beyond just the title.\n" .
"\n" .
"Use -expired to find expired entries.\n",
minargs => 1, maxargs => 2, args => "<search string>",
method => \&cli_find,
},
"pwd" => {
desc => "Print the current working directory",
maxargs => 0, proc => \&cli_pwd,
},
"icons" => {
desc => "Change group or entry icons in the database",
maxargs => 0,
proc => sub { run_no_TSTP(\&cli_icons, @_); },
},
},
);
$term->prompt(\&term_set_prompt);
# Seed our state global variable
our $state={
'appname' => $APP_NAME,
'term' => $term,
'OPTIONAL_PM' => \%OPTIONAL_PM,
'kdb_has_changed' => 0,
'last_ls_ents' => [], # Array of entries last listed to the user.
'put_master_passwd' => \&put_master_passwd,
'get_master_passwd' => \&get_master_passwd,
'last_activity_time' => 0, # initilized by setup_timeout_handling()
};
# If given --kdb=, open that file
if (length($opts->{kdb})) {
my $err = open_kdb($opts->{kdb}, $opts->{key}); # Sets $state->{'kdb'}
if (length($err)) {
print "Error opening file: $err\n";
}
} else {
new_kdb($state);
}
# Enter the interative kpcli shell session
print "\n" .
"KeePass CLI ($APP_NAME) v$VERSION is ready for operation.\n" .
"Type 'help' for a description of available commands.\n" .
"Type 'help <command>' for details on individual commands.\n";
if ($DEBUG) {print 'Using '.$term->{term}->ReadLine." for readline.\n"; }
if ( (! $DEBUG) && (lc($OSNAME) !~ m/^mswin/) &&
($term->{term}->ReadLine ne 'Term::ReadLine::Gnu')) {
print color('yellow') . "\n" .
"* NOTE: You are using " . $term->{term}->ReadLine . ".\n" .
" Term::ReadLine::Gnu will provide better functionality.\n" .
color('clear');
}
# My patch made it into Term::ShellUI v0.9, but I still chose not to make
# this program demand >=0.9 and instead look for the add_eof_exit_hook()
# and use it if it exists and warn if not.
if (Term::ShellUI->can('add_eof_exit_hook')) {
$term->add_eof_exit_hook(\&eof_exit_hook);
} else {
warn "* Please upgrade Term::ShellUI to version 0.9 or newer.\n";
}
print "\n";
setup_signal_handling(); # Exactly what the name indicates...
# Setup the inactivity timeout feature (--timeout).
if (defined($opts->{timeout}) && int($opts->{timeout}) > 0) {
if (! $state->{OPTIONAL_PM}->{'Sub::Install'}->{loaded}) {
print "Error: --timeout requires the Sub::Install module.\n";
exit;
}
setup_timeout_handling();
}
$term->run();
exit;
############################################################################
############################################################################
############################################################################
sub open_kdb {
my $file=shift @_;
my $key_file=shift @_;
our $state;
# Make sure the file exists, is readable, and is a keepass file
if (! -f $file) {
return "File does not exist: $file";
}
if (! -r $file) {
return "File is not readable: $file";
}
if (magic_file_type($file) ne 'keepass') {
return "Does not appear to be a KeePass file: $file";
}
# Look for lock file and warn if it is found
my $lock_file = $file . '.lock'; # KeePassX style
if (-f $lock_file &&
! (defined($opts->{readonly}) && int($opts->{readonly})) ) {
print color('bold yellow') .
"WARNING:" .
color('clear') . color('red') .
" A KeePassX-style lock file is in place for this file.\n" .
" It may be opened elsewhere." .
" " . color('bold yellow') . "Be careful of saving!\n" .
color('clear');
} else {
$state->{placed_lock_file} = $lock_file;
}
# Ask the user for the master password and then open the kdb
my $master_pass=GetMasterPasswd();
if (recent_sigint()) { return undef; } # Bail on SIGINT
$state->{kdb} = File::KeePass->new;
if (! eval { $state->{kdb}->load_db($file,
composite_master_pass($master_pass, $key_file)) }) {
die "Couldn't load the file $file: $@";
}
if ($state->{placed_lock_file}) {
touch_file($state->{placed_lock_file});
}
# We hold a read file handle open for no reason other than
# to show up in lsof.
if (defined($state->{kdb_file_handle})) {
close $state->{kdb_file_handle};
}
$state->{kdb_file_handle} = new FileHandle;
open($state->{kdb_file_handle}, '<', $file);
$state->{kdb_file} = $file;
$state->{key_file} = $key_file;
$state->{kdb_ver} = $state->{kdb}->{header}->{version}; # will be 1 or 2
$state->{put_master_passwd}($master_pass);
$state->{kdb_has_changed}=0;
$master_pass="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
# Build the %all_grp_paths_fwd and %all_grp_paths_rev structures
refresh_state_all_paths();
# Store the md5sum of the file so we can watch for unexpected changes
$state->{kdb_file_md5} = Digest::file::digest_file_hex($file, "MD5");
# Initialize our state into "/"
cli_cd($term, {'args' => ["/"]});
return ''; # If we return anything else it is an error message
}
# Called by Term::ShellUI to get the user prompt
sub term_set_prompt($$) {
my $term=shift @_;
my $raw_cmd=shift @_;
our $state;
my $app=$state->{appname};
my $pwd=get_pwd();
return "$app:$pwd> ";
}
# Walks through a tree of groups building a flat hash of NULL-separated
# paths to group IDs. Called on the root to build a full path tree.
sub build_all_group_paths {
my $hash = shift @_;
my $g = shift @_;
my $root_path = shift @_ || [];
foreach my $me (@{$g}) {
my @path_to_me = @{$root_path};
push @path_to_me, $me->{title};
my $path=join("\0",@path_to_me);
my $err_path = '/' . humanize_path($path);
if (defined($hash->{$path})) {
print color('bold yellow') . "WARNING: " . color('clear') .
color('red') . "Multiple groups titled: $err_path!\n" .
color('red') . "This is unsupported and may cause data loss!\n" .
color('clear');
}
$hash->{$path}=$me->{id};
if (defined($me->{groups})) {
build_all_group_paths($hash,$me->{groups},\@path_to_me);
}
}
return (scalar(keys(%{$hash})));
}
# Walks through a tree of groups building a flat hash of NULL-separated
# paths to entry IDs. Called on the root to build a full path tree.
sub build_all_entry_paths {
my $hash = shift @_;
my $g = shift @_;
my $root_path = shift @_ || [];
my $red=color('red');
foreach my $me (@{$g}) {
my @path_to_me = @{$root_path};
push @path_to_me, $me->{title};
if (defined($me->{entries})) {
ENTRY: foreach my $ent (@{$me->{entries}}) {
if ($ent->{'title'} eq 'Meta-Info' && $ent->{'username'} eq 'SYSTEM') {
next ENTRY; # skip Meta-Info/SYSTEM entries
}
my $path=join( "\0", (@path_to_me, $ent->{title}) );
my $err_path = '/' . humanize_path($path);
if ($ent->{title} eq '') {
print color('bold yellow') . "WARNING: " . color('clear') .
$red . "There is an entry with a blank title in $err_path!\n" .
color('clear');
}
if (defined($hash->{$path}) &&
$err_path !~ m/\/Backup\/|\/Meta-Info$/) {
print color('bold yellow') . "WARNING: " . color('clear') .
$red . "Multiple entries titled: $err_path!\n" .
$red . "This is unsupported and may cause data loss!\n" .
color('clear');
}
$hash->{$path}=$ent->{id};
}
}
if (defined($me->{groups})) {
build_all_entry_paths($hash,$me->{groups},\@path_to_me);
}
}
return (scalar(keys(%{$hash})));
}
# Returns the current path the user is sitting in.
sub get_pwd {
my $pwd='';
if (defined($state->{all_grp_paths_rev}->{$state->{path}->{id}})) {
$pwd=$state->{all_grp_paths_rev}->{$state->{path}->{id}};
}
$pwd =~ s%/%\\/%g;
$pwd =~ s/\0/\//g;
$pwd = '/' . $pwd;
return $pwd;
}
# Destroys our /_found group (where we place search results)
sub destroy_found {
our $state;
# Look for an exising /_found and kill it if it exists
my $k=$state->{kdb};
my $found_group=$k->find_group({level=>0,title=>$FOUND_DIR});
if (defined($found_group)) {
my @oldents = $k->find_entries({group=>$found_group->{id}});
foreach my $ent (@oldents) {
$k->delete_entry({id => $ent->{id}});
}
$k->delete_group({level=>0,title=>$FOUND_DIR});
# Because we destroyed /_found we must refresh our $state paths
refresh_state_all_paths();
}
}
# Refreshes $state->{all_grp_paths_fwd} and $state->{all_grp_paths_rev}
sub refresh_state_all_paths() {
our $state;
# Build all group paths
my %all_grp_paths_fwd;
build_all_group_paths(\%all_grp_paths_fwd,$state->{kdb}->groups);
my %all_grp_paths_rev = reverse %all_grp_paths_fwd;
$state->{all_grp_paths_fwd}=\%all_grp_paths_fwd;
$state->{all_grp_paths_rev}=\%all_grp_paths_rev;
# Build all entry paths
my %all_ent_paths_fwd;
build_all_entry_paths(\%all_ent_paths_fwd,$state->{kdb}->groups);
my %all_ent_paths_rev = reverse %all_ent_paths_fwd;
$state->{all_ent_paths_fwd}=\%all_ent_paths_fwd;
$state->{all_ent_paths_rev}=\%all_ent_paths_rev;
}
# Gathers the list of groups and entries for the pwd we're sitting in
sub get_current_groups_and_entries {
return get_groups_and_entries(get_pwd());
}
sub get_groups_and_entries {
my $path=shift @_;
our $state;
my $k=$state->{kdb};
# Collect the @groups and entries
my @groups=();
my @entries=();
my $norm_path = normalize_path_string($path);
if (length($norm_path) < 1) {
@groups = $k->find_groups({level=>0});
@entries = $k->find_entries({level => 0});
} else {
my $id=$state->{all_grp_paths_fwd}->{$norm_path};
my ($this_grp,@trash) = $k->find_groups({id=>$id});
if (defined($this_grp->{groups})) { # subgroups
@groups = @{$this_grp->{groups}};
}
@entries = $k->find_entries({group_id => $id});
}
# Remove Meta-Info/SYSTEM entries
my @non_meta_info = ();
foreach my $ent (@entries) {
if (!($ent->{'title'} eq 'Meta-Info' && $ent->{'username'} eq 'SYSTEM')) {
push @non_meta_info, $ent;
}
}
@entries = @non_meta_info;
# Sort the results
@groups = sort group_sort @groups;
@entries = sort { ncmp($a->{title},$b->{title}); } @entries;
return (\@groups,\@entries);
}
# This function takes a group ID and returns all of the child
# groups of that group, flattened.
sub all_child_groups_flattened {
my $group_id=shift @_;
our $state;
my $k=$state->{kdb};
my @groups=();
my ($this_grp,@trash) = $k->find_groups({id=>$group_id});
if (defined($this_grp->{groups})) { # subgroups
@groups = @{$this_grp->{groups}};
foreach my $child_group (@groups) {
push @groups, all_child_groups_flattened($child_group->{id});
}
}
return @groups;
}
# A function to properly sort groups by title
sub group_sort($$) {
my $a=shift @_;
my $b=shift @_;
# _found at level 0 is a special case (from our find command).
if ($a->{title} eq $FOUND_DIR && $a->{level} == 0) {
return 1;
} elsif ($b->{title} eq $FOUND_DIR && $b->{level} == 0) {
return -1;
# Backup at level=0 is a special case (KeePassX's Backup group).
} elsif ($a->{title} eq 'Backup' && $a->{level} == 0) {
return 1;
} elsif ($b->{title} eq 'Backup' && $b->{level} == 0) {
return -1;
# "Recycle Bin" at level=0 is a special case (KeePass v2).
} elsif ($a->{title} eq 'Recycle Bin' && $a->{level} == 0) {
return 1;
} elsif ($b->{title} eq 'Recycle Bin' && $b->{level} == 0) {
return -1;
# Sort everything else naturally (Sort::Naturally::ncmp).
} else {
return ncmp($a->{title},$b->{title}); # Natural sort
}
}
# -------------------------------------------------------------------------
# All of the cli_*() functions are below here
# -------------------------------------------------------------------------
# A simple wrapper function to block SIGTSTP (^Z) during certain commands
sub run_no_TSTP {
my $func = shift @_;
$SIG{TSTP}='IGNORE';
my @retval = &$func(@_);
$SIG{TSTP}='DEFAULT';
return @retval;
}
# Checks passwords for their quality
sub cli_pwck {
my $self = shift @_;
my $params = shift @_;
our $state;
if (recent_sigint()) { return undef; } # Bail on SIGINT
# If Data::Password is not avaiable we can't do this for the user
if (! $state->{OPTIONAL_PM}->{'Data::Password'}->{loaded}) {
print "Error: pwck requires the Data::Password module.\n";
return;
}
my @targets = ();
my $target = $params->{args}->[0];
# Start by trying to find a single entity with the paramter given.
# If no single entity is found then try to find entities based on
# assuming that the path given is a group.
my $ent=find_target_entity_by_number_or_path($target);
if (defined($ent)) {
push @targets, $ent;
} else {
my @groups = ();
my $target = normalize_path_string($target);
if ($target eq '' || $target eq '.' && get_pwd() eq '/') {
@groups = $state->{kdb}->find_groups({}); # Every group in the file!
} elsif (defined($state->{all_grp_paths_fwd}->{$target})) {
my $group_id = $state->{all_grp_paths_fwd}->{$target};
my $this_grp = $state->{kdb}->find_group( { id => $group_id } );
@groups = all_child_groups_flattened($group_id);
push @groups, $this_grp; # Push this group onto its children
}
# Loop over each target group adding each of its entries as targets
foreach my $group (@groups) {
if (defined($group->{entries})) {
push @targets, @{$group->{entries}};
}
}
}
# Test each password, collect the results and record empty passwords
my %results=();
my @empties = ();
print " working...\r";
my @busy_chars = qw(\ | / -); my $i=0; my $in=10;
foreach my $ent (@targets) {
printf "%s\r", $busy_chars[int($i/$in)%($#busy_chars+1)] if (!($i++ % $in));
my $pass = $state->{kdb}->locked_entry_password($ent);
if (length($pass) == 0) {
push @empties, $ent;
$results{$ent->{id}} = '';
} else {
$results{$ent->{id}} = IsBadPassword($pass);
if ($results{$ent->{id}} =~ m/dictionary word/i) {
# IsBadPassword() reports dictionary words that it finds. I don't
# like that from a security perspective so we change that here.
$results{$ent->{id}} = "contains a dictionary word";
}
}
# If the user hit ^C (SIGINT) then we need to stop
if (recent_sigint()) {
print "\r"; # Need to return to column 0 of the output line
return 0;
}
}
# If we only analyzed one password, return singular-style results
if (scalar(@targets) == 1) {
my $ent=$targets[0];
if (length($results{$ent->{id}})) {
print "Password concerns: " . $results{$ent->{id}} . "\n";
} elsif (scalar(@empties) > 0) {
print "Password field is empty.\n";
} else {
print "Password strength is good.\n";
}
} else {
# If we analyzed more than one password, return multiple-style results
my %problems=();
foreach my $ent_id (keys %results) {
if (length($results{$ent_id})) {
$problems{$state->{all_ent_paths_rev}->{$ent_id}} = $ent_id;
}
}
my $analyzed = scalar(@targets);
my $problem_count = scalar(keys %problems);
my $empty_count = scalar(@empties);
print "$analyzed passwords analyzed, $empty_count blank, " .
"$problem_count concerns found";
if ($problem_count > 0) { print ":"; } else { print "."; }
print "\n";
foreach my $path (sort keys %problems) {
print humanize_path($path) . ": $results{$problems{$path}}\n";
}
}
return 0;
}
# Prints some statistics about the open KeePass file
sub cli_stats {
my $self = shift @_;
my $params = shift @_;
our $state;
if (recent_sigint()) { return undef; } # Bail on SIGINT
# Group and entry counts
my %stats;
$stats{group_count} = scalar(keys(%{$state->{all_grp_paths_fwd}}));
$stats{entry_count} = scalar(keys(%{$state->{all_ent_paths_fwd}}));
# Password lengths
my $k=$state->{kdb};
my %password_lengths;
print " working...\r";
my @busy_chars = qw(\ | / -); my $i=0; my $in=100;
foreach my $ent_id (values(%{$state->{all_ent_paths_fwd}})) {
printf "%s\r", $busy_chars[int($i/$in)%($#busy_chars+1)] if (!($i++ % $in));
my $ent = $k->find_entry({id => $ent_id});
my $pass_len = length($k->locked_entry_password($ent));
if ($pass_len < 1) {
$password_lengths{"0"}++;
} elsif ($pass_len > 0 && $pass_len < 8) {
$password_lengths{"1-7"}++;
} elsif ($pass_len > 7 && $pass_len < 12) {
$password_lengths{"8-11"}++;
} elsif ($pass_len > 11 && $pass_len < 17) {
$password_lengths{"12-16"}++;
} elsif ($pass_len > 16 && $pass_len < 20) {
$password_lengths{"17-19"}++;
} elsif ($pass_len > 19) {
$password_lengths{"20+"}++;
}
# If the user hit ^C (SIGINT) then we need to stop
if (recent_sigint()) {
print " "x20 . "\r"; # Need to return to column 0 of the output line
return 0;
}
}
my $t= " "x20 . "\r" .
"File: " . $state->{kdb_file} . "\n" .
"Key file: " .
(defined($state->{key_file}) ? $state->{key_file} : 'N/A') . "\n";
if (defined($k->{header}->{database_name})) {
$t.="Name: " . $k->{header}->{database_name} . "\n";
}
if (defined($k->{header}->{database_description})) {
my $desc = $k->{header}->{database_description};
$desc =~ s/[\r\n]/\n/g;
my @l = split(/\n/, $desc);
$t .= "Description:\n" . "| " . join("\n| ", @l) . "\n";
}
$t .= "KeePass file version: " . $k->{header}->{version} . "\n" .
"Encryption type: " . $k->{header}->{enc_type} . "\n" .
"Encryption rounds: " . $k->{header}->{rounds} . "\n";
if (defined($k->{header}->{cipher})) {
$t.="Cipher: $stats{cipher}\n";
}
if (defined($k->{header}->{compression})) {
$t.="Compression: $stats{compression}\n";
}
$t .= "Number of groups: $stats{group_count}\n" .
"Number of entries: $stats{entry_count}\n" .
"Entries with passwords of length:\n".stats_print(\%password_lengths) .
"\n" .
"";
print $t;
}
sub cli_cls {
if (lc($OSNAME) =~ m/^mswin/ &&
(! $OPTIONAL_PM{'Win32::Console::ANSI'}->{loaded})) {
system("cls");
} else {
print "\033[2J\033[0;0H";
$|=1; # Needed for MS Windows (Win32::Console::ANSI works w/this flush)
}
}