I have a Rails 3.2.2 application which is a simple company intranet, however although there isn't any private information on there it's probably best if it was fairly secure from the outside world.
We do however have people working from home on fairly regular occasions that don't have a VPN setup.
Currently I have a firewall rule that blocks everyone except a list of our teams/branches static IP addresses. The problem with this is when a team member visits the site from home the site never loads because the firewall rejects them. What I would like to do is serve a simple page within the application explaining why they don't have "full" access.
The firewall is serving multiple applications, so I can't put the access denied page on there
I have read a few questions on SO such as Get real IP address in local Rails development environment which show how to get their IP address, but I'm unsure how to alter a default route based on that.
Dae raises a good point in the comments, but just so you know:
http://guides.rubyonrails.org/routing.html#advanced-constraints
class BlacklistConstraint
def initialize
#ips = Blacklist.retrieve_ips
end
def matches?(request)
#ips.include?(request.remote_ip)
end
end
YourApp::Application.routes.draw do
match "*path" => "blacklist#index", :constraints => BlacklistConstraint.new
end
To expand on Robin's Whitelist method, here is my solution using multiple partial whitelisted ip's
class WhitelistConstraint
def initialize
#ips = ["127.0", "10.0.0.0/1"]
end
def matches?(request)
!#ips.select{|req| request.remote_ip.include?(req) }.empty?
end
end
Related
Does anyone know of a way of changing the :host of the Phoenix application endpoint dynamically on every request?
Specifically to support multiple domains on a single phoenix app, i want to change the host in the endpoint based on the host in the connection object.
Am trying something on the lines of
conn = Map.get_and_update(conn.private.phoenix_endpoint[:url], :host, fn (_) -> "ll.com" end)
or
Keyword.put(conn.private.phoenix_endpoint.config(:url), :host, conn.host)
But am not quite correct.
Wouldn't it just be a value you assign the :to keyword in the redirect?
def index(conn, params) do
redirect conn, to: params[:location] # or whatever
end
The master_proxy package offers some useful tools to support multiple sites.
I have an app I created on Heroku which is written in Ruby (not rails) and Sinatra.
It is hosted on the default herokuapp domain so I can address the app with both HTTP and HTTPS.
The app requests user credentials which I forward on to an HTTPS call so the forwarding part is secure.
I want to ensure my users always connect securely to my app so the credentials aren't passed in clear text.
Despite lots of research, I've not found a solution to this simple requirement.
Is there a simple solution without changing my app to Ruby rails or otherwise?
Thanks,
Alan
I use a helper that looks like this:
def https_required!
if settings.production? && request.scheme == 'http'
headers['Location'] = request.url.sub('http', 'https')
halt 301, "https required\n"
end
end
I can then add it to any single route I want to force to https, or use it in the before filter to force on a set of urls:
before "/admin/*" do
https_required!
end
Redirect in a Before Filter
This is untested, but it should work. If not, or if it needs additional refinement, it should at least give you a reasonable starting point.
before do
redirect request.url.sub('http', 'https') unless request.secure?
end
See Also
Filters
Request Object
RackSsl::Enforcer
How can I use local resources like css, js, png, etc. within a dynamically rendered page using webrick? In other words, how are things like Ruby on Rails linking made to work? I suppose this is one of the most basic things, and there should be a simple way to do it.
Possible Solution
I managed to do what I wanted using two servlets as follows:
require 'webrick'
class WEBrick::HTTPServlet::AbstractServlet
def do_GET request, response
response.body = '<html>
<head><base href="http://localhost:2000"/></head>
<body><img src="path/image.png" /></body>
</html>'
end
end
s1 = WEBrick::HTTPServer.new(Port: 2000, BindAddress: "localhost")
s2 = WEBrick::HTTPServer.new(Port: 3000, BindAddress: "localhost")
%w[INT TERM].each{|signal| trap(signal){s1.stop}}
%w[INT TERM].each{|signal| trap(signal){s2.shutdown}}
s1.mount("/", WEBrick::HTTPServlet::FileHandler, '/')
s2.mount("/", WEBrick::HTTPServlet::AbstractServlet)
Thread.new{s1.start}
s2.start
Is this the right way to do it? I do not feel so. In addition, I am not completely satisfied with it. For one thing, I do not like the fact that I have to specify http://localhost:2000 in the body. Another is the use of thread does not seem right. Is there a better way to do this? If you think this is the right way, please answer so.
Generally speaking, because of security concerns browsers likely won't link to local files (using file:// schema) from an internet site (using http:// or https:// schema). See Can Google Chrome open local links?. This is unrelated to any server side technology.
Outside of that, it seems your server is working perfectly. You've made it so it responds to all requests with a HTML page containing a link to /. When you click on that link, something does indeed happen; a request is sent and you are served the same page again.
It kind of sounds like you want to expose your entire filesystem via HTTP. If that is what you're trying to accomplish, you can simply get away with not mounting a servlet:
server = WEBrick::HTTPServer.new(Port: 3000, BindAddress: "localhost", DocumentRoot: "/")
%w[INT TERM].each{|signal| trap(signal){server.shutdown}}
server.start
Try code like this:
require 'webrick'
class WEBrick::HTTPServlet::AbstractServlet
def do_GET request, response
if request.unparsed_uri == "/"
response.body = '<html><body>test</body></html>'
end
end
end
server = WEBrick::HTTPServer.new(Port: 3000, BindAddress: "localhost", DocumentRoot: "/")
%w[INT TERM].each { |signal| trap(signal) { server.shutdown } }
server.mount("/", WEBrick::HTTPServlet::AbstractServlet)
server.start
This works for me, I'm not sure why but it seems to work whenever I call at least one method on the request object.
It sounds like you are confusing web pages that are served vs. pages that are opened by the browser directly from your drive, and how file: differs from http:, https:, and ftp:.
file: is a locally available resource when a page is directly opened from the drive. The others are remotely available resources when a page is served from a httpd host.
The browser can't tell that a page from a server came from your drive; It only knows it got it from a server, somewhere, and doesn't know or care whether that server is on the same hardware. Browsers will not allow access to local resources from remotely retrieved pages. That was an exploit that was closed years ago.
See RFC 1738's specification 3.10 FILES for file: URLs for the official statements.
I finally found out that I can mount multiple servlets on a single server. It took a long time until I found such example.
require 'webrick'
class WEBrick::HTTPServlet::AbstractServlet
def do_GET request, response
response.body = '<html>
<head><base href="/resource/"/></head>
<body>
<img src="path_to_image/image.png";alt="picture"/>
<a href="path_to_directory/" />link</a>
...
</body>
</html>'
end
end
server = WEBrick::HTTPServer.new(Port: 3000, BindAddress: "localhost")
%w[INT TERM].each{|signal| trap(signal){server.shutdown}}
server.mount("/resource/", WEBrick::HTTPServlet::FileHandler, '/')
server.mount("/", WEBrick::HTTPServlet::AbstractServlet)
server.start
The path /resource/ can be anything else. The link will now correctly redirect to the expected directory, showing that there is no access permission, which indicates that things are working right; it's now just a matter of permission.
I am working on a website hosted on microsoft's office live service. It has a contact form enabling visitors to get in touch with the owner. I want to write a Ruby script that sits on a seperate sever and which the form will POST to. It will parse the form data and email the details to a preset address. The script should then redirect the browser to a confirmation page.
I have an ubuntu hardy machine running nginx and postfix. Ruby is installed and we shall see about using Thin and it's Rack functionality to handle the script. Now it's come to writing the script and i've drawn a blank.
It's been a long time and if i remember rightly the process is something like;
read HTTP header
parse parameters
send email
send redirect header
Broadly speaking, the question has been answered. Figuring out how to use the answer was more complicated than expected and I thought worth sharing.
First Steps:
I learnt rather abruptly that nginx doesn't directly support cgi scripts. You have to use some other process to run the script and get nginx to proxy requests over. If I was doing this in php (which in hind sight i think would have been a more natural choice) i could use something like php-fcgi and expect life would be pretty straight forward.
Ruby and fcgi felt pretty daunting. But if we are abandoning the ideal of loading these things at runtime then Rack is probably the most straight forward solution and Thin includes all we need. Learning how to make basic little apps with them has been profoundly beneficial to a relative Rails newcomer like me. The foundations of a Rails app can seem hidden for a long time and Rack has helped me lift the curtain that little bit further.
Nonetheless, following Yehuda's advice and looking up sinatra has been another surprise. I now have a basic sinatra app running in a Thin instance. It communicates with nginx over a unix socket in what i gather is the standard way. Sinatra enables a really elegant way to handle different requests and routes into the app. All you need is a get '/' {} to start handling requests to the virtual host. To add more (in a clean fashion) we just include a routes/script.rb into the main file.
# cgi-bin.rb
# main file loaded as a sinatra app
require 'sinatra'
# load cgi routes
require 'routes/default'
require 'routes/contact'
# 404 behaviour
not_found do
"Sorry, this CGI host does not recognize that request."
end
These route files will call on functionality stored in a separate library of classes:
# routes/contact.rb
# contact controller
require 'lib/contact/contactTarget'
require 'lib/contact/contactPost'
post '/contact/:target/?' do |target|
# the target for the message is taken from the URL
msg = ContactPost.new(request, target)
redirect msg.action, 302
end
The sheer horror of figuring out such a simple thing will stay with me for a while. I was expecting to calmly let nginx know that .rb files were to be executed and to just get on with it. Now that this little sinatra app is up and running, I'll be able to dive straight in if I want to add extra functionality in the future.
Implementation:
The ContactPost class handles the messaging aspect. All it needs to know are the parameters in the request and the target for the email. ContactPost::action kicks everything off and returns an address for the controller to redirect to.
There is a separate ContactTarget class that does some authentication to make sure the specified target accepts messages from the URL given in request.referrer. This is handled in ContactTarget::accept? as we can guess from the ContactPost::action method;
# lib/contact/contactPost.rb
class ContactPost
# ...
def action
return failed unless #target.accept? #request.referer
if send?
successful
else
failed
end
end
# ...
end
ContactPost::successful and ContactPost::failed each return a redirect address by combining paths supplied with the HTML form with the request.referer URI. All the behaviour is thus specified in the HTML form. Future websites that use this script just need to be listed in the user's own ~/cgi/contact.conf and they'll be away. This is because ContactTarget looks in /home/:target/cgi/contact.conf for the details. Maybe oneday this will be inappropriate, but for now it's just fine for my purposes.
The send method is simple enough, it creates an instance of a simple Email class and ships it out. The Email class is pretty much based on the standard usage example given in the Ruby net/smtp documentation;
# lib/email/email.rb
require 'net/smtp'
class Email
def initialize(from_alias, to, reply, subject, body)
#from_alias = from_alias
#from = "cgi_user#host.domain.com"
#to = to
#reply = reply
#subject = subject
#body = body
end
def send
Net::SMTP.start('localhost', 25) do |smtp|
smtp.send_message to_s, #from, #to
end
end
def to_s
<<END_OF_MESSAGE
From: #{#from_alias}
To: #{#to}
Reply-To: #{#from_alias}
Subject: #{#subject}
Date: #{DateTime::now().to_s}
#{#body}
END_OF_MESSAGE
end
end
All I need to do is rack up the application, let nginx know which socket to talk to and we're away.
Thank you everyone for your helpful pointers in the right direction! Long live sinatra!
It's all in the Net module, here's an example:
#net = Net::HTTP.new 'http://www.foo.com', 80
#params = {:name => 'doris', :email => 'doris#foo.com'}
# Create HTTP request
req = Net::HTTP::Post.new( 'script.cgi', {} )
req.set_form_data #params
# Send request
response = #net.start do |http|
http.read_timeout = 5600
http.request req
end
Probably the best way to do this would be to use an existing Ruby library like Sinatra:
require "rubygems"
require "sinatra"
get "/myurl" do
# params hash available here
# send email
end
You'll probably want to use MailFactory to send the actual email, but you definitely don't need to be mucking about with headers or parsing parameters.
CGI class of Ruby can be used for writing CGI scripts. Please check: http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/index.html
By the way, there is no need to read the HTTP header. Parsing parametres will be easy using CGI class. Then, send the e-mail and redirect.
Has anyone got RadiantCMS with multi_site working on Heroku? I actually tried it and it bombed big-time giving the error:
Heroku | No such app
There is no app configured at that hostname.
Perhaps the app owner has renamed it, or you mistyped the URL.
This is what I tried:
Go to tractor.heroku.com and login using admin / radiant.
If you see the 'Sites' section, you will find Foo and Bar sites.
I edited my /etc/hosts files and added foo.myapp.com and bar.myapp.com to the IP address that resolves to tractor.heroku.com (Not entirely sure if this is right)
Now type the URL "http://foo.myapp.com" in the browser and it gives me the above error.
Is there some special configuration required to get this working on Heroku?
So, I finally did get an answer from heroku support themselves. Pasting it here for everyone's benefit:
reception said:
fyi if you want a 301 redirect from appname.heroku.com url to yourdomain.tld i succeeded with this steps:
freeze radiant (in order to be able to modify application_controller.rb; see http://wiki.github.com/radiant/radiant/running-on-edge )
add this code to application_controller.rb inside class ApplicationController:
---->8
before_filter :redirect_domain
def redirect_domain
if request.host == 'appname.heroku.com'
redirect_to "http://yourdomain.tld#{request.request_uri}", :status=>301
end
end
---->8
(big thanx to David from suppport!)
regards
D