Rails | IP spoofing attack - ruby-on-rails

lately I have received such an error on ruby on rails, but do not know what it means. Any help well appreciated!
ERROR: Failed to generate exception summary:
ActionView::Template::Error: IP spoofing attack?! HTTP_CLIENT_IP="172.17.3.20" HTTP_X_FORWARDED_FOR="79.170.168.251"
EDIT:
I have such a function in the application controller
before_filter :ensure_domain
APP_DOMAIN = 'www.mysite.com'
def ensure_domain
if request.env['HTTP_HOST'] != APP_DOMAIN && Rails.env.production?
#HTTP 301 is a "permanent" redirect
redirect_to "https://#{APP_DOMAIN}#{request.path}", :status => 301
end
end

Unless you're actually doing IP-based authorization, you can likely ignore this. All that this message is telling you is that the IP that the request is coming from is different than the IP that's passed in the HTTP_X_FORWARDED_FOR header, which doesn't necessarily mean that it's a spoof. There are plenty of legitimate reasons for this, so it's generally okay to simply disable the spoof check by setting config.action_dispatch.ip_spoofing_check = false

Related

Rails under Apache and Passenger: no headers

In an Rails app, I have a filter that checks some headers. Something like:
before_action :validate_consumer
...
def validate_consumer
consumer = self.request.headers['HTTP_CONSUMER_SECRET'] == 'random_key'
consumer || render_unauthorized("Consumer -")
end
def render_unauthorized(token="")
self.headers['WWW-Authenticate'] = 'Token realm="Application"'
render json: {error: "#{token} Bad credentials", error_description: "Denied"}, status: 401
end
this works perfect running locally (development), the header the view sends (CONSUMER_SECRET) is present in the request. But when I run in production mode, this header does not exists. I guess that this might have something related with my environment: that app runs under Apache (with Phusion+Passenger). Could it be this the problem? Anyone knows how to solve?

Getting "Authentication failure! invalid_credentials: OAuth2::Error" for custom omniauth strategy

