Class: Keybox::Application::PasswordSafe

Inherits:
Base
  • Object
show all
Includes:
HighLineUtil
Defined in:
lib/keybox/application/password_safe.rb

Constant Summary collapse

DEFAULT_DIRECTORY =
File.join(home_directory,".keybox")
DEFAULT_DB =
File.join(DEFAULT_DIRECTORY,"database.yaml")
DEFAULT_CONFIG =
File.join(DEFAULT_DIRECTORY,"config.yaml")
DEFAULT_COLOR_SCHEME =
:none
ACTION_LIST =
%w(add delete edit show list master-password)

Constants included from HighLineUtil

HighLineUtil::NONE_SCHEME

Instance Attribute Summary collapse

Attributes inherited from Base

#error_message, #highline, #options, #parsed_options, #stderr, #stdin, #stdout

Instance Method Summary collapse

Methods included from HighLineUtil

#hagree, #hsay, #prompt

Methods inherited from Base

#error_version_help, home_directory, #merge_options, #set_io

Constructor Details

#initialize(argv = []) ⇒ PasswordSafe

Returns a new instance of PasswordSafe.



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/keybox/application/password_safe.rb', line 26

def initialize(argv = [])
    @actions = Array.new
    super(argv)
    
    # only one of the actions is allowed
    if actions.size > 1 then
        @error_message = [ "ERROR: Only one of #{ACTION_LIST.join(",")} is allowed at a time",
                            "Try `#{@parser.program_name} --help` for more information"].join("\n")
    end

end

Instance Attribute Details

#actionsObject

Returns the value of attribute actions.



16
17
18
# File 'lib/keybox/application/password_safe.rb', line 16

def actions
  @actions
end

#dbObject (readonly)

Returns the value of attribute db.



17
18
19
# File 'lib/keybox/application/password_safe.rb', line 17

def db
  @db
end

Instance Method Details

#add(account) ⇒ Object

add an account to the database If the account is a URL and use_password_hash_for_url is true then don’t us the URLAccountEntry instead of the usual HostAccountEntry



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/keybox/application/password_safe.rb', line 252

def add() 
    entry = Keybox::HostAccountEntry.new(, )

    if @options.use_password_hash_for_url then
        begin 
             = URI.parse() 
            if not .scheme.nil? then
                entry = Keybox::URLAccountEntry.new(,)
            end
        rescue ::URI::InvalidURIError => e
            # just ignore it, we're fine with the Host
            # Account Entry
        end

    end
    new_entry = gather_info(entry)
    hsay "Adding #{new_entry.title} to database.", :information
    @db << new_entry
end

#configuration_file_optionsObject

load options from the configuration file, if the file doesn’t exist, create it and dump the default options to it.

we use the default unless the parsed_options contain a configuration file then we use that one



135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/keybox/application/password_safe.rb', line 135

def configuration_file_options
    file_path = @parsed_options.config_file || DEFAULT_CONFIG

    # if the file is 0 bytes, then this is illegal and needs
    # to be overwritten.
    if not File.exists?(file_path) or File.size(file_path) == 0 then
        determine_color_scheme
        FileUtils.mkdir_p(File.dirname(file_path))
        File.open(file_path,"w") do |f|
            YAML.dump(default_options.marshal_dump,f)
        end
    end
    options = YAML.load_file(file_path) || Hash.new
end

#default_optionsObject



115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/keybox/application/password_safe.rb', line 115

def default_options
    if not @default_options then 
        @default_options                            = OpenStruct.new
        @default_options.debug                      = 0
        @default_options.show_help                  = false
        @default_options.show_version               = false
        @default_options.config_file                = Keybox::Application::PasswordSafe::DEFAULT_CONFIG
        @default_options.db_file                    = Keybox::Application::PasswordSafe::DEFAULT_DB
        @default_options.use_password_hash_for_url  = false
        @default_options.color_scheme               = Keybox::Application::PasswordSafe::DEFAULT_COLOR_SCHEME
    end
    return @default_options
end

#delete(account) ⇒ Object

delete an entry from the database



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/keybox/application/password_safe.rb', line 297

