HIGH broken authenticationrails

Broken Authentication in Rails

How Broken Authentication Manifests in Rails

Broken Authentication in Rails applications often stems from improper session management, weak password policies, and flawed access control implementations. Rails provides robust authentication scaffolding, but developers frequently bypass these protections or implement them incorrectly.

One common Rails-specific vulnerability is the use of skip_before_action to bypass authentication filters. For example:

class ApplicationController < ActionController::Base
before_action :authenticate_user!
end

class DashboardController < ApplicationController
skip_before_action :authenticate_user!, only: [:index]
end

While this might seem harmless for a public landing page, it can expose authenticated-only functionality if the only parameter is accidentally omitted or misconfigured.

Session fixation attacks are particularly relevant in Rails. Consider this vulnerable pattern:

class SessionsController < ApplicationController
def create
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to dashboard_path
end
end
end

The issue here is that the session ID isn't regenerated upon successful login, allowing an attacker to fixate a session ID before authentication. Rails provides reset_session for this exact scenario.

Mass assignment vulnerabilities in Rails can also lead to authentication bypasses. Before Rails 4's strong parameters, code like this was common:

user = User.new(params[:user])
user.save

An attacker could craft a request with user[admin]=true to escalate privileges if the User model had an admin attribute.

Token-based authentication in Rails APIs often suffers from improper implementation. A typical vulnerable pattern:

class Api::V1::BaseController < ApplicationController
before_action :authenticate_token!

private

def authenticate_token!
token = request.headers['Authorization'].split(' ').last
@current_user = User.find_by(auth_token: token)
end
end

This code fails to handle missing or malformed tokens, potentially allowing unauthenticated access if the header is absent.

Rails-Specific Detection

Detecting Broken Authentication in Rails applications requires both static code analysis and dynamic testing. middleBrick's Rails-specific scanning examines authentication patterns across your API endpoints.

middleBrick tests for authentication bypass by attempting unauthenticated requests to protected endpoints and analyzing the responses. For Rails applications, it specifically looks for:

  • Missing or misconfigured before_action filters
  • Exposed session cookies without proper security flags
  • Weak password reset token implementations
  • Improper CSRF protection
  • Session fixation vulnerabilities

The scanner also examines your Rails routes to identify endpoints that should require authentication but don't. For example, it flags patterns like:

resources :users, only: [:index, :show] # Should require auth
resources :admin, only: [:index] # Critical admin endpoint

middleBrick's OpenAPI/Swagger analysis is particularly effective for Rails APIs. It resolves $ref references in your API specifications and cross-references them with runtime findings. If your openapi.yml specifies authentication requirements but the actual implementation doesn't enforce them, middleBrick will detect this discrepancy.

For token-based authentication, middleBrick tests various token manipulation techniques:

Authorization: Bearer invalid-token
Authorization: Bearer
Authorization: Basic Zm9vOmJhcg==
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... (malformed JWT)

The scanner also checks for Rails-specific session vulnerabilities, including predictable session IDs and improper session storage configurations.

Rails-Specific Remediation

Remediating Broken Authentication in Rails requires leveraging the framework's built-in security features. Here are Rails-specific fixes for common vulnerabilities:

Session Management:

class ApplicationController < ActionController::Base
before_action :authenticate_user!

protected

def authenticate_user!
if session[:user_id].nil?
redirect_to login_path, alert: 'Please log in'
end
end

def current_user
@current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
end
helper_method :current_user
end

Proper Session Regeneration:

class SessionsController < ApplicationController
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
reset_session
session[:user_id] = user.id
redirect_to dashboard_path
else
flash.now[:alert] = 'Invalid credentials'
render :new
end
end
end

Strong Parameters (Rails 4+):

class UsersController < ApplicationController
before_action :set_user, only: [:show, :update, :destroy]
  # Never trust parameters from the scary internet, only allow the white list through
def user_params
params.require(:user).permit(:email, :password, :password_confirmation)
end
end

CSRF Protection:

# In ApplicationController
protect_from_forgery with: :exception

# In your forms
<%= form_with model: @user do |f| %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.submit %>
<% end %>

API Authentication with Devise:

class ApplicationController < ActionController::Base
before_action :authenticate_user!

def authenticate_user!
authenticate_or_request_with_http_token do |token, options|
User.find_by(auth_token: token)
end

Rate Limiting with Rack::Attack:

class Rack::Attack
# Throttle login attempts
throttle('logins/ip', limit: 5, period: 20) do |req|
if req.path == '/login' && req.post?
req.ip
end
end

# Throttle API requests
throttle('api/ip', limit: 100, period: 300) do |req|
if req.path.starts_with?('/api')
req.ip
end
end
end

Related CWEs: authentication

CWE IDNameSeverity
CWE-287Improper Authentication CRITICAL
CWE-306Missing Authentication for Critical Function CRITICAL
CWE-307Brute Force HIGH
CWE-308Single-Factor Authentication MEDIUM
CWE-309Use of Password System for Primary Authentication MEDIUM
CWE-347Improper Verification of Cryptographic Signature HIGH
CWE-384Session Fixation HIGH
CWE-521Weak Password Requirements MEDIUM
CWE-613Insufficient Session Expiration MEDIUM
CWE-640Weak Password Recovery HIGH

Frequently Asked Questions

How does middleBrick detect authentication bypass in Rails applications?

middleBrick performs black-box scanning by sending unauthenticated requests to protected Rails endpoints. It analyzes HTTP responses for authentication bypass indicators, checks session cookie security attributes, tests token manipulation, and examines route configurations. The scanner also validates that authentication requirements specified in your OpenAPI/Swagger specs match the actual runtime implementation.

Can middleBrick scan my Rails application without access to the source code?

Yes, middleBrick is a black-box scanner that requires only the API endpoint URL. It tests the unauthenticated attack surface by sending requests and analyzing responses, without needing source code, database access, or credentials. This makes it ideal for testing staging APIs, third-party services, or production endpoints where source access isn't available.