Skip to content

Ruby on Rails Cheat Sheet / Ruby on Rails 技巧表

Introduction / 介绍

This Cheatsheet intends to provide quick basic Ruby on Rails security tips for developers. It complements, augments or emphasizes points brought up in the Rails security guide from rails core.

这份 技巧表 旨在为开发者提供快速的基本 Ruby on Rails 安全提示。它补充、增强或强调了来自 Rails 核心的 Rails 安全指南 中提出的一些观点。

The Rails framework abstracts developers from quite a bit of tedious work and provides the means to accomplish complex tasks quickly and with ease. New developers, those unfamiliar with the inner-workings of Rails, likely need a basic set of guidelines to secure fundamental aspects of their application. The intended purpose of this doc is to be that guide.

Rails 框架将开发者从大量繁琐的工作中解放出来,并提供了快速轻松完成复杂任务的方法。新开发者,那些不熟悉 Rails 内部工作原理的人,可能需要一套基本指南来确保他们应用程序的基本安全。这份文档的目的是成为那样的指南。

Items / 项目

Command Injection / 命令注入

Ruby offers a function called "eval" which will dynamically build new Ruby code based on Strings. It also has a number of ways to call system commands.

Ruby 提供了一个名为 "eval" 的函数,可以根据字符串动态构建新的 Ruby 代码。它还有多种调用系统命令的方式。

eval("ruby code here")
system("os command here")
`ls -al /` # (backticks contain os command)
exec("os command here")
spawn("os command here")
open("| os command here")
Process.exec("os command here")
Process.spawn("os command here")
IO.binread("| os command here")
IO.binwrite("| os command here", "foo")
IO.foreach("| os command here") {}
IO.popen("os command here")
IO.read("| os command here")
IO.readlines("| os command here")
IO.write("| os command here", "foo")

While the power of these commands is quite useful, extreme care should be taken when using them in a Rails based application. Usually, its just a bad idea. If need be, an allow-list of possible values should be used and any input should be validated as thoroughly as possible.

虽然这些命令的功能非常有用,但在基于 Rails 的应用程序中使用它们时应该格外小心。通常来说,这并不是一个好主意。如果确实需要,应该使用一个允许列表来指定可能的值,并且应该尽可能彻底地验证任何输入。

The guides from Rails and OWASP contain further information on command injection.

Rails 指南 和 OWASP 指南中包含了有关命令注入的更多信息。

SQL Injection / SQL注入

Ruby on Rails is often used with an ORM called ActiveRecord, though it is flexible and can be used with other data sources. Typically very simple Rails applications use methods on the Rails models to query data. Many use cases protect for SQL Injection out of the box. However, it is possible to write code that allows for SQL Injection.

Ruby on Rails 通常与一个名为 ActiveRecord 的 ORM 一起使用,尽管它很灵活,也可以与其他数据源一起使用。通常,非常简单的 Rails 应用程序使用 Rails 模型上的方法来查询数据。许多用例默认保护 SQL 注入。然而,编写允许 SQL 注入的代码是可能的。

name = params[:name]
@projects = Project.where("name like '" + name + "'");

The statement is injectable because the name parameter is not escaped.

该语句是可注入的,因为名称参数没有被转义。

Here is the idiom for building this kind of statement:

以下是构建此类语句的惯用方法:

@projects = Project.where("name like ?", "%#{ActiveRecord::Base.sanitize_sql_like(params[:name])}%")

Use caution not to build SQL statements based on user controlled input. A list of more realistic and detailed examples is here: rails-sqli.org. OWASP has extensive information about SQL Injection.

请谨慎不要基于用户输入构建 SQL 语句。更多现实且详细的示例列表在此:rails-sqli.org。OWASP 提供了关于 SQL 注入 的详细信息。

Cross-site Scripting (XSS) / 跨站脚本(XSS)

By default, protection against XSS comes as the default behavior. When string data is shown in views, it is escaped prior to being sent back to the browser. This goes a long way, but there are common cases where developers bypass this protection - for example to enable rich text editing. In the event that you want to pass variables to the front end with tags intact, it is tempting to do the following in your .erb file (ruby markup).