def delete()
    matches = @db.find()
    count = 0
    matches.each do |match|
        hsay "-" * 40, :separator_bar
        hsay match, :normal
        hsay "-" * 40, :separator_bar

        if hagree "Delete this entry (y/n) ?" then
            @db.delete(match)
            count += 1
        end
    end
    hsay "#{count} records matching '#{}' deleted.", :information
end

#determine_color_schemeObject

determine the color scheme to store in the initial creation of the configuration file. We ask the user which of the color schemes will work best for them.



152
153
154
155
156
157
158
159
160
161
162
# File 'lib/keybox/application/password_safe.rb', line 152

def determine_color_scheme
    @default_options.color_scheme = @highline.choose do |menu|
        menu.layout     = :one_line
        menu.select_by  = :name
        menu.header     = nil
        menu.prompt     = "What color scheme would you like? "
        menu.choice("none") { :none }
        menu.choice("dark terminal background") { :dark_bg }
        menu.choice("light terminal background") { :light_bg }
    end
end

#edit(account) ⇒ Object

edit an entry in the database



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/keybox/application/password_safe.rb', line 316

def edit()
    matches = @db.find()
    count = 0
    matches.each do |match|
        hsay "-" * 40, :separator_bar
        hsay match, :normal
        hsay "-" * 40, :separator_bar

        if hagree "Edit this entry (y/n) ?" then
            entry = gather_info(match)
            @db.delete(match)
            @db << entry
            count += 1
            hsay "Entry '#{entry.title}' updated.", :information
        end
    end
    hsay "#{count} records matching '#{}' edited.", :information
end

#export_to_csv(file) ⇒ Object

Export data from the database into a CSV file



436
437
438
439
# File 'lib/keybox/application/password_safe.rb', line 436

def export_to_csv(file)
    Keybox::Convert::CSV.to_file(@db.records, file)
    hsay "Exported #{@db.records.size} records to #{file}.", :information
end

#fill_entry(entry) ⇒ Object



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
# File 'lib/keybox/application/password_safe.rb', line 441

def fill_entry(entry)

    # calculate maximum prompt width for pretty output
    max_length = entry.fields.collect { |f| f.length }.max
    max_length += entry.values.collect { |v| v.length }.max

    # now prompt for the entry items
    entry.fields.each do |field|
        echo = true
        validate = false
        default = entry.send(field)
        p = "#{field} [#{default}]"

        # we don't echo private field prompts and we validate
        # them
        if entry.private_field?(field) then
            echo = '*'
            validate = true
            p = "#{field}"
        end

        value = prompt("#{p}",:echo => echo ,:validate => validate,:width => max_length)

        if value.nil? or value.size == 0 then
            value = default
        end
        entry.send("#{field}=",value)
    end
    return entry
end

#gather_info(entry) ⇒ Object

Gather all the information for the



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/keybox/application/password_safe.rb', line 274

def gather_info(entry)
    gathered = false
    while not gathered do
        hsay "Gathering information for entry '#{entry.title}'", :information

        entry = fill_entry(entry)

        # dump the info we have gathered and make sure that
        # it is the input that the user wants to store.
       
        hsay "-" * 40, :separator_bar
        hsay entry, :normal
        hsay "-" * 40, :separator_bar

        gathered = hagree "Is this information correct? (y/n)"
    end

    entry
end

#import_from_csv(file) ⇒ Object

Import data into the database from a CSV file



426
427
428
429
430
431
432
# File 'lib/keybox/application/password_safe.rb', line 426

def import_from_csv(file)
    entries = Keybox::Convert::CSV.from_file(file)
    entries.each do |entry|
        @db << entry
    end
    hsay "Imported #{entries.size} records from #{file}.", :information
end

#list(account) ⇒ Object

list all the entries in the database. This doesn’t show the password for any of them, just lists the key information about each entry so the user can see what is in the database



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
# File 'lib/keybox/application/password_safe.rb', line 341

def list()
    matches = @db.find()
    title           = "Title"
    username        = "Username"
    add_info        = "Additional Information"
    if matches.size > 0 then
        lengths = {
            :title              => (matches.collect { |f| f.title.length } << title.length).max,
            :username           => (matches.collect { |f| f.username.length } << username.length).max,
            :additional_info    => add_info.length
        }

        full_length = lengths.values.inject(0) { |sum,n| sum + n}
        header = "  # #{"Title".ljust(lengths[:title])}    #{"Username".ljust(lengths[:username])}    #{add_info}"
        hsay header, :header
        #  3 spaces for number column + 1 space after and 4 spaces between
        #  each other column
        hsay"-" * (header.length), :header_bar

        matches.each_with_index do |match,i|
            line_number = sprintf("%3d", i + 1)
            # toggle colors
            color = [:even_row, :odd_row][i % 2]
            columns = []
            [:title, :username, :additional_info].each do |f|
                t = match.send(f)
                t = "-" if t.nil? or t.length == 0 
                columns << t.ljust(lengths[f])
            end
            cdata = columns.join(" " * 4)
            @highline.say("<%= color('#{line_number}',:line_number) %> <%= color(%Q{#{cdata}},'#{color}') %>")
        end
    else
        hsay "No matching records were found.", :information
    end
end

#load_color_schemeObject

load the given color scheme. If the scheme cannot be found it will default to the :none scheme which has no color

The color_scheme file exists either in the application data directory, or in the same directory as the configuration file.

The file name convention for the scheme file is schemename.color_scheme.yaml. So for instance the default :dark_bg color scheme file is named:

dark_bg.color_scheme.yaml


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
# File 'lib/keybox/application/password_safe.rb', line 178

def load_color_scheme
    if @options.color_scheme != :none then
        search_directories  = [ Keybox::APP_RESOURCE_DIR, File.dirname(@options.config_file) ]
        scheme_basename     = "#{@options.color_scheme.to_s}.color_scheme.yaml"
        scheme_path         = nil
       
        # get the path to the file
        search_directories.each do |sd|
            if File.exists?(File.join(sd,scheme_basename)) then
                scheme_path = File.join(sd,scheme_basename)
                break
            end
        end
      
        # if we have a file then load it and make sure we have
        # all the valid labels.
        if scheme_path then
            initial_color_scheme = YAML::load(File.read(scheme_path))
          
            # make sure that everything is a Symbol and in the
            # process make sure that all of the required labels
            # are there.
            color_scheme = {}
            initial_color_scheme.each_pair do |label,ansi_seq|
                color_scheme[label.to_sym] = ansi_seq.collect { |a| a.to_sym }
            end

            # validate that all the required color labels exist
            if (NONE_SCHEME.keys - color_scheme.keys).size == 0 then
                ::HighLine.color_scheme = ::HighLine::ColorScheme.new(color_scheme)
            else
                @options.color_scheme   = :none  
                ::HighLine.color_scheme = ::HighLine::ColorScheme.new(NONE_SCHEME)

                @stdout.puts "The color scheme in file '#{scheme_path}' is Invalid"
                @stdout.puts "It is missing the following items:"

                (NONE_SCHEME.keys - color_scheme.keys).each do |missing_label|
                    @stdout.puts "\t :#{missing_label}"
                end

                @stdout.puts "Not using any color scheme."
            end

        else
            # if we don't have a file then set the color
            # scheme to :none and we're done
            @options.color_scheme = :none
            ::HighLine.color_scheme = ::HighLine::ColorScheme.new(NONE_SCHEME)
        end
    else
        ::HighLine.color_scheme = ::HighLine::ColorScheme.new(NONE_SCHEME)
    end
end

#load_databaseObject

load the database from its super secret location



236
237
238
239
240
241
242
243
244
245
# File 'lib/keybox/application/password_safe.rb', line 236

def load_database
    password = nil
    if not File.exists?(@options.db_file) then
        hsay 'Creating initial database.', :information
        password  = prompt("Initial Password for (#{@options.db_file})", :echo => "*", :validate => true)
    else
        password  = prompt("Password for (#{@options.db_file})", :echo => "*")
    end
    @db = Keybox::Storage::Container.new(password,@options.db_file)
end

#master_password(ignore_this) ⇒ Object

Change the master password on the database



418
419
420
421
# File 'lib/keybox/application/password_safe.rb', line 418

def master_password(ignore_this)
    @db.passphrase = prompt("Enter new master password", :echo => '*', :validate => true, :width => 45) 
    hsay "New master password set.", :information
end

#option_parserObject



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
# File 'lib/keybox/application/password_safe.rb', line 38

