/phpseclib/Net/SSH2.php
http://github.com/phpseclib/phpseclib · PHP · 5160 lines · 2879 code · 546 blank · 1735 comment · 453 complexity · b048711bdddb15f44d6466fb86e06fe4 MD5 · raw file
Large files are truncated click here to view the full file
- <?php
- /**
- * Pure-PHP implementation of SSHv2.
- *
- * PHP version 5
- *
- * Here are some examples of how to use this library:
- * <code>
- * <?php
- * include 'vendor/autoload.php';
- *
- * $ssh = new \phpseclib3\Net\SSH2('www.domain.tld');
- * if (!$ssh->login('username', 'password')) {
- * exit('Login Failed');
- * }
- *
- * echo $ssh->exec('pwd');
- * echo $ssh->exec('ls -la');
- * ?>
- * </code>
- *
- * <code>
- * <?php
- * include 'vendor/autoload.php';
- *
- * $key = \phpseclib3\Crypt\PublicKeyLoader::load('...', '(optional) password');
- *
- * $ssh = new \phpseclib3\Net\SSH2('www.domain.tld');
- * if (!$ssh->login('username', $key)) {
- * exit('Login Failed');
- * }
- *
- * echo $ssh->read('username@username:~$');
- * $ssh->write("ls -la\n");
- * echo $ssh->read('username@username:~$');
- * ?>
- * </code>
- *
- * @category Net
- * @package SSH2
- * @author Jim Wigginton <terrafrost@php.net>
- * @copyright 2007 Jim Wigginton
- * @license http://www.opensource.org/licenses/mit-license.html MIT License
- * @link http://phpseclib.sourceforge.net
- */
- namespace phpseclib3\Net;
- use phpseclib3\Crypt\Blowfish;
- use phpseclib3\Crypt\Hash;
- use phpseclib3\Crypt\Random;
- use phpseclib3\Crypt\RC4;
- use phpseclib3\Crypt\Rijndael;
- use phpseclib3\Crypt\Common\PrivateKey;
- use phpseclib3\Crypt\RSA;
- use phpseclib3\Crypt\DSA;
- use phpseclib3\Crypt\EC;
- use phpseclib3\Crypt\DH;
- use phpseclib3\Crypt\TripleDES;
- use phpseclib3\Crypt\Twofish;
- use phpseclib3\Crypt\ChaCha20;
- use phpseclib3\Math\BigInteger; // Used to do Diffie-Hellman key exchange and DSA/RSA signature verification.
- use phpseclib3\System\SSH\Agent;
- use phpseclib3\System\SSH\Agent\Identity as AgentIdentity;
- use phpseclib3\Exception\NoSupportedAlgorithmsException;
- use phpseclib3\Exception\UnsupportedAlgorithmException;
- use phpseclib3\Exception\UnsupportedCurveException;
- use phpseclib3\Exception\ConnectionClosedException;
- use phpseclib3\Exception\UnableToConnectException;
- use phpseclib3\Exception\InsufficientSetupException;
- use phpseclib3\Common\Functions\Strings;
- use phpseclib3\Crypt\Common\AsymmetricKey;
- /**#@+
- * @access private
- */
- /**
- * No compression
- */
- define('NET_SSH2_COMPRESSION_NONE', 1);
- /**
- * zlib compression
- */
- define('NET_SSH2_COMPRESSION_ZLIB', 2);
- /**
- * zlib@openssh.com
- */
- define('NET_SSH2_COMPRESSION_ZLIB_AT_OPENSSH', 3);
- /**#@-*/
- /**
- * Pure-PHP implementation of SSHv2.
- *
- * @package SSH2
- * @author Jim Wigginton <terrafrost@php.net>
- * @access public
- */
- class SSH2
- {
- // Execution Bitmap Masks
- const MASK_CONSTRUCTOR = 0x00000001;
- const MASK_CONNECTED = 0x00000002;
- const MASK_LOGIN_REQ = 0x00000004;
- const MASK_LOGIN = 0x00000008;
- const MASK_SHELL = 0x00000010;
- const MASK_WINDOW_ADJUST = 0x00000020;
- /*
- * Channel constants
- *
- * RFC4254 refers not to client and server channels but rather to sender and recipient channels. we don't refer
- * to them in that way because RFC4254 toggles the meaning. the client sends a SSH_MSG_CHANNEL_OPEN message with
- * a sender channel and the server sends a SSH_MSG_CHANNEL_OPEN_CONFIRMATION in response, with a sender and a
- * recipient channel. at first glance, you might conclude that SSH_MSG_CHANNEL_OPEN_CONFIRMATION's sender channel
- * would be the same thing as SSH_MSG_CHANNEL_OPEN's sender channel, but it's not, per this snippet:
- * The 'recipient channel' is the channel number given in the original
- * open request, and 'sender channel' is the channel number allocated by
- * the other side.
- *
- * @see \phpseclib3\Net\SSH2::send_channel_packet()
- * @see \phpseclib3\Net\SSH2::get_channel_packet()
- * @access private
- */
- const CHANNEL_EXEC = 1; // PuTTy uses 0x100
- const CHANNEL_SHELL = 2;
- const CHANNEL_SUBSYSTEM = 3;
- const CHANNEL_AGENT_FORWARD = 4;
- const CHANNEL_KEEP_ALIVE = 5;
- /**
- * Returns the message numbers
- *
- * @access public
- * @see \phpseclib3\Net\SSH2::getLog()
- */
- const LOG_SIMPLE = 1;
- /**
- * Returns the message content
- *
- * @access public
- * @see \phpseclib3\Net\SSH2::getLog()
- */
- const LOG_COMPLEX = 2;
- /**
- * Outputs the content real-time
- *
- * @access public
- * @see \phpseclib3\Net\SSH2::getLog()
- */
- const LOG_REALTIME = 3;
- /**
- * Dumps the content real-time to a file
- *
- * @access public
- * @see \phpseclib3\Net\SSH2::getLog()
- */
- const LOG_REALTIME_FILE = 4;
- /**
- * Make sure that the log never gets larger than this
- *
- * @access public
- * @see \phpseclib3\Net\SSH2::getLog()
- */
- const LOG_MAX_SIZE = 1048576; // 1024 * 1024
- /**
- * Returns when a string matching $expect exactly is found
- *
- * @access public
- * @see \phpseclib3\Net\SSH2::read()
- */
- const READ_SIMPLE = 1;
- /**
- * Returns when a string matching the regular expression $expect is found
- *
- * @access public
- * @see \phpseclib3\Net\SSH2::read()
- */
- const READ_REGEX = 2;
- /**
- * Returns whenever a data packet is received.
- *
- * Some data packets may only contain a single character so it may be necessary
- * to call read() multiple times when using this option
- *
- * @access public
- * @see \phpseclib3\Net\SSH2::read()
- */
- const READ_NEXT = 3;
- /**
- * The SSH identifier
- *
- * @var string
- * @access private
- */
- private $identifier;
- /**
- * The Socket Object
- *
- * @var object
- * @access private
- */
- public $fsock;
- /**
- * Execution Bitmap
- *
- * The bits that are set represent functions that have been called already. This is used to determine
- * if a requisite function has been successfully executed. If not, an error should be thrown.
- *
- * @var int
- * @access private
- */
- protected $bitmap = 0;
- /**
- * Error information
- *
- * @see self::getErrors()
- * @see self::getLastError()
- * @var array
- * @access private
- */
- private $errors = [];
- /**
- * Server Identifier
- *
- * @see self::getServerIdentification()
- * @var array|false
- * @access private
- */
- protected $server_identifier = false;
- /**
- * Key Exchange Algorithms
- *
- * @see self::getKexAlgorithims()
- * @var array|false
- * @access private
- */
- private $kex_algorithms = false;
- /**
- * Key Exchange Algorithm
- *
- * @see self::getMethodsNegotiated()
- * @var string|false
- * @access private
- */
- private $kex_algorithm = false;
- /**
- * Minimum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods
- *
- * @see self::_key_exchange()
- * @var int
- * @access private
- */
- private $kex_dh_group_size_min = 1536;
- /**
- * Preferred Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods
- *
- * @see self::_key_exchange()
- * @var int
- * @access private
- */
- private $kex_dh_group_size_preferred = 2048;
- /**
- * Maximum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods
- *
- * @see self::_key_exchange()
- * @var int
- * @access private
- */
- private $kex_dh_group_size_max = 4096;
- /**
- * Server Host Key Algorithms
- *
- * @see self::getServerHostKeyAlgorithms()
- * @var array|false
- * @access private
- */
- private $server_host_key_algorithms = false;
- /**
- * Encryption Algorithms: Client to Server
- *
- * @see self::getEncryptionAlgorithmsClient2Server()
- * @var array|false
- * @access private
- */
- private $encryption_algorithms_client_to_server = false;
- /**
- * Encryption Algorithms: Server to Client
- *
- * @see self::getEncryptionAlgorithmsServer2Client()
- * @var array|false
- * @access private
- */
- private $encryption_algorithms_server_to_client = false;
- /**
- * MAC Algorithms: Client to Server
- *
- * @see self::getMACAlgorithmsClient2Server()
- * @var array|false
- * @access private
- */
- private $mac_algorithms_client_to_server = false;
- /**
- * MAC Algorithms: Server to Client
- *
- * @see self::getMACAlgorithmsServer2Client()
- * @var array|false
- * @access private
- */
- private $mac_algorithms_server_to_client = false;
- /**
- * Compression Algorithms: Client to Server
- *
- * @see self::getCompressionAlgorithmsClient2Server()
- * @var array|false
- * @access private
- */
- private $compression_algorithms_client_to_server = false;
- /**
- * Compression Algorithms: Server to Client
- *
- * @see self::getCompressionAlgorithmsServer2Client()
- * @var array|false
- * @access private
- */
- private $compression_algorithms_server_to_client = false;
- /**
- * Languages: Server to Client
- *
- * @see self::getLanguagesServer2Client()
- * @var array|false
- * @access private
- */
- private $languages_server_to_client = false;
- /**
- * Languages: Client to Server
- *
- * @see self::getLanguagesClient2Server()
- * @var array|false
- * @access private
- */
- private $languages_client_to_server = false;
- /**
- * Preferred Algorithms
- *
- * @see self::setPreferredAlgorithms()
- * @var array
- * @access private
- */
- private $preferred = [];
- /**
- * Block Size for Server to Client Encryption
- *
- * "Note that the length of the concatenation of 'packet_length',
- * 'padding_length', 'payload', and 'random padding' MUST be a multiple
- * of the cipher block size or 8, whichever is larger. This constraint
- * MUST be enforced, even when using stream ciphers."
- *
- * -- http://tools.ietf.org/html/rfc4253#section-6
- *
- * @see self::__construct()
- * @see self::_send_binary_packet()
- * @var int
- * @access private
- */
- private $encrypt_block_size = 8;
- /**
- * Block Size for Client to Server Encryption
- *
- * @see self::__construct()
- * @see self::_get_binary_packet()
- * @var int
- * @access private
- */
- private $decrypt_block_size = 8;
- /**
- * Server to Client Encryption Object
- *
- * @see self::_get_binary_packet()
- * @var object
- * @access private
- */
- private $decrypt = false;
- /**
- * Server to Client Length Encryption Object
- *
- * @see self::_get_binary_packet()
- * @var object
- * @access private
- */
- private $lengthDecrypt = false;
- /**
- * Client to Server Encryption Object
- *
- * @see self::_send_binary_packet()
- * @var object
- * @access private
- */
- private $encrypt = false;
- /**
- * Client to Server Length Encryption Object
- *
- * @see self::_send_binary_packet()
- * @var object
- * @access private
- */
- private $lengthEncrypt = false;
- /**
- * Client to Server HMAC Object
- *
- * @see self::_send_binary_packet()
- * @var object
- * @access private
- */
- private $hmac_create = false;
- /**
- * Server to Client HMAC Object
- *
- * @see self::_get_binary_packet()
- * @var object
- * @access private
- */
- private $hmac_check = false;
- /**
- * Size of server to client HMAC
- *
- * We need to know how big the HMAC will be for the server to client direction so that we know how many bytes to read.
- * For the client to server side, the HMAC object will make the HMAC as long as it needs to be. All we need to do is
- * append it.
- *
- * @see self::_get_binary_packet()
- * @var int
- * @access private
- */
- private $hmac_size = false;
- /**
- * Server Public Host Key
- *
- * @see self::getServerPublicHostKey()
- * @var string
- * @access private
- */
- private $server_public_host_key;
- /**
- * Session identifier
- *
- * "The exchange hash H from the first key exchange is additionally
- * used as the session identifier, which is a unique identifier for
- * this connection."
- *
- * -- http://tools.ietf.org/html/rfc4253#section-7.2
- *
- * @see self::_key_exchange()
- * @var string
- * @access private
- */
- private $session_id = false;
- /**
- * Exchange hash
- *
- * The current exchange hash
- *
- * @see self::_key_exchange()
- * @var string
- * @access private
- */
- private $exchange_hash = false;
- /**
- * Message Numbers
- *
- * @see self::__construct()
- * @var array
- * @access private
- */
- private $message_numbers = [];
- /**
- * Disconnection Message 'reason codes' defined in RFC4253
- *
- * @see self::__construct()
- * @var array
- * @access private
- */
- private $disconnect_reasons = [];
- /**
- * SSH_MSG_CHANNEL_OPEN_FAILURE 'reason codes', defined in RFC4254
- *
- * @see self::__construct()
- * @var array
- * @access private
- */
- private $channel_open_failure_reasons = [];
- /**
- * Terminal Modes
- *
- * @link http://tools.ietf.org/html/rfc4254#section-8
- * @see self::__construct()
- * @var array
- * @access private
- */
- private $terminal_modes = [];
- /**
- * SSH_MSG_CHANNEL_EXTENDED_DATA's data_type_codes
- *
- * @link http://tools.ietf.org/html/rfc4254#section-5.2
- * @see self::__construct()
- * @var array
- * @access private
- */
- private $channel_extended_data_type_codes = [];
- /**
- * Send Sequence Number
- *
- * See 'Section 6.4. Data Integrity' of rfc4253 for more info.
- *
- * @see self::_send_binary_packet()
- * @var int
- * @access private
- */
- private $send_seq_no = 0;
- /**
- * Get Sequence Number
- *
- * See 'Section 6.4. Data Integrity' of rfc4253 for more info.
- *
- * @see self::_get_binary_packet()
- * @var int
- * @access private
- */
- private $get_seq_no = 0;
- /**
- * Server Channels
- *
- * Maps client channels to server channels
- *
- * @see self::get_channel_packet()
- * @see self::exec()
- * @var array
- * @access private
- */
- protected $server_channels = [];
- /**
- * Channel Buffers
- *
- * If a client requests a packet from one channel but receives two packets from another those packets should
- * be placed in a buffer
- *
- * @see self::get_channel_packet()
- * @see self::exec()
- * @var array
- * @access private
- */
- private $channel_buffers = [];
- /**
- * Channel Status
- *
- * Contains the type of the last sent message
- *
- * @see self::get_channel_packet()
- * @var array
- * @access private
- */
- protected $channel_status = [];
- /**
- * Packet Size
- *
- * Maximum packet size indexed by channel
- *
- * @see self::send_channel_packet()
- * @var array
- * @access private
- */
- private $packet_size_client_to_server = [];
- /**
- * Message Number Log
- *
- * @see self::getLog()
- * @var array
- * @access private
- */
- private $message_number_log = [];
- /**
- * Message Log
- *
- * @see self::getLog()
- * @var array
- * @access private
- */
- private $message_log = [];
- /**
- * The Window Size
- *
- * Bytes the other party can send before it must wait for the window to be adjusted (0x7FFFFFFF = 2GB)
- *
- * @var int
- * @see self::send_channel_packet()
- * @see self::exec()
- * @access private
- */
- protected $window_size = 0x7FFFFFFF;
- /**
- * What we resize the window to
- *
- * When PuTTY resizes the window it doesn't add an additional 0x7FFFFFFF bytes - it adds 0x40000000 bytes.
- * Some SFTP clients (GoAnywhere) don't support adding 0x7FFFFFFF to the window size after the fact so
- * we'll just do what PuTTY does
- *
- * @var int
- * @see self::_send_channel_packet()
- * @see self::exec()
- * @access private
- */
- private $window_resize = 0x40000000;
- /**
- * Window size, server to client
- *
- * Window size indexed by channel
- *
- * @see self::send_channel_packet()
- * @var array
- * @access private
- */
- protected $window_size_server_to_client = [];
- /**
- * Window size, client to server
- *
- * Window size indexed by channel
- *
- * @see self::get_channel_packet()
- * @var array
- * @access private
- */
- private $window_size_client_to_server = [];
- /**
- * Server signature
- *
- * Verified against $this->session_id
- *
- * @see self::getServerPublicHostKey()
- * @var string
- * @access private
- */
- private $signature = '';
- /**
- * Server signature format
- *
- * ssh-rsa or ssh-dss.
- *
- * @see self::getServerPublicHostKey()
- * @var string
- * @access private
- */
- private $signature_format = '';
- /**
- * Interactive Buffer
- *
- * @see self::read()
- * @var array
- * @access private
- */
- private $interactiveBuffer = '';
- /**
- * Current log size
- *
- * Should never exceed self::LOG_MAX_SIZE
- *
- * @see self::_send_binary_packet()
- * @see self::_get_binary_packet()
- * @var int
- * @access private
- */
- private $log_size;
- /**
- * Timeout
- *
- * @see self::setTimeout()
- * @access private
- */
- protected $timeout;
- /**
- * Current Timeout
- *
- * @see self::get_channel_packet()
- * @access private
- */
- protected $curTimeout;
- /**
- * Keep Alive Interval
- *
- * @see self::setKeepAlive()
- * @access private
- */
- private $keepAlive;
- /**
- * Real-time log file pointer
- *
- * @see self::_append_log()
- * @var resource
- * @access private
- */
- private $realtime_log_file;
- /**
- * Real-time log file size
- *
- * @see self::_append_log()
- * @var int
- * @access private
- */
- private $realtime_log_size;
- /**
- * Has the signature been validated?
- *
- * @see self::getServerPublicHostKey()
- * @var bool
- * @access private
- */
- private $signature_validated = false;
- /**
- * Real-time log file wrap boolean
- *
- * @see self::_append_log()
- * @access private
- */
- private $realtime_log_wrap;
- /**
- * Flag to suppress stderr from output
- *
- * @see self::enableQuietMode()
- * @access private
- */
- private $quiet_mode = false;
- /**
- * Time of first network activity
- *
- * @var int
- * @access private
- */
- private $last_packet;
- /**
- * Exit status returned from ssh if any
- *
- * @var int
- * @access private
- */
- private $exit_status;
- /**
- * Flag to request a PTY when using exec()
- *
- * @var bool
- * @see self::enablePTY()
- * @access private
- */
- private $request_pty = false;
- /**
- * Flag set while exec() is running when using enablePTY()
- *
- * @var bool
- * @access private
- */
- private $in_request_pty_exec = false;
- /**
- * Flag set after startSubsystem() is called
- *
- * @var bool
- * @access private
- */
- private $in_subsystem;
- /**
- * Contents of stdError
- *
- * @var string
- * @access private
- */
- private $stdErrorLog;
- /**
- * The Last Interactive Response
- *
- * @see self::_keyboard_interactive_process()
- * @var string
- * @access private
- */
- private $last_interactive_response = '';
- /**
- * Keyboard Interactive Request / Responses
- *
- * @see self::_keyboard_interactive_process()
- * @var array
- * @access private
- */
- private $keyboard_requests_responses = [];
- /**
- * Banner Message
- *
- * Quoting from the RFC, "in some jurisdictions, sending a warning message before
- * authentication may be relevant for getting legal protection."
- *
- * @see self::_filter()
- * @see self::getBannerMessage()
- * @var string
- * @access private
- */
- private $banner_message = '';
- /**
- * Did read() timeout or return normally?
- *
- * @see self::isTimeout()
- * @var bool
- * @access private
- */
- private $is_timeout = false;
- /**
- * Log Boundary
- *
- * @see self::_format_log()
- * @var string
- * @access private
- */
- private $log_boundary = ':';
- /**
- * Log Long Width
- *
- * @see self::_format_log()
- * @var int
- * @access private
- */
- private $log_long_width = 65;
- /**
- * Log Short Width
- *
- * @see self::_format_log()
- * @var int
- * @access private
- */
- private $log_short_width = 16;
- /**
- * Hostname
- *
- * @see self::__construct()
- * @see self::_connect()
- * @var string
- * @access private
- */
- private $host;
- /**
- * Port Number
- *
- * @see self::__construct()
- * @see self::_connect()
- * @var int
- * @access private
- */
- private $port;
- /**
- * Number of columns for terminal window size
- *
- * @see self::getWindowColumns()
- * @see self::setWindowColumns()
- * @see self::setWindowSize()
- * @var int
- * @access private
- */
- private $windowColumns = 80;
- /**
- * Number of columns for terminal window size
- *
- * @see self::getWindowRows()
- * @see self::setWindowRows()
- * @see self::setWindowSize()
- * @var int
- * @access private
- */
- private $windowRows = 24;
- /**
- * Crypto Engine
- *
- * @see self::setCryptoEngine()
- * @see self::_key_exchange()
- * @var int
- * @access private
- */
- private static $crypto_engine = false;
- /**
- * A System_SSH_Agent for use in the SSH2 Agent Forwarding scenario
- *
- * @var \phpseclib3\System\Ssh\Agent
- * @access private
- */
- private $agent;
- /**
- * Connection storage to replicates ssh2 extension functionality:
- * {@link http://php.net/manual/en/wrappers.ssh2.php#refsect1-wrappers.ssh2-examples}
- *
- * @var SSH2[]
- */
- private static $connections;
- /**
- * Send the identification string first?
- *
- * @var bool
- * @access private
- */
- private $send_id_string_first = true;
- /**
- * Send the key exchange initiation packet first?
- *
- * @var bool
- * @access private
- */
- private $send_kex_first = true;
- /**
- * Some versions of OpenSSH incorrectly calculate the key size
- *
- * @var bool
- * @access private
- */
- private $bad_key_size_fix = false;
- /**
- * Should we try to re-connect to re-establish keys?
- *
- * @var bool
- * @access private
- */
- private $retry_connect = false;
- /**
- * Binary Packet Buffer
- *
- * @var string|false
- * @access private
- */
- private $binary_packet_buffer = false;
- /**
- * Preferred Signature Format
- *
- * @var string|false
- * @access private
- */
- protected $preferred_signature_format = false;
- /**
- * Authentication Credentials
- *
- * @var array
- * @access private
- */
- protected $auth = [];
- /**
- * Terminal
- *
- * @var string
- * @access private
- */
- private $term = 'vt100';
- /**
- * The authentication methods that may productively continue authentication.
- *
- * @see https://tools.ietf.org/html/rfc4252#section-5.1
- * @var array|null
- * @access private
- */
- private $auth_methods_to_continue = null;
- /**
- * Compression method
- *
- * @var int
- * @access private
- */
- private $compress = NET_SSH2_COMPRESSION_NONE;
- /**
- * Decompression method
- *
- * @var resource|object
- * @access private
- */
- private $decompress = NET_SSH2_COMPRESSION_NONE;
- /**
- * Compression context
- *
- * @var int
- * @access private
- */
- private $compress_context;
- /**
- * Decompression context
- *
- * @var resource|object
- * @access private
- */
- private $decompress_context;
- /**
- * Regenerate Compression Context
- *
- * @var bool
- * @access private
- */
- private $regenerate_compression_context = false;
- /**
- * Regenerate Decompression Context
- *
- * @var bool
- * @access private
- */
- private $regenerate_decompression_context = false;
- /**
- * Smart multi-factor authentication flag
- *
- * @var bool
- * @access private
- */
- private $smartMFA = true;
- /**
- * Default Constructor.
- *
- * $host can either be a string, representing the host, or a stream resource.
- *
- * @param mixed $host
- * @param int $port
- * @param int $timeout
- * @see self::login()
- * @return SSH2|void
- * @access public
- */
- public function __construct($host, $port = 22, $timeout = 10)
- {
- $this->message_numbers = [
- 1 => 'NET_SSH2_MSG_DISCONNECT',
- 2 => 'NET_SSH2_MSG_IGNORE',
- 3 => 'NET_SSH2_MSG_UNIMPLEMENTED',
- 4 => 'NET_SSH2_MSG_DEBUG',
- 5 => 'NET_SSH2_MSG_SERVICE_REQUEST',
- 6 => 'NET_SSH2_MSG_SERVICE_ACCEPT',
- 20 => 'NET_SSH2_MSG_KEXINIT',
- 21 => 'NET_SSH2_MSG_NEWKEYS',
- 30 => 'NET_SSH2_MSG_KEXDH_INIT',
- 31 => 'NET_SSH2_MSG_KEXDH_REPLY',
- 50 => 'NET_SSH2_MSG_USERAUTH_REQUEST',
- 51 => 'NET_SSH2_MSG_USERAUTH_FAILURE',
- 52 => 'NET_SSH2_MSG_USERAUTH_SUCCESS',
- 53 => 'NET_SSH2_MSG_USERAUTH_BANNER',
- 80 => 'NET_SSH2_MSG_GLOBAL_REQUEST',
- 81 => 'NET_SSH2_MSG_REQUEST_SUCCESS',
- 82 => 'NET_SSH2_MSG_REQUEST_FAILURE',
- 90 => 'NET_SSH2_MSG_CHANNEL_OPEN',
- 91 => 'NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION',
- 92 => 'NET_SSH2_MSG_CHANNEL_OPEN_FAILURE',
- 93 => 'NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST',
- 94 => 'NET_SSH2_MSG_CHANNEL_DATA',
- 95 => 'NET_SSH2_MSG_CHANNEL_EXTENDED_DATA',
- 96 => 'NET_SSH2_MSG_CHANNEL_EOF',
- 97 => 'NET_SSH2_MSG_CHANNEL_CLOSE',
- 98 => 'NET_SSH2_MSG_CHANNEL_REQUEST',
- 99 => 'NET_SSH2_MSG_CHANNEL_SUCCESS',
- 100 => 'NET_SSH2_MSG_CHANNEL_FAILURE'
- ];
- $this->disconnect_reasons = [
- 1 => 'NET_SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT',
- 2 => 'NET_SSH2_DISCONNECT_PROTOCOL_ERROR',
- 3 => 'NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED',
- 4 => 'NET_SSH2_DISCONNECT_RESERVED',
- 5 => 'NET_SSH2_DISCONNECT_MAC_ERROR',
- 6 => 'NET_SSH2_DISCONNECT_COMPRESSION_ERROR',
- 7 => 'NET_SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE',
- 8 => 'NET_SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED',
- 9 => 'NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE',
- 10 => 'NET_SSH2_DISCONNECT_CONNECTION_LOST',
- 11 => 'NET_SSH2_DISCONNECT_BY_APPLICATION',
- 12 => 'NET_SSH2_DISCONNECT_TOO_MANY_CONNECTIONS',
- 13 => 'NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER',
- 14 => 'NET_SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE',
- 15 => 'NET_SSH2_DISCONNECT_ILLEGAL_USER_NAME'
- ];
- $this->channel_open_failure_reasons = [
- 1 => 'NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED'
- ];
- $this->terminal_modes = [
- 0 => 'NET_SSH2_TTY_OP_END'
- ];
- $this->channel_extended_data_type_codes = [
- 1 => 'NET_SSH2_EXTENDED_DATA_STDERR'
- ];
- $this->define_array(
- $this->message_numbers,
- $this->disconnect_reasons,
- $this->channel_open_failure_reasons,
- $this->terminal_modes,
- $this->channel_extended_data_type_codes,
- [60 => 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ'],
- [60 => 'NET_SSH2_MSG_USERAUTH_PK_OK'],
- [60 => 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST',
- 61 => 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE'],
- // RFC 4419 - diffie-hellman-group-exchange-sha{1,256}
- [30 => 'NET_SSH2_MSG_KEXDH_GEX_REQUEST_OLD',
- 31 => 'NET_SSH2_MSG_KEXDH_GEX_GROUP',
- 32 => 'NET_SSH2_MSG_KEXDH_GEX_INIT',
- 33 => 'NET_SSH2_MSG_KEXDH_GEX_REPLY',
- 34 => 'NET_SSH2_MSG_KEXDH_GEX_REQUEST'],
- // RFC 5656 - Elliptic Curves (for curve25519-sha256@libssh.org)
- [30 => 'NET_SSH2_MSG_KEX_ECDH_INIT',
- 31 => 'NET_SSH2_MSG_KEX_ECDH_REPLY']
- );
- self::$connections[$this->getResourceId()] = class_exists('WeakReference') ? \WeakReference::create($this) : $this;
- if (is_resource($host)) {
- $this->fsock = $host;
- return;
- }
- if (is_string($host)) {
- $this->host = $host;
- $this->port = $port;
- $this->timeout = $timeout;
- }
- }
- /**
- * Set Crypto Engine Mode
- *
- * Possible $engine values:
- * OpenSSL, mcrypt, Eval, PHP
- *
- * @param int $engine
- * @access public
- */
- public static function setCryptoEngine($engine)
- {
- self::$crypto_engine = $engine;
- }
- /**
- * 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
- *
- * @access public
- */
- public function sendIdentificationStringFirst()
- {
- $this->send_id_string_first = true;
- }
- /**
- * 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
- *
- * @access public
- */
- public function sendIdentificationStringLast()
- {
- $this->send_id_string_first = false;
- }
- /**
- * 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
- *
- * @access public
- */
- public function sendKEXINITFirst()
- {
- $this->send_kex_first = true;
- }
- /**
- * 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
- *
- * @access public
- */
- public function sendKEXINITLast()
- {
- $this->send_kex_first = false;
- }
- /**
- * Connect to an SSHv2 server
- *
- * @throws \UnexpectedValueException on receipt of unexpected packets
- * @throws \RuntimeException on other errors
- * @access private
- */
- private function connect()
- {
- if ($this->bitmap & self::MASK_CONSTRUCTOR) {
- return;
- }
- $this->bitmap |= self::MASK_CONSTRUCTOR;
- $this->curTimeout = $this->timeout;
- $this->last_packet = microtime(true);
- if (!is_resource($this->fsock)) {
- $start = microtime(true);
- // with stream_select a timeout of 0 means that no timeout takes place;
- // with fsockopen a timeout of 0 means that you instantly timeout
- // to resolve this incompatibility a timeout of 100,000 will be used for fsockopen if timeout is 0
- $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->curTimeout == 0 ? 100000 : $this->curTimeout);
- if (!$this->fsock) {
- $host = $this->host . ':' . $this->port;
- throw new UnableToConnectException(rtrim("Cannot connect to $host. Error $errno. $errstr"));
- }
- $elapsed = microtime(true) - $start;
- if ($this->curTimeout) {
- $this->curTimeout-= $elapsed;
- if ($this->curTimeout < 0) {
- throw new \RuntimeException('Connection timed out whilst attempting to open socket connection');
- }
- }
- }
- $this->identifier = $this->generate_identifier();
- if ($this->send_id_string_first) {
- fputs($this->fsock, $this->identifier . "\r\n");
- }
- /* According to the SSH2 specs,
- "The server MAY send other lines of data before sending the version
- string. Each line SHOULD be terminated by a Carriage Return and Line
- Feed. Such lines MUST NOT begin with "SSH-", and SHOULD be encoded
- in ISO-10646 UTF-8 [RFC3629] (language is not specified). Clients
- MUST be able to process such lines." */
- $data = '';
- while (!feof($this->fsock) && !preg_match('#(.*)^(SSH-(\d\.\d+).*)#ms', $data, $matches)) {
- $line = '';
- while (true) {
- if ($this->curTimeout) {
- if ($this->curTimeout < 0) {
- throw new \RuntimeException('Connection timed out whilst receiving server identification string');
- }
- $read = [$this->fsock];
- $write = $except = null;
- $start = microtime(true);
- $sec = floor($this->curTimeout);
- $usec = 1000000 * ($this->curTimeout - $sec);
- if (@stream_select($read, $write, $except, $sec, $usec) === false) {
- throw new \RuntimeException('Connection timed out whilst receiving server identification string');
- }
- $elapsed = microtime(true) - $start;
- $this->curTimeout-= $elapsed;
- }
- $temp = stream_get_line($this->fsock, 255, "\n");
- if ($temp === false) {
- throw new \RuntimeException('Error reading from socket');
- }
- if (strlen($temp) == 255) {
- continue;
- }
- $line.= "$temp\n";
- // quoting RFC4253, "Implementers who wish to maintain
- // compatibility with older, undocumented versions of this protocol may
- // want to process the identification string without expecting the
- // presence of the carriage return character for reasons described in
- // Section 5 of this document."
- //if (substr($line, -2) == "\r\n") {
- // break;
- //}
- break;
- }
- $data.= $line;
- }
- if (feof($this->fsock)) {
- $this->bitmap = 0;
- throw new ConnectionClosedException('Connection closed by server');
- }
- $extra = $matches[1];
- if (defined('NET_SSH2_LOGGING')) {
- $this->append_log('<-', $matches[0]);
- $this->append_log('->', $this->identifier . "\r\n");
- }
- $this->server_identifier = trim($temp, "\r\n");
- if (strlen($extra)) {
- $this->errors[] = $data;
- }
- if (version_compare($matches[3], '1.99', '<')) {
- $this->bitmap = 0;
- throw new UnableToConnectException("Cannot connect to SSH $matches[3] servers");
- }
- if (!$this->send_id_string_first) {
- fputs($this->fsock, $this->identifier . "\r\n");
- }
- if (!$this->send_kex_first) {
- $response = $this->get_binary_packet();
- if (!strlen($response) || ord($response[0]) != NET_SSH2_MSG_KEXINIT) {
- $this->bitmap = 0;
- throw new \UnexpectedValueException('Expected SSH_MSG_KEXINIT');
- }
- $this->key_exchange($response);
- }
- if ($this->send_kex_first) {
- $this->key_exchange();
- }
- $this->bitmap|= self::MASK_CONNECTED;
- return true;
- }
- /**
- * Generates the SSH identifier
- *
- * You should overwrite this method in your own class if you want to use another identifier
- *
- * @access protected
- * @return string
- */
- private function generate_identifier()
- {
- $identifier = 'SSH-2.0-phpseclib_3.0';
- $ext = [];
- if (extension_loaded('sodium')) {
- $ext[] = 'libsodium';
- }
- if (extension_loaded('openssl')) {
- $ext[] = 'openssl';
- } elseif (extension_loaded('mcrypt')) {
- $ext[] = 'mcrypt';
- }
- if (extension_loaded('gmp')) {
- $ext[] = 'gmp';
- } elseif (extension_loaded('bcmath')) {
- $ext[] = 'bcmath';
- }
- if (!empty($ext)) {
- $identifier .= ' (' . implode(', ', $ext) . ')';
- }
- return $identifier;
- }
- /**
- * Key Exchange
- *
- * @return bool
- * @param string|bool $kexinit_payload_server optional
- * @throws \UnexpectedValueException on receipt of unexpected packets
- * @throws \RuntimeException on other errors
- * @throws \phpseclib3\Exception\NoSupportedAlgorithmsException when none of the algorithms phpseclib has loaded are compatible
- * @access private
- */
- private function key_exchange($kexinit_payload_server = false)
- {
- $preferred = $this->preferred;
- $send_kex = true;
- $kex_algorithms = isset($preferred['kex']) ?
- $preferred['kex'] :
- SSH2::getSupportedKEXAlgorithms();
- $server_host_key_algorithms = isset($preferred['hostkey']) ?
- $preferred['hostkey'] :
- SSH2::getSupportedHostKeyAlgorithms();
- $s2c_encryption_algorithms = isset($preferred['server_to_client']['crypt']) ?
- $preferred['server_to_client']['crypt'] :
- SSH2::getSupportedEncryptionAlgorithms();
- $c2s_encryption_algorithms = isset($preferred['client_to_server']['crypt']) ?
- $preferred['client_to_server']['crypt'] :
- SSH2::getSupportedEncryptionAlgorithms();
- $s2c_mac_algorithms = isset($preferred['server_to_client']['mac']) ?
- $preferred['server_to_client']['mac'] :
- SSH2::getSupportedMACAlgorithms();
- $c2s_mac_algorithms = isset($preferred['client_to_server']['mac']) ?
- $preferred['client_to_server']['mac'] :
- SSH2::getSupportedMACAlgorithms();
- $s2c_compression_algorithms = isset($preferred['server_to_client']['comp']) ?
- $preferred['server_to_client']['comp'] :
- SSH2::getSupportedCompressionAlgorithms();
- $c2s_compression_algorithms = isset($preferred['client_to_server']['comp']) ?
- $preferred['client_to_server']['comp'] :
- SSH2::getSupportedCompressionAlgorithms();
- // some SSH servers have buggy implementations of some of the above algorithms
- switch (true) {
- case $this->server_identifier == 'SSH-2.0-SSHD':
- case substr($this->server_identifier, 0, 13) == 'SSH-2.0-DLINK':
- if (!isset($preferred['server_to_client']['mac'])) {
- $s2c_mac_algorithms = array_values(array_diff(
- $s2c_mac_algorithms,
- ['hmac-sha1-96', 'hmac-md5-96']
- ));
- }
- if (!isset($preferred['client_to_server']['mac'])) {
- $c2s_mac_algorithms = array_values(array_diff(
- $c2s_mac_algorithms,
- ['hmac-sha1-96', 'hmac-md5-96']
- ));
- }
- }
- $client_cookie = Random::string(16);
- $kexinit_payload_client = pack('Ca*', NET_SSH2_MSG_KEXINIT, $client_cookie);
- $kexinit_payload_client.= Strings::packSSH2(
- 'L10bN',
- $kex_algorithms,
- $server_host_key_algorithms,
- $c2s_encryption_algorithms,
- $s2c_encryption_algorithms,
- $c2s_mac_algorithms,
- $s2c_mac_algorithms,
- $c2s_compression_algorithms,
- $s2c_compression_algorithms,
- [], // language, client to server
- [], // language, server to client
- false, // first_kex_packet_follows
- 0 // reserved for future extension
- );
- if ($kexinit_payload_server === false) {
- $this->send_binary_packet($kexinit_payload_client);
- $kexinit_payload_server = $this->get_binary_packet();
- if (!strlen($kexinit_payload_server) || ord($kexinit_payload_server[0]) != NET_SSH2_MSG_KEXINIT) {
- $this->disconnect_helper(NET_SSH2_DISCONNECT_PROTOCOL_ERROR);
- throw new \UnexpectedValueException('Expected SSH_MSG_KEXINIT');
- }
- $send_kex = false;
- }
- $response = $kexinit_payload_server;
- Strings::shift($response, 1); // skip past the message number (it should be SSH_MSG_KEXINIT)
- $server_cookie = Strings::shift($response, 16);
- list(
- $this->kex_algorithms,
- $this->server_host_key_algorithms,
- $this->encryption_algorithms_client_to_server,
- $this->encryption_algorithms_server_to_client,
- $this->mac_algorithms_client_to_server,
- $this->mac_algorithms_server_to_client,
- $this->compression_algorithms_client_to_server,
- $this->compression_algorithms_server_to_client,
- $this->languages_client_to_server,
- $this->languages_server_to_client,
- $first_kex_packet_follows
- ) = Strings::unpackSSH2('L10C', $response);
- if ($send_kex) {
- $this->send_binary_packet($kexinit_payload_client);
- }
- // we need to decide upon the symmetric encryption algorithms before we do the diffie-hellman key exchange
- // we don't initialize any crypto-objects, yet - we do that, later. for now, we need the lengths to make the
- // diffie-hellman key exchange as fast as possible
- $decrypt = self::array_intersect_first($s2c_encryption_algorithms, $this->encryption_algorithms_server_to_client);
- $decryptKeyLength = $this->encryption_algorithm_to_key_size($decrypt);
- if ($decryptKeyLength === null) {
- $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible server to client encryption algorithms found');
- }
- $encrypt = self::array_intersect_first($c2s_encryption_algorithms, $this->encryption_algorithms_client_to_server);
- $encryptKeyLength = $this->encryption_algorithm_to_key_size($encrypt);
- if ($encryptKeyLength === null) {
- $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible client to server encryption algorithms found');
- }
- // through diffie-hellman key exchange a symmetric key is obtained
- $this->kex_algorithm = self::array_intersect_first($kex_algorithms, $this->kex_algorithms);
- if ($this->kex_algorithm === false) {
- $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible key exchange algorithms found');
- }
- $server_host_key_algorithm = self::array_intersect_first($server_host_key_algorithms, $this->server_host_key_algorithms);
- if ($server_host_key_algorithm === false) {
- $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible server host key algorithms found');
- }
- $mac_algorithm_out = self::array_intersect_first($c2s_mac_algorithms, $this->mac_algorithms_client_to_server);
- if ($mac_algorithm_out === false) {
- $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible client to server message authentication algorithms found');
- }
- $mac_algorithm_in = self::array_intersect_first($s2c_mac_algorithms, $this->mac_algorithms_server_to_client);
- if ($mac_algorithm_in === false) {
- $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible server to client message authentication algorithms found');
- }
- $compression_map = [
- 'none' => NET_SSH2_COMPRESSION_NONE,
- 'zlib' => NET_SSH2_COMPRESSION_ZLIB,
- 'zlib@openssh.com' => NET_SSH2_COMPRESSION_ZLIB_AT_OPENSSH
- ];
- $compression_algorithm_in = self::array_intersect_first($s2c_compression_algorithms, $this->compression_algorithms_server_to_client);
- if ($compression_algorithm_in === false) {
- $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible server to client compression algorithms found');
- }
- $this->decompress = $compression_map[$compression_algorithm_in];
- $compression_algorithm_out = self::array_intersect_first($c2s_compression_algorithms, $this->compression_algorithms_client_to_server);
- if ($compression_algorithm_out === false) {
- $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible client to server compression algorithms found');
- }
- $this->compress = $compression_map[$compression_algorithm_out];
- switch ($this->kex_algorithm) {
- case 'diffie-hellman-group15-sha512':
- case 'diffie-hellman-group16-sha512':
- case 'diffie-hellman-group17-sha512':
- case 'diffie-hellman-group18-sha512':
- case 'ecdh-sha2-nistp521':
- $kexHash = new Hash('sha512');
- break;
- case 'ecdh-sha2-nistp384':
- $kexHash = new Hash('sha384');
- break;
- case 'diffie-hellman-group-exchange-sha256':
- case 'diffie-hellman-group14-sha256':
- case 'ecdh-sha2-nistp256':
- case 'curve25519-sha256@libssh.org':
- case 'curve25519-sha256':
- $kexHash = new Hash('sha256');
- break;
- default:
- $kexHash = new Hash('sha1');
- }
- // Only relevant in diffie-hellman-group-exchange-sha{1,256}, otherwise empty.
- $exchange_hash_rfc4419 = '';
- if (strpos($this->kex_algorithm, 'curve25519-sha256') === 0 || strpos($this->kex_algorithm, 'ecdh-sha2-nistp') === 0) {
- $curve = strpos($this->kex_algorithm, 'curve25519-sha256') === 0 ?
- 'Curve25519' :
- substr($this->kex_algorithm, 10);
- $ourPrivate = EC::createKey($curve);
- $ourPublicBytes = $ourPrivate->getPublicKey()->getEncodedCoordinates();
- $clientKexInitMessage = 'NET_SSH2_MSG_KEX_ECDH_INIT';
- $serverKexReplyMessage = 'NET_SSH2_MSG_KEX_ECDH_REPLY';
- } else {
- if (strpos($this->kex_algorithm, 'diffie-hellman-group-exchange') === 0) {
- $dh_group_sizes_packed = pack(
- 'NNN',
- $this->kex_dh_group_size_min,
- $this->kex_dh_group_size_preferred,
- $this->kex_dh_group_size_max
- );
- $packet = pack(
- 'Ca*',
- NET_SSH2_MSG_KEXDH_GEX_REQUEST,
- $dh_group_sizes_packed
- );
- $this->send_binary_packet($packet);
- $this->updateLogHistory('UNKNOWN (34)', 'NET_SSH2_MSG_KEXDH_GEX_REQUEST');
- $response = $this->get_binary_packet();
- list($type, $primeBytes, $gBytes) = Strings::unpackSSH2('Css', $response);
- if ($type != NET_SSH2_MSG_KEXDH_GEX_GROUP) {
- $this->disconnect_helper(NET_SSH2_DISCONNECT_PROTOCOL_ERROR);
- throw new \UnexpectedValueException('Expected SSH_MSG_KEX_DH_GEX_GROUP');
- }
- $this->updateLogHistory('NET_SSH2_MSG_KEXDH_REPLY', 'NET_SSH2_MSG_KEXDH_GEX_GROUP');
- $prime = new BigInteger($primeBytes, -256);
- $g = new BigInteger($gBytes, -256);
- $exchange_hash_rfc4419 = $dh_group_sizes_packed . Strings::packSSH2(
- 'ss',
- $primeBytes,
- $gBytes
- );
- $params = DH::createParameters($prime, $g);
- $clientKexInitMessage = 'NET_SSH2_MSG_KEXDH_GEX_INIT';
- $serverKexReplyMessage = 'NET_SSH2_MSG_KEXDH_GEX_REPLY';
- } else {
- $params = DH::createParameters($this->kex_algorithm);
- $clientKexInitMessage = 'NET_SSH2_MSG_KEXDH_INIT';
- $serverKexReplyMessage = 'NET_SSH2_MSG_KEXDH_REPLY';
- }
- $keyLength = min($kexHash->getLengthInBytes(), max($encryptKeyLen…