123456789_123456789_123456789_123456789_123456789_

Class: Mongo::Socket::SSL Private

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Instance Chain:
self, OpenSSL, ::Mongo::Socket, Socket::Constants
Inherits: Mongo::Socket
Defined in: lib/mongo/socket/ssl.rb

Overview

Wrapper for TLS sockets.

Since:

  • 2.0.0

Constant Summary

::Mongo::Socket - Inherited

DEFAULT_TCP_KEEPCNT, DEFAULT_TCP_KEEPIDLE, DEFAULT_TCP_KEEPINTVL, DEFAULT_TCP_USER_TIMEOUT, SSL_ERROR, TIMEOUT_ERROR, TIMEOUT_PACK, WRITE_CHUNK_SIZE

Class Method Summary

::Mongo::Socket - Inherited

.new

Initializes common socket attributes.

Instance Attribute Summary

::Mongo::Socket - Inherited

#alive?

Is the socket connection alive?

#connectable?

For backwards compatibility only, do not use.

#eof?

Tests if this socket has reached EOF.

#family, #monitor?, #options, #socket, #timeout

Instance Method Summary

::Mongo::Socket - Inherited

#close

Close the socket.

#connection_address, #connection_generation,
#gets

Delegates gets to the underlying socket.

#read

Will read all data from the socket for the provided number of bytes.

#readbyte

Read a single byte from the socket.

#summary,
#write

Writes data to the socket instance.

#allocate_string,
#do_write

Writes data to the socket instance.

#human_address, #map_exceptions, #raise_timeout_error!, #read_buffer_size,
#read_from_socket

Reads the length bytes from the socket.

#read_with_timeout

Reads the length bytes from the socket, the read operation duration is limited to #timeout second.

#read_without_timeout

Reads the length bytes from the socket.

#set_keepalive_opts, #set_option, #set_socket_options, #unix_socket?, #write_chunk,
#write_with_timeout

Writes data to to the socket, the write duration is limited to #timeout.

#write_without_timeout

Writes data to to the socket.

Instance Attribute Details

#contextSSLContext (readonly)

Returns:

  • (SSLContext)

    context The TLS context.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 122

attr_reader :context

#hostString (readonly)

Returns:

  • (String)

    host The host to connect to.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 125

attr_reader :host

#host_nameString (readonly)

Returns:

  • (String)

    host_name The original host name.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 128

attr_reader :host_name

#portInteger (readonly)

Returns:

  • (Integer)

    port The port to connect to.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 131

attr_reader :port

#verify_certificate?Boolean (readonly, private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 277

def verify_certificate?
  # If ssl_verify_certificate is not present, disable only if
  # ssl_verify is explicitly set to false.
  if options[:ssl_verify_certificate].nil?
    options[:ssl_verify] != false
  # If ssl_verify_certificate is present, enable or disable based on its value.
  else
    !!options[:ssl_verify_certificate]
  end
end

#verify_hostname?Boolean (readonly, private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 288

def verify_hostname?
  # If ssl_verify_hostname is not present, disable only if ssl_verify is
  # explicitly set to false.
  if options[:ssl_verify_hostname].nil?
    options[:ssl_verify] != false
  # If ssl_verify_hostname is present, enable or disable based on its value.
  else
    !!options[:ssl_verify_hostname]
  end
end

#verify_ocsp_endpoint?Boolean (readonly, private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 299

def verify_ocsp_endpoint?
  if !options[:ssl_verify_ocsp_endpoint].nil?
    options[:ssl_verify_ocsp_endpoint] != false
  elsif !options[:ssl_verify_certificate].nil?
    options[:ssl_verify_certificate] != false
  else
    options[:ssl_verify] != false
  end
end

Instance Method Details

#connect!SSL (private)

Note:

This method mutates the object by setting the socket internally.

Establishes a socket connection.

Examples:

Connect the socket.

sock.connect!

Returns:

  • (SSL)

    The connected socket instance.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 144

def connect!
  sockaddr = ::Socket.pack_sockaddr_in(port, host)
  connect_timeout = options[:connect_timeout]
  map_exceptions do
    if connect_timeout && connect_timeout != 0
      deadline = Utils.monotonic_time + connect_timeout
      if BSON::Environment.jruby?
        # We encounter some strange problems with connect_nonblock for
        # ssl sockets on JRuby. Therefore, we use the old +Timeout.timeout+
        # solution, even though it is known to be not very reliable.
        raise Error::SocketTimeoutError, 'connect_timeout expired' if connect_timeout < 0

        Timeout.timeout(connect_timeout, Error::SocketTimeoutError, "The socket took over #{options[:connect_timeout]} seconds to connect") do
          connect_without_timeout(sockaddr)
        end
      else
        connect_with_timeout(sockaddr, connect_timeout)
      end
      remaining_timeout = deadline - Utils.monotonic_time
      verify_certificate!(@socket)
      verify_ocsp_endpoint!(@socket, remaining_timeout)
    else
      connect_without_timeout(sockaddr)
      verify_certificate!(@socket)
      verify_ocsp_endpoint!(@socket)
    end
  end
  self
rescue
  @socket&.close
  @socket = nil
  raise
end

#connect_tcp_socket_with_timeout(sockaddr, deadline, connect_timeout) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 221

def connect_tcp_socket_with_timeout(sockaddr, deadline, connect_timeout)
  if deadline <= Utils.monotonic_time
    raise Error::SocketTimeoutError, "The socket took over #{connect_timeout} seconds to connect"
  end
  begin
    @tcp_socket.connect_nonblock(sockaddr)
  rescue IO::WaitWritable
    with_select_timeout(deadline, connect_timeout) do |select_timeout|
      IO.select(nil, [@tcp_socket], nil, select_timeout)
    end
    retry
  rescue Errno::EISCONN
    # Socket is connected, nothing to do.
  end
end

#connect_with_timeout(sockaddr, connect_timeout) (private)

Connects the socket with the connect timeout. The timeout applies to connecting both ssl socket and the underlying tcp socket.

Parameters:

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 211

def connect_with_timeout(sockaddr, connect_timeout)
  if connect_timeout <= 0
    raise Error::SocketTimeoutError, "The socket took over #{connect_timeout} seconds to connect"
  end

  deadline = Utils.monotonic_time + connect_timeout
  connect_tcp_socket_with_timeout(sockaddr, deadline, connect_timeout)
  connnect_ssl_socket_with_timeout(deadline, connect_timeout)
end

#connect_without_timeout(sockaddr) (private)

Connects the socket without a timeout provided.

Parameters:

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 199

def connect_without_timeout(sockaddr)
  @tcp_socket.connect(sockaddr)
  @socket = OpenSSL::SSL::SSLSocket.new(@tcp_socket, context)
  @socket.hostname = @host_name
  @socket.sync_close = true
  @socket.connect
end

#connnect_ssl_socket_with_timeout(deadline, connect_timeout) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 237

def connnect_ssl_socket_with_timeout(deadline, connect_timeout)
  if deadline <= Utils.monotonic_time
    raise Error::SocketTimeoutError, "The socket took over #{connect_timeout} seconds to connect"
  end
  @socket = OpenSSL::SSL::SSLSocket.new(@tcp_socket, context)
  @socket.hostname = @host_name
  @socket.sync_close = true

  # We still have time, connecting ssl socket.
  begin
    @socket.connect_nonblock
  rescue IO::WaitReadable, OpenSSL::SSL::SSLErrorWaitReadable
    with_select_timeout(deadline, connect_timeout) do |select_timeout|
      IO.select([@socket], nil, nil, select_timeout)
    end
    retry
  rescue IO::WaitWritable, OpenSSL::SSL::SSLErrorWaitWritable
    with_select_timeout(deadline, connect_timeout) do |select_timeout|
      IO.select(nil, [@socket], nil, select_timeout)
    end
    retry
  rescue Errno::EISCONN
    # Socket is connected, nothing to do
  end
end

#create_context(options) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 309

def create_context(options)
  OpenSSL::SSL::SSLContext.new.tap do |context|
    if OpenSSL::SSL.const_defined?(:OP_NO_RENEGOTIATION)
      context.options = context.options | OpenSSL::SSL::OP_NO_RENEGOTIATION
    end

    if context.respond_to?(:renegotiation_cb=)
      # Disable renegotiation for older Ruby versions per the sample code at
      # https://rubydocs.org/d/ruby-2-6-0/classes/OpenSSL/SSL/SSLContext.html
      # In JRuby we must allow one call as this callback is invoked for
      # the initial connection also, not just for renegotiations -
      # https://github.com/jruby/jruby-openssl/issues/180
      if BSON::Environment.jruby?
        allowed_calls = 1
      else
        allowed_calls = 0
      end
      context.renegotiation_cb = lambda do |ssl|
        if allowed_calls <= 0
          raise RuntimeError, 'Client renegotiation disabled'
        end
        allowed_calls -= 1
      end
    end

    set_cert(context, options)
    set_key(context, options)

    if verify_certificate?
      context.verify_mode = OpenSSL::SSL::VERIFY_PEER
      set_cert_verification(context, options)
    else
      context.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end

    if context.respond_to?(:verify_hostname=)
      # We manually check the hostname after the connection is established if necessary, so
      # we disable it here in order to give consistent errors across Ruby versions which
      # don't support hostname verification at the time of the handshake.
      context.verify_hostname = OpenSSL::SSL::VERIFY_NONE
    end
  end
end

#extract_certs(text) (private)

This was originally a scan + regex, but the regex was particularly inefficient and was flagged as a concern by static analysis.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 491

def extract_certs(text)
  [].tap do |list|
    pos = 0

    while (begin_idx = text.index(BEGIN_CERT, pos))
      end_idx = text.index(END_CERT, begin_idx)
      break unless end_idx

      end_idx += END_CERT.length
      list.push(text[begin_idx...end_idx])

      pos = end_idx
    end
  end
end

#human_address (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 476

def human_address
  "#{host}:#{port} (#{host_name}:#{port}, TLS)"
end

#load_private_key(text, passphrase) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 412

def load_private_key(text, passphrase)
  args = if passphrase
    [text, passphrase]
  else
    [text]
  end
  # On JRuby, PKey.read does not grok cert+key bundles.
  # https://github.com/jruby/jruby-openssl/issues/176
  if BSON::Environment.jruby?
    [OpenSSL::PKey::RSA, OpenSSL::PKey::DSA].each do |cls|
      begin
        return cls.send(:new, *args)
      rescue OpenSSL::PKey::PKeyError
        # ignore
      end
    end
    # Neither RSA nor DSA worked, fall through to trying PKey
  end
  OpenSSL::PKey.send(:read, *args)
end

#read_buffer_size (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 470

def read_buffer_size
  # Buffer size for TLS reads.
  # Capped at 16k due to https://linux.die.net/man/3/ssl_read
  16384
end

#readbyteObject

Read a single byte from the socket.

Examples:

Read a single byte.

socket.readbyte

Returns:

  • (Object)

    The read byte.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 187

def readbyte
  map_exceptions do
    byte = socket.read(1).bytes.to_a[0]
    byte.nil? ? raise(EOFError) : byte
  end
end

#run_tls_context_hooks (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 480

def run_tls_context_hooks
  Mongo.tls_context_hooks.each do |hook|
    hook.call(@context)
  end
end

#set_cert(context, options) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 353

def set_cert(context, options)
  # Since we clear cert_text during processing, we need to examine
  # ssl_cert_object here to avoid considering it if we have also
  # processed the text.
  if options[:ssl_cert]
    cert_text = File.read(options[:ssl_cert])
    cert_object = nil
  elsif cert_text = options[:ssl_cert_string]
    cert_object = nil
  else
    cert_object = options[:ssl_cert_object]
  end

  # The client certificate may be a single certificate or a bundle
  # (client certificate followed by intermediate certificates).
  # The text may also include private keys for the certificates.
  # OpenSSL supports passing the entire bundle as a certificate chain
  # to the context via SSL_CTX_use_certificate_chain_file, but the
  # Ruby openssl extension does not currently expose this functionality
  # per https://github.com/ruby/openssl/issues/254.
  # Therefore, extract the individual certificates from the certificate
  # text, and if there is more than one certificate provided, use
  # extra_chain_cert option to add the intermediate ones. This
  # implementation is modeled after
  # https://github.com/venuenext/ruby-kafka/commit/9495f5daf254b43bc88062acad9359c5f32cb8b5.
  # Note that the parsing here is not identical to what OpenSSL employs -
  # for instance, if there is no newline between two certificates
  # this code will extract them both but OpenSSL fails in this situation.
  if cert_text
    certs = extract_certs(cert_text)
    if certs.length > 1
      context.cert = OpenSSL::X509::Certificate.new(certs.shift)
      context.extra_chain_cert = certs.map do |cert|
        OpenSSL::X509::Certificate.new(cert)
      end
      # All certificates are already added to the context, skip adding
      # them again below.
      cert_text = nil
    end
  end

  if cert_text
    context.cert = OpenSSL::X509::Certificate.new(cert_text)
  elsif cert_object
    context.cert = cert_object
  end
end

#set_cert_verification(context, options) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 433

def set_cert_verification(context, options)
  context.verify_mode = OpenSSL::SSL::VERIFY_PEER
  cert_store = OpenSSL::X509::Store.new
  if options[:ssl_ca_cert]
    cert_store.add_file(options[:ssl_ca_cert])
  elsif options[:ssl_ca_cert_string]
    cert_store.add_cert(OpenSSL::X509::Certificate.new(options[:ssl_ca_cert_string]))
  elsif options[:ssl_ca_cert_object]
    raise TypeError("Option :ssl_ca_cert_object should be an array of OpenSSL::X509:Certificate objects") unless options[:ssl_ca_cert_object].is_a? Array
    options[:ssl_ca_cert_object].each {|cert| cert_store.add_cert(cert)}
  else
    cert_store.set_default_paths
  end
  context.cert_store = cert_store
end

#set_key(context, options) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 401

def set_key(context, options)
  passphrase = options[:ssl_key_pass_phrase]
  if options[:ssl_key]
    context.key = load_private_key(File.read(options[:ssl_key]), passphrase)
  elsif options[:ssl_key_string]
    context.key = load_private_key(options[:ssl_key_string], passphrase)
  elsif options[:ssl_key_object]
    context.key = options[:ssl_key_object]
  end
end

#verify_certificate!(socket) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 449

def verify_certificate!(socket)
  if verify_hostname?
    unless OpenSSL::SSL.verify_certificate_identity(socket.peer_cert, host_name)
      raise Error::SocketError, 'TLS handshake failed due to a hostname mismatch.'
    end
  end
end

#verify_ocsp_endpoint!(socket, timeout = nil) (private)

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 457

def verify_ocsp_endpoint!(socket, timeout = nil)
  unless verify_ocsp_endpoint?
    return
  end

  cert = socket.peer_cert
  ca_cert = socket.peer_cert_chain.last

  verifier = OcspVerifier.new(@host_name, cert, ca_cert, context.cert_store,
    **Utils.shallow_symbolize_keys(options).merge(timeout: timeout))
  verifier.verify_with_cache
end

#with_select_timeout(deadline, connect_timeout, &block) (private)

Raises ::Mongo::Error::SocketTimeoutError exception if deadline reached or the block returns nil. The block should call IO.select with the connect_timeout value. It returns nil if the connect_timeout expires.

Since:

  • 2.0.0

[ GitHub ]

  
# File 'lib/mongo/socket/ssl.rb', line 266

def with_select_timeout(deadline, connect_timeout, &block)
  select_timeout = deadline - Utils.monotonic_time
  if select_timeout <= 0
    raise Error::SocketTimeoutError, "The socket took over #{connect_timeout} seconds to connect"
  end
  rv = block.call(select_timeout)
  if rv.nil?
    raise Error::SocketTimeoutError, "The socket took over #{connect_timeout} seconds to connect"
  end
end