默认情况下,XSS 的防护是默认行为。当字符串数据在视图中显示时,在发送回浏览器之前会对其进行转义。这已经走了很长的路,但仍有常见的情况是开发者绕过这种保护 - 例如启用富文本编辑。如果你想在保留标签的情况下将变量传递到前端,可能会在 .erb 文件(Ruby 标记)中做以下操作:

# Wrong! Do not do this!
<%= raw @product.name %>

# Wrong! Do not do this!
<%== @product.name %>

# Wrong! Do not do this!
<%= @product.name.html_safe %>

Unfortunately, any field that uses raw, html_safe or similar like this will be a potential XSS target. Note that there are also widespread misunderstandings about html_safe().

不幸的是,任何使用 raw、html_safe 或类似功能的字段都将成为潜在的 XSS 目标。请注意,关于 html_safe() 也有广泛的理解误区。

This writeup) (本篇文档) describes the underlying SafeBuffer mechanism in detail. Other tags that change the way strings are prepared for output can introduce similar issues.

The method html_safe of String is somewhat confusingly named. It means that we know for sure the content of the string is safe to include in HTML without escaping. This method itself is un-safe!

String 的 html_safe 方法名称有些令人困惑。这意味着我们确信字符串的内容在包含到 HTML 中时是安全的,无需转义。这个方法本身是不安全的!

If you must accept HTML content from users, consider a markup language for rich text in an application (Examples include: Markdown and textile) and disallow HTML tags. This helps ensures that the input accepted doesn't include HTML content that could be malicious.

如果您必须接受用户提供的HTML内容,请考虑在应用程序中使用富文本标记语言(例如:Markdown和textile),并禁止HTML标签。这有助于确保接受的输入不包含可能有害的HTML内容。

If you cannot restrict your users from entering HTML, consider implementing content security policy to disallow the execution of any JavaScript. And finally, consider using the #sanitize method that lets you list allowed tags. Be careful, this method has been shown to be flawed numerous times and will never be a complete solution.

如果您无法限制用户输入HTML,请考虑实施内容安全策略以禁止执行任何JavaScript。最后,考虑使用允许列出允许标签的#sanitize方法。请注意,这种方法已被证明存在多次缺陷,并且永远不会是一个完整的解决方案。

User-controlled link destinations require URL validation in addition to HTML escaping:

用户控制的链接目标需要除了HTML转义之外的对URL进行验证:

<%= link_to "Personal Website", @user.website %>

If @user.website contains a javascript: URL, clicking the generated link can execute script:

如果@user.website包含javascript: URL,点击生成的链接可以执行脚本:

<a href="javascript:alert('Haxored')">Personal Website</a>

link_to does not enforce a URL-scheme allowlist. Validate personal website URLs to allow only https or http before rendering them, and retain HTML attribute escaping. See the XSS prevention rules for URL validation and encoding requirements. Do not use html_safe to bypass escaping.

A restrictive Content Security Policy can additionally block javascript: navigation, but it does not replace URL validation.

限制性的内容安全策略可以额外阻止javascript:导航,但它不能替代URL验证。

Brakeman scanner) (Brakeman扫描器) helps in finding XSS problems in Rails apps.

OWASP provides more general information about XSS in a top level page: Cross-site Scripting (XSS).

OWASP在其顶级页面上提供了关于XSS的更一般信息:跨站脚本(XSS)。

Sessions / 会话

By default, Ruby on Rails uses a Cookie based session store. What that means is that unless you change something, the session will not expire on the server. That means that some default applications may be vulnerable to replay attacks. It also means that sensitive information should never be put in the session.

默认情况下,Ruby on Rails 使用基于 Cookie 的会话存储。这意味着除非你更改设置,否则会话不会在服务器上过期。这意味着一些默认应用程序可能容易受到重放攻击。这也意味着敏感信息绝不应该存储在会话中。

The best practice is to use a database based session, which thankfully is very easy with Rails:

最佳实践是使用基于数据库的会话,幸运的是,在 Rails 中这非常简单:

Project::Application.config.session_store :active_record_store

There is an Session Management Cheat Sheet.

有关会话管理的速查表可供参考。

Authentication / 身份验证

As with all sensitive data, start securing your authentication with enabling TLS in your configuration:

与所有敏感数据一样,从在配置中启用 TLS 开始保护你的身份验证:

# config/environments/production.rb
# Force all access to the app over SSL, use Strict-Transport-Security,
# and use secure cookies
config.force_ssl = true

Uncomment the line 3 as above in your configuration.

在配置中取消注释上述第 3 行。

Rails 8.0 introduced a built-in authentication generator for basic authentication and password reset functionality. It is a starting point that must be adapted to the application, including implementing its sign-up flow. Libraries such as Devise remain another option.

Rails 8.0 引入了一个内置的身份验证生成器,用于基本身份验证和密码重置功能。这是一个起点,必须根据应用程序进行调整,包括实现其注册流程。Devise 等库仍然是另一种选择。

The following examples use the Devise gem.

以下示例使用了 Devise 钩子。

Install it using:

使用以下方法安装:

gem 'devise'

Then install it to the user model:

然后将其安装到用户模型中:

rails generate devise:install

Next, specify which resources (routes) require authenticated access in routes:

接下来,指定哪些资源(路由)需要经过身份验证的访问权限在路由中:

Rails.application.routes.draw do
  authenticate :user do
    resources :something do  # these resource require authentication
      ...
    end
  end

  devise_for :users # sign-up/-in/out routes

  root to: 'static#home' # no authentication required
end

To enforce password complexity, it is possible to use zxcvbn gem. Configure your user model with it:

为了强制密码复杂性,可以使用zxcvbn gem。使用它配置您的用户模型:

class User < ApplicationRecord
  devise :database_authenticatable,
    # other devise features, then
    :zxcvbnable
end

And configure the required password complexity:

并配置所需的密码复杂性:

# in config/initializers/devise.rb
Devise.setup do |config|
  # zxcvbn score for devise
  config.min_password_score = 4 # complexity score here.
  ...

You can try out this PoC to learn more about it.

您可以尝试这个PoC来了解更多信息。

Next, omniauth gem allows for multiple strategies for authentication. Using it one can configure secure authentication with Facebook, LDAP and many other providers. Read on here.

接下来,omniauth gem允许使用多种身份验证策略。使用它,可以配置与Facebook、LDAP和其他许多提供者的安全身份验证。请继续阅读这里。

Token Authentication / 令牌身份验证

Devise usually uses Cookies for authentication.

Devise通常使用Cookies进行身份验证。

In the case token authentication is wished instead, it could be implemented with a gem devise_token_auth.

如果希望使用令牌身份验证,可以使用gem devise_token_auth来实现。

It supports multiple front end technologies, for example angular2-token.

它支持多种前端技术,例如angular2-token。

This gem is configured similar to the devise gem itself. It also requires omniauth as a dependency.

此gem的配置与devise gem本身类似。它还需要omniauth作为依赖项。

# token-based authentication
gem 'devise_token_auth'
gem 'omniauth'

Then a route is defined:

然后定义一个路由:

mount_devise_token_auth_for 'User', at: 'auth'

And the User model is modified accordingly.

并相应地修改User模型。

These actions can be done with one command:

这些操作可以用一条命令完成:

rails g devise_token_auth:install [USER_CLASS] [MOUNT_PATH]

You may need to edit the generated migration to avoid unnecessary fields and/or field duplication depending on your use case.

您可能需要编辑生成的迁移,以避免不必要的字段和/或字段重复,具体取决于您的用例。

Note: when you use only token authentication, there is no more need in CSRF protection in controllers. If you use both ways: cookies and tokens, the paths where cookies are used for authentication still must be protected from forgery!

There is an Authentication Cheat Sheet.

Insecure Direct Object Reference or Forceful Browsing

By default, Ruby on Rails apps use a RESTful URI structure. That means that paths are often intuitive and guessable. To protect against a user trying to access or modify data that belongs to another user, it is important to specifically control actions. Out of the gate on a vanilla Rails application, there is no such built-in protection. It is possible to do this by hand at the controller level.

