3 # password store management tool
5 # Copyright (c) 2008, 2009 Peter Palfrader <peter@palfrader.org>
7 # Permission is hereby granted, free of charge, to any person obtaining
8 # a copy of this software and associated documentation files (the
9 # "Software"), to deal in the Software without restriction, including
10 # without limitation the rights to use, copy, modify, merge, publish,
11 # distribute, sublicense, and/or sell copies of the Software, and to
12 # permit persons to whom the Software is furnished to do so, subject to
13 # the following conditions:
15 # The above copyright notice and this permission notice shall be
16 # included in all copies or substantial portions of the Software.
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 Thread.abort_on_exception = true
33 GNUPG = "/usr/bin/gpg"
34 GROUP_PATTERN = "@[a-zA-Z0-9-]+"
35 USER_PATTERN = "[a-zA-Z0-9:-]+"
36 $program_name = File.basename($0, '.*')
38 $editor = ENV['EDITOR']
40 %w{/usr/bin/sensible-editor /usr/bin/editor /usr/bin/vi}.each do |editor|
41 if FileTest.executable?(editor)
51 @@keyid_fpr_mapping = {}
53 def GnuPG.readwrite3(intxt, infd, stdoutfd, stderrfd, statusfd)
54 outtxt, stderrtxt, statustxt = ''
55 thread_in = Thread.new {
59 thread_out = Thread.new {
60 outtxt = stdoutfd.read
63 thread_err = Thread.new {
64 errtxt = stderrfd.read
67 thread_status = Thread.new {
68 statustxt = statusfd.read
75 thread_status.join if thread_status
77 return outtxt, stderrtxt, statustxt
80 def GnuPG.gpgcall(intxt, args, require_success = false)
84 statR, statW = IO.pipe
95 exec(GNUPG, "--status-fd=#{statW.fileno}", *args)
97 outW.puts("[PWSEXECERROR]: #{e}")
100 raise ("Calling gnupg failed")
106 (outtxt, stderrtxt, statustxt) = readwrite3(intxt, inW, outR, errR, statR);
107 wpid, status = Process.waitpid2 pid
108 throw "Unexpected pid: #{pid} vs #{wpid}" unless pid == wpid
109 throw "Process has not exited!?" unless status.exited?
110 throw "gpg call did not exit sucessfully" if (require_success and status.exitstatus != 0)
111 if m=/^\[PWSEXECERROR\]: (.*)/.match(outtxt) then
112 STDERR.puts "Could not run GnuPG: #{m[1]}"
115 return outtxt, stderrtxt, statustxt, status.exitstatus
118 def GnuPG.init_keys()
120 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', %w{--fast-list-mode --with-colons --with-fingerprint --list-secret-keys}, true)
123 outtxt.split("\n").each do |line|
124 parts = line.split(':')
125 if (parts[0] == "ssb" or parts[0] == "sec")
126 @@my_keys.push parts[4]
127 elsif (parts[0] == "fpr")
128 @@my_fprs.push parts[9]
132 # This is for my private keys, so we can tell if a file is encrypted to us
133 def GnuPG.get_my_keys()
137 # And this is for my private keys also, so we can tell if we are encrypting to ourselves
138 def GnuPG.get_my_fprs()
143 # This maps public keyids to fingerprints, so we can figure
144 # out if a file that is encrypted to a bunch of keys is
145 # encrypted to the fingerprints it should be encrypted to
146 def GnuPG.get_fpr_from_keyid(keyid)
147 fpr = @@keyid_fpr_mapping[keyid]
148 # this can be null, if we tried to find the fpr but failed to find the key in our keyring
150 STDERR.puts "Warning: No key found for keyid #{keyid}"
154 def GnuPG.get_fprs_from_keyids(keyids)
155 learn_fingerprints_from_keyids(keyids)
156 return keyids.collect{ |k| get_fpr_from_keyid(k) or "unknown" }
159 # this is to load the keys we will soon be asking about into
160 # our keyid-fpr-mapping hash
161 def GnuPG.learn_fingerprints_from_keyids(keyids)
162 need_to_learn = keyids.reject{ |k| @@keyid_fpr_mapping.has_key?(k) }
163 if need_to_learn.size > 0
164 # we can't use --fast-list-mode here because GnuPG is broken
165 # and does not show elmo's fingerprint in a call like
166 # gpg --with-colons --fast-list-mode --with-fingerprint --list-key D7C3F131AB2A91F5
167 args = %w{--with-colons --with-fingerprint --list-keys}
168 args.concat need_to_learn
169 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', args, true)
173 outtxt.split("\n").each do |line|
174 parts = line.split(':')
175 if (parts[0] == "pub")
177 elsif (parts[0] == "fpr")
179 @@keyid_fpr_mapping[pub] = fpr
180 elsif (parts[0] == "sub")
181 @@keyid_fpr_mapping[parts[4]] = fpr
185 need_to_learn.reject{ |k| @@keyid_fpr_mapping.has_key?(k) }.each { |k| @@keyid_fpr_mapping[k] = nil }
189 def read_input(query, default_yes=true)
197 print "#{query} #{append} "
199 i = STDIN.readline.chomp.downcase
221 f = File.open(ENV['HOME']+'/.pws-trusted-users')
222 rescue Exception => e
228 f.readlines.each do |line|
237 args.push "--keyring=./.keyring" if FileTest.exists?(".keyring")
238 (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(content, args)
241 statustxt.split("\n").each do |line|
242 if m = /^\[GNUPG:\] GOODSIG/.match(line)
244 elsif m = /^\[GNUPG:\] VALIDSIG \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ ([0-9A-F]+)/.match(line)
250 STDERR.puts ".users file is not signed properly. GnuPG said on stdout:"
252 STDERR.puts "and on stderr:"
253 STDERR.puts stderrtxt
254 STDERR.puts "and via statusfd:"
255 STDERR.puts statustxt
259 if not trusted.include?(validsig)
260 STDERR.puts ".users file is signed by #{validsig} which is not in ~/.pws-trusted-users"
265 STDERR.puts "gpg verify failed for .users file"
274 f = File.open('.users')
275 rescue Exception => e
283 users = verify(users)
289 users.split("\n").each do |line|
293 if (m = /^(#{USER_PATTERN})\s*=\s*([0-9A-Fa-f]{40})\s*$/.match line)
296 if @users.has_key?(user)
297 STDERR.puts "User #{user} redefined at line #{lno}!"
301 elsif (m = /^(#{GROUP_PATTERN})\s*=\s*(.*)$/.match line)
304 if @groups.has_key?(group)
305 STDERR.puts "Group #{group} redefined at line #{lno}!"
308 members = members.split(/[\t ,]+/)
309 @groups[group] = { "members" => members }
315 return (name =~ /^@/)
317 def check_exists(x, whence, fatal=true)
320 ok=false unless (@groups.has_key?(x))
322 ok=false unless @users.has_key?(x)
325 STDERR.puts( (fatal ? "Error: " : "Warning: ") + "#{whence} contains unknown member #{x}")
331 @groups.each_pair do |groupname, group|
332 group['members'].each do |member|
333 check_exists(member, "Group #{groupname}")
335 group['members_to_do'] = group['members'].clone
341 @groups.each_pair do |groupname, group|
342 group['keys'] = [] unless group['keys']
344 still_contains_groups = false
345 group['members_to_do'].clone.each do |member|
347 if @groups[member]['members_to_do'].size == 0
348 group['keys'].concat @groups[member]['keys']
349 group['members_to_do'].delete(member)
352 still_contains_groups = true
355 group['keys'].push @users[member]
356 group['members_to_do'].delete(member)
360 all_expanded = false if still_contains_groups
362 break if all_expanded
364 cyclic_groups = @groups.keys.reject{|name| @groups[name]['members_to_do'].size == 0}.join(", ")
365 STDERR.puts "Cyclic group memberships in #{cyclic_groups}?"
371 def expand_targets(targets)
375 unless check_exists(t, "access line", false)
380 fprs.concat @groups[t]['keys']
394 attr_reader :accessible, :encrypted, :readable, :readers
396 def EncryptedFile.determine_readable(readers)
397 GnuPG.get_my_keys.each do |keyid|
398 return true if readers.include?(keyid)
403 def EncryptedFile.list_readers(statustxt)
405 statustxt.split("\n").each do |line|
406 m = /^\[GNUPG:\] ENC_TO ([0-9A-F]+)/.match line
413 def EncryptedFile.targets(text)
414 text.split("\n").each do |line|
418 m = /^access: "?((?:(?:#{GROUP_PATTERN}|#{USER_PATTERN}),?\s*)+)"?/.match line
420 return m[1].strip.split(/[\t ,]+/)
425 def initialize(filename, new=false)
426 @groupconfig = GroupConfig.new
433 unless FileTest.readable?(filename)
438 @encrypted_content = File.read(filename)
439 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall(@encrypted_content, %w{--with-colons --no-options --no-default-keyring --secret-keyring=/dev/null --keyring=/dev/null})
440 @encrypted = !(statustxt =~ /\[GNUPG:\] NODATA/)
442 @readers = EncryptedFile.list_readers(statustxt)
443 @readable = EncryptedFile.determine_readable(@readers)
448 (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(@encrypted_content, %w{--decrypt})
449 if !@new and exitstatus != 0
450 proceed = read_input("Warning: gpg returned non-zero exit status #{exitstatus} when decrypting #{@filename}. Proceed?", false)
451 exit(0) unless proceed
452 elsif !@new and outtxt.length == 0
453 proceed = read_input("Warning: #{@filename} decrypted to an empty file. Proceed?")
454 exit(0) unless proceed
460 def encrypt(content, recipients)
461 args = recipients.collect{ |r| "--recipient=#{r}"}
462 args.push "--trust-model=always"
463 args.push "--keyring=./.keyring" if FileTest.exists?(".keyring")
465 args.push "--encrypt"
466 (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(content, args)
469 statustxt.split("\n").each do |line|
470 m = /^\[GNUPG:\] INV_RECP \S+ ([0-9A-F]+)/.match line
475 again = read_input("Warning: the following recipients are invalid: #{invalid.join(", ")}. Try again (or proceed)?")
476 return false if again
478 if outtxt.length == 0
479 tryagain = read_input("Error: #{@filename} encrypted to an empty file. Edit again (or exit)?")
480 return false if tryagain
484 proceed = read_input("Warning: gpg returned non-zero exit status #{exitstatus} when encrypting #{@filename}. Said:\n#{stderrtxt}\n#{statustxt}\n\nProceed (or try again)?")
485 return false unless proceed
492 def determine_encryption_targets(content)
493 targets = EncryptedFile.targets(content)
495 tryagain = read_input("Warning: Did not find targets to encrypt to in header. Try again (or exit)?", true)
496 return false if tryagain
500 ok, expanded = @groupconfig.expand_targets(targets)
501 if (expanded.size == 0)
502 tryagain = read_input("Errors in access header. Edit again (or exit)?", true)
503 return false if tryagain
506 tryagain = read_input("Warnings in access header. Edit again (or continue)?", true)
507 return false if tryagain
511 GnuPG.get_my_fprs.each do |fpr|
512 if expanded.include?(fpr)
518 tryagain = read_input("File is not being encrypted to you. Edit again (or continue)?", true)
519 return false if tryagain
522 return true, expanded
525 def write_back(content, targets)
526 ok, encrypted = encrypt(content, targets)
527 return false unless ok
529 File.open(@filename,"w").write(encrypted)
535 def help(parser, code=0, io=STDOUT)
536 io.puts "Usage: #{$program_name} ls [<directory> ...]"
537 io.puts parser.summarize
538 io.puts "Lists the contents of the given directory/directories, or the current"
539 io.puts "directory if none is given. For each file show whether it is PGP-encrypted"
540 io.puts "file, and if yes whether we can read it."
546 dir = Dir.open(dirname)
547 rescue Exception => e
552 Dir.chdir(dirname) do
553 unless FileTest.exists?(".users")
554 STDERR.puts "The .users file does not exists here. This is not a password store, is it?"
557 dir.sort.each do |filename|
558 next if (filename =~ /^\./) and not (@all >= 3)
559 stat = File::Stat.new(filename)
561 puts "(sym) #{filename}" if (@all >= 2)
562 elsif stat.directory?
563 puts "(dir) #{filename}" if (@all >= 2)
565 puts "(other) #{filename}" if (@all >= 2)
567 f = EncryptedFile.new(filename)
569 puts "(!perm) #{filename}"
571 puts "(file) #{filename}" if (@all >= 2)
573 puts "(ok) #{filename}"
575 puts "(locked) #{filename}" if (@all >= 1)
584 ARGV.options do |opts|
585 opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
586 opts.on_tail("-a", "--all" , "Show all files (use up to 3 times to show even more than all)") { @all = @all+1 }
591 dirs.push('.') unless dirs.size > 0
592 dirs.each { |dir| ls_dir(dir) }
597 def help(parser, code=0, io=STDOUT)
598 io.puts "Usage: #{$program_name} ed <filename>"
599 io.puts parser.summarize
600 io.puts "Decrypts the file, spawns an editor, and encrypts it again"
605 encrypted_file = EncryptedFile.new(filename, @new)
606 if !@new and !encrypted_file.readable && !@force
607 STDERR.puts "#{filename} is probably not readable"
611 encrypted_to = GnuPG.get_fprs_from_keyids(encrypted_file.readers).sort
613 content = encrypted_file.decrypt
614 original_content = content
616 oldsize = content.length
617 tempfile = Tempfile.open('pws')
618 tempfile.puts content
620 system($editor, tempfile.path)
622 throw "Process has not exited!?" unless status.exited?
623 unless status.exitstatus == 0
624 proceed = read_input("Warning: Editor did not exit successfully (exit code #{status.exitstatus}. Proceed?")
625 exit(0) unless proceed
628 # some editors do not write new content in place, but instead
629 # make a new file and more it in the old file's place.
631 reopened = File.open(tempfile.path, "r+")
632 rescue Exception => e
636 content = reopened.read
638 # zero the file, well, both of them.
639 newsize = content.length
640 clearsize = (newsize > oldsize) ? newsize : oldsize
642 [tempfile, reopened].each do |f|
643 f.seek(0, IO::SEEK_SET)
644 f.print "\0"*clearsize
650 if content.length == 0
651 proceed = read_input("Warning: Content is now empty. Proceed?")
652 exit(0) unless proceed
655 ok, targets = encrypted_file.determine_encryption_targets(content)
658 if (original_content == content)
659 if (targets.sort == encrypted_to)
660 proceed = read_input("Nothing changed. Re-encrypt anyway?", false)
661 exit(0) unless proceed
663 STDERR.puts("Info: Content not changed but re-encrypting anyway because the list of keys changed")
667 success = encrypted_file.write_back(content, targets)
673 ARGV.options do |opts|
674 opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
675 opts.on_tail("-n", "--new" , "Edit new file") { |new| @new=new }
676 opts.on_tail("-f", "--force" , "Spawn an editor even if the file is probably not readable") { |force| @force=force }
679 help(ARGV.options, 1, STDERR) if ARGV.length != 1
680 filename = ARGV.shift
683 if FileTest.exists?(filename)
684 STDERR.puts "#{filename} does exist"
688 if !FileTest.exists?(filename)
689 STDERR.puts "#{filename} does not exist"
691 elsif !FileTest.file?(filename)
692 STDERR.puts "#{filename} is not a regular file"
694 elsif !FileTest.readable?(filename)
695 STDERR.puts "#{filename} is not accessible (unix perms)"
700 dirname = File.dirname(filename)
701 basename = File.basename(filename)
709 def help(parser, code=0, io=STDOUT)
710 io.puts "Usage: #{$program_name} get <filename> <query>"
711 io.puts parser.summarize
712 io.puts "Decrypts the file, fetches a key and outputs it to stdout."
713 io.puts "The file must be in YAML format."
714 io.puts "query is a query, formatted like /host/users/root"
718 def get(filename, what)
719 encrypted_file = EncryptedFile.new(filename, @new)
720 if !encrypted_file.readable
721 STDERR.puts "#{filename} is probably not readable"
726 yaml = YAML::load(encrypted_file.decrypt)
727 rescue Psych::SyntaxError, ArgumentError => e
728 STDERR.puts "Could not parse YAML: #{e.message}"
734 a = what.split("/")[1..-1]
737 # q = /, so print top level keys
748 STDERR.puts("No such key or invalid lookup expression")
749 elsif hit.respond_to?(:keys)
760 ARGV.options do |opts|
761 opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
764 help(ARGV.options, 1, STDERR) if ARGV.length != 2
765 filename = ARGV.shift
768 if !FileTest.exists?(filename)
769 STDERR.puts "#{filename} does not exist"
771 elsif !FileTest.file?(filename)
772 STDERR.puts "#{filename} is not a regular file"
774 elsif !FileTest.readable?(filename)
775 STDERR.puts "#{filename} is not accessible (unix perms)"
779 dirname = File.dirname(filename)
780 basename = File.basename(filename)
788 def help(parser, code=0, io=STDOUT)
789 io.puts "Usage: #{$program_name} update-keyring [<keyserver>]"
790 io.puts parser.summarize
791 io.puts "Updates the local .keyring file"
796 ARGV.options do |opts|
797 opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
800 help(ARGV.options, 1, STDERR) if ARGV.length > 1
801 keyserver = ARGV.shift
802 keyserver = 'keys.gnupg.net' unless keyserver
804 groupconfig = GroupConfig.new
805 users = groupconfig.get_users()
806 args = %w{--with-colons --no-options --no-default-keyring --keyring=./.keyring}
808 system('touch', '.keyring')
809 users.each_pair() do |uid, keyid|
811 cmd << "--keyserver=#{keyserver}"
814 puts "Fetching key for #{uid}"
815 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', cmd)
816 unless (statustxt =~ /^\[GNUPG:\] IMPORT_OK /)
817 STDERR.puts "Warning: did not find IMPORT_OK token in status output"
818 STDERR.puts "gpg exited with exit code #{ecode})"
819 STDERR.puts "Command was gpg #{cmd.join(' ')}"
820 STDERR.puts "stdout was #{outtxt}"
821 STDERR.puts "stderr was #{stderrtxt}"
822 STDERR.puts "statustxt was #{statustxt}"
826 cmd << '--batch' << '--edit' << keyid << 'minimize' << 'save'
827 (outtxt, stderrtxt, statustxt, ecode) = GnuPG.gpgcall('', cmd)
834 def help(code=0, io=STDOUT)
835 io.puts "Usage: #{$program_name} ed"
836 io.puts " #{$program_name} ls"
837 io.puts " #{$program_name} update-keyring"
838 io.puts " #{$program_name} help"
839 io.puts "Call #{$program_name} <command> --help for additional options/parameters"
846 when 'ls' then Ls.new
847 when 'ed' then Ed.new
848 when 'get' then Get.new
849 when 'update-keyring' then KeyringUpdater.new
865 # vim:set shiftwidth=2: