Class: Lockbox

Inherits:
Object
  • Object
show all
Defined in:
lib/lockbox/active_storage_extensions.rb,
lib/lockbox.rb,
lib/lockbox/io.rb,
lib/lockbox/box.rb,
lib/lockbox/model.rb,
lib/lockbox/utils.rb,
lib/lockbox/aes_gcm.rb,
lib/lockbox/railtie.rb,
lib/lockbox/version.rb,
lib/lockbox/encryptor.rb,
lib/lockbox/key_generator.rb,
lib/lockbox/carrier_wave_extensions.rb

Overview

ideally encrypt and decrypt would happen at the blob/service level however, there isn’t really a great place to define encryption settings there instead, we encrypt and decrypt at the attachment level, and we define encryption settings at the model level

Defined Under Namespace

Modules: ActiveStorageExtensions, CarrierWaveExtensions, Model Classes: AES_GCM, Box, DecryptionError, Encryptor, Error, IO, KeyGenerator, PaddingError, Railtie, Utils

Constant Summary collapse

PAD_FIRST_BYTE =
"\x80".b
PAD_ZERO_BYTE =
"\x00".b
VERSION =
"0.2.4"

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Lockbox

Returns a new instance of Lockbox.



91
92
93
94
95
96
97
98
# File 'lib/lockbox.rb', line 91

def initialize(**options)
  options = self.class.default_options.merge(options)
  previous_versions = options.delete(:previous_versions)

  @boxes =
    [Box.new(options)] +
    Array(previous_versions).map { |v| Box.new({key: options[:key]}.merge(v)) }
end

Class Attribute Details

.default_optionsObject

Returns the value of attribute default_options.



34
35
36
# File 'lib/lockbox.rb', line 34

def default_options
  @default_options
end

.master_keyObject



39
40
41
# File 'lib/lockbox.rb', line 39

def self.master_key
  @master_key ||= ENV["LOCKBOX_MASTER_KEY"]
end

Class Method Details

.attribute_key(table:, attribute:, master_key: nil, encode: true) ⇒ Object

Raises:

  • (ArgumentError)


162
163
164
165
166
167
168
169
# File 'lib/lockbox.rb', line 162

def self.attribute_key(table:, attribute:, master_key: nil, encode: true)
  master_key ||= Lockbox.master_key
  raise ArgumentError, "Missing master key" unless master_key

  key = Lockbox::KeyGenerator.new(master_key).attribute_key(table: table, attribute: attribute)
  key = to_hex(key) if encode
  key
end

.generate_keyObject



144
145
146
# File 'lib/lockbox.rb', line 144

def self.generate_key
  SecureRandom.hex(32)
end

.generate_key_pairObject



148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/lockbox.rb', line 148

def self.generate_key_pair
  require "rbnacl"
  # encryption and decryption servers exchange public keys
  # this produces smaller ciphertext than sealed box
  alice = RbNaCl::PrivateKey.generate
  bob = RbNaCl::PrivateKey.generate
  # alice is sending message to bob
  # use bob first in both cases to prevent keys being swappable
  {
    encryption_key: to_hex(bob.public_key.to_bytes + alice.to_bytes),
    decryption_key: to_hex(bob.to_bytes + alice.public_key.to_bytes)
  }
end

.migrate(model, restart: false) ⇒ Object



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
# File 'lib/lockbox.rb', line 43

def self.migrate(model, restart: false)
  # get fields
  fields = model.lockbox_attributes.select { |k, v| v[:migrating] }

  # get blind indexes
  blind_indexes = model.respond_to?(:blind_indexes) ? model.blind_indexes.select { |k, v| v[:migrating] } : {}

  # build relation
  relation = model.unscoped

  unless restart
    attributes = fields.map { |_, v| v[:encrypted_attribute] }
    attributes += blind_indexes.map { |_, v| v[:bidx_attribute] }

    if defined?(ActiveRecord::Base) && model.is_a?(ActiveRecord::Base)
      attributes.each_with_index do |attribute, i|
        relation =
          if i == 0
            relation.where(attribute => nil)
          else
            relation.or(model.unscoped.where(attribute => nil))
          end
      end
    end
  end

  if relation.respond_to?(:find_each)
    relation.find_each do |record|
      migrate_record(record, fields: fields, blind_indexes: blind_indexes, restart: restart)
    end
  else
    relation.all.each do |record|
      migrate_record(record, fields: fields, blind_indexes: blind_indexes, restart: restart)
    end
  end
end

.migrate_record(record, fields:, blind_indexes:, restart:) ⇒ Object

private



81
82
83
84
85
86
87
88
89
# File 'lib/lockbox.rb', line 81

def self.migrate_record(record, fields:, blind_indexes:, restart:)
  fields.each do |k, v|
    record.send("#{v[:attribute]}=", record.send(k)) if restart || !record.send(v[:encrypted_attribute])
  end
  blind_indexes.each do |k, v|
    record.send("compute_#{k}_bidx") if restart || !record.send(v[:bidx_attribute])
  end
  record.save(validate: false) if record.changed?
end

.pad(str, size: 16) ⇒ Object

ISO/IEC 7816-4 same as Libsodium libsodium.gitbook.io/doc/padding apply prior to encryption note: current implementation does not try to minimize side channels

Raises:

  • (ArgumentError)


184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/lockbox.rb', line 184

def self.pad(str, size: 16)
  raise ArgumentError, "Invalid size" if size < 1

  str = str.dup.force_encoding(Encoding::BINARY)

  pad_length = size - 1
  pad_length -= str.bytesize % size

  str << PAD_FIRST_BYTE
  pad_length.times do
    str << PAD_ZERO_BYTE
  end

  str
end

.to_hex(str) ⇒ Object



171
172
173
# File 'lib/lockbox.rb', line 171

def self.to_hex(str)
  str.unpack("H*").first
end

.unpad(str, size: 16) ⇒ Object

note: current implementation does not try to minimize side channels

Raises:

  • (ArgumentError)


202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/lockbox.rb', line 202

def self.unpad(str, size: 16)
  raise ArgumentError, "Invalid size" if size < 1

  if str.encoding != Encoding::BINARY
    str = str.dup.force_encoding(Encoding::BINARY)
  end

  i = 1
  while i <= size
    case str[-i]
    when PAD_ZERO_BYTE
      i += 1
    when PAD_FIRST_BYTE
      return str[0..-(i + 1)]
    else
      break
    end
  end

  raise Lockbox::PaddingError, "Invalid padding"
end

Instance Method Details

#decrypt(ciphertext, **options) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
# File 'lib/lockbox.rb', line 105

def decrypt(ciphertext, **options)
  ciphertext = check_string(ciphertext, "ciphertext")

  # ensure binary
  if ciphertext.encoding != Encoding::BINARY
    # dup to prevent mutation
    ciphertext = ciphertext.dup.force_encoding(Encoding::BINARY)
  end

  @boxes.each_with_index do |box, i|
    begin
      return box.decrypt(ciphertext, **options)
    rescue => e
      # returning DecryptionError instead of PaddingError
      # is for end-user convenience, not for security
      error_classes = [DecryptionError, PaddingError]
      error_classes << RbNaCl::LengthError if defined?(RbNaCl::LengthError)
      error_classes << RbNaCl::CryptoError if defined?(RbNaCl::CryptoError)
      if error_classes.any? { |ec| e.is_a?(ec) }
        raise DecryptionError, "Decryption failed" if i == @boxes.size - 1
      else
        raise e
      end
    end
  end
end

#decrypt_io(io, **options) ⇒ Object



138
139
140
141
142
# File 'lib/lockbox.rb', line 138

def decrypt_io(io, **options)
  new_io = Lockbox::IO.new(decrypt(io.read, **options))
  (io, new_io)
  new_io
end

#encrypt(message, **options) ⇒ Object



100
101
102
103
# File 'lib/lockbox.rb', line 100

def encrypt(message, **options)
  message = check_string(message, "message")
  @boxes.first.encrypt(message, **options)
end

#encrypt_io(io, **options) ⇒ Object



132
133
134
135
136
# File 'lib/lockbox.rb', line 132

def encrypt_io(io, **options)
  new_io = Lockbox::IO.new(encrypt(io.read, **options))
  (io, new_io)
  new_io
end