0% found this document useful (0 votes)
114 views

Ruby On Rails Cheatsheet

Ruby on Rails Cheatsheet

Uploaded by

Rizki Kurniawan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
114 views

Ruby On Rails Cheatsheet

Ruby on Rails Cheatsheet

Uploaded by

Rizki Kurniawan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 13
9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres Ruby on Rails Cheat Sheet 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, ‘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 ikely need a basic set of guidelines to secure fundamental aspects of their application. The intended purpose of this doc is to be that guide. 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. eval("ruby code here") systen(“os command here”) “Is -al /* # (backticks contain os command) exec("os command here) spewn("os command here") ‘open("| 08 command here”) Process.exec(“os conmand here") Process.spawn(“os command here") 0.binread("| os comand here") O.binwrite("| os conmand here”, 10.foreach("| os comand here") 0.popen(“os command here") 0.read("| os commend here") 0.readlines("| os command here") TO.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. ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml ans 9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres The guides from Rails and OWASP contain further information on command injection. SQL Injection Ruby on Rails is often used with an ORM called ActiveRecord, though itis 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, itis possible to write code that allows for SQL Injection. name = parans[:name]} aprojects = 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(“nane like 2", “xt {ActiveRecord: :Base. sanitize_sql_like(parans[:nane]))%") 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, Cross-site Scripting (XSS) By default, protection against XSS comes as the defautt behavior. When sting data is shown in Views, itis escaped prior to being sent back to the browser. This goes a long wey, 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 tothe front end with tags intact itis tempting todo the followingin your eb file (ruby markup). # Wrong! Do not do this! = raw @product.name %> # Wrong! Do not do this! @product.name %> # Wrong! Do not do this! t= Oproduct .name.html_safe % # Wrong! Do not do this! <= content_tag Gproduct.nane %> ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml 9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres Unfortunately, any field that uses raw, htnl_safe, content_tag or similar like this will bea potential XSS target. Note that there are also widespread misunderstandings about html safe() This writeup describes the underlying SafeBuffer mechanism in detail. Cther tags that change the Way strings are prepared for output can introduce similar issues, including content.tag. content_tag("/>") # XSS example # produces: > Themethod htm1_safe of Sting is somewhat confusingly named. It means that we know for sure the content cf the string is safe to include in HTML without escaping. This method itself is un- safe! Ifyou must accept HTML content from users, consider a markup language forrrich 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. Ifyou cannct restrict your users from entering HTML, consider implementing content security Policy 10 disallow the execution of any JavaScript. And finally, consider usingthe #senitize method that lets you list allowed tags. Be careful this method has been shown tobe flawed numerous times and will never be a complete solution. An often overlooked XSS attack vector for older versions of rails is the href value of a link: If euser.website Contains a link that starts with javascript: , the content will execute whena ser clicks the generated link: Personal Nebsite Newer Rails versions escape such links in a better way. Link_to "Personal Website”, 'javascript:alert(1);" .html_safe() # Will generate: # "Personal Website" Using Content Security Policyis one mere security measure to fortid execution for links starting With javascript: . Brakeman scanner helps in finding XSS problems in Rails apps. ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml ans 9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres OWASP provides more general information about XSS in a top level page: Cross-site Scripting (xs). ‘Sessions By default, Ruby on Rails uses 2 Cookie based session store. What that means is that unless you change something, the session will nct expire on the server. That means thet some default applications may be vuherable to replay attacks. It also means that sensitive information should never be putin the session. The best practice is to use @ database based session, which thankfully is very easy with Rails: Project: :application.config.session_store :active.record_store Thereis an Session Management Cheat Sheet, Authentication As with all sensitive deta, start securing your authentication with enabling TLSin your configuration: # config/environrents/production. rb # Force all access to the app over SSL, use Strict-Transport-Security, # and use secure cookies config. force_ss] = Uncomment the ine 3 as above in your configuration. Generally speaking, Rails does not provide authentication by itself. Hcwever, most developers sing Rails leverage libraries such as Devise or AuthLogic to provide authentication. Toenable authentication it is possible to use Devise gem. Install it using: gen “devise Then install it tothe user modet: rails generate devise:install Next, specify which resources (routes) require authenticated access inroutes: ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml ans 9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres Rails.application.routes.draw do authenticate :user do resources :sonething do # these resource require authentication end end devise_for :users # sign-up/~in/out routes root to: ‘static#home' # no authentication required end ‘Toenforce password complex'ty itis possible to use zxevbn gem. Configure your user model with it: class User < ApplicationRecord devise :database_authenticatable, # other devise features, then ‘2xevbnable 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 Po to learn more about it. Next, omniauth gem allows for multiple strategies for authentication. Using it one can configure secure authentication with Facebook, LDAP and many ather providers. Read on here, Token Authentication Devise usually uses Cookies for authentication. In the case token authentication is wished instead, it could be implemented with a gem devise_token_auth, Itsupports muftiple front end technologies, for example angular2-token. This gem is configured similar to the devise gemitself. It also requtes omniauth asa dependency, # token-based authentication gen ‘devise token_auth’ ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml sits 9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres gem “onniauth’ Then a route is defined: mount_devise_token-auth.for ‘User’, at: ‘auth ‘And the User madel is modified accordingly. ‘These actions can be done with one commend: rails g devise token_auth:instell [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! Thereis 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 quessable. 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 buittin protection. tis possible to do this by hand at the controller level. Itis also possible, and probably recommended, to consider resource-based access control libraries such as cancancan (cancan replacement) or pundit todo this. This ensures that all operations ona database otject are authorizedby the business logic of the application. More general information about this class of vulnerabilityis in the OWASP Top 10 Page, CSRF (Cross Site Request Forgery) Rubyon Rails has specific, built-in support for CSRF tokens. To enable it, or ensure that it is enabled, find the base ApplicationController andlook for a directive such as the following. class ApplicationController < ActionController: protect. from_forgery ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml es 9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres Note that the syntax for this type of control includes a way to add exceptions. Exceptions may be Useful for APIs or cther reasons but should be reviewed and consciously included. In the example below, the Rails ProjectContraller will not provide CSRF protection for the show method. class ProjectController < Applicationcontroller protect_from_forgery except: :show ‘Also note that by default Rails doesnot provide CSRF protection for any HTTP GET request. Note: if you use token authentication only, there is no need to protect from CSRF in controllers ike this. If cookie-based authentication is used on some paths, then the protections is still required on them. Theres a top level OWASP page for Cross-Site Request Forgery (CSRF). Redirects and Forwards Web applications often require the ability to dynamically redirect users based on client-supplied data, To clatfy, 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. For example: http://mww exanple .con/redirect?url-http://www.exanple_connerce_site.con/checkout The above request would redrect the user to http://www. exanple.com/checkout . The security concem associated with this functionality is leveraging an organization's trusted brand to phish users and trick them into visiting amalicious site, nour example, badhacker.com. Example: hetp://www .exanple..con/redirect?url=http: //badhacker.com ‘The most basic, but restrictive protection is to use the :only_path option. Setting this to true will essentially strip out any host information. Hewever, the :only-path option must be part of the first argument. If the first argument is not a hash table, then there is no way to pass in this option. Inthe absence of a custom helper or allow list, this is one approach that can work: begin if path = URI.parse(parans[:url]).path redirect_to path end rescue URT TnvalidURIError ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml m3 9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres redirect_to '/' end Hfmatching user input against alist of approved sites or TLDs against regular expression is a must, itrmakes 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 pattems. Those regular expressions must, at a minimum, have anchors or theres a greeter chance of an attacker bypassing the validation routine. Example: require ‘uri! host = URT.parse("#{parans[ :url]}")-host # this can be vulnerable to javascript://trusted.con/%@Aalert (@) # so check .schene and .port too validationroutine(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 allow list end Also blind redirecting to user input parameter can lead to XSS. Example code: redirect_to parans[ :to] Will give this URL: http: //example.con/redirect?to| status] =2@0&tol protocol |=javascript Lert(8)// “The obvious fix for this type of vulnerability isto restrict to specific Top-Level Domains (TLDs), statically define specific sites, or map a key to its vale. Example code: [ACCEPTABLE_URLS "our_app_1' => "https: //www..example_conmerce. site.com/checkout", “our_app_2' => "https: //www.example_user_site.com/change_settings” } Will give this UI http://www. exanple.con/redirect?url=our_app_1 Redirection handling code: ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml ans 9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres 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, 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. 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 HTMLS, standards, will allow this to occur but in order to do this; a couple precautions must be taken. When using a nonstandard HTTP construct, such as an atypical Content-Type header, for example, the following applies: The receiving site should list only those domains allowed to make such requests as well as set the Access-Control-Allon-Origin header in both the responseto the OPTIONS request and PosT request. This is because the OPTIONS request is sent first, in order to determine if the remcte or receiving site allows the requesting domain. Next, a secondrequest, a POST request, is sent. Once again, the header must be set in order for the transaction to be shown as-successful, When standard HTTP constructs are used: The request is sent and the browser, upon receiving a respanse, inspects the respense headers in order to determine if the response can and should be processed. Allow listin Rails: Gemfile: gen ‘rack-cors', :require => ‘rack/cors’ ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml ons 9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres config/application.rb: nodule Sample class Application < Rail config.middleware.use Rack: allow do origins ‘someserver .example.con’ resource %r{/users/\d+. json), sheaders => ['Origin', ‘Accept’, ‘Content-Type’ ], imethods => [:post, :get] end pplication cors do end end end Security-related headers To set a header value, simply access the response headers object as ahash inside your controller (oftenin a before/after fiter). response.headers[X-header-nane’] = ‘value’ Rails provides the default headers functionality that will automatically apply the valves supplied This works for most headers in almost all cases. ActionDispatch: :Response.default_headers = { "X-Frame-Options’ => 'SAMEORIGIN’ , "X-Content-Type-Options’ => ‘nosniff', "XXSS-Protection’ + Strict transport security is @ special case itis set in an environment fle(eg. production.rb) config. force_ss1 = Forthosenct on the edge, there is a library (secure_headers) for the same behavior with content security policy abstraction provided. twill aLtometically apply logic based on the user agent to producea concise set of headers. Business Logic Bugs ‘Any application in any technology can contain business logic errors thet result in security bugs. Business logic bugs are difficult to impossible to detect using automated tools. The best ways to ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml sons Ruby on Rails - OWASP Cheat Sheet Seres 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. ‘An example might be as follows: # this is an example of what NOT to do natch * :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. /config/database.ynl = May contain production credentials fconfig/initializers/secret_token.ro - Contains a secret used to hash session cook Jdo/oeeds.ro = May contain seed data including bootstrap a do /developnent .sqlites = May contain real data. Encryption Rails uses OS encryption. Generally speaking, itis always a bad idea to write your own encryption. Devise by default uses berypt for password hashing, which is an appropriate solution. ‘Typically, the following config causes the 10 stretches for production: sconfig/initializers/devise.rb config.stretches = Reils.env.test? 21 : 10 ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml ss 9725122, 6351 AM Ruby on Rails - OWASP Cheat Sheet Seres Updating Rails and Having a Process for Updating Dependencies 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. ‘An additional concern with Ruby applications in general is that most libraries (gems) are not signed by their authors. Itis 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. In general, itis 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. ‘+ INEXCEPTIONAL conditions, emergency updates may need to be applied. Tools Use brakeman, an open source code analysis tool for Rails applications, to identify meny potential issues. It wil 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. ‘There are emerging tools that can be used to rack security issues in dependency sets, like automated scanning from GitHub and GitLab. ‘Another area of tooling is the security testing tool Gauntlt which is built on cucumber and uses gherkin syntax to define attack files. Launched in May 2013 and very simitar to brakeman scanner, the dawnscanner rubygemis astatic analyzer for security issues that werk with Rails, Sinatra and Padrino web applications. Version 1.6.6 has more then 235 ruby specific CVE security checks. Related Articles and References « The Official Ralls Security Guide ‘¢ OWASP Ruby on Rails Security Guide ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml sans Ruby on Rails - OWASP Cheat Sheet Seres © The Ruby Security Reviewers Guide ‘The Ruby on Rails Security Mailing List ‘© Rails Insecure Defaults ‘ntps:ifcheatshectseries.owasp.orgicheatsheets!Ruby_on_Rals_Cheat_Sheet.ntml

You might also like