kgio-monkey.git  about / heads / tags
kinder, gentler SSL/TLS I/O for Ruby
blob 92ab881d7d3711bbda1e023fa2336dc4154294f2 9337 bytes (raw)
$ git show HEAD:lib/flipper.rb	# shows this blob on the CLI

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
 
# -*- encoding: binary -*-
require "kgio/monkey"

# This is a library for an experimental SSL proxy similar to
# {stunnel}[http://stunnel.org/] or {stud}[git://github.com/bumptech/stud].
# It does not use threads internally and uses as little memory as
# possible. It supports both client and server proxies in a single event
# loop and allows multiple event loops to be used.
#
# It is intended as a demo and testbed of kgio-monkey functionality,
# but maybe useful in production.  It only supports TCP <-> TCP
# connections.
#
# Most of Flipper is undocumented and the API is subject to change.
module Flipper
  autoload :SSLAccepted, "flipper/ssl_accepted"
  autoload :SSLUpstream, "flipper/ssl_upstream"
  autoload :Poller, "flipper/poller"
  autoload :FakePoll, "flipper/fake_poll"
  autoload :Configurator, "flipper/configurator"
  autoload :SNI, "flipper/sni"
  autoload :TDBSessionCache, "flipper/tdb_session_cache"
  autoload :MemcacheCommon, "flipper/memcache_common"
  autoload :DalliSessionCache, "flipper/dalli_session_cache"
  autoload :MemcachedSessionCache, "flipper/memcached_session_cache"

  @proto_user = { :SSLv2 => 2, :SSLv3 => 4, :TLSv1 => 8 }
  @proto_map = [
    OpenSSL::SSL::OP_NO_SSLv2 |
      OpenSSL::SSL::OP_NO_SSLv3 |
      OpenSSL::SSL::OP_NO_TLSv1,
    OpenSSL::SSL::OP_NO_SSLv3|OpenSSL::SSL::OP_NO_TLSv1,
    OpenSSL::SSL::OP_NO_SSLv2|OpenSSL::SSL::OP_NO_TLSv1,
    OpenSSL::SSL::OP_NO_TLSv1,
    OpenSSL::SSL::OP_NO_SSLv2|OpenSSL::SSL::OP_NO_SSLv3,
    OpenSSL::SSL::OP_NO_SSLv3,
    OpenSSL::SSL::OP_NO_SSLv2
  ]

  # we try to emulate the nginx configuration format/terminology as much
  # as possible to make it easy for users to learn.
  # ref: http://wiki.nginx.org/NginxHttpSslModule
  def self.ssl_context(opts)
    ctx = OpenSSL::SSL::SSLContext.new
    params = {
      :options => OpenSSL::SSL::OP_ALL,
      :session_id_context => "kgio",
    }
    monkey_opts = {
      # same default ecdh curve as nginx (as of r3961)
      :ssl_ecdh_curve => opts[:ssl_ecdh_curve] || "prime256v1",
    }

    tmp = opts[:ssl_certificate] and
      monkey_opts[:ssl_certificate] = File.expand_path(tmp)
    tmp = opts[:ssl_certificate_key] and
      monkey_opts[:ssl_certificate_key] = File.expand_path(tmp)

    tmp = opts[:ssl_version] and params[:ssl_version] = tmp
    tmp = opts[:ssl_ciphers] and params[:ciphers] = tmp
    tmp = opts[:ssl_verify_depth] and params[:verify_depth] = tmp
    tmp = opts[:ssl_session_timeout] and params[:timeout] = tmp
    tmp = opts[:ssl_ca_file] and params[:ca_file] = File.expand_path(tmp)

    if tmp = opts[:ssl_client_certificate]
      params[:verify_mode] = OpenSSL::SSL::VERIFY_PEER
      tmp = params[:ca_file] = File.expand_path(tmp)
      # load names
      params[:client_ca] = Kgio::SSL.split_pem(OpenSSL::X509::Certificate, tmp)
    end

    case tmp = opts[:ssl_verify_mode]
    when Array
      params[:verify_mode] = tmp.inject(0) do |mode,f|
        mode |= OpenSSL::SSL.const_get("VERIFY_#{f.to_s.upcase}")
      end
    when String, Symbol
      params[:verify_mode] = OpenSSL::SSL.const_get("VERIFY_#{tmp.to_s.upcase}")
    when Integer
      params[:verify_mode] = tmp
    end

    if tmp = opts[:ssl_client]
      params[:verify_mode] = OpenSSL::SSL::VERIFY_PEER
      tmp = opts[:ssl_ca_path] and params[:ca_path] = File.expand_path(tmp)
    else # server mode:
      # nginx defaults:
      params[:ciphers] ||= "HIGH:!aNULL:!MD5" # ref: nginx 1.0.5
      params[:verify_depth] ||= 1 if opts[:ssl_client_certificate]

      if tmp = opts[:ssl_verify_client]
        opts[:ssl_verify_mode] and
          raise ArgumentError,
                ":ssl_verify_mode and :ssl_verify_client are incompatible"
        params[:verify_mode] = case tmp
        when "on", true, :on
          OpenSSL::SSL::VERIFY_PEER |
            OpenSSL::SSL::VERIFY_FAIL_IF_NO_PEER_CERT |
            OpenSSL::SSL::VERIFY_CLIENT_ONCE
        when "off", false, :off
          OpenSSL::SSL::VERIFY_NONE
        when "optional", :optional
          OpenSSL::SSL::VERIFY_PEER
        else
          tmp = tmp.inspect
          raise ArgumentError, ":ssl_verify_client=#{tmp} " \
                               "must be one of: 'on', 'off', or 'optional'"
        end
      end
    end

    if tmp = opts[:ssl_dhparam]
      dhparam = OpenSSL::PKey::DH.new(IO.read(File.expand_path(tmp)))
      ctx.tmp_dh_callback = __dhparam_proc(dhparam)
    end

    opts[:ssl_prefer_server_ciphers] and
      params[:options] |= OpenSSL::SSL::OP_CIPHER_SERVER_PREFERENCE

    if opts[:ssl_no_compression]
      # ref: http://redmine.ruby-lang.org/issues/5183
      if defined?(Kgio::SSL::OP_NO_COMPRESSION)
        params[:options] |= Kgio::SSL::OP_NO_COMPRESSION
      else
        warn ":ssl_no_compression not supported per-context with old OpenSSL"
        warn "disabling OpenSSL compression globally"
        Kgio::SSL.compression = false
      end
    end

    # map an array of symbols (in @proto_user)
    if tmp = opts[:ssl_protocols]
      proto = Array(tmp).inject(0) do |m,k|
        flag = @proto_user[k.to_sym] or raise ArgumentError,
                       "#{k.inspect} not one of #{@proto_user.keys.inspect}"
        m |= flag
      end
      op = @proto_map[proto >> 1] and params[:options] |= op
    end

    ctx.set_params(params)

    if tmp = opts[:sni_hostnames]
      sni = opts[:flipper_sni] || Flipper::SNI.new
      Array(tmp).each { |h| sni.register(h, ctx) }
      ctx.servername_cb = sni.servername_cb
    end

    opts.key?(:ssl_session_cache) and
      __setup_cache(ctx, opts[:ssl_session_cache])

    Kgio::Monkey!(ctx, monkey_opts)
    if tmp = opts[:ssl_crl]
      store = ctx.cert_store or raise ArgumentError, "cert_store required"
      store.add_file(tmp)
    end
    ctx
  end

  def self.__dhparam_proc(dhparam) # :nodoc:
    proc { dhparam }
  end

  def self.__setup_cache(ctx, tmp) # :nodoc:
    cCTX = OpenSSL::SSL::SSLContext
    case tmp
    when false
      ctx.session_cache_mode = cCTX::SESSION_CACHE_OFF
    when nil # soft off, some mail clients may require it
      ctx.session_cache_mode = cCTX::SESSION_CACHE_SERVER |
                               cCTX::SESSION_CACHE_NO_AUTO_CLEAR |
                               cCTX::SESSION_CACHE_NO_INTERNAL_STORE
      ctx.session_cache_size = 1 # 0 is unlimited
    else
      ctx.session_cache_mode = cCTX::SESSION_CACHE_SERVER
      tmp = [ tmp ] if String === tmp || (Array === tmp && Symbol === tmp[0])
      caches = tmp.map { |cache| parse_cache_directive(ctx, cache) }
      caches.compact! or # compact! returns nil unless builtin:\d+ is present
        ctx.session_cache_mode |= cCTX::SESSION_CACHE_NO_INTERNAL_STORE
      if caches.size > 0 && RUBY_VERSION <= "1.9.2"
        warn("The OpenSSL Ruby extension does not properly support " \
             "external caches in Ruby <= 1.9.3")
        return
      end
      if caches.size == 1
        %w(session_new_cb session_remove_cb session_get_cb).each do |m|
          ctx.__send__("#{m}=", caches[0].__send__(m))
        end
      else
        __assign_caches(ctx, caches)
      end
    end
  end

  def self.parse_cache_directive(ctx, cache) # :nodoc:
    case cache
    when /\Abuiltin:(\d+)\z/
      ctx.session_cache_size = $1.to_i
      nil # causes caches.compact! to return the array
    when /\Atdb:(\d+)\z/
      Flipper::TDBSessionCache.new(nil, $1.to_i)
    when /\Atdb:(.+):(\d+)\z/
      Flipper::TDBSessionCache.new($1, $2.to_i)
    when /\Adalli:\[(.+)\]\z/
      servers = $1.split(/\s*,\s*/)
      opts = {}
      opts[:expires_in] = ctx.timeout if ctx.timeout && ctx.timeout > 0
      Flipper::DalliSessionCache.new(servers, opts)
    when /\Amemcached:\[(.+)\]\z/
      servers = $1.split(/\s*,\s*/)
      opts = {}
      opts[:default_ttl] = ctx.timeout if ctx.timeout && ctx.timeout > 0
      Flipper::MemcachedSessionCache.new(servers, opts)
    when Array
      case cache[0]
      when :dalli
        servers, opts = cache[1], cache[2] || {}
        opts[:expires_in] ||= ctx.timeout if ctx.timeout && ctx.timeout > 0
        Flipper::DalliSessionCache.new(servers, opts)
      when :memcached
        servers, opts = cache[1], cache[2] || {}
        opts[:default_ttl] ||= ctx.timeout if ctx.timeout && ctx.timeout > 0
        Flipper::MemcachedSessionCache.new(servers, opts)
      else
        raise ArgumentError, "unknown cache directive: #{cache.inspect}"
      end
    else
      raise ArgumentError, "unknown cache directive: #{cache.inspect}"
    end
  end

  def self.session_get_cb(callbacks) # :nodoc:
    lambda do |a|
      callbacks.each { |c| sess = c.call(a) and return sess }
    end
  end

  def self.session_new_cb(callbacks) # :nodoc:
    lambda do |a|
      callbacks.each { |c| c.call(a) }
    end
  end

  def self.session_remove_cb(callbacks) # :nodoc:
    lambda do |a|
      rv = nil
      callbacks.each do |c|
        c = c.call(a)
        rv ||= c
      end
      rv
    end
  end

  def self.__assign_caches(ctx, caches) # :nodoc:
    ctx.session_get_cb = session_get_cb(caches.map { |c| c.session_get_cb })
    ctx.session_new_cb = session_new_cb(caches.map { |c| c.session_new_cb })
    caches.map! { |c| c.session_remove_cb }
    ctx.session_remove_cb = session_remove_cb(caches)
  end
end
require "flipper/base"
require "flipper/socket"
require "flipper/tcp_proxy"

git clone https://yhbt.net/kgio-monkey.git