Created
July 11, 2018 08:19
-
-
Save Timbus/83b10bcf34ae545db3ccc2022efd038e to your computer and use it in GitHub Desktop.
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 "openssl" | |
require "socket" | |
server = TCPServer.new("localhost", 3900) | |
certfile = "cert.pem" | |
keyfile = "key.pem" | |
unless File.exists?(certfile) && File.exists?(keyfile) | |
openssl_params = [ | |
"req", "-newkey", "rsa:2048", "-nodes", "-keyout", keyfile, "-x509", | |
"-days", "365", "-batch", "-out", certfile, | |
] | |
puts "openssl #{openssl_params.join(" ")}" | |
unless Process.run("openssl", openssl_params).success? | |
abort "Cert generation failed" | |
end | |
end | |
dh_file = "dhfile.pem" | |
unless File.exists?(dh_file) | |
puts "No dh_file.. this will take a short while" | |
unless Process.run("openssl", %w[dhparam -out dhfile.pem 2048]).success? | |
abort "dh file generation failed" | |
end | |
end | |
context = OpenSSL::SSL::Context::Server.new(LibSSL.tlsv1_2_method) | |
context.ciphers = "DHE-RSA-AES128-GCM-SHA256" | |
context.certificate_chain = certfile | |
context.private_key = keyfile | |
# # We need a 'FILE*' for libssl. I use fopen to obtain one since I dunno if crystal has them | |
lib LibC | |
alias File = Void | |
fun fopen(file : Char*, modes : Char*) : File* | |
fun fclose(fp : File*) | |
end | |
lib LibSSL | |
SSL_CTRL_SET_TMP_DH = 3 | |
fun read_dh_params = PEM_read_DHparams(fp : Void*, dh : Void**, cb : Void*, u : Void*) : Void* | |
end | |
dh_file_handle = LibC.fopen(dh_file, "r") | |
dh = LibSSL.read_dh_params(dh_file_handle, nil, nil, nil) | |
LibC.fclose(dh_file_handle) | |
LibSSL.ssl_ctx_ctrl(context.to_unsafe, LibSSL::SSL_CTRL_SET_TMP_DH, 0, dh) | |
spawn do | |
puts "Starting server" | |
while client = server.accept | |
puts "Client connected" | |
OpenSSL::SSL::Socket::Server.open(client, context) do |socket| | |
puts "TLS Established" | |
socket.puts("Hi there!") | |
end | |
end | |
end | |
sleep 1 | |
puts "Starting client" | |
system("openssl", ["s_client", "-connect", "localhost:3900", "-tls1_2"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment