Class: Aspera::Secret::Store::MacosSecurity::Keychain

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/secret/store/macos_security.rb

Overview

keychain based on macOS keychain, using security command line

Constant Summary collapse

SECURITY_UTILITY =
'security'
DOMAINS =
%i[user system common dynamic].freeze
LIST_OPTIONS =
{
  domain: :c
}.freeze
KEYCHAIN_OPTIONS =
{
  password: :p
}.freeze
ADD_PASS_OPTIONS =
{
  account:  :a,
  creator:  :c,
  type:     :C,
  domain:   :d,
  kind:     :D,
  value:    :G,
  comment:  :j,
  label:    :l,
  path:     :p,
  port:     :P,
  protocol: :r,
  server:   :s,
  service:  :s,
  auth:     :t,
  password: :w,
  getpass:  :g
}.freeze
EXIT_ITEM_NOT_FOUND =

Exit code of security when the item is not found

44

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Keychain

Returns a new instance of Keychain.

Parameters:

  • path (String) —

    File path of the keychain



132
133
134
# File 'lib/aspera/secret/store/macos_security.rb', line 132

def initialize(path)
  @path = path
end

Instance Attribute Details

#path ⇒ Object (readonly)

Returns the value of attribute path.



129
130
131
# File 'lib/aspera/secret/store/macos_security.rb', line 129

def path
  @path
end

Class Method Details

.by_name(name) ⇒ Keychain?

Find a keychain by its short name (without .keychain-db extension)

Parameters:

  • name (String) —

    Keychain name

Returns:

  • (Keychain, nil) —

    Matching keychain or nil



109
110
111
# File 'lib/aspera/secret/store/macos_security.rb', line 109

def by_name(name)
  list.find { |kc| kc.path.end_with?("/#{name}.keychain-db") }
end

.create(path, password:) ⇒ Keychain

Create a new macOS keychain file

Parameters:

  • path (String) —

    File path for the new keychain

  • password (String) —

    Password for the new keychain

Returns:

  • (Keychain) —

    Created keychain instance



117
118
119
120
# File 'lib/aspera/secret/store/macos_security.rb', line 117

def create(path, password:)
  execute('create-keychain', {password: password}, KEYCHAIN_OPTIONS, path)
  new(path)
end

.default ⇒ Keychain

Get the macOS default keychain

Returns:

  • (Keychain) —

    Default keychain instance



88
89
90
# File 'lib/aspera/secret/store/macos_security.rb', line 88

def default
  key_chains(execute('default-keychain').first).first
end

.execute(command, options = nil, supported = nil, last_opt = nil, exception: true) ⇒ Array(String, String, Process::Status)

Execute a security CLI command with given options

Parameters:

  • command (String) —

    The security sub-command

  • options (Hash, nil) (defaults to: nil) —

    Command options

  • supported (Hash, nil) (defaults to: nil) —

    Mapping of option keys to CLI flags

  • last_opt (String, nil) (defaults to: nil) —

    Trailing argument (e.g. keychain path)

  • exception (Boolean) (defaults to: true) —

    Whether to raise on non-zero exit

Returns:

  • (Array(String, String, Process::Status)) —

    stdout, stderr, status



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/aspera/secret/store/macos_security.rb', line 56

def execute(command, options = nil, supported = nil, last_opt = nil, exception: true)
  url = options&.delete(:url)
  if !url.nil?
    uri = URI.parse(url)
    Aspera.assert(uri.scheme.eql?('https'), 'only https')
    options[:protocol] = 'htps'
    Aspera.assert(!uri.host.nil?, type: Error) { 'host required in URL' }
    options[:server] = uri.host
    options[:path] = uri.path unless ['', '/'].include?(uri.path)
    options[:port] = uri.port unless uri.port.eql?(443) && !url.include?(':443/')
  end
  command_args = [SECURITY_UTILITY, command]
  options&.each do |k, v|
    Aspera.assert(supported.key?(k)) { "unknown option: #{k}" }
    next if v.nil?
    command_args.push("-#{supported[k]}")
    # No shell is involved: value is passed as is
    command_args.push(v.to_s) unless v.to_s.empty?
  end
  command_args.push(last_opt) unless last_opt.nil?
  Environment.secure_execute(*command_args, mode: :capture, exception: exception)
end

.key_chains(output) ⇒ Array<Keychain>

Parse output of list command into Keychain objects

Parameters:

  • output (String) —

    Raw CLI output

Returns:

  • (Array<Keychain>) —

    List of keychain instances



82
83
84
# File 'lib/aspera/secret/store/macos_security.rb', line 82

def key_chains(output)
  output.split("\n").collect { |line| new(line.strip.gsub(/^"|"$/, '')) }
end

.list(options = {}) ⇒ Array<Keychain>

List keychains in the search list or domain

Parameters:

  • options (Hash) (defaults to: {}) —

    Domain options

Returns:

  • (Array<Keychain>) —

    List of keychains



101
102
103
104
# File 'lib/aspera/secret/store/macos_security.rb', line 101

def list(options = {})
  Aspera.assert_values(options[:domain], DOMAINS, type: ParameterError) { 'domain' } unless options[:domain].nil?
  key_chains(execute('list-keychains', options, LIST_OPTIONS).first)
end

.login ⇒ Keychain

Get the macOS login keychain