It is also possible, and probably recommended, to consider resource-based access control libraries such as cancancan (cancan replacement) or pundit to do this. This ensures that all operations on a database object are authorized by the business logic of the application.

More general information about this class of vulnerability is in OWASP Top 10:2025 A01 Broken Access Control and the Insecure Direct Object Reference Prevention Cheat Sheet.

CSRF (Cross Site Request Forgery)

Ruby on Rails has specific, built-in support for CSRF tokens. To enable it, or ensure that it is enabled, find the base ApplicationController and look for a directive such as the following:

class ApplicationController < ActionController::Base
  protect_from_forgery

Note that the syntax for this type of control includes a way to add exceptions. Exceptions may be useful for APIs or other reasons - but should be reviewed and consciously included. In the example below, the Rails ProjectController will not provide CSRF protection for the show method.

请注意,此类控制的语法包括添加异常的方式。异常可能对API或其他原因有用,但应进行审查并有意包含。以下示例中,Rails ProjectController不会为show方法提供CSRF保护。

class ProjectController < ApplicationController
  protect_from_forgery except: :show

Also note that by default Rails does not provide CSRF protection for any HTTP GET request.

还请注意,默认情况下,Rails不提供任何HTTP GET请求的CSRF保护。

Note: if you use token authentication only, there is no need to protect from CSRF in controllers like this. If cookie-based authentication is used on some paths, then the protections is still required on them.

注意: 如果您只使用令牌认证,则无需在类似此处的控制器中保护CSRF。如果某些路径使用基于cookie的认证,则在这些路径上仍需要保护。

There is a top level OWASP page for Cross-Site Request Forgery (CSRF).

OWASP有一个关于跨站请求伪造(CSRF)的顶级页面。

Redirects and Forwards / 重定向和转发

Web applications often require the ability to dynamically redirect users based on client-supplied data. To clarify, dynamic redirection usually entails the client including a URL in a parameter within a request to the application. Once received by the application, the user is redirected to the URL specified in the request.

Web应用程序通常需要根据客户端提供的数据动态重定向用户的能力。为了明确,动态重定向通常涉及客户端在向应用程序的请求中包含一个URL参数。一旦应用程序收到,用户将被重定向到请求中指定的URL。

For example:

例如:

http://www.example.com/redirect?url=http://www.example_commerce_site.com/checkout

The above request would redirect the user to http://www.example.com/checkout. The security concern associated with this functionality is leveraging an organization's trusted brand to phish users and trick them into visiting a malicious site, in our example, badhacker.com.

上述请求将用户重定向到http://www.example.com/checkout。与此功能相关的安全问题是利用组织的可信品牌来钓鱼用户并诱使他们访问恶意网站,在我们的例子中,是badhacker.com。

Example:

示例:

http://www.example.com/redirect?url=http://badhacker.com

For redirects that must stay within the application, use Rails' url_from to validate the destination against the request host and provide a fixed fallback:

