Class: ChefVault::Item

Inherits:
Chef::DataBagItem
  • Object
show all
Includes:
Mixins
Defined in:
lib/chef-vault/item.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Mixins

#delete_solo, #find_solo_path, #load_solo, #save_solo

Constructor Details

#initialize(vault, name, opts = {}) ⇒ Item

constructs a new ChefVault::Item

Parameters:

  • vault (String)

    the name of the data bag that contains the vault

  • name (String)

    the name of the item in the vault

  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • :node_name (String)

    the name of the node to decrypt secrets as. Defaults to the :node_name value of Chef::Config

  • :client_key_path (String)

    the name of the node to decrypt secrets as. Defaults to the :client_key value of Chef::Config


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/chef-vault/item.rb', line 61

def initialize(vault, name, opts = {})
  super() # Don't pass parameters
  @data_bag = vault
  @raw_data["id"] = name
  @keys = ChefVault::ItemKeys.new(vault, "#{name}_keys")
  @secret = generate_secret
  @encrypted = false
  opts = {
    :node_name => Chef::Config[:node_name],
    :client_key_path => Chef::Config[:client_key],
  }.merge(opts)
  @node_name = opts[:node_name]
  @client_key_path = opts[:client_key_path]
  @current_query = search
end

Instance Attribute Details

#client_key_pathString

Returns the path to the private key that is used to decrypt secrets. Defaults to the value of Chef::Config

Returns:

  • (String)

    the path to the private key that is used to decrypt secrets. Defaults to the value of Chef::Config


41
42
43
# File 'lib/chef-vault/item.rb', line 41

def client_key_path
  @client_key_path
end

#encrypted_data_bag_itemnil

Returns this attribute is not currently used

Returns:

  • (nil)

    this attribute is not currently used


31
32
33
# File 'lib/chef-vault/item.rb', line 31

def encrypted_data_bag_item
  @encrypted_data_bag_item
end

#keysChefVault::ItemKeys

Returns the keys associated with this vault

Returns:


27
28
29
# File 'lib/chef-vault/item.rb', line 27

def keys
  @keys
end

#node_nameString

Returns the node name that is used to decrypt secrets. Defaults to the value of Chef::Config

Returns:

  • (String)

    the node name that is used to decrypt secrets. Defaults to the value of Chef::Config


36
37
38
# File 'lib/chef-vault/item.rb', line 36

def node_name
  @node_name
end

Class Method Details

.data_bag_item_type(vault, name) ⇒ Symbol

determines whether a data bag item is a vault, an encrypted data bag item, or a normal data bag item. An item is a vault if:

a) the data bag item contains at least one key whose value is

an hash with the key 'encrypted data'

b) the data bag that contains the item contains a second item

suffixed with _keys

if a) is false, the item is a normal data bag if a) and b) are true, the item is a vault if a) is true but b) is false, the item is an encrypted data

bag item

Parameters:

  • vault (String)

    the name of the data bag

  • name (String)

    the name of the item in the data bag

Returns:

  • (Symbol)

    one of :vault, :encrypted or :normal


336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'lib/chef-vault/item.rb', line 336

def self.data_bag_item_type(vault, name)
  # adapted from https://github.com/opscode-cookbooks/chef-vault/blob/v1.3.0/libraries/chef_vault_item.rb
  # and https://github.com/sensu/sensu-chef/blob/2.9.0/libraries/sensu_helpers.rb
  dbi = Chef::DataBagItem.load(vault, name)
  encrypted = dbi.detect do |_, v|
    v.is_a?(Hash) && v.key?("encrypted_data")
  end

  # return a symbol describing the type of item we detected
  case
  when encrypted && Chef::DataBag.load(vault).key?("#{name}_keys")
    :vault
  when encrypted
    :encrypted
  else
    :normal
  end
end

.load(vault, name, opts = {}) ⇒ Object

loads an existing vault item

Parameters:

  • vault (String)

    the name of the data bag that contains the vault

  • name (String)

    the name of the item in the vault

  • opts (Hash) (defaults to: {})

Options Hash (opts):

  • :node_name (String)

    the name of the node to decrypt secrets as. Defaults to the :node_name value of Chef::Config

  • :client_key_path (String)

    the name of the node to decrypt secrets as. Defaults to the :client_key value of Chef::Config


285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/chef-vault/item.rb', line 285

def self.load(vault, name, opts = {})
  item = new(vault, name, opts)
  item.load_keys(vault, "#{name}_keys")

  begin
    item.raw_data =
      Chef::EncryptedDataBagItem.load(vault, name, item.secret).to_hash
  rescue Net::HTTPServerException => http_error
    if http_error.response.code == "404"
      raise ChefVault::Exceptions::ItemNotFound,
        "#{vault}/#{name} could not be found"
    else
      raise http_error
    end
  rescue Chef::Exceptions::ValidationFailed
    raise ChefVault::Exceptions::ItemNotFound,
      "#{vault}/#{name} could not be found"
  end

  item
end

.vault?(vault, name) ⇒ Boolean

determines if a data bag item looks like a vault

Parameters:

  • vault (String)

    the name of the data bag

  • name (String)

    the name of the item in the data bag

Returns:

  • (Boolean)

    true if the data bag item looks like a vault


316
317
318
# File 'lib/chef-vault/item.rb', line 316

def self.vault?(vault, name)
  :vault == data_bag_item_type(vault, name)
end

Instance Method Details

#[](key) ⇒ Object


212
213
214
215
# File 'lib/chef-vault/item.rb', line 212

def [](key)
  reload_raw_data if @encrypted
  super
end

#[]=(key, value) ⇒ Object


207
208
209
210
# File 'lib/chef-vault/item.rb', line 207

def []=(key, value)
  reload_raw_data if @encrypted
  super
end

#admins(admin_string, action = :add) ⇒ Object


134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/chef-vault/item.rb', line 134

def admins(admin_string, action = :add)
  admin_string.split(",").each do |admin|
    admin.strip!
    admin_key = load_actor(admin, "admins")
    case action
    when :add
      keys.add(admin_key, @secret)
    when :delete
      keys.delete(admin_key)
    else
      raise ChefVault::Exceptions::KeysActionNotValid,
            "#{action} is not a valid action"
    end
  end
end

#clients(search_or_client = search_results, action = :add) ⇒ Object


83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/chef-vault/item.rb', line 83

def clients(search_or_client = search_results, action = :add)
  # for backwards compatibility, if we're handed a string
  # do a search using that string and recurse
  if search_or_client.is_a?(String)
    clients(search_results(search_or_client), action)
  elsif search_or_client.is_a?(Chef::ApiClient)
    handle_client_action(search_or_client, action)
  else
    search_or_client.each do |name|
      begin
        client = load_actor(name, "clients")
        handle_client_action(client, action)
      rescue ChefVault::Exceptions::ClientNotFound
        ChefVault::Log.warn "node '#{name}' has no 'default' public key; skipping"
      end
    end
  end
end

#delete_client(client_name) ⇒ Object


307
308
309
310
# File 'lib/chef-vault/item.rb', line 307

def delete_client(client_name)
  client_key = load_actor(client_name, "clients")
  keys.delete(client_key)
end

#destroyObject


266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
# File 'lib/chef-vault/item.rb', line 266

def destroy
  keys.destroy

  if Chef::Config[:solo_legacy_mode]
    data_bag_path = File.join(Chef::Config[:data_bag_path],
                              data_bag)
    data_bag_item_path = File.join(data_bag_path, @raw_data["id"])

    FileUtils.rm("#{data_bag_item_path}.json")

    nil
  else
    super(data_bag, id)
  end
end

#generate_secret(key_size = 32) ⇒ Object

private


201
202
203
204
205
# File 'lib/chef-vault/item.rb', line 201

def generate_secret(key_size = 32)
  # Defaults to 32 bytes, as this is the size that a Chef
  # Encrypted Data Bag Item will digest all secrets down to anyway
  SecureRandom.random_bytes(key_size)
end

#get_adminsObject


150
151
152
# File 'lib/chef-vault/item.rb', line 150

def get_admins
  keys.admins
end

#get_clientsObject


122
123
124
# File 'lib/chef-vault/item.rb', line 122

def get_clients
  keys.clients
end

#load_keys(vault, keys) ⇒ Object

private


78
79
80
81
# File 'lib/chef-vault/item.rb', line 78

def load_keys(vault, keys)
  @keys = ChefVault::ItemKeys.load(vault, keys)
  @secret = secret
end

#refresh(clean_unknown_clients = false) ⇒ void

This method returns an undefined value.

refreshes a vault by re-processing the search query and adding a secret for any nodes found (including new ones)

Parameters:

  • clean_unknown_clients (Boolean) (defaults to: false)

    remove clients that can no longer be found


360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/chef-vault/item.rb', line 360

def refresh(clean_unknown_clients = false)
  unless search
    raise ChefVault::Exceptions::SearchNotFound,
          "#{vault}/#{item} does not have a stored search_query, "\
          "probably because it was created with an older version "\
          "of chef-vault. Use 'knife vault update' to update the "\
          "databag with the search query."
  end

  # a bit of a misnomer; this doesn't remove unknown
  # admins, just clients which are nodes
  remove_unknown_nodes if clean_unknown_clients

  # re-process the search query to add new clients
  clients

  # save the updated keys only
  save_keys(@raw_data["id"])
end

#remove(key) ⇒ Object


154
155
156
# File 'lib/chef-vault/item.rb', line 154

def remove(key)
  @raw_data.delete(key)
end

#rotate_keys!(clean_unknown_clients = false) ⇒ Object


175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/chef-vault/item.rb', line 175

def rotate_keys!(clean_unknown_clients = false)
  @secret = generate_secret

  # clean existing encrypted data for clients/admins
  keys.clear_encrypted

  unless get_clients.empty?
    # a bit of a misnomer; this doesn't remove unknown
    # admins, just clients which are nodes
    remove_unknown_nodes if clean_unknown_clients
    # re-encrypt the new shared secret for all remaining clients
    clients(get_clients)
  end

  unless get_admins.empty?
    # re-encrypt the new shared secret for all admins
    get_admins.each do |admin|
      admins(admin)
    end
  end

  save
  reload_raw_data
end

#save(item_id = @raw_data["id"]) ⇒ Object


217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/chef-vault/item.rb', line 217

def save(item_id = @raw_data["id"])
  save_keys(item_id)
  # Make sure the item is encrypted before saving
  encrypt! unless @encrypted

  # Now save the encrypted data
  if Chef::Config[:solo_legacy_mode]
    save_solo(item_id)
  else
    begin
      Chef::DataBag.load(data_bag)
    rescue Net::HTTPServerException => http_error
      if http_error.response.code == "404"
        chef_data_bag = Chef::DataBag.new
        chef_data_bag.name data_bag
        chef_data_bag.create
      end
    end

    super
  end
end

#save_keys(item_id = @raw_data["id"]) ⇒ Object


240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/chef-vault/item.rb', line 240

def save_keys(item_id = @raw_data["id"])
  # validate the format of the id before attempting to save
  validate_id!(item_id)

  # ensure that the ID of the vault hasn't changed since the keys
  # data bag item was created
  keys_id = keys["id"].match(/^(.+)_keys/)[1]
  if keys_id != item_id
    raise ChefVault::Exceptions::IdMismatch,
      "id mismatch - input JSON has id '#{item_id}' but vault item has id '#{keys_id}'"
  end

  # save the keys first, raising an error if no keys were defined
  if keys.admins.empty? && keys.clients.empty?
    raise ChefVault::Exceptions::NoKeysDefined,
      "No keys defined for #{item_id}"
  end

  keys.save
end

#search(search_query = nil) ⇒ Object


126
127
128
129
130
131
132
# File 'lib/chef-vault/item.rb', line 126

def search(search_query = nil)
  if search_query
    keys.search_query(search_query)
  else
    keys.search_query
  end
end

#search_results(statement = search) ⇒ Object


102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/chef-vault/item.rb', line 102

def search_results(statement = search)
  @search_results = nil if statement != @current_query
  @current_query = statement
  @search_results ||= begin
    results_returned = false
    results = []
    query = Chef::Search::Query.new
    query.search(:node, statement, filter_result: { name: ["name"] }, rows: 10000) do |node|
      results_returned = true
      results << node["name"]
    end

    unless results_returned
      ChefVault::Log.warn "No clients were returned from search, you may not have "\
        "got what you expected!!"
    end
    results
  end
end

#secretObject


158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/chef-vault/item.rb', line 158

def secret
  if @keys.include?(@node_name)
    private_key = OpenSSL::PKey::RSA.new(File.open(@client_key_path).read())
    begin
      private_key.private_decrypt(Base64.decode64(@keys[@node_name]))
    rescue OpenSSL::PKey::RSAError
      raise ChefVault::Exceptions::SecretDecryption,
        "#{data_bag}/#{id} is encrypted for you, but your private key failed to decrypt the contents.  "\
        "(if you regenerated your client key, have an administrator of the vault run 'knife vault refresh')"
    end
  else
    raise ChefVault::Exceptions::SecretDecryption,
      "#{data_bag}/#{id} is not encrypted with your public key.  "\
      "Contact an administrator of the vault item to encrypt for you!"
  end
end

#to_json(*a) ⇒ Object


261
262
263
264
# File 'lib/chef-vault/item.rb', line 261

def to_json(*a)
  json = super
  json.gsub(self.class.name, self.class.superclass.name)
end