diff --git a/Gemfile b/Gemfile index b3f6f31..48de394 100644 --- a/Gemfile +++ b/Gemfile @@ -84,3 +84,5 @@ gem "omniauth_openid_connect", "~> 0.8" gem "omniauth-rails_csrf_protection", "~> 2.0" gem "prawn", "~> 2.5" # printable logbook entries +gem "rotp", "~> 6.3" # authenticator app (TOTP) codes +gem "rqrcode", "~> 3.1" # QR code for setting up the authenticator diff --git a/Gemfile.lock b/Gemfile.lock index 809041d..99faae5 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -115,6 +115,7 @@ GEM nokogiri (~> 1.10, >= 1.10.4) rubyzip (>= 2.4, < 4) chartkick (5.3.0) + chunky_png (1.4.0) commonmarker (2.10.1-aarch64-linux) commonmarker (2.10.1-aarch64-linux-musl) commonmarker (2.10.1-arm-linux-gnu) @@ -367,6 +368,11 @@ GEM logger (~> 1) nokogiri (~> 1) rubyzip (>= 3.0.0, < 4.0.0) + rotp (6.4.0) + rqrcode (3.2.0) + chunky_png (~> 1.0) + rqrcode_core (~> 2.0) + rqrcode_core (2.1.0) rubocop (1.92.2) json (>= 2.3) language_server-protocol (~> 3.17.0.2) @@ -530,6 +536,8 @@ DEPENDENCIES puma (>= 5.0) rails (~> 8.1.0) roo (~> 4.0) + rotp (~> 6.3) + rqrcode (~> 3.1) rubocop-rails-omakase rubyzip (~> 3.7) selenium-webdriver @@ -579,6 +587,7 @@ CHECKSUMS capybara (3.40.0) sha256=42dba720578ea1ca65fd7a41d163dd368502c191804558f6e0f71b391054aeef caxlsx (4.5.0) sha256=e3d98d859f148df05d5462086b5079b523f29c1766b569535f1d68629ce743ff chartkick (5.3.0) sha256=19a2bba39decf54c4939d3f31460535f8814c85045672ba2ed616c6897325b00 + chunky_png (1.4.0) sha256=89d5b31b55c0cf4da3cf89a2b4ebc3178d8abe8cbaf116a1dba95668502fdcfe commonmarker (2.10.1-aarch64-linux) sha256=3ab9e7027d2350364bdc541680cc28e21011b2950abf7d08ac29093fa691bdc3 commonmarker (2.10.1-aarch64-linux-musl) sha256=98e6d1a03ba708438d804702e3c25f3423bff21a1e9975280eb265d889677dfc commonmarker (2.10.1-arm-linux-gnu) sha256=dc1ce6cfe5547d2814351ef306d5d1dd05f9c08ad405c76baa94748326c83b7f @@ -680,6 +689,9 @@ CHECKSUMS reline (0.7.0) sha256=5b012d8e55dbf9d450f12bde2cf7d15ff546ae80b3f8f3b30e570d431815583d rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142 roo (4.0.0) sha256=83e25e85add9313fcf9d1e6c88720ce2bba2fa22590375eca23092be1d0690e8 + rotp (6.4.0) sha256=e2de8e0dfda5729b430f384e6233432bf0402c4f57ca270fa0cc1b5a42ed49f2 + rqrcode (3.2.0) sha256=64c1494ca6bb67d731330f38b50e3fd09eeab4f5dcd04b608e21218d1d0b9542 + rqrcode_core (2.1.0) sha256=f303b85df89c1b8fc5ee8dc19808c9dc4330e6329b660d99d4a8cbb36ca13051 rubocop (1.92.2) sha256=14fb31eed143a0dc6f78186c550c1715e81cd38f59d05d1165050e445c1f5382 rubocop-ast (1.50.0) sha256=b9ca88300da0803ee222ad20cdb30494c0a784eed06fdc35d254b06d662788db rubocop-performance (1.27.0) sha256=eeeb1374d062a368ee1c787b70eb0b0cc4b184cb1f8565f424760946146d61ce diff --git a/README.md b/README.md index 474a45b..7b0082b 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ DEMO=1 bin/rails db:seed # optional: demo aircraft N12345 bin/dev # http://localhost:3000 ``` -With demo data, sign in as `admin@example.com` / `password123` (admin, owner of N12345) or `pilot@example.com` / `password123` (pilot). +With demo data, sign in as `admin@example.com` / `demo-password-123` (admin, owner of N12345) or `pilot@example.com` / `demo-password-123` (pilot). Without demo data, the first visit asks you to create the admin account. Run the tests: `bin/rails test` @@ -69,6 +69,7 @@ The app is a standard Rails app. Run `bin/rails db:prepare && bin/thrust bin/rai | `OIDC_AUTO_CREATE_USERS` | `true` creates an account for anyone the provider lets in. New accounts start with no aircraft. Default off: an admin adds users first. | | `OIDC_TRUST_EMAIL` | `true` links existing accounts by email even if the provider doesn't mark it verified. Only use it if users can't edit their own email at the provider. | | `OIDC_ADMIN_GROUP` | Optional. Members of this provider group become admins and others lose admin, synced at each sign-in. | +| `PWNED_PASSWORDS_CHECK` | `false` turns off the check of new passwords against Have I Been Pwned (only the first 5 characters of the password's SHA-1 are sent). Use it if the server has no outbound internet access; the check also allows the password if the service can't be reached. | | `PASSWORD_LOGIN` | `false` hides email/password sign-in, emailed sign-in links and password resets once SSO works. It's ignored while SSO isn't configured, so you can't lock yourself out. | | `APP_REPOSITORY_URL` | Optional. The source code link on Admin → About, for a fork. | | `APP_REVISION`, `APP_BUILT_AT` | Set as Docker build arguments (see the `Dockerfile`) so Admin → About shows the version and the records keep a software version history. | @@ -129,6 +130,7 @@ To back up or move a single aircraft with all its files, use **Access & Sharing | Oil and fuel | Records, trend charts, and averages (last 20 intervals, IQR outlier filtering, manual exclusion). | | Activity log | Every write is recorded as an `AircraftEvent`. | | Access | Admin, owner, and pilot roles, plus share links (Current Status or Maintenance Detail, optional expiry, at most 10 per aircraft). Admins can disable accounts; a disabled account can't sign in or sign entries, and its past signatures stay. | +| Sign-in security | Passwords of at least 12 characters, checked against known breaches (Have I Been Pwned, k-anonymity). 10 failed sign-ins in a row lock an account for 15 minutes from any address, and the user is emailed; admins can unlock. Optional authenticator-app (TOTP) codes with recovery codes for password and emailed-link sign-in and for signing entries; admins can reset them. Rate limits per address on every sign-in form. | | Help | The [user guide](docs/guide/README.md), shown in the app under **Help**. | ### Roles diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index fc59d02..9fbb4ee 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -1,6 +1,6 @@ class Admin::UsersController < ApplicationController before_action :require_admin! - before_action :set_user, only: %i[edit update destroy disable enable] + before_action :set_user, only: %i[edit update destroy disable enable unlock reset_two_factor] def index @users = User.order(:email_address).includes(:certificates, aircraft_roles: :aircraft) @@ -39,6 +39,19 @@ class Admin::UsersController < ApplicationController # Ends their access and their ability to sign (AC 120-78B 2.2.6.4) while # keeping their account, so the signatures they made stay attributed. + def unlock + @user.unlock! + redirect_to admin_users_path, notice: "#{@user.email_address} unlocked." + end + + # For a user who lost their authenticator: they sign in with their password + # alone and can set it up again. + def reset_two_factor + @user.disable_otp! + Rails.logger.info("[auth] #{current_user.email_address} turned off two-factor for #{@user.email_address}") + redirect_to admin_users_path, notice: "Two-factor turned off for #{@user.email_address}. Ask them to set it up again from their profile." + end + def disable return redirect_to admin_users_path, alert: "You can't disable yourself." if @user == current_user @user.update!(disabled_at: Time.current) diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb index 7adc300..ea09382 100644 --- a/app/controllers/concerns/authentication.rb +++ b/app/controllers/concerns/authentication.rb @@ -58,6 +58,29 @@ module Authentication end end + # Password or emailed-link sign-in: straight in, or first the + # authenticator code if the user has one set up (SSO skips this; the + # provider handles its own second factor). + OTP_PENDING_FOR = 5.minutes + + def begin_sign_in(user, return_to:, notice: nil) + reset_session # fresh session id after signing in + if user.otp_enabled? + session[:otp_user_id] = user.id + session[:otp_started_at] = Time.current.to_i + session[:return_to_after_authenticating] = return_to + redirect_to two_factor_session_path + else + start_new_session_for user + redirect_to return_to, notice: notice + end + end + + def pending_otp_user + return unless (id = session[:otp_user_id]) && Time.zone.at(session[:otp_started_at].to_i) > OTP_PENDING_FOR.ago + User.active.find_by(id: id) + end + def terminate_session Current.session.destroy cookies.delete(:session_id) diff --git a/app/controllers/concerns/entry_signing.rb b/app/controllers/concerns/entry_signing.rb index b3a0d65..b9563ef 100644 --- a/app/controllers/concerns/entry_signing.rb +++ b/app/controllers/concerns/entry_signing.rb @@ -11,10 +11,20 @@ module EntrySigning session[:after_reauth] = signing_page_path # where single sign-on returns after signing in again end - # Password re-entered now, or single sign-on completed in the last few minutes. + # Password re-entered now (with an authenticator code too, if the user has + # one), or single sign-on completed in the last few minutes. Wrong + # passwords and codes count toward the account lockout. def reauthenticated_method if params[:password].present? - return "password" if current_user.authenticate_password(params[:password]) + return if current_user.locked? + unless current_user.authenticate_password(params[:password]) + current_user.register_failed_sign_in! + return + end + return "password" unless current_user.otp_enabled? + return "password_totp" if current_user.verify_second_factor(params[:otp_code]) + current_user.register_failed_sign_in! + return elsif current_user.sso_uid? && (at = session[:reauthenticated_at]) && Time.zone.at(at) > EntrySigner::REAUTH_WINDOW.ago return "sso" end @@ -27,7 +37,11 @@ module EntrySigning unless params[:confirm] == "1" return signing_failed(entry, "Tick the box to confirm you're signing this entry.") end - return signing_failed(entry, "Re-enter your password (or sign in again with #{Sso.label}) to sign.") unless method + unless method + return signing_failed(entry, "This account is locked for a few minutes after too many failed tries.") if current_user.reload.locked? + return signing_failed(entry, "Re-enter your password#{' and a current authenticator code' if current_user.otp_enabled?} (or sign in again with #{Sso.label}) to sign.") + end + current_user.clear_failed_sign_ins! signature = EntrySigner.new(entry, user: current_user, certificate: certificate, auth_method: method, request: request).sign! session.delete(:reauthenticated_at) diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rb index f60a895..322fd3a 100644 --- a/app/controllers/passwords_controller.rb +++ b/app/controllers/passwords_controller.rb @@ -24,7 +24,7 @@ class PasswordsController < ApplicationController @user.sessions.destroy_all # a reset signs out every device redirect_to new_session_path, notice: "Password has been reset." else - redirect_to edit_password_path(params[:token]), alert: "Passwords did not match." + redirect_to edit_password_path(params[:token]), alert: @user.errors.full_messages.to_sentence.presence || "Enter a new password." end end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb index dba5949..237587b 100644 --- a/app/controllers/sessions_controller.rb +++ b/app/controllers/sessions_controller.rb @@ -1,6 +1,8 @@ class SessionsController < ApplicationController - allow_unauthenticated_access only: %i[ new create ] - rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_url, alert: "Try again later." } + allow_unauthenticated_access only: %i[new create two_factor verify_two_factor] + rate_limit to: 10, within: 3.minutes, only: %i[create verify_two_factor], with: -> { redirect_to new_session_url, alert: "Try again later." } + + FAILED = "Try another email address or password. After #{User::LOCK_AFTER} failed tries in a row an account is locked for #{User::LOCK_FOR.inspect}.".freeze def new end @@ -8,15 +10,36 @@ class SessionsController < ApplicationController def create return redirect_to new_session_path, alert: "Sign in with #{Sso.label}." unless Sso.password_login? - if (user = User.authenticate_by(params.permit(:email_address, :password))) && user.disabled? + if (user = User.authenticate_with_lockout(email_address: params[:email_address], password: params[:password])) && user.disabled? redirect_to new_session_path, alert: "This account is disabled." elsif user - return_to = after_authentication_url - reset_session # fresh session id after signing in - start_new_session_for user - redirect_to return_to + begin_sign_in user, return_to: after_authentication_url else - redirect_to new_session_path, alert: "Try another email address or password." + redirect_to new_session_path(email_address: params[:email_address].to_s.first(200)), alert: FAILED + end + end + + # Second step for accounts with an authenticator app. + def two_factor + redirect_to new_session_path, alert: "Sign in again." unless pending_otp_user + end + + def verify_two_factor + user = pending_otp_user + return redirect_to(new_session_path, alert: "That took too long. Sign in again.") unless user + if user.locked? + reset_session + redirect_to new_session_path, alert: FAILED + elsif user.verify_second_factor(params[:code]) + user.clear_failed_sign_ins! + return_to = after_authentication_url + reset_session + start_new_session_for user + notice = user.recovery_codes_left < 3 ? "Signed in. You have #{user.recovery_codes_left} recovery codes left: make new ones on your profile." : nil + redirect_to return_to, notice: notice + else + user.register_failed_sign_in! + redirect_to two_factor_session_path, alert: "That code didn't match. Try the current code from your authenticator app, or a recovery code." end end diff --git a/app/controllers/sign_in_links_controller.rb b/app/controllers/sign_in_links_controller.rb index f4486c9..5fd3f75 100644 --- a/app/controllers/sign_in_links_controller.rb +++ b/app/controllers/sign_in_links_controller.rb @@ -26,9 +26,7 @@ class SignInLinksController < ApplicationController def consume return redirect_to new_session_path, alert: "This account is disabled." if @user.disabled? - reset_session # fresh session id after signing in - start_new_session_for @user # also spends the link - redirect_to root_path, notice: "Signed in." + begin_sign_in @user, return_to: root_path, notice: "Signed in." # signing in also spends the link end private diff --git a/app/controllers/two_factors_controller.rb b/app/controllers/two_factors_controller.rb new file mode 100644 index 0000000..22175b8 --- /dev/null +++ b/app/controllers/two_factors_controller.rb @@ -0,0 +1,48 @@ +# Profile → Two-factor: set up an authenticator app (TOTP) for password and +# emailed-link sign-in, turn it off, or make new recovery codes. +class TwoFactorsController < ApplicationController + rate_limit to: 10, within: 5.minutes, only: %i[create destroy recovery_codes], with: -> { redirect_to edit_profile_path(anchor: "two-factor"), alert: "Try again later." } + + def new + return redirect_to(back_path, notice: "Two-factor is already on.") if current_user.otp_enabled? + session[:pending_otp_secret] ||= User.new_otp_secret + @secret = session[:pending_otp_secret] + svg = RQRCode::QRCode.new(User.otp_uri(@secret, current_user.email_address)).as_svg(module_size: 4, use_path: true, viewbox: true) + @qr_data_uri = "data:image/svg+xml;base64,#{Base64.strict_encode64(svg)}" + end + + def create + secret = session[:pending_otp_secret] + return redirect_to(new_two_factor_path(return_to: params[:return_to])) unless secret + if User.valid_otp?(secret, params[:code]) + session.delete(:pending_otp_secret) + @codes = current_user.enable_otp!(secret) + log_security("turned on two-factor") + render :codes + else + redirect_to new_two_factor_path(return_to: params[:return_to]), alert: "That code didn't match. Check the time on your phone and try the current code." + end + end + + def recovery_codes + return redirect_to(edit_profile_path(anchor: "two-factor"), alert: "That code didn't match.") unless current_user.verify_second_factor(params[:code]) + @codes = current_user.enable_otp!(current_user.otp_secret) + log_security("made new recovery codes") + render :codes + end + + def destroy + return redirect_to(edit_profile_path(anchor: "two-factor"), alert: "That code didn't match.") unless current_user.verify_second_factor(params[:code]) + current_user.disable_otp! + log_security("turned off two-factor") + redirect_to edit_profile_path(anchor: "two-factor"), notice: "Two-factor is off." + end + + private + + # Back to a signing invitation the user came from, else the profile. + def back_path = params[:return_to].to_s.match?(%r{\A/sign/[\w-]+\z}) ? params[:return_to] : edit_profile_path(anchor: "two-factor") + helper_method :back_path + + def log_security(what) = Rails.logger.info("[auth] #{current_user.email_address} #{what}") +end diff --git a/app/mailers/sessions_mailer.rb b/app/mailers/sessions_mailer.rb index b07a240..aa08fad 100644 --- a/app/mailers/sessions_mailer.rb +++ b/app/mailers/sessions_mailer.rb @@ -4,4 +4,9 @@ class SessionsMailer < ApplicationMailer @token = user.generate_token_for(:email_sign_in) mail subject: "Your sign-in link", to: user.email_address end + + def locked(user) + @user = user + mail subject: "Your account was locked after failed sign-ins", to: user.email_address + end end diff --git a/app/models/entry_signature.rb b/app/models/entry_signature.rb index e0deb7a..4010728 100644 --- a/app/models/entry_signature.rb +++ b/app/models/entry_signature.rb @@ -7,7 +7,8 @@ # by this server, so the signature record can't be altered unnoticed either. class EntrySignature < ApplicationRecord include Versioned - AUTH_METHODS = { "password" => "password re-entered", "sso" => "single sign-on, signed in again" }.freeze + AUTH_METHODS = { "password" => "password re-entered", "password_totp" => "password and authenticator code re-entered", + "sso" => "single sign-on, signed in again" }.freeze # "Certified by" conveys the intent to sign (2.2.2). LABEL = "Certified by".freeze diff --git a/app/models/user.rb b/app/models/user.rb index 074db6a..5c14f3a 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -22,7 +22,86 @@ class User < ApplicationRecord validates :email_address, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP } - validates :password, length: { minimum: 8 }, allow_nil: true + PASSWORD_MIN = 12 + validates :password, length: { minimum: PASSWORD_MIN, maximum: 72 }, allow_nil: true + validate :password_not_breached + + # Lockout: this many failed sign-ins in a row (password, authenticator + # code, or password at signing) locks the account for a while, from + # whatever address they come. The user is emailed. + LOCK_AFTER = 10 + LOCK_FOR = 15.minutes + + encrypts :otp_secret + OTP_ISSUER = "Simple Aircraft Manager".freeze + RECOVERY_CODES = 10 + + # Password sign-in with lockout. Returns the user, or nil (wrong details, + # or locked: the same answer, so it doesn't reveal which). + def self.authenticate_with_lockout(email_address:, password:) + user = find_by(email_address: email_address.to_s.strip.downcase) + return if user&.locked? + authed = authenticate_by(email_address: email_address.to_s, password: password.to_s) + authed ? authed.tap(&:clear_failed_sign_ins!) : user&.register_failed_sign_in! + end + + def locked? = locked_until&.future? + + # Counts a failed attempt; locks the account (and returns nil) at the limit. + def register_failed_sign_in! + self.class.where(id: id).update_all("failed_sign_ins = failed_sign_ins + 1") + reload + if failed_sign_ins >= LOCK_AFTER + update_columns(failed_sign_ins: 0, locked_until: LOCK_FOR.from_now) + SessionsMailer.locked(self).deliver_later if MailSettings.configured? + Rails.logger.warn("[auth] #{email_address} locked after #{LOCK_AFTER} failed sign-ins") + end + nil + end + + def clear_failed_sign_ins! + update_columns(failed_sign_ins: 0, locked_until: nil) if failed_sign_ins.positive? || locked_until + end + + def unlock! = update_columns(failed_sign_ins: 0, locked_until: nil) + + # --- Authenticator app (TOTP) --- + + def otp_enabled? = otp_enabled_at.present? && otp_secret.present? + + def self.new_otp_secret = ROTP::Base32.random + + def self.otp_uri(secret, email) = ROTP::TOTP.new(secret, issuer: OTP_ISSUER).provisioning_uri(email) + + # A code from the authenticator for this secret, allowing 30 s of clock drift. + def self.valid_otp?(secret, code, after: nil) + ROTP::TOTP.new(secret, issuer: OTP_ISSUER).verify(code.to_s.gsub(/\s/, ""), drift_behind: 30, drift_ahead: 30, after: after) + end + + # Turns it on with a confirmed secret; returns the recovery codes to show once. + def enable_otp!(secret) + codes = Array.new(RECOVERY_CODES) { SecureRandom.alphanumeric(10).downcase.scan(/.{5}/).join("-") } + update!(otp_secret: secret, otp_enabled_at: Time.current, otp_last_used_at: nil, otp_recovery_codes: codes.map { recovery_digest(_1) }) + codes + end + + def disable_otp! = update!(otp_secret: nil, otp_enabled_at: nil, otp_last_used_at: nil, otp_recovery_codes: nil) + + # An authenticator code (each accepted once) or an unused recovery code. + def verify_second_factor(code) + return false unless otp_enabled? + code = code.to_s.strip.downcase + if code.gsub(/\s/, "").match?(/\A\d{6}\z/) + step = self.class.valid_otp?(otp_secret, code, after: otp_last_used_at) + step ? update_columns(otp_last_used_at: step) && true : false + else + digests = Array(otp_recovery_codes) + match = digests.find { ActiveSupport::SecurityUtils.secure_compare(_1, recovery_digest(code)) } + match ? update_columns(otp_recovery_codes: digests - [ match ]) && true : false + end + end + + def recovery_codes_left = Array(otp_recovery_codes).size # Aircraft visible to this user: admins see the whole fleet. def accessible_aircraft @@ -38,4 +117,13 @@ class User < ApplicationRecord def display_name name.presence || email_address end + + private + + def recovery_digest(code) = OpenSSL::HMAC.hexdigest("SHA256", Rails.application.key_generator.generate_key("otp-recovery", 32), code.to_s.strip.downcase) + + def password_not_breached + return if password.blank? || errors.include?(:password) + errors.add(:password, "has appeared in a data breach (Have I Been Pwned); choose a different one") if PwnedPasswords.breached?(password) + end end diff --git a/app/services/pwned_passwords.rb b/app/services/pwned_passwords.rb new file mode 100644 index 0000000..1956d10 --- /dev/null +++ b/app/services/pwned_passwords.rb @@ -0,0 +1,33 @@ +require "net/http" + +# Checks a password against the Have I Been Pwned breach corpus with the +# k-anonymity range API: only the first 5 characters of its SHA-1 are sent, +# never the password. If the service can't be reached the password is +# allowed (logged), so an outage doesn't stop anyone changing a password. +# PWNED_PASSWORDS_CHECK=false turns it off (e.g. no outbound internet). +module PwnedPasswords + API = "https://api.pwnedpasswords.com/range/".freeze + + mattr_accessor :checker, default: ->(password) { lookup(password) } + + def self.enabled? = ENV["PWNED_PASSWORDS_CHECK"] != "false" + def self.breached?(password) = enabled? && password.present? && checker.call(password) + + def self.lookup(password) + sha1 = Digest::SHA1.hexdigest(password).upcase + prefix, suffix = sha1[0, 5], sha1[5..] + uri = URI("#{API}#{prefix}") + req = Net::HTTP::Get.new(uri) + req["Add-Padding"] = "true" + req["User-Agent"] = "Simple-Aircraft-Manager" + res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 3, read_timeout: 3) { _1.request(req) } + return false unless res.is_a?(Net::HTTPSuccess) + res.body.each_line.any? do |line| + hash, count = line.strip.split(":") + hash == suffix && count.to_i.positive? + end + rescue StandardError => e + Rails.logger.warn("[pwned passwords] check skipped: #{e.class}: #{e.message}") + false + end +end diff --git a/app/views/admin/procedures/_document.html.erb b/app/views/admin/procedures/_document.html.erb index b2e449b..ecf6e02 100644 --- a/app/views/admin/procedures/_document.html.erb +++ b/app/views/admin/procedures/_document.html.erb @@ -62,7 +62,7 @@
| Name | Aircraft | Last sign-in | |||
|---|---|---|---|---|---|
| <%= u.name %> <% if u.admin? %>Admin<% end %><% if u.sso_uid? %> <%= Sso.label %><% end %> | +<%= u.name %> <% if u.admin? %>Admin<% end %><% if u.sso_uid? %> <%= Sso.label %><% end %><% if u.otp_enabled? %> 2FA<% end %><% if u.locked? %> Locked<% end %> | <%= u.email_address %><% if u.certificates.any? %> <%= u.certificates.map { "#{_1.short_label} #{_1.number}" }.join(", ") %> <% end %> |
<%= u.aircraft_roles.map { "#{_1.aircraft.tail_number} (#{_1.role})" }.join(", ").presence || "—" %> | <%= u.last_signed_in_at ? "#{time_ago_in_words(u.last_signed_in_at)} ago" : "never" %> | <% if u.disabled? %>Disabled<%= button_to "Enable", enable_admin_user_path(u), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %> <% elsif u != current_user %><%= button_to "Disable", disable_admin_user_path(u), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline", data: { turbo_confirm: "Disable #{u.email_address}? They'll be signed out and can't sign in or sign entries. Their past signatures are kept." } } %><% end %> + <% if u.locked? %><%= button_to "Unlock", unlock_admin_user_path(u), method: :patch, class: "btn-secondary btn-sm", form: { class: "inline" } %><% end %> + <% if u.otp_enabled? %><%= button_to "Reset 2FA", reset_two_factor_admin_user_path(u), method: :patch, class: "btn-secondary btn-sm", title: "Turn off their authenticator app (lost phone)", form: { class: "inline", data: { turbo_confirm: "Turn off two-factor for #{u.email_address}? Only do this after confirming it's really them." } } %><% end %> <%= link_to "Edit", edit_admin_user_path(u), class: "btn-secondary btn-sm" %> |
Proves it's you signing, not someone at your keyboard.<%= " Or sign in again with #{Sso.label} below." if Sso.enabled? && current_user.sso_uid? %>
+ <% if current_user.otp_enabled? %> +Recommended: <%= link_to "add an authenticator app", new_two_factor_path(return_to: request.path), class: "link" %> to your account, so your signature can't be made with a stolen password alone.
+<% end %> diff --git a/app/views/invited_signings/welcome.html.erb b/app/views/invited_signings/welcome.html.erb index c3c93fa..40e0807 100644 --- a/app/views/invited_signings/welcome.html.erb +++ b/app/views/invited_signings/welcome.html.erb @@ -11,7 +11,7 @@ <% if @account_errors.present? %>At least <%= User::PASSWORD_MIN %> characters; not one known from a data breach.
On since <%= @user.otp_enabled_at.to_date %>: signing in with your password or an emailed link also asks for a code from your authenticator app. <%= @user.recovery_codes_left %> recovery codes left.
+ <%= form_with url: two_factor_path, class: "mt-3 flex flex-wrap items-end gap-2" do |f| %> +Add a code from an authenticator app on your phone to password and emailed-link sign-in, so a stolen password alone can't get in.<%= " (Signing in with #{Sso.label} uses its own second factor.)" if Sso.enabled? %>
+Your FAA certificates, for signing logbook entries: “Sign as” fills in your name, the kind of certificate and its number.
diff --git a/app/views/sessions/two_factor.html.erb b/app/views/sessions/two_factor.html.erb new file mode 100644 index 0000000..1772f27 --- /dev/null +++ b/app/views/sessions/two_factor.html.erb @@ -0,0 +1,11 @@ +<% content_for :title, "Sign in" %> +Enter the 6-digit code from your authenticator app. Lost your phone? Enter one of your recovery codes instead.
+<%= link_to "Start again", new_session_path, class: "link" %>
+ <% end %> +Your Simple Aircraft Manager account (<%= @user.email_address %>) was locked for <%= User::LOCK_FOR.inspect %> after <%= User::LOCK_AFTER %> failed sign-in attempts in a row.
+If that was you, wait and try again. If it wasn't, someone may be guessing your password: change it once you're back in (Profile), turn on an authenticator app, and tell your administrator.
diff --git a/app/views/sessions_mailer/locked.text.erb b/app/views/sessions_mailer/locked.text.erb new file mode 100644 index 0000000..a9c8f51 --- /dev/null +++ b/app/views/sessions_mailer/locked.text.erb @@ -0,0 +1,3 @@ +Your Simple Aircraft Manager account (<%= @user.email_address %>) was locked for <%= User::LOCK_FOR.inspect %> after <%= User::LOCK_AFTER %> failed sign-in attempts in a row. + +If that was you, wait and try again. If it wasn't, someone may be guessing your password: change it once you're back in (Profile), turn on an authenticator app, and tell your administrator. diff --git a/app/views/setup/new.html.erb b/app/views/setup/new.html.erb index f445796..c641754 100644 --- a/app/views/setup/new.html.erb +++ b/app/views/setup/new.html.erb @@ -5,7 +5,7 @@ <%= f.errors_summary %> <%= f.field :name %> <%= f.field :email_address, as: :email, label: "Email", required: true %> - <%= f.field :password, as: :password, required: true, hint: "At least 8 characters." %> + <%= f.field :password, as: :password, required: true, hint: "At least #{User::PASSWORD_MIN} characters; not one known from a data breach." %> <%= f.field :password_confirmation, as: :password, required: true %> <%= f.submit "Create Admin Account", class: "btn-primary w-full justify-center" %> <% end %> diff --git a/app/views/two_factors/codes.html.erb b/app/views/two_factors/codes.html.erb new file mode 100644 index 0000000..50290f0 --- /dev/null +++ b/app/views/two_factors/codes.html.erb @@ -0,0 +1,9 @@ +<% content_for :title, "Recovery codes" %> +Two-factor is on. If you lose your phone, each of these codes signs you in once in place of an authenticator code. Print them or keep them in a password manager: they won't be shown again.
+After your password (or an emailed sign-in link) you'll also enter a 6-digit code from an app on your phone, so a stolen password alone can't get in. Any authenticator app works: Google Authenticator, Microsoft Authenticator, 1Password, Authy…
+Can't scan it? Enter this key instead: <%= @secret.scan(/.{4}/).join(" ") %>
<%= link_to "Not now", back_path, class: "link" %>
+([A-Z2-7 ]+)}, 1].delete(" ")
+ post two_factor_path, params: { code: "000000" }
+ assert_redirected_to new_two_factor_path
+ refute @user.reload.otp_enabled?
+ post two_factor_path, params: { code: ROTP::TOTP.new(secret).now }
+ assert_response :success
+ assert_select "ul li", User::RECOVERY_CODES
+ assert @user.reload.otp_enabled?
+ assert_equal secret, @user.otp_secret
+ assert_not_equal secret, @user.read_attribute_before_type_cast(:otp_secret) # encrypted
+ end
+
+ test "with two-factor on, sign-in asks for a code; codes work once; recovery codes work once" do
+ codes = enable_two_factor(@user)
+ attempt(PASSWORD)
+ assert_redirected_to two_factor_session_path
+ get root_path
+ assert_redirected_to new_session_path # not signed in yet
+
+ post two_factor_session_path, params: { code: "123456" }
+ assert_redirected_to two_factor_session_path
+ assert_equal 1, @user.reload.failed_sign_ins
+ code = totp(@user)
+ post two_factor_session_path, params: { code: code }
+ assert_redirected_to root_url
+ get root_path
+ assert_response :success
+
+ delete session_path
+ attempt(PASSWORD)
+ post two_factor_session_path, params: { code: code } # same code again: refused
+ assert_redirected_to two_factor_session_path
+ post two_factor_session_path, params: { code: codes.first.upcase }
+ assert_redirected_to root_url
+ assert_equal User::RECOVERY_CODES - 1, @user.reload.recovery_codes_left
+
+ delete session_path
+ attempt(PASSWORD)
+ post two_factor_session_path, params: { code: codes.first }
+ assert_redirected_to two_factor_session_path
+ end
+
+ test "the code step expires, and an emailed sign-in link also needs the code" do
+ enable_two_factor(@user)
+ attempt(PASSWORD)
+ travel 6.minutes do
+ post two_factor_session_path, params: { code: totp(@user) }
+ assert_redirected_to new_session_path
+ end
+
+ token = @user.generate_token_for(:email_sign_in)
+ post consume_sign_in_link_path(token)
+ assert_redirected_to two_factor_session_path
+ post two_factor_session_path, params: { code: totp(@user) }
+ assert_redirected_to root_url
+ end
+
+ test "turning it off or making new recovery codes needs a code; admins can reset it" do
+ enable_two_factor(@user)
+ attempt(PASSWORD)
+ post two_factor_session_path, params: { code: totp(@user) }
+ delete two_factor_path, params: { code: "000000" }
+ assert @user.reload.otp_enabled?
+ travel 31.seconds do
+ post recovery_codes_two_factor_path, params: { code: totp(@user) }
+ assert_select "ul li", User::RECOVERY_CODES
+ end
+ travel 61.seconds do
+ delete two_factor_path, params: { code: totp(@user) }
+ refute @user.reload.otp_enabled?
+ end
+
+ enable_two_factor(@user)
+ admin = create_user("admin@example.com", admin: true)
+ sign_in admin
+ patch reset_two_factor_admin_user_path(@user)
+ refute @user.reload.otp_enabled?
+ end
+
+ test "signing an entry also needs the authenticator code, and wrong passwords count toward the lockout" do
+ a = create_aircraft(owner: @user)
+ entry = a.logbook_entries.create!(date: Date.current, entry_type: "MAINTENANCE", text: "Changed oil", aircraft_hours_at_entry: 1000)
+ cert = @user.certificates.create!(kind: "AP", number: "7654321")
+ enable_two_factor(@user)
+ attempt(PASSWORD)
+ post two_factor_session_path, params: { code: totp(@user) }
+
+ post aircraft_logbook_entry_signature_path(a, entry), params: { certificate_id: cert.id, password: PASSWORD, confirm: "1" }
+ assert_response :unprocessable_entity
+ assert_includes response.body, "authenticator code"
+ post aircraft_logbook_entry_signature_path(a, entry), params: { certificate_id: cert.id, password: "wrong-password", confirm: "1" }
+ assert_equal 2, @user.reload.failed_sign_ins
+ travel 31.seconds do
+ post aircraft_logbook_entry_signature_path(a, entry), params: { certificate_id: cert.id, password: PASSWORD, otp_code: totp(@user), confirm: "1" }
+ assert_equal "password_totp", entry.reload.signature.auth_method
+ assert_equal 0, @user.reload.failed_sign_ins
+ end
+ end
+end
diff --git a/test/integration/sso_test.rb b/test/integration/sso_test.rb
index f1c5870..6fe707a 100644
--- a/test/integration/sso_test.rb
+++ b/test/integration/sso_test.rb
@@ -105,7 +105,7 @@ class SsoTest < ActionDispatch::IntegrationTest
ENV["PASSWORD_LOGIN"] = "false"
get new_session_path
assert_select "input[name=password]", 0
- post session_path, params: { email_address: "jane@example.com", password: "password123" }
+ post session_path, params: { email_address: "jane@example.com", password: "test-password-123" }
assert_redirected_to new_session_path
assert_match "Sign in with Authentik", flash[:alert]
post passwords_path, params: { email_address: "jane@example.com" }
diff --git a/test/test_helper.rb b/test/test_helper.rb
index 41ce8de..9ad3528 100644
--- a/test/test_helper.rb
+++ b/test/test_helper.rb
@@ -4,13 +4,14 @@ require "rails/test_help"
require "webmock/minitest"
WebMock.disable_net_connect!(allow_localhost: true)
Dir[File.expand_path("support/**/*.rb", __dir__)].each { require _1 }
+PwnedPasswords.checker = ->(password) { password == "breached-password-1" } # no network in tests
module ActiveSupport
class TestCase
parallelize(workers: :number_of_processors)
def create_user(email = "user#{SecureRandom.hex(3)}@example.com", admin: false)
- User.create!(email_address: email, password: "password123", name: email.split("@").first, admin: admin)
+ User.create!(email_address: email, password: "test-password-123", name: email.split("@").first, admin: admin)
end
def create_aircraft(owner: nil, pilot: nil, **attrs)
@@ -33,7 +34,7 @@ end
class ActionDispatch::IntegrationTest
def sign_in(user)
- post session_path, params: { email_address: user.email_address, password: "password123" }
+ post session_path, params: { email_address: user.email_address, password: "test-password-123" }
follow_redirect!
end
end