• Stars
    star
    235
  • Rank 171,079 (Top 4 %)
  • Language
    Ruby
  • License
    MIT License
  • Created about 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple, secure key management for Lockbox and attr_encrypted

KMS Encrypted

Simple, secure key management for Lockbox and attr_encrypted

With KMS Encrypted:

  • Master encryption keys are not on application servers
  • Encrypt and decrypt permissions can be granted separately
  • There’s an immutable audit log of all activity
  • Decryption can be disabled if an attack is detected
  • It’s easy to rotate keys

Supports AWS KMS, Google Cloud KMS, and Vault

Check out this post for more info on securing sensitive data with Rails

Build Status

How It Works

This approach uses a key management service (KMS) to manage encryption keys and Lockbox / attr_encrypted to do the encryption.

To encrypt an attribute, we first generate a data key and encrypt it with the KMS. This is known as 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.

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.

Installation

Add this line to your application’s Gemfile:

gem "kms_encrypted"

And follow the instructions for your key management service:

AWS KMS

Add this line to your application’s Gemfile:

gem "aws-sdk-kms"

Create an Amazon Web Services account if you don’t have one. KMS works great whether or not you run your infrastructure on AWS.

Create a KMS master key and set it in your environment along with your AWS credentials (dotenv is great for this)

KMS_KEY_ID=arn:aws:kms:...
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...

You can also use the alias

KMS_KEY_ID=alias/my-alias

Google Cloud KMS

Add this line to your application’s Gemfile:

gem "google-cloud-kms"

Create a Google Cloud Platform account if you don’t have one. KMS works great whether or not you run your infrastructure on GCP.

Create a KMS key ring and key and set it in your environment along with your GCP credentials (dotenv is great for this)

KMS_KEY_ID=projects/my-project/locations/global/keyRings/my-key-ring/cryptoKeys/my-key

Vault

Add this line to your application’s Gemfile:

gem "vault"

Enable the transit secrets engine

vault secrets enable transit

And create a key

vault write -f transit/keys/my-key derived=true

Set it in your environment along with your Vault credentials (dotenv is great for this)

KMS_KEY_ID=vault/my-key
VAULT_ADDR=http://127.0.0.1:8200
VAULT_TOKEN=secret

Getting Started

Create a migration to add a column for the encrypted KMS data keys

add_column :users, :encrypted_kms_key, :text

And update your model

class User < ApplicationRecord
  has_kms_key

  # Lockbox fields
  has_encrypted :email, key: :kms_key

  # Lockbox files
  encrypts_attached :license, key: :kms_key

  # attr_encrypted fields
  attr_encrypted :email, key: :kms_key
end

For each encrypted attribute, use the kms_key method for its key.

Auditing & Alerting

Context

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:

class User < ApplicationRecord
  def kms_encryption_context
    {
      model_name: model_name.to_s,
      model_id: id
    }
  end
end

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 without downtime if needed.

Order of Events

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:

  1. Start a database transaction
  2. Insert the record, getting back the id
  3. Call KMS to encrypt the data key, passing the id as part of the context
  4. Update the encrypted_kms_key column
  5. Commit the database transaction

With Postgres, you can avoid a network call inside a transaction with:

class User < ApplicationRecord
  has_kms_key eager_encrypt: :fetch_id
end

This changes the flow to:

  1. Prefetch the id with the Postgres nextval function
  2. Call KMS to encrypt the data key, passing the id as part of the context
  3. Insert the record with the id and encrypted data key

If you don’t need the id from the database for context, you can use:

class User < ApplicationRecord
  has_kms_key eager_encrypt: true
end

AWS KMS

AWS CloudTrail logs all decryption calls. You can view them in the CloudTrail console. Note that it can take 20 minutes for events to show up. You can also use the AWS CLI.

aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=Decrypt

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 to query them.

Read more about encryption context here.

Alerting

Set up alerts for suspicious behavior. To get near real-time alerts (20-30 second delay), use CloudWatch Events.

First, create a new SNS topic with a name like "decryptions". We’ll use this shortly.

Next, open CloudWatch Events 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”.

Select the SNS topic created earlier as the target and save the rule.

To set up an alarm, go to this page 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.

While the alarm we created isn’t super sophisticated, this setup provides a great foundation for alerting as your organization grows.

You can use the SNS topic or another target to send events to a log provider or SIEM, where can you do more advanced anomaly detection.

You should also use other tools to detect breaches, like an IDS. You can use Amazon GuardDuty if you run infrastructure on AWS.

Google Cloud KMS

Follow the instructions here 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.

Vault

Follow the instructions here to set up data access logging.

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.

Context will show up hashed in the audit logs. To get the hash for a record, use:

KmsEncrypted.context_hash(record.kms_encryption_context, path: "file")

The path option should point to your audit device. Common paths are file, syslog, and socket.

Separate Permissions

A great feature of KMS is the ability to grant encryption and decryption permission separately.

Be extremely selective of servers you allow to decrypt.

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).

# Lockbox
user.email_ciphertext = nil
user.encrypted_kms_key = nil

# attr_encrypted
user.encrypted_email = nil
user.encrypted_email_iv = nil
user.encrypted_kms_key = nil

AWS KMS

To encrypt the data, use an IAM policy with:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "EncryptData",
            "Effect": "Allow",
            "Action": "kms:Encrypt",
            "Resource": "arn:aws:kms:..."
        }
    ]
}

To decrypt the data, use an IAM policy with:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "DecryptData",
            "Effect": "Allow",
            "Action": "kms:Decrypt",
            "Resource": "arn:aws:kms:..."
        }
    ]
}

Google Cloud KMS

todo: document

Vault

To encrypt the data, use a policy with:

path "transit/encrypt/my-key"
{
  capabilities = ["create", "update"]
}

To decrypt the data, use a policy with:

path "transit/decrypt/my-key"
{
  capabilities = ["create", "update"]
}

Apply a policy with:

vault policy write encrypt encrypt.hcl

And create a token with specific policies with:

vault token create -policy=encrypt -policy=decrypt -no-default-policy

Testing

For testing, you can prevent network calls to KMS by setting:

KMS_KEY_ID=insecure-test-key

In a Rails application, you can also create config/initializers/kms_encrypted.rb with:

KmsEncrypted.key_id = Rails.env.test? ? "insecure-test-key" : ENV["KMS_KEY_ID"]

Key Rotation

Key management services allow you to rotate the master key without any code changes.

  • For AWS KMS, you can use automatic key rotation
  • For Google Cloud, use the Google Cloud Console or API
  • For Vault, use:
vault write -f transit/keys/my-key/rotate

New data will be encrypted with the new master key version. To encrypt existing data with new master key version, run:

User.find_each do |user|
  user.rotate_kms_key!
end

Note: This method does not rotate encrypted files, so avoid calling rotate_kms_key! on models with file uploads for now.

Switching Keys

You can change keys within your current KMS or move to a different KMS without downtime. Update your model:

class User < ApplicationRecord
  has_kms_key version: 2, key_id: ENV["KMS_KEY_ID_V2"],
    previous_versions: {
      1 => {key_id: ENV["KMS_KEY_ID"]}
    }
end

New data will be encrypted with the new key. To update existing data, use:

User.where("encrypted_kms_key NOT LIKE 'v2:%'").find_each do |user|
  user.rotate_kms_key!
end

Once all data is updated, you can remove the previous_versions option.

Switching Context

You can change your encryption context without downtime. Update your model:

class User < ApplicationRecord
  has_kms_key version: 2,
    previous_versions: {
      1 => {key_id: ENV["KMS_KEY_ID"]}
    }

  def kms_encryption_context(version:)
    if version == 1
      # previous context method
    else
      # new context method
    end
  end
end

New data will be encrypted with the new context. To update existing data, use:

User.where("encrypted_kms_key NOT LIKE 'v2:%'").find_each do |user|
  user.rotate_kms_key!
end

Once all data is updated, you can remove the previous_versions option.

Multiple Keys Per Record

You may want to protect different columns with different data keys (or even master keys).

To do this, add another column

add_column :users, :encrypted_kms_key_phone, :text

And update your model

class User < ApplicationRecord
  has_kms_key
  has_kms_key name: :phone, key_id: "..."

  # Lockbox
  has_encrypted :email, key: :kms_key
  has_encrypted :phone, key: :kms_key_phone

  # attr_encrypted
  attr_encrypted :email, key: :kms_key
  attr_encrypted :phone, key: :kms_key_phone
end

To rotate keys, use:

user.rotate_kms_key_phone!

For custom context, use:

class User < ApplicationRecord
  def kms_encryption_context_phone
    # some hash
  end
end

Outside Models

To encrypt and decrypt outside of models, create a box:

kms = KmsEncrypted::Box.new

You can pass key_id, version, and previous_versions if needed.

Encrypt

kms.encrypt(message, context: {model_name: "User", model_id: 123})

Decrypt

kms.decrypt(ciphertext, context: {model_name: "User", model_id: 123})

Related Projects

To securely search encrypted data, check out Blind Index.

Upgrading

1.0

KMS Encrypted 1.0 brings a number of improvements. Here are a few breaking changes to be aware of:

  • There’s now a default encryption context with the model name and id
  • ActiveSupport notifications were changed from generate_data_key and decrypt_data_key to encrypt and decrypt
  • AWS KMS uses the Encrypt operation instead of GenerateDataKey

If you didn’t previously use encryption context, add the upgrade_context option to your models:

class User < ApplicationRecord
  has_kms_key upgrade_context: true
end

Then run:

User.where("encrypted_kms_key NOT LIKE 'v1:%'").find_each do |user|
  user.rotate_kms_key!
end

And remove the upgrade_context option.

History

View the changelog

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

To get started with development and testing:

git clone https://github.com/ankane/kms_encrypted.git
cd kms_encrypted
bundle install
bundle exec rake test

More Repositories

1

pghero

A performance dashboard for Postgres
Ruby
7,123
star
2

searchkick

Intelligent search made easy
Ruby
6,257
star
3

chartkick

Create beautiful JavaScript charts with one line of Ruby
Ruby
6,157
star
4

blazer

Business intelligence made simple
Ruby
4,511
star
5

ahoy

Simple, powerful, first-party analytics for Rails
Ruby
3,872
star
6

strong_migrations

Catch unsafe migrations in development
Ruby
3,662
star
7

groupdate

The simplest way to group temporal data
Ruby
3,617
star
8

pgsync

Sync data from one Postgres database to another
Ruby
2,787
star
9

the-ultimate-guide-to-ruby-timeouts

Timeouts for popular Ruby gems
Ruby
2,212
star
10

production_rails

Best practices for running Rails in production
1,975
star
11

dexter

The automatic indexer for Postgres
Ruby
1,491
star
12

lockbox

Modern encryption for Ruby and Rails
Ruby
1,290
star
13

chartkick.js

Create beautiful charts with one line of JavaScript
JavaScript
1,211
star
14

react-chartkick

Create beautiful JavaScript charts with one line of React
JavaScript
1,183
star
15

pretender

Log in as another user in Rails
Ruby
1,124
star
16

ahoy_email

First-party email analytics for Rails
Ruby
1,051
star
17

secure_rails

Rails security best practices
954
star
18

pgslice

Postgres partitioning as easy as pie
Ruby
953
star
19

mailkick

Email subscriptions for Rails
Ruby
847
star
20

vue-chartkick

Create beautiful JavaScript charts with one line of Vue
JavaScript
747
star
21

eps

Machine learning for Ruby
Ruby
609
star
22

awesome-legal

Awesome free legal documents for companies
589
star
23

searchjoy

Search analytics made easy
Ruby
579
star
24

polars-ruby

Blazingly fast DataFrames for Ruby
Ruby
563
star
25

torch.rb

Deep learning for Ruby, powered by LibTorch
Ruby
552
star
26

blind_index

Securely search encrypted database fields
Ruby
470
star
27

safely

Rescue and report exceptions in non-critical code
Ruby
470
star
28

authtrail

Track Devise login activity
Ruby
466
star
29

multiverse

Multiple databases for Rails 🎉
Ruby
463
star
30

ahoy.js

Simple, powerful JavaScript analytics
JavaScript
463
star
31

hightop

A nice shortcut for group count queries
Ruby
462
star
32

field_test

A/B testing for Rails
Ruby
460
star
33

s3tk

A security toolkit for Amazon S3
Python
439
star
34

disco

Recommendations for Ruby and Rails using collaborative filtering
Ruby
431
star
35

active_median

Median and percentile for Active Record, Mongoid, arrays, and hashes
Ruby
427
star
36

informers

State-of-the-art natural language processing for Ruby
Ruby
417
star
37

notable

Track notable requests and background jobs
Ruby
402
star
38

shorts

Short, random tutorials and posts
379
star
39

tensorflow-ruby

Deep learning for Ruby
Ruby
350
star
40

distribute_reads

Scale database reads to replicas in Rails
Ruby
328
star
41

slowpoke

Rack::Timeout enhancements for Rails
Ruby
327
star
42

prophet-ruby

Time series forecasting for Ruby
Ruby
321
star
43

rover

Simple, powerful data frames for Ruby
Ruby
311
star
44

groupdate.sql

The simplest way to group temporal data
PLpgSQL
280
star
45

jetpack

A friendly package manager for R
R
234
star
46

neighbor

Nearest neighbor search for Rails and Postgres
Ruby
230
star
47

rollup

Rollup time-series data in Rails
Ruby
230
star
48

hypershield

Shield sensitive data in Postgres and MySQL
Ruby
227
star
49

logstop

Keep personal data out of your logs
Ruby
218
star
50

pdscan

Scan your data stores for unencrypted personal data (PII)
Go
213
star
51

delete_in_batches

Fast batch deletes for Active Record and Postgres
Ruby
202
star
52

vega-ruby

Interactive charts for Ruby, powered by Vega and Vega-Lite
Ruby
192
star
53

mapkick

Create beautiful JavaScript maps with one line of Ruby
Ruby
173
star
54

dbx

A fast, easy-to-use database library for R
R
171
star
55

fastText-ruby

Efficient text classification and representation learning for Ruby
Ruby
162
star
56

autosuggest

Autocomplete suggestions based on what your users search
Ruby
162
star
57

swipeout

Swipe-to-delete goodness for the mobile web
JavaScript
159
star
58

pghero.sql

Postgres insights made easy
PLpgSQL
154
star
59

mainstreet

Address verification for Ruby and Rails
Ruby
149
star
60

or-tools-ruby

Operations research tools for Ruby
Ruby
139
star
61

mapkick.js

Create beautiful, interactive maps with one line of JavaScript
JavaScript
138
star
62

trend-ruby

Anomaly detection and forecasting for Ruby
Ruby
128
star
63

mitie-ruby

Named-entity recognition for Ruby
Ruby
122
star
64

barkick

Barcodes made easy
Ruby
120
star
65

ownership

Code ownership for Rails
Ruby
111
star
66

anomaly

Easy-to-use anomaly detection for Ruby
Ruby
98
star
67

errbase

Common exception reporting for a variety of services
Ruby
87
star
68

tokenizers-ruby

Fast state-of-the-art tokenizers for Ruby
Rust
81
star
69

ip_anonymizer

IP address anonymizer for Ruby and Rails
Ruby
79
star
70

str_enum

String enums for Rails
Ruby
75
star
71

faiss-ruby

Efficient similarity search and clustering for Ruby
C++
73
star
72

trend-api

Anomaly detection and forecasting API
R
71
star
73

archer

Rails console history for Heroku, Docker, and more
Ruby
70
star
74

onnxruntime-ruby

Run ONNX models in Ruby
Ruby
70
star
75

xgboost-ruby

High performance gradient boosting for Ruby
Ruby
69
star
76

secure-spreadsheet

Encrypt and password protect sensitive CSV and XLSX files
JavaScript
66
star
77

active_hll

HyperLogLog for Rails and Postgres
Ruby
66
star
78

guess

Statistical gender detection for Ruby
Ruby
60
star
79

morph

An encrypted, in-memory, key-value store
C++
59
star
80

lightgbm-ruby

High performance gradient boosting for Ruby
Ruby
56
star
81

midas-ruby

Edge stream anomaly detection for Ruby
Ruby
54
star
82

moves

Ruby client for Moves
Ruby
54
star
83

blingfire-ruby

High speed text tokenization for Ruby
Ruby
54
star
84

vowpalwabbit-ruby

Fast online machine learning for Ruby
Ruby
52
star
85

xlearn-ruby

High performance factorization machines for Ruby
Ruby
51
star
86

tomoto-ruby

High performance topic modeling for Ruby
C++
51
star
87

trove

Deploy machine learning models in Ruby (and Rails)
Ruby
50
star
88

mapkick-static

Create beautiful static maps with one line of Ruby
Ruby
42
star
89

ahoy_events

Simple, powerful event tracking for Rails
Ruby
42
star
90

practical-search

Let’s make search a better experience for our users
40
star
91

breakout-ruby

Breakout detection for Ruby
Ruby
40
star
92

plu

Price look-up codes made easy
Ruby
40
star
93

ngt-ruby

High-speed approximate nearest neighbors for Ruby
Ruby
39
star
94

gindex

Concurrent index migrations for Rails
Ruby
39
star
95

clockwork_web

A web interface for Clockwork
Ruby
38
star
96

ahoy_guide

A foundation of knowledge and libraries for solid analytics
38
star
97

notable_web

A web interface for Notable
HTML
36
star
98

AnomalyDetection.rb

Time series anomaly detection for Ruby
Ruby
34
star
99

khiva-ruby

High-performance time series algorithms for Ruby
Ruby
34
star
100

immudb-ruby

Ruby client for immudb, the immutable database
Ruby
34
star