Class: Net::SSH::Transport::Session

Inherits:
Object
  • Object
show all
Includes:
Loggable, Constants
Defined in:
lib/net/ssh/transport/session.rb

Overview

The transport layer represents the lowest level of the SSH protocol, and implements basic message exchanging and protocol initialization. It will never be instantiated directly (unless you really know what you’re about), but will instead be created for you automatically when you create a new SSH session via Net::SSH.start.

Constant Summary collapse

DEFAULT_PORT =

The standard port for the SSH protocol.

22

Constants included from Constants

Constants::DEBUG, Constants::DISCONNECT, Constants::IGNORE, Constants::KEXDH_INIT, Constants::KEXDH_REPLY, Constants::KEXINIT, Constants::NEWKEYS, Constants::SERVICE_ACCEPT, Constants::SERVICE_REQUEST, Constants::UNIMPLEMENTED

Instance Attribute Summary collapse

Attributes included from Loggable

#logger

Instance Method Summary collapse

Methods included from Loggable

#debug, #error, #fatal, #info, #lwarn

Constructor Details

#initialize(host, options = {}) ⇒ Session

Instantiates a new transport layer abstraction. This will block until the initial key exchange completes, leaving you with a ready-to-use transport session.



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
# File 'lib/net/ssh/transport/session.rb', line 56

def initialize(host, options={})
  self.logger = options[:logger]

  @host = host
  @port = options[:port] || DEFAULT_PORT
  @bind_address = options[:bind_address] || nil
  @options = options

  debug { "establishing connection to #{@host}:#{@port}" }
  factory = options[:proxy] || TCPSocket
  @socket = timeout(options[:timeout] || 0) { @bind_address.nil? || options[:proxy] ? factory.open(@host, @port) : factory.open(@host,@port,@bind_address) }
  @socket.extend(PacketStream)
  @socket.logger = @logger

  debug { "connection established" }

  @queue = []

  @host_key_verifier = select_host_key_verifier(options[:paranoid])


  @server_version = timeout(options[:timeout] || 0) { ServerVersion.new(socket, logger) }

  @algorithms = Algorithms.new(self, options)
  wait { algorithms.initialized? }
end

Instance Attribute Details

#algorithmsObject (readonly)

The Algorithms instance used to perform key exchanges.



44
45
46
# File 'lib/net/ssh/transport/session.rb', line 44

def algorithms
  @algorithms
end

#hostObject (readonly)

The host to connect to, as given to the constructor.



29
30
31
# File 'lib/net/ssh/transport/session.rb', line 29

def host
  @host
end

#host_key_verifierObject (readonly)

The host-key verifier object used to verify host keys, to ensure that the connection is not being spoofed.



48
49
50
# File 'lib/net/ssh/transport/session.rb', line 48

def host_key_verifier
  @host_key_verifier
end

#optionsObject (readonly)

The hash of options that were given to the object at initialization.



51
52
53
# File 'lib/net/ssh/transport/session.rb', line 51

def options
  @options
end

#portObject (readonly)

The port number to connect to, as given in the options to the constructor. If no port number was given, this will default to DEFAULT_PORT.



33
34
35
# File 'lib/net/ssh/transport/session.rb', line 33

def port
  @port
end

#queueObject (readonly)

this method is primarily for use in tests



251
252
253
# File 'lib/net/ssh/transport/session.rb', line 251

def queue
  @queue
end

#server_versionObject (readonly)

The ServerVersion instance that encapsulates the negotiated protocol version.



41
42
43
# File 'lib/net/ssh/transport/session.rb', line 41

def server_version
  @server_version
end

#socketObject (readonly)

The underlying socket object being used to communicate with the remote host.



37
38
39
# File 'lib/net/ssh/transport/session.rb', line 37

def socket
  @socket
end

Instance Method Details

#closeObject

Cleans up (see PacketStream#cleanup) and closes the underlying socket.



104
105
106
107
# File 'lib/net/ssh/transport/session.rb', line 104

def close
  socket.cleanup
  socket.close
end

#closed?Boolean

Returns true if the underlying socket has been closed.

Returns:

  • (Boolean)


99
100
101
# File 'lib/net/ssh/transport/session.rb', line 99

def closed?
  socket.closed?
end

#configure_client(options = {}) ⇒ Object

Configure’s the packet stream’s client state with the given set of options. This is typically used to define the cipher, compression, and hmac algorithms to use when sending packets to the server.



231
232
233
# File 'lib/net/ssh/transport/session.rb', line 231

def configure_client(options={})
  socket.client.set(options)
end

#configure_server(options = {}) ⇒ Object

Configure’s the packet stream’s server state with the given set of options. This is typically used to define the cipher, compression, and hmac algorithms to use when reading packets from the server.



238
239
240
# File 'lib/net/ssh/transport/session.rb', line 238

def configure_server(options={})
  socket.server.set(options)
end

#enqueue_message(message) ⇒ Object

Enqueues the given message, such that it will be sent at the earliest opportunity. This does not block, but returns immediately.



224
225
226
# File 'lib/net/ssh/transport/session.rb', line 224

def enqueue_message(message)
  socket.enqueue_packet(message)
end

#hint(which, value = true) ⇒ Object

Sets a new hint for the packet stream, which the packet stream may use to change its behavior. (See PacketStream#hints).



244
245
246
# File 'lib/net/ssh/transport/session.rb', line 244

def hint(which, value=true)
  socket.hints[which] = value
end

#host_as_stringObject

Returns the host (and possibly IP address) in a format compatible with SSH known-host files.



85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/net/ssh/transport/session.rb', line 85

def host_as_string
  @host_as_string ||= begin
    string = "#{host}"
    string = "[#{string}]:#{port}" if port != DEFAULT_PORT
    if socket.peer_ip != host
      string2 = socket.peer_ip
      string2 = "[#{string2}]:#{port}" if port != DEFAULT_PORT
      string << "," << string2
    end
    string
  end
end

#next_messageObject

Blocks until a new packet is available to be read, and returns that packet. See #poll_message.



150
151
152
# File 'lib/net/ssh/transport/session.rb', line 150

def next_message
  poll_message(:block)
end

#peerObject

Returns a hash of information about the peer (remote) side of the socket, including :ip, :port, :host, and :canonized (see #host_as_string).



144
145
146
# File 'lib/net/ssh/transport/session.rb', line 144

def peer
  @peer ||= { :ip => socket.peer_ip, :port => @port.to_i, :host => @host, :canonized => host_as_string }
end

#poll_message(mode = :nonblock, consume_queue = true) ⇒ Object

Tries to read the next packet from the socket. If mode is :nonblock (the default), this will not block and will return nil if there are no packets waiting to be read. Otherwise, this will block until a packet is available. Note that some packet types (DISCONNECT, IGNORE, UNIMPLEMENTED, DEBUG, and KEXINIT) are handled silently by this method, and will never be returned.

If a key-exchange is in process and a disallowed packet type is received, it will be enqueued and otherwise ignored. When a key-exchange is not in process, and consume_queue is true, packets will be first read from the queue before the socket is queried.



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
# File 'lib/net/ssh/transport/session.rb', line 165

def poll_message(mode=:nonblock, consume_queue=true)
  loop do
    if consume_queue && @queue.any? && algorithms.allow?(@queue.first)
      return @queue.shift
    end

    packet = socket.next_packet(mode)
    return nil if packet.nil?

    case packet.type
    when DISCONNECT
      raise Net::SSH::Disconnect, "disconnected: #{packet[:description]} (#{packet[:reason_code]})"

    when IGNORE
      debug { "IGNORE packet recieved: #{packet[:data].inspect}" }

    when UNIMPLEMENTED
      lwarn { "UNIMPLEMENTED: #{packet[:number]}" }

    when DEBUG
      __send__(packet[:always_display] ? :fatal : :debug) { packet[:message] }

    when KEXINIT
      algorithms.accept_kexinit(packet)

    else
      return packet if algorithms.allow?(packet)
      push(packet)
    end
  end
end

#push(packet) ⇒ Object

Adds the given packet to the packet queue. If the queue is non-empty, #poll_message will return packets from the queue in the order they were received.



212
213
214
# File 'lib/net/ssh/transport/session.rb', line 212

def push(packet)
  @queue.push(packet)
end

#rekey!Object

Requests a rekey operation, and blocks until the operation completes. If a rekey is already pending, this returns immediately, having no effect.



127
128
129
130
131
132
# File 'lib/net/ssh/transport/session.rb', line 127

def rekey!
  if !algorithms.pending?
    algorithms.rekey!
    wait { algorithms.initialized? }
  end
end

#rekey_as_neededObject

Returns immediately if a rekey is already in process. Otherwise, if a rekey is needed (as indicated by the socket, see PacketStream#if_needs_rekey?) one is performed, causing this method to block until it completes.



137
138
139
140
# File 'lib/net/ssh/transport/session.rb', line 137

def rekey_as_needed
  return if algorithms.pending?
  socket.if_needs_rekey? { rekey! }
end

#send_message(message) ⇒ Object

Sends the given message via the packet stream, blocking until the entire message has been sent.



218
219
220
# File 'lib/net/ssh/transport/session.rb', line 218

def send_message(message)
  socket.send_packet(message)
end

#service_request(service) ⇒ Object

Returns a new service_request packet for the given service name, ready for sending to the server.



120
121
122
# File 'lib/net/ssh/transport/session.rb', line 120

def service_request(service)
  Net::SSH::Buffer.from(:byte, SERVICE_REQUEST, :string, service)
end

#shutdown!Object

Performs a “hard” shutdown of the connection. In general, this should never be done, but it might be necessary (in a rescue clause, for instance, when the connection needs to close but you don’t know the status of the underlying protocol’s state).



113
114
115
116
# File 'lib/net/ssh/transport/session.rb', line 113

def shutdown!
  error { "forcing connection closed" }
  socket.close
end

#waitObject

Waits (blocks) until the given block returns true. If no block is given, this just waits long enough to see if there are any pending packets. Any packets read are enqueued (see #push).



200
201
202
203
204
205
206
207
# File 'lib/net/ssh/transport/session.rb', line 200

def wait
  loop do
    break if block_given? && yield
    message = poll_message(:nonblock, false)
    push(message) if message
    break if !block_given?
  end
end