kms_encrypted 1.1.1 → 1.2.0

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: dd32d5162572d1645342bbf2b41e11f5cdafc5dcd180e3482615f73df03d2158
4
- data.tar.gz: 6751b51e2b74bf292b2b76f88783cf7e9aab8f1243ebbe8a54c8a79e3a51b76e
3
+ metadata.gz: f0f09d385a70037946d973c086b0eea95497df19cc8b572b899bdbb6188b55e2
4
+ data.tar.gz: 2165ab882704315f6321cdac7544ed7db5a1da256187f954d292b92b14dbb35b
5
5
  SHA512:
6
- metadata.gz: 38659f6fa4e22615bba67cf9419c73aa996befc67cb969266d2b46caf6068622e8dab9c90ac63aa60c07ca99c9152eb930a280025999c1513666f5d07c51fe02
7
- data.tar.gz: b9c0be48197d38e34d055fca992568b4736fcf29d6cf638e24598482f92e86c2dd016b09d517d8d43027ec451fd7fb56e75ee10a15b124f4bac390ee421b7fe6
6
+ metadata.gz: 341db4f5ec475a23fce65729360fe625b8e7f6905f870654ff668e8651eb89d03852a0073a53c1c2c9200cd5b33da347d8236a1430b80cdf6c46f6835d995e63
7
+ data.tar.gz: ef0f312ed2695cb1f658968cd15349e9dc1d56982e99b8411e8070d0daa6cbd3e025cd613ddd920e6688f012dc8ad587c472f3f8377031e501ed62b8bd9be663
@@ -1,3 +1,7 @@
1
+ ## 1.2.0 (2020-08-18)
2
+
3
+ - Raise error when trying to rotate key used for encrypted files
4
+
1
5
  ## 1.1.1 (2020-04-16)
2
6
 
3
7
  - Fixed `SystemStackError` with `reload` and CarrierWave
data/README.md CHANGED
@@ -18,19 +18,443 @@ Check out [this post](https://ankane.org/sensitive-data-rails) for more info on
18
18
 
19
19
  ## How It Works
20
20
 
21
- 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
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 attr_encrypted and store the encrypted version in the `encrypted_kms_key` column. For each record, we generate a different data key.
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
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 attr_encrypted to decrypt the data. We can easily track decryptions since we have a different data key for each record.
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
+ ```
86
+
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
+ ```
100
+
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
+ ```
26
114
 
27
115
  ## Getting Started
28
116
 
29
- 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
30
224
 
31
- - [AWS KMS](guides/Amazon.md)
32
- - [Google Cloud KMS](guides/Google.md)
33
- - [Vault](guides/Vault.md)
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.
244
+
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
+ ```
34
458
 
35
459
  ## Outside Models
36
460
 
@@ -107,27 +107,68 @@ module KmsEncrypted
107
107
  }
108
108
  end
109
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
110
120
  define_method("rotate_#{key_method}!") do
111
121
  # decrypt
112
122
  plaintext_attributes = {}
113
123
 
114
124
  # attr_encrypted
115
125
  if self.class.respond_to?(:encrypted_attributes)
116
- self.class.encrypted_attributes.select { |_, v| v[:key] == key_method.to_sym }.keys.each do |key|
117
- plaintext_attributes[key] = send(key)
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
118
132
  end
119
133
  end
120
134
 
121
135
  # lockbox attributes
136
+ # only checks key, not previous versions
122
137
  if self.class.respond_to?(:lockbox_attributes)
123
- self.class.lockbox_attributes.select { |_, v| v[:key] == key_method.to_sym }.keys.each do |key|
124
- plaintext_attributes[key] = send(key)
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
125
144
  end
126
145
  end
127
146
 
128
- # TODO lockbox attachments
129
- # if self.class.respond_to?(:lockbox_attachments)
130
- # end
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
171
+ end
131
172
 
132
173
  # reset key
133
174
  instance_variable_set("@#{key_method}", nil)
@@ -1,3 +1,3 @@
1
1
  module KmsEncrypted
2
- VERSION = "1.1.1"
2
+ VERSION = "1.2.0"
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.1.1
4
+ version: 1.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Andrew Kane
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2020-04-16 00:00:00.000000000 Z
11
+ date: 2020-08-19 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activesupport
@@ -114,14 +114,14 @@ dependencies:
114
114
  requirements:
115
115
  - - ">="
116
116
  - !ruby/object:Gem::Version
117
- version: '0.2'
117
+ version: 0.4.7
118
118
  type: :development
119
119
  prerelease: false
120
120
  version_requirements: !ruby/object:Gem::Requirement
121
121
  requirements:
122
122
  - - ">="
123
123
  - !ruby/object:Gem::Version
124
- version: '0.2'
124
+ version: 0.4.7
125
125
  - !ruby/object:Gem::Dependency
126
126
  name: aws-sdk-kms
127
127
  requirement: !ruby/object:Gem::Requirement
@@ -164,6 +164,20 @@ dependencies:
164
164
  - - ">="
165
165
  - !ruby/object:Gem::Version
166
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'
167
181
  description:
168
182
  email: andrew@chartkick.com
169
183
  executables: []