Headed to RSA? Schedule time to discuss how Qwiet AI agents can help secure your software

AppSec Resources
Article

AppSec Mistakes To Avoid When Building Your Rails App

Introduction

Ruby on Rails (Rails) has become popular for web application building due to its simplicity and convention-over-configuration approach. While these features make Rails development efficient and accessible, they also present unique security challenges. Developers need to be aware of the potential vulnerabilities arising from these conventions and how to address them effectively to keep applications secure. This article explores common security pitfalls encountered in Rails development, such as issues with SQL injection, XSS, mass assignment, and file handling.

Common Security Mistakes in Rails Applications

SQL Injection via Dynamic Queries

SQL injection remains a common vulnerability in Rails, especially when developers use dynamic queries that include user input. It happens when attackers manipulate input to execute arbitrary SQL commands, potentially accessing or altering database content without proper authorization. This issue typically arises when user input is interpolated directly into query strings, bypassing Rails’ built-in protections.

A common mistake is using raw user input in dynamic SQL queries. Interpolating user-supplied data directly into query strings can create exploitable vulnerabilities. Consider the following example:

# Example of insecure code prone to SQL injection
User.where(“email = ‘#{params[:email]}'”) # Unsafe, vulnerable to SQL injection

In this code, params[:email] is inserted directly into the SQL query string. If an attacker inputs [email protected]’ OR ‘1’=’1, the query becomes:

SELECT * FROM users WHERE email = [email protected] OR ‘1’=‘1’;

 

This query bypasses the intended condition, potentially exposing all records in the users table. Such vulnerabilities can be leveraged for unauthorized data access and other harmful actions.

Secure Alternatives Using ActiveRecord’s Parameterized Queries

To avoid SQL injection, Rails developers should use parameterized queries provided by ActiveRecord. This method separates SQL logic from data, ensuring user input is treated as a parameter rather than code:

# Example of secure code using parameterized queries
User.where(email: params[:email]) # Safe, using parameterized queries

In this example, params[:email] is bound as a query parameter, preventing user input from altering the query structure. Rails handles the input safely, rendering any injection attempts ineffective. This simple adjustment prevents potential exploitation by treating user input as data, not executable SQL.

How Qwiet Can Help

Qwiet’s SAST tool, equipped with its Code Property Graph (CPG) and AI-driven analysis, can dynamically detect potential SQL injection points in Rails applications. 

By mapping how data flows through the code, Qwiet identifies instances where user input might be directly included in query strings. It flags these risky patterns for developers to review and provides detailed insights to support secure coding practices. This proactive detection helps Rails developers mitigate SQL injection vulnerabilities before they become an issue.

Cross-Site Scripting (XSS) in Rails Views

Improper handling of user input in views can lead to XSS (Cross-Site Scripting) vulnerabilities, particularly risky in Rails applications with dynamic content. XSS allows attackers to inject malicious scripts that run in the context of a user’s browser, potentially stealing sensitive information, hijacking sessions, or manipulating the user interface. This can occur when user input is rendered in the view without proper encoding.

A common mistake is rendering user-generated content without escaping it, which allows the browser to execute any embedded scripts within the input. This is especially problematic when developers directly output parameters or user-provided data without applying the proper encoding.

Example of Insecure Code in a View

<%= params[:user_input] %> # Unsafe, directly renders user input without escaping

In this code snippet, params[:user_input] is rendered directly into the view without any escaping. If an attacker inputs something like <script>alert(‘XSS’)</script>, it will be executed by the browser when the page loads. This exposes users to potential attacks, allowing attackers to run arbitrary JavaScript in their browser session.

Safe Practices for Input Handling in Rails

Rails comes with built-in protections for handling user input safely. The h method (or simply relying on Rails’ default behavior when outputting user data) automatically escapes potentially harmful characters, converting them to safe HTML entities.

<%= h params[:user_input] %> # Automatically escapes user input

With this code, any special characters in params[:user_input] are escaped, preventing scripts from executing in the user’s browser. This ensures that user-generated content is displayed as plain text, rather than being interpreted as HTML or JavaScript. While html_safe can render safe content without escaping, it should only be applied when you know the content is sanitized.

How Qwiet Can Help

Qwiet’s SAST tool excels in identifying potential XSS vulnerabilities in Rails applications by analyzing code paths where user input is rendered in views. Using its Code Property Graph (CPG) technology, Qwiet pinpoints unescaped data outputs and highlights these issues with detailed insights. This helps developers secure user-facing components by flagging areas where user input might be rendered unsafely, ensuring that such vulnerabilities are caught and resolved before reaching production.

Mass Assignment and Insecure Parameter Handling

Rails applications can be vulnerable to mass assignment when user-controlled data is not properly filtered. Mass assignment happens when user parameters are automatically mapped to model attributes. Without control over which attributes can be updated, attackers could set or modify sensitive fields that should remain protected. This can lead to unauthorized changes, data corruption, or privilege escalation.

One common pitfall is using methods like update or create with user-supplied parameters without filtering the permitted attributes. This allows attackers to manipulate parameters to include restricted fields, which can be used to overwrite sensitive data or escalate privileges.

Example of Insecure Mass Assignment

# Example of insecure mass assignment
User.update(params[:user]) # Insecure, allows modification of all attributes

In this code, params[:user] may contain attributes, including those not meant to be user-editable, such as admin or role. An attacker could submit a form with these hidden or modified attributes, potentially elevating their access level or altering critical data in the application. This type of vulnerability is particularly dangerous when models include sensitive fields that authorized processes should only modify.

Secure Methods Using Strong Parameters

To protect against mass assignment, Rails developers should use strong parameters to specify which attributes can be mass-assigned. This ensures that only whitelisted fields can be updated, even if malicious data is submitted.

# Example of secure parameter handling using strong parameters
user.update(params.require(:user).permit(:name, :email)) # Securely whitelists attributes

 

In this code, params.require(:user).permit(:name,:email) specifies that only the name and email attributes can be updated. The update method will ignore any attempt to include other fields, such as admin or role. This simple adjustment ensures that user input is filtered, minimizing the risk of unintended modifications.

How Qwiet Can Help

Qwiet identifies mass assignment vulnerabilities in Rails applications by analyzing code in models and controllers. It flags instances where parameters are used without strong filtering, guiding developers to review and implement secure practices like strong parameters. By highlighting these potential vulnerabilities, Qwiet helps teams catch unsafe code early, preventing exploitation related to mass assignment and keeping sensitive attributes protected.

Insecure File Uploads and Lack of Validation

If not properly validated, file uploads in Rails applications can pose significant security risks. Unvalidated files can lead to remote code execution (RCE), allowing attackers to execute arbitrary code on the server or the storage of malicious files that can compromise application data. This can occur when applications do not check the file type, size, or contents, potentially allowing dangerous files to be uploaded and executed.

Common mistakes include accepting file uploads without verifying their content type, size, or safety. When developers fail to apply strict checks on uploaded files, it becomes easier for attackers to upload scripts or executable files that can be run by the server, leading to serious security issues.

Example of Unsafe File Upload Handling

# Example of insecure file upload handling
@user.avatar.attach(params[:avatar]) # Unsafe, allows unvalidated files

In this code, params[:avatar] are attached directly to the user’s avatar without validation. Any file, regardless of its type or content, could be uploaded and stored. An attacker could use this flaw to upload a script or a file with malicious code disguised as an image or document, potentially leading to execution if the server processes it or exposes it in a way that triggers execution.

Best Practices for File Upload Security

Rails developers should validate the content type and size of the uploaded files to enhance the security of file uploads. This ensures that only files matching approved types and sizes are accepted, reducing the risk of handling potentially dangerous files.

ruby

Copy code

# Example of secure file upload handling with validation
if params[:avatar].content_type.in?(%w[image/png image/jpg image/jpeg]) && params[:avatar].size < 5.megabytes
  @user.avatar.attach(params.require(:avatar)) # Secure, validated
else
  # Handle invalid file scenario
  flash[:alert] = “Invalid file type or size.”
end

In this example, the content_type check ensures that only images with specific types (png, jpg, jpeg) are allowed. The size check ensures that the file size is under 5 megabytes, adding an extra validation layer. These checks prevent malicious files from being uploaded and limit the risk of processing unexpected or harmful files.

How Qwiet AI Can Help

Qwiet AI can identify insecure file handling practices in Rails applications. It scans for areas where file uploads are managed without proper validations and flags these as potential risks. By analyzing how files are accepted and processed, Qwiet provides developers with detailed feedback on where validation checks are missing or insufficient. This proactive approach helps teams secure their applications against vulnerabilities related to file uploads, ensuring that only safe, validated files are processed and stored.

Qwiet’s Native Support for Rails Security Testing

Qwiet is a SAST tool built with native support for Ruby on Rails, catering specifically to the needs of Rails developers. Its specialized capabilities allow it to understand Rails-specific structures and conventions, making it highly effective in identifying vulnerabilities within Rails applications. Whether you are dealing with models, controllers, or views, Qwiet AI’s tailored analysis helps pinpoint issues unique to Rails development, offering detailed insights to guide secure coding practices.

One standout feature of our platform is the ability to perform deep code scans locally through its preZero technology. This method creates a Code Property Graph (CPG) locally and sends only this graph to the cloud for further analysis without exposing the source code itself. This local-first approach enhances privacy and security, ensuring that your proprietary codebase remains under your control while still benefiting from advanced scanning and vulnerability detection

To find out more about how Qwiet AI can help secure your Rails App, book a demo today.

About Qwiet AI

Qwiet AI empowers developers and AppSec teams to dramatically reduce risk by quickly finding and fixing the vulnerabilities most likely to reach their applications and ignoring reported vulnerabilities that pose little risk. Industry-leading accuracy allows developers to focus on security fixes that matter and improve code velocity while enabling AppSec engineers to shift security left.

A unified code security platform, Qwiet AI scans for attack context across custom code, APIs, OSS, containers, internal microservices, and first-party business logic by combining results of the company’s and Intelligent Software Composition Analysis (SCA). Using its unique graph database that combines code attributes and analyzes actual attack paths based on real application architecture, Qwiet AI then provides detailed guidance on risk remediation within existing development workflows and tooling. Teams that use Qwiet AI ship more secure code, faster. Backed by SYN Ventures, Bain Capital Ventures, Blackstone, Mayfield, Thomvest Ventures, and SineWave Ventures, Qwiet AI is based in Santa Clara, California. For information, visit: https://qwietdev.wpengine.com

application-security cross-site-scripting cybersecurity development-best-practices rails-security ruby-on-rails secure-coding sql-injection vulnerability-management web-development