Skip to content

Instantly share code, notes, and snippets.

@pedro823
Created December 31, 2018 16:13
Show Gist options
  • Save pedro823/27d3031081f99c2405b5c148318f367e to your computer and use it in GitHub Desktop.
Save pedro823/27d3031081f99c2405b5c148318f367e to your computer and use it in GitHub Desktop.
require 'thread'
require 'socket'
require 'concurrent' # gem install concurrent-ruby
PASSWORD = 'GS2W_{P4ssw0RD_T1MinG_4TT4Ck!}'
ALPHABET = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
PORT = 9999
THROTTLE = Concurrent::Semaphore.new 5
def generate_id
ALPHABET.sample(8).join
end
def validate_password(password)
time_to_validade = 0
s_end = ''
valid = true
password.split('').each_with_index do |val, idx|
if val != PASSWORD[idx]
valid = false
break
end
time_to_validade += 0.05
sleep(0.05)
end
if password != PASSWORD
# Wrong length
return "false #{time_to_validade.round(2)}"
end
if valid
s_end = " The password is the flag."
end
"#{valid} #{time_to_validade.round(2)}" + s_end
end
def password_challenge(client)
id = generate_id
puts "client at #{client.remote_address.ip_address} id=#{id}"
unless THROTTLE.try_acquire(1, 1)
client.puts "Too many requests at the same time. Try again later!"
return
end
begin
client.write "Please input the password: "
password = client.readpartial(31).chomp
response = validate_password password
puts "id=#{id} password=#{password} response='#{response}'"
client.puts response
ensure
THROTTLE.release(1)
end
end
server = TCPServer.new PORT
loop do
Thread.new(server.accept) do |client|
password_challenge client
client.close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment