Created
April 6, 2017 14:19
-
-
Save ploubser/008893637ce30ffc2fbcdf7f3c8154d0 to your computer and use it in GitHub Desktop.
Port malarkey
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'socket' | |
require 'openssl' | |
def is_ssl_enabled?(tcp_socket) | |
ctx = OpenSSL::SSL::SSLContext.new | |
ctx.set_params({ :options=>OpenSSL::SSL::OP_ALL }) | |
ctx.verify_mode = OpenSSL::SSL::VERIFY_NONE | |
enabled = true | |
OpenSSL::SSL::SSLSocket.new(tcp_socket, ctx).tap do |socket| | |
begin | |
socket.sync_close = true | |
socket.connect_nonblock | |
rescue IO::WaitReadable | |
if IO.select([socket], nil, nil, 1) | |
retry | |
else | |
enabled = false | |
end | |
rescue IO::WaitWritable | |
if IO.select([socket], nil, nil, 1) | |
retry | |
else | |
enabled = false | |
end | |
rescue OpenSSL::SSL::SSLError | |
enabled = false | |
end | |
return enabled | |
end | |
end | |
def connect_to_port(port) | |
begin | |
TCPSocket.new('0.0.0.0', port) | |
rescue Errno::ECONNREFUSED | |
nil | |
end | |
end | |
def get_port_state(port) | |
state = { :open => false, | |
:ssl => "unkown" } | |
tcp_socket = connect_to_port(port) | |
return state unless tcp_socket # couldn't connect, can't figure anything out | |
state[:open] = true | |
state[:ssl] = is_ssl_enabled?(tcp_socket) | |
tcp_socket.close | |
state | |
end | |
def combine_port_states(states) | |
states.reduce({}) do |old_state, state| | |
old_state[:open] ||= state[:open] | |
old_state[:ssl] ||= state[:ssl] | |
old_state[:open] &&= state[:open] | |
old_state[:ssl] &&= state[:open] | |
old_state | |
end | |
end | |
enable_extension(:port) do |port| | |
resource = Puppet::Resource.new('ssl', port.to_s) | |
state = {} | |
if port =~ /^(\d+)-(\d+)$/ | |
port_states = [] | |
threads = [] # god help us all | |
($1.to_i..$2.to_i).to_a.each do |p| | |
threads << Thread.new do | |
port_states << get_port_state(p) | |
end | |
end | |
threads.each do |t| | |
t.join | |
end | |
state = combine_port_states(port_states) | |
else | |
state = get_port_state(port) | |
end | |
# add the state keys to the resource | |
state.each do |key, val| | |
resource[key] = val | |
end | |
resource | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment