Arp Spoofing in Hanami
How Arp Spoofing Manifests in Hanami
Arp Spoofing in Hanami applications typically exploits the framework's routing and middleware stack to intercept or manipulate API traffic. In Hanami's architecture, HTTP requests flow through a series of middleware before reaching the action controllers, creating potential interception points.
The most common manifestation occurs when attackers manipulate ARP tables to redirect traffic intended for your Hanami API to their own machine. Once positioned as a man-in-the-middle, they can exploit Hanami's request processing pipeline. For instance, if your Hanami application uses WebSockets for real-time features, an attacker positioned via ARP spoofing can intercept the upgrade handshake and inject malicious WebSocket frames.
Consider a Hanami action that handles file uploads:
class Uploads::Create < Hanami::Action
def handle(req, res)
file = req.params[:file]
# Process file upload
res.body = { status: 'success' }
end
endWhen ARP spoofing is active, an attacker can intercept the multipart form data before it reaches this action, potentially modifying the file content or injecting malicious payloads. The Hanami middleware stack processes the request sequentially, meaning any ARP-based interception occurs before your application logic executes.
Another vulnerability pattern involves Hanami's session management. If your application uses cookie-based sessions:
class Application < Hanami::Application
configure do
sessions do
cookie name: 'hanami_session', secret: ENV['SESSION_SECRET']
end
end
endARP spoofing allows attackers to capture session cookies in transit, enabling session hijacking. The attacker can then craft requests with the stolen session ID, bypassing authentication checks in your Hanami actions.
Hanami's routing system can also be targeted. If your application exposes internal APIs through route patterns like:
routes.draw do
get '/api/internal/:id', to: 'internal#show'
endAn ARP-spoofing attacker can intercept requests and modify the :id parameter before it reaches the action, potentially accessing resources they shouldn't have permission to view.
Hanami-Specific Detection
Detecting ARP spoofing in Hanami applications requires monitoring both network-level indicators and application-level anomalies. From a network perspective, you can implement middleware that checks for unusual ARP traffic patterns.
Here's a Hanami middleware that detects potential ARP spoofing by monitoring request source consistency:
class ArpSpoofingDetector
def initialize(app)
@app = app
@request_tracker = {}
end
def call(env)
ip = env['REMOTE_ADDR']
user_agent = env['HTTP_USER_AGENT']
# Track request patterns for this IP/user agent combination
key = "#{ip}::#{user_agent}"
if @request_tracker[key]
last_request = @request_tracker[key]
# If requests are coming too fast from the same source
if time_diff < 0.1 && last_request[:ip] != ip
# Potential ARP spoofing detected
log_spoofing_attempt(ip, last_request[:ip], env)
end
end
@request_tracker[key] = { time: Time.now, ip: ip }
end
private
def log_spoofing_attempt(current_ip, previous_ip, env)
# Log to monitoring system
puts "[ARP SPOOFING ALERT] IP changed from #{previous_ip} to #{current_ip}"
# You could also trigger alerts or block the request
endRegister this middleware in your Hanami application:
class Application < Hanami::Application
configure do
middleware do
use ArpSpoofingDetector
end
end
endFor automated detection, middleBrick's API security scanner can identify ARP spoofing-related vulnerabilities by analyzing your Hanami application's attack surface. The scanner examines:
- Authentication bypass opportunities in your Hanami actions
- Session management weaknesses that could be exploited via ARP interception
- Input validation gaps that allow parameter manipulation
- WebSocket endpoint security configurations
middleBrick's scanning process for Hanami applications includes testing for IDOR (Insecure Direct Object Reference) vulnerabilities that ARP spoofing could exploit, as well as checking for proper authentication implementation across all API endpoints.
Hanami-Specific Remediation
Securing Hanami applications against ARP spoofing requires a defense-in-depth approach. Start by implementing strong authentication and authorization at the application level, ensuring that even if traffic is intercepted, the attacker cannot easily exploit it.
Here's a secure Hanami action pattern that mitigates ARP spoofing risks:
class Secure::Show < Hanami::Action
include Secured # Custom concern for authentication
def handle(req, res)
# Verify user has permission to access this resource
authorize_resource(req.params[:id], current_user(req))
# Use parameterized queries to prevent injection
record = Repository.find_by_id(req.params[:id])
halt 404 if record.nil? || record.user_id != current_user(req).id
res.body = record.to_h
end
private
def authorize_resource(resource_id, user)
# Check permissions in database, not just from request params
unless Policy.can_view?(user, resource_id)
halt 403, 'Access denied'
end
end
endImplement request signing to detect tampering from ARP-based interceptions:
class SignedRequestMiddleware
def initialize(app)
@app = app
end
def call(env)
request = Rack::Request.new(env)
# Verify request signature if present
if request.path.start_with?('/api/signed')
unless valid_signature?(request)
return [401, {}, ['Invalid signature']]
end
end
@app.call(env)
end
private
def valid_signature?(request)
signature = request.get_header('HTTP_X_REQUEST_SIGNATURE')
payload = request.body.read
expected = OpenSSL::HMAC.hexdigest('SHA256', ENV['SIGNING_SECRET'], payload)
ActiveSupport::SecurityUtils.secure_compare(signature, expected)
end
endAdd this middleware to your Hanami application configuration:
class Application < Hanami::Application
configure do
middleware do
use SignedRequestMiddleware
end
end
endFor WebSocket connections, implement origin checking and authentication tokens:
class WebSocket::Connection < Hanami::Action
def handle(req, res)
# Verify origin header to prevent ARP-based hijacking
unless valid_origin?(req.env['HTTP_ORIGIN'])
halt 403
end
# Require authentication token for WebSocket upgrade
token = extract_token(req)
halt 401 unless valid_token?(token)
# Establish secure WebSocket connection
ws.on :message do |event|
process_message(event.data)
end
end
end
endFinally, implement rate limiting to prevent automated ARP-based attacks:
class RateLimited::Create < Hanami::Action
include RateLimited # Custom concern
def handle(req, res)
# Rate limiting automatically applied by concern
# Process request only if within limits
record = Repository.create(req.params)
res.body = { id: record.id }
end
endThese remediation patterns work together to ensure that even if an attacker successfully performs ARP spoofing, they cannot easily exploit your Hanami application due to the multiple layers of security.