3 # password store management tool
5 # Copyright (c) 2008 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
93 exec(GNUPG, "--status-fd=#{statW.fileno}", *args)
94 raise ("Calling gnupg failed")
100 (outtxt, stderrtxt, statustxt) = readwrite3(intxt, inW, outR, errR, statR);
101 wpid, status = Process.waitpid2 pid
102 throw "Unexpected pid: #{pid} vs #{wpid}" unless pid == wpid
103 throw "Process has not exited!?" unless status.exited?
104 throw "gpg call did not exit sucessfully" if (require_success and status.exitstatus != 0)
105 return outtxt, stderrtxt, statustxt, status.exitstatus
108 def GnuPG.init_keys()
110 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', %w{--fast-list-mode --with-colons --with-fingerprint --list-secret-keys}, true)
113 outtxt.split("\n").each do |line|
114 parts = line.split(':')
115 if (parts[0] == "ssb" or parts[0] == "sec")
116 @@my_keys.push parts[4]
117 elsif (parts[0] == "fpr")
118 @@my_fprs.push parts[9]
122 # This is for my private keys, so we can tell if a file is encrypted to us
123 def GnuPG.get_my_keys()
127 # And this is for my private keys also, so we can tell if we are encrypting to ourselves
128 def GnuPG.get_my_fprs()
133 # This maps public keyids to fingerprints, so we can figure
134 # out if a file that is encrypted to a bunch of keys is
135 # encrypted to the fingerprints it should be encrypted to
136 def GnuPG.get_fpr_from_keyid(keyid)
137 fpr = @@keyid_fpr_mapping[keyid]
138 # this can be null, if we tried to find the fpr but failed to find the key in our keyring
140 STDERR.puts "Warning: No key found for keyid #{keyid}"
144 def GnuPG.get_fprs_from_keyids(keyids)
145 learn_fingerprints_from_keyids(keyids)
146 return keyids.collect{ |k| get_fpr_from_keyid(k) or "unknown" }
149 # this is to load the keys we will soon be asking about into
150 # our keyid-fpr-mapping hash
151 def GnuPG.learn_fingerprints_from_keyids(keyids)
152 need_to_learn = keyids.reject{ |k| @@keyid_fpr_mapping.has_key?(k) }
153 if need_to_learn.size > 0
154 # we can't use --fast-list-mode here because GnuPG is broken
155 # and does not show elmo's fingerprint in a call like
156 # gpg --with-colons --fast-list-mode --with-fingerprint --list-key D7C3F131AB2A91F5
157 args = %w{--with-colons --with-fingerprint --list-keys}
158 args.concat need_to_learn
159 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', args, true)
163 outtxt.split("\n").each do |line|
164 parts = line.split(':')
165 if (parts[0] == "pub")
167 elsif (parts[0] == "fpr")
169 @@keyid_fpr_mapping[pub] = fpr
170 elsif (parts[0] == "sub")
171 @@keyid_fpr_mapping[parts[4]] = fpr
175 need_to_learn.reject{ |k| @@keyid_fpr_mapping.has_key?(k) }.each { |k| @@keyid_fpr_mapping[k] = nil }
179 def read_input(query, default_yes=true)
187 print "#{query} #{append} "
188 i = STDIN.readline.chomp.downcase
207 f = File.open(ENV['HOME']+'/.pws-trusted-users')
208 rescue Exception => e
214 f.readlines.each do |line|
222 (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(content, %w{})
225 statustxt.split("\n").each do |line|
226 if m = /^\[GNUPG:\] GOODSIG/.match(line)
228 elsif m = /^\[GNUPG:\] VALIDSIG \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ \S+ ([0-9A-F]+)/.match(line)
234 STDERR.puts ".users file is not signed properly. GnuPG said on stdout:"
236 STDERR.puts "and on stderr:"
237 STDERR.puts stderrtxt
238 STDERR.puts "and via statusfd:"
239 STDERR.puts statustxt
243 if not trusted.include?(validsig)
244 STDERR.puts ".users file is signed by #{validsig} which is not in ~/.pws-trusted-users"
249 STDERR.puts "gpg verify failed for .users file"
258 f = File.open('.users')
259 rescue Exception => e
267 users = verify(users)
273 users.split("\n").each do |line|
277 if (m = /^([a-zA-Z0-9-]+)\s*=\s*([0-9A-Fa-f]{40})\s*$/.match line)
280 if @users.has_key?(user)
281 STDERR.puts "User #{user} redefined at line #{lno}!"
285 elsif (m = /^(@[a-zA-Z0-9-]+)\s*=\s*(.*)$/.match line)
288 if @groups.has_key?(group)
289 STDERR.puts "Group #{group} redefined at line #{lno}!"
292 members = members.split(/[\t ,]+/)
293 @groups[group] = { "members" => members }
299 return (name =~ /^@/)
301 def check_exists(x, whence, fatal=true)
304 ok=false unless (@groups.has_key?(x))
306 ok=false unless @users.has_key?(x)
309 STDERR.puts( (fatal ? "Error: " : "Warning: ") + "#{whence} contains unknown member #{x}")
315 @groups.each_pair do |groupname, group|
316 group['members'].each do |member|
317 check_exists(member, "Group #{groupname}")
319 group['members_to_do'] = group['members'].clone
325 @groups.each_pair do |groupname, group|
326 group['keys'] = [] unless group['keys']
328 still_contains_groups = false
329 group['members_to_do'].clone.each do |member|
331 if @groups[member]['members_to_do'].size == 0
332 group['keys'].concat @groups[member]['keys']
333 group['members_to_do'].delete(member)
336 still_contains_groups = true
339 group['keys'].push @users[member]
340 group['members_to_do'].delete(member)
344 all_expanded = false if still_contains_groups
346 break if all_expanded
348 cyclic_groups = @groups.keys.reject{|name| @groups[name]['members_to_do'].size == 0}.join(", ")
349 STDERR.puts "Cyclic group memberships in #{cyclic_groups}?"
355 def expand_targets(targets)
359 unless check_exists(t, "access line", false)
364 fprs.concat @groups[t]['keys']
378 attr_reader :accessible, :encrypted, :readable, :readers
380 def EncryptedFile.determine_readable(readers)
381 GnuPG.get_my_keys.each do |keyid|
382 return true if readers.include?(keyid)
387 def EncryptedFile.list_readers(statustxt)
389 statustxt.split("\n").each do |line|
390 m = /^\[GNUPG:\] ENC_TO ([0-9A-F]+)/.match line
397 def EncryptedFile.targets(text)
398 metaline = text.split("\n").first
399 m = /^access: (.*)/.match metaline
401 return m[1].strip.split(/[\t ,]+/)
405 def initialize(filename, new=false)
406 @groupconfig = GroupConfig.new
413 unless FileTest.readable?(filename)
418 @encrypted_content = File.read(filename)
419 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall(@encrypted_content, %w{--with-colons --no-options --no-default-keyring --secret-keyring=/dev/null --keyring=/dev/null})
420 @encrypted = !(statustxt =~ /\[GNUPG:\] NODATA/)
422 @readers = EncryptedFile.list_readers(statustxt)
423 @readable = EncryptedFile.determine_readable(@readers)
428 (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(@encrypted_content, %w{--decrypt})
429 if !@new and exitstatus != 0
430 proceed = read_input("Warning: gpg returned non-zero exit status #{exitstatus} when decrypting #{@filename}. Proceed?", false)
431 exit(0) unless proceed
432 elsif !@new and outtxt.length == 0
433 proceed = read_input("Warning: #{@filename} decrypted to an empty file. Proceed?")
434 exit(0) unless proceed
440 def encrypt(content, recipients)
441 args = recipients.collect{ |r| "--recipient=#{r}"}
442 args.push "--trust-model=always"
443 args.push "--keyring=./.keyring" if FileTest.exists?(".keyring")
445 args.push "--encrypt"
446 (outtxt, stderrtxt, statustxt, exitstatus) = GnuPG.gpgcall(content, args)
449 statustxt.split("\n").each do |line|
450 m = /^\[GNUPG:\] INV_RECP \S+ ([0-9A-F]+)/.match line
455 again = read_input("Warning: the following recipients are invalid: #{invalid.join(", ")}. Try again (or proceed)?")
456 return false if again
458 if outtxt.length == 0
459 tryagain = read_input("Error: #{@filename} encrypted to an empty file. Edit again (or exit)?")
460 return false if tryagain
464 proceed = read_input("Warning: gpg returned non-zero exit status #{exitstatus} when encrypting #{@filename}. Said:\n#{stderrtxt}\n#{statustxt}\n\nProceed (or try again)?")
465 return false unless proceed
472 def determine_encryption_targets(content)
473 targets = EncryptedFile.targets(content)
475 tryagain = read_input("Warning: Did not find targets to encrypt to in header. Try again (or exit)?", true)
476 return false if tryagain
480 ok, expanded = @groupconfig.expand_targets(targets)
481 if (expanded.size == 0)
482 tryagain = read_input("Errors in access header. Edit again (or exit)?", true)
483 return false if tryagain
486 tryagain = read_input("Warnings in access header. Edit again (or continue)?", true)
487 return false if tryagain
491 GnuPG.get_my_fprs.each do |fpr|
492 if expanded.include?(fpr)
498 tryagain = read_input("File is not being encrypted to you. Edit again (or continue)?", true)
499 return false if tryagain
502 return true, expanded
505 def write_back(content, targets)
506 ok, encrypted = encrypt(content, targets)
507 return false unless ok
509 File.open(@filename,"w").write(encrypted)
515 def help(parser, code=0, io=STDOUT)
516 io.puts "Usage: #{$program_name} ls [<directory> ...]"
517 io.puts parser.summarize
518 io.puts "Lists the contents of the given directory/directories, or the current"
519 io.puts "directory if none is given. For each file show whether it is PGP-encrypted"
520 io.puts "file, and if yes whether we can read it."
526 dir = Dir.open(dirname)
527 rescue Exception => e
532 Dir.chdir(dirname) do
533 unless FileTest.exists?(".users")
534 STDERR.puts "The .users file does not exists here. This is not a password store, is it?"
537 dir.sort.each do |filename|
538 next if (filename =~ /^\./) and not (@all >= 3)
539 stat = File::Stat.new(filename)
541 puts "(sym) #{filename}" if (@all >= 2)
542 elsif stat.directory?
543 puts "(dir) #{filename}" if (@all >= 2)
545 puts "(other) #{filename}" if (@all >= 2)
547 f = EncryptedFile.new(filename)
549 puts "(!perm) #{filename}"
551 puts "(file) #{filename}" if (@all >= 2)
553 puts "(ok) #{filename}"
555 puts "(locked) #{filename}" if (@all >= 1)
564 ARGV.options do |opts|
565 opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
566 opts.on_tail("-a", "--all" , "Show all files (use up to 3 times to show even more than all)") { @all = @all+1 }
571 dirs.push('.') unless dirs.size > 0
572 dirs.each { |dir| ls_dir(dir) }
577 def help(parser, code=0, io=STDOUT)
578 io.puts "Usage: #{$program_name} ed <filename>"
579 io.puts parser.summarize
580 io.puts "Decrypts the file, spawns an editor, and encrypts it again"
585 encrypted_file = EncryptedFile.new(filename, @new)
586 if !@new and !encrypted_file.readable && !@force
587 STDERR.puts "#{filename} is probably not readable"
591 encrypted_to = GnuPG.get_fprs_from_keyids(encrypted_file.readers).sort
593 content = encrypted_file.decrypt
594 original_content = content
596 oldsize = content.length
597 tempfile = Tempfile.open('pws')
598 tempfile.puts content
600 system($editor, tempfile.path)
602 throw "Process has not exited!?" unless status.exited?
603 unless status.exitstatus == 0
604 proceed = read_input("Warning: Editor did not exit successfully (exit code #{status.exitstatus}. Proceed?")
605 exit(0) unless proceed
607 tempfile.seek(0, IO::SEEK_SET)
608 content = tempfile.read
611 newsize = content.length
612 tempfile.seek(0, IO::SEEK_SET)
613 clearsize = (newsize > oldsize) ? newsize : oldsize
614 tempfile.print "\0"*clearsize
618 if content.length == 0
619 proceed = read_input("Warning: Content is now empty. Proceed?")
620 exit(0) unless proceed
623 ok, targets = encrypted_file.determine_encryption_targets(content)
626 if (original_content == content)
627 if (targets.sort == encrypted_to)
628 proceed = read_input("Nothing changed. Re-encrypt anyway?", false)
629 exit(0) unless proceed
631 STDERR.puts("Info: Content not changed but re-encrypting anyway because the list of keys changed")
635 success = encrypted_file.write_back(content, targets)
641 ARGV.options do |opts|
642 opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
643 opts.on_tail("-n", "--new" , "Edit new file") { |@new| }
644 opts.on_tail("-f", "--force" , "Spawn an editor even if the file is probably not readable") { |@force| }
647 help(ARGV.options, 1, STDERR) if ARGV.length != 1
648 filename = ARGV.shift
651 if FileTest.exists?(filename)
652 STDERR.puts "#{filename} does exist"
656 if !FileTest.exists?(filename)
657 STDERR.puts "#{filename} does not exist"
659 elsif !FileTest.file?(filename)
660 STDERR.puts "#{filename} is not a regular file"
662 elsif !FileTest.readable?(filename)
663 STDERR.puts "#{filename} is not accessible (unix perms)"
668 dirname = File.dirname(filename)
669 basename = File.basename(filename)
677 def help(parser, code=0, io=STDOUT)
678 io.puts "Usage: #{$program_name} update-keyring [<keyserver>]"
679 io.puts parser.summarize
680 io.puts "Updates the local .keyring file"
685 ARGV.options do |opts|
686 opts.on_tail("-h", "--help" , "Display this help screen") { help(opts) }
689 help(ARGV.options, 1, STDERR) if ARGV.length > 1
690 keyserver = ARGV.shift
691 keyserver = 'subkeys.pgp.net' unless keyserver
693 groupconfig = GroupConfig.new
694 users = groupconfig.get_users()
695 args = %w{--with-colons --no-options --no-default-keyring --keyring=./.keyring}
697 system('touch', '.keyring')
698 users.each_pair() do |uid, keyid|
700 cmd << "--keyserver=#{keyserver}"
703 puts "Fetching key for #{uid}"
704 (outtxt, stderrtxt, statustxt) = GnuPG.gpgcall('', cmd)
705 unless (statustxt =~ /^\[GNUPG:\] IMPORT_OK /)
706 STDERR.puts "Warning: did not find IMPORT_OK token in status output"
707 STDERR.puts "gpg exited with exit code #{ecode})"
708 STDERR.puts "Command was gpg #{cmd.join(' ')}"
709 STDERR.puts "stdout was #{outtxt}"
710 STDERR.puts "stderr was #{stderrtxt}"
711 STDERR.puts "statustxt was #{statustxt}"
715 cmd << '--batch' << '--edit' << keyid << 'minimize' << 'save'
716 (outtxt, stderrtxt, statustxt, ecode) = GnuPG.gpgcall('', cmd)
723 def help(code=0, io=STDOUT)
724 io.puts "Usage: #{$program_name} ed"
725 io.puts " #{$program_name} ls"
726 io.puts " #{$program_name} update-keyring"
727 io.puts " #{$program_name} help"
728 io.puts "Call #{$program_name} <command> --help for additional options/parameters"
737 when 'update-keyring': KeyringUpdater.new
753 # vim:set shiftwidth=2: