[ Index ]

PHP Cross Reference of DokuWiki

title

Body

[close]

/vendor/phpseclib/phpseclib/phpseclib/Net/ -> SSH2.php (summary)

Pure-PHP implementation of SSHv2. PHP version 5

Author: Jim Wigginton
Copyright: 2007 Jim Wigginton
License: http://www.opensource.org/licenses/mit-license.html MIT License
Link: http://phpseclib.sourceforge.net
File Size: 5436 lines (192 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 1 class

SSH2:: (101 methods):
  __construct()
  setCryptoEngine()
  sendIdentificationStringFirst()
  sendIdentificationStringLast()
  sendKEXINITFirst()
  sendKEXINITLast()
  stream_select()
  connect()
  generate_identifier()
  key_exchange()
  encryption_algorithm_to_key_size()
  encryption_algorithm_to_crypt_instance()
  mac_algorithm_to_hash_instance()
  bad_algorithm_candidate()
  login()
  sublogin()
  login_helper()
  keyboard_interactive_login()
  keyboard_interactive_process()
  ssh_agent_login()
  privatekey_login()
  getTimeout()
  setTimeout()
  setKeepAlive()
  getStdError()
  exec()
  getOpenChannelCount()
  open_channel()
  openShell()
  get_interactive_channel()
  is_channel_status_data()
  get_open_channel()
  requestAgentForwarding()
  read()
  write()
  startSubsystem()
  stopSubsystem()
  reset()
  isTimeout()
  disconnect()
  __destruct()
  isConnected()
  isAuthenticated()
  isShellOpen()
  isPTYOpen()
  isInteractiveChannelOpen()
  getInteractiveChannelId()
  ping()
  reconnect()
  reset_connection()
  get_binary_packet()
  read_remaining_bytes()
  filter()
  enableQuietMode()
  disableQuietMode()
  isQuietModeEnabled()
  enablePTY()
  disablePTY()
  isPTYEnabled()
  get_channel_packet()
  send_binary_packet()
  append_log()
  append_log_helper()
  send_channel_packet()
  close_channel()
  close_channel_bitmap()
  disconnect_helper()
  define_array()
  getLog()
  format_log()
  on_channel_open()
  array_intersect_first()
  getErrors()
  getLastError()
  getServerIdentification()
  getServerAlgorithms()
  getSupportedKEXAlgorithms()
  getSupportedHostKeyAlgorithms()
  getSupportedEncryptionAlgorithms()
  getSupportedMACAlgorithms()
  getSupportedCompressionAlgorithms()
  getAlgorithmsNegotiated()
  forceMultipleChannels()
  setTerminal()
  setPreferredAlgorithms()
  getBannerMessage()
  getServerPublicHostKey()
  getExitStatus()
  getWindowColumns()
  getWindowRows()
  setWindowColumns()
  setWindowRows()
  setWindowSize()
  __toString()
  getResourceId()
  getConnectionByResourceId()
  getConnections()
  updateLogHistory()
  getAuthMethodsToContinue()
  enableSmartMFA()
  disableSmartMFA()


Class: SSH2  - X-Ref

Pure-PHP implementation of SSHv2.

__construct($host, $port = 22, $timeout = 10)   X-Ref
Default Constructor.

$host can either be a string, representing the host, or a stream resource.
If $host is a stream resource then $port doesn't do anything, altho $timeout
still will be used

see: self::login()
param: mixed $host
param: int $port
param: int $timeout

setCryptoEngine($engine)   X-Ref
Set Crypto Engine Mode

Possible $engine values:
OpenSSL, mcrypt, Eval, PHP

param: int $engine

sendIdentificationStringFirst()   X-Ref
Send Identification String First

https://tools.ietf.org/html/rfc4253#section-4.2 says "when the connection has been established,
both sides MUST send an identification string". It does not say which side sends it first. In
theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy


sendIdentificationStringLast()   X-Ref
Send Identification String Last

https://tools.ietf.org/html/rfc4253#section-4.2 says "when the connection has been established,
both sides MUST send an identification string". It does not say which side sends it first. In
theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy


sendKEXINITFirst()   X-Ref
Send SSH_MSG_KEXINIT First

https://tools.ietf.org/html/rfc4253#section-7.1 says "key exchange begins by each sending
sending the [SSH_MSG_KEXINIT] packet". It does not say which side sends it first. In theory
it shouldn't matter but it is a fact of life that some SSH servers are simply buggy


sendKEXINITLast()   X-Ref
Send SSH_MSG_KEXINIT Last

https://tools.ietf.org/html/rfc4253#section-7.1 says "key exchange begins by each sending
sending the [SSH_MSG_KEXINIT] packet". It does not say which side sends it first. In theory
it shouldn't matter but it is a fact of life that some SSH servers are simply buggy


stream_select(&$read, &$write, &$except, $seconds, $microseconds = null)   X-Ref
stream_select wrapper

Quoting https://stackoverflow.com/a/14262151/569976,
"The general approach to `EINTR` is to simply handle the error and retry the operation again"

This wrapper does that loop

connect()   X-Ref
Connect to an SSHv2 server


generate_identifier()   X-Ref
Generates the SSH identifier

You should overwrite this method in your own class if you want to use another identifier

return: string

key_exchange($kexinit_payload_server = false)   X-Ref
Key Exchange

param: string|bool $kexinit_payload_server optional
return: bool

encryption_algorithm_to_key_size($algorithm)   X-Ref
Maps an encryption algorithm name to the number of key bytes.

param: string $algorithm Name of the encryption algorithm
return: int|null Number of bytes as an integer or null for unknown

encryption_algorithm_to_crypt_instance($algorithm)   X-Ref
Maps an encryption algorithm name to an instance of a subclass of
\phpseclib3\Crypt\Common\SymmetricKey.

param: string $algorithm Name of the encryption algorithm
return: SymmetricKey|null

mac_algorithm_to_hash_instance($algorithm)   X-Ref
Maps an encryption algorithm name to an instance of a subclass of
\phpseclib3\Crypt\Hash.

param: string $algorithm Name of the encryption algorithm
return: array{Hash, int}|null

bad_algorithm_candidate($algorithm)   X-Ref
No description

login($username, ...$args)   X-Ref
Login

The $password parameter can be a plaintext password, a \phpseclib3\Crypt\RSA|EC|DSA object, a \phpseclib3\System\SSH\Agent object or an array

see: self::_login()
param: string $username
param: string|PrivateKey|array[]|Agent|null ...$args
return: bool

sublogin($username, ...$args)   X-Ref
Login Helper

see: self::_login_helper()
param: string $username
param: string|PrivateKey|array[]|Agent|null ...$args
return: bool

login_helper($username, $password = null)   X-Ref
Login Helper

{@internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis}
by sending dummy SSH_MSG_IGNORE messages.}

param: string $username
param: string|AsymmetricKey|array[]|Agent|null ...$args
return: bool

keyboard_interactive_login($username, $password)   X-Ref
Login via keyboard-interactive authentication

See {@link http://tools.ietf.org/html/rfc4256 RFC4256} for details.  This is not a full-featured keyboard-interactive authenticator.

param: string $username
param: string|array $password
return: bool

keyboard_interactive_process(...$responses)   X-Ref
Handle the keyboard-interactive requests / responses.

param: string|array ...$responses
return: bool

ssh_agent_login($username, Agent $agent)   X-Ref
Login with an ssh-agent provided key

param: string $username
param: \phpseclib3\System\SSH\Agent $agent
return: bool

privatekey_login($username, PrivateKey $privatekey)   X-Ref
Login with an RSA private key

{@internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis}
by sending dummy SSH_MSG_IGNORE messages.}

param: string $username
param: \phpseclib3\Crypt\Common\PrivateKey $privatekey
return: bool

getTimeout()   X-Ref
Return the currently configured timeout

return: int

setTimeout($timeout)   X-Ref
Set Timeout

$ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely.  setTimeout() makes it so it'll timeout.
Setting $timeout to false or 0 will mean there is no timeout.

param: mixed $timeout

setKeepAlive($interval)   X-Ref
Set Keep Alive

Sends an SSH2_MSG_IGNORE message every x seconds, if x is a positive non-zero number.

param: int $interval

getStdError()   X-Ref
Get the output from stdError


exec($command, callable $callback = null)   X-Ref
Execute Command

If $callback is set to false then \phpseclib3\Net\SSH2::get_channel_packet(self::CHANNEL_EXEC) will need to be called manually.
In all likelihood, this is not a feature you want to be taking advantage of.

param: string $command
return: string|bool

getOpenChannelCount()   X-Ref
How many channels are currently open?

return: int

open_channel($channel, $skip_extended = false)   X-Ref
Opens a channel

param: string $channel
param: bool $skip_extended
return: bool

openShell()   X-Ref
Creates an interactive shell

Returns bool(true) if the shell was opened.
Returns bool(false) if the shell was already open.

see: self::isShellOpen()
see: self::read()
see: self::write()
return: bool

get_interactive_channel()   X-Ref
Return the channel to be used with read(), write(), and reset(), if none were specified

see: self::read()
see: self::write()
return: int

is_channel_status_data($channel)   X-Ref
Indicates the DATA status on the given channel

param: int $channel The channel number to evaluate
return: bool

get_open_channel()   X-Ref
Return an available open channel

return: int

requestAgentForwarding()   X-Ref
Request agent forwarding of remote server

return: bool

read($expect = '', $mode = self::READ_SIMPLE, $channel = null)   X-Ref
Returns the output of an interactive shell

Returns when there's a match for $expect, which can take the form of a string literal or,
if $mode == self::READ_REGEX, a regular expression.

If not specifying a channel, an open interactive channel will be selected, or, if there are
no open channels, an interactive shell will be created. If there are multiple open
interactive channels, a legacy behavior will apply in which channel selection prioritizes
an active subsystem, the exec pty, and, lastly, the shell. If using multiple interactive
channels, callers are discouraged from relying on this legacy behavior and should specify
the intended channel.

see: self::write()
param: string $expect
param: int $mode One of the self::READ_* constants
param: int|null $channel Channel id returned by self::getInteractiveChannelId()
return: string|bool|null

write($cmd, $channel = null)   X-Ref
Inputs a command into an interactive shell.

If not specifying a channel, an open interactive channel will be selected, or, if there are
no open channels, an interactive shell will be created. If there are multiple open
interactive channels, a legacy behavior will apply in which channel selection prioritizes
an active subsystem, the exec pty, and, lastly, the shell. If using multiple interactive
channels, callers are discouraged from relying on this legacy behavior and should specify
the intended channel.

see: SSH2::read()
param: string $cmd
param: int|null $channel Channel id returned by self::getInteractiveChannelId()
return: void

startSubsystem($subsystem)   X-Ref
Start a subsystem.

Right now only one subsystem at a time is supported. To support multiple subsystem's stopSubsystem() could accept
a string that contained the name of the subsystem, but at that point, only one subsystem of each type could be opened.
To support multiple subsystem's of the same name maybe it'd be best if startSubsystem() generated a new channel id and
returns that and then that that was passed into stopSubsystem() but that'll be saved for a future date and implemented
if there's sufficient demand for such a feature.

see: self::stopSubsystem()
param: string $subsystem
return: bool

stopSubsystem()   X-Ref
Stops a subsystem.

see: self::startSubsystem()
return: bool

reset($channel = null)   X-Ref
Closes a channel

If read() timed out you might want to just close the channel and have it auto-restart on the next read() call

If not specifying a channel, an open interactive channel will be selected. If there are
multiple open interactive channels, a legacy behavior will apply in which channel selection
prioritizes an active subsystem, the exec pty, and, lastly, the shell. If using multiple
interactive channels, callers are discouraged from relying on this legacy behavior and
should specify the intended channel.

param: int|null $channel Channel id returned by self::getInteractiveChannelId()
return: void

isTimeout()   X-Ref
Is timeout?

Did exec() or read() return because they timed out or because they encountered the end?


disconnect()   X-Ref
Disconnect


__destruct()   X-Ref
Destructor.

Will be called, automatically, if you're supporting just PHP5.  If you're supporting PHP4, you'll need to call
disconnect().


isConnected($level = 0)   X-Ref
Is the connection still active?

$level has 3x possible values:
0 (default): phpseclib takes a passive approach to see if the connection is still active by calling feof()
on the socket
1: phpseclib takes an active approach to see if the connection is still active by sending an SSH_MSG_IGNORE
packet that doesn't require a response
2: phpseclib takes an active approach to see if the connection is still active by sending an SSH_MSG_CHANNEL_OPEN
packet and imediately trying to close that channel. some routers, in particular, however, will only let you
open one channel, so this approach could yield false positives

param: int $level
return: bool

isAuthenticated()   X-Ref
Have you successfully been logged in?

return: bool

isShellOpen()   X-Ref
Is the interactive shell active?

return: bool

isPTYOpen()   X-Ref
Is the exec pty active?

return: bool

isInteractiveChannelOpen($channel)   X-Ref
Is the given interactive channel active?

param: int $channel Channel id returned by self::getInteractiveChannelId()
return: bool

getInteractiveChannelId()   X-Ref
Returns a channel identifier, presently of the last interactive channel opened, regardless of current status.
Returns 0 if no interactive channel has been opened.

see: self::isInteractiveChannelOpen()
return: int

ping()   X-Ref
Pings a server connection, or tries to reconnect if the connection has gone down

Inspired by http://php.net/manual/en/mysqli.ping.php

return: bool

reconnect()   X-Ref
In situ reconnect method

return: boolean

reset_connection($reason)   X-Ref
Resets a connection for re-use

param: int $reason

get_binary_packet($skip_channel_filter = false)   X-Ref
Gets Binary Packets

See '6. Binary Packet Protocol' of rfc4253 for more info.

see: self::_send_binary_packet()
param: bool $skip_channel_filter
return: bool|string

read_remaining_bytes($remaining_length)   X-Ref
Read Remaining Bytes

see: self::get_binary_packet()
param: int $remaining_length
return: string

filter($payload, $skip_channel_filter)   X-Ref
Filter Binary Packets

Because some binary packets need to be ignored...

see: self::_get_binary_packet()
param: string $payload
param: bool $skip_channel_filter
return: string|bool

enableQuietMode()   X-Ref
Enable Quiet Mode

Suppress stderr from output


disableQuietMode()   X-Ref
Disable Quiet Mode

Show stderr in output


isQuietModeEnabled()   X-Ref
Returns whether Quiet Mode is enabled or not

see: self::enableQuietMode()
see: self::disableQuietMode()
return: bool

enablePTY()   X-Ref
Enable request-pty when using exec()


disablePTY()   X-Ref
Disable request-pty when using exec()


isPTYEnabled()   X-Ref
Returns whether request-pty is enabled or not

see: self::enablePTY()
see: self::disablePTY()
return: bool

get_channel_packet($client_channel, $skip_extended = false)   X-Ref
Gets channel data

Returns the data as a string. bool(true) is returned if:

- the server closes the channel
- if the connection times out
- if the channel status is CHANNEL_OPEN and the response was CHANNEL_OPEN_CONFIRMATION
- if the channel status is CHANNEL_REQUEST and the response was CHANNEL_SUCCESS
- if the channel status is CHANNEL_CLOSE and the response was CHANNEL_CLOSE

bool(false) is returned if:

- if the channel status is CHANNEL_REQUEST and the response was CHANNEL_FAILURE

param: int $client_channel
param: bool $skip_extended
return: mixed

send_binary_packet($data, $logged = null)   X-Ref
Sends Binary Packets

See '6. Binary Packet Protocol' of rfc4253 for more info.

see: self::_get_binary_packet()
param: string $data
param: string $logged
return: void

append_log($message_number, $message)   X-Ref
Logs data packets

Makes sure that only the last 1MB worth of packets will be logged

param: string $message_number
param: string $message

append_log_helper($constant, $message_number, $message, array &$message_number_log, array &$message_log, &$log_size, &$realtime_log_file, &$realtime_log_wrap, &$realtime_log_size)   X-Ref
Logs data packet helper

param: int $constant
param: string $message_number
param: string $message
param: array &$message_number_log
param: array &$message_log
param: int &$log_size
param: resource &$realtime_log_file
param: bool &$realtime_log_wrap
param: int &$realtime_log_size

send_channel_packet($client_channel, $data)   X-Ref
Sends channel data

Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate

param: int $client_channel
param: string $data
return: void

close_channel($client_channel, $want_reply = false)   X-Ref
Closes and flushes a channel

\phpseclib3\Net\SSH2 doesn't properly close most channels.  For exec() channels are normally closed by the server
and for SFTP channels are presumably closed when the client disconnects.  This functions is intended
for SCP more than anything.

param: int $client_channel
param: bool $want_reply
return: void

close_channel_bitmap($client_channel)   X-Ref
Maintains execution state bitmap in response to channel closure

param: int $client_channel The channel number to maintain closure status of
return: void

disconnect_helper($reason)   X-Ref
Disconnect

param: int $reason
return: false

define_array(...$args)   X-Ref
Define Array

Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of
named constants from it, using the value as the name of the constant and the index as the value of the constant.
If any of the constants that would be defined already exists, none of the constants will be defined.

param: mixed[] ...$args

getLog()   X-Ref
Returns a log of the packets that have been sent and received.

Returns a string if NET_SSH2_LOGGING == self::LOG_COMPLEX, an array if NET_SSH2_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SSH2_LOGGING')

return: array|false|string

format_log(array $message_log, array $message_number_log)   X-Ref
Formats a log for printing

param: array $message_log
param: array $message_number_log
return: string

on_channel_open()   X-Ref
Helper function for agent->on_channel_open()

Used when channels are created to inform agent
of said channel opening. Must be called after
channel open confirmation received


array_intersect_first(array $array1, array $array2)   X-Ref
Returns the first value of the intersection of two arrays or false if
the intersection is empty. The order is defined by the first parameter.

param: array $array1
param: array $array2
return: mixed False if intersection is empty, else intersected value.

getErrors()   X-Ref
Returns all errors / debug messages on the SSH layer

If you are looking for messages from the SFTP layer, please see SFTP::getSFTPErrors()

return: string[]

getLastError()   X-Ref
Returns the last error received on the SSH layer

If you are looking for messages from the SFTP layer, please see SFTP::getLastSFTPError()

return: string

getServerIdentification()   X-Ref
Return the server identification.

return: string|false

getServerAlgorithms()   X-Ref
Returns a list of algorithms the server supports

return: array

getSupportedKEXAlgorithms()   X-Ref
Returns a list of KEX algorithms that phpseclib supports

return: array

getSupportedHostKeyAlgorithms()   X-Ref
Returns a list of host key algorithms that phpseclib supports

return: array

getSupportedEncryptionAlgorithms()   X-Ref
Returns a list of symmetric key algorithms that phpseclib supports

return: array

getSupportedMACAlgorithms()   X-Ref
Returns a list of MAC algorithms that phpseclib supports

return: array

getSupportedCompressionAlgorithms()   X-Ref
Returns a list of compression algorithms that phpseclib supports

return: array

getAlgorithmsNegotiated()   X-Ref
Return list of negotiated algorithms

Uses the same format as https://www.php.net/ssh2-methods-negotiated

return: array

forceMultipleChannels()   X-Ref
Force multiple channels (even if phpseclib has decided to disable them)


setTerminal($term)   X-Ref
Allows you to set the terminal

param: string $term

setPreferredAlgorithms(array $methods)   X-Ref
Accepts an associative array with up to four parameters as described at
<https://www.php.net/manual/en/function.ssh2-connect.php>

param: array $methods

getBannerMessage()   X-Ref
Returns the banner message.

Quoting from the RFC, "in some jurisdictions, sending a warning message before
authentication may be relevant for getting legal protection."

return: string

getServerPublicHostKey()   X-Ref
Returns the server public host key.

Caching this the first time you connect to a server and checking the result on subsequent connections
is recommended.  Returns false if the server signature is not signed correctly with the public host key.

return: string|false

getExitStatus()   X-Ref
Returns the exit status of an SSH command or false.

return: false|int

getWindowColumns()   X-Ref
Returns the number of columns for the terminal window size.

return: int

getWindowRows()   X-Ref
Returns the number of rows for the terminal window size.

return: int

setWindowColumns($value)   X-Ref
Sets the number of columns for the terminal window size.

param: int $value

setWindowRows($value)   X-Ref
Sets the number of rows for the terminal window size.

param: int $value

setWindowSize($columns = 80, $rows = 24)   X-Ref
Sets the number of columns and rows for the terminal window size.

param: int $columns
param: int $rows

__toString()   X-Ref
To String Magic Method

return: string

getResourceId()   X-Ref
Get Resource ID

We use {} because that symbols should not be in URL according to
{@link http://tools.ietf.org/html/rfc3986#section-2 RFC}.
It will safe us from any conflicts, because otherwise regexp will
match all alphanumeric domains.

return: string

getConnectionByResourceId($id)   X-Ref
Return existing connection

param: string $id
return: bool|SSH2 will return false if no such connection

getConnections()   X-Ref
Return all excising connections

return: array<string, SSH2>

updateLogHistory($old, $new)   X-Ref
No description

getAuthMethodsToContinue()   X-Ref
Return the list of authentication methods that may productively continue authentication.

see: https://tools.ietf.org/html/rfc4252#section-5.1
return: array|null

enableSmartMFA()   X-Ref
Enables "smart" multi-factor authentication (MFA)


disableSmartMFA()   X-Ref
Disables "smart" multi-factor authentication (MFA)