devise-two-factor 4.1.1 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- checksums.yaml.gz.sig +0 -0
- data/.github/dependabot.yml +6 -0
- data/.github/workflows/ci.yml +3 -18
- data/.markdownlint.json +6 -0
- data/CHANGELOG.md +15 -0
- data/README.md +109 -63
- data/SECURITY.md +5 -0
- data/UPGRADING.md +218 -2
- data/devise-two-factor.gemspec +4 -7
- data/gemfiles/rails_7.0.gemfile +2 -2
- data/gemfiles/{rails_4.1.gemfile → rails_7.1.gemfile} +2 -2
- data/lib/devise-two-factor.rb +11 -5
- data/lib/devise_two_factor/models/two_factor_authenticatable.rb +32 -17
- data/lib/devise_two_factor/models/two_factor_backupable.rb +3 -2
- data/lib/devise_two_factor/spec_helpers/two_factor_authenticatable_shared_examples.rb +6 -18
- data/lib/devise_two_factor/spec_helpers/two_factor_backupable_shared_examples.rb +2 -2
- data/lib/devise_two_factor/strategies/two_factor_authenticatable.rb +1 -1
- data/lib/devise_two_factor/strategies/two_factor_backupable.rb +0 -3
- data/lib/devise_two_factor/version.rb +1 -1
- data/lib/generators/devise_two_factor/devise_two_factor_generator.rb +2 -7
- data/spec/devise/models/two_factor_authenticatable_spec.rb +11 -69
- data/spec/devise/models/two_factor_backupable_spec.rb +11 -2
- data/spec/spec_helper.rb +0 -1
- data.tar.gz.sig +0 -0
- metadata +15 -57
- metadata.gz.sig +0 -0
- data/gemfiles/rails_4.2.gemfile +0 -8
- data/gemfiles/rails_5.0.gemfile +0 -8
- data/gemfiles/rails_5.1.gemfile +0 -8
- data/gemfiles/rails_5.2.gemfile +0 -8
- data/gemfiles/rails_6.0.gemfile +0 -8
- data/gemfiles/rails_6.1.gemfile +0 -8
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA256:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 131bab7308f2b9d46a41b5e11b85411e0cd097e97f16c82356eadb1cf87d5cc3
|
4
|
+
data.tar.gz: b117115cfbb9ffe4f6dcec8127de0e0d51ca5fa835407a82cad8afc17f923f5f
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: 187bd4ed05b0ad83da40cbe208c4bbe2ce91581d95f437cdaa27364ddb0be3696a2a03aad62e8a02f07adaeca24778202710f20f79422156b4aef63d13a03721
|
7
|
+
data.tar.gz: 5635dccf010dd259404e9e03092eb9e107896b31f178d1ae3760046aa794fe449eb3bd2929bfb08c29df725376d8abc3dbb3f80e2dfb63405172c6130c24c687
|
checksums.yaml.gz.sig
CHANGED
Binary file
|
data/.github/workflows/ci.yml
CHANGED
@@ -12,29 +12,14 @@ jobs:
|
|
12
12
|
fail-fast: false
|
13
13
|
matrix:
|
14
14
|
# Due to https://github.com/actions/runner/issues/849, we should quote versions
|
15
|
-
ruby: ['
|
16
|
-
rails: ['
|
17
|
-
exclude:
|
18
|
-
- { ruby: '2.3', rails: '7.0' }
|
19
|
-
- { ruby: '2.4', rails: '7.0' }
|
20
|
-
- { ruby: '2.5', rails: '7.0' }
|
21
|
-
- { ruby: '2.6', rails: '7.0' }
|
22
|
-
- { ruby: '2.3', rails: '6.0' }
|
23
|
-
- { ruby: '2.3', rails: '6.1' }
|
24
|
-
- { ruby: '2.4', rails: '6.0' }
|
25
|
-
- { ruby: '2.4', rails: '6.1' }
|
26
|
-
- { ruby: '2.7', rails: '4.1' }
|
27
|
-
- { ruby: '2.7', rails: '4.2' }
|
28
|
-
- { ruby: '3.0', rails: '4.1' }
|
29
|
-
- { ruby: '3.0', rails: '4.2' }
|
30
|
-
- { ruby: 'truffleruby-head', rails: '4.1' }
|
31
|
-
- { ruby: 'truffleruby-head', rails: '4.2' }
|
15
|
+
ruby: ['3.1', '3.2', '3.3', 'truffleruby-head']
|
16
|
+
rails: ['7.0', '7.1']
|
32
17
|
|
33
18
|
name: Ruby ${{ matrix.ruby }}, Rails ${{ matrix.rails }}
|
34
19
|
env: # $BUNDLE_GEMFILE must be set at the job level, so it is set for all steps
|
35
20
|
BUNDLE_GEMFILE: ${{ github.workspace }}/gemfiles/rails_${{ matrix.rails }}.gemfile
|
36
21
|
steps:
|
37
|
-
- uses: actions/checkout@
|
22
|
+
- uses: actions/checkout@v4
|
38
23
|
- name: Set up Ruby
|
39
24
|
uses: ruby/setup-ruby@v1
|
40
25
|
with:
|
data/.markdownlint.json
ADDED
data/CHANGELOG.md
CHANGED
@@ -2,6 +2,21 @@
|
|
2
2
|
|
3
3
|
## Unreleased
|
4
4
|
|
5
|
+
## 5.1.0
|
6
|
+
|
7
|
+
- Remove faker dev dependency
|
8
|
+
- Insert two_factor_authenticatable at the top of the devise module list
|
9
|
+
- README and CI improvements
|
10
|
+
|
11
|
+
## 5.0.0
|
12
|
+
|
13
|
+
**Breaking Changes**
|
14
|
+
- attr_encrypted has been deprecated in favor of native Rails attribute encryption. See [UPGRADING.md](UPGRADING.md) for details on how to migrate your records. You **must** use or build a migration strategy (see examples in [UPGRADING.md](UPGRADING.md)) to use existing data!
|
15
|
+
- Rails 7 is now required.
|
16
|
+
|
17
|
+
## 4.1.0 / 4.1.1
|
18
|
+
- Add support for attr_encrypted v4
|
19
|
+
|
5
20
|
## 4.0.2
|
6
21
|
- Add Rails 7.0 support
|
7
22
|
- Renew signing certificate
|
data/README.md
CHANGED
@@ -1,7 +1,6 @@
|
|
1
1
|
# Devise-Two-Factor Authentication
|
2
|
-
By [Tinfoil Security](https://www.tinfoilsecurity.com/) (acq. [Synopsys](https://www.synopsys.com/) 2020). Interested in [working with us](https://www.synopsys.com/careers.html)? We're hiring!
|
3
2
|
|
4
|
-

|
5
4
|
|
6
5
|
Devise-Two-Factor is a minimalist extension to Devise which offers support for two-factor authentication, through the [TOTP](https://en.wikipedia.org/wiki/Time-based_One-Time_Password) scheme. It:
|
7
6
|
|
@@ -11,89 +10,109 @@ Devise-Two-Factor is a minimalist extension to Devise which offers support for t
|
|
11
10
|
* Is extensible, and includes two-factor backup codes as an example of how plugins can be structured
|
12
11
|
|
13
12
|
## Contributing
|
13
|
+
|
14
14
|
We welcome pull requests, bug reports, and other contributions. We're especially looking for help getting this gem fully compatible with Rails 5+ and squashing any deprecation messages.
|
15
15
|
|
16
16
|
## Example App
|
17
|
-
An example Rails 4 application is provided in the `demo` directory. It showcases a minimal example of Devise-Two-Factor in action, and can act as a reference for integrating the gem into your own application.
|
18
17
|
|
19
|
-
|
18
|
+
See [examples](demo/README.md).
|
20
19
|
|
21
20
|
## Getting Started
|
22
|
-
|
21
|
+
|
22
|
+
Devise-Two-Factor doesn't require much to get started, but there are two prerequisites before you can start using it in your application:
|
23
|
+
|
24
|
+
1. A Rails application with [devise](https://github.com/heartcombo/devise) installed
|
25
|
+
1. Secrets configured for ActiveRecord encrypted attributes
|
23
26
|
|
24
27
|
First, you'll need a Rails application setup with Devise. Visit the Devise [homepage](https://github.com/plataformatec/devise) for instructions.
|
25
28
|
|
26
|
-
|
29
|
+
Devise-Two-Factor uses [ActiveRecord encrypted attributes](https://edgeguides.rubyonrails.org/active_record_encryption.html). If you haven't already set up ActiveRecord encryption you must generate a key set and configure your application to use them either with Rails' encrypted credentials or from another source such as environment variables.
|
27
30
|
|
28
|
-
```
|
29
|
-
|
31
|
+
```bash
|
32
|
+
# Generates a random key set and outputs it to stdout
|
33
|
+
./bin/rails db:encryption:init
|
30
34
|
```
|
31
35
|
|
32
|
-
|
33
|
-
|
34
|
-
```ruby
|
35
|
-
devise :two_factor_authenticatable,
|
36
|
-
:otp_secret_encryption_key => ENV['YOUR_ENCRYPTION_KEY_HERE']
|
36
|
+
You can load the key set using Rails' credentials.
|
37
37
|
|
38
|
+
```bash
|
39
|
+
# Copy the generated key set into your encrypted credentials file
|
40
|
+
# Setting the EDITOR environment variable is optional, but without it your default editor will open
|
41
|
+
EDITOR="code --wait" ./bin/rails credentials:edit
|
38
42
|
```
|
39
43
|
|
40
|
-
|
44
|
+
To learn more about credentials run `./bin/rails credentials:help`.
|
45
|
+
|
46
|
+
Alternatively, you can configure your application with environment variables rather than Rails' credentials.
|
41
47
|
|
42
48
|
```ruby
|
43
|
-
|
49
|
+
# Copy the generate key set and set them as environment variables
|
50
|
+
|
51
|
+
config.active_record.encryption.primary_key = ENV['ACTIVE_RECORD_ENCRYPTION_PRIMARY_KEY']
|
52
|
+
config.active_record.encryption.deterministic_key = ENV['ACTIVE_RECORD_ENCRYPTION_DETERMINISTIC_KEY']
|
53
|
+
config.active_record.encryption.key_derivation_salt = ENV['ACTIVE_RECORD_ENCRYPTION_KEY_DERIVATION_SALT']
|
44
54
|
```
|
45
55
|
|
46
|
-
|
56
|
+
Add Devise-Two-Factor to your Gemfile with:
|
47
57
|
|
48
|
-
|
58
|
+
```ruby
|
59
|
+
# Gemfile
|
49
60
|
|
50
|
-
|
51
|
-
|
52
|
-
* encrypted_otp_secret_salt
|
53
|
-
* consumed_timestep
|
54
|
-
* otp_required_for_login
|
61
|
+
gem 'devise-two-factor'
|
62
|
+
```
|
55
63
|
|
56
|
-
|
64
|
+
There is a generator which automates most of the setup:
|
57
65
|
|
58
|
-
```
|
59
|
-
|
66
|
+
```bash
|
67
|
+
# MODEL is the name of the model you wish to configure devise_two_factor e.g. User or Admin
|
68
|
+
./bin/rails generate devise_two_factor MODEL
|
60
69
|
```
|
61
70
|
|
62
|
-
|
71
|
+
Where `MODEL` is the name of the model you wish to add two-factor functionality to (for example `user`)
|
63
72
|
|
64
|
-
|
73
|
+
This generator will:
|
65
74
|
|
66
|
-
|
75
|
+
1. Create a new migration which adds a few columns to the specified model:
|
67
76
|
|
68
|
-
```ruby
|
69
|
-
|
77
|
+
```ruby
|
78
|
+
add_column :users, :otp_secret, :string
|
79
|
+
add_column :users, :consumed_timestep, :integer
|
80
|
+
add_column :users, :otp_required_for_login, :boolean
|
81
|
+
```
|
70
82
|
|
71
|
-
|
83
|
+
1. Edit `app/models/MODEL.rb` (where MODEL is your model name):
|
84
|
+
* add the `:two_factor_authenticatable` devise module
|
85
|
+
* remove the `:database_authenticatable` if present because it is incompatible with `:two_factor_authenticatable`
|
86
|
+
1. Add a Warden config block to your Devise initializer, which enables the strategies required for two-factor authentication.
|
72
87
|
|
73
|
-
|
88
|
+
Remember to apply the new migration after you run the generator:
|
74
89
|
|
75
|
-
|
76
|
-
|
77
|
-
end
|
90
|
+
```bash
|
91
|
+
./bin/rails db:migrate
|
78
92
|
```
|
79
93
|
|
80
|
-
|
94
|
+
Next you need to whitelist `:otp_attempt` as a permitted parameter in Devise `:sign_in` controller. You can do this by adding the following to your `application_controller.rb`:
|
81
95
|
|
82
96
|
```ruby
|
83
|
-
|
97
|
+
# app/controllers/application_controller.rb
|
84
98
|
|
85
|
-
|
99
|
+
before_action :configure_permitted_parameters, if: :devise_controller?
|
86
100
|
|
87
|
-
|
101
|
+
# ...
|
88
102
|
|
89
|
-
|
90
|
-
|
91
|
-
|
103
|
+
protected
|
104
|
+
|
105
|
+
def configure_permitted_parameters
|
106
|
+
devise_parameter_sanitizer.permit(:sign_in, keys: [:otp_attempt])
|
107
|
+
end
|
92
108
|
```
|
93
109
|
|
94
|
-
|
110
|
+
Finally you should verify that `:database_authenticatable` is **not** being loaded by your model. The generator will try to remove it, but if you have a non-standard Devise setup, this step may fail.
|
111
|
+
|
112
|
+
**Loading both `:database_authenticatable` and `:two_factor_authenticatable` in a model is a security issue** It will allow users to bypass two-factor authenticatable due to the way Warden handles cascading strategies!
|
95
113
|
|
96
114
|
## Designing Your Workflow
|
115
|
+
|
97
116
|
Devise-Two-Factor only worries about the backend, leaving the details of the integration up to you. This means that you're responsible for building the UI that drives the gem. While there is an example Rails application included in the gem, it is important to remember that this gem is intentionally very open-ended, and you should build a user experience which fits your individual application.
|
98
117
|
|
99
118
|
There are two key workflows you'll have to think about:
|
@@ -103,8 +122,8 @@ There are two key workflows you'll have to think about:
|
|
103
122
|
|
104
123
|
We chose to keep things as simple as possible, and our implementation can be found by registering at [Tinfoil Security](https://www.tinfoilsecurity.com/), and enabling two-factor authentication from the [security settings page](https://www.tinfoilsecurity.com/account/security).
|
105
124
|
|
106
|
-
|
107
125
|
### Logging In
|
126
|
+
|
108
127
|
Logging in with two-factor authentication works extremely similarly to regular database authentication in Devise. The `TwoFactorAuthenticatable` strategy accepts three parameters:
|
109
128
|
|
110
129
|
1. email
|
@@ -114,11 +133,13 @@ Logging in with two-factor authentication works extremely similarly to regular d
|
|
114
133
|
These parameters can be submitted to the standard Devise login route, and the strategy will handle the authentication of the user for you.
|
115
134
|
|
116
135
|
### Disabling Automatic Login After Password Resets
|
136
|
+
|
117
137
|
If you use the Devise `recoverable` strategy, the default behavior after a password reset is to automatically authenticate the user and log them in. This is obviously a problem if a user has two-factor authentication enabled, as resetting the password would get around the two-factor requirement.
|
118
138
|
|
119
139
|
Because of this, you need to set `sign_in_after_reset_password` to `false` (either globally in your Devise initializer or via `devise_for`).
|
120
140
|
|
121
141
|
### Enabling Two-Factor Authentication
|
142
|
+
|
122
143
|
Enabling two-factor authentication for a user is easy. For example, if my user model were named User, I could do the following:
|
123
144
|
|
124
145
|
```ruby
|
@@ -149,6 +170,7 @@ current_user.current_otp
|
|
149
170
|
```
|
150
171
|
|
151
172
|
The generated code will be valid for the duration specified by `otp_allowed_drift`. This value can be modified by adding a config in `config/initializers/devise.rb`.
|
173
|
+
|
152
174
|
```ruby
|
153
175
|
Devise.otp_allowed_drift = 240 # value in seconds
|
154
176
|
Devise.setup do |config|
|
@@ -165,13 +187,27 @@ However you decide to handle enrollment, there are a few important consideration
|
|
165
187
|
It sounds like a lot of work, but most of these problems have been very elegantly solved by other people. We recommend taking a look at the excellent workflows used by Heroku and Google for inspiration.
|
166
188
|
|
167
189
|
### Filtering sensitive parameters from the logs
|
190
|
+
|
168
191
|
To prevent two-factor authentication codes from leaking if your application logs get breached, you'll want to filter sensitive parameters from the Rails logs. Add the following to `config/initializers/filter_parameter_logging.rb`:
|
169
192
|
|
170
193
|
```ruby
|
171
194
|
Rails.application.config.filter_parameters += [:otp_attempt]
|
172
195
|
```
|
173
196
|
|
197
|
+
### Preventing Brute-Force Attacks
|
198
|
+
|
199
|
+
With any authentication solution it is also important to protect your users from brute-force attacks. For Devise-Two-Factor specifically if a user's username and password have already been compromised an attacker would be able to try possible TOTP codes and see if they can hit a lucky collision to log in. While Devise-Two-Factor is open-ended by design and cannot solve this for all applications natively there are some possible mitigations to consider. A non-exhaustive list follows:
|
200
|
+
|
201
|
+
1. Use the `lockable` strategy from Devise to lock a user after a certain number of failed login attempts. See https://www.rubydoc.info/github/heartcombo/devise/main/Devise/Models/Lockable for more information.
|
202
|
+
2. Configure a rate limit for your application, especially on the endpoints used to log in. One such library to accomplish this is [rack-attack](https://rubygems.org/gems/rack-attack).
|
203
|
+
3. When displaying authentication errors hide whether validating a username/password combination failed or a two-factor code failed behind a more generic error message.
|
204
|
+
|
205
|
+
#### Acknowledgements
|
206
|
+
|
207
|
+
Thank you to Christian Reitter (Radically Open Security) and Chris MacNaughton (Centauri Solutions) for reporting the issue.
|
208
|
+
|
174
209
|
## Backup Codes
|
210
|
+
|
175
211
|
Devise-Two-Factor is designed with extensibility in mind. One such extension, `TwoFactorBackupable`, is included and serves as a good example of how to extend this gem. This plugin allows you to add the ability to generate single-use backup codes for a user, which they may use to bypass two-factor authentication, in the event that they lose access to their device.
|
176
212
|
|
177
213
|
To install it, you need to add the `:two_factor_backupable` directive to your model.
|
@@ -186,17 +222,39 @@ You'll also be required to enable the `:two_factor_backupable` strategy, by addi
|
|
186
222
|
manager.default_strategies(:scope => :user).unshift :two_factor_backupable
|
187
223
|
```
|
188
224
|
|
189
|
-
|
225
|
+
### Migration
|
226
|
+
|
227
|
+
The final installation step may be dependent on your version of Rails.
|
228
|
+
|
229
|
+
#### PostgreSQL
|
190
230
|
|
191
231
|
```ruby
|
192
232
|
class AddDeviseTwoFactorBackupableToUsers < ActiveRecord::Migration
|
193
233
|
def change
|
194
|
-
# Change type from :string to :text if using MySQL database
|
195
234
|
add_column :users, :otp_backup_codes, :string, array: true
|
196
235
|
end
|
197
236
|
end
|
198
237
|
```
|
199
238
|
|
239
|
+
#### MySQL
|
240
|
+
|
241
|
+
```ruby
|
242
|
+
# migration
|
243
|
+
class AddDeviseTwoFactorBackupableToUsers < ActiveRecord::Migration
|
244
|
+
def change
|
245
|
+
add_column :users, :otp_backup_codes, :text
|
246
|
+
end
|
247
|
+
end
|
248
|
+
|
249
|
+
# model
|
250
|
+
class User < ApplicationRecord
|
251
|
+
devise :two_factor_backupable
|
252
|
+
serialize :otp_backup_codes, Array
|
253
|
+
end
|
254
|
+
```
|
255
|
+
|
256
|
+
### Generation
|
257
|
+
|
200
258
|
You can then generate backup codes for a user:
|
201
259
|
|
202
260
|
```ruby
|
@@ -214,23 +272,8 @@ devise :two_factor_backupable, otp_backup_code_length: 32,
|
|
214
272
|
otp_number_of_backup_codes: 10
|
215
273
|
```
|
216
274
|
|
217
|
-
### Help! I'm not using Rails 4.0!
|
218
|
-
Don't worry! `TwoFactorBackupable` stores the backup codes as an array of strings in the database. In Rails 4.0 this is supported natively, but in earlier versions you can use a gem to emulate this behavior: we recommend [activerecord-postgres-array](https://github.com/tlconnor/activerecord-postgres-array).
|
219
|
-
|
220
|
-
You'll then simply have to create a migration to add an array named `otp_backup_codes` to your model. If you use the above gem, this migration might look like:
|
221
|
-
|
222
|
-
```ruby
|
223
|
-
class AddTwoFactorBackupCodesToUsers < ActiveRecord::Migration
|
224
|
-
def change
|
225
|
-
# Change type from :string_array to :text_array if using MySQL database
|
226
|
-
add_column :users, :otp_backup_codes, :string_array
|
227
|
-
end
|
228
|
-
end
|
229
|
-
```
|
230
|
-
|
231
|
-
Now just continue with the setup in the previous section, skipping the generator step.
|
232
|
-
|
233
275
|
## Testing
|
276
|
+
|
234
277
|
Devise-Two-Factor includes shared-examples for both `TwoFactorAuthenticatable` and `TwoFactorBackupable`. Adding the following two lines to the specs for your two-factor enabled models will allow you to test your models for two-factor functionality:
|
235
278
|
|
236
279
|
```ruby
|
@@ -241,6 +284,7 @@ it_behaves_like "two_factor_backupable"
|
|
241
284
|
```
|
242
285
|
|
243
286
|
## Troubleshooting
|
287
|
+
|
244
288
|
If you are using Rails 4.x and Ruby >= 2.7, you may get an error like
|
245
289
|
|
246
290
|
```
|
@@ -250,9 +294,11 @@ Failure/Error: require 'devise'
|
|
250
294
|
NoMethodError:
|
251
295
|
undefined method `new' for BigDecimal:Class
|
252
296
|
```
|
297
|
+
|
253
298
|
see https://github.com/ruby/bigdecimal#which-version-should-you-select and https://github.com/ruby/bigdecimal/issues/127
|
254
299
|
for more details, but you should be able to solve this
|
255
300
|
by explicitly requiring an older version of bigdecimal in your gemfile like
|
256
|
-
|
301
|
+
|
302
|
+
```ruby
|
257
303
|
gem "bigdecimal", "~> 1.4"
|
258
304
|
```
|
data/SECURITY.md
ADDED
data/UPGRADING.md
CHANGED
@@ -1,4 +1,220 @@
|
|
1
|
-
#
|
1
|
+
# Upgrading
|
2
|
+
|
3
|
+
## Upgrading from 5.x to 6.x
|
4
|
+
|
5
|
+
### save!
|
6
|
+
|
7
|
+
`consume_otp!` and `invalidate_otp_backup_code!` now call `save!` instead of `save` (or nothing at all in the case of `invalide_otp_backup_code!`). If you manually called `save`/`save!` after calling `invalidate_otp_backup_code` you may be able to remove it.
|
8
|
+
|
9
|
+
### Secret Lengths
|
10
|
+
|
11
|
+
The `otp_secret_length` and `otp_backup_code_length` options have changed to be the number of random bytes that are generated.
|
12
|
+
If you had configured these values you may want to change them if you wish to keep the same output length.
|
13
|
+
|
14
|
+
`otp_secret_length` now has a default value of 20, generating a 160 bit secret key with an output length length of 32 bytes.
|
15
|
+
|
16
|
+
`otp_backup_code_length` now has a default value of 16, generating a 32 byte backup code.
|
17
|
+
|
18
|
+
## Upgrading from 4.x to 5.x
|
19
|
+
|
20
|
+
### Background
|
21
|
+
|
22
|
+
#### Database columns in version 4.x and older
|
23
|
+
|
24
|
+
Versions 4.x and older stored the OTP secret in an attribute called `encrypted_otp_secret` using the [attr_encrypted](https://github.com/attr-encrypted/attr_encrypted) gem. This gem is currently unmaintained which is part of the motivation for moving to Rails encrypted attributes. This attribute was backed by three database columns:
|
25
|
+
|
26
|
+
```
|
27
|
+
encrypted_otp_secret
|
28
|
+
encrypted_otp_secret_iv
|
29
|
+
encrypted_otp_secret_salt
|
30
|
+
```
|
31
|
+
|
32
|
+
Two other columns were also created:
|
33
|
+
|
34
|
+
```
|
35
|
+
consumed_timestep
|
36
|
+
otp_required_for_login
|
37
|
+
```
|
38
|
+
|
39
|
+
A fresh install of 4.x would create all five of the database columns above.
|
40
|
+
|
41
|
+
#### Database columns in version 5.x and later
|
42
|
+
|
43
|
+
Versions 5+ of this gem uses a single [Rails 7+ encrypted attribute](https://edgeguides.rubyonrails.org/active_record_encryption.html) named `otp_secret`to store the OTP secret in the database table (usually `users` but will be whatever model you picked).
|
44
|
+
|
45
|
+
A fresh install of 5+ will add the following columns to your `users` table:
|
46
|
+
|
47
|
+
```bash
|
48
|
+
otp_secret # this replaces encrypted_otp_secret, encrypted_otp_secret_iv, encrypted_otp_secret_salt
|
49
|
+
consumed_timestep
|
50
|
+
otp_required_for_login
|
51
|
+
```
|
52
|
+
|
53
|
+
We have attempted to make the upgrade as painless as possible but unfortunately because of the secret storage change, it cannot be as simple as `bundle update devise-two-factor` :heart:
|
54
|
+
|
55
|
+
### Assumptions
|
56
|
+
|
57
|
+
This guide assumes you are upgrading an existing Rails 6 app (with `devise` and `devise-two-factor`) to Rails 7.
|
58
|
+
|
59
|
+
This gem must be upgraded **as part of a Rails 7 upgrade**. See [the official Rails upgrading guide](https://guides.rubyonrails.org/upgrading_ruby_on_rails.html) for an overview of upgrading Rails.
|
60
|
+
|
61
|
+
### Phase 1: Upgrading devise-two-factor as part of Rails 7 upgrade
|
62
|
+
|
63
|
+
1. Update the version constraint for Rails in your `Gemfile` to your desired version e.g. `gem "rails", "~> 7.0.3"`
|
64
|
+
1. Run `bundle install` and resolve any issues with dependencies.
|
65
|
+
1. Update the version constraint for `devise-two-factor` in your `Gemfile` to the the latest version (must be at least 5.x e.g. `~> 5.0`
|
66
|
+
1. Run `./bin/rails app:update` as per the [Rails upgrade guide](https://guides.rubyonrails.org/upgrading_ruby_on_rails.html) and tweak the output as required for your app.
|
67
|
+
1. Run `./bin/rails db:migrate` to update your DB based on the changes made by `app:update`
|
68
|
+
1. Add a new `otp_secret` attribute to your user model
|
69
|
+
```bash
|
70
|
+
# TODO: replace 'User' in the migration name with the name of your user model
|
71
|
+
./bin/rails g migration AddOtpSecretToUser otp_secret:string
|
72
|
+
./bin/rails db:migrate
|
73
|
+
```
|
74
|
+
1. Add a `legacy_otp_secret` method to your user model e.g. `User`.
|
75
|
+
* This method is used by the gem to find and decode the OTP secret from the legacy database columns.
|
76
|
+
* The implementation shown below works if you set up devise-two-factor with the settings suggested in the [OLD README](https://github.com/devise-two-factor/devise-two-factor/blob/8d74f5ee45594bf00e60d5d49eb6fcde82c2d2ba/README.md).
|
77
|
+
* If you have customised the encryption scheme used to store the OTP secret then you will need to update this method to match.
|
78
|
+
* If you are unsure, you should try the method below as is, and if you can still sign in users with OTP enabled then all is well.
|
79
|
+
```ruby
|
80
|
+
class User
|
81
|
+
# ...
|
82
|
+
|
83
|
+
private
|
84
|
+
|
85
|
+
##
|
86
|
+
# Decrypt and return the `encrypted_otp_secret` attribute which was used in
|
87
|
+
# prior versions of devise-two-factor
|
88
|
+
# @return [String] The decrypted OTP secret
|
89
|
+
def legacy_otp_secret
|
90
|
+
return nil unless self[:encrypted_otp_secret]
|
91
|
+
return nil unless self.class.otp_secret_encryption_key
|
92
|
+
|
93
|
+
hmac_iterations = 2000 # a default set by the Encryptor gem
|
94
|
+
key = self.class.otp_secret_encryption_key
|
95
|
+
salt = Base64.decode64(encrypted_otp_secret_salt)
|
96
|
+
iv = Base64.decode64(encrypted_otp_secret_iv)
|
97
|
+
|
98
|
+
raw_cipher_text = Base64.decode64(encrypted_otp_secret)
|
99
|
+
# The last 16 bytes of the ciphertext are the authentication tag - we use
|
100
|
+
# Galois Counter Mode which is an authenticated encryption mode
|
101
|
+
cipher_text = raw_cipher_text[0..-17]
|
102
|
+
auth_tag = raw_cipher_text[-16..-1]
|
103
|
+
|
104
|
+
# this algorithm lifted from
|
105
|
+
# https://github.com/attr-encrypted/encryptor/blob/master/lib/encryptor.rb#L54
|
106
|
+
|
107
|
+
# create an OpenSSL object which will decrypt the AES cipher with 256 bit
|
108
|
+
# keys in Galois Counter Mode (GCM). See
|
109
|
+
# https://ruby.github.io/openssl/OpenSSL/Cipher.html
|
110
|
+
cipher = OpenSSL::Cipher.new('aes-256-gcm')
|
111
|
+
|
112
|
+
# tell the cipher we want to decrypt. Symmetric algorithms use a very
|
113
|
+
# similar process for encryption and decryption, hence the same object can
|
114
|
+
# do both.
|
115
|
+
cipher.decrypt
|
116
|
+
|
117
|
+
# Use a Password-Based Key Derivation Function to generate the key actually
|
118
|
+
# used for encryption from the key we got as input.
|
119
|
+
cipher.key = OpenSSL::PKCS5.pbkdf2_hmac_sha1(key, salt, hmac_iterations, cipher.key_len)
|
120
|
+
|
121
|
+
# set the Initialization Vector (IV)
|
122
|
+
cipher.iv = iv
|
123
|
+
|
124
|
+
# The tag must be set after calling Cipher#decrypt, Cipher#key= and
|
125
|
+
# Cipher#iv=, but before calling Cipher#final. After all decryption is
|
126
|
+
# performed, the tag is verified automatically in the call to Cipher#final.
|
127
|
+
#
|
128
|
+
# If the auth_tag does not verify, then #final will raise OpenSSL::Cipher::CipherError
|
129
|
+
cipher.auth_tag = auth_tag
|
130
|
+
|
131
|
+
# auth_data must be set after auth_tag has been set when decrypting See
|
132
|
+
# http://ruby-doc.org/stdlib-2.0.0/libdoc/openssl/rdoc/OpenSSL/Cipher.html#method-i-auth_data-3D
|
133
|
+
# we are not adding any authenticated data but OpenSSL docs say this should
|
134
|
+
# still be called.
|
135
|
+
cipher.auth_data = ''
|
136
|
+
|
137
|
+
# #update is (somewhat confusingly named) the method which actually
|
138
|
+
# performs the decryption on the given chunk of data. Our OTP secret is
|
139
|
+
# short so we only need to call it once.
|
140
|
+
#
|
141
|
+
# It is very important that we call #final because:
|
142
|
+
#
|
143
|
+
# 1. The authentication tag is checked during the call to #final
|
144
|
+
# 2. Block based cipher modes (e.g. CBC) work on fixed size chunks. We need
|
145
|
+
# to call #final to get it to process the last chunk properly. The output
|
146
|
+
# of #final should be appended to the decrypted value. This isn't
|
147
|
+
# required for streaming cipher modes but including it is a best practice
|
148
|
+
# so that your code will continue to function correctly even if you later
|
149
|
+
# change to a block cipher mode.
|
150
|
+
cipher.update(cipher_text) + cipher.final
|
151
|
+
end
|
152
|
+
end
|
153
|
+
```
|
154
|
+
2. Set up [Rails encrypted secrets](https://edgeguides.rubyonrails.org/active_record_encryption.html)
|
155
|
+
```bash
|
156
|
+
./bin/rails db:encryption:init
|
157
|
+
# capture the output and put in encrypted credentials via
|
158
|
+
./bin/rails credentials:edit
|
159
|
+
```
|
160
|
+
3. Complete your Rails 7 upgrade (making whatever other changes are required)
|
161
|
+
|
162
|
+
You can now deploy your upgraded application and devise-two-factor should work as before.
|
163
|
+
|
164
|
+
This gem will fall back to **reading** the OTP secret from the legacy columns if it cannot find one in the new `otp_secret` column. When you **write** a new OTP secret it will always be written to the new `otp_secret` column.
|
165
|
+
|
166
|
+
### Phase 2: Clean up
|
167
|
+
|
168
|
+
This "clean up" phase can happen at the same time as your initial deployment but teams managing existing apps will likely want to do clean-up as separate, later deployments.
|
169
|
+
|
170
|
+
1. Create a rake task to copy the OTP secret for each user from the legacy column to the new `otp_secret` column. This prepares the way for us to remove the legacy columns in a later step.
|
171
|
+
```ruby
|
172
|
+
# lib/tasks/devise_two_factor_migration.rake
|
173
|
+
|
174
|
+
# Use this as a starting point for your task to migrate your user's OTP secrets.
|
175
|
+
namespace :devise_two_factor do
|
176
|
+
desc "Copy devise_two_factor OTP secret from old format to new format"
|
177
|
+
task copy_otp_secret_to_rails7_encrypted_attr: [:environment] do
|
178
|
+
# TODO: change User to your user model
|
179
|
+
User.find_each do |user| # find_each finds in batches of 1,000 by default
|
180
|
+
otp_secret = user.otp_secret # read from otp_secret column, fall back to legacy columns if new column is empty
|
181
|
+
puts "Processing #{user.email}"
|
182
|
+
user.update!(otp_secret: otp_secret)
|
183
|
+
end
|
184
|
+
end
|
185
|
+
end
|
186
|
+
```
|
187
|
+
1. Remove the `#legacy_otp_secret` method from your user model (e.g. `User`) because it is no longer required.
|
188
|
+
1. Remove the now unused legacy columns from the database. This assumes you have run a rake task as in the previous step to migrate all the legacy stored secrets to the new storage.
|
189
|
+
```bash
|
190
|
+
# TODO: replace 'Users' in migration name with the name of your user model
|
191
|
+
./bin/rails g migration RemoveLegacyDeviseTwoFactorSecretsFromUsers
|
192
|
+
```
|
193
|
+
which generates
|
194
|
+
```ruby
|
195
|
+
class RemoveLegacyDeviseTwoFactorSecretsFromUsers < ActiveRecord::Migration[7.0]
|
196
|
+
def change
|
197
|
+
# TODO: change :users to whatever your users table is
|
198
|
+
|
199
|
+
# WARNING: Only run this when you are confident you have copied the OTP
|
200
|
+
# secret for ALL users from `encrypted_otp_secret` to `otp_secret`!
|
201
|
+
remove_column :users, :encrypted_otp_secret
|
202
|
+
remove_column :users, :encrypted_otp_secret_iv
|
203
|
+
remove_column :users, :encrypted_otp_secret_salt
|
204
|
+
end
|
205
|
+
end
|
206
|
+
```
|
207
|
+
1. Remove `otp_secret_encryption_key` from the model setup. This also assumes you successfully ran the rake task in step 1.
|
208
|
+
```ruby
|
209
|
+
# from this:
|
210
|
+
devise :two_factor_authenticatable,
|
211
|
+
otp_secret_encryption_key: ENV['YOUR_ENCRYPTION_KEY_HERE']
|
212
|
+
|
213
|
+
# to this:
|
214
|
+
devise :two_factor_authenticatable
|
215
|
+
```
|
216
|
+
|
217
|
+
## Upgrading from 2.x to 3.x
|
2
218
|
|
3
219
|
Pull request #76 allows for compatibility with `attr_encrypted` 3.0, which should be used due to a security vulnerability discovered in 2.0.
|
4
220
|
|
@@ -18,7 +234,7 @@ class User < ActiveRecord::Base
|
|
18
234
|
:otp_secret_encryption_key => ENV['DEVISE_TWO_FACTOR_ENCRYPTION_KEY']
|
19
235
|
```
|
20
236
|
|
21
|
-
|
237
|
+
## Upgrading from 1.x to 2.x
|
22
238
|
|
23
239
|
Pull request #43 added a new field to protect against "shoulder-surfing" attacks. If upgrading, you'll need to add the `:consumed_timestep` column to your `Users` model.
|
24
240
|
|
data/devise-two-factor.gemspec
CHANGED
@@ -5,12 +5,11 @@ Gem::Specification.new do |s|
|
|
5
5
|
s.name = 'devise-two-factor'
|
6
6
|
s.version = DeviseTwoFactor::VERSION.dup
|
7
7
|
s.platform = Gem::Platform::RUBY
|
8
|
-
s.
|
8
|
+
s.license = 'MIT'
|
9
9
|
s.summary = 'Barebones two-factor authentication with Devise'
|
10
|
-
s.
|
11
|
-
s.
|
12
|
-
s.
|
13
|
-
s.authors = ['Shane Wilton']
|
10
|
+
s.homepage = 'https://github.com/devise-two-factor/devise-two-factor'
|
11
|
+
s.description = 'Devise-Two-Factor is a minimalist extension to Devise which offers support for two-factor authentication through the TOTP scheme.'
|
12
|
+
s.authors = ['Quinn Wilton']
|
14
13
|
|
15
14
|
s.cert_chain = [
|
16
15
|
'certs/tinfoil-cacert.pem',
|
@@ -23,7 +22,6 @@ Gem::Specification.new do |s|
|
|
23
22
|
|
24
23
|
s.add_runtime_dependency 'railties', '~> 7.0'
|
25
24
|
s.add_runtime_dependency 'activesupport', '~> 7.0'
|
26
|
-
s.add_runtime_dependency 'attr_encrypted', '>= 1.3', '< 5', '!= 2'
|
27
25
|
s.add_runtime_dependency 'devise', '~> 4.0'
|
28
26
|
s.add_runtime_dependency 'rotp', '~> 6.0'
|
29
27
|
|
@@ -32,5 +30,4 @@ Gem::Specification.new do |s|
|
|
32
30
|
s.add_development_dependency 'bundler', '> 1.0'
|
33
31
|
s.add_development_dependency 'rspec', '> 3'
|
34
32
|
s.add_development_dependency 'simplecov'
|
35
|
-
s.add_development_dependency 'faker'
|
36
33
|
end
|