-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpa
More file actions
executable file
·1253 lines (1052 loc) · 40.7 KB
/
Copy pathpa
File metadata and controls
executable file
·1253 lines (1052 loc) · 40.7 KB
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
#!/bin/sh
#
# pa - a simple password manager
# Cross-platform support: macOS, Linux, Windows (WSL/MSYS2/Cygwin)
# Version information (updated during installation)
PA_VERSION="__VERSION__"
PA_RELEASE_DATE="__RELEASE_DATE__"
PA_COMMIT="__COMMIT__"
# Capture git information early, before directory changes
# This is only used when running from source (placeholders not replaced)
if [ "$PA_VERSION" = "__VERSION__" ] && command -v git >/dev/null 2>&1; then
# Get script directory
script_dir="$(cd "$(dirname "$0")" && pwd)"
if [ -d "$script_dir/.git" ]; then
# Change to script directory temporarily
original_cwd="$(pwd)"
cd "$script_dir"
PA_DEV_TAG=$(git describe --tags 2>/dev/null || git describe --always 2>/dev/null || echo "no-tag")
PA_DEV_COMMIT=$(git rev-parse --short HEAD 2>/dev/null || echo "no-commit")
PA_DEV_STATUS=$(git status --porcelain 2>/dev/null)
PA_DEV_DATE=$(git log -1 --format=%cd --date=short 2>/dev/null || echo "unknown")
# Return to original directory
cd "$original_cwd"
fi
fi
# OS detection and credential storage functions
detect_os() {
case "$(uname -s)" in
Darwin*) echo "macos" ;;
Linux*)
if grep -q Microsoft /proc/version 2>/dev/null; then
echo "wsl"
else
echo "linux"
fi
;;
CYGWIN*|MINGW*|MSYS*) echo "windows" ;;
*) echo "unknown" ;;
esac
}
# Store credential in OS-specific credential store
store_credential() {
local service="$1"
local username="$2"
local password="$3"
local os_type="$4"
case "$os_type" in
"windows"|"wsl")
# Use Windows Credential Manager via cmdkey
if command -v powershell.exe >/dev/null 2>&1; then
printf '%s' "$password" | powershell.exe -Command "
\$securePassword = ConvertTo-SecureString -String (Read-Host) -AsPlainText -Force;
\$credential = New-Object System.Management.Automation.PSCredential('$username', \$securePassword);
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime] | Out-Null;
\$vault = New-Object Windows.Security.Credentials.PasswordVault;
try { \$vault.Remove(\$vault.Retrieve('$service', '$username')) } catch {};
\$vault.Add((New-Object Windows.Security.Credentials.PasswordCredential('$service', '$username', '$password')))
" 2>/dev/null
elif command -v cmdkey.exe >/dev/null 2>&1; then
printf '%s' "$password" | cmdkey.exe /generic:"$service" /user:"$username" /pass 2>/dev/null
else
return 1
fi
;;
"linux")
# Use secret-tool (libsecret) on Linux
if command -v secret-tool >/dev/null 2>&1; then
printf '%s' "$password" | secret-tool store --label="pa: $service" service "$service" username "$username" 2>/dev/null
else
return 1
fi
;;
"macos")
# Use macOS Keychain
if command -v security >/dev/null 2>&1; then
security delete-generic-password -s "$service" -a "$username" 2>/dev/null || true
printf '%s' "$password" | security add-generic-password -s "$service" -a "$username" -w 2>/dev/null
else
return 1
fi
;;
*)
return 1
;;
esac
}
# Retrieve credential from OS-specific credential store
retrieve_credential() {
local service="$1"
local username="$2"
local os_type="$3"
case "$os_type" in
"windows"|"wsl")
if command -v powershell.exe >/dev/null 2>&1; then
powershell.exe -Command "
[Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime] | Out-Null;
\$vault = New-Object Windows.Security.Credentials.PasswordVault;
try {
\$credential = \$vault.Retrieve('$service', '$username');
\$credential.RetrievePassword();
Write-Output \$credential.Password
} catch { exit 1 }
" 2>/dev/null
else
return 1
fi
;;
"linux")
if command -v secret-tool >/dev/null 2>&1; then
secret-tool lookup service "$service" username "$username" 2>/dev/null
else
return 1
fi
;;
"macos")
if command -v security >/dev/null 2>&1; then
security find-generic-password -s "$service" -a "$username" -w 2>/dev/null
else
return 1
fi
;;
*)
return 1
;;
esac
}
# ============================================================================
# SECURE CACHE MANAGEMENT FUNCTIONS
# ============================================================================
# Initialize cache configuration and directories
cache_init() {
# Cache configuration
PA_CACHE_TIMEOUT="${PA_CACHE_TIMEOUT:-900}" # Default 15 minutes (900 seconds)
PA_CACHE_ENABLED="${PA_DISABLE_CACHE:+false}"
PA_CACHE_ENABLED="${PA_CACHE_ENABLED:-true}"
# Skip cache initialization if disabled
[ "$PA_CACHE_ENABLED" = "false" ] && return 0
# Determine secure cache directory based on OS
local os_type=$(detect_os)
case "$os_type" in
"linux")
# Prefer /dev/shm (in-memory) on Linux, fallback to /tmp
if [ -w /dev/shm ]; then
PA_CACHE_BASE_DIR="/dev/shm"
else
PA_CACHE_BASE_DIR="/tmp"
fi
;;
"macos"|"windows"|"wsl"|*)
PA_CACHE_BASE_DIR="${TMPDIR:-/tmp}"
;;
esac
# Create user-specific cache directory
PA_CACHE_DIR="$PA_CACHE_BASE_DIR/pa-cache-$USER"
# Create cache directory with secure permissions
if [ ! -d "$PA_CACHE_DIR" ]; then
mkdir -p "$PA_CACHE_DIR" 2>/dev/null || return 1
chmod 700 "$PA_CACHE_DIR" 2>/dev/null || return 1
fi
return 0
}
# Generate cache key from file path
cache_key() {
local file="$1"
local abs_path
# Get absolute path for consistent hashing
abs_path=$(cd "$(dirname "$file")" && pwd)/$(basename "$file") 2>/dev/null || echo "$file"
# Generate SHA-256 hash if available, fallback to simple hash
if command -v sha256sum >/dev/null 2>&1; then
printf '%s' "$abs_path" | sha256sum | cut -d' ' -f1
elif command -v shasum >/dev/null 2>&1; then
printf '%s' "$abs_path" | shasum -a 256 | cut -d' ' -f1
else
# Simple fallback hash for systems without sha256
printf '%s' "$abs_path" | od -An -tx1 | tr -d ' \n' | head -c 64
fi
}
# Get current timestamp
cache_timestamp() {
date +%s 2>/dev/null || echo "0"
}
# Check if cache entry is valid (not expired)
cache_is_valid() {
local cache_file="$1"
local meta_file="${cache_file%.data}.meta"
local current_time=$(cache_timestamp)
local cache_time
# Check if both cache and meta files exist
[ -f "$cache_file" ] && [ -f "$meta_file" ] || return 1
# Read timestamp from meta file
cache_time=$(head -n 1 "$meta_file" 2>/dev/null) || return 1
# Validate timestamp format
case "$cache_time" in
''|*[!0-9]*) return 1 ;;
esac
# Check if cache has expired
[ $((current_time - cache_time)) -lt "$PA_CACHE_TIMEOUT" ]
}
# Secure file locking (if flock is available)
cache_lock() {
local lock_file="$1"
local timeout="${2:-10}"
# Create lock file if it doesn't exist
touch "$lock_file" 2>/dev/null || return 1
# Use flock if available, otherwise skip locking
if command -v flock >/dev/null 2>&1; then
flock -w "$timeout" "$lock_file" true
else
return 0
fi
}
# Release file lock
cache_unlock() {
local lock_file="$1"
# Remove lock file if it exists
[ -f "$lock_file" ] && rm -f "$lock_file" 2>/dev/null
return 0
}
# Get data from cache
cache_get() {
local file="$1"
local output_mode="${2:-stdout}" # stdout or variable
# Skip if cache is disabled
[ "$PA_CACHE_ENABLED" = "false" ] && return 1
# Initialize cache if needed
cache_init || return 1
# Generate cache key and paths
local key=$(cache_key "$file")
local cache_file="$PA_CACHE_DIR/cache-$key.data"
local lock_file="$PA_CACHE_DIR/cache-$key.lock"
# Acquire lock
cache_lock "$lock_file" || return 1
# Check if cache is valid
if cache_is_valid "$cache_file"; then
# Cache hit - output data based on mode
if [ "$output_mode" = "stdout" ]; then
cat "$cache_file" 2>/dev/null
else
# Return data in variable (caller must use command substitution)
cat "$cache_file" 2>/dev/null
fi
cache_unlock "$lock_file"
return 0
fi
# Cache miss or expired
cache_unlock "$lock_file"
return 1
}
# Store data in cache
cache_set() {
local file="$1"
local data="$2"
# Skip if cache is disabled
[ "$PA_CACHE_ENABLED" = "false" ] && return 1
# Initialize cache if needed
cache_init || return 1
# Generate cache key and paths
local key=$(cache_key "$file")
local cache_file="$PA_CACHE_DIR/cache-$key.data"
local meta_file="$PA_CACHE_DIR/cache-$key.meta"
local lock_file="$PA_CACHE_DIR/cache-$key.lock"
# Acquire lock
cache_lock "$lock_file" || return 1
# Create temporary files for atomic write
local tmp_cache_file="$PA_CACHE_DIR/tmp-$key.data.$$"
local tmp_meta_file="$PA_CACHE_DIR/tmp-$key.meta.$$"
# Write data to temporary file
if [ -n "$data" ]; then
printf '%s' "$data" > "$tmp_cache_file" 2>/dev/null || {
cache_unlock "$lock_file"
rm -f "$tmp_cache_file" "$tmp_meta_file" 2>/dev/null
return 1
}
else
# If data is empty, read from stdin
cat > "$tmp_cache_file" 2>/dev/null || {
cache_unlock "$lock_file"
rm -f "$tmp_cache_file" "$tmp_meta_file" 2>/dev/null
return 1
}
fi
# Write metadata (timestamp, file path)
{
cache_timestamp
printf '%s\n' "$file"
} > "$tmp_meta_file" 2>/dev/null || {
cache_unlock "$lock_file"
rm -f "$tmp_cache_file" "$tmp_meta_file" 2>/dev/null
return 1
}
# Set secure permissions
chmod 600 "$tmp_cache_file" "$tmp_meta_file" 2>/dev/null || {
cache_unlock "$lock_file"
rm -f "$tmp_cache_file" "$tmp_meta_file" 2>/dev/null
return 1
}
# Atomic move to final location
mv "$tmp_cache_file" "$cache_file" 2>/dev/null &&
mv "$tmp_meta_file" "$meta_file" 2>/dev/null || {
cache_unlock "$lock_file"
rm -f "$tmp_cache_file" "$tmp_meta_file" "$cache_file" "$meta_file" 2>/dev/null
return 1
}
# Release lock
cache_unlock "$lock_file"
return 0
}
# Clear specific cache entry
cache_clear() {
local file="$1"
# Skip if cache is disabled
[ "$PA_CACHE_ENABLED" = "false" ] && return 0
# Initialize cache if needed
cache_init || return 0
# Generate cache key and paths
local key=$(cache_key "$file")
local cache_file="$PA_CACHE_DIR/cache-$key.data"
local meta_file="$PA_CACHE_DIR/cache-$key.meta"
local lock_file="$PA_CACHE_DIR/cache-$key.lock"
# Acquire lock
cache_lock "$lock_file" || return 0
# Securely remove cache files
if [ -f "$cache_file" ]; then
# Try to overwrite with zeros first (more secure)
if command -v dd >/dev/null 2>&1; then
dd if=/dev/zero of="$cache_file" bs=1k count=1 2>/dev/null || true
fi
rm -f "$cache_file" 2>/dev/null
fi
# Remove metadata file
[ -f "$meta_file" ] && rm -f "$meta_file" 2>/dev/null
# Release and remove lock
cache_unlock "$lock_file"
rm -f "$lock_file" 2>/dev/null
return 0
}
# Clear all cache entries
cache_clear_all() {
# Skip if cache is disabled
[ "$PA_CACHE_ENABLED" = "false" ] && return 0
# Initialize cache if needed
cache_init || return 0
# Create global lock
local global_lock="$PA_CACHE_DIR/global.lock"
cache_lock "$global_lock" || return 0
# Securely remove all cache files
if [ -d "$PA_CACHE_DIR" ]; then
# Find and remove all cache files
find "$PA_CACHE_DIR" -type f -name "cache-*.data" 2>/dev/null | while read -r cache_file; do
# Try to overwrite with zeros first (more secure)
if command -v dd >/dev/null 2>&1; then
dd if=/dev/zero of="$cache_file" bs=1k count=1 2>/dev/null || true
fi
rm -f "$cache_file" 2>/dev/null
done
# Remove all metadata and lock files
find "$PA_CACHE_DIR" -type f -name "cache-*.meta" -o -name "cache-*.lock" 2>/dev/null | xargs rm -f 2>/dev/null || true
fi
# Release global lock
cache_unlock "$global_lock"
rm -f "$global_lock" 2>/dev/null
return 0
}
# Clean up expired cache entries
cache_cleanup_expired() {
# Skip if cache is disabled
[ "$PA_CACHE_ENABLED" = "false" ] && return 0
# Initialize cache if needed
cache_init || return 0
# Create global lock for cleanup
local global_lock="$PA_CACHE_DIR/cleanup.lock"
cache_lock "$global_lock" 5 || return 0 # Short timeout for cleanup
local current_time=$(cache_timestamp)
local cleaned_count=0
# Find all cache metadata files
if [ -d "$PA_CACHE_DIR" ]; then
find "$PA_CACHE_DIR" -type f -name "cache-*.meta" 2>/dev/null | while read -r meta_file; do
# Extract cache key from meta file name
local key=$(basename "$meta_file" .meta | sed 's/^cache-//')
local cache_file="$PA_CACHE_DIR/cache-$key.data"
local lock_file="$PA_CACHE_DIR/cache-$key.lock"
# Skip if we can't acquire individual lock quickly
cache_lock "$lock_file" 1 || continue
# Check if entry is expired
if ! cache_is_valid "$cache_file"; then
# Remove expired entry
if [ -f "$cache_file" ]; then
# Secure deletion
if command -v dd >/dev/null 2>&1; then
dd if=/dev/zero of="$cache_file" bs=1k count=1 2>/dev/null || true
fi
rm -f "$cache_file" 2>/dev/null
fi
[ -f "$meta_file" ] && rm -f "$meta_file" 2>/dev/null
cleaned_count=$((cleaned_count + 1))
fi
cache_unlock "$lock_file"
rm -f "$lock_file" 2>/dev/null
done
fi
# Release global lock
cache_unlock "$global_lock"
rm -f "$global_lock" 2>/dev/null
return 0
}
# Get cache statistics
cache_stats() {
# Skip if cache is disabled
[ "$PA_CACHE_ENABLED" = "false" ] && {
printf '%s\n' "Cache: disabled"
return 0
}
# Initialize cache if needed
cache_init || {
printf '%s\n' "Cache: initialization failed"
return 1
}
local total_entries=0
local valid_entries=0
local expired_entries=0
local total_size=0
# Count cache entries
if [ -d "$PA_CACHE_DIR" ]; then
# Count total entries
total_entries=$(find "$PA_CACHE_DIR" -type f -name "cache-*.data" 2>/dev/null | wc -l)
# Analyze each entry
find "$PA_CACHE_DIR" -type f -name "cache-*.data" 2>/dev/null | while read -r cache_file; do
if cache_is_valid "$cache_file"; then
valid_entries=$((valid_entries + 1))
else
expired_entries=$((expired_entries + 1))
fi
# Calculate size if possible
if [ -f "$cache_file" ]; then
local file_size=$(wc -c < "$cache_file" 2>/dev/null || echo "0")
total_size=$((total_size + file_size))
fi
done
fi
# Display statistics
printf '%s\n' "Cache Statistics:"
printf '%s\n' " Status: enabled"
printf '%s\n' " Directory: $PA_CACHE_DIR"
printf '%s\n' " Timeout: ${PA_CACHE_TIMEOUT}s ($(($PA_CACHE_TIMEOUT / 60))m)"
printf '%s\n' " Total entries: $total_entries"
printf '%s\n' " Valid entries: $valid_entries"
printf '%s\n' " Expired entries: $expired_entries"
printf '%s\n' " Total size: ${total_size} bytes"
return 0
}
# Decrypt file with automatic passphrase handling and caching
decrypt_with_key() {
local file="$1"
local os_type=$(detect_os)
local decrypted_data
local cache_hit=false
# Try cache first (only for Secure Enclave or hardware keys)
if [ "$PA_CACHE_ENABLED" != "false" ] && cache_uses_secure_hardware; then
if decrypted_data=$(cache_get "$file" 2>/dev/null); then
printf '%s' "$decrypted_data"
cache_hit=true
return 0
fi
fi
# Cache miss or cache disabled - proceed with actual decryption
# First try without passphrase (for regular keys or hardware keys)
if decrypted_data=$($age --decrypt -i "$identities_file" "$file" 2>/dev/null); then
# Store in cache if using secure hardware and cache is enabled
if [ "$PA_CACHE_ENABLED" != "false" ] && [ "$cache_hit" = "false" ] && cache_uses_secure_hardware; then
printf '%s' "$decrypted_data" | cache_set "$file" 2>/dev/null || true
fi
printf '%s' "$decrypted_data"
return 0
fi
# If that fails and we're not using hardware keys, try with stored passphrase
if [ "$os_type" != "unknown" ] && [ -z "${PA_NO_KEYRING+x}" ]; then
key_passphrase=$(retrieve_credential "pa-encryption-key" "$USER" "$os_type" 2>/dev/null)
if [ "$key_passphrase" ]; then
if decrypted_data=$(printf '%s\n' "$key_passphrase" | $age --decrypt -i "$identities_file" "$file" 2>/dev/null); then
# Store in cache if using secure hardware and cache is enabled
if [ "$PA_CACHE_ENABLED" != "false" ] && [ "$cache_hit" = "false" ] && cache_uses_secure_hardware; then
printf '%s' "$decrypted_data" | cache_set "$file" 2>/dev/null || true
fi
printf '%s' "$decrypted_data"
return 0
fi
fi
fi
# If all else fails, prompt for passphrase
printf '%s: ' "Enter passphrase for encryption key"
stty -echo 2>/dev/null
read -r user_passphrase
stty echo 2>/dev/null
printf '\n'
if [ "$user_passphrase" ]; then
if decrypted_data=$(printf '%s\n' "$user_passphrase" | $age --decrypt -i "$identities_file" "$file" 2>/dev/null); then
# Store in cache if using secure hardware and cache is enabled
if [ "$PA_CACHE_ENABLED" != "false" ] && [ "$cache_hit" = "false" ] && cache_uses_secure_hardware; then
printf '%s' "$decrypted_data" | cache_set "$file" 2>/dev/null || true
fi
printf '%s' "$decrypted_data"
return 0
fi
fi
return 1
}
# Check if current setup uses secure hardware (Secure Enclave or YubiKey)
cache_uses_secure_hardware() {
# Check if we're using age-plugin-se (Secure Enclave)
if command -v age-plugin-se >/dev/null 2>&1 && [ -f "$identities_file" ]; then
# Check if identities file contains Secure Enclave key
if grep -q "age-plugin-se" "$identities_file" 2>/dev/null; then
return 0
fi
fi
# Check if we're using age-plugin-yubikey
if command -v age-plugin-yubikey >/dev/null 2>&1 && [ -f "$identities_file" ]; then
# Check if identities file contains YubiKey
if grep -q "age-plugin-yubikey" "$identities_file" 2>/dev/null; then
return 0
fi
fi
return 1
}
# Cache management command
pw_cache() {
local subcmd="${1:-status}"
case "$subcmd" in
"status"|"stat")
cache_stats
;;
"clear"|"clean")
if yn "clear all cached entries?"; then
cache_clear_all
printf '%s\n' "Cache cleared successfully."
else
printf '%s\n' "Cache clear cancelled."
fi
;;
"stats"|"statistics")
cache_stats
;;
"cleanup")
cache_cleanup_expired
printf '%s\n' "Expired cache entries cleaned up."
;;
*)
printf '%s\n' "Usage: pa cache [status|clear|stats|cleanup]"
printf '%s\n' " status - Show cache status and basic statistics"
printf '%s\n' " clear - Clear all cached entries (requires confirmation)"
printf '%s\n' " stats - Show detailed cache statistics"
printf '%s\n' " cleanup - Clean up expired cache entries"
return 1
;;
esac
}
pw_add() {
if yn "generate a password?"; then
pass=$(rand_chars "${PA_LENGTH:-50}" "${PA_PATTERN:-A-Za-z0-9-_}") ||
die "couldn't generate a password"
else
# 'sread()' is a simple wrapper function around 'read'
# to prevent user input from being printed to the terminal.
sread pass "enter a password"
[ "$pass" ] ||
die "password can't be empty"
sread pass2 "enter a password (again)"
# Disable this check as we dynamically populate the two
# passwords using the 'sread()' function.
# shellcheck disable=2154
[ "$pass" = "$pass2" ] ||
die "passwords don't match"
fi
mkdir -p "$(dirname -- "$name")" ||
die "couldn't create category '$(dirname -- "$name")'"
# Use 'age' to store the password in an encrypted file.
# A heredoc is used here instead of a 'printf' to avoid
# leaking the password through the '/proc' filesystem.
#
# Heredocs are sometimes implemented via temporary files,
# however this is typically done using 'mkstemp()' which
# is more secure than a leak in '/proc'.
$age --encrypt -R "$recipients_file" -o "./$name.age" <<-EOF ||
$pass
EOF
die "couldn't encrypt $name.age"
printf '%s\n' "saved '$name' to the store."
$git_enabled && git_add_and_commit "./$name.age" "add '$name'"
}
pw_edit() {
# Use appropriate temporary directory for each platform
case "$(detect_os)" in
"windows"|"wsl")
# Use Windows temp directory or fallback
tmpdir="${TEMP:-${TMP:-/tmp}}"
;;
"linux")
# Prefer /dev/shm because it's an in-memory
# space that we can use to store data without
# having bits laying around in sectors.
tmpdir=/dev/shm
# Fall back to $TMPDIR or /tmp - /dev/shm is Linux-only
# and shared memory space on other operating systems
# have non-standard methods of setup/access.
[ -w /dev/shm ] || tmpdir=${TMPDIR:-/tmp}
;;
*)
# macOS and others use /tmp
tmpdir=/tmp
;;
esac
# Reimplement mktemp here, because
# mktemp isn't defined in POSIX.
new=true tmpfile=$tmpdir/pa.$(rand_chars 10 'A-Za-z0-9') ||
die "couldn't generate random characters"
trap 'rm -f "$tmpfile"' EXIT
if [ ! -f "$name.age" ]; then new=true; else new=false && {
decrypt_with_key "./$name.age" > "$tmpfile" ||
die "couldn't decrypt $name.age"
}; fi
# Use EDITOR environment variable or fallback to vi
editor_cmd="${EDITOR:-vi}"
# Check if the editor command exists
if ! command -v $(printf '%s' "$editor_cmd" | cut -d' ' -f1) >/dev/null 2>&1; then
die "editor '$editor_cmd' not found. Set EDITOR environment variable or install vi"
fi
# Launch the editor
$editor_cmd "$tmpfile" ||
die "editor '$editor_cmd' exited with code $?"
[ -s "$tmpfile" ] || return
mkdir -p "$(dirname -- "$name")" ||
die "couldn't create category '$(dirname -- "$name")'"
$age --encrypt -R "$recipients_file" -o "./$name.age" "$tmpfile" ||
die "couldn't encrypt $name.age"
if $new; then printf '%s\n' "saved '$name' to the store."; fi
$git_enabled && git_add_and_commit "./$name.age" "edit '$name'"
}
pw_del() {
yn "delete password '$name'?" || return
rm -f "./$name.age"
rmdir -p "$(dirname -- "$name")" 2>/dev/null || :
$git_enabled && git_add_and_commit "./$name.age" "delete '$name'"
}
pw_show() {
decrypt_with_key "./$name.age" ||
die "couldn't decrypt $name.age"
}
pw_list() {
find "./$name" -type f -name \*.age | sed 's/..//;s/\.age$//' | sort
}
pw_find() {
# Check if fzf is available
command -v fzf >/dev/null 2>&1 ||
die "fzf not found, install from https://github.com/junegunn/fzf"
# Get the selected password name using fzf
name=$(find . -type f -name '*.age' | \
sed 's/..//;s/\.age$//' | \
sort | \
fzf --height 40% --reverse --no-multi --prompt="Select password: ") ||
die "no password selected"
# If a command was provided, execute it with the selected password
if [ $# -gt 0 ]; then
case $1 in
s*|show) pw_show ;;
e*|edit) pw_edit ;;
d*|del) pw_del ;;
*) die "unsupported find command '$1'. Use: show, edit, del" ;;
esac
else
# Default action is to show the password
pw_show
fi
}
pw_find() {
# Check if fzf is available
command -v fzf >/dev/null 2>&1 ||
die "fzf not found, install from https://github.com/junegunn/fzf"
# Get the selected password name using fzf
name=$(find . -type f -name '*.age' | \
sed 's/..//;s/\.age$//' | \
sort | \
fzf --height 40% --reverse --no-multi --prompt="Select password: ") ||
die "no password selected"
# If a command was provided, execute it with the selected password
if [ $# -gt 0 ]; then
case $1 in
s*|show) pw_show ;;
e*|edit) pw_edit ;;
d*|del) pw_del ;;
*) die "unsupported find command '$1'. Use: show, edit, del" ;;
esac
else
# Default action is to show the password
pw_show
fi
}
git_add_and_commit() {
git add "$1" ||
die "couldn't git add $1"
git commit -qm "$2" ||
die "couldn't git commit $2"
}
rand_chars() {
# Generate random characters cross-platform
# $1 = number of chars to receive
# $2 = filter for the chars
if [ -r /dev/urandom ]; then
# Unix-like systems (Linux, macOS, WSL)
LC_ALL=C tr -dc "$2" </dev/urandom | dd ibs=1 obs=1 count="$1" 2>/dev/null
elif command -v openssl >/dev/null 2>&1; then
# Fallback using OpenSSL (available on most platforms)
openssl rand -base64 $((($1 * 4 + 2) / 3)) | LC_ALL=C tr -dc "$2" | dd ibs=1 obs=1 count="$1" 2>/dev/null
elif command -v powershell.exe >/dev/null 2>&1; then
# Windows PowerShell fallback
powershell.exe -Command "
\$chars = '$2';
\$result = '';
for (\$i = 0; \$i -lt $1; \$i++) {
\$result += \$chars[(Get-Random -Maximum \$chars.Length)]
};
Write-Output \$result
" 2>/dev/null | tr -d '\r\n'
else
# Last resort: use date and process ID for some randomness
# This is not cryptographically secure but better than nothing
seed=$(date +%s)$$
i=0
result=""
while [ $i -lt "$1" ]; do
seed=$((seed * 1103515245 + 12345))
char_index=$((seed % ${#2}))
char=$(printf '%s' "$2" | dd ibs=1 obs=1 skip=$char_index count=1 2>/dev/null)
result="$result$char"
i=$((i + 1))
done
printf '%s' "$result"
fi
}
yn() {
printf '%s [y/N]: ' "$1"
# Enable raw input to allow for a single byte to be read from
# stdin without needing to wait for the user to press Return.
[ -t 0 ] && stty -echo -icanon
# Read a single byte from stdin using 'dd'. POSIX 'read' has
# no support for single/'N' byte based input from the user.
answer=$(dd ibs=1 count=1 2>/dev/null)
# Disable raw input, leaving the terminal how we *should*
# have found it.
[ -t 0 ] && stty echo icanon
printf '%s\n' "$answer"
# Handle the answer here directly, enabling this function's
# return status to be used in place of checking for '[yY]'
# throughout this program.
glob "$answer" '[yY]'
}
sread() {
printf '%s: ' "$2"
# Disable terminal printing while the user inputs their
# password. POSIX 'read' has no '-s' flag which would
# effectively do the same thing.
[ -t 0 ] && stty -echo
read -r "$1"
[ -t 0 ] && stty echo
printf '\n'
}
glob() {
# This is a simple wrapper around a case statement to allow
# for simple string comparisons against globs.
#
# Example: if glob "Hello World" '* World'; then
#
# Disable this warning as it is the intended behavior.
# shellcheck disable=2254
case $1 in $2) return 0 ;; esac
return 1
}
die() {
printf '%s: %s.\n' "$(basename "$0")" "$1" >&2
exit 1
}
usage() {
printf %s "\
pa
a simple password manager
commands:
[a]dd [name] - Add a password entry.
[c]ache - Cache management (status|clear|stats).
[d]el [name] - Delete a password entry.
[e]dit [name] - Edit a password entry with \$EDITOR (default: vi).
[f]ind [cmd] - Fuzzy search passwords with fzf (show|edit|del).
[g]it [cmd] - Run git command in the password dir.
[l]ist [cat] - List all entries in a category.
[s]how [name] - Show password for an entry.
[v]ersion - Show version information.
cache commands:
cache status - Show cache status and statistics.
cache clear - Clear all cached entries.
cache stats - Show detailed cache statistics.
env vars:
data directory: export PA_DIR=~/.local/share/pa
password length: export PA_LENGTH=50
password pattern: export PA_PATTERN=A-Za-z0-9-_
disable tracking: export PA_NOGIT=
disable keyring: export PA_NO_KEYRING=1
disable cache: export PA_DISABLE_CACHE=1
editor command: export EDITOR=nano
cache timeout (seconds): export PA_CACHE_TIMEOUT=900
platform support:
- macOS: Keychain integration, Secure Enclave (age-plugin-se)
- Linux: libsecret/secret-tool integration
- Windows: Credential Manager integration (WSL/MSYS2/Cygwin)
- Hardware: YubiKey (age-plugin-yubikey) on all platforms
"
exit 0
}
version() {
# Check if we're running from source (placeholders not replaced)
if [ "$PA_VERSION" = "__VERSION__" ]; then
# Running from source - use captured git values
if [ "$PA_DEV_TAG" ]; then
if [ -n "$PA_DEV_STATUS" ]; then
version_string="${PA_DEV_TAG}-dirty"
release_date_string="development"
else
version_string="$PA_DEV_TAG"
release_date_string="$PA_DEV_DATE"
fi
printf '%s\n' "pa version: $version_string"
printf '%s\n' "release date: $release_date_string"
printf '%s\n' "commit: $PA_DEV_COMMIT"
else
printf '%s\n' "pa version: development"
printf '%s\n' "release date: development"
printf '%s\n' "commit: unknown"
fi
else
# Running from installed version - use embedded values
printf '%s\n' "pa version: $PA_VERSION"
printf '%s\n' "release date: $PA_RELEASE_DATE"
printf '%s\n' "commit: $PA_COMMIT"
fi
exit 0
}
# ============================================================================
# SECURE CLEANUP AND SIGNAL HANDLING
# ============================================================================
# Secure cleanup function for cache
cache_secure_cleanup() {
# Only cleanup if cache is enabled and initialized
[ "$PA_CACHE_ENABLED" = "false" ] && return 0