Currently I am working on rails 4 project, and now I have to link / connect another application (not sso but for accessing API's) say example.com. (Note: example.com uses 3-legged oauth security architecture)
After searching found that I have to implement omniouth strategy.
For this I have refereed this link. As per Strategy-Contribution-Guide I am able to complete setup and request Phase, You can find my sample code here.
require 'multi_json'
require 'omniauth/strategies/oauth2'
require 'uri'
module OmniAuth
module Strategies
class MyAppStrategy < OmniAuth::Strategies::OAuth2
option :name, 'my_app_strategy'
option :client_options, {
site: site_url,
authorize_url: authorize_url,
request_url: request_url,
token_url: token_url,
token_method: :post,
header: { Accept: accept_header }
}
option :headers, { Accept: accept_header }
option :provider_ignores_state, true
def consumer
binding.pry
::OAuth::Consumer.new(options.client_id, options.client_secret, options.client_options)
end
def request_phase # rubocop:disable MethodLength
binding.pry
request_token = consumer.get_request_token({:oauth_callback => callback_url}, options.request_params)
session["oauth"] ||= {}
session["oauth"][name.to_s] = {"callback_confirmed" => request_token.callback_confirmed?, "request_token" => request_token.token, "request_secret" => request_token.secret}
if request_token.callback_confirmed?
redirect request_token.authorize_url(options[:authorize_params])
else
redirect request_token.authorize_url(options[:authorize_params].merge(:oauth_callback => callback_url))
end
rescue ::Timeout::Error => e
fail!(:timeout, e)
rescue ::Net::HTTPFatalError, ::OpenSSL::SSL::SSLError => e
fail!(:service_unavailable, e)
end
def callback_phase # rubocop:disable MethodLength
fail(OmniAuth::NoSessionError, "Session Expired") if session["oauth"].nil?
request_token = ::OAuth::RequestToken.new(consumer, session["oauth"][name.to_s].delete("request_token"), session["oauth"][name.to_s].delete("request_secret"))
opts = {}
if session["oauth"][name.to_s]["callback_confirmed"]
opts[:oauth_verifier] = request["oauth_verifier"]
else
opts[:oauth_callback] = 'http://localhost:3000/auth/callback' #callback_url
end
#access_token = request_token.get_access_token(opts)
super
rescue ::Timeout::Error => e
fail!(:timeout, e)
rescue ::Net::HTTPFatalError, ::OpenSSL::SSL::SSLError => e
fail!(:service_unavailable, e)
rescue ::OAuth::Unauthorized => e
fail!(:invalid_credentials, e)
rescue ::OmniAuth::NoSessionError => e
fail!(:session_expired, e)
end
def custom_build_access_token
binding.pry
verifier = request["oauth_verifier"]
client.auth_code.get_token(verifier, get_token_options(callback_url), deep_symbolize(options.auth_token_params))
end
alias_method :build_access_token, :custom_build_access_token
def raw_info
binding.pry
#raw_info ||= access_token.get('users/me').parsed || {}
end
private
def callback_url
options[:redirect_uri] || (full_host + script_name + callback_path)
end
def get_token_options(redirect_uri)
{ :redirect_uri => redirect_uri }.merge(token_params.to_hash(:symbolize_keys => true))
end
end
end
end
I am able redirect to example.com, also after login I am able to return to my callback_phase (you will ask how did you know, so answer is I have added binding.pry in callback_phase method for checking the flow).
But after executing the strategy I am getting following error
ERROR -- omniauth: (my_app_strategy) Authentication failure! invalid_credentials: OAuth2::Error.
After debugging found that I am getting this error for the super call (from callback_phase method).
First I though may be there are some credentials issue but I am able fetch access token using following (which is executing before the super call)
#access_token = request_token.get_access_token(opts)
Also for more information I am getting error for build_access_token which is the oauth2 method
You can refer this link for more info (just search the build_access_token on the page).
EDIT - 1
After debugging found that getting this issue from the request method.
(While making the faraday request). Here is the code snippet
response = connection.run_request(verb, url, opts[:body], opts[:headers]) do |req|
yield(req) if block_given?
end
Here is my faraday request
#<struct Faraday::Request method=:post, path="example.com/oauth/access_token", params={}, headers={"User-Agent"=>"Faraday v0.9.2", "Content-Type"=>"application/x-www-form-urlencoded"}, body={"grant_type"=>"authorization_code", "code"=>"aPexxxvUg", "client_id"=>"xxxxxur303GXEch7QK9k", "client_secret"=>"xxxxxxcad97b3d252e2bcdd393a", :redirect_uri=>"http://localhost:3000/auth/my_app_strategy/callback"}, options=#<Faraday::RequestOptions (empty)>>
In response I am getting following error message
HTTP Status 400 - Inadequate OAuth consumer credentials.
So can any one help to fix this issue?
Is there any other way to store the access token so that I can utilize this for communication purpose.
Thanks
First of all, I wan to make clear how Oauth2 works:
Oauth2, the protocol says:
You redirect the user to the provider sign in endpoint adding some required parameters (Ejm: PROVIDER/public/oauth?redirect_uri=MYWEB/oauthDemo&
response_type=code&client_id=ABCDE). Sometimes there is also a scope/permission/resource parameter that indicates whats your purpose.
-> Then the users signs in and is redirected to your endpoint MYWEB/public/oauth with a code
Now you have to request the access token doing a POST to the providers endpoint. Example:
POST PROVIDER?code=d5Q3HC7EGNH36SE3N&
client_id=d4HQNPFIXFD255H&
client_secret=1a98b7cb92407cbd8961cd8db778de53&
redirect_uri=https://example.com/oauthDemo&
grant_type=authorization_code
Now you have the access_token and you can use it to get information or decode it using JWT.
Having this clear, and seeing that your call seems corect:
#<struct Faraday::Request method=:post, path="PROVIDER/oauth/access_token", params={}, headers={"User-Agent"=>"Faraday v0.9.2", "Content-Type"=>"application/x-www-form-urlencoded"}, body={"grant_type"=>"authorization_code", "code"=>"aPexxxvUg", "client_id"=>"xxxxxur303GXEch7QK9k", "client_secret"=>"xxxxxxcad97b3d252e2bcdd393a", :redirect_uri=>"MYWEB/auth/my_app_strategy/callback"}, options=#<Faraday::RequestOptions (empty)>>
As the response is "HTTP Status 400 - Inadequate OAuth consumer credentials.", I think maybe you:
a. Your client is not well configured on the Provider. Usually you use to have a basic configuration on the provider site so he can recognise you. So maybe is not well configured.
b. There is a resource/permission/scope parameter missing or wrong configured on the first step (in the redirection to the provider). So when you ask for the token there is a problem.

Rails, Backbone, PhoneGap, CORS (not allowed by Access-Control-Allow-Origin error)

I'm building a Phonegap app in that uses backbone.js and a Rails backend. While creating new users, I am getting a CORS related error:
I am running my PhoneGap web app on http://0.0.0.0:8000 ($ python -m SimpleHTTPServer), and running my Rails app in webrick on http://0.0.0.0:3000 ($ rails server).
The problem happens when trying to create a new "Spot" in Backbone like this (chrome js console):
> s = new App.Models.Spot()
(creates Spot)
> s.save()
(returns error Object)
OPTIONS http://0.0.0.0:3000/spots.json 404 (Not Found) jquery-1.8.2.js:8416
XMLHttpRequest cannot load http://0.0.0.0:3000/spots.json. Origin http://0.0.0.0:8000 is not allowed by Access-Control-Allow-Origin.
Here is my application controller:
def set_access_control_headers
headers['Access-Control-Allow-Origin'] = 'http://0.0.0.0:8000'
headers['Access-Control-Request-Method'] = 'POST, GET'
end
I have read numerous articles, and the furthest along I could get was when modifying my routes.rb to include this:
match '*all' => 'application#cor', :constraints => {:method => 'OPTIONS'}
And in my application_controller.rb
def cor
headers["Access-Control-Allow-Origin"] = "*"
headers["Access-Control-Allow-Methods"] = %w{GET POST PUT DELETE OPTIONS}.join(",")
headers["Access-Control-Allow-Headers"] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(",")
head(:ok) if request.request_method == "OPTIONS"
end
Adding the route and the 'cor' method will then allow me to make saves, but, I will have the same error when deleting records.
I get the basic idea of CORS, I can't access a server with a different domain than that of the origin of my request. But how exactly to set this up with Rails, Backbone, Phonegap, is not clear to me. Any help would be awesome, thanks!
I've follow this article (section "CORS in Rails") and it works for me.
I change if request.method == :options to if request.method == 'OPTIONS' and add methods PUT, DELETE to headers['Access-Control-Allow-Methods']. Insted of '*' in Access-Control-Allow-Origin I have localhost:8080 (I'm running my app on nginx).
Hope this will help.
PD: Do you have filters (hooks) in your application controller?

invalid URI - How to prevent, URI::InvalidURIError errors?

I got the following back from delayed_job:
[Worker(XXXXXX pid:3720)] Class#XXXXXXX failed with URI::InvalidURIError: bad URI(is not URI?): https://s3.amazonaws.com/cline-local-dev/2/attachments/542/original/mac-os-x[1].jpeg?AWSAccessKeyId=xxxxxxxx&Expires=1295403309&Signature=xxxxxxx%3D - 3 failed attempts
The way this URI comes from in my app is.
In my user_mailer I do:
#comment.attachments.each do |a|
attachments[a.attachment_file_name] = open(a.authenticated_url()) {|f| f.read }
end
Then in my attachments model:
def authenticated_url(style = nil, expires_in = 90.minutes)
AWS::S3::S3Object.url_for(attachment.path(style || attachment.default_style), attachment.bucket_name, :expires_in => expires_in, :use_ssl => attachment.s3_protocol == 'https')
end
That being said, is there some type of URI.encode or parsing I can do to prevent a valid URI (as I checked the URL works in my browser) for erroring and killing delayed_job in rails 3?
Thank you!
Ruby has (at least) two modules for dealing with URIs.
URI is part of the standard library.
Addressable::URI, is a separate gem, and more comprehensive, and claims to conform to the spec.
Parse a URL with either one, modify any parameters using the gem's methods, then convert it using to_s before passing it on, and you should be good to go.
I tried ' open( URI.parse(URI.encode( a.authenticated_url() )) ' but that errord with OpenURI::HTTPError: 403 Forbidden
If you navigated to that page via a browser and it succeeded, then later failed going to it directly via code, it's likely there is a cookie or session state that is missing. You might need to use something like Mechanize, which will maintain that state while allowing you to navigate through a site.
EDIT:
require 'addressable/uri'
url = 'http://www.example.com'
uri = Addressable::URI.parse(url)
uri.query_values = {
:foo => :bar,
:q => '"one two"'
}
uri.to_s # => "http://www.example.com?foo=bar&q=%22one%20two%22"

Automatically handle missing database connection in ActiveRecord?

With the launch of Amazon's Relational Database Service today and their 'enforced' maintenance windows I wondered if anyone has any solutions for handling a missing database connection in Rails.
Ideally I'd like to be able to automatically present a maintenance page to visitors if the database connection disappears (i.e. Amazon are doing their maintenance) - has anyone ever done anything like this?
Cheers
Arfon
You can do this with a Rack Middleware:
class RescueFromNoDB < Struct.new(:app)
def call(env)
app.call(env)
rescue Mysql::Error => e
if e.message =~ /Can't connect to/
[500, {"Content-Type" => "text/plain"}, ["Can't get to the DB server right now."]]
else
raise
end
end
end
Obviously you can customize the error message, and the e.message =~ /Can't connect to/ bit may just be paranoia, almost all other SQL errors should be caught inside ActionController::Dispatcher.

Resources