<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>eXpand yOur cReativity &#187; Security</title>
	<atom:link href="http://blog.bhushangahire.net/category/security/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.bhushangahire.net</link>
	<description></description>
	<lastBuildDate>Thu, 05 Jan 2012 07:17:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>How Do I Enable remote access to PostgreSQL database server?</title>
		<link>http://blog.bhushangahire.net/2010/05/11/how-do-i-enable-remote-access-to-postgresql-database-server/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-do-i-enable-remote-access-to-postgresql-database-server</link>
		<comments>http://blog.bhushangahire.net/2010/05/11/how-do-i-enable-remote-access-to-postgresql-database-server/#comments</comments>
		<pubDate>Tue, 11 May 2010 12:11:22 +0000</pubDate>
		<dc:creator>Bhushan G Ahire</dc:creator>
				<category><![CDATA[Amazon EC2]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[postgres]]></category>
		<category><![CDATA[remote]]></category>
		<category><![CDATA[server]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=177</guid>
		<description><![CDATA[By default, PostgreSQL database server remote access disabled for security reasons. However, some time you need to provide the remote access to database server from home computer or from web server. Step # 1: Login over ssh if server is outside your IDC Login over ssh to remote PostgreSQL database server: $ ssh user@remote.pgsql.server.com Step [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="format_text entry-content">
<div style="float: right; margin-top: 0px; margin-left: 5px;"><a title="See all Postgresql related tips/articles" href="http://www.cyberciti.biz/tips/category/postgresql/"><br />
<img src="http://figs.cyberciti.biz/3rdparty/pgsql-logo.png" border="0" alt="" /></a></div>
<p>By default, PostgreSQL database server remote access disabled for security reasons. However, some time you need to provide the remote access to database server from home computer or from web server.</p>
<h2>Step # 1: Login over ssh if server is outside your IDC</h2>
<p>Login over ssh to remote PostgreSQL  database server:</p>
<p><code>$ ssh user@remote.pgsql.server.com</code></p>
<h2>Step # 2: Enable client authentication</h2>
<p>Once connected, you need edit the PostgreSQL configuration file, edit the PostgreSQL configuration file <strong>/var/lib/pgsql/data/pg_hba.conf</strong> (or <strong>/etc/postgresql/8.2/main/pg_hba.conf</strong> for latest 8.2 version) using a text editor such as vi.</p>
<p>Login as postgres user using su / sudo command, enter:</p>
<p><code>$ su - postgres</code></p>
<p>Edit the file:</p>
<p><code>$ vi /var/lib/pgsql/data/pg_hba.conf</code></p>
<p>OR</p>
<p><code>$ vi /etc/postgresql/8.2/main/pg_hba.conf</code></p>
<p>Append the following configuration lines to give access to 10.10.29.0/24 network:</p>
<p><code>host all all 10.10.29.0/24 trust</code></p>
<p>Save and close the file.  Make sure you replace 10.10.29.0/24 with  actual network IP address range of the clients system in your own network.</p>
<h2>Step # 2: Enable networking for PostgreSQL</h2>
<p>You need to enable TCP / IP networking. Use either step #3 or #3a as per your PostgreSQL database server version.</p>
<h2>Step # 3: Allow TCP/IP socket</h2>
<p>If you are using <strong>PostgreSQL version 8.x or newer</strong> use the following instructions or skip to <a href="#3a">Step # 3a</a> for older version (7.x or older).</p>
<p>You need to open PostgreSQL configuration file /var/lib/pgsql/data/postgresql.conf or /etc/postgresql/8.2/main/postgresql.conf.</p>
<p><code># vi /etc/postgresql/8.2/main/postgresql.conf</code></p>
<p>OR</p>
<p><code># vi /var/lib/pgsql/data/postgresql.conf </code></p>
<p>Find configuration line that read as follows:</p>
<p><code>listen_addresses='localhost'</code></p>
<p>Next set IP address(es) to listen on; you can use comma-separated list of addresses; defaults to &#8216;localhost&#8217;, and &#8216;*&#8217; is all ip address:</p>
<p><code>listen_addresses='*'</code></p>
<p>Or just bind to 202.54.1.2 and 202.54.1.3 IP address</p>
<p><code>listen_addresses='202.54.1.2 202.54.1.3'</code></p>
<p>Save and close the file. Skip to <a href="#4">step # 4</a>.</p>
<h3>Step #3a &#8211; Information for old version 7.x  or older</h3>
<p>Following configuration only required for <strong>PostgreSQL version 7.x or older</strong>. Open config file, enter:</p>
<p><code># vi /var/lib/pgsql/data/postgresql.conf </code></p>
<p>Bind and open TCP/IP port by setting tcpip_socket to true.  Set / modify tcpip_socket to true:</p>
<p><code>tcpip_socket = true</code></p>
<p>Save and close the file.</p>
<h2>Step # 4: Restart PostgreSQL Server</h2>
<p>Type the following command:</p>
<p><code># /etc/init.d/postgresql restart</code></p>
<h2>Step # 5: Iptables firewall rules</h2>
<p>Make sure iptables is not blocking communication, <a href="http://www.cyberciti.biz/tips/howto-iptables-postgresql-open-port.html">open port 5432</a> (append rules to your iptables scripts or file <a href="http://www.cyberciti.biz/faq/howto-block-ipaddress-of-spammers-with-firewall/">/etc/sysconfig/iptables</a>):</p>
<pre>iptables -A INPUT -p tcp -s 0/0 --sport 1024:65535 -d 20.04.23.22  --dport 5432 -m state --state NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp -s 20.04.23.22 --sport 5432 -d 0/0 --dport 1024:65535 -m state --state ESTABLISHED -j ACCEPT</pre>
<p>Restart firewall:</p>
<p><code># /etc/init.d/iptables restart</code></p>
<h2>Step # 6: Test your setup</h2>
<p>Use psql command from client system. Connect to remote server using IP address 20.04.23.22 and login using postgres username and testdatabase database, enter:</p>
<p><code>$ psql -h 20.04.23.22 -U postgres -d testdatabase</code></p>
</div>
<div class="shr-publisher-177"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2010/05/11/how-do-i-enable-remote-access-to-postgresql-database-server/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Setup Capistrano to deploy Rails application on Amazon EC2 with Git</title>
		<link>http://blog.bhushangahire.net/2010/02/17/setup-capistrano-to-deploy-rails-application-on-amazon-ec2-with-git/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=setup-capistrano-to-deploy-rails-application-on-amazon-ec2-with-git</link>
		<comments>http://blog.bhushangahire.net/2010/02/17/setup-capistrano-to-deploy-rails-application-on-amazon-ec2-with-git/#comments</comments>
		<pubDate>Wed, 17 Feb 2010 06:22:49 +0000</pubDate>
		<dc:creator>Bhushan G Ahire</dc:creator>
				<category><![CDATA[capistrano]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[server]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=155</guid>
		<description><![CDATA[1: Create a new Rails app &#8211; we&#8217;ll call is &#8216;deploytest&#8217; $ 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 [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="post-body entry-content">1: Create a new Rails app &#8211; we&#8217;ll call is &#8216;deploytest&#8217;</p>
<pre class="prettyprint"><span class="pln">$ rails deploytest
$ cd deploytest</span></pre>
<p>2: Create a local Git repository for it</p>
<pre class="prettyprint"><span class="pln">$ git init
$ git add </span><span class="pun">*</span><span class="pln">
$ git commit </span><span class="pun">-</span><span class="pln">a </span><span class="pun">-</span><span class="pln">m </span><span class="str">'initial commit'</span><span class="pln">
$ git status</span></pre>
<p>3: Create a couple of Capistrano files</p>
<pre class="prettyprint"><span class="pln">$ capify </span><span class="pun">.</span></pre>
<p>4: Edit config/deploy.rb</p>
<pre class="prettyprint"><span class="com"># The name of your app</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">application</span><span class="pun">,</span><span class="pln"> </span><span class="str">"deploytest"</span><span class="pln">
</span><span class="com"># The directory on the EC2 node that will be deployed to</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">deploy_to</span><span class="pun">,</span><span class="pln"> </span><span class="str">"/var/www/apps/#{application}"</span><span class="pln">
</span><span class="com"># The type of Source Code Management system you are using</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">scm</span><span class="pun">,</span><span class="pln"> </span><span class="pun">:</span><span class="pln">git
</span><span class="com"># The location of the LOCAL repository relative to the current app</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">repository</span><span class="pun">,</span><span class="pln">  </span><span class="str">"."</span><span class="pln">
</span><span class="com"># The way in which files will be transferred from repository to remote host</span><span class="pln">
</span><span class="com"># If you were using a hosted github repository this would be slightly different</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">deploy_via</span><span class="pun">,</span><span class="pln"> </span><span class="pun">:</span><span class="pln">copy

</span><span class="com"># The address of the remote host on EC2 (the Public DNS address)</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">location</span><span class="pun">,</span><span class="pln"> </span><span class="str">"ec2-xxx-xxx-xxx-xxx.compute-1.amazonaws.com"</span><span class="pln">
</span><span class="com"># setup some Capistrano roles</span><span class="pln">
role </span><span class="pun">:</span><span class="pln">app</span><span class="pun">,</span><span class="pln"> location
role </span><span class="pun">:</span><span class="pln">web</span><span class="pun">,</span><span class="pln"> location
role </span><span class="pun">:</span><span class="pln">db</span><span class="pun">,</span><span class="pln">  location</span><span class="pun">,</span><span class="pln"> </span><span class="pun">:</span><span class="pln">primary </span><span class="pun">=&gt;</span><span class="pln"> </span><span class="kwd">true</span><span class="pln">

</span><span class="com"># Set up SSH so it can connect to the EC2 node - assumes your SSH key is in ~/.ssh/id_rsa</span><span class="pln">
</span><span class="kwd">set</span><span class="pln"> </span><span class="pun">:</span><span class="pln">user</span><span class="pun">,</span><span class="pln"> </span><span class="str">"root"</span><span class="pln">
ssh_options</span><span class="pun">[:</span><span class="pln">keys</span><span class="pun">]</span><span class="pln"> </span><span class="pun">=</span><span class="pln"> </span><span class="pun">[</span><span class="typ">File</span><span class="pun">.</span><span class="pln">join</span><span class="pun">(</span><span class="pln">ENV</span><span class="pun">[</span><span class="str">"HOME"</span><span class="pun">],</span><span class="pln"> </span><span class="str">".ssh"</span><span class="pun">,</span><span class="pln"> </span><span class="str">"id_rsa"</span><span class="pun">)]</span><span class="pln">
</span></pre>
<p>The only account on a default EC2 instance is root. You probably want to create a second user that is responsible for your application.</p>
<p>5: Copy your SSH public key to your EC2 node</p>
<pre class="prettyprint"><span class="pln">$ scp </span><span class="pun">-</span><span class="pln">i </span><span class="pun">~</span><span class="str">/my-ec2-keypair ~/</span><span class="pun">.</span><span class="pln">ssh</span><span class="pun">/</span><span class="pln">id_rsa</span><span class="pun">.</span><span class="pln">pub root@ec2</span><span class="pun">-</span><span class="lit">xxx</span><span class="pun">-</span><span class="lit">xxx</span><span class="pun">-</span><span class="lit">xxx</span><span class="pun">-xxx</span><span class="lit">.compute</span><span class="pun">-</span><span class="lit">1.amazonaws</span><span class="pun">.</span><span class="pln">com</span><span class="pun">:</span><span class="str">/root/</span><span class="pun">.</span><span class="pln">ssh</span><span class="pun">/</span><span class="pln">authorized_keys2</span></pre>
<p>NOTE the filename authorized_keys2 &#8211; not authorized_keys!!</p>
<p>6: Setup the EC2 node for Capistrano deployment.<br />
From your LOCAL machine, not the EC2 node:</p>
<pre class="prettyprint"><span class="pln">$ cap deploy</span><span class="pun">:</span><span class="pln">setup</span></pre>
<p>7: Finally, deploy your application</p>
<pre class="prettyprint"><span class="pln">$ cap deploy</span></pre>
<p>You will see lots of output and with this dummy application some of those will report errors/warnings. Don&#8217;t worry about that for now.</p>
<p>8: Check that the Deployment was successful<br />
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.</p>
<p>Bear in mind that Capistrano add new &#8216;releases&#8217; of your software in separate directories and symlinks the &#8216;current&#8217; directory to the latest. So the root of your deployed application is the &#8216;current&#8217; subdirectory.</p>
<p>Hope this will help you setting up your ec2 instance with capistrano.</p></div>
<div class="shr-publisher-155"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2010/02/17/setup-capistrano-to-deploy-rails-application-on-amazon-ec2-with-git/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use Google Apps mail configuration with rails application.</title>
		<link>http://blog.bhushangahire.net/2009/07/22/how-to-use-google-apps-mail-configuration-with-rails-application/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-use-google-apps-mail-configuration-with-rails-application</link>
		<comments>http://blog.bhushangahire.net/2009/07/22/how-to-use-google-apps-mail-configuration-with-rails-application/#comments</comments>
		<pubDate>Wed, 22 Jul 2009 10:05:21 +0000</pubDate>
		<dc:creator>Bhushan Ahire</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[google apps]]></category>
		<category><![CDATA[setup]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=134</guid>
		<description><![CDATA[I am using google apps for my domain www.bhushangahire.com For one of my rails application I am using this domain mail account setup for sending mails. But I am not able to send the mail with the default smtp setings we use for sending mail. So I search on net and I found the Goggle [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div id="content"><!--single.php--></p>
<p><!--loop--></p>
<p><!--post title--></p>
<div class="post-meta-top">
<div class="clearboth"></div>
<p><!--content with more link--></p>
<p>I am using google apps for my domain <strong>www.bhushangahire.com</strong></p>
<p>For one of my rails application I am using this domain mail account setup for sending mails.</p>
<p>But I am not able to send the mail with the default smtp setings we use for sending mail.</p>
<p>So I search on net and I found the Goggle Apps consider its in different way. Which is TLS ans SSH service, which is not by default comes with the Action mailler.</p>
<p class="vspace"><span class="wikiword">ActionMailer</span> can’t send emails using <span class="wikiword">GMail</span> out of the box. To add this functionality do the following configuration in your rails application:</p>
<ol>
<li>Create the file <strong><code>lib/smtp_tls.rb</code></strong>
<div class="code">
<pre>require "openssl"
require "net/smtp"

Net::SMTP.class_eval do
private
def do_start(helodomain, user, secret, authtype)
raise IOError, 'SMTP session already started' if @started
check_auth_args user, secret, authtype if user or secret

sock = timeout(@open_timeout) { TCPSocket.open(@address, @port) }
@socket = Net::InternetMessageIO.new(sock)
@socket.read_timeout = 60 #@read_timeout

check_response(critical { recv_response() })
do_helo(helodomain)

raise 'openssl library not installed' unless defined?(OpenSSL)
starttls
ssl = OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
ssl.connect
@socket = Net::InternetMessageIO.new(ssl)
@socket.read_timeout = 60 #@read_timeout
do_helo(helodomain)

authenticate user, secret, authtype if user
@started = true
ensure
unless @started
# authentication failed, cancel connection.
@socket.close if not @started and @socket and not @socket.closed?
@socket = nil
end
end

def do_helo(helodomain)
begin
if @esmtp
ehlo helodomain
else
helo helodomain
end
rescue Net::ProtocolError
if @esmtp
@esmtp = false
@error_occured = false
retry
end
raise
end
end

def starttls
getok('STARTTLS')
end

def quit
begin
getok('QUIT')
rescue EOFError
rescue OpenSSL::SSL::SSLError
end
end
end</pre>
</div>
</li>
<li>Add the following lines to <strong><code>config/environment.rb</code></strong> and replace the values with the appropriate username and password:
<div class="code">
<pre>require 'smtp_tls'
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.raise_delivery_errors = true
ActionMailer::Base.server_settings = {
:address =&gt; "smtp.gmail.com",
:port =&gt; 587,
:domain =&gt; "mydomain.com",
:authentication =&gt; :plain,
:user_name =&gt; "username@mydomain.com",
:password =&gt; "password"
}</pre>
</div>
<p><strong><sup>*</sup>Note:</strong>To work your domain with <strong>“mydomain.com”</strong> you have to configure your <strong>MX records</strong> to work Gmail mail sending functionality out of box.</p>
<p>Else you can use a temporary address <strong>@mydomain.com.test-google-a.com</strong>, I have not tested with this as I have already configure my <strong>MX records</strong>.</p>
<p>You can get more information on changing <strong><a href="http://www.google.com/support/a/bin/answer.py?answer=33352">http://www.google.com/support/a/bin/answer.py?answer=33352</a></strong>.</p>
<p>Hope this information is useful to you. <img class="wp-smiley" src="http://blogs.circlesource.com/wp-includes/images/smilies/icon_wink.gif" alt=";-)" /></li>
</ol>
<p><!--for paginate posts--></p>
<p><!--Post Meta--></div>
</div>
<div class="shr-publisher-134"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2009/07/22/how-to-use-google-apps-mail-configuration-with-rails-application/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grant privileges to all tables in a database for postgresql</title>
		<link>http://blog.bhushangahire.net/2009/06/17/grant-privileges-to-all-tables-in-a-database-for-postgresql/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=grant-privileges-to-all-tables-in-a-database-for-postgresql</link>
		<comments>http://blog.bhushangahire.net/2009/06/17/grant-privileges-to-all-tables-in-a-database-for-postgresql/#comments</comments>
		<pubDate>Wed, 17 Jun 2009 11:50:08 +0000</pubDate>
		<dc:creator>Bhushan Ahire</dc:creator>
				<category><![CDATA[Security]]></category>
		<category><![CDATA[grant]]></category>
		<category><![CDATA[permissions]]></category>
		<category><![CDATA[postgres]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=127</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="snap_preview">
<p>Grant privileges to all tables in a database (select, update, insert, delete)</p>
<p>Eg:( Creating a read-only user in postgres)</p>
<p>–Function to grant access(select,insert,update,delete) to users<br />
<code><br />
CREATE FUNCTION pg_grant(TEXT, TEXT, TEXT, TEXT)<br />
RETURNS integer AS '<br />
DECLARE obj record;<br />
num integer;<br />
BEGIN<br />
num:=0;<br />
FOR obj IN SELECT relname FROM pg_class c<br />
JOIN pg_namespace ns ON (c.relnamespace = ns.oid) WHERE<br />
relkind in (''r'',''v'',''S'') AND<br />
nspname = $4 AND<br />
relname LIKE $3<br />
LOOP<br />
EXECUTE ''GRANT '' || $2 || '' ON '' || obj.relname || '' TO '' || $1;<br />
num := num + 1;<br />
END LOOP;<br />
RETURN num;<br />
END;<br />
' LANGUAGE plpgsql SECURITY DEFINER;<br />
</code><br />
–Function to revoke access(select,insert,update,delete) from users<br />
<code><br />
CREATE FUNCTION pg_revoke(TEXT, TEXT, TEXT, TEXT)<br />
RETURNS integer AS '<br />
DECLARE obj record;<br />
num integer;<br />
BEGIN<br />
num:=0;<br />
FOR obj IN SELECT relname FROM pg_class c<br />
JOIN pg_namespace ns ON (c.relnamespace = ns.oid) WHERE<br />
relkind in (''r'',''v'',''S'') AND<br />
nspname = $4 AND<br />
relname LIKE $3<br />
LOOP<br />
EXECUTE ''REVOKE '' || $2 || '' ON '' || obj.relname || '' FROM '' || $1;<br />
num := num + 1;<br />
END LOOP;<br />
RETURN num;<br />
END;<br />
' LANGUAGE plpgsql SECURITY DEFINER;<br />
</code><br />
–Create users for your database<br />
<code><br />
CREATE USER userreadonly WITH PASSWORD 'userr3ad0nly';<br />
CREATE USER userall WITH PASSWORD 'usersh0pa11';<br />
</code><br />
–Grant respective access to users<br />
<code><br />
select pg_grant('</code><code>userreadonly </code><code>','select','%','public');<br />
select pg_grant('</code><code>userall </code><code>','select,insert,update,delete','%','public');<br />
</code></p>
<p>You might need to create lang for plpgsql if you had not done so<br />
<code><br />
createlang plpgsql yrdatabasename</code></p>
</div>
<div class="shr-publisher-127"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2009/06/17/grant-privileges-to-all-tables-in-a-database-for-postgresql/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Get location from IP address in Ruby On Rails for free&#8230;.</title>
		<link>http://blog.bhushangahire.net/2009/05/20/get-location-from-ip-address-in-ruby-on-rails-for-free/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=get-location-from-ip-address-in-ruby-on-rails-for-free</link>
		<comments>http://blog.bhushangahire.net/2009/05/20/get-location-from-ip-address-in-ruby-on-rails-for-free/#comments</comments>
		<pubDate>Wed, 20 May 2009 09:42:07 +0000</pubDate>
		<dc:creator>Bhushan Ahire</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[ip address]]></category>
		<category><![CDATA[location]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=116</guid>
		<description><![CDATA[Find below the code for finding location from IP address using IP location tools. require 'net/http' require 'rexml/document' include REXML class MapsController < ApplicationController def index @location = locateIp() end def locateIp ip = request.remote_ip ips = ip.to_s url = "http://iplocationtools.com/ip_query.php?ip="+ips xml_data = Net::HTTP.get_response(URI.parse(url)).body xmldoc = REXML::Document.new(xml_data) # Now get the root element root = [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><div class="snap_preview">
<p>Find below the code for finding location from IP address using <a href="http://www.iplocationtools.com/">IP location tools</a>.</p>
<pre>require 'net/http'
require 'rexml/document'
include REXML

class MapsController < ApplicationController
	def index
		@location = locateIp()

	end

	def locateIp
		ip = request.remote_ip
		ips = ip.to_s
		url = "http://iplocationtools.com/ip_query.php?ip="+ips

		xml_data = Net::HTTP.get_response(URI.parse(url)).body

                xmldoc = REXML::Document.new(xml_data)

		# Now get the root element
		root = xmldoc.root
		city = ""
		regionName = ""
		countryName = ""

		# This will take country name...
		xmldoc.elements.each("Response/CountryName") {
		|e| countryName << e.text
	    }

		# Now get city name...
		xmldoc.elements.each("Response/City") {
   		|e| city << e.text
	    }

		# This will take regionName...
		xmldoc.elements.each("Response/RegionName") {
   		|e| regionName << e.text
	    }

     	ipLocation = city +", "+regionName+", "+countryName

	 return ipLocation
   end #end of method locateIp

end</pre>
</div>
<div class="shr-publisher-116"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2009/05/20/get-location-from-ip-address-in-ruby-on-rails-for-free/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Install and Configure FTP Server in Amazon EC2 instance</title>
		<link>http://blog.bhushangahire.net/2009/04/15/install-and-configure-ftp-server-in-amazon-ec2-instance/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=install-and-configure-ftp-server-in-amazon-ec2-instance</link>
		<comments>http://blog.bhushangahire.net/2009/04/15/install-and-configure-ftp-server-in-amazon-ec2-instance/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 14:17:51 +0000</pubDate>
		<dc:creator>Bhushan Ahire</dc:creator>
				<category><![CDATA[Amazon EC2]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[amazon]]></category>
		<category><![CDATA[connection]]></category>
		<category><![CDATA[ec2]]></category>
		<category><![CDATA[ftp]]></category>
		<category><![CDATA[live]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[setup]]></category>

		<guid isPermaLink="false">http://blog.bhushangahire.net/?p=97</guid>
		<description><![CDATA[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. [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>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.</p>
<p>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.</p>
<p>Install vsftpd FTP server, if not installed earlier: </p>
<p><code># yum install vsfptd</code></p>
<p>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. </p>
<p>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:</p>
<p>FTP server’s port 21 from anywhere (Client initiates connection).<br />
FTP server’s port 21 to ports &gt; 1023 (Server responds to client’s control port).<br />
FTP server’s ports &gt; 1023 from anywhere (Client initiates data connection to random port specified by server).<br />
FTP server’s ports &gt; 1023 to remote ports &gt; 1023 (Server sends ACKs (and data) to client’s data port).</p>
<p>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.</p>
<p>Opening up all ports &gt; 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.</p>
<p>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). </p>
<p><code># ec2-describe-group</code></p>
<p>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.<br />
<code># ec2-describe-group<br />
-bash: ec2-describe-group: command not found</code></p>
<p>You need to install ec2 command line tools. You can find them <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=351&amp;categoryID=88" onclick="javascript:urchinTracker('/outbound/developer.amazonwebservices.com/connect/entry.jspa?externalID=351_038_categoryID=88?ref=http_//www.google.co.in/search?hl=en_client=firefox-a_rls=org.mozilla_3Aen-US_3Aofficial_q=how+to+connect+amazon+ec2+instance+with+sftp_btnG=Search_meta=_aq=o_oq=');">here</a>  and the instructions to setup/configure can be found <a href="http://docs.amazonwebservices.com/AWSEC2/2008-02-01/GettingStartedGuide/?ref=get-started" onclick="javascript:urchinTracker('/outbound/docs.amazonwebservices.com/AWSEC2/2008-02-01/GettingStartedGuide/?ref=get-started?ref=http_//www.google.co.in/search?hl=en_client=firefox-a_rls=org.mozilla_3Aen-US_3Aofficial_q=how+to+connect+amazon+ec2+instance+with+sftp_btnG=Search_meta=_aq=o_oq=');">here.</a> </p>
<p>Open the ports now: </p>
<p><code># ec2-authorize default -p 20-21<br />
# ec2-authorize default -p 1024-1048</code></p>
<p>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 <a href="http://developer.amazonwebservices.com/connect/entry.jspa?externalID=609" onclick="javascript:urchinTracker('/outbound/developer.amazonwebservices.com/connect/entry.jspa?externalID=609?ref=http_//www.google.co.in/search?hl=en_client=firefox-a_rls=org.mozilla_3Aen-US_3Aofficial_q=how+to+connect+amazon+ec2+instance+with+sftp_btnG=Search_meta=_aq=o_oq=');">here.</a> </p>
<p>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:</p>
<p><code>Status: Connected<br />
Status: Retrieving directory listing...<br />
Command: PWD<br />
Response: 257 "/" is current directory.<br />
Command: TYPE A<br />
Response: 200 Type set to A<br />
Command: PASV<br />
Response: 227 Entering Passive Mode (216,182,238,73,129,75).<br />
Command: LIST<br />
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.<br />
Error: Could not retrieve directory listing<br />
</code></p>
<p>Time to configure vsftpd.conf file:<br />
<code># vi /etc/vsftpd/vsftpd.conf<br />
---Add following lines at the end of file---<br />
	pasv_enable=YES<br />
	pasv_min_port=1024<br />
	pasv_max_port=1048<br />
	pasv_address=<strong>Public IP of your instance</strong></code></p>
<p>Put public IP of your EC2 instance and then Save the file. Now restart the server: </p>
<p><code># /etc/init.d/vsftpd restart</code></p>
<div class="shr-publisher-97"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2009/04/15/install-and-configure-ftp-server-in-amazon-ec2-instance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails active_record_store &amp; Segmentation fault</title>
		<link>http://blog.bhushangahire.net/2008/02/25/rails-active_record_store-segmentation-fault/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=rails-active_record_store-segmentation-fault</link>
		<comments>http://blog.bhushangahire.net/2008/02/25/rails-active_record_store-segmentation-fault/#comments</comments>
		<pubDate>Mon, 25 Feb 2008 07:52:17 +0000</pubDate>
		<dc:creator>Bhushan Ahire</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Security]]></category>
		<category><![CDATA[active_record_store]]></category>
		<category><![CDATA[segmentation fault]]></category>

		<guid isPermaLink="false">http://www.bhushangahire.net/2008/02/25/rails-active_record_store-segmentation-fault/</guid>
		<description><![CDATA[Here&#8217;s a quick tip if you&#8217;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&#8217;re getting the Segmentation fault and your server crashes is because you&#8217;re trying to store too much data in sessions table of your application (I assume you are using active_record_store as a [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p class="entry">Here&#8217;s a quick tip if you&#8217;re getting errors like this one in your Rails application:</p>
<blockquote><p>/usr/local/lib/ruby/gems/1.8/gems/actionpack-2.0.2/lib/action_controller/session/active_record_store.rb:84: [BUG] Segmentation fault</p></blockquote>
<p>The most probable reason you&#8217;re getting the Segmentation fault and your server crashes is because you&#8217;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).</p>
<p>The problem with &#8220;too much data&#8221; is that by default, the session table creation rake task created the following migration in Rails 1.x:</p>
<blockquote><p>class AddSessions &lt; ActiveRecord::Migration<br />
def self.up</p>
<p>create_table :sessions do |t|<br />
t.column :session_id, :string<br />
<strong> t.column :data, :text</strong><br />
t.column :updated_at, :datetime<br />
end<br />
add_index :sessions, :session_id<br />
end</p>
<p>def self.down</p>
<p>drop_table :sessions<br />
end<br />
end</p></blockquote>
<p>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&#8217;re trying to store more than 64Kb in your session.</p>
<p>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:</p>
<p>Should look something like that (Rails 2 syntax):</p>
<blockquote><p>class CreateSessions &lt; ActiveRecord::Migration<br />
def self.up</p>
<p>drop_table :sessions</p>
<p>create_table :sessions do |t|<br />
t.string :session_id, :null =&gt; false<br />
<strong> t.column :data, :binary, :limit =&gt; 10.megabyte</strong><br />
t.timestamps<br />
end</p>
<p>add_index :sessions, :session_id<br />
add_index :sessions, :updated_at<br />
end</p>
<p>def self.down<br />
drop_table :sessions<br />
end<br />
end</p></blockquote>
<p>Empty your sessions table, restart your server and you&#8217;re done. No more segmentation faults. Of course you shouldn&#8217;t store that much data in a session in the first place.</p>
<div class="shr-publisher-34"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2008/02/25/rails-active_record_store-segmentation-fault/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby On Rails Security Guide</title>
		<link>http://blog.bhushangahire.net/2008/02/08/ruby-on-rails-security-guide/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=ruby-on-rails-security-guide</link>
		<comments>http://blog.bhushangahire.net/2008/02/08/ruby-on-rails-security-guide/#comments</comments>
		<pubDate>Fri, 08 Feb 2008 06:26:22 +0000</pubDate>
		<dc:creator>Bhushan Ahire</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Security]]></category>

		<guid isPermaLink="false">http://www.bhushangahire.net/2008/02/08/ruby-on-rails-security-guide/</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p class="entry-content">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.</p>
<p><a title="authen" name="authen"></a></p>
<h2>Authentication</h2>
<p>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.</p>
<p>Plugin &#8211; <strong>Restful Authentication</strong> (recommended) &#8211; easy to use and you can tweak it according to your requirements.</p>
<p class="linkbox"> <a href="http://railscasts.com/episodes/67" target="_blank">http://railscasts.com/episodes/67</a><br />
<a href="http://svn.techno-weenie.net/projects/plugins/restful_authentication/" target="_blank">http://svn.techno-weenie.net/projects/plugins/restful_authentication/</a></p>
<p><strong>Build your own authentication</strong>. You should rarely need to do this &#8230; Restful Authentication is quite flexible.
</p>
<p class="linkbox"> <a href="http://www.aidanf.net/rails_user_authentication_tutorial" target="_blank">http://www.aidanf.net/rails_user_authentication_tutorial</a></p>
<p><strong>OpenID</strong> &#8211; a universal authentication system to avoid use of multiple username and password on the Internet. OpenID is getting quite famous now-a-days.</p>
<p class="linkbox"> <a href="http://media.railscasts.com/videos/068_openid_authentication.mov" target="_blank">http://media.railscasts.com/videos/068_openid_authentication.mov</a><br />
<a href="http://agilewebdevelopment.com/plugins/openidauthentication" target="_blank">http://agilewebdevelopment.com/plugins/openidauthentication</a></p>
<p><strong>Access Control</strong> : To easily proivde different priviliges to your users. There are a lot of cool plugins available for access control.</p>
<p class="linkbox"> <a href="https://opensvn.csie.org/traccgi/tobionrails" target="_blank">https://opensvn.csie.org/traccgi/tobionrails</a><br />
<a href="http://code.google.com/p/rolerequirement/" target="_blank">http://code.google.com/p/rolerequirement/</a><br />
<a href="http://agilewebdevelopment.com/plugins/activeacl_rails_authorization_system" target="_blank">http://agilewebdevelopment.com/plugins/activeacl_rails_authorization_system</a></p>
<p><strong>Centralized Authentication Server</strong> &#8211; 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.
</p>
<p class="linkbox"> <a href="http://agilewebdevelopment.com/plugins/cas_authentication_filter" target="_blank">http://agilewebdevelopment.com/plugins/cas_authentication_filter</a></p>
<p>Use <strong>Google Authentication API</strong> to let your users login using their google username and password.</p>
<p class="linkbox"> <a href="http://rubyforge.org/projects/asgoogleaccount/" target="_blank">http://rubyforge.org/projects/asgoogleaccount/</a></p>
<p><strong>More Plugins</strong> :</p>
<p class="linkbox"> Rails inbuilt Authentication &#8211;  <a href="http://ryandaigle.com/articles/2006/12/4/whats-new-in-edge-rails-new-http-authentication-plugin-and-a-plea-to-contribute" target="_blank">http://ryandaigle.com/articles/2006/12/4/whats-new-in&#8230;</a><br />
Acts_as_authenticated &#8211; <a href="http://technoweenie.stikipad.com/plugins/show/User+Authentication" target="_blank">http://technoweenie.stikipad.com/plugins/show/User+Authentication</a><br />
Super Simple Authentication &#8211; <a href="http://ariejan.net/2007/08/24/super-simple-authentication-plugin-and-generator/" target="_blank">http://ariejan.net/2007/08/24/super-simple-&#8230;</a></p>
<p><a title="model" name="model"></a></p>
<h1>- Model -</h1>
<p><a title="sqlinjection" name="sqlinjection"></a></p>
<h2>SQL Injection</h2>
<p>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.</p>
<p><strong>Description</strong> :
</p>
<p class="linkbox"> <a href="http://manuals.rubyonrails.com/read/chapter/43" target="_blank">http://manuals.rubyonrails.com/read/chapter/43</a></p>
<p><strong>Alternate Solution</strong> &#8211; use hash for specifying conditions in <code class="inline">#find</code></p>
<p class="linkbox"> <a href="http://weblog.rubyonrails.org/2006/11/26/1-2-new-in-activerecord" target="_blank">http://weblog.rubyonrails.org/2006/11/26/1-2-new-in-activerecord</a></p>
<p><a title="validation" name="validation"></a></p>
<h2>Activerecord Validation</h2>
<p>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.</p>
<p><strong>Description</strong> :</p>
<p class="linkbox"> <a href="http://rails.rubyonrails.com/classes/ActiveRecord/Validations/ClassMethods.html" target="_blank">http://rails.rubyonrails.com/classes/ActiveRecord/Validations/ClassMethods.html</a></p>
<p><strong>Conditional validation</strong> using <code class="inline"> <img src='http://blog.bhushangahire.net/wp-includes/images/smilies/icon_surprised.gif' alt=':o' class='wp-smiley' /> n</code> and <code class="inline">:if</code> options. Checkout this cool video</p>
<p class="linkbox"> <a href="http://media.railscasts.com/videos/041_conditional_validations.mov" target="_blank">http://media.railscasts.com/videos/041_conditional_validations.mov</a></p>
<p>Be careful using <strong>validates_uniqueness_of</strong>, it has problems when used with <code class="inline">:scope</code> option. Open bug tickets :</p>
<p class="linkbox"> <a href="http://dev.rubyonrails.org/ticket/5608" target="_blank">http://dev.rubyonrails.org/ticket/5608</a><br />
<a href="http://dev.rubyonrails.org/ticket/9235" target="_blank">http://dev.rubyonrails.org/ticket/9235</a><br />
<a href="http://dev.rubyonrails.org/ticket/8811" target="_blank">http://dev.rubyonrails.org/ticket/8811</a><a href="http://dev.rubyonrails.org/ticket/8774" target="_blank">http://dev.rubyonrails.org/ticket/8774</a></p>
<p>Use <strong>:allow_blank</strong> to pass validations if value is nil or empty string
</p>
<p class="linkbox"> <a href="http://ryandaigle.com/articles/2007/9/5/what-s-new-in-edge-rails-validations-now-allow_blank" target="_blank">http://ryandaigle.com/articles/2007/9/5/what-s-new-in-edge-rails-validations-now-allow_blank</a></p>
<p><strong>Testing Validations</strong> &#8211; do read the comments in this article</p>
<p class="linkbox"><a href="http://blog.jayfields.com/2006/12/rails-unit-testing-activerecord.html" target="_blank">http://blog.jayfields.com/2006/12/rails-unit-testing-activerecord.html<br />
</a></p>
<p><strong>Useful Tips</strong></p>
<ul>
<li>Its easy to manage &#8216;nil&#8217; values using <code class="inline">:allow_nil</code>, its quite handy. For ex: set <code class="inline">:allow_nil =&gt; true</code> in validates_uniqueness_of to check uniqueness of non-nil values and ignore nil values</li>
<li> validates_presence_of is not required if you are using validates_format_of, unless regular expression accepts empty string.</li>
</ul>
<p><a title="crdfp" name="crdfp"></a></p>
<h2>Creating records directly from parameters</h2>
<p>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.</p>
<p><strong>Description</strong> :
</p>
<p class="linkbox"> <a href="http://manuals.rubyonrails.com/read/chapter/47" target="_blank">http://manuals.rubyonrails.com/read/chapter/47</a></p>
<p><strong>Alternate Solution</strong> &#8211; Trim the parameters to keep the required keys and remove the others.</p>
<p class="linkbox"> <a href="http://wiki.rubyonrails.org/rails/pages/HowToPreventFormInjection" target="_blank">http://wiki.rubyonrails.org/rails/pages/HowToPreventFormInjection</a></p>
<p><a title="controller" name="controller"></a></p>
<h1>- Controller -</h1>
<p><a title="em" name="em"></a></p>
<h2>Exposing methods</h2>
<p>Use private and protected in controller for methods which should not be actions. Actions are pubic methods and can be invoked from the browser.</p>
<p><strong>hide_action</strong> : If non-action controller methods must be public, hide them using hide_action.</p>
<p class="linkbox"> <a href="http://www.mathewabonyi.com/articles/2006/08/11/hide_action-a-hidden-treasure" target="_blank">http://www.mathewabonyi.com/articles/2006/08/11/hide_action-a-hidden-treasure</a></p>
<p>Be careful of bypassing private and protected using <strong>meta-programming</strong></p>
<p class="linkbox"> <a href="http://dev.zeraweb.com/design-blog-14" target="_blank">http://dev.zeraweb.com/design-blog-14</a></p>
<p><a title="authorization" name="authorization"></a></p>
<h2>Authorize parameters</h2>
<p>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.</p>
<p>For example :</p>
<table class="CodeRay">
<tr>
<td class="code">
<pre ondblclick="with (this.style) { overflow = (overflow == 'auto' || overflow == '') ? 'visible' : 'auto' }"><span class="c">## To find information of an order which belongs to a particular user.</span><tt>
</tt>
<span class="c">#Incorrect :</span><tt>
</tt><span class="iv">@order</span> = <span class="co">Order</span>.find(order_id)<tt>
</tt>
<span class="c">#Correct :</span><tt>
</tt><span class="iv">@order</span> = <span class="iv">@user</span>.orders.find(order_id)</pre>
</td>
</tr>
</table>
<p>Do not ignore <strong>hidden fields</strong> &#8211; a user can easily modify their value, so suspect them similar to params[:id]</p>
<p class="linkbox"> <a href="http://searchsecurity.techtarget.com/tip/1,289483,sid14_gci1153816,00.html" target="_blank">http://searchsecurity.techtarget.com/tip/1,289483,sid14_gci1153816,00.html</a></p>
<p><a title="fsl" name="fsl"></a></p>
<h2>Filter sensitive logs</h2>
<p>Prevent logs of sensitive unencrypted data using <code class="inline">#filter_parameter_logging</code> 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.</p>
<p><strong>Video Tutorial</strong></p>
<p class="linkbox"> <a href="http://railscasts.com/episodes/9" target="_blank">http://railscasts.com/episodes/9</a></p>
<p><a title="csrf" name="csrf"></a></p>
<h2>Cross Site Reference(or Request) Forgery (CSRF)</h2>
<p>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.</p>
<p>Its little complex to understand this attack. So, only those readers who are very enthusiastic to know about it, please read the <strong>Description</strong> below. Rest can directly move ahead to use the plugin.</p>
<p><strong>Description</strong> :</p>
<p class="linkbox"> <a href="http://isc.sans.org/diary.html?storyid=1750" target="_blank">http://isc.sans.org/diary.html?storyid=1750</a><br />
<a href="http://en.wikipedia.org/wiki/Cross-site_request_forgery" target="_blank">http://en.wikipedia.org/wiki/Cross-site_request_forgery</a></p>
<p>Use <strong>Get and Post</strong> appropiately (note : Both get and post are vulnerable to CSRF)
</p>
<p class="linkbox"> <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1" target="_blank">http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.1.1</a></p>
<p><strong>Example</strong> &#8211; Gmail CSRF security flaw</p>
<p class="linkbox"> <a href="http://ajaxian.com/archives/gmail-csrf-security-flaw" target="_blank">http://ajaxian.com/archives/gmail-csrf-security-flaw</a></p>
<p>Plugin &#8211; <strong>CSRF Killer</strong> (recommended) &#8211; it requires edge rails</p>
<p class="linkbox"> <a href="http://svn.techno-weenie.net/projects/plugins/csrf_killer/" target="_blank">http://svn.techno-weenie.net/projects/plugins/csrf_killer/</a><br />
<a href="http://activereload.net/2007/3/6/your-requests-are-safe-with-us" target="_blank">http://activereload.net/2007/3/6/your-requests-are-safe-with-us</a></p>
<p class="linkbox"> Secure action &#8211; <a href="http://code.google.com/p/secure-action-plugin/" target="_blank">http://code.google.com/p/secure-action-plugin/</a><br />
Security extension &#8211; <a href="http://svn.aviditybytes.com/rails/plugins/security_extensions/" target="_blank">http://svn.aviditybytes.com/rails/plugins/security_extensions/</a></p>
<p><a title="sessions" name="sessions"></a></p>
<h2>Minimize session attacks</h2>
<p>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:</p>
<ol>
<li>Store IP Address, but creates problem if user moves from one network to another.</li>
<li>Create a new session everytime someone logs in.</li>
<li>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.</li>
</ol>
<p><strong>Code for session expiry on timeout</strong></p>
<table class="CodeRay">
<tr>
<td class="code">
<pre ondblclick="with (this.style) { overflow = (overflow == 'auto' || overflow == '') ? 'visible' : 'auto' }"><span class="c">## Timeout after inactivity of one hour.</span><tt>
</tt><span class="co">MAX_SESSION_PERIOD</span> = <span class="i">3600</span><tt>
</tt>before_filter <span class="sy">:session_expiry</span>
<span class="r">def</span> <span class="fu">session_expiry</span><tt>
</tt>   reset_session <span class="r">if</span> session[<span class="sy">:expiry_time</span>] <span class="r">and</span> session[<span class="sy">:expiry_time</span>] < <span class="co">Time.now<tt>
</tt>   session[<span class="sy">:expiry_time</span>] = <span class="co">MAX_SESSION_PERIOD</span>.seconds.from_now<tt>
</tt>   <span class="r">return</span> <span class="pc">true</span><tt>
</tt><span class="r">end</span></pre>
</td>
</tr>
</table>
<p>Plugin &#8211; <strong>Session Expiration</strong> for session expiry on timeout
</p>
<p class="linkbox"> <a href="http://www.naffis.com/2007/5/22/automatically-expiring-sessions-in-rails" target="_blank">http://www.naffis.com/2007/5/22/automatically-expiring-sessions-in-rails</a></p>
<p>Do not put expiry time in the cookie unless your cookie information is properly encrypted. If not, use server side session expiry.</p>
<p class="linkbox"> <a href="http://wiki.rubyonrails.org/rails/pages/HowtoChangeSessionOptions" target="_blank">http://wiki.rubyonrails.org/rails/pages/HowtoChangeSessionOptions</a></p>
<p>Persistent session / login in rails &#8211; global setting in enviornment.rb</p>
<table class="CodeRay">
<tr>
<td class="line_numbers" title="click to toggle" onclick="with (this.firstChild.style) { display = (display == '') ? 'none' : '' }">
<pre><tt>
</tt></pre>
</td>
<td class="code">
<pre ondblclick="with (this.style) { overflow = (overflow == 'auto' || overflow == '') ? 'visible' : 'auto' }"><span class="co">ActionController</span>::<span class="co">Base</span>.session_options[<span class="sy">:session_expires</span>] = &lt;i&gt;say after two years&lt;<span class="rx"><span class="dl">/</span><span class="k">i&gt;</span></span></pre>
</td>
</tr>
</table>
<p>Persistent session / login in rails &#8211; to give your users a feature &#8211; <strong>remember me</strong></p>
<p class="linkbox"> <a href="http://blog.codahale.com/2006/04/08/dynamic-session-expiration-times-with-rails/" target="_blank">http://blog.codahale.com/2006/04/08/dynamic-session-expiration-times-with-rails/</a><br />
<a href="http://www.onrails.org/articles/2006/02/18/auto-login" target="_blank">http://www.onrails.org/articles/2006/02/18/auto-login</a><br />
<a href="http://livsey.org/2006/6/30/persistent-logins-in-rails" target="_blank">http://livsey.org/2006/6/30/persistent-logins-in-rails</a></p>
<p><a title="dnsbl" name="dnsbl"></a></p>
<h2>Stop spam on your website from DNS Blacklist</h2>
<p>Avoid access to your website from IP addresses which are present in DNS Blacklist(DNSBL).</p>
<p>Plugin &#8211; <strong>DNSBL check</strong>
</p>
<p class="linkbox"> <a href="http://spacebabies.nl/dnsbl_check/" target="_blank">http://spacebabies.nl/dnsbl_check/</a></p>
<p><a title="cap" name="cap"></a></p>
<h2>Caching authenticated pages</h2>
<p>Page caching does bypass any security filters in your application. So avoid caching authenticated pages and use action or fragment caching instead.</p>
<p><a title="view" name="view"></a></p>
<h1>- View -</h1>
<p><a title="xss" name="xss"></a></p>
<h2>Cross site scripting(XSS) attack</h2>
<p>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.</p>
<p><strong>Description</strong></p>
<p class="linkbox"> <a href="http://manuals.rubyonrails.com/read/chapter/44" target="_blank">http://manuals.rubyonrails.com/read/chapter/44</a></p>
<p><strong>Can we avoid tedious use of h() in views?</strong></p>
<p class="linkbox"> <a href="http://wiki.rubyonrails.org/rails/pages/HowToEscapeHTML" target="_blank">http://wiki.rubyonrails.org/rails/pages/HowToEscapeHTML</a></p>
<p><strong>Sanitize()</strong> is used to escape script tags and other malicious content other than html tags. Avoid using it &#8230; its unsecure. Use white_list instead.</p>
<p class="linkbox"> <a href="http://www.rorsecurity.info/2007/08/17/dont-use-strip_tags-strip_links-and-sanitize/" target="_blank">http://www.rorsecurity.info/2007/08/17/dont-use-strip_tags-strip_links-and-sanitize/</a></p>
<p><strong>White_list</strong> plugin</p>
<p class="linkbox"> <a href="http://svn.techno-weenie.net/projects/plugins/white_list/README" target="_blank">http://svn.techno-weenie.net/projects/plugins/white_list/README</a></p>
<p><a title="asfp" name="asfp"></a></p>
<h2>Anti-spam form protection</h2>
<p>Use <a href="http://en.wikipedia.org/wiki/Captcha">Captcha</a> or Javascript based form protection techniques to ensure only human can submit forms successfully.</p>
<p>When using Captcha do ensure the following :</p>
<ol>
<li>Images are rendered on webpage using <code class="inline">send_data</code> and are not stored at the server, because its not required to store images and are redundant.</li>
<li>Avoid using algorithm used by standard Catpcha plugins as they can easily be hacked, instead tweak an existing algorithm or write your own.</li>
<li>Use a Captcha which does not store secret code or images in filesystem, as you will have trouble using Captcha with multiple servers.</li>
</ol>
<p><strong>Tutorial</strong> &#8211; a nice article on concepts of captcha</p>
<p class="linkbox"> <a href="http://revolutiononrails.blogspot.com/2007/04/pedo-mellon-minno-or-captcha-on-rails.html" target="_blank">http://revolutiononrails.blogspot.com/2007/04/pedo-mellon-minno-or-captcha-on-rails.html</a></p>
<p>Plugin &#8211; <strong>ReCaptcha</strong> (recommended)</p>
<p class="linkbox"> <a href="http://recaptcha.net/" target="_blank">http://recaptcha.net/</a><br />
<a href="http://ambethia.com/recaptcha/" target="_blank">http://ambethia.com/recaptcha/</a></p>
<p>Plugin &#8211; BrainBuster &#8211; a <strong>logic captcha</strong> 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.
</p>
<p class="linkbox"> <a href="http://robsanheim.com/brain-buster" target="_blank">http://robsanheim.com/brain-buster</a></p>
<p>Plugin &#8211; <strong>Simple Captcha</strong> (not recommended) as it breaks all the must have features of a good Captcha implementation.</p>
<p class="linkbox"> <a href="http://expressica.com/2007/03/23/simple_captcha_1_0/" target="_blank">http://expressica.com/2007/03/23/simple_captcha_1_0/</a></p>
<p>For less critical systems like blogs, a more <strong>user-friendly option</strong> 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.</p>
<p class="linkbox"> CSS based Negative Captcha &#8211; <a href="http://damienkatz.net/2007/01/negative_captch.html" target="_blank">http://damienkatz.net/2007/01/negative_captch.html</a><br />
Inverse Captcha for Mephisto &#8211; <a href="http://www.artweb-design.de/projects/mephisto-plugin-inverse-captcha-for-comments-anti-spam" target="_blank">http://www.artweb-design.de/projects/mephisto-plugin-inverse&#8230;</a><br />
JavaScript based Form Spam Protection &#8211; <a href="http://form-spam-protection.googlecode.com/svn/form_spam_protection/" target="_blank">http://form-spam-protection.googlecode.com/svn/form&#8230;</a></p>
<p><strong>Captcha with Multiple Servers</strong>
</p>
<p class="linkbox"> <a href="http://upstream-berlin.com/blog/2007/08/17/captchas-with-rails-and-multiple-servers/" target="_blank">http://upstream-berlin.com/blog/2007/08/17/captchas-with-rails-and-multiple-servers/</a></p>
<p><a title="mailto" name="mailto"></a></p>
<h2>Hide mailto links</h2>
<p>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.</p>
<p>Plugin &#8211; <strong>CipherMail</strong></p>
<p class="linkbox"> <a href="http://agilewebdevelopment.com/plugins/ciphermail" target="_blank">http://agilewebdevelopment.com/plugins/ciphermail</a></p>
<p><a title="uspe" name="uspe"></a></p>
<h2>Use password strength evaluators</h2>
<p>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&#8217;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.</p>
<p>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.</p>
<p><strong>Tools</strong></p>
<p class="linkbox"> <a href="http://www.certainkey.com/demos/password/" target="_blank">http://www.certainkey.com/demos/password/</a><a href="http://www.jeffro2pt0.com/ajax-powered-password-strength-meter/" target="_blank">http://www.jeffro2pt0.com/ajax-powered-password-strength-meter/</a><br />
<a href="http://www.geekwisdom.com/dyn/passwdmeter" target="_blank">http://www.geekwisdom.com/dyn/passwdmeter</a><br />
<a href="http://www.jvoorhis.com/articles/2006/04/06/automatic-password-suggestion-for-your-rails-app" target="_blank">http://www.jvoorhis.com/articles/2006/04/06/automatic-password-suggestion-for-your-rails-app</a></p>
<p><a title="misc" name="misc"></a></p>
<h1>- Miscellaneous -</h1>
<p><a title="transmission" name="transmission"></a></p>
<h2>Transmission of Sensitive information</h2>
<p>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.</p>
<p>Plugin <strong>ssl_requirement</strong>
</p>
<p class="linkbox"> <a href="http://svn.rubyonrails.org/rails/plugins/ssl_requirement/README" target="_blank">http://svn.rubyonrails.org/rails/plugins/ssl_requirement/README</a></p>
<p><strong>Mongrel, rails, apache and SSL</strong></p>
<p class="linkbox"><a href="http://blog.innerewut.de/2006/06/21/mongrel-and-rails-behind-apache-2-2-and-ssl" target="_blank">http://blog.innerewut.de/2006/06/21/mongrel-and-rails-behind-apache-2-2-and-ssl</a></p>
<p>Controller in <strong>SSL subdomain</strong></p>
<p class="linkbox"> <a href="http://www.railsonwave.com/railsonwave/2007/7/10/howto-put-a-controller-under-a-ssl-subdomain" target="_blank">http://www.railsonwave.com/railsonwave/2007/7/10/howto-put-a-controller-under-a-ssl-subdomain</a></p>
<p><strong>Sample SSL code in rails</strong></p>
<p class="linkbox"> <a href="http://blog.caboo.se/articles/2007/4/21/sample-rails-app-branch-with-ssl" target="_blank">http://blog.caboo.se/articles/2007/4/21/sample-rails-app-branch-with-ssl</a></p>
<p><a title="fileupload" name="fileupload"></a></p>
<h2>File upload</h2>
<p>Be very careful when you allow your users to upload files and make them available for other users to download.</p>
<p><strong>Description</strong></p>
<p class="linkbox"> <a href="http://www.rorsecurity.info/2007/03/27/working-with-files-in-rails/" target="_blank">http://www.rorsecurity.info/2007/03/27/working-with-files-in-rails/</a></p>
<p><strong>Must read</strong> &#8211; Section 26.7 of Agile web development with rails &#8211; 2nd edition</p>
<p class="linkbox"> <a href="http://www.pragmaticprogrammer.com/titles/rails2/" target="_blank">http://www.pragmaticprogrammer.com/titles/rails2/</a></p>
<p><strong>In place file upload</strong></p>
<p class="linkbox"> <a href="http://kpumuk.info/ruby-on-rails/in-place-file-upload-with-ruby-on-rails/" target="_blank">http://kpumuk.info/ruby-on-rails/in-place-file-upload-with-ruby-on-rails/</a></p>
<p>3 plugins for file upload reviewed at :</p>
<p class="linkbox"><a href="http://www.flex888.com/2007/03/21/three-ruby-on-rails-file-upload-plugins-reviewed.html" target="_blank">http://www.flex888.com/2007/03/21/three-ruby-on-rails-file-upload-plugins-reviewed.html</a></p>
<p><a title="environment" name="environment"></a></p>
<h2>Secure your setup / environment</h2>
<p class="linkbox"> <a href="http://www.igvita.com/blog/2006/10/10/securing-your-rails-environment/" target="_blank">http://www.igvita.com/blog/2006/10/10/securing-your-rails-environment/</a></p>
<p><a title="mysql" name="mysql"></a></p>
<h2>Proper Mysql configuration</h2>
<p class="linkbox"> <a href="http://www.rorsecurity.info/2007/02/25/securing-mysql/" target="_blank">http://www.rorsecurity.info/2007/02/25/securing-mysql/</a><br />
<a href="http://www.rorsecurity.info/2007/02/27/rails%e2%80%99-friends-securing-mysql-continued/" target="_blank">http://www.rorsecurity.info/2007/02/27/rails%e2%80%99-friends-securing-mysql-continued/</a></p>
<p><a title="goodpassword" name="goodpassword"></a></p>
<h2>Use good passwords</h2>
</p>
<p class="linkbox"> <a href="http://en.wikipedia.org/wiki/Password_strength" target="_blank">http://en.wikipedia.org/wiki/Password_strength</a><a href="http://www.rorsecurity.info/2007/06/05/use-good-passwords/" target="_blank">http://www.rorsecurity.info/2007/06/05/use-good-passwords/</a></p>
<p><a title="directory" name="directory"></a></p>
<h1>Security plugins directory</h1>
<p class="linkbox"> <a href="http://agilewebdevelopment.com/plugins/category/1" target="_blank">http://agilewebdevelopment.com/plugins/category/1</a><br />
<a href="http://www.railslodge.com/plugins" target="_blank">http://www.railslodge.com/plugins</a><br />
<a href="http://railsify.com/categories/security-production" target="_blank">http://railsify.com/categories/security-production</a></p>
<p><a href="http://www.quarkruby.com/2007/9/20/ruby-on-rails-security-guide">Original Source http://www.quarkruby.com/2007/9/20/ruby-on-rails-security-guide</a></p>
<div class="shr-publisher-33"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://blog.bhushangahire.net/2008/02/08/ruby-on-rails-security-guide/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
<enclosure url="http://media.railscasts.com/videos/068_openid_authentication.mov" length="29067479" type="video/quicktime" />
<enclosure url="http://media.railscasts.com/videos/041_conditional_validations.mov" length="9050127" type="video/quicktime" />
		</item>
	</channel>
</rss>

