kms_encrypted 1.0.0 → 1.2.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 11c711222f049df42c663c9e68a2822fb7e318d3f3fc02f6346801c998ead328
4
- data.tar.gz: 98200a87d8bf02a7398b075aaa6d79dff706a4d15d850584ebd952329980520b
3
+ metadata.gz: 0d6182ffbaae6402f3cfd620f93242fe457a37aeda8609362d7eb08572f020e0
4
+ data.tar.gz: e2241d145e0407fcc6238e94ae653dc98de17538b95b4ee7df8c8ff48a94cbf3
5
5
  SHA512:
6
- metadata.gz: 7b3d37f2739f1a869a8a34c62e9300c3b54b0e8b87b98377883fa252d161aaafcb387044049bf0bfb070e86d481034bcf5c19b0e83d21a4668a513b02f3da151
7
- data.tar.gz: b5596bc03466ac15b09d72cd1e00093eda05e2dcd3ca17607484ff678da808647bb7d364be27b5cfc912cdcccb991cbb55b18fd94206a4cb4510d17eaeb4c0da
6
+ metadata.gz: b696faad41fce6bba45b23f981ec1eb1e557b9048e7e7bc79ebb4f70ee090a0bf0b8dbc68ef9226db88c2d75f3e13a1e04feabba5002a43466b845f9abb30b3c
7
+ data.tar.gz: 569fc18fcb7d7c7751735310867efd5a8411f1756f539cc2073ed3360ea1ca05a761ef3d67694427ee810f3c556d4ef1c7ea122a88ff9ddb763c480ba60f9b61
@@ -1,4 +1,27 @@
1
- ## 1.0.0
1
+ ## 1.2.1 (2020-09-28)
2
+
3
+ - Fixed `Version not active` error when switching keys
4
+
5
+ ## 1.2.0 (2020-08-18)
6
+
7
+ - Raise error when trying to rotate key used for encrypted files
8
+
9
+ ## 1.1.1 (2020-04-16)
10
+
11
+ - Fixed `SystemStackError` with `reload` and CarrierWave
12
+
13
+ ## 1.1.0 (2019-07-09)
14
+
15
+ - Added support for Lockbox
16
+ - Dropped support for Rails 4.2
17
+
18
+ ## 1.0.1 (2019-01-21)
19
+
20
+ - Added support for encryption and decryption outside models
21
+ - Added support for dynamic keys
22
+ - Fixed issue with inheritance
23
+
24
+ ## 1.0.0 (2018-12-17)
2
25
 
3
26
  - Added versioning
4
27
  - Added `context_hash` method
@@ -9,38 +32,38 @@ Breaking changes
9
32
  - ActiveSupport notifications were changed from `generate_data_key` and `decrypt_data_key` to `encrypt` and `decrypt`
10
33
  - AWS KMS uses the `Encrypt` operation instead of `GenerateDataKey`
11
34
 
12
- ## 0.3.0
35
+ ## 0.3.0 (2018-11-11)
13
36
 
14
37
  - Added support for Vault
15
38
  - Removed `KmsEncrypted.kms_client` and `KmsEncrypted.client_options` in favor of `KmsEncrypted.aws_client`
16
39
  - Removed `KmsEncrypted::Google.kms_client` in favor of `KmsEncrypted.google_client`
17
40
 
18
- ## 0.2.0
41
+ ## 0.2.0 (2018-02-23)
19
42
 
20
43
  - Added support for Google KMS
21
44
 
22
- ## 0.1.4
45
+ ## 0.1.4 (2017-12-03)
23
46
 
24
47
  - Added `kms_keys` method to models
25
48
  - Reset data keys when record is reloaded
26
49
  - Added `kms_client`
27
50
  - Added ActiveSupport notifications
28
51
 
29
- ## 0.1.3
52
+ ## 0.1.3 (2017-12-01)
30
53
 
31
54
  - Added test key
32
55
  - Added `client_options`
33
56
  - Allow private or protected `kms_encryption_context` method
34
57
 
35
- ## 0.1.2
58
+ ## 0.1.2 (2017-09-25)
36
59
 
37
60
  - Use `KMS_KEY_ID` env variable by default
38
61
 
39
- ## 0.1.1
62
+ ## 0.1.1 (2017-09-23)
40
63
 
41
64
  - Added key rotation
42
65
  - Added support for multiple keys per record
43
66
 
44
- ## 0.1.0
67
+ ## 0.1.0 (2017-09-23)
45
68
 
46
69
  - First release
@@ -1,4 +1,4 @@
1
- Copyright (c) 2017-2018 Andrew Kane
1
+ Copyright (c) 2017-2020 Andrew Kane
2
2
 
3
3
  MIT License
4
4
 
data/README.md CHANGED
@@ -1,34 +1,482 @@
1
1
  # KMS Encrypted
2
2
 
3
- Simple, secure key management for [attr_encrypted](https://github.com/attr-encrypted/attr_encrypted)
3
+ Simple, secure key management for [Lockbox](https://github.com/ankane/lockbox) and [attr_encrypted](https://github.com/attr-encrypted/attr_encrypted)
4
4
 
5
5
  With KMS Encrypted:
6
6
 
7
7
  - Master encryption keys are not on application servers
8
+ - Encrypt and decrypt permissions can be granted separately
8
9
  - There’s an immutable audit log of all activity
9
10
  - Decryption can be disabled if an attack is detected
10
- - Encrypt and decrypt permissions can be granted separately
11
11
  - It’s easy to rotate keys
12
12
 
13
13
  Supports [AWS KMS](https://aws.amazon.com/kms/), [Google Cloud KMS](https://cloud.google.com/kms/), and [Vault](https://www.vaultproject.io/)
14
14
 
15
+ Check out [this post](https://ankane.org/sensitive-data-rails) for more info on securing sensitive data with Rails
16
+
15
17
  [![Build Status](https://travis-ci.org/ankane/kms_encrypted.svg?branch=master)](https://travis-ci.org/ankane/kms_encrypted)
16
18
 
17
19
  ## How It Works
18
20
 
19
- This approach uses a key management service (KMS) to manage encryption keys and attr_encrypted to do the encryption.
21
+ This approach uses a key management service (KMS) to manage encryption keys and Lockbox / attr_encrypted to do the encryption.
22
+
23
+ To encrypt an attribute, we first generate a data key and encrypt it with the KMS. This is known as [envelope encryption](https://cloud.google.com/kms/docs/envelope-encryption). We pass the unencrypted version to the encryption library and store the encrypted version in the `encrypted_kms_key` column. For each record, we generate a different data key.
24
+
25
+ To decrypt an attribute, we first decrypt the data key with the KMS. Once we have the decrypted key, we pass it to the encryption library to decrypt the data. We can easily track decryptions since we have a different data key for each record.
26
+
27
+ ## Installation
28
+
29
+ Add this line to your application’s Gemfile:
30
+
31
+ ```ruby
32
+ gem 'kms_encrypted'
33
+ ```
34
+
35
+ And follow the instructions for your key management service:
36
+
37
+ - [AWS KMS](#aws-kms)
38
+ - [Google Cloud KMS](#google-cloud-kms)
39
+ - [Vault](#vault)
40
+
41
+ ### AWS KMS
42
+
43
+ Add this line to your application’s Gemfile:
44
+
45
+ ```ruby
46
+ gem 'aws-sdk-kms'
47
+ ```
48
+
49
+ Create an [Amazon Web Services](https://aws.amazon.com/) account if you don’t have one. KMS works great whether or not you run your infrastructure on AWS.
50
+
51
+ Create a [KMS master key](https://console.aws.amazon.com/iam/home#/encryptionKeys) and set it in your environment along with your AWS credentials ([dotenv](https://github.com/bkeepers/dotenv) is great for this)
52
+
53
+ ```sh
54
+ KMS_KEY_ID=arn:aws:kms:...
55
+ AWS_ACCESS_KEY_ID=...
56
+ AWS_SECRET_ACCESS_KEY=...
57
+ ```
58
+
59
+ You can also use the alias
60
+
61
+ ```sh
62
+ KMS_KEY_ID=alias/my-alias
63
+ ```
64
+
65
+ ### Google Cloud KMS
66
+
67
+ Add this line to your application’s Gemfile:
68
+
69
+ ```ruby
70
+ gem 'google-api-client'
71
+ ```
72
+
73
+ Create a [Google Cloud Platform](https://cloud.google.com/) account if you don’t have one. KMS works great whether or not you run your infrastructure on GCP.
74
+
75
+ Create a [KMS key ring and key](https://console.cloud.google.com/iam-admin/kms) and set it in your environment along with your GCP credentials ([dotenv](https://github.com/bkeepers/dotenv) is great for this)
76
+
77
+ ```sh
78
+ KMS_KEY_ID=projects/.../locations/.../keyRings/.../cryptoKeys/...
79
+ ```
80
+
81
+ The Google API client logs requests by default. Be sure to turn off the logger in production or it will leak the plaintext.
82
+
83
+ ```ruby
84
+ Google::Apis.logger = Logger.new(nil)
85
+ ```
20
86
 
21
- To encrypt an attribute, we first generate a data key and encrypt it with the KMS. This is known as [envelope encryption](https://cloud.google.com/kms/docs/envelope-encryption). We pass the unencrypted version to attr_encrypted and store the encrypted version in the `encrypted_kms_key` column. For each record, we generate a different data key.
87
+ ### Vault
88
+
89
+ Add this line to your application’s Gemfile:
90
+
91
+ ```ruby
92
+ gem 'vault'
93
+ ```
94
+
95
+ Enable the [transit](https://www.vaultproject.io/docs/secrets/transit/index.html) secrets engine
96
+
97
+ ```sh
98
+ vault secrets enable transit
99
+ ```
22
100
 
23
- To decrypt an attribute, we first decrypt the data key with the KMS. Once we have the decrypted key, we pass it to attr_encrypted to decrypt the data. We can easily track decryptions since we have a different data key for each record.
101
+ And create a key
102
+
103
+ ```sh
104
+ vault write -f transit/keys/my-key derived=true
105
+ ```
106
+
107
+ Set it in your environment along with your Vault credentials ([dotenv](https://github.com/bkeepers/dotenv) is great for this)
108
+
109
+ ```sh
110
+ KMS_KEY_ID=vault/my-key
111
+ VAULT_ADDR=http://127.0.0.1:8200
112
+ VAULT_TOKEN=secret
113
+ ```
24
114
 
25
115
  ## Getting Started
26
116
 
27
- Follow the instructions for your key management service:
117
+ Create a migration to add a column for the encrypted KMS data keys
118
+
119
+ ```ruby
120
+ add_column :users, :encrypted_kms_key, :text
121
+ ```
122
+
123
+ And update your model
124
+
125
+ ```ruby
126
+ class User < ApplicationRecord
127
+ has_kms_key
128
+
129
+ # Lockbox fields
130
+ encrypts :email, key: :kms_key
131
+
132
+ # Lockbox files
133
+ encrypts_attached :license, key: :kms_key
134
+
135
+ # attr_encrypted fields
136
+ attr_encrypted :email, key: :kms_key
137
+ end
138
+ ```
139
+
140
+ For each encrypted attribute, use the `kms_key` method for its key.
141
+
142
+ ## Auditing & Alerting
143
+
144
+ ### Context
145
+
146
+ Encryption context is used in auditing to identify the data being decrypted. This is the model name and id by default. You can customize this with:
147
+
148
+ ```ruby
149
+ class User < ApplicationRecord
150
+ def kms_encryption_context
151
+ {
152
+ model_name: model_name.to_s,
153
+ model_id: id
154
+ }
155
+ end
156
+ end
157
+ ```
158
+
159
+ The context is used as part of the encryption and decryption process, so it must be a value that doesn’t change. Otherwise, you won’t be able to decrypt. You can [rotate the context](#switching-context) without downtime if needed.
160
+
161
+ ### Order of Events
162
+
163
+ Since the default context includes the id, the data key cannot be encrypted until the record has an id. For new records, the default flow is:
164
+
165
+ 1. Start a database transaction
166
+ 2. Insert the record, getting back the id
167
+ 3. Call KMS to encrypt the data key, passing the id as part of the context
168
+ 4. Update the `encrypted_kms_key` column
169
+ 5. Commit the database transaction
170
+
171
+ With Postgres, you can avoid a network call inside a transaction with:
172
+
173
+ ```ruby
174
+ class User < ApplicationRecord
175
+ has_kms_key eager_encrypt: :fetch_id
176
+ end
177
+ ```
178
+
179
+ This changes the flow to:
180
+
181
+ 1. Prefetch the id with the Postgres `nextval` function
182
+ 2. Call KMS to encrypt the data key, passing the id as part of the context
183
+ 3. Insert the record with the id and encrypted data key
184
+
185
+ If you don’t need the id from the database for context, you can use:
186
+
187
+ ```ruby
188
+ class User < ApplicationRecord
189
+ has_kms_key eager_encrypt: true
190
+ end
191
+ ```
192
+
193
+ ### AWS KMS
194
+
195
+ [AWS CloudTrail](https://aws.amazon.com/cloudtrail/) logs all decryption calls. You can view them in the [CloudTrail console](https://console.aws.amazon.com/cloudtrail/home#/events?EventName=Decrypt). Note that it can take 20 minutes for events to show up. You can also use the AWS CLI.
196
+
197
+ ```sh
198
+ aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=Decrypt
199
+ ```
200
+
201
+ If you haven’t already, enable CloudTrail storage to S3 to ensure events are accessible after 90 days. Later, you can use Amazon Athena and this [table structure](https://www.1strategy.com/blog/2017/07/25/auditing-aws-activity-with-cloudtrail-and-athena/) to query them.
202
+
203
+ Read more about [encryption context here](https://docs.aws.amazon.com/kms/latest/developerguide/encryption-context.html).
204
+
205
+ #### Alerting
206
+
207
+ Set up alerts for suspicious behavior. To get near real-time alerts (20-30 second delay), use CloudWatch Events.
208
+
209
+ First, create a new SNS topic with a name like "decryptions". We’ll use this shortly.
210
+
211
+ Next, open [CloudWatch Events](https://console.aws.amazon.com/cloudwatch/home#rules:) and create a rule to match “Events by Service”. Choose “Key Management Service (KMS)” as the service name and “AWS API Call via CloudTrail” as the event type. For operations, select “Specific Operations” and enter “Decrypt”.
212
+
213
+ Select the SNS topic created earlier as the target and save the rule.
214
+
215
+ To set up an alarm, go to [this page](https://console.aws.amazon.com/cloudwatch/home?#metricsV2:graph=%7E();namespace=AWS/Events;dimensions=RuleName) in CloudWatch Metrics. Find the rule and check “Invocations”. On the “Graphed Metrics” tab, change the statistic to “Sum” and the period to “1 minute”. Finally, click the bell icon to create an alarm for high number of decryptions.
216
+
217
+ While the alarm we created isn’t super sophisticated, this setup provides a great foundation for alerting as your organization grows.
218
+
219
+ You can use the SNS topic or another target to send events to a log provider or [SIEM](https://en.wikipedia.org/wiki/Security_information_and_event_management), where can you do more advanced anomaly detection.
220
+
221
+ You should also use other tools to detect breaches, like an [IDS](https://www.alienvault.com/blogs/security-essentials/open-source-intrusion-detection-tools-a-quick-overview). You can use [Amazon GuardDuty](https://aws.amazon.com/guardduty/) if you run infrastructure on AWS.
222
+
223
+ ### Google Cloud KMS
224
+
225
+ Follow the [instructions here](https://cloud.google.com/kms/docs/logging) to set up data access logging. There is not currently a way to see what data is being decrypted, since the additional authenticated data is not logged. For this reason, we recommend another KMS provider.
226
+
227
+ ### Vault
228
+
229
+ Follow the [instructions here](https://www.vaultproject.io/docs/audit/) to set up data access logging.
230
+
231
+ **Note:** Vault will only verify this value if `derived` was set to true when creating the key. If this is not done, the context cannot be trusted.
232
+
233
+ Context will show up hashed in the audit logs. To get the hash for a record, use:
234
+
235
+ ```ruby
236
+ KmsEncrypted.context_hash(record.kms_encryption_context, path: "file")
237
+ ```
238
+
239
+ The `path` option should point to your audit device. Common paths are `file`, `syslog`, and `socket`.
240
+
241
+ ## Separate Permissions
242
+
243
+ A great feature of KMS is the ability to grant encryption and decryption permission separately.
28
244
 
29
- - [AWS KMS](guides/Amazon.md)
30
- - [Google Cloud KMS](guides/Google.md)
31
- - [Vault](guides/Vault.md)
245
+ Be extremely selective of servers you allow to decrypt.
246
+
247
+ For servers that can only encrypt, clear out the existing data and data key before assigning new values (otherwise, you’ll get a decryption error).
248
+
249
+ ```ruby
250
+ # Lockbox
251
+ user.email_ciphertext = nil
252
+ user.encrypted_kms_key = nil
253
+
254
+ # attr_encrypted
255
+ user.encrypted_email = nil
256
+ user.encrypted_email_iv = nil
257
+ user.encrypted_kms_key = nil
258
+ ```
259
+
260
+ ### AWS KMS
261
+
262
+ To encrypt the data, use an IAM policy with:
263
+
264
+ ```json
265
+ {
266
+ "Version": "2012-10-17",
267
+ "Statement": [
268
+ {
269
+ "Sid": "EncryptData",
270
+ "Effect": "Allow",
271
+ "Action": "kms:Encrypt",
272
+ "Resource": "arn:aws:kms:..."
273
+ }
274
+ ]
275
+ }
276
+ ```
277
+
278
+ To decrypt the data, use an IAM policy with:
279
+
280
+ ```json
281
+ {
282
+ "Version": "2012-10-17",
283
+ "Statement": [
284
+ {
285
+ "Sid": "DecryptData",
286
+ "Effect": "Allow",
287
+ "Action": "kms:Decrypt",
288
+ "Resource": "arn:aws:kms:..."
289
+ }
290
+ ]
291
+ }
292
+ ```
293
+
294
+ ### Google Cloud KMS
295
+
296
+ todo: document
297
+
298
+ ### Vault
299
+
300
+ To encrypt the data, use a policy with:
301
+
302
+ ```hcl
303
+ path "transit/encrypt/my-key"
304
+ {
305
+ capabilities = ["create", "update"]
306
+ }
307
+ ```
308
+
309
+ To decrypt the data, use a policy with:
310
+
311
+ ```hcl
312
+ path "transit/decrypt/my-key"
313
+ {
314
+ capabilities = ["create", "update"]
315
+ }
316
+ ```
317
+
318
+ Apply a policy with:
319
+
320
+ ```sh
321
+ vault policy write encrypt encrypt.hcl
322
+ ```
323
+
324
+ And create a token with specific policies with:
325
+
326
+ ```sh
327
+ vault token create -policy=encrypt -policy=decrypt -no-default-policy
328
+ ```
329
+
330
+ ## Testing
331
+
332
+ For testing, you can prevent network calls to KMS by setting:
333
+
334
+ ```sh
335
+ KMS_KEY_ID=insecure-test-key
336
+ ```
337
+
338
+ ## Key Rotation
339
+
340
+ Key management services allow you to rotate the master key.
341
+
342
+ AWS KMS supports [automatic key rotation](https://docs.aws.amazon.com/kms/latest/developerguide/rotate-keys.html).
343
+
344
+ For Google Cloud, use the Google Cloud Console or API.
345
+
346
+ For Vault, use:
347
+
348
+ ```sh
349
+ vault write -f transit/keys/my-key/rotate
350
+ ```
351
+
352
+ New data will be encrypted with the new master key version. To encrypt existing data with new master key version, run:
353
+
354
+ ```ruby
355
+ User.find_each do |user|
356
+ user.rotate_kms_key!
357
+ end
358
+ ```
359
+
360
+ **Note:** This method does not rotate encrypted files, so avoid calling `rotate_kms_key!` on models with file uploads for now.
361
+
362
+ ### Switching Keys
363
+
364
+ You can change keys within your current KMS or move to a different KMS without downtime. Update your model:
365
+
366
+ ```ruby
367
+ class User < ApplicationRecord
368
+ has_kms_key version: 2, key_id: ENV["KMS_KEY_ID_V2"],
369
+ previous_versions: {
370
+ 1 => {key_id: ENV["KMS_KEY_ID"]}
371
+ }
372
+ end
373
+ ```
374
+
375
+ New data will be encrypted with the new key. To update existing data, use:
376
+
377
+ ```ruby
378
+ User.where("encrypted_kms_key NOT LIKE 'v2:%'").find_each do |user|
379
+ user.rotate_kms_key!
380
+ end
381
+ ```
382
+
383
+ Once all data is updated, you can remove the `previous_versions` option.
384
+
385
+ ### Switching Context
386
+
387
+ You can change your encryption context without downtime. Update your model:
388
+
389
+ ```ruby
390
+ class User < ApplicationRecord
391
+ has_kms_key version: 2,
392
+ previous_versions: {
393
+ 1 => {key_id: ENV["KMS_KEY_ID"]}
394
+ }
395
+
396
+ def kms_encryption_context(version:)
397
+ if version == 1
398
+ # previous context method
399
+ else
400
+ # new context method
401
+ end
402
+ end
403
+ end
404
+ ```
405
+
406
+ New data will be encrypted with the new context. To update existing data, use:
407
+
408
+ ```ruby
409
+ User.where("encrypted_kms_key NOT LIKE 'v2:%'").find_each do |user|
410
+ user.rotate_kms_key!
411
+ end
412
+ ```
413
+
414
+ Once all data is updated, you can remove the `previous_versions` option.
415
+
416
+ ## Multiple Keys Per Record
417
+
418
+ You may want to protect different columns with different data keys (or even master keys).
419
+
420
+ To do this, add another column
421
+
422
+ ```ruby
423
+ add_column :users, :encrypted_kms_key_phone, :text
424
+ ```
425
+
426
+ And update your model
427
+
428
+ ```ruby
429
+ class User < ApplicationRecord
430
+ has_kms_key
431
+ has_kms_key name: :phone, key_id: "..."
432
+
433
+ # Lockbox
434
+ encrypts :email, key: :kms_key
435
+ encrypts :phone, key: :kms_key_phone
436
+
437
+ # attr_encrypted
438
+ attr_encrypted :email, key: :kms_key
439
+ attr_encrypted :phone, key: :kms_key_phone
440
+ end
441
+ ```
442
+
443
+ To rotate keys, use:
444
+
445
+ ```ruby
446
+ user.rotate_kms_key_phone!
447
+ ```
448
+
449
+ For custom context, use:
450
+
451
+ ```ruby
452
+ class User < ApplicationRecord
453
+ def kms_encryption_context_phone
454
+ # some hash
455
+ end
456
+ end
457
+ ```
458
+
459
+ ## Outside Models
460
+
461
+ To encrypt and decrypt outside of models, create a box:
462
+
463
+ ```ruby
464
+ kms = KmsEncrypted::Box.new
465
+ ```
466
+
467
+ You can pass `key_id`, `version`, and `previous_versions` if needed.
468
+
469
+ Encrypt
470
+
471
+ ```ruby
472
+ kms.encrypt(message, context: {model_name: "User", model_id: 123})
473
+ ```
474
+
475
+ Decrypt
476
+
477
+ ```ruby
478
+ kms.decrypt(ciphertext, context: {model_name: "User", model_id: 123})
479
+ ```
32
480
 
33
481
  ## Related Projects
34
482
 
@@ -74,3 +522,12 @@ Everyone is encouraged to help improve this project. Here are a few ways you can
74
522
  - Fix bugs and [submit pull requests](https://github.com/ankane/kms_encrypted/pulls)
75
523
  - Write, clarify, or fix documentation
76
524
  - Suggest or add new features
525
+
526
+ To get started with development and testing:
527
+
528
+ ```sh
529
+ git clone https://github.com/ankane/kms_encrypted.git
530
+ cd kms_encrypted
531
+ bundle install
532
+ bundle exec rake test
533
+ ```
@@ -5,6 +5,7 @@ require "json"
5
5
  require "securerandom"
6
6
 
7
7
  # modules
8
+ require "kms_encrypted/box"
8
9
  require "kms_encrypted/database"
9
10
  require "kms_encrypted/log_subscriber"
10
11
  require "kms_encrypted/model"
@@ -0,0 +1,91 @@
1
+ module KmsEncrypted
2
+ class Box
3
+ attr_reader :key_id, :version, :previous_versions
4
+
5
+ def initialize(key_id: nil, version: nil, previous_versions: nil)
6
+ @key_id = key_id || ENV["KMS_KEY_ID"]
7
+ @version = version || 1
8
+ @previous_versions = previous_versions || {}
9
+ end
10
+
11
+ def encrypt(plaintext, context: nil)
12
+ context = version_context(context, version)
13
+ key_id = version_key_id(version)
14
+ ciphertext = KmsEncrypted::Client.new(key_id: key_id, data_key: true).encrypt(plaintext, context: context)
15
+ "v#{version}:#{encode64(ciphertext)}"
16
+ end
17
+
18
+ def decrypt(ciphertext, context: nil)
19
+ m = /\Av(\d+):/.match(ciphertext)
20
+ if m
21
+ version = m[1].to_i
22
+ ciphertext = ciphertext.sub("v#{version}:", "")
23
+ else
24
+ version = 1
25
+ legacy_context = true
26
+
27
+ # legacy
28
+ if ciphertext.start_with?("$gc$")
29
+ _, _, short_key_id, ciphertext = ciphertext.split("$", 4)
30
+
31
+ # restore key, except for cryptoKeyVersion
32
+ stored_key_id = decode64(short_key_id).split("/")[0..3]
33
+ stored_key_id.insert(0, "projects")
34
+ stored_key_id.insert(2, "locations")
35
+ stored_key_id.insert(4, "keyRings")
36
+ stored_key_id.insert(6, "cryptoKeys")
37
+ key_id = stored_key_id.join("/")
38
+ elsif ciphertext.start_with?("vault:")
39
+ ciphertext = Base64.encode64(ciphertext)
40
+ end
41
+ end
42
+
43
+ key_id ||= version_key_id(version)
44
+ ciphertext = decode64(ciphertext)
45
+ context = version_context(context, version)
46
+
47
+ KmsEncrypted::Client.new(
48
+ key_id: key_id,
49
+ data_key: true,
50
+ legacy_context: legacy_context
51
+ ).decrypt(ciphertext, context: context)
52
+ end
53
+
54
+ private
55
+
56
+ def version_key_id(version)
57
+ key_id =
58
+ if previous_versions[version]
59
+ previous_versions[version][:key_id]
60
+ elsif self.version == version
61
+ self.key_id
62
+ else
63
+ raise KmsEncrypted::Error, "Version not active: #{version}"
64
+ end
65
+
66
+ raise ArgumentError, "Missing key id" unless key_id
67
+
68
+ key_id
69
+ end
70
+
71
+ def version_context(context, version)
72
+ if context.respond_to?(:call)
73
+ if context.arity == 0
74
+ context.call
75
+ else
76
+ context.call(version)
77
+ end
78
+ else
79
+ context
80
+ end
81
+ end
82
+
83
+ def encode64(bytes)
84
+ Base64.strict_encode64(bytes)
85
+ end
86
+
87
+ def decode64(bytes)
88
+ Base64.decode64(bytes)
89
+ end
90
+ end
91
+ end
@@ -8,32 +8,20 @@ module KmsEncrypted
8
8
  @options = record.class.kms_keys[key_method.to_sym]
9
9
  end
10
10
 
11
- def name
12
- options[:name]
11
+ def version
12
+ @version ||= evaluate_option(:version).to_i
13
13
  end
14
14
 
15
- def current_version
16
- @version ||= begin
17
- version = options[:version]
18
- version = record.instance_exec(&version) if version.respond_to?(:call)
19
- version.to_i
20
- end
15
+ def key_id
16
+ @key_id ||= evaluate_option(:key_id)
21
17
  end
22
18
 
23
- def key_version(version)
24
- versions = (options[:previous_versions] || {}).dup
25
- versions[current_version] ||= options.slice(:key_id)
26
-
27
- raise KmsEncrypted::Error, "Version not active: #{version}" unless versions[version]
28
-
29
- key_id = versions[version][:key_id]
30
-
31
- raise ArgumentError, "Missing key id" unless key_id
32
-
33
- key_id
19
+ def previous_versions
20
+ @previous_versions ||= evaluate_option(:previous_versions)
34
21
  end
35
22
 
36
23
  def context(version)
24
+ name = options[:name]
37
25
  context_method = name ? "kms_encryption_context_#{name}" : "kms_encryption_context"
38
26
  if record.method(context_method).arity == 0
39
27
  record.send(context_method)
@@ -43,51 +31,34 @@ module KmsEncrypted
43
31
  end
44
32
 
45
33
  def encrypt(plaintext)
46
- key_id = key_version(current_version)
47
- context = context(current_version)
48
- ciphertext = KmsEncrypted::Client.new(key_id: key_id, data_key: true).encrypt(plaintext, context: context)
49
- "v#{current_version}:#{encode64(ciphertext)}"
34
+ context = context(version)
35
+
36
+ KmsEncrypted::Box.new(
37
+ key_id: key_id,
38
+ version: version,
39
+ previous_versions: previous_versions
40
+ ).encrypt(plaintext, context: context)
50
41
  end
51
42
 
52
43
  def decrypt(ciphertext)
44
+ # determine version for context
53
45
  m = /\Av(\d+):/.match(ciphertext)
54
- if m
55
- version = m[1].to_i
56
- ciphertext = ciphertext.sub("v#{version}:", "")
57
- else
58
- version = 1
59
- context = {} if options[:upgrade_context]
60
- legacy_context = true
61
-
62
- # legacy
63
- if ciphertext.start_with?("$gc$")
64
- _, _, short_key_id, ciphertext = ciphertext.split("$", 4)
65
-
66
- # restore key, except for cryptoKeyVersion
67
- stored_key_id = decode64(short_key_id).split("/")[0..3]
68
- stored_key_id.insert(0, "projects")
69
- stored_key_id.insert(2, "locations")
70
- stored_key_id.insert(4, "keyRings")
71
- stored_key_id.insert(6, "cryptoKeys")
72
- key_id = stored_key_id.join("/")
73
- elsif ciphertext.start_with?("vault:")
74
- ciphertext = Base64.encode64(ciphertext)
75
- end
76
- end
77
-
78
- key_id ||= key_version(version)
79
- context ||= context(version)
80
- ciphertext = decode64(ciphertext)
81
-
82
- KmsEncrypted::Client.new(key_id: key_id, data_key: true, legacy_context: legacy_context).decrypt(ciphertext, context: context)
46
+ ciphertext_version = m ? m[1].to_i : 1
47
+ context = (options[:upgrade_context] && !m) ? {} : context(ciphertext_version)
48
+
49
+ KmsEncrypted::Box.new(
50
+ key_id: key_id,
51
+ version: version,
52
+ previous_versions: previous_versions
53
+ ).decrypt(ciphertext, context: context)
83
54
  end
84
55
 
85
- def encode64(bytes)
86
- Base64.strict_encode64(bytes)
87
- end
56
+ private
88
57
 
89
- def decode64(bytes)
90
- Base64.decode64(bytes)
58
+ def evaluate_option(key)
59
+ opt = options[key]
60
+ opt = record.instance_exec(&opt) if opt.respond_to?(:call)
61
+ opt
91
62
  end
92
63
  end
93
64
  end
@@ -8,12 +8,22 @@ module KmsEncrypted
8
8
  context_method = name ? "kms_encryption_context_#{name}" : "kms_encryption_context"
9
9
 
10
10
  class_eval do
11
- class << self
12
- def kms_keys
13
- @kms_keys ||= {}
14
- end unless respond_to?(:kms_keys)
11
+ @kms_keys ||= {}
12
+
13
+ unless respond_to?(:kms_keys)
14
+ def self.kms_keys
15
+ parent_keys =
16
+ if superclass.respond_to?(:kms_keys)
17
+ superclass.kms_keys
18
+ else
19
+ {}
20
+ end
21
+
22
+ parent_keys.merge(@kms_keys || {})
23
+ end
15
24
  end
16
- kms_keys[key_method.to_sym] = {
25
+
26
+ @kms_keys[key_method.to_sym] = {
17
27
  key_id: key_id,
18
28
  name: name,
19
29
  version: version,
@@ -21,7 +31,7 @@ module KmsEncrypted
21
31
  upgrade_context: upgrade_context
22
32
  }
23
33
 
24
- if kms_keys.size == 1
34
+ if @kms_keys.size == 1
25
35
  after_save :encrypt_kms_keys
26
36
 
27
37
  # fetch all keys together so only need to update database once
@@ -45,16 +55,17 @@ module KmsEncrypted
45
55
  end
46
56
  end
47
57
 
48
- # same pattern as attr_encrypted reload
49
58
  if method_defined?(:reload)
50
- alias_method :reload_without_kms_encrypted, :reload
51
- def reload(*args, &block)
52
- result = reload_without_kms_encrypted(*args, &block)
53
- self.class.kms_keys.keys.each do |key_method|
54
- instance_variable_set("@#{key_method}", nil)
59
+ m = Module.new do
60
+ define_method(:reload) do |*args, &block|
61
+ result = super(*args, &block)
62
+ self.class.kms_keys.keys.each do |key_method|
63
+ instance_variable_set("@#{key_method}", nil)
64
+ end
65
+ result
55
66
  end
56
- result
57
67
  end
68
+ prepend m
58
69
  end
59
70
  end
60
71
 
@@ -96,11 +107,67 @@ module KmsEncrypted
96
107
  }
97
108
  end
98
109
 
110
+ # automatically detects attributes and files where the encryption key is:
111
+ # 1. a symbol that matches kms key method exactly
112
+ # does not detect attributes and files where the encryption key is:
113
+ # 1. callable (warns)
114
+ # 2. a symbol that internally calls kms key method
115
+ # it could try to get the exact key and compare
116
+ # (there's a very small chance this could have false positives)
117
+ # but bias towards simplicity for now
118
+ # TODO possibly raise error for callable keys in 2.0
119
+ # with option to override/specify attributes
99
120
  define_method("rotate_#{key_method}!") do
100
121
  # decrypt
101
122
  plaintext_attributes = {}
102
- self.class.encrypted_attributes.select { |_, v| v[:key] == key_method.to_sym }.keys.each do |key|
103
- plaintext_attributes[key] = send(key)
123
+
124
+ # attr_encrypted
125
+ if self.class.respond_to?(:encrypted_attributes)
126
+ self.class.encrypted_attributes.each do |key, v|
127
+ if v[:key] == key_method.to_sym
128
+ plaintext_attributes[key] = send(key)
129
+ elsif v[:key].respond_to?(:call)
130
+ warn "[kms_encrypted] Can't detect if encrypted attribute uses this key"
131
+ end
132
+ end
133
+ end
134
+
135
+ # lockbox attributes
136
+ # only checks key, not previous versions
137
+ if self.class.respond_to?(:lockbox_attributes)
138
+ self.class.lockbox_attributes.each do |key, v|
139
+ if v[:key] == key_method.to_sym
140
+ plaintext_attributes[key] = send(key)
141
+ elsif v[:key].respond_to?(:call)
142
+ warn "[kms_encrypted] Can't detect if encrypted attribute uses this key"
143
+ end
144
+ end
145
+ end
146
+
147
+ # lockbox attachments
148
+ # only checks key, not previous versions
149
+ if self.class.respond_to?(:lockbox_attachments)
150
+ self.class.lockbox_attachments.each do |key, v|
151
+ if v[:key] == key_method.to_sym
152
+ # can likely add support at some point, but may be complicated
153
+ # ideally use rotate_encryption! from Lockbox
154
+ # but needs access to both old and new keys
155
+ # also need to update database atomically
156
+ raise KmsEncrypted::Error, "Can't rotate key used for encrypted files"
157
+ elsif v[:key].respond_to?(:call)
158
+ warn "[kms_encrypted] Can't detect if encrypted attachment uses this key"
159
+ end
160
+ end
161
+ end
162
+
163
+ # CarrierWave uploaders
164
+ if self.class.respond_to?(:uploaders)
165
+ self.class.uploaders.each do |_, uploader|
166
+ # for simplicity, only checks if key is callable
167
+ if uploader.respond_to?(:lockbox_options) && uploader.lockbox_options[:key].respond_to?(:call)
168
+ warn "[kms_encrypted] Can't detect if encrypted uploader uses this key"
169
+ end
170
+ end
104
171
  end
105
172
 
106
173
  # reset key
@@ -1,3 +1,3 @@
1
1
  module KmsEncrypted
2
- VERSION = "1.0.0"
2
+ VERSION = "1.2.1"
3
3
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: kms_encrypted
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.0.0
4
+ version: 1.2.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andrew Kane
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2018-12-17 00:00:00.000000000 Z
11
+ date: 2020-09-28 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activesupport
@@ -16,14 +16,14 @@ dependencies:
16
16
  requirements:
17
17
  - - ">="
18
18
  - !ruby/object:Gem::Version
19
- version: '0'
19
+ version: '5'
20
20
  type: :runtime
21
21
  prerelease: false
22
22
  version_requirements: !ruby/object:Gem::Requirement
23
23
  requirements:
24
24
  - - ">="
25
25
  - !ruby/object:Gem::Version
26
- version: '0'
26
+ version: '5'
27
27
  - !ruby/object:Gem::Dependency
28
28
  name: bundler
29
29
  requirement: !ruby/object:Gem::Requirement
@@ -108,6 +108,20 @@ dependencies:
108
108
  - - ">="
109
109
  - !ruby/object:Gem::Version
110
110
  version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: lockbox
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: 0.4.7
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: 0.4.7
111
125
  - !ruby/object:Gem::Dependency
112
126
  name: aws-sdk-kms
113
127
  requirement: !ruby/object:Gem::Requirement
@@ -150,6 +164,20 @@ dependencies:
150
164
  - - ">="
151
165
  - !ruby/object:Gem::Version
152
166
  version: '0'
167
+ - !ruby/object:Gem::Dependency
168
+ name: carrierwave
169
+ requirement: !ruby/object:Gem::Requirement
170
+ requirements:
171
+ - - ">="
172
+ - !ruby/object:Gem::Version
173
+ version: '0'
174
+ type: :development
175
+ prerelease: false
176
+ version_requirements: !ruby/object:Gem::Requirement
177
+ requirements:
178
+ - - ">="
179
+ - !ruby/object:Gem::Version
180
+ version: '0'
153
181
  description:
154
182
  email: andrew@chartkick.com
155
183
  executables: []
@@ -160,6 +188,7 @@ files:
160
188
  - LICENSE.txt
161
189
  - README.md
162
190
  - lib/kms_encrypted.rb
191
+ - lib/kms_encrypted/box.rb
163
192
  - lib/kms_encrypted/client.rb
164
193
  - lib/kms_encrypted/clients/aws.rb
165
194
  - lib/kms_encrypted/clients/base.rb
@@ -182,16 +211,15 @@ required_ruby_version: !ruby/object:Gem::Requirement
182
211
  requirements:
183
212
  - - ">="
184
213
  - !ruby/object:Gem::Version
185
- version: '2.2'
214
+ version: '2.4'
186
215
  required_rubygems_version: !ruby/object:Gem::Requirement
187
216
  requirements:
188
217
  - - ">="
189
218
  - !ruby/object:Gem::Version
190
219
  version: '0'
191
220
  requirements: []
192
- rubyforge_project:
193
- rubygems_version: 2.7.6
221
+ rubygems_version: 3.1.2
194
222
  signing_key:
195
223
  specification_version: 4
196
- summary: Simple, secure key management for attr_encrypted
224
+ summary: Simple, secure key management for Lockbox and attr_encrypted
197
225
  test_files: []