-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpw7.pl
executable file
Β·2346 lines (2211 loc) Β· 110 KB
/
pw7.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/env perl -w
use warnings;
use strict;
use Crypt::OpenPGP;
use Expect;
use File::Path 'rmtree';
use Getopt::Std;
use IO::Prompt;
use IO::Stty;
use Sys::Hostname; #to get the hostname
use Term::ReadLine; #used for the menuing system
use Term::ReadKey;
#This untaints the environment path
$ENV{'PATH'} = '/bin:/usr/bin';
package pw7;
my $version = "0.1b";
my @ISA = qw(Exporter);
my @EXPORT = qw(signalHandler);
my %commandLineOptions;
Getopt::Std::getopts('hvdt', \%commandLineOptions);
$SIG{'QUIT'} = \&signalHandler;
$SIG{'TERM'} = \&signalHandler;
$SIG{'KILL'} = \&signalHandler;
$SIG{'INT'} = \&signalHandler;
my $env;
$env->{'commandlineoptions'} = \%commandLineOptions;
$env->{'loginName'} = getlogin();
$env = pw7::init($env);
$env = pw7::logMeIn($env);
$env = pw7::main($env);
sub main {
my $environment = $_[0] or die "Print menu called without environment.\n";
pw7::printDebug($environment, "Main called.\n");
my $term = Term::ReadLine->new('Password');
my $prompt = $environment->{'prompt'};
while ( defined ($_ = $term->readline($environment->{'prompt'})))
{
($_ eq '?' || $_ eq 'help') && do {
pw7::printRegularMenu($environment);
next;
};
(/^init/) && do {
$environment = pw7::initUser($environment);
if ($environment->{'errorLevel'} eq '0') {
print "Environment initialized successfully.\n";
} else {
print "Environment initialize failed: " . $environment->{'errorString'} . "\n";
delete $environment->{'errorString'};
$environment->{'errorLevel'}=0;
}
next;
};
(/^login/) && do {
pw7::logMeIn($environment, "Password: ");
next;
};
(/^get/) && do {
my @arg = split(/\s+/, $_);
$environment->{'itemName'} = $arg[1];
$environment->{'fromLoginIndicator'} = '0';
$environment->{'itemPath'} = $environment->{'itemsPath'};
pw7::getItem($environment);
delete $environment->{'itemPath'};
next;
};
(/^full/) && do {
my @arg = split(/\s+/, $_);
$environment->{'itemName'} = $arg[1];
$environment->{'fromLoginIndicator'} = '0';
$environment->{'itemPath'} = $environment->{'itemsPath'};
$environment->{'getFull'} = '1';
pw7::getItem($environment);
delete $environment->{'itemPath'};
next;
};
(/^create/) && do {
$environment = pw7::checkLocked($environment);
if ($environment->{'isLocked'}) {
print "User " . $environment->{'lockedBy'} . " has the application locked with PID " . $environment->{'lockPID'} . ".\n";
next;
} else {
$environment = pw7::lockApplication($environment);
my @arg = split(/\s+/, $_);
$environment->{'itemName'} = $arg[1];
$environment = pw7::newItem($environment);
$environment = pw7::unlockApplication($environment);
next;
}
};
(/^passwd/) && do {
$environment = pw7::changePassword($environment);
next;
};
(/^auth/) && do {
$environment = pw7::checkLocked($environment);
if ($environment->{'isLocked'}) {
print "User " . $environment->{'lockedBy'} . " has the application locked with PID " . $environment->{'lockPID'} . ".\n";
} else {
$environment = pw7::lockApplication($environment);
my @arg = split(/\s+/, $_);
$environment->{'itemName'} = $arg[1];
pw7::authItem($environment);
$environment = pw7::unlockApplication($environment);
}
next;
};
(/^set/) && do {
$environment = pw7::checkLocked($environment);
if ($environment->{'isLocked'}) {
print "User " . $environment->{'lockedBy'} . " has the application locked with PID " . $environment->{'lockPID'} . ".\n";
} else {
$environment = pw7::lockApplication($environment);
my @arg = split(/\s+/, $_);
$environment->{'itemName'} = $arg[1];
$environment = pw7::setItem($environment);
$environment = pw7::unlockApplication($environment);
}
next;
};
(/^delete/) && do {
$environment = pw7::checkLocked($environment);
if ($environment->{'isLocked'}) {
print "User " . $environment->{'lockedBy'} . " has the application locked with PID " . $environment->{'lockPID'} . ".\n";
} else {
$environment = pw7::lockApplication($environment);
my @arg = split(/\s+/, $_);
if ( defined $arg[1]) {
pw7::printDebug($environment, "deleting Item: " . $arg[1] . "\n");
$environment->{'itemName'} = $arg[1];
$environment = pw7::deleteItem($environment);
$environment = pw7::unlockApplication($environment);
} else {
print "Pass an item name as a parameter.\n";
}
}
next;
};
(/^quit/ || /^exit/) && do {
$environment = pw7::logMeOut($environment);
last;
};
($_ eq 'logout') && do {
$environment = pw7::logMeOut($environment);
next;
};
($_ eq 'p') && do {
$environment = pw7::printHashReference($environment);
next;
};
($_ eq 'a' || $_ eq 'ahelp') && do {
pw7::printAdvancedMenu($environment);
next;
};
($_ eq 'lm') && do {
pw7::listMasterPublicKeys($environment);
next;
};
($_ eq 'lh') && do {
pw7::listHomePrivateKeys($environment);
next;
};
($_ eq 'g') && do {
$environment = pw7::checkLocked($environment);
if ($environment->{'isLocked'}) {
print "User " . $environment->{'lockedBy'} . " has the application locked with PID " . $environment->{'lockPID'} . ".\n";
next;
} else {
$environment = pw7::lockApplication($environment);
pw7::generateKeys($environment, $environment->{'loginName'} . "-Pw7");
$environment = pw7::unlockApplication($environment);
next;
}
};
($_ eq 's') && do {
$environment = pw7::checkLocked($environment);
pw7::printDebug($environment, "Submit personal called.\n");
if ($environment->{'isLocked'}) {
print "User " . $environment->{'lockedBy'} . " has the application locked with PID " . $environment->{'lockPID'} . ".\n";
next;
} else {
$environment = pw7::lockApplication($environment);
&addPersonalPublicToMaster($environment);
$environment = pw7::unlockApplication($environment);
next;
}
};
($_ eq 'e') && do {
if ($environment->{'userFullyAuthenticated'} eq '0') {
print "Login first (login).";
} elsif ($environment->{'userFullyAuthenticated'} eq '1') {
$environment = pw7::readAuthFileFromDisk($environment);
}
next;
};
($_ eq 't') && do {
pw7::toggleVerbose($environment);
next;
};
($_ eq 'hm') && do {
pw7::printUserNametoHexKeyMappings($environment, "master");
next;
};
($_ eq 'hp') && do {
pw7::printUserNametoHexKeyMappings($environment, "private");
next;
};
($_ eq 'list') && do {
pw7::listItems($environment);
next;
};
($_ eq 'r') && do {
pw7::printAuthorizationsDataStructure($environment);
next;
};
($_ eq 'c') && do {
pw7::createDummyEncryptedFile($environment);
next;
};
($_ eq 'l') && do {
$environment = pw7::lockApplication($environment);
next;
};
($_ eq 'u') && do {
$environment = pw7::unlockApplication($environment);
next;
};
($_ eq 'd') && do {
$environment = pw7::deleteEverythingAndStartOver($environment);
next;
};
($_ eq 'fc') && do {
$environment = pw7::doFileAndPermissionChecks($environment);
next;
};
#write the authorization table to disk
($_ eq 'w') && do {
$environment = pw7::checkLocked($environment);
if ($environment->{'isLocked'}) {
print "User " . $environment->{'lockedBy'} . " has the application locked with PID " . $environment->{'lockPID'} . ".\n";
next;
} else {
$environment = pw7::lockApplication($environment);
&writeAuthorizationsTableToDisk($environment);
$environment = pw7::unlockApplication($environment);
next;
}
};
($_ eq 'wh') && do {
$environment = pw7::checkLocked($environment);
if ($environment->{'isLocked'}) {
print "User " . $environment->{'lockedBy'} . " has the application locked with PID " . $environment->{'lockPID'} . ".\n";
next;
} else {
print "The application isn't locked.\n";
next;
}
};
($_ eq 'f') && do {
$environment = pw7::checkLocked($environment);
if ($environment->{'isLocked'}) {
$environment = pw7::forceUnlock($environment);
next;
} else {
print "The application is not locked.\n";
next;
}
};
($_ eq 'cl') && do {
$environment = pw7::checkLocked($environment);
print "Locked status: " . scalar($environment->{'isLocked'}) . "\n";
next;
};
($_ eq 'ch') && do {
$environment = pw7::changeLoginName($environment);
next;
};
do {
print "Invalid menu command (try ? for help).\n";
}
}
return $environment;
}
sub init {
my $environment = $_[0] or die "Init called without environment\n";
#print these should probably be tuned
$environment->{'gpgPath'} = '/usr/local/bin/gpg';
#this should print out the PID of every process on the system
$environment->{'pscmd'} = '/bin/ps -ef | awk \'{print $2}\'';
$environment->{'applicationData'} = '/var/tmp/pw7/';
$environment->{'applicationRootData'} = '/var/tmp/pw7/';
#these generally don't need to be tuned
$environment->{'homepath'} = $ENV{HOME};
$environment->{'authFile'} = $environment->{'applicationData'} . 'pw7.auth';
$environment->{'encryptedauthFile'} = $environment->{'applicationData'} . 'pw7.encryptedauth';
$environment->{'itemsPath'} = $environment->{'applicationRootData'} . 'items/';
$environment->{'homeKeyPath'} = $environment->{'homepath'} . '/.pw7/' . $environment->{'loginName'};
$environment->{'homeKeyRoot'} = $environment->{'homeKeyPath'} . '/personalkeyring';
$environment->{'masterPublicKeyringPath'} = $environment->{'applicationRootData'};
$environment->{'lockFilePath'} = $environment->{'applicationData'};
$environment->{'masterPublicKeyring'} = $environment->{'masterPublicKeyringPath'} . '/pubring.gpg';
$environment->{'homePublicKeyring'} = $environment->{'homeKeyPath'} . "/pubring.gpg";
$environment->{'homePrivateKeyring'} = $environment->{'homeKeyPath'} . "/secring.gpg";
$environment->{'keySize'} = '1024';
$environment->{'term'} = Term::ReadLine->new('Password');
$environment->{'prompt'} = $environment->{'loginName'} . '@pw7> ';
$environment->{'passphrase'} = '';
$environment->{'keyValidityTimeInDays'} = '0'; #maybe implement expiring keys, key rotation later
$environment->{'hostname'} = Sys::Hostname::hostname();
$environment->{'termreadlineconf'} = $environment->{'term'}->Attribs();
$environment->{'passphraseValidated'} = '0';
$environment->{'verbose'} = 'false';
$environment->{'rootKeyName'} = 'pw7-rootcert';
$environment->{'maxItemNameLength'} = '33';
$environment->{'errorLevel'} = '0';
$environment->{'requiresignedauth'} = '0';
$environment->{'errorLevel'} = '0';
$environment->{'currentPID'} = "$$";
$environment->{'isPasswordRotating'} = '0';
$environment->{'developerMode'} = '0';
$environment->{'timestamp'} = localtime(time);
$environment->{'userFullyAuthenticated'} = '0';
$environment->{'getFull'} = '0';
if ($environment->{'commandlineoptions'}->{'t'}) {
print "Executing application in temporary mode\n";
$environment->{'gpgPath'} = '/tmp/gpg';
$environment->{'applicationData'} = '/tmp/pw7Data/';
$environment->{'applicationRootData'} = '/tmp/pw7RootData/';
} else {
}
if ($environment->{'commandlineoptions'}->{'h'}) {
pw7::printUsage();
exit 1;
}
if ($environment->{'commandlineoptions'}->{'v'}) {
pw7::toggleVerbose($environment);
}
if ($environment->{'commandlineoptions'}->{'d'}) {
$environment = pw7::deleteEverythingAndStartOver($environment);
}
$environment = pw7::doFileAndPermissionChecks($environment);
return $environment;
}
sub changePassword {
my $environment = $_[0] or die "Print menu called without environment\n";
pw7::printDebug($environment, "Change password called.\n");
if ($environment->{'passphraseValidated'} eq '0') {
print "Login first (login).\n";
return $environment;
} elsif ($environment->{'passphraseValidated'} eq '1') {
my $command = $environment->{'gpgPath'} . " --homedir " . $environment->{'homeKeyPath'} . " --edit-key " . $environment->{'loginName'} . "-pw7" . "\n";
pw7::printDebug($environment, $command);
my $session = new Expect();
$session->spawn("$command") or die "Unable to execute command: $command";
if ($environment->{'verbose'} eq 'true') {
pw7::printDebug($environment, "Setting expect.pm settings for verbose.\n");
$session->debug(1);
$session->log_stdout(1);
} else {
$session->log_stdout(0);
$session->debug(0);
}
my $match = $session->expect(10,
[qr/Command>/ => sub {
$session->send("passwd\n"),
Expect::exp_continue; }],
[qr/Enter passphrase: $/ => sub {
$session->send($environment->{'passphrase'} . "\n")}]
);
$environment->{'isPasswordRotating'} = '1';
pw7::setMyPassphrase($environment);
pw7::printDebug($environment, "match: $match\n");
$match = $session->expect(10,
["Enter passphrase:" => sub {
pw7::printDebug($environment, "sending first passphrase\n");
$session->send($environment->{'passphrase'} . "\n"),
Expect::exp_continue;}],
["Repeat passphrase: " => sub {
pw7::printDebug($environment, "Sending second passphrase\n");
$session->send($environment->{'passphrase'} . "\n"),
Expect::exp_continue;}],
["Command> " => sub {
$session->send("quit\n"),
Expect::exp_continue;}],
[qr/Save changes\? \(y\/N\)/ => sub {
print "\nSaving updated key.\n";
$session->send("y\n"),
Expect::exp_continue;}]
);
$environment->{'passphrase'} = $environment->{'password'};
delete $environment->{'password'};
}
return $environment;
}
sub printUsage {
print "usage: $0 [-v] pw7 command\n";
print "\truns the pw7 interactive interpreter\n";
print "\t-v\tverbose mode\n";
print "\t-h\tprint this help menu and exit\n";
print "\t-d\tdelete everything and start over\n";
}
sub signalHandler {
my $environment = $_[0] or die "Print menu called without environment\n";
print "Caught signal, exiting.\n";
$environment = pw7::unlockApplication($environment);
Term::ReadKey::ReadMode('restore');
exit 1;
}
sub printRegularMenu {
my $environment = $_[0] or die "Print menu called without environment\n";
print "\nuser commands:\n";
print "\t? Print this help\n";
print "\tget <item> Get the password for item <title>\n";
print "\tset <item> Set the password for item <title>\n";
print "\tcreate <item> Create a new item <title> and set the item's password\n";
print "\tauth <item> Change authorizations for an item\n";
print "\tdelete <item> Delete an iten\n";
print "\tpasswd Rotate the password for your private key\n";
print "\tlist List all items\n";
print "\ta Print advanced help\n";
print "\texit Graceful exit\n";
return $environment;
}
sub printAdvancedMenu {
my $environment = $_[0] or die "Print advanced menu called without environment\n";
print "\nadvanced menu:\n";
print "\tp Print the environment\n";
print "\tlm List the keys in the master ring\n";
print "\tlh List the keys in your private ring\n";
print "\tg Generate a private keypair\n";
print "\ts Submit your public key to the master ring\n";
print "\te Read the auth file from disk\n";
print "\tw Write the auth file to disk\n";
print "\tc Create dummy file for password validation\n";
print "\tt Toggle verbose mode\n";
print "\thm Print username to hex key mappings for master database\n";
print "\thp Print username to hex key mappings for private database\n";
print "\td Delete all files and start over.\n";
print "\tfc Check to make sure all necessary files and directories exist.\n";
print "\tr Print the authorizations database\n";
print "\tl Lock the application\n";
print "\tu Unlock the application\n";
print "\tcl Check if the application is locked\n";
print "\twh Show who has the application locked\n";
print "\tf Force unlock from another user.\n";
print "\tch Change your login name\n";
print "\tlogin Authenticate\n";
print "\tlogout De-authenticate\n";
print "\tfull Get full raw item\n";
return $environment;
}
#this subroutine allows a user to change their login name to simulate multiple
#users in the environment. It's generally used for debug and testing.
sub changeLoginName {
my $environment = $_[0] or die "changeLoginName called without environment\n";
print "This feature is disabled.\n";
return $environment;
my $userResponse;
print "Enter your new login name: ";
$userResponse = Term::ReadKey::ReadLine(0);
chomp($userResponse);
if($userResponse eq $environment->{'rootKeyName'}) {
print "Cannot change to pw7-rootcert.\n";
return $environment;
} else {
pw7::printDebug($environment, "Not trying to use rootcert\n");
}
if(length($userResponse) < 1) {
print "User name must be at least one character long.\n";
return $environment;
} else {
pw7::printDebug($environment, "User name is at least one character long\n");
}
if($userResponse=~/^[a-zA-Z0-9_-]+$/) {
pw7::printDebug($environment, "User response passed regex validation\n");
} else {
print "Login name failed regex data validation.\n";
$environment->{'prompt'} = $environment->{'loginName'} . "\@pw7> ";
return $environment;
}
pw7::printDebug($environment, "new login name: $userResponse\n");
$environment = pw7::logMeOut($environment);
$environment = undef;
undef $environment;
my $env;
$env->{'version'} = $version;
$env->{'loginName'} = $userResponse;
$env = pw7::init($env);
$env = pw7::initUser($env);
$env = pw7::logMeIn($env, "Password: ");
return $env;
}
#this subroutine returns the username of the person who has the appllication
#locked.
sub populateLockInfo {
my $environment = $_[0] or die "Who has locked called without environment.\n";
pw7::printDebug($environment, "Who has locked called.\n");
delete $environment->{'lockPID'};
delete $environment->{'lockedBy'};
delete $environment->{'lockedByCurrent'};
if ($environment->{'isLocked'}) {
my @glob = glob($environment->{'lockFilePath'} . "LOCK-*");
if (scalar(@glob) == 1) {
pw7::printDebug($environment, "Somebody has the application locked\n");
my $culprit = $glob[0];
pw7::printDebug($environment, "culprit before: $culprit\n");
$culprit=~s/LOCK\-(\S+)\-(\S+)//;
pw7::printDebug($environment, "Application locked by $1 with PID: $2\n");
$environment->{'lockPID'} = $2;
$environment->{'lockedBy'} = $1;
$environment = pw7::checkAndCleanStaleLock($environment);
return $environment;
if (-f $environment->{'lockFilePath'} . "LOCK-" . $environment->{'loginName'} . "-$$") {
$environment->{'lockedByCurrent'} = 'true';
} else {
$environment->{'lockedByCurrent'} = 'false';
}
} else {
print "Found a lock file that is not equal to 1. This should never happen.\n";
}
} else {
pw7::printDebug($environment, "Application is not locked.\n");
return $environment;
}
return $environment;
}
#this subroutine will return 1 if the application is locked, 0 if it is not.
sub checkLocked {
my $environment = $_[0] or die "Check locked called without environment.\n";
pw7::printDebug($environment, "Check locked called.\n");
delete $environment->{'lockFile'};
delete $environment->{'isLocked'};
my @glob = glob($environment->{'lockFilePath'} . "LOCK-*");
if (scalar(@glob) == 0) {
pw7::printDebug($environment, "Didn't find a lock file.\n");
$environment->{'isLocked'} = '0';
} elsif (scalar(@glob) > 1) {
die "Found multiple lock files. This should never happen.\n";
} elsif (scalar(@glob) == 1) {
pw7::printDebug($environment, "Found a lock file.\n");
$environment->{'lockFile'} = $glob[0];
$environment->{'isLocked'} = '1';
$environment=pw7::populateLockInfo($environment);
} else {
die "Unknown error when checking if applicaiton is locked.\n";
}
return $environment;
}
#this subroutine will lock the application. It can be called with 'l' from the
#main menu. It's also called from a few code blocks.
sub lockApplication {
my $environment = $_[0] or die "Lock application called without environment.\n";
pw7::printDebug($environment, "Lock application called.\n");
$environment = pw7::doFileAndPermissionChecks($environment);
$environment = pw7::checkLocked($environment);
if ($environment->{'isLocked'}) {
print "Application is already locked.\n";
} else {
pw7::printDebug($environment, "Creating: ". $environment->{'lockFilePath'} . "LOCK-" . $environment->{'loginName'} . "-$$\n");
my $fileName = $environment->{'lockFilePath'} . "LOCK-" . $environment->{'loginName'} . "-$$";
pw7::checkIfFileExistsAndCreateItIfItDoesnt($environment, $fileName);
$environment = pw7::checkLocked($environment);
pw7::printDebug($environment, "Successfully locked.\n");
}
return $environment;
}
#this unlocks the application. It can be called with 'u' from the main
#menu and is also called from some code blocks.
sub unlockApplication {
my $environment = $_[0] or die "Unlock application called without environment.\n";
pw7::printDebug($environment, "Unlock application called.\n");
if (-f $environment->{'lockFilePath'} . "LOCK-" . $environment->{'loginName'} . "-$$") {
pw7::printDebug($environment, "Unlocking Application.\n");
$environment->{'fileToDelete'} = $environment->{'lockFilePath'} . "LOCK-" . $environment->{'loginName'} . "-$$";
pw7::checkIfFileExistsAndDeleteItIfItDoes($environment);
delete $environment->{'lockPID'};
delete $environment->{'lockedBy'};
delete $environment->{'lockFile'};
delete $environment->{'lockedByCurrent'};
$environment->{'isLocked'} = '0';
return $environment;
pw7::printDebug($environment, "Application successfully unlocked.\n");
} else {
print "You have the application locked, but not with process ID $$ (you can try force unlock with 'f').\n";
return $environment;
}
return $environment;
}
#this will force an unlock of the application. it can only be called with 'f'
#from the main menu
sub forceUnlock {
my $environment = $_[0] or die "Toggle verbose called without environment.\n";
pw7::printDebug($environment, "Force unlock called.\n");
$environment = pw7::checkLocked($environment);
if ($environment->{'isLocked'}) {
my @glob = glob($environment->{'lockFilePath'} . "LOCK-*");
my $lockfile = $glob[0];
$environment->{'fileToDelete'}=$lockfile;
if(&yesNo($environment, "Are you sure you want to force an application unlock? This could cause data corruption.")) {
pw7::checkIfFileExistsAndDeleteItIfItDoes($environment);
$environment->{'isLocked'} = '0';
delete $environment->{'lockFile'};
delete $environment->{'lockPID'};
delete $environment->{'lockedBy'};
delete $environment->{'lockedByCurrent'};
pw7::printDebug($environment, "Force unlock was successful.\n");
} else {
print "Force unlock aborted.\n";
}
} else {
print "The application is not locked.\n";
}
return $environment;
}
#this sub will toggle verbose logging on and off. It's toggled with 't' from the main menu.
sub toggleVerbose {
my $environment = $_[0] or die "Toggle verbose called without environment.\n";
if($environment->{'verbose'} eq 'false') {
print "Verbose mode enabled.\n";
$environment->{'verbose'} = 'true' ;
} elsif ($environment->{'verbose'} eq 'true') {
print "Verbose mode disabled.\n";
$environment->{'verbose'} = 'false';
}
}
#this will print the string passed to it if debug is enabled.
sub printDebug {
my $environment = $_[0] or die "Toggle verbose called without environmen\n";
my $message = $_[1] or die "Print debug called without environment\n";
if ( defined $environment->{'verbose'}) {
if($environment->{'verbose'} eq 'true') {
print "DEBUG: " . $message;
} else {
}
} else {
}
}
#this subroutine will change the authorizations for a particular item
sub authItem {
my $environment = $_[0] or die "Auth item called without environment.\n";
my $itemName = $environment->{'itemName'};
if (!$itemName) {
print "Pass an item name as a parameter to this command.\n";
return $environment;
} else {
}
my $itemPath = $environment->{'itemsPath'} . $itemName;
if ($environment->{'userFullyAuthenticated'} eq '0') {
print "Login first (login) bleh\n";
return $environment;
}
if(!&checkIfItemIsInList($environment, $itemName)) {
print "Item $itemName does not exist.\n";
return $environment;
} elsif (!&checkIfIAmAuthorizedToAnItem($environment,$itemName)) {
print "You are not authorized to item $itemName\n";
return $environment;
} elsif (&checkIfIAmAuthorizedToAnItem($environment,$itemName)) {
my $decryptedData = $environment->{'pgp'}->decrypt(Filename => "$itemPath",Passphrase => $environment->{'passphrase'});
my @metadata = split(/\n/, $decryptedData);
my $authorizations = $metadata[0];
my @currentAuthorizations = split(/\, /, $authorizations);
pw7::printDebug($environment, "authorizations from file: @currentAuthorizations\n");
$environment->{'authorizationsFromFile'} = \@currentAuthorizations;
my $password = $metadata[1];
if($password) {
$environment->{'password'}=$password;
$environment->{'itemName'}=$itemName;
pw7::printDebug($environment, "Successfully decrypted file: $itemPath.\n");
$environment = pw7::setAuth($environment);
@currentAuthorizations = @{$environment->{'decryptedauthorizationDataStucture'}{$itemName}};
$password = join(',', @currentAuthorizations);
my $hexid;
my @authorizedkeys;
foreach my $userName (@currentAuthorizations) {
pw7::printDebug($environment, "checking for hex id: $userName\n");
$hexid = $environment->{'usertohexid-master'}{$userName} or die "Security violation.\n";
push (@authorizedkeys, $hexid);
}
if ($environment->{'itemName'} eq 'pw7-appauth') {
pw7::printDebug($environment, "setting authorization on application auth, changing password to string of hex keys.\n");
$password = join(', ', @authorizedkeys);
$environment->{'password'}=$password;
$environment->{'authorizationsValid'} = '1';
} else {
pw7::printDebug($environment, "not setting authorization on application auth.\n");
$environment = pw7::validateAuthorizations($environment);
}
if ($environment->{'authorizationsValid'} eq '1') {
$environment->{'timestamp'} = localtime(time);
$environment = pw7::encryptData($environment);
delete $environment->{'timestamp'};
$environment->{'writePath'} = $environment->{'itemsPath'};
$environment = pw7::writeEncryptedDataToDisk($environment);
pw7::writeAuthorizationsTableToDisk($environment);
$environment = pw7::readAuthFileFromDisk($environment);
delete $environment->{'password'};
undef $password;
return $environment;
} else {
print "Authorizations could not be validated.\n";
}
} else {
print "Unable to decrypt file: $itemPath. This should never happen.\n";
}
}
return $environment;
}
sub validateAuthorizations {
my $environment = $_[0] or die "Auth item called without environment.\n";
my $itemName = $environment->{'itemName'};
$environment->{'authorizationsValid'} = '1';
my @authorizationsToCheck = @{$environment->{'decryptedauthorizationDataStucture'}{$itemName}};
my $itemPath = $environment->{'itemsPath'} . '/pw7-appauth';
$environment = pw7::createPGPHandler($environment);
my $decryptedData = $environment->{'pgp'}->decrypt(Filename => "$itemPath",Passphrase => $environment->{'passphrase'});
my @metadata = split(/\n/, $decryptedData);
my $passwordString = $metadata[1];
my @validKeys = split (', ',$passwordString);
foreach my $userName (@authorizationsToCheck) {
my $hexid = $environment->{'usertohexid-master'}{$userName} or die "Security violation.\n";
if(grep { $_ eq $hexid } @validKeys) {
pw7::printDebug($environment, "The hexid $hexid is authorized to use the application.\n");
} else {
die "The hexid $hexid is not authorized to use the application.\n";
$environment->{'authorizationsValid'} = '1';
}
}
return $environment;
}
#this subroutine will prompt for N/y in the form of a question with the string
#passed to it. it will return 1 if the response is affirmative, 0 if it is not
sub yesNo {
my $environment = $_[0] or die "yesNo called without environment\n";
my $question = $_[1] or die "yesNo called without a question to ask\n";
delete $environment->{'userResponse'};
my $userResponse = "";
while (($userResponse ne 'y') && ($userResponse ne 'n')) {
print "$question (y/n)? ";
$userResponse = Term::ReadKey::ReadLine(0);
chomp($userResponse);
if ($userResponse eq "") {
$environment->{'prompt'} = $environment->{'loginName'}. "\@pw7> ";
return 0;
}
elsif (($userResponse ne "y") && ($userResponse ne "n")) {
print "\nEnter 'y' or 'n'\n";
print "$question ";
$userResponse = Term::ReadKey::ReadLine(0);
}
}
$environment->{'prompt'} = $environment->{'loginName'}. "\@pw7> ";
if($userResponse eq 'y') {
return 1;
} elsif ($userResponse eq 'n') {
return 0;
}
return $environment;
}
#this will create a dummy encrypted file. It's used to test authentication for
#the user. It's required to login.
sub createDummyEncryptedFile {
my $environment = $_[0] or die "Create dummy encrypted file called without environmen\n";
my $itemName = "dummyFile";
$environment->{'password'}="1337";
my $dummyFile = $environment->{'homeKeyPath'} . "/" . $itemName;
pw7::printDebug($environment, "Dummy file: ". "$dummyFile\n");
if(-f $dummyFile) {
print "You already have a dummy file.\n";
return;
}
$environment->{'ringIdentifier'} = "private";
$environment = pw7::doIhaveAHexKeyMapping($environment);
if(!$environment->{'hexKeyMapping'}) {
print "Generate a keypair first (g).\n";
return;
}
$environment->{'ringIdentifier'} = "master";
$environment = pw7::doIhaveAHexKeyMapping($environment);
if(!$environment->{'hexKeyMapping'}) {
print "Submit your key to the ring first (s).\n";
return;
}
$environment->{'itemName'} = $itemName;
$environment->{'timestamp'} = localtime(time);
$environment = pw7::encryptData($environment);
delete $environment->{'timestamp'};
$environment->{'writePath'} = $environment->{'homeKeyPath'};
$environment = pw7::writeEncryptedDataToDisk($environment);
pw7::printDebug($environment, "Dummy file created.\n");
}
#this is to rotate the value of a password. it tests to make sure the user can
#encrypt the file before it's re-encrypted, preventing an auth file hack.
sub setItem {
my $environment = $_[0] or die "Get item called without environmen\n";
my $itemName = $environment->{'itemName'} or die "Set item called without environment\n";
my $itemPath = $environment->{'itemsPath'} . "/" . $itemName;
pw7::printDebug($environment, "set item called with item path: $itemPath\n");
if ($environment->{'userFullyAuthenticated'} eq '0') {
print "Login first (login).\n";
return $environment;
} else {
}
if ($environment->{'itemName'} eq 'pw7-appauth') {
print "This is a special item that is set by the auth command.\n";
return $environment;
}
if(!&checkIfItemIsInList($environment, $itemName)) {
print "Item $itemName does not exist.\n";
return $environment;
} elsif (!&checkIfIAmAuthorizedToAnItem($environment,$itemName)) {
print "You are not authorized to item $itemName\n";
return $environment;
} elsif (&checkIfIAmAuthorizedToAnItem($environment,$itemName)) {
pw7::printDebug($environment, "You are authorized to this item.\n");
if ($environment->{'userFullyAuthenticated'} eq '1') {
$environment->{'isPasswordRotating'} = '1';
$environment= pw7::getPassword($environment);
$environment->{'itemName'} = $itemName;
my $pswd = $environment->{'pgp'}->decrypt(Filename => "$itemPath",Passphrase => $environment->{'passphrase'});
my @metadata = split(/\n/, $pswd);
my $authorizations = $metadata[0];
my $password = $metadata[1];
$environment->{'timestamp'} = $metadata[3];
if (!$pswd) {
pw7::printDebug($environment, "Failed decrypting old file. This should never happen.\n");
} else {
pw7::printDebug($environment, "Successfully decrypted old file\n");
$environment = pw7::encryptData($environment);
delete $environment->{'timestamp'};
$environment->{'itemName'} = $itemName;
$environment->{'writePath'} = $environment->{'itemsPath'};
$environment = pw7::writeEncryptedDataToDisk($environment);
}
pw7::printDebug($environment, "changing password from $pswd\n");
} else {
die "Unknown passphrasevalidated value, this should never happen\n";
}
} else {
die "Unknown error setting item\n";
}
return $environment;
}
#this sub will get the value of a particular item name.
sub getItem {
my $environment = $_[0] or die "Get item called without environment\n";
pw7::printDebug($environment, "get item called with itemspath as: $environment->{'itemPath'}\n");
pw7::printDebug($environment, "get item called with fromLoginIndicator: $environment->{'fromLoginIndicator'}\n");
my $fromLoginIndicator = $environment->{'fromLoginIndicator'}; # "Get item called without from login indicator\n";
my $itemsPath = $environment->{'itemPath'} or die "Get item called without items path\n";
pw7::printDebug($environment, "get item called with login indicator: $fromLoginIndicator\n");
my $itemPath;
my $itemName;
if ($environment->{'userFullyAuthenticated'} eq '0' && $fromLoginIndicator == 0) {
print "Login first (login).\n";
return;
} elsif ($fromLoginIndicator == 1) {
pw7::printDebug($environment, "Called with fromLoginIndicator: $fromLoginIndicator.\n");
}
pw7::printDebug($environment, "from login indicator: $fromLoginIndicator\n");
pw7::printDebug($environment, "get item canned with items path: ". $itemsPath . "\n");
if ($environment->{'itemName'}) {
$itemName = $environment->{'itemName'} or die "Get item called without item name\n";
} else {
print "Pass item name in as a parameter.\n";
return;
}
if ($itemsPath eq $environment->{'itemsPath'}) {
$itemPath = $itemsPath . $itemName;
pw7::printDebug($environment, "items path: $itemsPath\n");
pw7::printDebug($environment, "item name : $itemName\n");
if(!&checkIfItemIsInList($environment, $itemName)) {
print "Item $itemName does not exist.\n";
return;
}
if (!&checkIfIAmAuthorizedToAnItem($environment,$itemName)) {
print "You are not authorized to this item.\n";
return;
}
} elsif ($itemsPath = $environment->{'homeKeyPath'}) {
$itemPath = $itemsPath . "/" . $itemName;
pw7::printDebug($environment, "items path: $itemsPath\n");
} else {
pw7::printDebug($environment, "Items path not valid. This should never happen.\n");
}
pw7::printDebug($environment, "Item path after selected: $itemPath\n");
pw7::printDebug($environment, "Trying to decrypt $itemPath with password $environment->{'passphrase'}\n");
$environment = &createPGPHandler($environment);
my $decryptedData = $environment->{'pgp'}->decrypt(Filename => "$itemPath",Passphrase => $environment->{'passphrase'});
if ($environment->{'pgp'}->errstr =~ /unlock failed/) {
pw7::printDebug($environment, "PGP error string: " . $environment->{'pgp'}->errstr . "\n");
pw7::printDebug($environment, "Login failed.\n");
} elsif ($environment->{'pgp'}->errstr =~ /No Signature/) { #this is the result of a successful decryption
pw7::printDebug($environment, "PGP error string: " . $environment->{'pgp'}->errstr . "\n");
if($fromLoginIndicator == "0") {
my @metadata = split(/\n/, $decryptedData);
my $authorizations = $metadata[0];
my $password = $metadata[1];
my $timestamp = $metadata[3];
if($environment->{'getFull'} eq '1') {
print "$decryptedData\n";
$environment->{'getFull'} = '0';
} else {
print "$password\n";
}
pw7::printDebug($environment, "authorizations: $authorizations\n");
} else {
pw7::printDebug($environment, "Not echoing decrypted text to screen because decrypt came from login. \n");
pw7::printDebug($environment, "Login successful.\n");
}
if ($environment->{'itemName'} eq 'dummyFile') {
pw7::printDebug($environment, "Just unlocked dummy file.\n");
$environment->{'passphraseValidated'} = '1';
} else {
pw7::printDebug($environment, "Didn't unlock dummy file.\n");
}
} elsif ($environment->{'pgp'}->errstr =~ /No such file or directory/) {
die "PGP error string No such file or directory incurred. This should never happen.\n";
} elsif ($environment->{'pgp'}->errstr =~ /Need passphrase to unlock secret key/) {
} elsif ($environment->{'pgp'}->errstr =~ /Can't find a secret key to decrypt message/) {
print "Your private key can't decrypt this item.\n";
return;
} elsif (!$environment->{'pgp'}->errstr) {
print "Successfully decrypted file.\n";
if ($environment->{'itemName'} eq 'dummyFile') {
$environment->{'passphraseValidated'} = 1;
} else {
print "Didn't unlock dummy file\n";
}
}
else {
die "Unexpected PGP error string: " . $environment->{'pgp'}->errstr . "\n";
}
}
#this will set the user's passphrase for the private key.
sub setMyPassphrase {
my $environment = $_[0] or die "Set my passphrase called without environment\n";
my $passwordmatched="0";
my $passphrase="";
my $passphraserepeat="";
Term::ReadKey::ReadMode('noecho');
while ( $passwordmatched eq "0" ) {
if ($environment->{'isPasswordRotating'} eq '1') {
print 'enter new passphrase: ';
} else {
print 'enter passphrase: ';
}