### Start Rails Server
Source: https://github.com/presidentbeef/brakeman/blob/main/test/apps/rails3.2/README.rdoc
Navigate to your application directory and start the Rails server. Use '--help' for available options.
```bash
cd myapp; rails server
```
--------------------------------
### Build and Install Brakeman Gem
Source: https://github.com/presidentbeef/brakeman/blob/main/README.md
Instructions for cloning the Brakeman repository, building the gem, and installing it locally. This is useful for development or if you need a specific version.
```sh
git clone git://github.com/presidentbeef/brakeman.git
cd brakeman
gem build brakeman.gemspec
gem install brakeman*.gem
```
--------------------------------
### Output Current Brakeman Options
Source: https://github.com/presidentbeef/brakeman/blob/main/README.md
The `-C` option outputs the current configuration, which can be useful for generating a starting point for a configuration file. This example skips the 'plugins/' directory.
```sh
$ brakeman -C --skip-files plugins/
---
:skip_files:
- plugins/
```
--------------------------------
### Install Brakeman via Docker
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Pull the Brakeman Docker image for containerized use.
```bash
docker pull presidentbeef/brakeman
```
--------------------------------
### Run Full Test Suite
Source: https://github.com/presidentbeef/brakeman/blob/main/test/README.md
Execute the complete Brakeman test suite. Ensure you have run `bundle` first to install dependencies.
```bash
bundle
rake
```
--------------------------------
### Install Brakeman via RubyGems
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Install Brakeman using the RubyGems package manager.
```bash
gem install brakeman
```
--------------------------------
### Example Test Methods Generated by to_test.rb
Source: https://github.com/presidentbeef/brakeman/wiki/How-to-Report-a-Brakeman-Issue
These are example test methods generated by the `to_test.rb` script. They use `assert_warning` to check for specific Brakeman warnings.
```ruby
#...
def test_command_injection_1
assert_warning :type => :warning,
:warning_type => "Command Injection",
:line => 34,
:message => /^Possible\ command\ injection/,
:confidence => 0,
:file => /home_controller\.rb/
end
def test_command_injection_2
assert_warning :type => :warning,
:warning_type => "Command Injection",
:line => 36,
:message => /^Possible\ command\ injection/,
:confidence => 0,
:file => /home_controller\.rb/
end
#...
```
--------------------------------
### Use the Rails Debugger
Source: https://github.com/presidentbeef/brakeman/blob/main/test/apps/rails3.2/README.rdoc
Enable the debugger by starting your server with the '--debugger' flag. This allows you to pause execution and inspect/modify application state.
```ruby
class WeblogController < ActionController::Base
def index
@posts = Post.all
debugger
end
end
```
--------------------------------
### Clone Brakeman Repository
Source: https://github.com/presidentbeef/brakeman/wiki/How-to-Report-a-Brakeman-Issue
Clone the Brakeman repository to your local machine to start contributing.
```bash
git clone your_new_fork
```
--------------------------------
### Get File Paths
Source: https://github.com/presidentbeef/brakeman/wiki/Adding-a-New-Report-Format
Choose the appropriate method for file paths based on your formatter's needs: `Warning#file` for absolute paths, `relative_path(warning.file)` for relative paths, or `warning_file(warning)` for automatic selection.
```ruby
absolute_path = warning.file
relative_path = relative_path(warning.file)
auto_path = warning_file(warning)
```
--------------------------------
### Unprotected Mass Assignment Example
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/mass_assignment/index.markdown
This example shows a common mass assignment vulnerability where user input directly populates a model. Brakeman warns on such instances.
```ruby
User.new(params[:user])
```
--------------------------------
### Install Brakeman with Bundler
Source: https://github.com/presidentbeef/brakeman/blob/main/README.md
Add Brakeman to your development dependencies in your Gemfile.
```ruby
group :development do
gem 'brakeman', require: false
end
```
--------------------------------
### Basic Authentication with Hardcoded Password
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/basic_auth/index.markdown
This example shows how to implement basic authentication in a Rails controller. The warning is raised if the password is a hardcoded string.
```ruby
class PostsController < ApplicationController
http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index
#...
end
```
--------------------------------
### Example Brakeman Test Case
Source: https://github.com/presidentbeef/brakeman/blob/main/CONTRIBUTING.md
This is an example of a generated test case for Brakeman, using `assert_warning` to check for specific warning types, messages, line numbers, and confidence levels.
```ruby
#...
def test_command_injection_1
assert_warning :type => :warning,
:warning_type => "Command Injection",
:line => 34,
:message => /^Possible\ command\ injection/,
:confidence => 0,
:file => /home_controller\.rb/
end
def test_command_injection_2
assert_warning :type => :warning,
:warning_type => "Command Injection",
:line => 36,
:message => /^Possible\ command\ injection/,
:confidence => 0,
:file => /home_controller\.rb/
end
#...
```
--------------------------------
### Unsafe Redirect with User Input
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/redirect/index.markdown
This example shows a redirect that uses user-supplied parameters, which could be manipulated to redirect to a malicious site. Brakeman will warn about this pattern.
```ruby
redirect_to params.merge(:action => :home)
```
--------------------------------
### Run Brakeman Tests
Source: https://github.com/presidentbeef/brakeman/blob/main/CONTRIBUTING.md
Execute Brakeman's test suite using either the `ruby test/test.rb` command or the `rake` task. Install `simplecov` before running tests to generate a test coverage report in `coverage/index.html`.
```ruby
ruby test/test.rb
```
```ruby
rake
```
--------------------------------
### Unsafe YAML.load Usage
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/remote_code_execution_yaml_load/index.markdown
Avoid passing user input directly to YAML.load. This example demonstrates an unsafe practice that can lead to arbitrary code execution.
```ruby
#Do not do this!
YAML.load(params[:file])
```
--------------------------------
### Writing a Custom Brakeman Check
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Create custom security checks by inheriting from `Brakeman::BaseCheck`, registering with `Brakeman::Checks.add`, and implementing the `run_check` method. This example checks for user input passed directly to `Rails.logger`.
```ruby
# File: path/to/checks/check_unsafe_logger.rb
require 'brakeman/checks/base_check'
class Brakeman::CheckUnsafeLogger < Brakeman::BaseCheck
Brakeman::Checks.add self
@description = "Checks for user input passed directly to Rails.logger"
def run_check
# Find all calls to Rails.logger.info / .debug / .warn / .error
tracker.find_call(target: :'Rails.logger', method: [:info, :debug, :warn, :error]).each do |result|
next unless original?(result)
call = result[:call]
# Check if any argument contains direct user input
call.arguments.each do |arg|
if match = has_immediate_user_input?(arg)
warn result: result,
warning_type: "Information Disclosure",
warning_code: :custom_check,
message: msg("Possible sensitive data leak: ", msg_input(match), " passed to logger"),
confidence: :medium,
user_input: match
end
end
end
end
end
```
--------------------------------
### Safe Scoped Find in Rails
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/unscoped_find/index.markdown
This example demonstrates a secure way to find records by scoping the query to the currently logged-in user. This prevents unauthorized access to other users' data.
```ruby
current_user = User.find(session[:user_id])
current_user.accounts.find(params[:id])
```
--------------------------------
### Display Help
Source: https://github.com/presidentbeef/brakeman/wiki/Brakeman-Commandline-Options
Display all available commandline options with brief explanations.
```bash
brakeman -h
```
```bash
brakeman --help
```
--------------------------------
### Create Configuration File
Source: https://github.com/presidentbeef/brakeman/wiki/Brakeman-Commandline-Options
Dump commandline configuration options to a YAML file instead of running a scan. If no file is specified, output goes to standard output.
```bash
brakeman -C config.yml
```
```bash
brakeman --create-config config.yml
```
--------------------------------
### Manage Ignored Warnings
Source: https://github.com/presidentbeef/brakeman/blob/main/README.md
Use Brakeman to create and manage the ignore configuration file.
```bash
brakeman -I
```
--------------------------------
### Rails 2.x link_to Vulnerability Example
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/link_to/index.markdown
In Rails 2.x, `link_to` did not escape the HREF body. This example shows how a script tag in the HREF could execute.
```ruby
link_to "", "http://google.com"
```
--------------------------------
### Get Brakeman Scan Time
Source: https://github.com/presidentbeef/brakeman/wiki/Benchmarking-Brakeman
Use the --summary flag to get Brakeman's reported scan time, excluding startup and report generation penalties for more accurate benchmarking.
```bash
brakeman -q --summary
```
--------------------------------
### Report Controller and Route Information
Source: https://github.com/presidentbeef/brakeman/blob/main/OPTIONS.md
Enable the reporting of controller and route information with the `--routes` flag.
```bash
brakeman --routes
```
--------------------------------
### Specify Ignore Configuration File
Source: https://github.com/presidentbeef/brakeman/blob/main/OPTIONS.md
Use the `-i` flag to specify a custom configuration file for ignoring warnings.
```bash
brakeman -i path/to/config.ignore
```
--------------------------------
### Rails 2.x XSS Vulnerability Example
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/cross_site_scripting_to_json/index.markdown
This example demonstrates how a Rails 2.x application can be vulnerable to XSS when `Hash#to_json` is used without proper HTML entity escaping. The injected script can break out of the JSON string and execute.
```ruby
# controller
@attrs = {:email => 'some@email.com
```
```html
```
```html
```
--------------------------------
### Run Single Test File
Source: https://github.com/presidentbeef/brakeman/blob/main/test/README.md
Execute a specific test file located in the `test/tests` directory.
```bash
ruby test/tests/some_file.rb
```
--------------------------------
### Load Configuration File
Source: https://github.com/presidentbeef/brakeman/wiki/Brakeman-Commandline-Options
Load Brakeman configuration settings from a YAML file. This file is often generated using the -C option.
```bash
brakeman -c config.yml
```
```bash
brakeman --config-file config.yml
```
--------------------------------
### Create a New Rails Application
Source: https://github.com/presidentbeef/brakeman/blob/main/test/apps/rails3.2/README.rdoc
Use the 'rails new' command to generate a new Rails application. Replace 'myapp' with your desired application name.
```bash
rails new myapp
```
--------------------------------
### Get Rails Version
Source: https://github.com/presidentbeef/brakeman/wiki/Adding-a-New-Report-Format
Retrieve the detected Rails version as a string using the `rails_version` method.
```ruby
rails_version_string = rails_version
```
--------------------------------
### Configure GitHub Repository for Markdown Links
Source: https://github.com/presidentbeef/brakeman/blob/main/OPTIONS.md
Use `--github-repo USER/REPO[/PATH][@REF]` to generate Markdown reports with links to files on GitHub.
```bash
brakeman --github-repo USER/REPO[/PATH][@REF]
```
```bash
brakeman --github-repo presidentbeef/inject-some-sql
```
--------------------------------
### List Available Checks
Source: https://github.com/presidentbeef/brakeman/wiki/Brakeman-Commandline-Options
List all available security checks with a brief description for each.
```bash
brakeman -k
```
```bash
brakeman --checks
```
--------------------------------
### Enable Debug Mode
Source: https://github.com/presidentbeef/brakeman/wiki/Brakeman-Commandline-Options
Enable debug mode to get more detailed information during the scan and in the report, including backtraces and rendered templates.
```bash
brakeman -d
```
```bash
brakeman --debug
```
--------------------------------
### Simplify Simple Addition
Source: https://github.com/presidentbeef/brakeman/wiki/Using-Brakeman::AliasProcessor
Shows how AliasProcessor simplifies basic arithmetic addition operations.
```ruby
x = 1 + 2 + 3
x += 4
x
```
```ruby
x = 6
x = 10
10
```
--------------------------------
### Run Brakeman.run with basic options
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Initiate a Brakeman scan by providing the path to the Rails application directory.
```ruby
require 'brakeman'
tracker = Brakeman.run('/path/to/rails/app')
```
--------------------------------
### Get Warning Fingerprint
Source: https://github.com/presidentbeef/brakeman/wiki/Adding-a-New-Report-Format
Use `Warning#fingerprint` to generate a unique identifier for a warning, which is useful for comparing warnings across different scans.
```ruby
unique_id = warning.fingerprint
```
--------------------------------
### Save Brakeman config to a file
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Generate a Brakeman configuration file by running brakeman with the -C flag and redirecting output.
```bash
brakeman -C --skip-files plugins/ > config/brakeman.yml
```
--------------------------------
### Unsafe Unscoped Find in Rails
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/unscoped_find/index.markdown
This example shows an unsafe unscoped `find` call. It can allow attackers to access any record, not just those belonging to the current user.
```ruby
Account.find(params[:id])
```
--------------------------------
### Generate Test Suite for Specific App
Source: https://github.com/presidentbeef/brakeman/blob/main/test/README.md
Create a new test file for a specific application within the `apps` directory. This generates tests based on reported warnings.
```bash
cd test && ruby to_test.rb apps/some_app > tests/some_app.rb
```
--------------------------------
### Output to Console and File
Source: https://github.com/presidentbeef/brakeman/blob/main/README.md
Send the report to both standard output (with color) and a JSON file.
```bash
brakeman --color -o /dev/stdout -o output.json
```
--------------------------------
### Checking for Immediate Model Usage
Source: https://github.com/presidentbeef/brakeman/wiki/Creating-Custom-Brakeman-Rules
Illustrates how to use `has_immediate_model?` to identify direct usage of models, which can be relevant for security checks.
```ruby
has_immediate_model?(some_sexp)
```
--------------------------------
### Parsing JSON Report with Ruby
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Parse the JSON report generated by Brakeman to process scan data programmatically. This example shows how to extract scan information and warnings.
```ruby
require 'json'
data = JSON.parse(report.to_json, symbolize_names: true)
puts "Scan date: #{data[:scan_info][:timestamp]}"
puts "App path: #{data[:scan_info][:app_path]}"
puts "Rails ver: #{data[:scan_info][:rails_version]}"
data[:warnings].each { |w| puts "#{w[:warning_type]}: #{w[:file]}:#{w[:line]}" }
```
--------------------------------
### Finding Multiple Targets and Methods
Source: https://github.com/presidentbeef/brakeman/wiki/Creating-Custom-Brakeman-Rules
Demonstrates how to search for multiple targets and methods simultaneously using arrays in the `tracker.find_call` options.
```ruby
tracker.find_call(target: [:x, :W], method: [:y, :z])
```
--------------------------------
### Mitigated XSS with escape_html_entities_in_json = true
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/cross_site_scripting_to_json/index.markdown
This example shows the output when `ActiveSupport#escape_html_entities_in_json` is set to `true`. The potentially harmful characters are correctly escaped, preventing the XSS attack.
```html
```
--------------------------------
### Run Tests Without Bundler
Source: https://github.com/presidentbeef/brakeman/blob/main/test/README.md
Alternative method to run the test suite without using Bundler. This directly executes the main test file.
```bash
ruby test/test.rb
```
--------------------------------
### Inspect and Modify Objects in Debugger
Source: https://github.com/presidentbeef/brakeman/blob/main/test/apps/rails3.2/README.rdoc
When the debugger is active, you can interact with your application's objects via an IRB prompt in the server window. This example shows inspecting and modifying a Post object.
```irb
>> @posts.inspect
=> "[#nil, \"body\"=>nil, \"id\"=>\"1\"}>,
#\"Rails\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
>> @posts.first.title = "hello from a debugger"
=> "hello from a debugger"
```
```irb
>> f = @posts.first
=> #nil, "body"=>nil, "id"=>"1"}>
>> f.
Display all 152 possibilities? (y or n)
```
--------------------------------
### Basic SQL Injection in Rails 2.x
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/sql_injection/index.markdown
This example demonstrates a common SQL injection vulnerability in older Rails versions (2.x) by directly interpolating user input into a SQL query's conditions.
```ruby
User.first(:conditions => "username = '#{params[:username]}'")
```
--------------------------------
### Simplify Hash Operations
Source: https://github.com/presidentbeef/brakeman/wiki/Using-Brakeman::AliasProcessor
Demonstrates simplification of hash assignments and merges.
```ruby
x = {:goodbye => "goodbye cruel world" }
x[:hello] = "hello world"
x.merge! :goodbye => "You say goodbye, I say :hello"
x[:goodbye]
```
```ruby
x = { :goodbye => "goodbye cruel world" }
{ :goodbye => "goodbye cruel world" }[:hello] = "hello world"
{ :goodbye => "You say goodbye, I say :hello", :hello => "hello world" }
"You say goodbye, I say :hello"
```
--------------------------------
### Basic content_tag Usage
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/content_tag/index.markdown
Demonstrates the basic usage of `content_tag` to generate an HTML paragraph with simple content.
```ruby
content_tag :p, "Hi!"
=> "Hi!
"
```
--------------------------------
### SQL Injection with String Concatenation in Rails 3.x
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/sql_injection/index.markdown
This example illustrates a SQL injection vulnerability in Rails 3.x using string concatenation to build a WHERE clause with user-provided data. Local variables are also used here.
```ruby
username = params[:user][:name].downcase
password = params[:user][:password]
User.first.where("username = '" + username + "' AND password = '" + password + "'")
```
--------------------------------
### Loading Custom Checks via Command Line
Source: https://github.com/presidentbeef/brakeman/wiki/Creating-Custom-Brakeman-Rules
Specify paths to custom check directories using the `--add-checks-path` option. Multiple paths can be comma-separated.
```bash
--add-checks-path path/to/checks/
```
--------------------------------
### Multiple Output Files
Source: https://github.com/presidentbeef/brakeman/blob/main/README.md
Generate reports in multiple formats by specifying multiple output files.
```bash
brakeman -o output.html -o output.json
```
--------------------------------
### Template Location in JSON Reports
Source: https://github.com/presidentbeef/brakeman/wiki/Upcoming-Changes-in-Brakeman-3.1
This example shows the 'location' field within a JSON report, indicating a rendered template. This specific format will be removed in Brakeman 3.1 as it is considered redundant with the updated render path information.
```json
"location": {
"type": "template",
"template": "home/index (HomeController#index)"
}
```
--------------------------------
### Unsafe Command Execution with String Interpolation
Source: https://github.com/presidentbeef/brakeman/blob/main/docs/warning_types/command_injection/index.markdown
These examples show common Ruby methods that are vulnerable to command injection when user input is directly interpolated into shell commands. Avoid interpolating user-controlled data into commands executed by the system.
```ruby
`ls #{params[:file]}`
```
```ruby
system("ls #{params[:dir]}")
```
```ruby
exec("md5sum #{params[:input]}")
```
--------------------------------
### Specify URL Safe Methods
Source: https://github.com/presidentbeef/brakeman/blob/main/OPTIONS.md
Use `--url-safe-methods` to ignore warnings for methods that ensure safe URL protocols.
```bash
brakeman --url-safe-methods ensure_safe_protocol_or_something
```
--------------------------------
### Simplify Simple Math Operations
Source: https://github.com/presidentbeef/brakeman/wiki/Using-Brakeman::AliasProcessor
Demonstrates simplification of multiplication, division, and subtraction.
```ruby
x = 8 * 5
y = 32 / 8
y -= 2
x += y
x
```
```ruby
x = 40
y = 4
y = 2
x = 42
42
```
--------------------------------
### Run Brakeman and Handle Exit Codes
Source: https://context7.com/presidentbeef/brakeman/llms.txt
This code snippet demonstrates how to run Brakeman programmatically and handle specific exit codes for different error conditions, such as security warnings or the absence of a Rails application. Ensure Brakeman is installed and accessible.
```ruby
require 'brakeman'
begin
tracker = Brakeman.run(app_path: '/path/to/rails/app', quiet: true)
exit 0 if tracker.warnings.empty?
exit Brakeman::Warnings_Found_Exit_Code
rescue Brakeman::NoApplication => e
$stderr.puts "Not a Rails app: #{e.message}"
exit Brakeman::No_App_Found_Exit_Code
rescue Brakeman::MissingChecksError => e
$stderr.puts "Unknown check: #{e.message}"
exit Brakeman::Missing_Checks_Exit_Code
end
```
--------------------------------
### Run Brakeman in Quiet Mode
Source: https://github.com/presidentbeef/brakeman/wiki/Benchmarking-Brakeman
Use quiet mode and pipe the report to /dev/null to avoid I/O inconsistencies during benchmarking.
```bash
brakeman -q -o /dev/null
```
--------------------------------
### Run Brakeman.run with full options
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Perform a comprehensive Brakeman scan using a detailed options hash, including confidence levels, skipped checks, and output file configurations.
```ruby
require 'brakeman'
# Full options example
tracker = Brakeman.run(
app_path: '/path/to/rails/app',
quiet: true,
min_confidence: 1, # 0=High only, 1=Medium+, 2=All (Weak+)
skip_checks: ['SymbolDoS'],
safe_methods: ['my_sanitizer'],
sql_safe_methods: ['escape_for_sql'],
parallel_checks: true,
output_files: ['report.html', 'report.json'],
github_repo: 'myorg/myapp'
)
```
--------------------------------
### Run Brakeman with Docker
Source: https://github.com/presidentbeef/brakeman/blob/main/README.md
Use Docker to run Brakeman, mounting your Rails application directory. Options for color output and HTML reports are available.
```bash
docker run -v "$(pwd)":/code presidentbeef/brakeman
```
```bash
docker run -v "$(pwd)":/code presidentbeef/brakeman --color
```
```bash
docker run -v "$(pwd)":/code presidentbeef/brakeman -o brakeman_results.html
```
```bash
docker run -v 'path/to/rails/application':/code presidentbeef/brakeman -o brakeman_results.html
```
--------------------------------
### Run Brakeman with a custom config file
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Use the -c flag to specify a custom configuration file path for Brakeman scans.
```bash
brakeman -c path/to/my_brakeman.yml
```
--------------------------------
### Finding Method Calls with tracker.find_call
Source: https://github.com/presidentbeef/brakeman/wiki/Creating-Custom-Brakeman-Rules
Demonstrates how to use the `tracker.find_call` utility to locate specific method calls, including options for targeting specific methods and receivers.
```ruby
tracker.find_call(target: :x, method: :y)
```
--------------------------------
### Enable Debugging Information
Source: https://github.com/presidentbeef/brakeman/blob/main/README.md
Display detailed debugging information during the scan.
```bash
brakeman -d
```
--------------------------------
### Checking for Included User Input
Source: https://github.com/presidentbeef/brakeman/wiki/Creating-Custom-Brakeman-Rules
Shows how to use `include_user_input?` to determine if user input exists anywhere within a given sexp, including nested structures.
```ruby
include_user_input?(some_sexp)
```
--------------------------------
### Checking for Immediate User Input
Source: https://github.com/presidentbeef/brakeman/wiki/Creating-Custom-Brakeman-Rules
Explains the use of `has_immediate_user_input?` to detect dangerous values like request parameters, cookies, or headers within a given sexp.
```ruby
has_immediate_user_input?(some_sexp)
```
--------------------------------
### Push Changes to Origin
Source: https://github.com/presidentbeef/brakeman/wiki/How-to-Report-a-Brakeman-Issue
Push your committed changes to your remote fork.
```bash
git push origin fix_some_broken_stuff
```
--------------------------------
### Run All Brakeman Checks
Source: https://github.com/presidentbeef/brakeman/blob/main/OPTIONS.md
Use the -A flag to enable all available security checks. This provides a comprehensive analysis but may increase scan time.
```bash
brakeman -A
```
--------------------------------
### Generate Brakeman Configuration File
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Use the -C flag to print current Brakeman options as YAML. This output can be saved to a configuration file (e.g., config/brakeman.yml) for persistent settings.
```bash
brakeman -C --skip-files plugins/
```
```yaml
---
:skip_files:
- plugins/
```
--------------------------------
### Simplify Unknown Hash Assignment
Source: https://github.com/presidentbeef/brakeman/wiki/Using-Brakeman::AliasProcessor
Illustrates simplification of hash assignment with an unknown hash object.
```ruby
some_hash[:x] = 1
p some_hash[:x]
```
```ruby
some_hash[:x] = 1
p(1)
```
--------------------------------
### Brakeman Docker Usage
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Run Brakeman scans using Docker. Mount your application code into the container and specify options as command-line arguments.
```bash
# Scan the current directory (mount as /code)
docker run --rm -v "$(pwd)":/code presidentbeef/brakeman
```
```bash
# With color output
docker run --rm -v "$(pwd)":/code presidentbeef/brakeman --color
```
```bash
# Save HTML report to the mounted directory
docker run --rm -v "$(pwd)":/code presidentbeef/brakeman -o brakeman_results.html
```
```bash
# JSON report, quiet mode, minimum confidence 1
docker run --rm -v "$(pwd)":/code presidentbeef/brakeman -q -w1 -o results.json
```
--------------------------------
### Check for new security warnings after comparison
Source: https://context7.com/presidentbeef/brakeman/llms.txt
Implement a CI gate by checking if Brakeman.compare detected any new security warnings and exiting with an error code if so.
```ruby
if diff[:new].any?
puts "New security warnings introduced:"
diff[:new].each { |w| puts " #{w[:warning_type]}: #{w[:message]}" }
exit 1
else
puts "No new warnings. Fixed: #{diff[:fixed].count}"
end
```
--------------------------------
### Brakeman.run
Source: https://context7.com/presidentbeef/brakeman/llms.txt
The primary library entry point for running a full Brakeman scan. It accepts an application path or an options hash and returns a Tracker object with scan results.
```APIDOC
## Brakeman.run — Programmatic API entry point
`Brakeman.run` is the primary library entry point. It accepts an options hash (or a plain path string) and returns a `Brakeman::Tracker` object containing all scan results, warnings, errors, and metadata.
```ruby
require 'brakeman'
# Simple usage: just pass the Rails app path
tracker = Brakeman.run('/path/to/rails/app')
# Full options example
tracker = Brakeman.run(
app_path: '/path/to/rails/app',
quiet: true,
min_confidence: 1, # 0=High only, 1=Medium+, 2=All (Weak+)
skip_checks: ['SymbolDoS'],
safe_methods: ['my_sanitizer'],
sql_safe_methods: ['escape_for_sql'],
parallel_checks: true,
output_files: ['report.html', 'report.json'],
github_repo: 'myorg/myapp'
)
# Inspect results
puts "Scan duration: #{tracker.duration.round(2)}s"
puts "Warnings found: #{tracker.warnings.count}"
puts "Errors during scan: #{tracker.errors.count}"
tracker.warnings.each do |w|
puts "[#{w.confidence_name}] #{w.warning_type} in #{w.file.relative}:#{w.line}"
puts " #{w.message}"
puts " Fingerprint: #{w.fingerprint}"
end
# Generate reports programmatically
html_report = tracker.report.to_html
json_report = tracker.report.to_json
md_report = tracker.report.to_markdown
File.write('report.html', html_report)
```
```
--------------------------------
### Create a New Branch for Fixes
Source: https://github.com/presidentbeef/brakeman/wiki/How-to-Report-a-Brakeman-Issue
Create a new branch for your fixes to keep your changes organized.
```bash
git checkout -b fix_some_broken_stuff
```
--------------------------------
### Simplify Regular If/Elsif Statement
Source: https://github.com/presidentbeef/brakeman/wiki/Using-Brakeman::AliasProcessor
Illustrates the simplification of a more complex 'if/elsif/else' structure.
```ruby
if something
x = "Something is awesome!"
elsif something_else
x = "Something else is awesome!"
else
x = "This is the default!"
end
puts x
```
```ruby
if something then
x = "Something is awesome!"
else
if something_else then
x = "Something else is awesome!"
else
x = "This is the default!"
end
end
puts((("Something is awesome!" or "Something else is awesome!") or "This is the default!"))
```