Verify self-signed TLS certificate for HTTPS in Ruby - ruby

How do I use SSL certificate verification in GET Request in RUBY (using password parameter in URL)? ->
require 'net/https'
require 'uri'
uri = URI.parse(ARGV[0] || 'https://example.com?password=my_password')
http = Net::HTTP.new(uri.host, uri.port)
if uri.scheme == "https"
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.ca_file=File.join(File.dirname(__FILE__),
"/Users/me/Desktop/demp.pem")
end
http.start do
http.request_get(uri.path) do |res|
print res.body
end
end
--> output
SSL_connect returned=1 errno=0 state=error: certificate verify failed (self signed certificate in certificate chain) (OpenSSL::SSL::SSLError)

This worked for me.
require 'net/http'
require 'net/https'
require 'openssl'
require 'uri'
require 'json'
ContentURI = URI.parse("example.com")
#cert_raw = File.read('cert.pem')
TestDataPath = '.'
req = Net::HTTP::Get.new(ContentURI.path)
https = Net::HTTP.new(ContentURI.host, ContentURI.port)
https.use_ssl = true
https.cert = OpenSSL::X509::Certificate.new(#cert_raw)
https.key = OpenSSL::PKey::RSA.new(#cert_raw)
https.verify_mode = OpenSSL::SSL::VERIFY_PEER
resp = https.start { |cx| cx.request(req) }
p resp
p resp.body

Related

Https response time in ruby

I'm trying to get webservice response time using ruby. My code
require 'net/http'
require 'benchmark'
require 'uri'
puts time = Benchmark.realtime = {Net::HTTP.get_response(URI.parse("http://webservice"))}
It works fine but when I'm trying to get response time of https based url I get an error
'connect_nonblock': SSL_connect returned=1 errno=0 state=error: certificate verify faule
Is any way to fix this?
You should make request with enabled ssl:
uri = URI('https://secure.example.com/some_path?query=string')
Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
request = Net::HTTP::Get.new uri
response = http.request request # Net::HTTPResponse object
end

How to solve net http internal server error

I am passing xml data from an xml for post_xml to a web service which reads this data but am getting an error # my passing method is as below. What am I missing out or how shoul i go about it. Thank you
require 'net/http'
require 'open-uri'
pegPayStatusCode = ""
conn = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
if uri.scheme == 'https'
require 'net/https'
conn.use_ssl = true
conn.verify_mode = OpenSSL::SSL::VERIFY_NONE # needed for windows environment
end
#request.body=post_xml
request.set_form_data({"q" => "#{post_xml}", "per_page" => "50"})
response = conn.request(request)
pegPayStatusCode = response

uninitialized constant Net::HTTP::Patch (NameError)

I keep the error "/usr/local/bin/git_flow_tools.rb:55:in `set_issue': uninitialized constant Net::HTTP::Patch (NameError)"
I'm require this:
require 'rubygems'
require 'net/http'
require 'net/https'
require 'uri'
require 'timeout'
require 'json'
require 'pp'
This function fail:
def self.set_issue(user, repo, number, data)
uri = URI.parse('https://api.github.com')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == 'https'
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
path = URI.escape("/repos/#{user}/#{repo}/issues/#{number}")
req = Net::HTTP::Patch.new(path)
req['Content-Type'] = 'application/json'
req['Accept'] = 'application/json'
req['Authorization'] = 'token OAUTH-TOKEN'
req.body = data
begin
Timeout::timeout(30) { JSON.parse http.request(req).body }
rescue Exception => e
puts "Failed to contact github #{e}"
end
end
Other methods like Get, Put or Post works fine.
Any ideas?
try to add after requirements
class Net::HTTP::Patch < Net::HTTPRequest
METHOD = 'PATCH'
REQUEST_HAS_BODY = true
RESPONSE_HAS_BODY = true
end

Ruby https POST with headers

How can I make a Https post with a header in Ruby with a json?
I have tried:
uri = URI.parse("https://...")
https = Net::HTTP.new(uri.host,uri.port)
req = Net::HTTP::Post.new(uri.path)
req['foo'] = bar
res = https.request(req)
puts res.body
The problem it was a json. This solve my problem. Anyway, my question was not clear, so the bounty goes to Juri
require 'uri'
require 'net/http'
require 'net/https'
require 'json'
#toSend = {
"date" => "2012-07-02",
"aaaa" => "bbbbb",
"cccc" => "dddd"
}.to_json
uri = URI.parse("https:/...")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
req['foo'] = 'bar'
req.body = "[ #{#toSend} ]"
res = https.request(req)
puts "Response #{res.code} #{res.message}: #{res.body}"
Try:
require 'net/http'
require 'net/https'
uri = URI.parse("https://...")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path)
req['foo'] = bar
res = https.request(req)
puts res.body
Here's a cleaner way to use Net::HTTP. If you just want to get the response and throw other objects away this is quite useful.
require 'net/http'
require 'json'
uri = URI("https://example.com/path")
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
# The body needs to be a JSON string, use whatever you know to parse Hash to JSON
req.body = {a: 1}.to_json
http.request(req)
end
# The "res" is what you need, get content from "res.body". It's a JSON string too.
A secure-by-default example:
require 'net/http'
require 'net/https'
req = Net::HTTP::Post.new("/some/page.json", {'Content-Type' =>'application/json'})
req.body = your_post_body_json_or_whatever
http = Net::HTTP.new('www.example.com', 443)
http.use_ssl = true
http.ssl_version = :TLSv1 # ruby >= 2.0 supports :TLSv1_1 and :TLSv1_2.
# SSLv3 is broken at time of writing (POODLE), and it's old anyway.
http.verify_mode = OpenSSL::SSL::VERIFY_PEER # please don't use verify_none.
# if you want to verify a server is from a certain signing authority,
# (self-signed certs, for example), do this:
http.ca_file = 'my-signing-authority.crt'
response = http.start {|http| http.request(req) }
Its working, you can pass data and header like this:
header = {header part}
data = {"a"=> "123"}
uri = URI.parse("https://anyurl.com")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path, header)
req.body = data.to_json
res = https.request(req)
puts "Response #{res.code} #{res.message}: #{res.body}"

How to connect to an https server with an invalid certificate using the latest versions of Ruby

Consider the following code:
require 'net/https'
uri = URI.parse("https://host/index.html")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.path)
response = http.request(request)
where https://host/index.html is a valid address with an invalid certificate on the server.
On older versions of ruby (specifically 1.8.7-p334 and 1.9.2-p180) this code works fine. On all recent versions (1.8.7-p352, 1.9.2-p290 and 1.9.3-p0) it throws the following exception:
OpenSSL::SSL::SSLError: SSL_connect SYSCALL returned=5 errno=0 state=unknown state
on the last line.
Changing verify_mode to OpenSSL::SSL::VERIFY_PEER gives exactly the error suggesting it is attempting to verify the certificate in spite of the setting.
How can I convince ruby to ignore the invalid certificate and connect?
uri = URI("https://host/index.html")
req = Net::HTTP::Get.new(uri.path)
res = Net::HTTP.start(
uri.host, uri.port,
:use_ssl => uri.scheme == 'https',
:verify_mode => OpenSSL::SSL::VERIFY_NONE) do |https|
https.request(req)
end
require 'nokogiri'
require 'open-uri'
require 'net/https'
#doc = Nokogiri::HTML(open(my_url, :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE))

Resources