From 65a903181cd5cdd78b4df7eacc1c574f0ef8e95c Mon Sep 17 00:00:00 2001 From: Eric Wong Date: Sat, 29 Nov 2014 04:08:54 +0000 Subject: initial cut at OpenSSL support The current CA model and code quality of OpenSSL have long put me off from supporting TLS; however but efforts such as "Let's Encrypt" and the fallout from Heartbleed give me hope for the future. This implements, as much as possible, a "hands-off" approach to TLS support via OpenSSL. This implementation allows us to shift responsibility away from us to users and upstreams (the Ruby 'openssl' extension maintainers, software packagers, and OpenSSL project itself). This is also perhaps the easiest way for now for us, while being most powerful for users. It requires users to configure their own OpenSSL context object which we'll use as-is. This context object is used as the :ssl_ctx parameter to the "listen" directive in the yahns configuration file: require 'openssl' # we will not do this for the user, even ctx = OpenSSL::SSL::SSLContext.new # user must configure ctx here... listen 443, ssl_ctx: ctx This way, in case we support GnuTLS or other TLS libraries, there'll be less confusion as to what a user is actually using. Note: this feature requires Ruby 2.1 and later for non-kgio {read,write}_nonblock(.. exception: false) support. --- lib/yahns/socket_helper.rb | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) (limited to 'lib/yahns/socket_helper.rb') diff --git a/lib/yahns/socket_helper.rb b/lib/yahns/socket_helper.rb index 6e1830f..66df8b0 100644 --- a/lib/yahns/socket_helper.rb +++ b/lib/yahns/socket_helper.rb @@ -16,7 +16,7 @@ module Yahns::SocketHelper # :nodoc: end def set_server_sockopt(sock, opt) - opt = {backlog: 1024}.merge!(opt || {}) + opt = {backlog: 1024}.merge!(opt) sock.close_on_exec = true TCPSocket === sock and sock.setsockopt(:IPPROTO_TCP, :TCP_NODELAY, 1) @@ -97,7 +97,12 @@ module Yahns::SocketHelper # :nodoc: sock.bind(Socket.pack_sockaddr_in(port, addr)) sock.autoclose = false - Yahns::TCPServer.for_fd(sock.fileno) + + if ssl_ctx = opt[:ssl_ctx] + Yahns::OpenSSLServer.wrap(sock.fileno, ssl_ctx) + else + Yahns::TCPServer.for_fd(sock.fileno) + end end # returns rfc2732-style (e.g. "[::1]:666") addresses for IPv6 @@ -128,11 +133,15 @@ module Yahns::SocketHelper # :nodoc: end # casts a given Socket to be a TCPServer or UNIXServer - def server_cast(sock) + def server_cast(sock, opts) sock.autoclose = false begin Socket.unpack_sockaddr_in(sock.getsockname) - Yahns::TCPServer.for_fd(sock.fileno) + if ssl_ctx = opts[:ssl_ctx] + Yahns::OpenSSLServer.wrap(sock.fileno, ssl_ctx) + else + Yahns::TCPServer.for_fd(sock.fileno) + end rescue ArgumentError Yahns::UNIXServer.for_fd(sock.fileno) end -- cgit v1.2.3-24-ge0c7