1: Create a new Rails app - we'll call is 'deploytest'
$ rails deploytest
$ cd deploytest
2: Create a local Git repository for it
$ git init
$ git add *
$ git commit -a -m 'initial commit'
$ git status
3: Create a couple of Capistrano files
$ capify .
4: Edit config/deploy.rb
# The name of your app
set :application, "deploytest"
# The directory on the EC2 node that will be deployed to
set :deploy_to, "/var/www/apps/#{application}"
# The type of Source Code Management system you are using
set :scm, :git
# The location of the LOCAL repository relative to the current app
set :repository, "."
# The way in which files will be transferred from repository to remote host
# If you were using a hosted github repository this would be slightly different
set :deploy_via, :copy
# The address of the remote host on EC2 (the Public DNS address)
set :location, "ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com"
# setup some Capistrano roles
role :app, location
role :web, location
role :db, location, :primary => true
# Set up SSH so it can connect to the EC2 node - assumes your SSH key is in ~/.ssh/id_rsa
set :user, "root"
ssh_options[:keys] = [File.join(ENV["HOME"], ".ssh", "id_rsa")]
The only account on a default EC2 instance is root. You probably want to create a second user that is responsible for your application.
5: Copy your SSH public key to your EC2 node
$ scp -i ~/my-ec2-keypair ~/.ssh/id_rsa.pub root@ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com:/root/.ssh/authorized_keys2
NOTE the filename authorized_keys2 - not authorized_keys!!
6: Setup the EC2 node for Capistrano deployment.
From your LOCAL machine, not the EC2 node:
$ cap deploy:setup
7: Finally, deploy your application
$ cap deploy
You will see lots of output and with this dummy application some of those will report errors/warnings. Don't worry about that for now.
8: Check that the Deployment was successful
Connect to the EC2 node with SSH the regular way, cd to the app directory and check that everything is there. If that is all working then you are ready to deploy a real application and add custom tasks for managing the database, restarting the server etc.
Bear in mind that Capistrano add new 'releases' of your software in separate directories and symlinks the 'current' directory to the latest. So the root of your deployed application is the 'current' subdirectory.
Hope this will help you setting up your ec2 instance with capistrano.
Grant privileges to all tables in a database (select, update, insert, delete)
Eg:( Creating a read-only user in postgres)
–Function to grant access(select,insert,update,delete) to users
CREATE FUNCTION pg_grant(TEXT, TEXT, TEXT, TEXT)
RETURNS integer AS '
DECLARE obj record;
num integer;
BEGIN
num:=0;
FOR obj IN SELECT relname FROM pg_class c
JOIN pg_namespace ns ON (c.relnamespace = ns.oid) WHERE
relkind in (''r'',''v'',''S'') AND
nspname = $4 AND
relname LIKE $3
LOOP
EXECUTE ''GRANT '' || $2 || '' ON '' || obj.relname || '' TO '' || $1;
num := num + 1;
END LOOP;
RETURN num;
END;
' LANGUAGE plpgsql SECURITY DEFINER;
–Function to revoke access(select,insert,update,delete) from users
CREATE FUNCTION pg_revoke(TEXT, TEXT, TEXT, TEXT)
RETURNS integer AS '
DECLARE obj record;
num integer;
BEGIN
num:=0;
FOR obj IN SELECT relname FROM pg_class c
JOIN pg_namespace ns ON (c.relnamespace = ns.oid) WHERE
relkind in (''r'',''v'',''S'') AND
nspname = $4 AND
relname LIKE $3
LOOP
EXECUTE ''REVOKE '' || $2 || '' ON '' || obj.relname || '' FROM '' || $1;
num := num + 1;
END LOOP;
RETURN num;
END;
' LANGUAGE plpgsql SECURITY DEFINER;
–Create users for your database
CREATE USER userreadonly WITH PASSWORD 'userr3ad0nly';
CREATE USER userall WITH PASSWORD 'usersh0pa11';
–Grant respective access to users
select pg_grant('userreadonly ','select','%','public');
select pg_grant('userall ','select,insert,update,delete','%','public');
You might need to create lang for plpgsql if you had not done so
createlang plpgsql yrdatabasename
For many users, running FTP Sever in Amazon EC2 instance is headache at the first time. You need to experiment before being able to transfer data. The main problems are Ingress firewall in Amazon environment and NAT traversal.
Here I’m using vsftp (vsfptd) Server, which is one of the most popular and easy to configure. The instance is running from base Fedora 4 AMI but the setup should be identical to other Red Hat based distros.
Install vsftpd FTP server, if not installed earlier:
# yum install vsfptd
Its upto you which FTP method i.e. Active or Passive you want to use. The problem with active mode is that your computer is sending a request out of port 21 when all of a sudden, the server attempts to initiate a request with your computer on port 20. Since communication on port 21 does not imply communication on port 20, it appears as if some unauthorized host has attempted to initiate a new connection with your computer. Kind of sounds like a hack right? Your firewall may think so too (or your NAT router may have no idea to which computer to route the request). Active mode is not used as default method of ftp transfer in many clients these days.
On the other hand, as the Ingress firewall is running in AWS, from the firewall’s standpoint, to support passive mode FTP the following communication channels need to be opened:
FTP server’s port 21 from anywhere (Client initiates connection).
FTP server’s port 21 to ports > 1023 (Server responds to client’s control port).
FTP server’s ports > 1023 from anywhere (Client initiates data connection to random port specified by server).
FTP server’s ports > 1023 to remote ports > 1023 (Server sends ACKs (and data) to client’s data port).
That second part is the problem: FTP server listens on a random port and hands that back to the client, so the client initiates a connection to a random server port, which you must allow.
Opening up all ports > 1023 isn’t so good for security. But what you can do is allow the ports through the distributed firewall and then setup your own filtering inside your instance. Instead, you would better open a fixed number of ports (such as 1024 to 1048) and configure your FTP Server to only use that ports.
Check whether required ports are open or not in your EC2 security group. (if you are unaware about security group, it should be ‘defaul’ unless you created a new one).
# ec2-describe-group
This command will print all ports which are currently open. If you dont find port 20,21,1024-1048 then you need to open these ports but if you dont find the command itself i.e.
# ec2-describe-group
-bash: ec2-describe-group: command not found
You need to install ec2 command line tools. You can find them here and the instructions to setup/configure can be found here.
Open the ports now:
# ec2-authorize default -p 20-21
# ec2-authorize default -p 1024-1048
Here, ‘default’ is the name of security group. You can also open ports for specific IPs. For ease of use, you better install ElasticFox, a firefox extension to manage EC2 stuff. you can find more about it here.
At this moment, you can start your FTP server and if you try to connect it, the process will get failed. By checking logs, you should find something like:
Status: Connected
Status: Retrieving directory listing...
Command: PWD
Response: 257 "/" is current directory.
Command: TYPE A
Response: 200 Type set to A
Command: PASV
Response: 227 Entering Passive Mode (216,182,238,73,129,75).
Command: LIST
Error: Transfer channel can't be opened. Reason: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
Error: Could not retrieve directory listing
Time to configure vsftpd.conf file:
# vi /etc/vsftpd/vsftpd.conf
---Add following lines at the end of file---
pasv_enable=YES
pasv_min_port=1024
pasv_max_port=1048
pasv_address=Public IP of your instance
Put public IP of your EC2 instance and then Save the file. Now restart the server:
# /etc/init.d/vsftpd restart
Here's a quick tip if you're getting errors like this one in your Rails application:
/usr/local/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/session/active_record_store.rb:84: [BUG] Segmentation fault
The most probable reason you're getting the Segmentation fault and your server crashes is because you're trying to store too much data in sessions table of your application (I assume you are using active_record_store as a session store).
The problem with "too much data" is that by default, the session table creation rake task created the following migration in Rails 1.x:
class AddSessions < ActiveRecord::Migration
def self.up
create_table :sessions do |t|
t.column :session_id, :string
t.column :data, :text
t.column :updated_at, :datetime
end
add_index :sessions, :session_id
end
def self.down
drop_table :sessions
end
end
Please note the data field defined as text. This means that it can only store up to 64Kb of data. And that also means that if you're trying to store more than 64Kb in your session.
In order to fix the problem, you just need to manually change the column type before you run migration which creates session store, or just create a new migration which changes parameters of the data column in existing sessions table:
Should look something like that (Rails 2 syntax):
class CreateSessions < ActiveRecord::Migration
def self.up
drop_table :sessions
create_table :sessions do |t|
t.string :session_id, :null => false
t.column :data, :binary, :limit => 10.megabyte
t.timestamps
end
add_index :sessions, :session_id
add_index :sessions, :updated_at
end
def self.down
drop_table :sessions
end
end
Empty your sessions table, restart your server and you're done. No more segmentation faults. Of course you shouldn't store that much data in a session in the first place.
Ruby on Rails does a decent job in handling security concerns in the background. You will have to configure your application to avoid few security attacks while plugins would be required for many security concerns which are not at all or poorly managed by rails.
Authentication
Authentication is the foremost requirement of most of the web applications to authenticate and give privileges to their users. Apart from normal authentication mechanism rails have plugins for OpenID, CAS and Access Control. Build your own authentication system only if your requirements are very unique or you do not trust other implementations.
Plugin - Restful Authentication (recommended) - easy to use and you can tweak it according to your requirements.
http://railscasts.com/episodes/67
http://svn.techno-weenie.net/projects/plugins/restful_authentication/
Build your own authentication. You should rarely need to do this ... Restful Authentication is quite flexible.
http://www.aidanf.net/rails_user_authentication_tutorial
OpenID - a universal authentication system to avoid use of multiple username and password on the Internet. OpenID is getting quite famous now-a-days.
http://media.railscasts.com/videos/068_openid_authentication.mov
http://agilewebdevelopment.com/plugins/openidauthentication
Access Control : To easily proivde different priviliges to your users. There are a lot of cool plugins available for access control.
https://opensvn.csie.org/traccgi/tobionrails
http://code.google.com/p/rolerequirement/
http://agilewebdevelopment.com/plugins/activeacl_rails_authorization_system
Centralized Authentication Server - is used to implement single login/password for your users across multiple application. It can also be used for a single sign-on system. For example, Gmail and Google Reader have a single sign-on between them.
http://agilewebdevelopment.com/plugins/cas_authentication_filter
Use Google Authentication API to let your users login using their google username and password.
http://rubyforge.org/projects/asgoogleaccount/
More Plugins :
Rails inbuilt Authentication - http://ryandaigle.com/articles/2006/12/4/whats-new-in...
Acts_as_authenticated - http://technoweenie.stikipad.com/plugins/show/User+Authentication
Super Simple Authentication - http://ariejan.net/2007/08/24/super-simple-...
- Model -
SQL Injection
The problem arises when metacharacters are injected into your queries to database. Rails has a very good support to avoid SQL injection if you follow conventions in issuing queries to your database.
Description :
http://manuals.rubyonrails.com/read/chapter/43
Alternate Solution - use hash for specifying conditions in #find
http://weblog.rubyonrails.org/2006/11/26/1-2-new-in-activerecord
Activerecord Validation
To validate the contents of model object before records are created/modified in the database. Activerecord validations are very useful over database data-type constraints to ensure values entered into the database follow your rules. You might have javascript validations for forms but javascript can easily be switched off. Use javascript validations only for better user experience.
Description :
http://rails.rubyonrails.com/classes/ActiveRecord/Validations/ClassMethods.html
Conditional validation using
n and :if options. Checkout this cool video
http://media.railscasts.com/videos/041_conditional_validations.mov
Be careful using validates_uniqueness_of, it has problems when used with :scope option. Open bug tickets :
http://dev.rubyonrails.org/ticket/5608
http://dev.rubyonrails.org/ticket/9235
http://dev.rubyonrails.org/ticket/8811http://dev.rubyonrails.org/ticket/8774
Use :allow_blank to pass validations if value is nil or empty string
http://ryandaigle.com/articles/2007/9/5/what-s-new-in-edge-rails-validations-now-allow_blank
Testing Validations - do read the comments in this article
http://blog.jayfields.com/2006/12/rails-unit-testing-activerecord.html
Useful Tips
- Its easy to manage 'nil' values using
:allow_nil, its quite handy. For ex: set :allow_nil => true in validates_uniqueness_of to check uniqueness of non-nil values and ignore nil values
- validates_presence_of is not required if you are using validates_format_of, unless regular expression accepts empty string.
Creating records directly from parameters
While creating database records directly from form params, a malicious user can add extra fields into the params and manually submit the web page which will set values of fields which you do not want user to set.
Description :
http://manuals.rubyonrails.com/read/chapter/47
Alternate Solution - Trim the parameters to keep the required keys and remove the others.
http://wiki.rubyonrails.org/rails/pages/HowToPreventFormInjection
- Controller -
Exposing methods
Use private and protected in controller for methods which should not be actions. Actions are pubic methods and can be invoked from the browser.
hide_action : If non-action controller methods must be public, hide them using hide_action.
http://www.mathewabonyi.com/articles/2006/08/11/hide_action-a-hidden-treasure
Be careful of bypassing private and protected using meta-programming
http://dev.zeraweb.com/design-blog-14
Authorize parameters
Always authorize user request. By tweaking form parameters or url a user can send request to view/modify other users information if there is no proper authorization of parameters.
For example :
## To find information of an order which belongs to a particular user.
#Incorrect :
@order = Order.find(order_id)
#Correct :
@order = @user.orders.find(order_id)
|
Do not ignore hidden fields - a user can easily modify their value, so suspect them similar to params[:id]
http://searchsecurity.techtarget.com/tip/1,289483,sid14_gci1153816,00.html
Filter sensitive logs
Prevent logs of sensitive unencrypted data using #filter_parameter_logging in controller. The default behavior is to log request parameters in production as well as development environment, and you would not like logging of password, credit card number, etc.
Video Tutorial
http://railscasts.com/episodes/9
Cross Site Reference(or Request) Forgery (CSRF)
In a CSRF attack, the attacker makes victim click on a link of his choice which would contain a GET/POST request and causes web application to take malicious action. The link could be embedded in a iframe or an img tag. Its recommended to use secret token while communicating with user to avoid this attack.
Its little complex to understand this attack. So, only those readers who are very enthusiastic to know about it, please read the Description below. Rest can directly move ahead to use the plugin.
Description :
http://isc.sans.org/diary.html?storyid=1750
http://en.wikipedia.org/wiki/Cross-site_request_forgery
Use Get and Post appropiately (note : Both get and post are vulnerable to CSRF)
http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1
Example - Gmail CSRF security flaw
http://ajaxian.com/archives/gmail-csrf-security-flaw
Plugin - CSRF Killer (recommended) - it requires edge rails
http://svn.techno-weenie.net/projects/plugins/csrf_killer/
http://activereload.net/2007/3/6/your-requests-are-safe-with-us
Secure action - http://code.google.com/p/secure-action-plugin/
Security extension - http://svn.aviditybytes.com/rails/plugins/security_extensions/
Minimize session attacks
If an attacker has session-id of your user, he can create HTTP requests to access user account. An attacker can get session-id by direct access to user machine or is able to successfully run malicious scripts at user machine. In this section we will talk about how to avoid or minimize the risk if attacker has user session-id. Following steps are helpful:
- Store IP Address, but creates problem if user moves from one network to another.
- Create a new session everytime someone logs in.
- Expire session on user logout, user is idle for a time period or on closing of browser/tab. For maximum security expire sessions on all the three conditions.
Code for session expiry on timeout
## Timeout after inactivity of one hour.
MAX_SESSION_PERIOD = 3600
before_filter :session_expiry
def session_expiry
reset_session if session[:expiry_time] and session[:expiry_time] < Time.now
session[:expiry_time] = MAX_SESSION_PERIOD.seconds.from_now
return true
end
|
Plugin - Session Expiration for session expiry on timeout
http://www.naffis.com/2007/5/22/automatically-expiring-sessions-in-rails
Do not put expiry time in the cookie unless your cookie information is properly encrypted. If not, use server side session expiry.
http://wiki.rubyonrails.org/rails/pages/HowtoChangeSessionOptions
Persistent session / login in rails - global setting in enviornment.rb
|
ActionController::Base.session_options[:session_expires] = <i>say after two years</i>
|
Persistent session / login in rails - to give your users a feature - remember me
http://blog.codahale.com/2006/04/08/dynamic-session-expiration-times-with-rails/
http://www.onrails.org/articles/2006/02/18/auto-login
http://livsey.org/2006/6/30/persistent-logins-in-rails
Stop spam on your website from DNS Blacklist
Avoid access to your website from IP addresses which are present in DNS Blacklist(DNSBL).
Plugin - DNSBL check
http://spacebabies.nl/dnsbl_check/
Caching authenticated pages
Page caching does bypass any security filters in your application. So avoid caching authenticated pages and use action or fragment caching instead.
- View -
Cross site scripting(XSS) attack
Cross Site Scripting is a technique found in web applications which allow code injection by malicious web users into the web pages viewed by other users. An attacker can steal login of your user by stealing his cookie. The most common method of attack is to place javascript code on a website that can receive the session cookie. To avoid the attack, escape HTML meta characters which will avoid execution of malicious Javascript code. Ruby on Rails has inbuilt methods like escape_html() (h()), url_encode(), sanatize(), etc to escape HTML meta characters.
Description
http://manuals.rubyonrails.com/read/chapter/44
Can we avoid tedious use of h() in views?
http://wiki.rubyonrails.org/rails/pages/HowToEscapeHTML
Sanitize() is used to escape script tags and other malicious content other than html tags. Avoid using it ... its unsecure. Use white_list instead.
http://www.rorsecurity.info/2007/08/17/dont-use-strip_tags-strip_links-and-sanitize/
White_list plugin
http://svn.techno-weenie.net/projects/plugins/white_list/README
Anti-spam form protection
Use Captcha or Javascript based form protection techniques to ensure only human can submit forms successfully.
When using Captcha do ensure the following :
- Images are rendered on webpage using
send_data and are not stored at the server, because its not required to store images and are redundant.
- Avoid using algorithm used by standard Catpcha plugins as they can easily be hacked, instead tweak an existing algorithm or write your own.
- Use a Captcha which does not store secret code or images in filesystem, as you will have trouble using Captcha with multiple servers.
Tutorial - a nice article on concepts of captcha
http://revolutiononrails.blogspot.com/2007/04/pedo-mellon-minno-or-captcha-on-rails.html
Plugin - ReCaptcha (recommended)
http://recaptcha.net/
http://ambethia.com/recaptcha/
Plugin - BrainBuster - a logic captcha based on simple puzzles, math and word problems. By default, it has limited set of problems and you would have to come up with large set of your own problems.
http://robsanheim.com/brain-buster
Plugin - Simple Captcha (not recommended) as it breaks all the must have features of a good Captcha implementation.
http://expressica.com/2007/03/23/simple_captcha_1_0/
For less critical systems like blogs, a more user-friendly option can be use of CSS based technique or JavaScript based plugin unlike Captcha. Both JavaScript and CSS based techniques can only avoid spam from dumb or general bots. If an hacker specifically targets your site or bot is smart enough, you are dead, so be careful.
CSS based Negative Captcha - http://damienkatz.net/2007/01/negative_captch.html
Inverse Captcha for Mephisto - http://www.artweb-design.de/projects/mephisto-plugin-inverse...
JavaScript based Form Spam Protection - http://form-spam-protection.googlecode.com/svn/form...
Captcha with Multiple Servers
http://upstream-berlin.com/blog/2007/08/17/captchas-with-rails-and-multiple-servers/
Hide mailto links
Mailto links in a webpage can be attacked by e-mail harvesting bots. Use the plugin CipherMail to generate a 1024 bit random key and obfuscate the mailto link.
Plugin - CipherMail
http://agilewebdevelopment.com/plugins/ciphermail
Use password strength evaluators
A lot of people have used password strength evaluators simply because its used by google in their registration form. You can use it to help your users register with strong password. But I don't think its a must have security addon. Uptill now I have not found a good algorithm to assess strength of a password, but some of them are reasonable.
Also, if there is an open source tool or algorithm for evaluating password strength, it can easily be broken. So, you might consider tweaking the algorithm or building one from scratch.
Tools
http://www.certainkey.com/demos/password/http://www.jeffro2pt0.com/ajax-powered-password-strength-meter/
http://www.geekwisdom.com/dyn/passwdmeter
http://www.jvoorhis.com/articles/2006/04/06/automatic-password-suggestion-for-your-rails-app
- Miscellaneous -
Transmission of Sensitive information
Use SSL to encrypt sensitive data between transfer from client to server. SSL hits server performace, so you might consider using SSL only for few pages which transfer sensitive data to and fro.
Plugin ssl_requirement
http://svn.rubyonrails.org/rails/plugins/ssl_requirement/README
Mongrel, rails, apache and SSL
http://blog.innerewut.de/2006/06/21/mongrel-and-rails-behind-apache-2-2-and-ssl
Controller in SSL subdomain
http://www.railsonwave.com/railsonwave/2007/7/10/howto-put-a-controller-under-a-ssl-subdomain
Sample SSL code in rails
http://blog.caboo.se/articles/2007/4/21/sample-rails-app-branch-with-ssl
File upload
Be very careful when you allow your users to upload files and make them available for other users to download.
Description
http://www.rorsecurity.info/2007/03/27/working-with-files-in-rails/
Must read - Section 26.7 of Agile web development with rails - 2nd edition
http://www.pragmaticprogrammer.com/titles/rails2/
In place file upload
http://kpumuk.info/ruby-on-rails/in-place-file-upload-with-ruby-on-rails/
3 plugins for file upload reviewed at :
http://www.flex888.com/2007/03/21/three-ruby-on-rails-file-upload-plugins-reviewed.html
Secure your setup / environment
http://www.igvita.com/blog/2006/10/10/securing-your-rails-environment/
Proper Mysql configuration
http://www.rorsecurity.info/2007/02/25/securing-mysql/
http://www.rorsecurity.info/2007/02/27/rails%e2%80%99-friends-securing-mysql-continued/
Use good passwords
http://en.wikipedia.org/wiki/Password_strengthhttp://www.rorsecurity.info/2007/06/05/use-good-passwords/
Security plugins directory
http://agilewebdevelopment.com/plugins/category/1
http://www.railslodge.com/plugins
http://railsify.com/categories/security-production
Original Source http://www.quarkruby.com/2007/9/20/ruby-on-rails-security-guide