对于必须保持在应用程序内的重定向,请使用 Rails 的 url_from 方法(https://api.rubyonrails.org/v8.1.3.1/classes/ActionController/Redirecting.html#method-i-url_from)来验证目标地址是否与请求主机一致,并提供固定的回退方案:

redirect_to url_from(params[:url]) || "/"

Do not treat URI.parse(value).path as redirect validation: the path of https://trusted.example//evil.example/path is //evil.example/path, which is a protocol-relative external destination. Keep Rails' open-redirect protection enabled; if the application requires specific destinations, use an application-defined allowlist instead.

不要将 URI.parse(value).path 作为重定向验证:https://trusted.example//evil.example/path 的路径是 //evil.example/path,这是一个协议相关的外部目标。保持 Rails 的开放重定向保护开启;如果应用程序需要特定的目标,请使用应用程序定义的允许列表代替。

If matching user input against a list of approved sites or TLDs against regular expression is a must, it makes sense to leverage a library such as URI.parse() to obtain the host and then take the host value and match it against regular expression patterns. Those regular expressions must, at a minimum, have anchors or there is a greater chance of an attacker bypassing the validation routine.

如果必须将用户输入与批准的站点列表或 TLDs 与正则表达式进行匹配,那么利用 URI.parse() 获取主机并使用主机值与正则表达式模式进行匹配是有意义的。这些正则表达式至少必须具有锚点,否则攻击者有更大的机会绕过验证流程。

Example:

示例:

require 'uri'
host = URI.parse("#{params[:url]}").host
# this can be vulnerable to javascript://trusted.com/%0Aalert(0)
# so check .scheme and .port too
validation_routine(host) if host
def validation_routine(host)
  # Validation routine where we use  \A and \z as anchors *not* ^ and $
  # you could also check the host value against an allowlist
end

Also blind redirecting to user input parameter can lead to XSS.

此外,盲重定向到用户输入参数也可能导致 XSS 攻击。

Example code:

示例代码:

redirect_to params[:to]

Will give this URL:

将给出此 URL:

http://example.com/redirect?to[status]=200&to[protocol]=javascript:alert(0)//

The obvious fix for this type of vulnerability is to restrict to specific Top-Level Domains (TLDs), statically define specific sites, or map a key to it's value.

此类漏洞的明显修复方法是限制到特定的顶级域名(TLDs),静态定义特定站点,或将键映射到其值。

Example code:

示例代码:

ACCEPTABLE_URLS = {
  'our_app_1' => "https://www.example_commerce_site.com/checkout",
  'our_app_2' => "https://www.example_user_site.com/change_settings"
}

Will give this URL:

将给出此 URL:

http://www.example.com/redirect?url=our_app_1

Redirection handling code:

重定向处理代码:

def redirect
  url = ACCEPTABLE_URLS["#{params[:url]}"]
  redirect_to url if url
end

There is a more general OWASP resource about unvalidated redirects and forwards.

关于未经验证的重定向和转发的OWASP资源更为通用。

Dynamic Render Paths / 动态渲染路径

In Rails, controller actions and views can dynamically determine which view or partial to render by calling the render method. If user input is used in or for the template name, an attacker could cause the application to render an arbitrary view, such as an administrative page.

在Rails中,控制器动作和视图可以通过调用render方法动态确定要渲染的视图或部分。如果用户输入用于或包含在模板名称中,攻击者可能导致应用程序渲染任意视图,例如管理页面。

Care should be taken when using user input to determine which view to render. If possible, avoid any user input in the name or path to the view.

在使用用户输入确定要渲染的视图时,应谨慎行事。如果可能,避免在视图名称或路径中使用任何用户输入。

Cross Origin Resource Sharing / 跨源资源共享

Occasionally, a need arises to share resources with another domain. For example, a file-upload function that sends data via an AJAX request to another domain. In these cases, the same-origin rules followed by web browsers must be sent. Modern browsers, in compliance with HTML5 standards, will allow this to occur but in order to do this; a couple precautions must be taken.

偶尔,需要与其他域名共享资源。例如,一个通过AJAX请求发送数据到另一个域的文件上传功能。在这些情况下,必须遵循Web浏览器遵循的同源规则。现代浏览器符合HTML5标准,将允许这种情况发生,但为了做到这一点,必须采取一些预防措施。

When using a nonstandard HTTP construct, such as an atypical Content-Type header, for example, the following applies:

在使用非标准HTTP结构,例如不典型的Content-Type头部时,以下规则适用:

The receiving site should list only those domains allowed to make such requests as well as set the Access-Control-Allow-Origin header in both the response to the OPTIONS request and POST request. This is because the OPTIONS request is sent first, in order to determine if the remote or receiving site allows the requesting domain. Next, a second request, a POST request, is sent. Once again, the header must be set in order for the transaction to be shown as successful.

接收站点应列出允许发起此类请求的域名,并在对OPTIONS请求和POST请求的响应中设置Access-Control-Allow-Origin头部。这是因为OPTIONS请求首先发送,以确定远程或接收站点是否允许请求域名。接下来,发送第二个请求,即POST请求。再次,必须设置头部,以便交易显示为成功。

When standard HTTP constructs are used:

当使用标准HTTP结构时:

The request is sent and the browser, upon receiving a response, inspects the response headers in order to determine if the response can and should be processed.

请求被发送,浏览器在接收到响应后,会检查响应头部以确定是否可以并且应该处理响应。

Allowlist in Rails:

Rails中的允许列表:

Gemfile:

gem 'rack-cors', :require => 'rack/cors'

config/application.rb:

module Sample
  class Application < Rails::Application
    config.middleware.use Rack::Cors do
      allow do
        origins 'someserver.example.com'
        resource %r{/users/\d+.json},
        :headers => ['Origin', 'Accept', 'Content-Type'],
        :methods => [:post, :get]
      end
    end
  end
end

To set a header value, simply access the response.headers object as a hash inside your controller (often in a before/after_filter).

要设置一个头部值,只需在控制器中(通常在before/after_filter中)将response.headers对象作为哈希访问即可。

response.headers['X-header-name'] = 'value'

Rails provides the default_headers functionality that will automatically apply the values supplied. This works for most headers in almost all cases.

Rails提供了default_headers功能,该功能将自动应用提供的值。这在几乎所有情况下都适用于大多数头部。

ActionDispatch::Response.default_headers = {
  'X-Frame-Options' => 'SAMEORIGIN',
  'X-Content-Type-Options' => 'nosniff',
  'X-XSS-Protection' => '0'
}

Strict transport security) (严格传输安全) is a special case, it is set in an environment file (e.g. production.rb)

config.force_ssl = true

For those not on the edge, there is a library (secure_headers) for the same behavior with content security policy abstraction provided. It will automatically apply logic based on the user agent to produce a concise set of headers.

对于那些不在边缘的用户,有一个库(secure_headers)提供了相同的行为,并提供了内容安全策略的抽象。它将根据用户代理自动应用逻辑,生成一组简洁的头部。

Business Logic Bugs / 业务逻辑错误

Any application in any technology can contain business logic errors that result in security bugs. Business logic bugs are difficult to impossible to detect using automated tools. The best ways to prevent business logic security bugs are to do code review, pair program and write unit tests.

任何应用在任何技术中都可能包含导致安全漏洞的业务逻辑错误。业务逻辑错误很难或无法使用自动化工具检测。预防业务逻辑安全漏洞的最好方法是进行代码审查、结对编程和编写单元测试。

Attack Surface / 攻击面

Generally speaking, Rails avoids open redirect and path traversal types of vulnerabilities because of its /config/routes.rb file which dictates what URLs should be accessible and handled by which controllers. The routes file is a great place to look when thinking about the scope of the attack surface.

一般来说,Rails通过其/config/routes.rb文件避免开放重定向和路径遍历类型的漏洞,该文件规定了哪些URL应该被访问和处理以及由哪个控制器处理。在考虑攻击面范围时,查看路由文件是一个很好的地方。

An example might be as follows:

以下是一个示例:

# this is an example of what NOT to do
match ':controller(/:action(/:id(.:format)))'

In this case, this route allows any public method on any controller to be called as an action. As a developer, you want to make sure that users can only reach the controller methods intended and in the way intended.

在这种情况下,此路由允许调用任何控制器上的任何公共方法作为操作。作为开发者,您想要确保用户只能以预期的方式访问预期的控制器方法。

Sensitive Files / 敏感文件

Many Ruby on Rails apps are open source and hosted on publicly available source code repositories. Whether that is the case or the code is committed to a corporate source control system, there are certain files that should be either excluded or carefully managed.

许多 Ruby on Rails 应用程序是开源的,托管在公开可用的源代码仓库上。无论是这种情况还是代码提交到企业源代码控制系统,都有一些文件应该被排除或谨慎管理。

/config/database.yml                 -  May contain production credentials.
/config/initializers/secret_token.rb -  Contains a secret used to hash session cookie.
/db/seeds.rb                         -  May contain seed data including bootstrap admin user.
/db/development.sqlite3              -  May contain real data.

Encryption / 加密

Rails uses OS encryption. Generally speaking, it is always a bad idea to write your own encryption.

Rails 使用操作系统加密。一般来说,编写自己的加密总是一个坏主意。

Devise by default uses bcrypt for password hashing, which is an appropriate solution.

Devise 默认使用 bcrypt 进行密码散列,这是一个合适的解决方案。

Typically, the following config causes the 10 stretches for production: /config/initializers/devise.rb

通常,以下配置会导致生产环境中的 10 次扩展:/config/initializers/devise.rb

config.stretches = Rails.env.test? ? 1 : 10

Updating Rails and Having a Process for Updating Dependencies / 更新 Rails 和拥有一个更新依赖项的流程

In early 2013, a number of critical vulnerabilities were identified in the Rails Framework. Organizations that had fallen behind current versions had more trouble updating and harder decisions along the way, including patching the source code for the framework itself.

2013年初,Rails框架中发现了多个关键漏洞。那些落后于当前版本的机构在更新过程中遇到了更多麻烦,包括对框架本身源代码的修补决策更为艰难。

An additional concern with Ruby applications in general is that most libraries (gems) are not signed by their authors. It is literally impossible to build a Rails based project with libraries that come from trusted sources. One good practice might be to audit the gems you are using.

对于Ruby应用程序来说,还有一个额外的担忧,那就是大多数库(gem)都没有由其作者签名。实际上,使用来自可信来源的库构建基于Rails的项目是不可能的。一个良好的做法可能是审计你正在使用的gem。

In general, it is important to have a process for updating dependencies. An example process might define three mechanisms for triggering an update of response:

总的来说,有一个更新依赖项的流程是很重要的。一个示例流程可能定义了三种触发响应更新的机制:

  • Every month/quarter dependencies in general are updated.
    中文:每月/每季度的依赖项通常都会更新。
  • Every week important security vulnerabilities are taken into account and potentially trigger an update.
    中文:每周都会考虑重要的安全漏洞,并可能触发更新。
  • In EXCEPTIONAL conditions, emergency updates may need to be applied.
    中文:在异常情况下,可能需要应用紧急更新。

Tools / 工具

Use brakeman, an open source code analysis tool for Rails applications, to identify many potential issues. It will not necessarily produce comprehensive security findings, but it can find easily exposed issues. A great way to see potential issues in Rails is to review the brakeman documentation of warning types.

使用brakeman,这是一个针对Rails应用程序的开源代码分析工具,以识别许多潜在问题。它不一定能产生全面的网络安全发现,但它可以找到容易暴露的问题。查看Rails中潜在问题的好方法是审查brakeman的警告类型文档。

A newer alternative is bearer, an open source code security and privacy analysis tool for both Ruby and JavaScript/TypeScript code, in order to identify a broad range of OWASP Top 10 potential issues. It provides many configuration options and can easily integrate into your CI/CD pipeline.

一个较新的替代方案是bearer,这是一个针对Ruby和JavaScript/TypeScript代码的开源代码安全和隐私分析工具,用于识别广泛的OWASP Top 10潜在问题。它提供了许多配置选项,并且可以轻松集成到你的CI/CD管道中。

There are emerging tools that can be used to track security issues in dependency sets, like automated scanning from GitHub and GitLab.

存在一些新兴工具可以用于跟踪依赖集的安全问题,例如来自 GitHub 和 GitLab 的自动化扫描工具。

Another area of tooling is the security testing tool Gauntlt which is built on cucumber and uses gherkin syntax to define attack files.

另一个工具领域是安全测试工具 Gauntlt,它基于 cucumber 构建,并使用 gherkin 语法来定义攻击文件。

Launched in May 2013 and very similar to brakeman scanner, the dawnscanner rubygem is a static analyzer for security issues that work with Rails, Sinatra and Padrino web applications. Version 1.6.6 has more than 235 ruby specific CVE security checks.

于 2013 年 5 月推出,与 brakeman 扫描器非常相似,dawnscanner rubygem 是一个用于 Rails、Sinatra 和 Padrino 网络应用的静态安全分析器。版本 1.6.6 包含超过 235 个针对 ruby 的特定 CVE 安全检查。

References / 参考