def option_parser
    OptionParser.new do |op|

        op.separator ""
        op.separator "General Options:"
        
        op.on("-f", "--file DATABASE_FILE", "The Database File to use") do |db_file|
            @parsed_options.db_file = db_file
        end

        op.on("-c", "--config CONFIG_FILE", "The Configuration file to use") do |cfile|
            @parsed_options.config_file = cfile
        end

        op.on("--color SCHEME","The color scheme to use", "none,dark_bg,light_bg,<other>") do |scheme|
            @parsed_options.color_scheme = scheme.to_sym
        end
              
        op.on("-D", "--debug", "Ouput debug information to STDERR") do 
            @parsed_options.debug = true
        end

        op.on("--[no-]use-hash-for-url", "Use the password hash algorithm ", "  for URL accounts") do |r|
            @parsed_options.use_password_hash_for_url = r
        end

        op.separator ""
        op.separator "Commands, one and only one of these is required:"
        
        op.on("-h", "--help") do
            @parsed_options.show_help = true
        end

        op.on("-a", "--add ACCOUNT", "Create a new account in keybox") do ||
            @actions << [:add, ]
        end

        op.on("-d", "--delete ACCOUNT", "Delete the account from keybox") do ||
            @actions << [:delete, ]
        end

        op.on("-e", "--edit ACCOUNT", "Edit the account in keybox") do ||
            @actions << [:edit, ]
        end
        
        op.on("-l", "--list [REGEX]", "List the matching accounts", "  (no argument will list all)") do |regex|
            regex = regex || ".*"
            @actions << [:list, regex]
        end

        op.on("-m", "--master-password", "Change the master password") do
            @actions << [:master_password, nil]
        end
        
        op.on("-s", "--show [REGEX]", "Show the given account(s)") do |regex|
            regex = regex || ".*"
            @actions << [:show, regex]
        end

        op.on("-v", "--version", "Show version information") do
            @parsed_options.show_version = true
        end

        op.separator ""
        op.separator "Import / Export from other data formats:"
        
        op.on("-i", "--import-from-csv FILE", "Import from a CSV file") do |file|
            @actions << [:import_from_csv, file]
        end

        op.on("-x", "--export-to-csv FILE", "Export contents to a CSV file") do |file|
            @actions << [:export_to_csv, file]
        end

    end
end

#runObject



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
# File 'lib/keybox/application/password_safe.rb', line 472

def run
    begin
        error_version_help
        merge_options
        load_color_scheme
        load_database

        if @actions.size == 0 then
            @actions << [:list, ".*"]
        end
        
        action, param = *@actions.shift
        self.send(action, param)
        
        if @db.modified? then 
            hsay "Database modified, saving.", :information
            @db.save
        else
            hsay "Database not modified.", :information
        end
    rescue SignalException => se
        @stdout.puts
        hsay "Interrupted", :error
        hsay "There may be private information on your screen.", :error
        hsay "Please close this terminal.", :error
        exit 1
    rescue StandardError => e
        hsay "Error: #{e.message}", :error
        exit 1
    end
end

#show(account) ⇒ Object

output all the information for the accounts matching



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
# File 'lib/keybox/application/password_safe.rb', line 381

def show()
    matches = @db.find()
    if matches.size > 0 then
        matches.each_with_index do |match,i|
            hsay "#{sprintf("%3d",i + 1)}. #{match.title}", :header
            max_name_length = match.max_field_length + 1
            match.each do |name,value|
                next if name == "title"
                next if value.length == 0

                name_out = name.rjust(max_name_length)
                @highline.say("<%= color(%Q{#{name_out}}, :name) %> <%= color(':',:separator) %> ")

                if match.private_field?(name) then
                    @highline.ask(
                       "<%= color(%Q{#{value}},:private) %> <%= color('(press any key).', :prompt) %> "
                    ) do |q|
                        q.overwrite = true
                        q.echo      = false
                        q.character = true
                    end
                    
                    @highline.say("<%= color(%Q{#{name_out}}, :name) %> <%= color(':',:separator) %> <%= color('#{'*' * 20}', :private) %>")
                else
                    hsay value, :value
                end
            end
            @stdout.puts
        end
    else
        hsay "No matching records were found.", :information
    end
end