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"
35 $program_name = File.basename($0, '.*')
37 $editor = ENV['EDITOR']
39 %w{/usr/bin/sensible-editor /usr/bin/editor /usr/bin/vi}.each do |editor|
40 if FileTest.executable?(editor)
50 @@keyid_fpr_mapping = {}
52 def GnuPG.readwrite3(intxt, infd, stdoutfd, stderrfd, statusfd)
53 outtxt, stderrtxt, statustxt = ''
54 thread_in = Thread.new {
58 thread_out = Thread.new {
59 outtxt = stdoutfd.read
62 thread_err = Thread.new {
63 errtxt = stderrfd.read
66 thread_status = Thread.new {
67 statustxt = statusfd.read
74 thread_status.join if thread_status
76 return outtxt, stderrtxt, statustxt
79 def GnuPG.gpgcall(intxt, args, require_success = false)
83 statR, statW = IO.pipe
94 exec(GNUPG, "--status-fd=#{statW.fileno}", *args)
96 outW.puts("[PWSEXECERROR]: #{e}")
99 raise ("Calling gnupg failed")
105 (outtxt, stderrtxt, statustxt) = readwrite3(intxt, inW, outR, errR, statR);
106 wpid, status = Process.waitpid2 pid
107 throw "Unexpected pid: #{pid} vs #{wpid}" unless pid == wpid
108 throw "Process has not exited!?" unless status.exited?
109 throw "gpg call did not exit sucessfully" if (require_success and status.exitstatus != 0)
110 if m=/^\[PWSEXECERROR\]: (.*)/.match(outtxt) then
111 STDERR.puts "Could not run GnuPG: #{m[1]}"
114 return outtxt, stderrtxt, statustxt, status.exitstatus
117 def GnuPG.init_keys()
119 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', %w{--fast-list-mode --with-colons --with-fingerprint --list-secret-keys}, true)
122 outtxt.split("\n").each do |line|
123 parts = line.split(':')
124 if (parts[0] == "ssb" or parts[0] == "sec")
125 @@my_keys.push parts[4]
126 elsif (parts[0] == "fpr")
127 @@my_fprs.push parts[9]
131 # This is for my private keys, so we can tell if a file is encrypted to us
132 def GnuPG.get_my_keys()
136 # And this is for my private keys also, so we can tell if we are encrypting to ourselves
137 def GnuPG.get_my_fprs()
142 # This maps public keyids to fingerprints, so we can figure
143 # out if a file that is encrypted to a bunch of keys is
144 # encrypted to the fingerprints it should be encrypted to
145 def GnuPG.get_fpr_from_keyid(keyid)
146 fpr = @@keyid_fpr_mapping[keyid]
147 # this can be null, if we tried to find the fpr but failed to find the key in our keyring
149 STDERR.puts "Warning: No key found for keyid #{keyid}"
153 def GnuPG.get_fprs_from_keyids(keyids)
154 learn_fingerprints_from_keyids(keyids)
155 return keyids.collect{ |k| get_fpr_from_keyid(k) or "unknown" }
158 # this is to load the keys we will soon be asking about into
159 # our keyid-fpr-mapping hash
160 def GnuPG.learn_fingerprints_from_keyids(keyids)
161 need_to_learn = keyids.reject{ |k| @@keyid_fpr_mapping.has_key?(k) }
162 if need_to_learn.size > 0
163 # we can't use --fast-list-mode here because GnuPG is broken
164 # and does not show elmo's fingerprint in a call like
165 # gpg --with-colons --fast-list-mode --with-fingerprint --list-key D7C3F131AB2A91F5
166 args = %w{--with-colons --with-fingerprint --list-keys}
167 args.concat need_to_learn
168 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', args, true)
172 outtxt.split("\n").each do |line|
173 parts = line.split(':')
174 if (parts[0] == "pub")
176 elsif (parts[0] == "fpr")
178 @@keyid_fpr_mapping[pub] = fpr
179 elsif (parts[0] == "sub")
180 @@keyid_fpr_mapping[parts[4]] = fpr
184 need_to_learn.reject{ |k| @@keyid_fpr_mapping.has_key?(k) }.each { |k| @@keyid_fpr_mapping[k] = nil }
188 def read_input(query, default_yes=true)
196 print "#{query} #{append} "
197 i = STDIN.readline.chomp.downcase
216 f = File.open(ENV['HOME']+'/.pws-trusted-users')
217 rescue Exception => e
223 f.readlines.each do |line|
231 (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(content, %w{})
234 statustxt.split("\n").each do |line|
235 if m = /^\[GNUPG:\] GOODSIG/.match(line)
237 elsif m = /^\[GNUPG:\] VALIDSIG \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ ([0-9A-F]+)/.match(line)
243 STDERR.puts ".users file is not signed properly. GnuPG said on stdout:"
245 STDERR.puts "and on stderr:"
246 STDERR.puts stderrtxt
247 STDERR.puts "and via statusfd:"
248 STDERR.puts statustxt
252 if not trusted.include?(validsig)
253 STDERR.puts ".users file is signed by #{validsig} which is not in ~/.pws-trusted-users"
258 STDERR.puts "gpg verify failed for .users file"
267 f = File.open('.users')
268 rescue Exception => e
276 users = verify(users)
282 users.split("\n").each do |line|
286 if (m = /^([a-zA-Z0-9-]+)\s*=\s*([0-9A-Fa-f]{40})\s*$/.match line)
289 if @users.has_key?(user)
290 STDERR.puts "User #{user} redefined at line #{lno}!"
294 elsif (m = /^(@[a-zA-Z0-9-]+)\s*=\s*(.*)$/.match line)
297 if @groups.has_key?(group)
298 STDERR.puts "Group #{group} redefined at line #{lno}!"
301 members = members.split(/[\t ,]+/)
302 @groups[group] = { "members" => members }
308 return (name =~ /^@/)
310 def check_exists(x, whence, fatal=true)
313 ok=false unless (@groups.has_key?(x))
315 ok=false unless @users.has_key?(x)
318 STDERR.puts( (fatal ? "Error: " : "Warning: ") + "#{whence} contains unknown member #{x}")
324 @groups.each_pair do |groupname, group|
325 group['members'].each do |member|
326 check_exists(member, "Group #{groupname}")
328 group['members_to_do'] = group['members'].clone
334 @groups.each_pair do |groupname, group|
335 group['keys'] = [] unless group['keys']
337 still_contains_groups = false
338 group['members_to_do'].clone.each do |member|
340 if @groups[member]['members_to_do'].size == 0
341 group['keys'].concat @groups[member]['keys']
342 group['members_to_do'].delete(member)
345 still_contains_groups = true
348 group['keys'].push @users[member]
349 group['members_to_do'].delete(member)
353 all_expanded = false if still_contains_groups
355 break if all_expanded
357 cyclic_groups = @groups.keys.reject{|name| @groups[name]['members_to_do'].size == 0}.join(", ")
358 STDERR.puts "Cyclic group memberships in #{cyclic_groups}?"
364 def expand_targets(targets)
368 unless check_exists(t, "access line", false)
373 fprs.concat @groups[t]['keys']
387 attr_reader :accessible, :encrypted, :readable, :readers
389 def EncryptedFile.determine_readable(readers)
390 GnuPG.get_my_keys.each do |keyid|
391 return true if readers.include?(keyid)
396 def EncryptedFile.list_readers(statustxt)
398 statustxt.split("\n").each do |line|
399 m = /^\[GNUPG:\] ENC_TO ([0-9A-F]+)/.match line
406 def EncryptedFile.targets(text)
407 metaline = text.split("\n").first
408 m = /^access: (.*)/.match metaline
410 return m[1].strip.split(/[\t ,]+/)
414 def initialize(filename, new=false)
415 @groupconfig = GroupConfig.new
422 unless FileTest.readable?(filename)
427 @encrypted_content = File.read(filename)
428 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall(@encrypted_content, %w{--with-colons --no-options --no-default-keyring --secret-keyring=/dev/null --keyring=/dev/null})
429 @encrypted = !(statustxt =~ /\[GNUPG:\] NODATA/)
431 @readers = EncryptedFile.list_readers(statustxt)
432 @readable = EncryptedFile.determine_readable(@readers)
437 (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(@encrypted_content, %w{--decrypt})
438 if !@new and exitstatus != 0
439 proceed = read_input("Warning: gpg returned non-zero exit status #{exitstatus} when decrypting #{@filename}. Proceed?", false)
440 exit(0) unless proceed
441 elsif !@new and outtxt.length == 0
442 proceed = read_input("Warning: #{@filename} decrypted to an empty file. Proceed?")
443 exit(0) unless proceed
449 def encrypt(content, recipients)
450 args = recipients.collect{ |r| "--recipient=#{r}"}
451 args.push "--trust-model=always"
452 args.push "--keyring=./.keyring" if FileTest.exists?(".keyring")
454 args.push "--encrypt"
455 (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(content, args)
458 statustxt.split("\n").each do |line|
459 m = /^\[GNUPG:\] INV_RECP \S+ ([0-9A-F]+)/.match line
464 again = read_input("Warning: the following recipients are invalid: #{invalid.join(", ")}. Try again (or proceed)?")
465 return false if again
467 if outtxt.length == 0
468 tryagain = read_input("Error: #{@filename} encrypted to an empty file. Edit again (or exit)?")
469 return false if tryagain
473 proceed = read_input("Warning: gpg returned non-zero exit status #{exitstatus} when encrypting #{@filename}. Said:\n#{stderrtxt}\n#{statustxt}\n\nProceed (or try again)?")
474 return false unless proceed
481 def determine_encryption_targets(content)
482 targets = EncryptedFile.targets(content)
484 tryagain = read_input("Warning: Did not find targets to encrypt to in header. Try again (or exit)?", true)
485 return false if tryagain
489 ok, expanded = @groupconfig.expand_targets(targets)
490 if (expanded.size == 0)
491 tryagain = read_input("Errors in access header. Edit again (or exit)?", true)
492 return false if tryagain
495 tryagain = read_input("Warnings in access header. Edit again (or continue)?", true)
496 return false if tryagain
500 GnuPG.get_my_fprs.each do |fpr|
501 if expanded.include?(fpr)
507 tryagain = read_input("File is not being encrypted to you. Edit again (or continue)?", true)
508 return false if tryagain
511 return true, expanded
514 def write_back(content, targets)
515 ok, encrypted = encrypt(content, targets)
516 return false unless ok
518 File.open(@filename,"w").write(encrypted)
524 def help(parser, code=0, io=STDOUT)
525 io.puts "Usage: #{$program_name} ls [<directory> ...]"
526 io.puts parser.summarize
527 io.puts "Lists the contents of the given directory/directories, or the current"
528 io.puts "directory if none is given. For each file show whether it is PGP-encrypted"
529 io.puts "file, and if yes whether we can read it."
535 dir = Dir.open(dirname)
536 rescue Exception => e
541 Dir.chdir(dirname) do
542 unless FileTest.exists?(".users")
543 STDERR.puts "The .users file does not exists here. This is not a password store, is it?"
546 dir.sort.each do |filename|
547 next if (filename =~ /^\./) and not (@all >= 3)
548 stat = File::Stat.new(filename)
550 puts "(sym) #{filename}" if (@all >= 2)
551 elsif stat.directory?
552 puts "(dir) #{filename}" if (@all >= 2)
554 puts "(other) #{filename}" if (@all >= 2)
556 f = EncryptedFile.new(filename)
558 puts "(!perm) #{filename}"
560 puts "(file) #{filename}" if (@all >= 2)
562 puts "(ok) #{filename}"
564 puts "(locked) #{filename}" if (@all >= 1)
573 ARGV.options do |opts|
574 opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
575 opts.on_tail("-a", "--all" , "Show all files (use up to 3 times to show even more than all)") { @all = @all+1 }
580 dirs.push('.') unless dirs.size > 0
581 dirs.each { |dir| ls_dir(dir) }
586 def help(parser, code=0, io=STDOUT)
587 io.puts "Usage: #{$program_name} ed <filename>"
588 io.puts parser.summarize
589 io.puts "Decrypts the file, spawns an editor, and encrypts it again"
594 encrypted_file = EncryptedFile.new(filename, @new)
595 if !@new and !encrypted_file.readable && !@force
596 STDERR.puts "#{filename} is probably not readable"
600 encrypted_to = GnuPG.get_fprs_from_keyids(encrypted_file.readers).sort
602 content = encrypted_file.decrypt
603 original_content = content
605 oldsize = content.length
606 tempfile = Tempfile.open('pws')
607 tempfile.puts content
609 system($editor, tempfile.path)
611 throw "Process has not exited!?" unless status.exited?
612 unless status.exitstatus == 0
613 proceed = read_input("Warning: Editor did not exit successfully (exit code #{status.exitstatus}. Proceed?")
614 exit(0) unless proceed
616 tempfile.seek(0, IO::SEEK_SET)
617 content = tempfile.read
620 newsize = content.length
621 tempfile.seek(0, IO::SEEK_SET)
622 clearsize = (newsize > oldsize) ? newsize : oldsize
623 tempfile.print "\0"*clearsize
627 if content.length == 0
628 proceed = read_input("Warning: Content is now empty. Proceed?")
629 exit(0) unless proceed
632 ok, targets = encrypted_file.determine_encryption_targets(content)
635 if (original_content == content)
636 if (targets.sort == encrypted_to)
637 proceed = read_input("Nothing changed. Re-encrypt anyway?", false)
638 exit(0) unless proceed
640 STDERR.puts("Info: Content not changed but re-encrypting anyway because the list of keys changed")
644 success = encrypted_file.write_back(content, targets)
650 ARGV.options do |opts|
651 opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
652 opts.on_tail("-n", "--new" , "Edit new file") { |@new| }
653 opts.on_tail("-f", "--force" , "Spawn an editor even if the file is probably not readable") { |@force| }
656 help(ARGV.options, 1, STDERR) if ARGV.length != 1
657 filename = ARGV.shift
660 if FileTest.exists?(filename)
661 STDERR.puts "#{filename} does exist"
665 if !FileTest.exists?(filename)
666 STDERR.puts "#{filename} does not exist"
668 elsif !FileTest.file?(filename)
669 STDERR.puts "#{filename} is not a regular file"
671 elsif !FileTest.readable?(filename)
672 STDERR.puts "#{filename} is not accessible (unix perms)"
677 dirname = File.dirname(filename)
678 basename = File.basename(filename)
686 def help(parser, code=0, io=STDOUT)
687 io.puts "Usage: #{$program_name} update-keyring [<keyserver>]"
688 io.puts parser.summarize
689 io.puts "Updates the local .keyring file"
694 ARGV.options do |opts|
695 opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
698 help(ARGV.options, 1, STDERR) if ARGV.length > 1
699 keyserver = ARGV.shift
700 keyserver = 'keys.gnupg.net' unless keyserver
702 groupconfig = GroupConfig.new
703 users = groupconfig.get_users()
704 args = %w{--with-colons --no-options --no-default-keyring --keyring=./.keyring}
706 system('touch', '.keyring')
707 users.each_pair() do |uid, keyid|
709 cmd << "--keyserver=#{keyserver}"
712 puts "Fetching key for #{uid}"
713 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', cmd)
714 unless (statustxt =~ /^\[GNUPG:\] IMPORT_OK /)
715 STDERR.puts "Warning: did not find IMPORT_OK token in status output"
716 STDERR.puts "gpg exited with exit code #{ecode})"
717 STDERR.puts "Command was gpg #{cmd.join(' ')}"
718 STDERR.puts "stdout was #{outtxt}"
719 STDERR.puts "stderr was #{stderrtxt}"
720 STDERR.puts "statustxt was #{statustxt}"
724 cmd << '--batch' << '--edit' << keyid << 'minimize' << 'save'
725 (outtxt, stderrtxt, statustxt, ecode) = GnuPG.gpgcall('', cmd)
732 def help(code=0, io=STDOUT)
733 io.puts "Usage: #{$program_name} ed"
734 io.puts " #{$program_name} ls"
735 io.puts " #{$program_name} update-keyring"
736 io.puts " #{$program_name} help"
737 io.puts "Call #{$program_name} <command> --help for additional options/parameters"
746 when 'update-keyring': KeyringUpdater.new
762 # vim:set shiftwidth=2: