Class: Lockbox

Inherits:
Object
  • Object
show all
Defined in:
lib/lockbox/active_storage_extensions.rb,
lib/lockbox.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, KeyGenerator, PaddingError, Railtie, Utils

Constant Summary collapse

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

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Lockbox

Returns a new instance of Lockbox.



73
74
75
76
77
78
79
80
# File 'lib/lockbox.rb', line 73

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(v) }
end

Class Attribute Details

.default_optionsObject

Returns the value of attribute default_options.



28
29
30
# File 'lib/lockbox.rb', line 28

def default_options
  @default_options
end

.master_keyObject



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

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)


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

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



112
113
114
# File 'lib/lockbox.rb', line 112

def self.generate_key
  SecureRandom.hex(32)
end

.generate_key_pairObject



116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/lockbox.rb', line 116

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



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

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] }

    attributes.each_with_index do |attribute, i|
      relation =
        if i == 0
          relation.where(attribute => nil)
        else
          relation.or(model.where(attribute => nil))
        end
    end
  end

  # migrate
  relation.find_each do |record|
    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
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)


152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/lockbox.rb', line 152

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



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

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)


170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# File 'lib/lockbox.rb', line 170

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



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/lockbox.rb', line 87

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
      error_classes = [DecryptionError]
      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

#encrypt(message, **options) ⇒ Object



82
83
84
85
# File 'lib/lockbox.rb', line 82

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