Returns:

  • (Keychain) —

    Login keychain instance



94
95
96
# File 'lib/aspera/secret/store/macos_security.rb', line 94

def 
  key_chains(execute('login-keychain').first).first
end

.search_list=(keychain_list) ⇒ Array(String, String, Process::Status)

Set the keychain search list

Parameters:

  • keychain_list (Array<Keychain>) —

    Ordered list of keychains

Returns:

  • (Array(String, String, Process::Status)) —

    Execution result



125
126
127
# File 'lib/aspera/secret/store/macos_security.rb', line 125

def search_list=(keychain_list)
  Environment.secure_execute(SECURITY_UTILITY, 'list-keychains', '-s', *keychain_list.map(&:path), mode: :capture)
end

Instance Method Details

#decode_hex_blob(string) ⇒ String

Decode a hexadecimal encoded string into UTF-8

Parameters:

  • string (String) —

    Hex string

Returns:



139
140
141
# File 'lib/aspera/secret/store/macos_security.rb', line 139

def decode_hex_blob(string)
  [string].pack('H*').force_encoding('UTF-8')
end

#delete ⇒ Array(String, String, Process::Status)

Delete this keychain file from disk

Returns:

  • (Array(String, String, Process::Status)) —

    Execution result



197
198
199
# File 'lib/aspera/secret/store/macos_security.rb', line 197

def delete
  self.class.execute('delete-keychain', nil, nil, @path)
end

#lock ⇒ Array(String, String, Process::Status)

Lock this keychain

Returns:

  • (Array(String, String, Process::Status)) —

    Execution result



191
192
193
# File 'lib/aspera/secret/store/macos_security.rb', line 191

def lock
  self.class.execute('lock-keychain', nil, nil, @path)
end

#password(operation, pass_type, options) ⇒ Hash?

Perform generic or internet password operation (add, find, delete)

Parameters:

  • operation (Symbol) —

    :add, :find, or :delete

  • pass_type (Symbol) —

    :generic or :internet

  • options (Hash) —

    Operation options (account, service, password, label, etc.)

Returns:

  • (Hash, nil) —

    Parsed attributes for :find, or nil



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
# File 'lib/aspera/secret/store/macos_security.rb', line 148

def password(operation, pass_type, options)
  Aspera.assert_values(operation, %i[add find delete]) { 'operation' }
  Aspera.assert_values(pass_type, %i[generic internet]) { 'pass_type' }
  Aspera.assert_type(options, Hash)
  missing = (operation.eql?(:add) ? %i[account service password] : %i[label]) - options.keys
  Aspera.assert(missing.empty?) { "missing options: #{missing}" }
  options[:getpass] = '' if operation.eql?(:find)
  stdout, stderr, status = self.class.execute("#{operation}-#{pass_type}-password", options, ADD_PASS_OPTIONS, @path, exception: false)
  unless status.success?
    return if operation.eql?(:find) && status.exitstatus.eql?(EXIT_ITEM_NOT_FOUND)
    raise Error, stderr.strip.gsub(/^.*: /, '')
  end
  return unless operation.eql?(:find)
  attributes = {}
  # Attributes are on stdout, password (option -g) is on stderr
  "#{stdout}\n#{stderr}".split("\n").each do |line|
    case line
    when /^keychain: "(.+)"/
      # ignore
    when /0x00000007 .+="(.+)"/
      attributes['label'] = Regexp.last_match(1)
    when /"(\w{4})".+="(.+)"/
      attributes[Regexp.last_match(1)] = Regexp.last_match(2)
    when /"(\w{4})"<blob>=0x([[:xdigit:]]+)/
      attributes[Regexp.last_match(1)] = decode_hex_blob(Regexp.last_match(2))
    when /^password: "(.+)"/
      attributes['password'] = Regexp.last_match(1)
    when /^password: 0x([[:xdigit:]]+)/
      attributes['password'] = decode_hex_blob(Regexp.last_match(1))
    end
  end
  return attributes
end

#set_settings(timeout: nil, lock_on_sleep: false) ⇒ Array(String, String, Process::Status)

Configure settings for this keychain (lock timeout, lock on sleep)

Parameters:

  • timeout (Integer, nil) (defaults to: nil) —

    Inactivity timeout in seconds

  • lock_on_sleep (Boolean) (defaults to: false) —

    Whether to lock when system sleeps

Returns:

  • (Array(String, String, Process::Status)) —

    Execution result



205
206
207
208
209
210
211
# File 'lib/aspera/secret/store/macos_security.rb', line 205

def set_settings(timeout: nil, lock_on_sleep: false)
  args = [SECURITY_UTILITY, 'set-keychain-settings']
  args.push('-l') if lock_on_sleep
  args.push('-u', '-t', timeout.to_s) if timeout
  args.push(@path)
  Environment.secure_execute(*args, mode: :capture)
end

#unlock(password:) ⇒ Array(String, String, Process::Status)

Unlock this keychain with its password

Parameters:

  • password (String) —

    Password of the keychain

Returns:

  • (Array(String, String, Process::Status)) —

    Execution result



185
186
187
# File 'lib/aspera/secret/store/macos_security.rb', line 185

def unlock(password:)
  self.class.execute('unlock-keychain', {password: password}, KEYCHAIN_OPTIONS, @path)
end