PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/fuelphp/fuel/core/vendor/phpseclib/Net/SSH2.php

http://github.com/eryx/php-framework-benchmark
PHP | 2633 lines | 1405 code | 317 blank | 911 comment | 227 complexity | 8cdc353c64ec6d08b66ce1b284d72410 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, Apache-2.0, LGPL-2.1, LGPL-3.0, BSD-2-Clause
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. namespace PHPSecLib;
  4. /**
  5. * Pure-PHP implementation of SSHv2.
  6. *
  7. * PHP versions 4 and 5
  8. *
  9. * Here are some examples of how to use this library:
  10. * <code>
  11. * <?php
  12. * include('Net/SSH2.php');
  13. *
  14. * $ssh = new Net_SSH2('www.domain.tld');
  15. * if (!$ssh->login('username', 'password')) {
  16. * exit('Login Failed');
  17. * }
  18. *
  19. * echo $ssh->exec('pwd');
  20. * echo $ssh->exec('ls -la');
  21. * ?>
  22. * </code>
  23. *
  24. * <code>
  25. * <?php
  26. * include('Crypt/RSA.php');
  27. * include('Net/SSH2.php');
  28. *
  29. * $key = new Crypt_RSA();
  30. * //$key->setPassword('whatever');
  31. * $key->loadKey(file_get_contents('privatekey'));
  32. *
  33. * $ssh = new Net_SSH2('www.domain.tld');
  34. * if (!$ssh->login('username', $key)) {
  35. * exit('Login Failed');
  36. * }
  37. *
  38. * echo $ssh->read('username@username:~$');
  39. * $ssh->write("ls -la\n");
  40. * echo $ssh->read('username@username:~$');
  41. * ?>
  42. * </code>
  43. *
  44. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  45. * of this software and associated documentation files (the "Software"), to deal
  46. * in the Software without restriction, including without limitation the rights
  47. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  48. * copies of the Software, and to permit persons to whom the Software is
  49. * furnished to do so, subject to the following conditions:
  50. *
  51. * The above copyright notice and this permission notice shall be included in
  52. * all copies or substantial portions of the Software.
  53. *
  54. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  55. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  56. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  57. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  58. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  59. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  60. * THE SOFTWARE.
  61. *
  62. * @category Net
  63. * @package Net_SSH2
  64. * @author Jim Wigginton <terrafrost@php.net>
  65. * @copyright MMVII Jim Wigginton
  66. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  67. * @version $Id: SSH2.php,v 1.53 2010-10-24 01:24:30 terrafrost Exp $
  68. * @link http://phpseclib.sourceforge.net
  69. */
  70. /**#@+
  71. * Crypt random global function
  72. *
  73. * @see Crypt/Random.php
  74. */
  75. require_once (__DIR__.DS.'../Crypt/Random.php');
  76. /**#@+
  77. * Execution Bitmap Masks
  78. *
  79. * @see Net_SSH2::bitmap
  80. * @access private
  81. */
  82. define('NET_SSH2_MASK_CONSTRUCTOR', 0x00000001);
  83. define('NET_SSH2_MASK_LOGIN', 0x00000002);
  84. define('NET_SSH2_MASK_SHELL', 0x00000004);
  85. /**#@-*/
  86. /**#@+
  87. * Channel constants
  88. *
  89. * RFC4254 refers not to client and server channels but rather to sender and recipient channels. we don't refer
  90. * to them in that way because RFC4254 toggles the meaning. the client sends a SSH_MSG_CHANNEL_OPEN message with
  91. * a sender channel and the server sends a SSH_MSG_CHANNEL_OPEN_CONFIRMATION in response, with a sender and a
  92. * recepient channel. at first glance, you might conclude that SSH_MSG_CHANNEL_OPEN_CONFIRMATION's sender channel
  93. * would be the same thing as SSH_MSG_CHANNEL_OPEN's sender channel, but it's not, per this snipet:
  94. * The 'recipient channel' is the channel number given in the original
  95. * open request, and 'sender channel' is the channel number allocated by
  96. * the other side.
  97. *
  98. * @see Net_SSH2::_send_channel_packet()
  99. * @see Net_SSH2::_get_channel_packet()
  100. * @access private
  101. */
  102. define('NET_SSH2_CHANNEL_EXEC', 0); // PuTTy uses 0x100
  103. define('NET_SSH2_CHANNEL_SHELL',1);
  104. /**#@-*/
  105. /**#@+
  106. * @access public
  107. * @see Net_SSH2::getLog()
  108. */
  109. /**
  110. * Returns the message numbers
  111. */
  112. define('NET_SSH2_LOG_SIMPLE', 1);
  113. /**
  114. * Returns the message content
  115. */
  116. define('NET_SSH2_LOG_COMPLEX', 2);
  117. /**#@-*/
  118. /**#@+
  119. * @access public
  120. * @see Net_SSH2::read()
  121. */
  122. /**
  123. * Returns when a string matching $expect exactly is found
  124. */
  125. define('NET_SSH2_READ_SIMPLE', 1);
  126. /**
  127. * Returns when a string matching the regular expression $expect is found
  128. */
  129. define('NET_SSH2_READ_REGEX', 2);
  130. /**#@-*/
  131. /**
  132. * Pure-PHP implementation of SSHv2.
  133. *
  134. * @author Jim Wigginton <terrafrost@php.net>
  135. * @version 0.1.0
  136. * @access public
  137. * @package Net_SSH2
  138. */
  139. class Net_SSH2 {
  140. /**
  141. * The SSH identifier
  142. *
  143. * @var String
  144. * @access private
  145. */
  146. var $identifier = 'SSH-2.0-phpseclib_0.2';
  147. /**
  148. * The Socket Object
  149. *
  150. * @var Object
  151. * @access private
  152. */
  153. var $fsock;
  154. /**
  155. * Execution Bitmap
  156. *
  157. * The bits that are set reprsent functions that have been called already. This is used to determine
  158. * if a requisite function has been successfully executed. If not, an error should be thrown.
  159. *
  160. * @var Integer
  161. * @access private
  162. */
  163. var $bitmap = 0;
  164. /**
  165. * Error information
  166. *
  167. * @see Net_SSH2::getErrors()
  168. * @see Net_SSH2::getLastError()
  169. * @var String
  170. * @access private
  171. */
  172. var $errors = array();
  173. /**
  174. * Server Identifier
  175. *
  176. * @see Net_SSH2::getServerIdentification()
  177. * @var String
  178. * @access private
  179. */
  180. var $server_identifier = '';
  181. /**
  182. * Key Exchange Algorithms
  183. *
  184. * @see Net_SSH2::getKexAlgorithims()
  185. * @var Array
  186. * @access private
  187. */
  188. var $kex_algorithms;
  189. /**
  190. * Server Host Key Algorithms
  191. *
  192. * @see Net_SSH2::getServerHostKeyAlgorithms()
  193. * @var Array
  194. * @access private
  195. */
  196. var $server_host_key_algorithms;
  197. /**
  198. * Encryption Algorithms: Client to Server
  199. *
  200. * @see Net_SSH2::getEncryptionAlgorithmsClient2Server()
  201. * @var Array
  202. * @access private
  203. */
  204. var $encryption_algorithms_client_to_server;
  205. /**
  206. * Encryption Algorithms: Server to Client
  207. *
  208. * @see Net_SSH2::getEncryptionAlgorithmsServer2Client()
  209. * @var Array
  210. * @access private
  211. */
  212. var $encryption_algorithms_server_to_client;
  213. /**
  214. * MAC Algorithms: Client to Server
  215. *
  216. * @see Net_SSH2::getMACAlgorithmsClient2Server()
  217. * @var Array
  218. * @access private
  219. */
  220. var $mac_algorithms_client_to_server;
  221. /**
  222. * MAC Algorithms: Server to Client
  223. *
  224. * @see Net_SSH2::getMACAlgorithmsServer2Client()
  225. * @var Array
  226. * @access private
  227. */
  228. var $mac_algorithms_server_to_client;
  229. /**
  230. * Compression Algorithms: Client to Server
  231. *
  232. * @see Net_SSH2::getCompressionAlgorithmsClient2Server()
  233. * @var Array
  234. * @access private
  235. */
  236. var $compression_algorithms_client_to_server;
  237. /**
  238. * Compression Algorithms: Server to Client
  239. *
  240. * @see Net_SSH2::getCompressionAlgorithmsServer2Client()
  241. * @var Array
  242. * @access private
  243. */
  244. var $compression_algorithms_server_to_client;
  245. /**
  246. * Languages: Server to Client
  247. *
  248. * @see Net_SSH2::getLanguagesServer2Client()
  249. * @var Array
  250. * @access private
  251. */
  252. var $languages_server_to_client;
  253. /**
  254. * Languages: Client to Server
  255. *
  256. * @see Net_SSH2::getLanguagesClient2Server()
  257. * @var Array
  258. * @access private
  259. */
  260. var $languages_client_to_server;
  261. /**
  262. * Block Size for Server to Client Encryption
  263. *
  264. * "Note that the length of the concatenation of 'packet_length',
  265. * 'padding_length', 'payload', and 'random padding' MUST be a multiple
  266. * of the cipher block size or 8, whichever is larger. This constraint
  267. * MUST be enforced, even when using stream ciphers."
  268. *
  269. * -- http://tools.ietf.org/html/rfc4253#section-6
  270. *
  271. * @see Net_SSH2::Net_SSH2()
  272. * @see Net_SSH2::_send_binary_packet()
  273. * @var Integer
  274. * @access private
  275. */
  276. var $encrypt_block_size = 8;
  277. /**
  278. * Block Size for Client to Server Encryption
  279. *
  280. * @see Net_SSH2::Net_SSH2()
  281. * @see Net_SSH2::_get_binary_packet()
  282. * @var Integer
  283. * @access private
  284. */
  285. var $decrypt_block_size = 8;
  286. /**
  287. * Server to Client Encryption Object
  288. *
  289. * @see Net_SSH2::_get_binary_packet()
  290. * @var Object
  291. * @access private
  292. */
  293. var $decrypt = false;
  294. /**
  295. * Client to Server Encryption Object
  296. *
  297. * @see Net_SSH2::_send_binary_packet()
  298. * @var Object
  299. * @access private
  300. */
  301. var $encrypt = false;
  302. /**
  303. * Client to Server HMAC Object
  304. *
  305. * @see Net_SSH2::_send_binary_packet()
  306. * @var Object
  307. * @access private
  308. */
  309. var $hmac_create = false;
  310. /**
  311. * Server to Client HMAC Object
  312. *
  313. * @see Net_SSH2::_get_binary_packet()
  314. * @var Object
  315. * @access private
  316. */
  317. var $hmac_check = false;
  318. /**
  319. * Size of server to client HMAC
  320. *
  321. * 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.
  322. * 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
  323. * append it.
  324. *
  325. * @see Net_SSH2::_get_binary_packet()
  326. * @var Integer
  327. * @access private
  328. */
  329. var $hmac_size = false;
  330. /**
  331. * Server Public Host Key
  332. *
  333. * @see Net_SSH2::getServerPublicHostKey()
  334. * @var String
  335. * @access private
  336. */
  337. var $server_public_host_key;
  338. /**
  339. * Session identifer
  340. *
  341. * "The exchange hash H from the first key exchange is additionally
  342. * used as the session identifier, which is a unique identifier for
  343. * this connection."
  344. *
  345. * -- http://tools.ietf.org/html/rfc4253#section-7.2
  346. *
  347. * @see Net_SSH2::_key_exchange()
  348. * @var String
  349. * @access private
  350. */
  351. var $session_id = false;
  352. /**
  353. * Exchange hash
  354. *
  355. * The current exchange hash
  356. *
  357. * @see Net_SSH2::_key_exchange()
  358. * @var String
  359. * @access private
  360. */
  361. var $exchange_hash = false;
  362. /**
  363. * Message Numbers
  364. *
  365. * @see Net_SSH2::Net_SSH2()
  366. * @var Array
  367. * @access private
  368. */
  369. var $message_numbers = array();
  370. /**
  371. * Disconnection Message 'reason codes' defined in RFC4253
  372. *
  373. * @see Net_SSH2::Net_SSH2()
  374. * @var Array
  375. * @access private
  376. */
  377. var $disconnect_reasons = array();
  378. /**
  379. * SSH_MSG_CHANNEL_OPEN_FAILURE 'reason codes', defined in RFC4254
  380. *
  381. * @see Net_SSH2::Net_SSH2()
  382. * @var Array
  383. * @access private
  384. */
  385. var $channel_open_failure_reasons = array();
  386. /**
  387. * Terminal Modes
  388. *
  389. * @link http://tools.ietf.org/html/rfc4254#section-8
  390. * @see Net_SSH2::Net_SSH2()
  391. * @var Array
  392. * @access private
  393. */
  394. var $terminal_modes = array();
  395. /**
  396. * SSH_MSG_CHANNEL_EXTENDED_DATA's data_type_codes
  397. *
  398. * @link http://tools.ietf.org/html/rfc4254#section-5.2
  399. * @see Net_SSH2::Net_SSH2()
  400. * @var Array
  401. * @access private
  402. */
  403. var $channel_extended_data_type_codes = array();
  404. /**
  405. * Send Sequence Number
  406. *
  407. * See 'Section 6.4. Data Integrity' of rfc4253 for more info.
  408. *
  409. * @see Net_SSH2::_send_binary_packet()
  410. * @var Integer
  411. * @access private
  412. */
  413. var $send_seq_no = 0;
  414. /**
  415. * Get Sequence Number
  416. *
  417. * See 'Section 6.4. Data Integrity' of rfc4253 for more info.
  418. *
  419. * @see Net_SSH2::_get_binary_packet()
  420. * @var Integer
  421. * @access private
  422. */
  423. var $get_seq_no = 0;
  424. /**
  425. * Server Channels
  426. *
  427. * Maps client channels to server channels
  428. *
  429. * @see Net_SSH2::_get_channel_packet()
  430. * @see Net_SSH2::exec()
  431. * @var Array
  432. * @access private
  433. */
  434. var $server_channels = array();
  435. /**
  436. * Channel Buffers
  437. *
  438. * If a client requests a packet from one channel but receives two packets from another those packets should
  439. * be placed in a buffer
  440. *
  441. * @see Net_SSH2::_get_channel_packet()
  442. * @see Net_SSH2::exec()
  443. * @var Array
  444. * @access private
  445. */
  446. var $channel_buffers = array();
  447. /**
  448. * Channel Status
  449. *
  450. * Contains the type of the last sent message
  451. *
  452. * @see Net_SSH2::_get_channel_packet()
  453. * @var Array
  454. * @access private
  455. */
  456. var $channel_status = array();
  457. /**
  458. * Packet Size
  459. *
  460. * Maximum packet size indexed by channel
  461. *
  462. * @see Net_SSH2::_send_channel_packet()
  463. * @var Array
  464. * @access private
  465. */
  466. var $packet_size_client_to_server = array();
  467. /**
  468. * Message Number Log
  469. *
  470. * @see Net_SSH2::getLog()
  471. * @var Array
  472. * @access private
  473. */
  474. var $message_number_log = array();
  475. /**
  476. * Message Log
  477. *
  478. * @see Net_SSH2::getLog()
  479. * @var Array
  480. * @access private
  481. */
  482. var $message_log = array();
  483. /**
  484. * The Window Size
  485. *
  486. * Bytes the other party can send before it must wait for the window to be adjusted (0x7FFFFFFF = 4GB)
  487. *
  488. * @var Integer
  489. * @see Net_SSH2::_send_channel_packet()
  490. * @see Net_SSH2::exec()
  491. * @access private
  492. */
  493. var $window_size = 0x7FFFFFFF;
  494. /**
  495. * Window size
  496. *
  497. * Window size indexed by channel
  498. *
  499. * @see Net_SSH2::_send_channel_packet()
  500. * @var Array
  501. * @access private
  502. */
  503. var $window_size_client_to_server = array();
  504. /**
  505. * Server signature
  506. *
  507. * Verified against $this->session_id
  508. *
  509. * @see Net_SSH2::getServerPublicHostKey()
  510. * @var String
  511. * @access private
  512. */
  513. var $signature = '';
  514. /**
  515. * Server signature format
  516. *
  517. * ssh-rsa or ssh-dss.
  518. *
  519. * @see Net_SSH2::getServerPublicHostKey()
  520. * @var String
  521. * @access private
  522. */
  523. var $signature_format = '';
  524. /**
  525. * Interactive Buffer
  526. *
  527. * @see Net_SSH2::read()
  528. * @var Array
  529. * @access private
  530. */
  531. var $interactiveBuffer = '';
  532. /**
  533. * Default Constructor.
  534. *
  535. * Connects to an SSHv2 server
  536. *
  537. * @param String $host
  538. * @param optional Integer $port
  539. * @param optional Integer $timeout
  540. * @return Net_SSH2
  541. * @access public
  542. */
  543. function __construct($host, $port = 22, $timeout = 10)
  544. {
  545. $this->message_numbers = array(
  546. 1 => 'NET_SSH2_MSG_DISCONNECT',
  547. 2 => 'NET_SSH2_MSG_IGNORE',
  548. 3 => 'NET_SSH2_MSG_UNIMPLEMENTED',
  549. 4 => 'NET_SSH2_MSG_DEBUG',
  550. 5 => 'NET_SSH2_MSG_SERVICE_REQUEST',
  551. 6 => 'NET_SSH2_MSG_SERVICE_ACCEPT',
  552. 20 => 'NET_SSH2_MSG_KEXINIT',
  553. 21 => 'NET_SSH2_MSG_NEWKEYS',
  554. 30 => 'NET_SSH2_MSG_KEXDH_INIT',
  555. 31 => 'NET_SSH2_MSG_KEXDH_REPLY',
  556. 50 => 'NET_SSH2_MSG_USERAUTH_REQUEST',
  557. 51 => 'NET_SSH2_MSG_USERAUTH_FAILURE',
  558. 52 => 'NET_SSH2_MSG_USERAUTH_SUCCESS',
  559. 53 => 'NET_SSH2_MSG_USERAUTH_BANNER',
  560. 80 => 'NET_SSH2_MSG_GLOBAL_REQUEST',
  561. 81 => 'NET_SSH2_MSG_REQUEST_SUCCESS',
  562. 82 => 'NET_SSH2_MSG_REQUEST_FAILURE',
  563. 90 => 'NET_SSH2_MSG_CHANNEL_OPEN',
  564. 91 => 'NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION',
  565. 92 => 'NET_SSH2_MSG_CHANNEL_OPEN_FAILURE',
  566. 93 => 'NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST',
  567. 94 => 'NET_SSH2_MSG_CHANNEL_DATA',
  568. 95 => 'NET_SSH2_MSG_CHANNEL_EXTENDED_DATA',
  569. 96 => 'NET_SSH2_MSG_CHANNEL_EOF',
  570. 97 => 'NET_SSH2_MSG_CHANNEL_CLOSE',
  571. 98 => 'NET_SSH2_MSG_CHANNEL_REQUEST',
  572. 99 => 'NET_SSH2_MSG_CHANNEL_SUCCESS',
  573. 100 => 'NET_SSH2_MSG_CHANNEL_FAILURE'
  574. );
  575. $this->disconnect_reasons = array(
  576. 1 => 'NET_SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT',
  577. 2 => 'NET_SSH2_DISCONNECT_PROTOCOL_ERROR',
  578. 3 => 'NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED',
  579. 4 => 'NET_SSH2_DISCONNECT_RESERVED',
  580. 5 => 'NET_SSH2_DISCONNECT_MAC_ERROR',
  581. 6 => 'NET_SSH2_DISCONNECT_COMPRESSION_ERROR',
  582. 7 => 'NET_SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE',
  583. 8 => 'NET_SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED',
  584. 9 => 'NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE',
  585. 10 => 'NET_SSH2_DISCONNECT_CONNECTION_LOST',
  586. 11 => 'NET_SSH2_DISCONNECT_BY_APPLICATION',
  587. 12 => 'NET_SSH2_DISCONNECT_TOO_MANY_CONNECTIONS',
  588. 13 => 'NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER',
  589. 14 => 'NET_SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE',
  590. 15 => 'NET_SSH2_DISCONNECT_ILLEGAL_USER_NAME'
  591. );
  592. $this->channel_open_failure_reasons = array(
  593. 1 => 'NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED'
  594. );
  595. $this->terminal_modes = array(
  596. 0 => 'NET_SSH2_TTY_OP_END'
  597. );
  598. $this->channel_extended_data_type_codes = array(
  599. 1 => 'NET_SSH2_EXTENDED_DATA_STDERR'
  600. );
  601. $this->_define_array(
  602. $this->message_numbers,
  603. $this->disconnect_reasons,
  604. $this->channel_open_failure_reasons,
  605. $this->terminal_modes,
  606. $this->channel_extended_data_type_codes,
  607. array(60 => 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ'),
  608. array(60 => 'NET_SSH2_MSG_USERAUTH_PK_OK'),
  609. array(60 => 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST',
  610. 61 => 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE')
  611. );
  612. $this->fsock = @fsockopen($host, $port, $errno, $errstr, $timeout);
  613. if (!$this->fsock) {
  614. user_error(rtrim("Cannot connect to $host. Error $errno. $errstr"), E_USER_NOTICE);
  615. return;
  616. }
  617. /* According to the SSH2 specs,
  618. "The server MAY send other lines of data before sending the version
  619. string. Each line SHOULD be terminated by a Carriage Return and Line
  620. Feed. Such lines MUST NOT begin with "SSH-", and SHOULD be encoded
  621. in ISO-10646 UTF-8 [RFC3629] (language is not specified). Clients
  622. MUST be able to process such lines." */
  623. $temp = '';
  624. $extra = '';
  625. while (!feof($this->fsock) && !preg_match('#^SSH-(\d\.\d+)#', $temp, $matches)) {
  626. if (substr($temp, -2) == "\r\n") {
  627. $extra.= $temp;
  628. $temp = '';
  629. }
  630. $temp.= fgets($this->fsock, 255);
  631. }
  632. if (feof($this->fsock)) {
  633. user_error('Connection closed by server', E_USER_NOTICE);
  634. return false;
  635. }
  636. $ext = array();
  637. if (extension_loaded('mcrypt')) {
  638. $ext[] = 'mcrypt';
  639. }
  640. if (extension_loaded('gmp')) {
  641. $ext[] = 'gmp';
  642. } else if (extension_loaded('bcmath')) {
  643. $ext[] = 'bcmath';
  644. }
  645. if (!empty($ext)) {
  646. $this->identifier.= ' (' . implode(', ', $ext) . ')';
  647. }
  648. if (defined('NET_SSH2_LOGGING')) {
  649. $this->message_number_log[] = '<-';
  650. $this->message_number_log[] = '->';
  651. if (NET_SSH2_LOGGING == NET_SSH2_LOG_COMPLEX) {
  652. $this->message_log[] = $temp;
  653. $this->message_log[] = $this->identifier . "\r\n";
  654. }
  655. }
  656. $this->server_identifier = trim($temp, "\r\n");
  657. if (!empty($extra)) {
  658. $this->errors[] = utf8_decode($extra);
  659. }
  660. if ($matches[1] != '1.99' && $matches[1] != '2.0') {
  661. user_error("Cannot connect to SSH $matches[1] servers", E_USER_NOTICE);
  662. return;
  663. }
  664. fputs($this->fsock, $this->identifier . "\r\n");
  665. $response = $this->_get_binary_packet();
  666. if ($response === false) {
  667. user_error('Connection closed by server', E_USER_NOTICE);
  668. return;
  669. }
  670. if (ord($response[0]) != NET_SSH2_MSG_KEXINIT) {
  671. user_error('Expected SSH_MSG_KEXINIT', E_USER_NOTICE);
  672. return;
  673. }
  674. if (!$this->_key_exchange($response)) {
  675. return;
  676. }
  677. $this->bitmap = NET_SSH2_MASK_CONSTRUCTOR;
  678. }
  679. /**
  680. * Key Exchange
  681. *
  682. * @param String $kexinit_payload_server
  683. * @access private
  684. */
  685. function _key_exchange($kexinit_payload_server)
  686. {
  687. static $kex_algorithms = array(
  688. 'diffie-hellman-group1-sha1', // REQUIRED
  689. 'diffie-hellman-group14-sha1' // REQUIRED
  690. );
  691. static $server_host_key_algorithms = array(
  692. 'ssh-rsa', // RECOMMENDED sign Raw RSA Key
  693. 'ssh-dss' // REQUIRED sign Raw DSS Key
  694. );
  695. static $encryption_algorithms = array(
  696. // from <http://tools.ietf.org/html/rfc4345#section-4>:
  697. 'arcfour256',
  698. 'arcfour128',
  699. 'arcfour', // OPTIONAL the ARCFOUR stream cipher with a 128-bit key
  700. 'aes128-cbc', // RECOMMENDED AES with a 128-bit key
  701. 'aes192-cbc', // OPTIONAL AES with a 192-bit key
  702. 'aes256-cbc', // OPTIONAL AES in CBC mode, with a 256-bit key
  703. // from <http://tools.ietf.org/html/rfc4344#section-4>:
  704. 'aes128-ctr', // RECOMMENDED AES (Rijndael) in SDCTR mode, with 128-bit key
  705. 'aes192-ctr', // RECOMMENDED AES with 192-bit key
  706. 'aes256-ctr', // RECOMMENDED AES with 256-bit key
  707. '3des-ctr', // RECOMMENDED Three-key 3DES in SDCTR mode
  708. '3des-cbc', // REQUIRED three-key 3DES in CBC mode
  709. 'none' // OPTIONAL no encryption; NOT RECOMMENDED
  710. );
  711. static $mac_algorithms = array(
  712. 'hmac-sha1-96', // RECOMMENDED first 96 bits of HMAC-SHA1 (digest length = 12, key length = 20)
  713. 'hmac-sha1', // REQUIRED HMAC-SHA1 (digest length = key length = 20)
  714. 'hmac-md5-96', // OPTIONAL first 96 bits of HMAC-MD5 (digest length = 12, key length = 16)
  715. 'hmac-md5', // OPTIONAL HMAC-MD5 (digest length = key length = 16)
  716. 'none' // OPTIONAL no MAC; NOT RECOMMENDED
  717. );
  718. static $compression_algorithms = array(
  719. 'none' // REQUIRED no compression
  720. //'zlib' // OPTIONAL ZLIB (LZ77) compression
  721. );
  722. static $str_kex_algorithms, $str_server_host_key_algorithms,
  723. $encryption_algorithms_server_to_client, $mac_algorithms_server_to_client, $compression_algorithms_server_to_client,
  724. $encryption_algorithms_client_to_server, $mac_algorithms_client_to_server, $compression_algorithms_client_to_server;
  725. if (empty($str_kex_algorithms)) {
  726. $str_kex_algorithms = implode(',', $kex_algorithms);
  727. $str_server_host_key_algorithms = implode(',', $server_host_key_algorithms);
  728. $encryption_algorithms_server_to_client = $encryption_algorithms_client_to_server = implode(',', $encryption_algorithms);
  729. $mac_algorithms_server_to_client = $mac_algorithms_client_to_server = implode(',', $mac_algorithms);
  730. $compression_algorithms_server_to_client = $compression_algorithms_client_to_server = implode(',', $compression_algorithms);
  731. }
  732. $client_cookie = '';
  733. for ($i = 0; $i < 16; $i++) {
  734. $client_cookie.= chr(crypt_random(0, 255));
  735. }
  736. $response = $kexinit_payload_server;
  737. $this->_string_shift($response, 1); // skip past the message number (it should be SSH_MSG_KEXINIT)
  738. $server_cookie = $this->_string_shift($response, 16);
  739. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  740. $this->kex_algorithms = explode(',', $this->_string_shift($response, $temp['length']));
  741. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  742. $this->server_host_key_algorithms = explode(',', $this->_string_shift($response, $temp['length']));
  743. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  744. $this->encryption_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
  745. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  746. $this->encryption_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
  747. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  748. $this->mac_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
  749. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  750. $this->mac_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
  751. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  752. $this->compression_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
  753. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  754. $this->compression_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
  755. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  756. $this->languages_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
  757. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  758. $this->languages_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
  759. extract(unpack('Cfirst_kex_packet_follows', $this->_string_shift($response, 1)));
  760. $first_kex_packet_follows = $first_kex_packet_follows != 0;
  761. // the sending of SSH2_MSG_KEXINIT could go in one of two places. this is the second place.
  762. $kexinit_payload_client = pack('Ca*Na*Na*Na*Na*Na*Na*Na*Na*Na*Na*CN',
  763. NET_SSH2_MSG_KEXINIT, $client_cookie, strlen($str_kex_algorithms), $str_kex_algorithms,
  764. strlen($str_server_host_key_algorithms), $str_server_host_key_algorithms, strlen($encryption_algorithms_client_to_server),
  765. $encryption_algorithms_client_to_server, strlen($encryption_algorithms_server_to_client), $encryption_algorithms_server_to_client,
  766. strlen($mac_algorithms_client_to_server), $mac_algorithms_client_to_server, strlen($mac_algorithms_server_to_client),
  767. $mac_algorithms_server_to_client, strlen($compression_algorithms_client_to_server), $compression_algorithms_client_to_server,
  768. strlen($compression_algorithms_server_to_client), $compression_algorithms_server_to_client, 0, '', 0, '',
  769. 0, 0
  770. );
  771. if (!$this->_send_binary_packet($kexinit_payload_client)) {
  772. return false;
  773. }
  774. // here ends the second place.
  775. // we need to decide upon the symmetric encryption algorithms before we do the diffie-hellman key exchange
  776. for ($i = 0; $i < count($encryption_algorithms) && !in_array($encryption_algorithms[$i], $this->encryption_algorithms_server_to_client); $i++);
  777. if ($i == count($encryption_algorithms)) {
  778. user_error('No compatible server to client encryption algorithms found', E_USER_NOTICE);
  779. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  780. }
  781. // we don't initialize any crypto-objects, yet - we do that, later. for now, we need the lengths to make the
  782. // diffie-hellman key exchange as fast as possible
  783. $decrypt = $encryption_algorithms[$i];
  784. switch ($decrypt) {
  785. case '3des-cbc':
  786. case '3des-ctr':
  787. $decryptKeyLength = 24; // eg. 192 / 8
  788. break;
  789. case 'aes256-cbc':
  790. case 'aes256-ctr':
  791. $decryptKeyLength = 32; // eg. 256 / 8
  792. break;
  793. case 'aes192-cbc':
  794. case 'aes192-ctr':
  795. $decryptKeyLength = 24; // eg. 192 / 8
  796. break;
  797. case 'aes128-cbc':
  798. case 'aes128-ctr':
  799. $decryptKeyLength = 16; // eg. 128 / 8
  800. break;
  801. case 'arcfour':
  802. case 'arcfour128':
  803. $decryptKeyLength = 16; // eg. 128 / 8
  804. break;
  805. case 'arcfour256':
  806. $decryptKeyLength = 32; // eg. 128 / 8
  807. break;
  808. case 'none';
  809. $decryptKeyLength = 0;
  810. }
  811. for ($i = 0; $i < count($encryption_algorithms) && !in_array($encryption_algorithms[$i], $this->encryption_algorithms_client_to_server); $i++);
  812. if ($i == count($encryption_algorithms)) {
  813. user_error('No compatible client to server encryption algorithms found', E_USER_NOTICE);
  814. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  815. }
  816. $encrypt = $encryption_algorithms[$i];
  817. switch ($encrypt) {
  818. case '3des-cbc':
  819. case '3des-ctr':
  820. $encryptKeyLength = 24;
  821. break;
  822. case 'aes256-cbc':
  823. case 'aes256-ctr':
  824. $encryptKeyLength = 32;
  825. break;
  826. case 'aes192-cbc':
  827. case 'aes192-ctr':
  828. $encryptKeyLength = 24;
  829. break;
  830. case 'aes128-cbc':
  831. case 'aes128-ctr':
  832. $encryptKeyLength = 16;
  833. break;
  834. case 'arcfour':
  835. case 'arcfour128':
  836. $encryptKeyLength = 16;
  837. break;
  838. case 'arcfour256':
  839. $encryptKeyLength = 32;
  840. break;
  841. case 'none';
  842. $encryptKeyLength = 0;
  843. }
  844. $keyLength = $decryptKeyLength > $encryptKeyLength ? $decryptKeyLength : $encryptKeyLength;
  845. // through diffie-hellman key exchange a symmetric key is obtained
  846. for ($i = 0; $i < count($kex_algorithms) && !in_array($kex_algorithms[$i], $this->kex_algorithms); $i++);
  847. if ($i == count($kex_algorithms)) {
  848. user_error('No compatible key exchange algorithms found', E_USER_NOTICE);
  849. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  850. }
  851. switch ($kex_algorithms[$i]) {
  852. // see http://tools.ietf.org/html/rfc2409#section-6.2 and
  853. // http://tools.ietf.org/html/rfc2412, appendex E
  854. case 'diffie-hellman-group1-sha1':
  855. $p = pack('H256', 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' .
  856. '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' .
  857. '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' .
  858. 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF');
  859. $keyLength = $keyLength < 160 ? $keyLength : 160;
  860. $hash = 'sha1';
  861. break;
  862. // see http://tools.ietf.org/html/rfc3526#section-3
  863. case 'diffie-hellman-group14-sha1':
  864. $p = pack('H512', 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' .
  865. '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' .
  866. '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' .
  867. 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05' .
  868. '98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB' .
  869. '9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' .
  870. 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' .
  871. '3995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF');
  872. $keyLength = $keyLength < 160 ? $keyLength : 160;
  873. $hash = 'sha1';
  874. }
  875. $p = new Math_BigInteger($p, 256);
  876. //$q = $p->bitwise_rightShift(1);
  877. /* To increase the speed of the key exchange, both client and server may
  878. reduce the size of their private exponents. It should be at least
  879. twice as long as the key material that is generated from the shared
  880. secret. For more details, see the paper by van Oorschot and Wiener
  881. [VAN-OORSCHOT].
  882. -- http://tools.ietf.org/html/rfc4419#section-6.2 */
  883. $q = new Math_BigInteger(1);
  884. $q = $q->bitwise_leftShift(2 * $keyLength);
  885. $q = $q->subtract(new Math_BigInteger(1));
  886. $g = new Math_BigInteger(2);
  887. $x = new Math_BigInteger();
  888. $x->setRandomGenerator('crypt_random');
  889. $x = $x->random(new Math_BigInteger(1), $q);
  890. $e = $g->modPow($x, $p);
  891. $eBytes = $e->toBytes(true);
  892. $data = pack('CNa*', NET_SSH2_MSG_KEXDH_INIT, strlen($eBytes), $eBytes);
  893. if (!$this->_send_binary_packet($data)) {
  894. user_error('Connection closed by server', E_USER_NOTICE);
  895. return false;
  896. }
  897. $response = $this->_get_binary_packet();
  898. if ($response === false) {
  899. user_error('Connection closed by server', E_USER_NOTICE);
  900. return false;
  901. }
  902. extract(unpack('Ctype', $this->_string_shift($response, 1)));
  903. if ($type != NET_SSH2_MSG_KEXDH_REPLY) {
  904. user_error('Expected SSH_MSG_KEXDH_REPLY', E_USER_NOTICE);
  905. return false;
  906. }
  907. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  908. $this->server_public_host_key = $server_public_host_key = $this->_string_shift($response, $temp['length']);
  909. $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
  910. $public_key_format = $this->_string_shift($server_public_host_key, $temp['length']);
  911. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  912. $fBytes = $this->_string_shift($response, $temp['length']);
  913. $f = new Math_BigInteger($fBytes, -256);
  914. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  915. $this->signature = $this->_string_shift($response, $temp['length']);
  916. $temp = unpack('Nlength', $this->_string_shift($this->signature, 4));
  917. $this->signature_format = $this->_string_shift($this->signature, $temp['length']);
  918. $key = $f->modPow($x, $p);
  919. $keyBytes = $key->toBytes(true);
  920. $this->exchange_hash = pack('Na*Na*Na*Na*Na*Na*Na*Na*',
  921. strlen($this->identifier), $this->identifier, strlen($this->server_identifier), $this->server_identifier,
  922. strlen($kexinit_payload_client), $kexinit_payload_client, strlen($kexinit_payload_server),
  923. $kexinit_payload_server, strlen($this->server_public_host_key), $this->server_public_host_key, strlen($eBytes),
  924. $eBytes, strlen($fBytes), $fBytes, strlen($keyBytes), $keyBytes
  925. );
  926. $this->exchange_hash = pack('H*', $hash($this->exchange_hash));
  927. if ($this->session_id === false) {
  928. $this->session_id = $this->exchange_hash;
  929. }
  930. for ($i = 0; $i < count($server_host_key_algorithms) && !in_array($server_host_key_algorithms[$i], $this->server_host_key_algorithms); $i++);
  931. if ($i == count($server_host_key_algorithms)) {
  932. user_error('No compatible server host key algorithms found', E_USER_NOTICE);
  933. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  934. }
  935. if ($public_key_format != $server_host_key_algorithms[$i] || $this->signature_format != $server_host_key_algorithms[$i]) {
  936. user_error('Sever Host Key Algorithm Mismatch', E_USER_NOTICE);
  937. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  938. }
  939. $packet = pack('C',
  940. NET_SSH2_MSG_NEWKEYS
  941. );
  942. if (!$this->_send_binary_packet($packet)) {
  943. return false;
  944. }
  945. $response = $this->_get_binary_packet();
  946. if ($response === false) {
  947. user_error('Connection closed by server', E_USER_NOTICE);
  948. return false;
  949. }
  950. extract(unpack('Ctype', $this->_string_shift($response, 1)));
  951. if ($type != NET_SSH2_MSG_NEWKEYS) {
  952. user_error('Expected SSH_MSG_NEWKEYS', E_USER_NOTICE);
  953. return false;
  954. }
  955. switch ($encrypt) {
  956. case '3des-cbc':
  957. $this->encrypt = new Crypt_TripleDES();
  958. // $this->encrypt_block_size = 64 / 8 == the default
  959. break;
  960. case '3des-ctr':
  961. $this->encrypt = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
  962. // $this->encrypt_block_size = 64 / 8 == the default
  963. break;
  964. case 'aes256-cbc':
  965. case 'aes192-cbc':
  966. case 'aes128-cbc':
  967. $this->encrypt = new Crypt_AES();
  968. $this->encrypt_block_size = 16; // eg. 128 / 8
  969. break;
  970. case 'aes256-ctr':
  971. case 'aes192-ctr':
  972. case 'aes128-ctr':
  973. $this->encrypt = new Crypt_AES(CRYPT_AES_MODE_CTR);
  974. $this->encrypt_block_size = 16; // eg. 128 / 8
  975. break;
  976. case 'arcfour':
  977. case 'arcfour128':
  978. case 'arcfour256':
  979. $this->encrypt = new Crypt_RC4();
  980. break;
  981. case 'none';
  982. //$this->encrypt = new Crypt_Null();
  983. }
  984. switch ($decrypt) {
  985. case '3des-cbc':
  986. $this->decrypt = new Crypt_TripleDES();
  987. break;
  988. case '3des-ctr':
  989. $this->decrypt = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
  990. break;
  991. case 'aes256-cbc':
  992. case 'aes192-cbc':
  993. case 'aes128-cbc':
  994. $this->decrypt = new Crypt_AES();
  995. $this->decrypt_block_size = 16;
  996. break;
  997. case 'aes256-ctr':
  998. case 'aes192-ctr':
  999. case 'aes128-ctr':
  1000. $this->decrypt = new Crypt_AES(CRYPT_AES_MODE_CTR);
  1001. $this->decrypt_block_size = 16;
  1002. break;
  1003. case 'arcfour':
  1004. case 'arcfour128':
  1005. case 'arcfour256':
  1006. $this->decrypt = new Crypt_RC4();
  1007. break;
  1008. case 'none';
  1009. //$this->decrypt = new Crypt_Null();
  1010. }
  1011. $keyBytes = pack('Na*', strlen($keyBytes), $keyBytes);
  1012. if ($this->encrypt) {
  1013. $this->encrypt->enableContinuousBuffer();
  1014. $this->encrypt->disablePadding();
  1015. $iv = pack('H*', $hash($keyBytes . $this->exchange_hash . 'A' . $this->session_id));
  1016. while ($this->encrypt_block_size > strlen($iv)) {
  1017. $iv.= pack('H*', $hash($keyBytes . $this->exchange_hash . $iv));
  1018. }
  1019. $this->encrypt->setIV(substr($iv, 0, $this->encrypt_block_size));
  1020. $key = pack('H*', $hash($keyBytes . $this->exchange_hash . 'C' . $this->session_id));
  1021. while ($encryptKeyLength > strlen($key)) {
  1022. $key.= pack('H*', $hash($keyBytes . $this->exchange_hash . $key));
  1023. }
  1024. $this->encrypt->setKey(substr($key, 0, $encryptKeyLength));
  1025. }
  1026. if ($this->decrypt) {
  1027. $this->decrypt->enableContinuousBuffer();
  1028. $this->decrypt->disablePadding();
  1029. $iv = pack('H*', $hash($keyBytes . $this->exchange_hash . 'B' . $this->session_id));
  1030. while ($this->decrypt_block_size > strlen($iv)) {
  1031. $iv.= pack('H*', $hash($keyBytes . $this->exchange_hash . $iv));
  1032. }
  1033. $this->decrypt->setIV(substr($iv, 0, $this->decrypt_block_size));
  1034. $key = pack('H*', $hash($keyBytes . $this->exchange_hash . 'D' . $this->session_id));
  1035. while ($decryptKeyLength > strlen($key)) {
  1036. $key.= pack('H*', $hash($keyBytes . $this->exchange_hash . $key));
  1037. }
  1038. $this->decrypt->setKey(substr($key, 0, $decryptKeyLength));
  1039. }
  1040. /* The "arcfour128" algorithm is the RC4 cipher, as described in
  1041. [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream
  1042. generated by the cipher MUST be discarded, and the first byte of the
  1043. first encrypted packet MUST be encrypted using the 1537th byte of
  1044. keystream.
  1045. -- http://tools.ietf.org/html/rfc4345#section-4 */
  1046. if ($encrypt == 'arcfour128' || $encrypt == 'arcfour256') {
  1047. $this->encrypt->encrypt(str_repeat("\0", 1536));
  1048. }
  1049. if ($decrypt == 'arcfour128' || $decrypt == 'arcfour256') {
  1050. $this->decrypt->decrypt(str_repeat("\0", 1536));
  1051. }
  1052. for ($i = 0; $i < count($mac_algorithms) && !in_array($mac_algorithms[$i], $this->mac_algorithms_client_to_server); $i++);
  1053. if ($i == count($mac_algorithms)) {
  1054. user_error('No compatible client to server message authentication algorithms found', E_USER_NOTICE);
  1055. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1056. }
  1057. $createKeyLength = 0; // ie. $mac_algorithms[$i] == 'none'
  1058. switch ($mac_algorithms[$i]) {
  1059. case 'hmac-sha1':
  1060. $this->hmac_create = new Crypt_Hash('sha1');
  1061. $createKeyLength = 20;
  1062. break;
  1063. case 'hmac-sha1-96':
  1064. $this->hmac_create = new Crypt_Hash('sha1-96');
  1065. $createKeyLength = 20;
  1066. break;
  1067. case 'hmac-md5':
  1068. $this->hmac_create = new Crypt_Hash('md5');
  1069. $createKeyLength = 16;
  1070. break;
  1071. case 'hmac-md5-96':
  1072. $this->hmac_create = new Crypt_Hash('md5-96');
  1073. $createKeyLength = 16;
  1074. }
  1075. for ($i = 0; $i < count($mac_algorithms) && !in_array($mac_algorithms[$i], $this->mac_algorithms_server_to_client); $i++);
  1076. if ($i == count($mac_algorithms)) {
  1077. user_error('No compatible server to client message authentication algorithms found', E_USER_NOTICE);
  1078. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1079. }
  1080. $checkKeyLength = 0;
  1081. $this->hmac_size = 0;
  1082. switch ($mac_algorithms[$i]) {
  1083. case 'hmac-sha1':
  1084. $this->hmac_check = new Crypt_Hash('sha1');
  1085. $checkKeyLength = 20;
  1086. $this->hmac_size = 20;
  1087. break;
  1088. case 'hmac-sha1-96':
  1089. $this->hmac_check = new Crypt_Hash('sha1-96');
  1090. $checkKeyLength = 20;
  1091. $this->hmac_size = 12;
  1092. break;
  1093. case 'hmac-md5':
  1094. $this->hmac_check = new Crypt_Hash('md5');
  1095. $checkKeyLength = 16;
  1096. $this->hmac_size = 16;
  1097. break;
  1098. case 'hmac-md5-96':
  1099. $this->hmac_check = new Crypt_Hash('md5-96');
  1100. $checkKeyLength = 16;
  1101. $this->hmac_size = 12;
  1102. }
  1103. $key = pack('H*', $hash($keyBytes . $this->exchange_hash . 'E' . $this->session_id));
  1104. while ($createKeyLength > strlen($key)) {
  1105. $key.= pack('H*', $hash($keyBytes . $this->exchange_hash . $key));
  1106. }
  1107. $this->hmac_create->setKey(substr($key, 0, $createKeyLength));
  1108. $key = pack('H*', $hash($keyBytes . $this->exchange_hash . 'F' . $this->session_id));
  1109. while ($checkKeyLength > strlen($key)) {
  1110. $key.= pack('H*', $hash($keyBytes . $this->exchange_hash . $key));
  1111. }
  1112. $this->hmac_check->setKey(substr($key, 0, $checkKeyLength));
  1113. for ($i = 0; $i < count($compression_algorithms) && !in_array($compression_algorithms[$i], $this->compression_algorithms_server_to_client); $i++);
  1114. if ($i == count($compression_algorithms)) {
  1115. user_error('No compatible server to client compression algorithms found', E_USER_NOTICE);
  1116. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1117. }
  1118. $this->decompress = $compression_algorithms[$i] == 'zlib';
  1119. for ($i = 0; $i < count($compression_algorithms) && !in_array($compression_algorithms[$i], $this->compression_algorithms_client_to_server); $i++);
  1120. if ($i == count($compression_algorithms)) {
  1121. user_error('No compatible client to server compression algorithms found', E_USER_NOTICE);
  1122. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1123. }
  1124. $this->compress = $compression_algorithms[$i] == 'zlib';
  1125. return true;
  1126. }
  1127. /**
  1128. * Login
  1129. *
  1130. * The $password parameter can be a plaintext password or a Crypt_RSA object.
  1131. *
  1132. * @param String $username
  1133. * @param optional String $password
  1134. * @return Boolean
  1135. * @access public
  1136. * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis}
  1137. * by sending dummy SSH_MSG_IGNORE messages.
  1138. */
  1139. function login($username, $password = '')
  1140. {
  1141. if (!($this->bitmap & NET_SSH2_MASK_CONSTRUCTOR)) {
  1142. return false;
  1143. }
  1144. $packet = pack('CNa*',
  1145. NET_SSH2_MSG_SERVICE_REQUEST, strlen('ssh-userauth'), 'ssh-userauth'
  1146. );
  1147. if (!$this->_send_binary_packet($packet)) {
  1148. return false;
  1149. }
  1150. $response = $this->_get_binary_packet();
  1151. if ($response === false) {
  1152. user_error('Connection closed by server', E_USER_NOTICE);
  1153. return false;
  1154. }
  1155. extract(unpack('Ctype', $this->_string_shift($response, 1)));
  1156. if ($type != NET_SSH2_MSG_SERVICE_ACCEPT) {
  1157. user_error('Expected SSH_MSG_SERVICE_ACCEPT', E_USER_NOTICE);
  1158. return false;
  1159. }
  1160. // although PHP5's get_class() preserves the case, PHP4's does not
  1161. if (is_object($password) && strtolower(get_class($password)) == 'crypt_rsa') {
  1162. return $this->_privatekey_login($username, $password);
  1163. }
  1164. $utf8_password = utf8_encode($password);
  1165. $packet = pack('CNa*Na*Na*CNa*',
  1166. NET_SSH2_MSG_USERAUTH_REQUEST, strlen($username), $username, strlen('ssh-connection'), 'ssh-connection',
  1167. strlen('password'), 'password', 0, strlen($utf8_password), $utf8_password
  1168. );
  1169. if (!$this->_send_binary_packet($packet)) {
  1170. return false;
  1171. }
  1172. // remove the username and password from the last logged packet
  1173. if (defined('NET_SSH2_LOGGING') && NET_SSH2_LOGGING == NET_SSH2_LOG_COMPLEX) {
  1174. $packet = pack('CNa*Na*Na*CNa*',
  1175. NET_SSH2_MSG_USERAUTH_REQUEST, strlen('username'), 'username', strlen('ssh-connection'), 'ssh-connection',
  1176. strlen('password'), 'password', 0, strlen('password'), 'password'
  1177. );
  1178. $this->message_log[count($this->message_log) - 1] = $packet;
  1179. }
  1180. $response = $this->_get_binary_packet();
  1181. if ($response === false) {
  1182. user_error('Connection closed by server', E_USER_NOTICE);
  1183. return false;
  1184. }
  1185. extract(unpack('Ctype', $this->_string_shift($response, 1)));
  1186. switch ($type) {
  1187. case NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: // in theory, the password can be changed
  1188. if (defined('NET_SSH2_LOGGING')) {
  1189. $this->message_number_log[count($this->message_number_log) - 1] = 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ';
  1190. }
  1191. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1192. $this->errors[] = 'SSH_MSG_USERAUTH_PASSWD_CHANGEREQ: ' . utf8_decode($this->_string_shift($response, $length));
  1193. return $this->_disconnect(NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
  1194. case NET_SSH2_MSG_USERAUTH_FAILURE:
  1195. // can we use keyboard-interactive authentication? if not then either the login is bad or the server employees
  1196. // multi-factor authentication
  1197. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1198. $auth_methods = explode(',', $this->_string_shift($response, $length));
  1199. if (in_array('keyboard-interactive', $auth_methods)) {
  1200. if ($this->_keyboard_interactive_login($username, $password)) {
  1201. $this->bitmap |= NET_SSH2_MASK_LOGIN;
  1202. return true;
  1203. }
  1204. return false;
  1205. }
  1206. return false;
  1207. case NET_SSH2_MSG_USERAUTH_SUCCESS:
  1208. $this->bitmap |= NET_SSH2_MASK_LOGIN;
  1209. return true;
  1210. }
  1211. return false;
  1212. }
  1213. /**
  1214. * Login via keyboard-interactive authentication
  1215. *
  1216. * See {@link http://tools.ietf.org/html/rfc4256 RFC4256} for details. This is not a full-featured keyboard-interactive authenticator.
  1217. *
  1218. * @param String $username
  1219. * @param String $password
  1220. * @return Boolean
  1221. * @access private
  1222. */
  1223. function _keyboard_interactive_login($username, $password)
  1224. {
  1225. $packet = pack('CNa*Na*Na*Na*Na*',
  1226. NET_SSH2_MSG_USERAUTH_REQUEST, strlen($username), $username, strlen('ssh-connection'), 'ssh-connection',
  1227. strlen('keyboard-interactive'), 'keyboard-interactive', 0, '', 0, ''
  1228. );
  1229. if (!$this->_send_binary_packet($packet)) {
  1230. return false;
  1231. }
  1232. return $this->_keyboard_interactive_process($password);
  1233. }
  1234. /**
  1235. * Handle the keyboard-interactive requests / responses.
  1236. *
  1237. * @param String $responses...
  1238. * @return Boolean
  1239. * @access private
  1240. */
  1241. function _keyboard_interactive_process()
  1242. {
  1243. $responses = func_get_args();
  1244. $response = $this->_get_binary_packet();
  1245. if ($response === false) {
  1246. user_error('Connection closed by server', E_USER_NOTICE);
  1247. return false;
  1248. }
  1249. extract(unpack('Ctype', $this->_string_shift($response, 1)));
  1250. switch ($type) {
  1251. case NET_SSH2_MSG_USERAUTH_INFO_REQUEST:
  1252. // see http://tools.ietf.org/html/rfc4256#section-3.2
  1253. if (defined('NET_SSH2_LOGGING')) {
  1254. $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
  1255. 'UNKNOWN',
  1256. 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST',
  1257. $this->message_number_log[count($this->message_number_log) - 1]
  1258. );
  1259. }
  1260. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1261. $this->_string_shift($response, $length); // name; may be empty
  1262. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1263. $this->_string_shift($response, $length); // instruction; may be empty
  1264. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1265. $this->_string_shift($response, $length); // language tag; may be empty
  1266. extract(unpack('Nnum_prompts', $this->_string_shift($response, 4)));
  1267. /*
  1268. for ($i = 0; $i < $num_prompts; $i++) {
  1269. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1270. // prompt - ie. "Password: "; must not be empty
  1271. $this->_string_shift($response, $length);
  1272. $echo = $this->_string_shift($response) != chr(0);
  1273. }
  1274. */
  1275. /*
  1276. After obtaining the requested information from the user, the client
  1277. MUST respond with an SSH_MSG_USERAUTH_INFO_RESPONSE message.
  1278. */
  1279. // see http://tools.ietf.org/html/rfc4256#section-3.4
  1280. $packet = $logged = pack('CN', NET_SSH2_MSG_USERAUTH_INFO_RESPONSE, count($responses));
  1281. for ($i = 0; $i < count($responses); $i++) {
  1282. $packet.= pack('Na*', strlen($responses[$i]), $responses[$i]);
  1283. $logged.= pack('Na*', strlen('dummy-answer'), 'dummy-answer');
  1284. }
  1285. if (!$this->_send_binary_packet($packet)) {
  1286. return false;
  1287. }
  1288. if (defined('NET_SSH2_LOGGING')) {
  1289. $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
  1290. 'UNKNOWN',
  1291. 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE',
  1292. $this->message_number_log[count($this->message_number_log) - 1]
  1293. );
  1294. $this->message_log[count($this->message_log) - 1] = $logged;
  1295. }
  1296. /*
  1297. After receiving the response, the server MUST send either an
  1298. SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE, or another
  1299. SSH_MSG_USERAUTH_INFO_REQUEST message.
  1300. */
  1301. // maybe phpseclib should force close the connection after x request / responses? unless something like that is done
  1302. // there could be an infinite loop of request / responses.
  1303. return $this->_keyboard_interactive_process();
  1304. case NET_SSH2_MSG_USERAUTH_SUCCESS:
  1305. return true;
  1306. case NET_SSH2_MSG_USERAUTH_FAILURE:
  1307. return false;
  1308. }
  1309. return false;
  1310. }
  1311. /**
  1312. * Login with an RSA private key
  1313. *
  1314. * @param String $username
  1315. * @param Crypt_RSA $password
  1316. * @return Boolean
  1317. * @access private
  1318. * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis}
  1319. * by sending dummy SSH_MSG_IGNORE messages.
  1320. */
  1321. function _privatekey_login($username, $privatekey)
  1322. {
  1323. // see http://tools.ietf.org/html/rfc4253#page-15
  1324. $publickey = $privatekey->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_RAW);
  1325. if ($publickey === false) {
  1326. return false;
  1327. }
  1328. $publickey = array(
  1329. 'e' => $publickey['e']->toBytes(true),
  1330. 'n' => $publickey['n']->toBytes(true)
  1331. );
  1332. $publickey = pack('Na*Na*Na*',
  1333. strlen('ssh-rsa'), 'ssh-rsa', strlen($publickey['e']), $publickey['e'], strlen($publickey['n']), $publickey['n']
  1334. );
  1335. $part1 = pack('CNa*Na*Na*',
  1336. NET_SSH2_MSG_USERAUTH_REQUEST, strlen($username), $username, strlen('ssh-connection'), 'ssh-connection',
  1337. strlen('publickey'), 'publickey'
  1338. );
  1339. $part2 = pack('Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publickey), $publickey);
  1340. $packet = $part1 . chr(0) . $part2;
  1341. if (!$this->_send_binary_packet($packet)) {
  1342. return false;
  1343. }
  1344. $response = $this->_get_binary_packet();
  1345. if ($response === false) {
  1346. user_error('Connection closed by server', E_USER_NOTICE);
  1347. return false;
  1348. }
  1349. extract(unpack('Ctype', $this->_string_shift($response, 1)));
  1350. switch ($type) {
  1351. case NET_SSH2_MSG_USERAUTH_FAILURE:
  1352. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1353. $this->errors[] = 'SSH_MSG_USERAUTH_FAILURE: ' . $this->_string_shift($response, $length);
  1354. return $this->_disconnect(NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
  1355. case NET_SSH2_MSG_USERAUTH_PK_OK:
  1356. // we'll just take it on faith that the public key blob and the public key algorithm name are as
  1357. // they should be
  1358. if (defined('NET_SSH2_LOGGING')) {
  1359. $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
  1360. 'UNKNOWN',
  1361. 'NET_SSH2_MSG_USERAUTH_PK_OK',
  1362. $this->message_number_log[count($this->message_number_log) - 1]
  1363. );
  1364. }
  1365. }
  1366. $packet = $part1 . chr(1) . $part2;
  1367. $privatekey->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
  1368. $signature = $privatekey->sign(pack('Na*a*', strlen($this->session_id), $this->session_id, $packet));
  1369. $signature = pack('Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($signature), $signature);
  1370. $packet.= pack('Na*', strlen($signature), $signature);
  1371. if (!$this->_send_binary_packet($packet)) {
  1372. return false;
  1373. }
  1374. $response = $this->_get_binary_packet();
  1375. if ($response === false) {
  1376. user_error('Connection closed by server', E_USER_NOTICE);
  1377. return false;
  1378. }
  1379. extract(unpack('Ctype', $this->_string_shift($response, 1)));
  1380. switch ($type) {
  1381. case NET_SSH2_MSG_USERAUTH_FAILURE:
  1382. // either the login is bad or the server employees multi-factor authentication
  1383. return false;
  1384. case NET_SSH2_MSG_USERAUTH_SUCCESS:
  1385. $this->bitmap |= NET_SSH2_MASK_LOGIN;
  1386. return true;
  1387. }
  1388. return false;
  1389. }
  1390. /**
  1391. * Execute Command
  1392. *
  1393. * If $block is set to false then Net_SSH2::_get_channel_packet(NET_SSH2_CHANNEL_EXEC) will need to be called manually.
  1394. * In all likelihood, this is not a feature you want to be taking advantage of.
  1395. *
  1396. * @param String $command
  1397. * @param optional Boolean $block
  1398. * @return String
  1399. * @access public
  1400. */
  1401. function exec($command, $block = true)
  1402. {
  1403. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1404. return false;
  1405. }
  1406. // RFC4254 defines the (client) window size as "bytes the other party can send before it must wait for the window to
  1407. // be adjusted". 0x7FFFFFFF is, at 4GB, the max size. technically, it should probably be decremented, but,
  1408. // honestly, if you're transfering more than 4GB, you probably shouldn't be using phpseclib, anyway.
  1409. // see http://tools.ietf.org/html/rfc4254#section-5.2 for more info
  1410. $this->window_size_client_to_server[NET_SSH2_CHANNEL_EXEC] = 0x7FFFFFFF;
  1411. // 0x8000 is the maximum max packet size, per http://tools.ietf.org/html/rfc4253#section-6.1, although since PuTTy
  1412. // uses 0x4000, that's what will be used here, as well.
  1413. $packet_size = 0x4000;
  1414. $packet = pack('CNa*N3',
  1415. NET_SSH2_MSG_CHANNEL_OPEN, strlen('session'), 'session', NET_SSH2_CHANNEL_EXEC, $this->window_size_client_to_server[NET_SSH2_CHANNEL_EXEC], $packet_size);
  1416. if (!$this->_send_binary_packet($packet)) {
  1417. return false;
  1418. }
  1419. $this->channel_status[NET_SSH2_CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_OPEN;
  1420. $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_EXEC);
  1421. if ($response === false) {
  1422. return false;
  1423. }
  1424. // sending a pty-req SSH_MSG_CHANNEL_REQUEST message is unnecessary and, in fact, in most cases, slows things
  1425. // down. the one place where it might be desirable is if you're doing something like Net_SSH2::exec('ping localhost &').
  1426. // with a pty-req SSH_MSG_CHANNEL_REQUEST, exec() will return immediately and the ping process will then
  1427. // then immediately terminate. without such a request exec() will loop indefinitely. the ping process won't end but
  1428. // neither will your script.
  1429. // although, in theory, the size of SSH_MSG_CHANNEL_REQUEST could exceed the maximum packet size established by
  1430. // SSH_MSG_CHANNEL_OPEN_CONFIRMATION, RFC4254#section-5.1 states that the "maximum packet size" refers to the
  1431. // "maximum size of an individual data packet". ie. SSH_MSG_CHANNEL_DATA. RFC4254#section-5.2 corroborates.
  1432. $packet = pack('CNNa*CNa*',
  1433. NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[NET_SSH2_CHANNEL_EXEC], strlen('exec'), 'exec', 1, strlen($command), $command);
  1434. if (!$this->_send_binary_packet($packet)) {
  1435. return false;
  1436. }
  1437. $this->channel_status[NET_SSH2_CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_REQUEST;
  1438. $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_EXEC);
  1439. if ($response === false) {
  1440. return false;
  1441. }
  1442. $this->channel_status[NET_SSH2_CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_DATA;
  1443. if (!$block) {
  1444. return true;
  1445. }
  1446. $output = '';
  1447. while (true) {
  1448. $temp = $this->_get_channel_packet(NET_SSH2_CHANNEL_EXEC);
  1449. switch (true) {
  1450. case $temp === true:
  1451. return $output;
  1452. case $temp === false:
  1453. return false;
  1454. default:
  1455. $output.= $temp;
  1456. }
  1457. }
  1458. }
  1459. /**
  1460. * Creates an interactive shell
  1461. *
  1462. * @see Net_SSH2::read()
  1463. * @see Net_SSH2::write()
  1464. * @return Boolean
  1465. * @access private
  1466. */
  1467. function _initShell()
  1468. {
  1469. $this->window_size_client_to_server[NET_SSH2_CHANNEL_SHELL] = 0x7FFFFFFF;
  1470. $packet_size = 0x4000;
  1471. $packet = pack('CNa*N3',
  1472. NET_SSH2_MSG_CHANNEL_OPEN, strlen('session'), 'session', NET_SSH2_CHANNEL_SHELL, $this->window_size_client_to_server[NET_SSH2_CHANNEL_SHELL], $packet_size);
  1473. if (!$this->_send_binary_packet($packet)) {
  1474. return false;
  1475. }
  1476. $this->channel_status[NET_SSH2_CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_OPEN;
  1477. $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_SHELL);
  1478. if ($response === false) {
  1479. return false;
  1480. }
  1481. $terminal_modes = pack('C', NET_SSH2_TTY_OP_END);
  1482. $packet = pack('CNNa*CNa*N5a*',
  1483. NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[NET_SSH2_CHANNEL_SHELL], strlen('pty-req'), 'pty-req', 1, strlen('vt100'), 'vt100',
  1484. 80, 24, 0, 0, strlen($terminal_modes), $terminal_modes);
  1485. if (!$this->_send_binary_packet($packet)) {
  1486. return false;
  1487. }
  1488. $response = $this->_get_binary_packet();
  1489. if ($response === false) {
  1490. user_error('Connection closed by server', E_USER_NOTICE);
  1491. return false;
  1492. }
  1493. list(, $type) = unpack('C', $this->_string_shift($response, 1));
  1494. switch ($type) {
  1495. case NET_SSH2_MSG_CHANNEL_SUCCESS:
  1496. break;
  1497. case NET_SSH2_MSG_CHANNEL_FAILURE:
  1498. default:
  1499. user_error('Unable to request pseudo-terminal', E_USER_NOTICE);
  1500. return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
  1501. }
  1502. $packet = pack('CNNa*C',
  1503. NET_SSH2_MSG_CHANNEL_REQUEST, $this->server_channels[NET_SSH2_CHANNEL_SHELL], strlen('shell'), 'shell', 1);
  1504. if (!$this->_send_binary_packet($packet)) {
  1505. return false;
  1506. }
  1507. $this->channel_status[NET_SSH2_CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_REQUEST;
  1508. $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_SHELL);
  1509. if ($response === false) {
  1510. return false;
  1511. }
  1512. $this->channel_status[NET_SSH2_CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_DATA;
  1513. $this->bitmap |= NET_SSH2_MASK_SHELL;
  1514. return true;
  1515. }
  1516. /**
  1517. * Returns the output of an interactive shell
  1518. *
  1519. * Returns when there's a match for $expect, which can take the form of a string literal or,
  1520. * if $mode == NET_SSH2_READ_REGEX, a regular expression.
  1521. *
  1522. * @see Net_SSH2::read()
  1523. * @param String $expect
  1524. * @param Integer $mode
  1525. * @return String
  1526. * @access public
  1527. */
  1528. function read($expect, $mode = NET_SSH2_READ_SIMPLE)
  1529. {
  1530. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1531. user_error('Operation disallowed prior to login()', E_USER_NOTICE);
  1532. return false;
  1533. }
  1534. if (!($this->bitmap & NET_SSH2_MASK_SHELL) && !$this->_initShell()) {
  1535. user_error('Unable to initiate an interactive shell session', E_USER_NOTICE);
  1536. return false;
  1537. }
  1538. $match = $expect;
  1539. while (true) {
  1540. if ($mode == NET_SSH2_READ_REGEX) {
  1541. preg_match($expect, $this->interactiveBuffer, $matches);
  1542. $match = $matches[0];
  1543. }
  1544. $pos = strpos($this->interactiveBuffer, $match);
  1545. if ($pos !== false) {
  1546. return $this->_string_shift($this->interactiveBuffer, $pos + strlen($match));
  1547. }
  1548. $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_SHELL);
  1549. $this->interactiveBuffer.= $response;
  1550. }
  1551. }
  1552. /**
  1553. * Inputs a command into an interactive shell.
  1554. *
  1555. * @see Net_SSH1::interactiveWrite()
  1556. * @param String $cmd
  1557. * @return Boolean
  1558. * @access public
  1559. */
  1560. function write($cmd)
  1561. {
  1562. if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1563. user_error('Operation disallowed prior to login()', E_USER_NOTICE);
  1564. return false;
  1565. }
  1566. if (!($this->bitmap & NET_SSH2_MASK_SHELL) && !$this->_initShell()) {
  1567. user_error('Unable to initiate an interactive shell session', E_USER_NOTICE);
  1568. return false;
  1569. }
  1570. return $this->_send_channel_packet(NET_SSH2_CHANNEL_SHELL, $cmd);
  1571. }
  1572. /**
  1573. * Disconnect
  1574. *
  1575. * @access public
  1576. */
  1577. function disconnect()
  1578. {
  1579. $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
  1580. }
  1581. /**
  1582. * Destructor.
  1583. *
  1584. * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
  1585. * disconnect().
  1586. *
  1587. * @access public
  1588. */
  1589. function __destruct()
  1590. {
  1591. $this->disconnect();
  1592. }
  1593. /**
  1594. * Gets Binary Packets
  1595. *
  1596. * See '6. Binary Packet Protocol' of rfc4253 for more info.
  1597. *
  1598. * @see Net_SSH2::_send_binary_packet()
  1599. * @return String
  1600. * @access private
  1601. */
  1602. function _get_binary_packet()
  1603. {
  1604. if (feof($this->fsock)) {
  1605. user_error('Connection closed prematurely', E_USER_NOTICE);
  1606. return false;
  1607. }
  1608. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  1609. $raw = fread($this->fsock, $this->decrypt_block_size);
  1610. $stop = strtok(microtime(), ' ') + strtok('');
  1611. if (empty($raw)) {
  1612. return '';
  1613. }
  1614. if ($this->decrypt !== false) {
  1615. $raw = $this->decrypt->decrypt($raw);
  1616. }
  1617. extract(unpack('Npacket_length/Cpadding_length', $this->_string_shift($raw, 5)));
  1618. $remaining_length = $packet_length + 4 - $this->decrypt_block_size;
  1619. $buffer = '';
  1620. while ($remaining_length > 0) {
  1621. $temp = fread($this->fsock, $remaining_length);
  1622. $buffer.= $temp;
  1623. $remaining_length-= strlen($temp);
  1624. }
  1625. if (!empty($buffer)) {
  1626. $raw.= $this->decrypt !== false ? $this->decrypt->decrypt($buffer) : $buffer;
  1627. $buffer = $temp = '';
  1628. }
  1629. $payload = $this->_string_shift($raw, $packet_length - $padding_length - 1);
  1630. $padding = $this->_string_shift($raw, $padding_length); // should leave $raw empty
  1631. if ($this->hmac_check !== false) {
  1632. $hmac = fread($this->fsock, $this->hmac_size);
  1633. if ($hmac != $this->hmac_check->hash(pack('NNCa*', $this->get_seq_no, $packet_length, $padding_length, $payload . $padding))) {
  1634. user_error('Invalid HMAC', E_USER_NOTICE);
  1635. return false;
  1636. }
  1637. }
  1638. //if ($this->decompress) {
  1639. // $payload = gzinflate(substr($payload, 2));
  1640. //}
  1641. $this->get_seq_no++;
  1642. if (defined('NET_SSH2_LOGGING')) {
  1643. $temp = isset($this->message_numbers[ord($payload[0])]) ? $this->message_numbers[ord($payload[0])] : 'UNKNOWN (' . ord($payload[0]) . ')';
  1644. $this->message_number_log[] = '<- ' . $temp .
  1645. ' (' . round($stop - $start, 4) . 's)';
  1646. if (NET_SSH2_LOGGING == NET_SSH2_LOG_COMPLEX) {
  1647. $this->message_log[] = substr($payload, 1);
  1648. }
  1649. }
  1650. return $this->_filter($payload);
  1651. }
  1652. /**
  1653. * Filter Binary Packets
  1654. *
  1655. * Because some binary packets need to be ignored...
  1656. *
  1657. * @see Net_SSH2::_get_binary_packet()
  1658. * @return String
  1659. * @access private
  1660. */
  1661. function _filter($payload)
  1662. {
  1663. switch (ord($payload[0])) {
  1664. case NET_SSH2_MSG_DISCONNECT:
  1665. $this->_string_shift($payload, 1);
  1666. extract(unpack('Nreason_code/Nlength', $this->_string_shift($payload, 8)));
  1667. $this->errors[] = 'SSH_MSG_DISCONNECT: ' . $this->disconnect_reasons[$reason_code] . "\r\n" . utf8_decode($this->_string_shift($payload, $length));
  1668. $this->bitmask = 0;
  1669. return false;
  1670. case NET_SSH2_MSG_IGNORE:
  1671. $payload = $this->_get_binary_packet();
  1672. break;
  1673. case NET_SSH2_MSG_DEBUG:
  1674. $this->_string_shift($payload, 2);
  1675. extract(unpack('Nlength', $this->_string_shift($payload, 4)));
  1676. $this->errors[] = 'SSH_MSG_DEBUG: ' . utf8_decode($this->_string_shift($payload, $length));
  1677. $payload = $this->_get_binary_packet();
  1678. break;
  1679. case NET_SSH2_MSG_UNIMPLEMENTED:
  1680. return false;
  1681. case NET_SSH2_MSG_KEXINIT:
  1682. if ($this->session_id !== false) {
  1683. if (!$this->_key_exchange($payload)) {
  1684. $this->bitmask = 0;
  1685. return false;
  1686. }
  1687. $payload = $this->_get_binary_packet();
  1688. }
  1689. }
  1690. // see http://tools.ietf.org/html/rfc4252#section-5.4; only called when the encryption has been activated and when we haven't already logged in
  1691. if (($this->bitmap & NET_SSH2_MASK_CONSTRUCTOR) && !($this->bitmap & NET_SSH2_MASK_LOGIN) && ord($payload[0]) == NET_SSH2_MSG_USERAUTH_BANNER) {
  1692. $this->_string_shift($payload, 1);
  1693. extract(unpack('Nlength', $this->_string_shift($payload, 4)));
  1694. $this->errors[] = 'SSH_MSG_USERAUTH_BANNER: ' . utf8_decode($this->_string_shift($payload, $length));
  1695. $payload = $this->_get_binary_packet();
  1696. }
  1697. // only called when we've already logged in
  1698. if (($this->bitmap & NET_SSH2_MASK_CONSTRUCTOR) && ($this->bitmap & NET_SSH2_MASK_LOGIN)) {
  1699. switch (ord($payload[0])) {
  1700. case NET_SSH2_MSG_GLOBAL_REQUEST: // see http://tools.ietf.org/html/rfc4254#section-4
  1701. $this->_string_shift($payload, 1);
  1702. extract(unpack('Nlength', $this->_string_shift($payload)));
  1703. $this->errors[] = 'SSH_MSG_GLOBAL_REQUEST: ' . utf8_decode($this->_string_shift($payload, $length));
  1704. if (!$this->_send_binary_packet(pack('C', NET_SSH2_MSG_REQUEST_FAILURE))) {
  1705. return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
  1706. }
  1707. $payload = $this->_get_binary_packet();
  1708. break;
  1709. case NET_SSH2_MSG_CHANNEL_OPEN: // see http://tools.ietf.org/html/rfc4254#section-5.1
  1710. $this->_string_shift($payload, 1);
  1711. extract(unpack('N', $this->_string_shift($payload, 4)));
  1712. $this->errors[] = 'SSH_MSG_CHANNEL_OPEN: ' . utf8_decode($this->_string_shift($payload, $length));
  1713. $this->_string_shift($payload, 4); // skip over client channel
  1714. extract(unpack('Nserver_channel', $this->_string_shift($payload, 4)));
  1715. $packet = pack('CN3a*Na*',
  1716. NET_SSH2_MSG_REQUEST_FAILURE, $server_channel, NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED, 0, '', 0, '');
  1717. if (!$this->_send_binary_packet($packet)) {
  1718. return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
  1719. }
  1720. $payload = $this->_get_binary_packet();
  1721. break;
  1722. case NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST:
  1723. $payload = $this->_get_binary_packet();
  1724. }
  1725. }
  1726. return $payload;
  1727. }
  1728. /**
  1729. * Gets channel data
  1730. *
  1731. * Returns the data as a string if it's available and false if not.
  1732. *
  1733. * @param $client_channel
  1734. * @return Mixed
  1735. * @access private
  1736. */
  1737. function _get_channel_packet($client_channel, $skip_extended = false)
  1738. {
  1739. if (!empty($this->channel_buffers[$client_channel])) {
  1740. return array_shift($this->channel_buffers[$client_channel]);
  1741. }
  1742. while (true) {
  1743. $response = $this->_get_binary_packet();
  1744. if ($response === false) {
  1745. user_error('Connection closed by server', E_USER_NOTICE);
  1746. return false;
  1747. }
  1748. if (empty($response)) {
  1749. return '';
  1750. }
  1751. extract(unpack('Ctype/Nchannel', $this->_string_shift($response, 5)));
  1752. switch ($this->channel_status[$channel]) {
  1753. case NET_SSH2_MSG_CHANNEL_OPEN:
  1754. switch ($type) {
  1755. case NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
  1756. extract(unpack('Nserver_channel', $this->_string_shift($response, 4)));
  1757. $this->server_channels[$client_channel] = $server_channel;
  1758. $this->_string_shift($response, 4); // skip over (server) window size
  1759. $temp = unpack('Npacket_size_client_to_server', $this->_string_shift($response, 4));
  1760. $this->packet_size_client_to_server[$client_channel] = $temp['packet_size_client_to_server'];
  1761. return true;
  1762. //case NET_SSH2_MSG_CHANNEL_OPEN_FAILURE:
  1763. default:
  1764. user_error('Unable to open channel', E_USER_NOTICE);
  1765. return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
  1766. }
  1767. break;
  1768. case NET_SSH2_MSG_CHANNEL_REQUEST:
  1769. switch ($type) {
  1770. case NET_SSH2_MSG_CHANNEL_SUCCESS:
  1771. return true;
  1772. //case NET_SSH2_MSG_CHANNEL_FAILURE:
  1773. default:
  1774. user_error('Unable to request pseudo-terminal', E_USER_NOTICE);
  1775. return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
  1776. }
  1777. }
  1778. switch ($type) {
  1779. case NET_SSH2_MSG_CHANNEL_DATA:
  1780. /*
  1781. if ($client_channel == NET_SSH2_CHANNEL_EXEC) {
  1782. // SCP requires null packets, such as this, be sent. further, in the case of the ssh.com SSH server
  1783. // this actually seems to make things twice as fast. more to the point, the message right after
  1784. // SSH_MSG_CHANNEL_DATA (usually SSH_MSG_IGNORE) won't block for as long as it would have otherwise.
  1785. // in OpenSSH it slows things down but only by a couple thousandths of a second.
  1786. $this->_send_channel_packet($client_channel, chr(0));
  1787. }
  1788. */
  1789. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1790. $data = $this->_string_shift($response, $length);
  1791. if ($client_channel == $channel) {
  1792. return $data;
  1793. }
  1794. if (!isset($this->channel_buffers[$client_channel])) {
  1795. $this->channel_buffers[$client_channel] = array();
  1796. }
  1797. $this->channel_buffers[$client_channel][] = $data;
  1798. break;
  1799. case NET_SSH2_MSG_CHANNEL_EXTENDED_DATA:
  1800. if ($skip_extended) {
  1801. break;
  1802. }
  1803. /*
  1804. if ($client_channel == NET_SSH2_CHANNEL_EXEC) {
  1805. $this->_send_channel_packet($client_channel, chr(0));
  1806. }
  1807. */
  1808. // currently, there's only one possible value for $data_type_code: NET_SSH2_EXTENDED_DATA_STDERR
  1809. extract(unpack('Ndata_type_code/Nlength', $this->_string_shift($response, 8)));
  1810. $data = $this->_string_shift($response, $length);
  1811. if ($client_channel == $channel) {
  1812. return $data;
  1813. }
  1814. if (!isset($this->channel_buffers[$client_channel])) {
  1815. $this->channel_buffers[$client_channel] = array();
  1816. }
  1817. $this->channel_buffers[$client_channel][] = $data;
  1818. break;
  1819. case NET_SSH2_MSG_CHANNEL_REQUEST:
  1820. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1821. $value = $this->_string_shift($response, $length);
  1822. switch ($value) {
  1823. case 'exit-signal':
  1824. $this->_string_shift($response, 1);
  1825. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1826. $this->errors[] = 'SSH_MSG_CHANNEL_REQUEST (exit-signal): ' . $this->_string_shift($response, $length);
  1827. $this->_string_shift($response, 1);
  1828. extract(unpack('Nlength', $this->_string_shift($response, 4)));
  1829. if ($length) {
  1830. $this->errors[count($this->errors)].= "\r\n" . $this->_string_shift($response, $length);
  1831. }
  1832. //case 'exit-status':
  1833. default:
  1834. // "Some systems may not implement signals, in which case they SHOULD ignore this message."
  1835. // -- http://tools.ietf.org/html/rfc4254#section-6.9
  1836. break;
  1837. }
  1838. break;
  1839. case NET_SSH2_MSG_CHANNEL_CLOSE:
  1840. $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$channel]));
  1841. return true;
  1842. case NET_SSH2_MSG_CHANNEL_EOF:
  1843. break;
  1844. default:
  1845. user_error('Error reading channel data', E_USER_NOTICE);
  1846. return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
  1847. }
  1848. }
  1849. }
  1850. /**
  1851. * Sends Binary Packets
  1852. *
  1853. * See '6. Binary Packet Protocol' of rfc4253 for more info.
  1854. *
  1855. * @param String $data
  1856. * @see Net_SSH2::_get_binary_packet()
  1857. * @return Boolean
  1858. * @access private
  1859. */
  1860. function _send_binary_packet($data)
  1861. {
  1862. if (feof($this->fsock)) {
  1863. user_error('Connection closed prematurely', E_USER_NOTICE);
  1864. return false;
  1865. }
  1866. //if ($this->compress) {
  1867. // // the -4 removes the checksum:
  1868. // // http://php.net/function.gzcompress#57710
  1869. // $data = substr(gzcompress($data), 0, -4);
  1870. //}
  1871. // 4 (packet length) + 1 (padding length) + 4 (minimal padding amount) == 9
  1872. $packet_length = strlen($data) + 9;
  1873. // round up to the nearest $this->encrypt_block_size
  1874. $packet_length+= (($this->encrypt_block_size - 1) * $packet_length) % $this->encrypt_block_size;
  1875. // subtracting strlen($data) is obvious - subtracting 5 is necessary because of packet_length and padding_length
  1876. $padding_length = $packet_length - strlen($data) - 5;
  1877. $padding = '';
  1878. for ($i = 0; $i < $padding_length; $i++) {
  1879. $padding.= chr(crypt_random(0, 255));
  1880. }
  1881. // we subtract 4 from packet_length because the packet_length field isn't supposed to include itself
  1882. $packet = pack('NCa*', $packet_length - 4, $padding_length, $data . $padding);
  1883. $hmac = $this->hmac_create !== false ? $this->hmac_create->hash(pack('Na*', $this->send_seq_no, $packet)) : '';
  1884. $this->send_seq_no++;
  1885. if ($this->encrypt !== false) {
  1886. $packet = $this->encrypt->encrypt($packet);
  1887. }
  1888. $packet.= $hmac;
  1889. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  1890. $result = strlen($packet) == fputs($this->fsock, $packet);
  1891. $stop = strtok(microtime(), ' ') + strtok('');
  1892. if (defined('NET_SSH2_LOGGING')) {
  1893. $temp = isset($this->message_numbers[ord($data[0])]) ? $this->message_numbers[ord($data[0])] : 'UNKNOWN (' . ord($data[0]) . ')';
  1894. $this->message_number_log[] = '-> ' . $temp .
  1895. ' (' . round($stop - $start, 4) . 's)';
  1896. if (NET_SSH2_LOGGING == NET_SSH2_LOG_COMPLEX) {
  1897. $this->message_log[] = substr($data, 1);
  1898. }
  1899. }
  1900. return $result;
  1901. }
  1902. /**
  1903. * Sends channel data
  1904. *
  1905. * Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate
  1906. *
  1907. * @param Integer $client_channel
  1908. * @param String $data
  1909. * @return Boolean
  1910. * @access private
  1911. */
  1912. function _send_channel_packet($client_channel, $data)
  1913. {
  1914. while (strlen($data) > $this->packet_size_client_to_server[$client_channel]) {
  1915. // resize the window, if appropriate
  1916. $this->window_size_client_to_server[$client_channel]-= $this->packet_size_client_to_server[$client_channel];
  1917. if ($this->window_size_client_to_server[$client_channel] < 0) {
  1918. $packet = pack('CNN', NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST, $this->server_channels[$client_channel], $this->window_size);
  1919. if (!$this->_send_binary_packet($packet)) {
  1920. return false;
  1921. }
  1922. $this->window_size_client_to_server[$client_channel]+= $this->window_size;
  1923. }
  1924. $packet = pack('CN2a*',
  1925. NET_SSH2_MSG_CHANNEL_DATA,
  1926. $this->server_channels[$client_channel],
  1927. $this->packet_size_client_to_server[$client_channel],
  1928. $this->_string_shift($data, $this->packet_size_client_to_server[$client_channel])
  1929. );
  1930. if (!$this->_send_binary_packet($packet)) {
  1931. return false;
  1932. }
  1933. }
  1934. // resize the window, if appropriate
  1935. $this->window_size_client_to_server[$client_channel]-= strlen($data);
  1936. if ($this->window_size_client_to_server[$client_channel] < 0) {
  1937. $packet = pack('CNN', NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST, $this->server_channels[$client_channel], $this->window_size);
  1938. if (!$this->_send_binary_packet($packet)) {
  1939. return false;
  1940. }
  1941. $this->window_size_client_to_server[$client_channel]+= $this->window_size;
  1942. }
  1943. return $this->_send_binary_packet(pack('CN2a*',
  1944. NET_SSH2_MSG_CHANNEL_DATA,
  1945. $this->server_channels[$client_channel],
  1946. strlen($data),
  1947. $data));
  1948. }
  1949. /**
  1950. * Closes and flushes a channel
  1951. *
  1952. * Net_SSH2 doesn't properly close most channels. For exec() channels are normally closed by the server
  1953. * and for SFTP channels are presumably closed when the client disconnects. This functions is intended
  1954. * for SCP more than anything.
  1955. *
  1956. * @param Integer $client_channel
  1957. * @return Boolean
  1958. * @access private
  1959. */
  1960. function _close_channel($client_channel)
  1961. {
  1962. // see http://tools.ietf.org/html/rfc4254#section-5.3
  1963. $packet = pack('CN',
  1964. NET_SSH2_MSG_CHANNEL_EOF,
  1965. $this->server_channels[$client_channel]);
  1966. if (!$this->_send_binary_packet($packet)) {
  1967. return false;
  1968. }
  1969. while ($this->_get_channel_packet($client_channel) !== true);
  1970. }
  1971. /**
  1972. * Disconnect
  1973. *
  1974. * @param Integer $reason
  1975. * @return Boolean
  1976. * @access private
  1977. */
  1978. function _disconnect($reason)
  1979. {
  1980. if ($this->bitmap) {
  1981. $data = pack('CNNa*Na*', NET_SSH2_MSG_DISCONNECT, $reason, 0, '', 0, '');
  1982. $this->_send_binary_packet($data);
  1983. $this->bitmap = 0;
  1984. fclose($this->fsock);
  1985. return false;
  1986. }
  1987. }
  1988. /**
  1989. * String Shift
  1990. *
  1991. * Inspired by array_shift
  1992. *
  1993. * @param String $string
  1994. * @param optional Integer $index
  1995. * @return String
  1996. * @access private
  1997. */
  1998. function _string_shift(&$string, $index = 1)
  1999. {
  2000. $substr = substr($string, 0, $index);
  2001. $string = substr($string, $index);
  2002. return $substr;
  2003. }
  2004. /**
  2005. * Define Array
  2006. *
  2007. * Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of
  2008. * named constants from it, using the value as the name of the constant and the index as the value of the constant.
  2009. * If any of the constants that would be defined already exists, none of the constants will be defined.
  2010. *
  2011. * @param Array $array
  2012. * @access private
  2013. */
  2014. function _define_array()
  2015. {
  2016. $args = func_get_args();
  2017. foreach ($args as $arg) {
  2018. foreach ($arg as $key=>$value) {
  2019. if (!defined($value)) {
  2020. define($value, $key);
  2021. } else {
  2022. break 2;
  2023. }
  2024. }
  2025. }
  2026. }
  2027. /**
  2028. * Returns a log of the packets that have been sent and received.
  2029. *
  2030. * Returns a string if NET_SSH2_LOGGING == NET_SSH2_LOG_COMPLEX, an array if NET_SSH2_LOGGING == NET_SSH2_LOG_SIMPLE and false if !defined('NET_SSH2_LOGGING')
  2031. *
  2032. * @access public
  2033. * @return String or Array
  2034. */
  2035. function getLog()
  2036. {
  2037. if (!defined('NET_SSH2_LOGGING')) {
  2038. return false;
  2039. }
  2040. switch (NET_SSH2_LOGGING) {
  2041. case NET_SSH2_LOG_SIMPLE:
  2042. return $this->message_number_log;
  2043. break;
  2044. case NET_SSH2_LOG_COMPLEX:
  2045. return $this->_format_log($this->message_log, $this->message_number_log);
  2046. break;
  2047. default:
  2048. return false;
  2049. }
  2050. }
  2051. /**
  2052. * Formats a log for printing
  2053. *
  2054. * @param Array $message_log
  2055. * @param Array $message_number_log
  2056. * @access private
  2057. * @return String
  2058. */
  2059. function _format_log($message_log, $message_number_log)
  2060. {
  2061. static $boundary = ':', $long_width = 65, $short_width = 16;
  2062. $output = '';
  2063. for ($i = 0; $i < count($message_log); $i++) {
  2064. $output.= $message_number_log[$i] . "\r\n";
  2065. $current_log = $message_log[$i];
  2066. $j = 0;
  2067. do {
  2068. if (!empty($current_log)) {
  2069. $output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 ';
  2070. }
  2071. $fragment = $this->_string_shift($current_log, $short_width);
  2072. $hex = substr(
  2073. preg_replace(
  2074. '#(.)#es',
  2075. '"' . $boundary . '" . str_pad(dechex(ord(substr("\\1", -1))), 2, "0", STR_PAD_LEFT)',
  2076. $fragment),
  2077. strlen($boundary)
  2078. );
  2079. // replace non ASCII printable characters with dots
  2080. // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
  2081. // also replace < with a . since < messes up the output on web browsers
  2082. $raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment);
  2083. $output.= str_pad($hex, $long_width - $short_width, ' ') . $raw . "\r\n";
  2084. $j++;
  2085. } while (!empty($current_log));
  2086. $output.= "\r\n";
  2087. }
  2088. return $output;
  2089. }
  2090. /**
  2091. * Returns all errors
  2092. *
  2093. * @return String
  2094. * @access public
  2095. */
  2096. function getErrors()
  2097. {
  2098. return $this->errors;
  2099. }
  2100. /**
  2101. * Returns the last error
  2102. *
  2103. * @return String
  2104. * @access public
  2105. */
  2106. function getLastError()
  2107. {
  2108. return $this->errors[count($this->errors) - 1];
  2109. }
  2110. /**
  2111. * Return the server identification.
  2112. *
  2113. * @return String
  2114. * @access public
  2115. */
  2116. function getServerIdentification()
  2117. {
  2118. return $this->server_identifier;
  2119. }
  2120. /**
  2121. * Return a list of the key exchange algorithms the server supports.
  2122. *
  2123. * @return Array
  2124. * @access public
  2125. */
  2126. function getKexAlgorithms()
  2127. {
  2128. return $this->kex_algorithms;
  2129. }
  2130. /**
  2131. * Return a list of the host key (public key) algorithms the server supports.
  2132. *
  2133. * @return Array
  2134. * @access public
  2135. */
  2136. function getServerHostKeyAlgorithms()
  2137. {
  2138. return $this->server_host_key_algorithms;
  2139. }
  2140. /**
  2141. * Return a list of the (symmetric key) encryption algorithms the server supports, when receiving stuff from the client.
  2142. *
  2143. * @return Array
  2144. * @access public
  2145. */
  2146. function getEncryptionAlgorithmsClient2Server()
  2147. {
  2148. return $this->encryption_algorithms_client_to_server;
  2149. }
  2150. /**
  2151. * Return a list of the (symmetric key) encryption algorithms the server supports, when sending stuff to the client.
  2152. *
  2153. * @return Array
  2154. * @access public
  2155. */
  2156. function getEncryptionAlgorithmsServer2Client()
  2157. {
  2158. return $this->encryption_algorithms_server_to_client;
  2159. }
  2160. /**
  2161. * Return a list of the MAC algorithms the server supports, when receiving stuff from the client.
  2162. *
  2163. * @return Array
  2164. * @access public
  2165. */
  2166. function getMACAlgorithmsClient2Server()
  2167. {
  2168. return $this->mac_algorithms_client_to_server;
  2169. }
  2170. /**
  2171. * Return a list of the MAC algorithms the server supports, when sending stuff to the client.
  2172. *
  2173. * @return Array
  2174. * @access public
  2175. */
  2176. function getMACAlgorithmsServer2Client()
  2177. {
  2178. return $this->mac_algorithms_server_to_client;
  2179. }
  2180. /**
  2181. * Return a list of the compression algorithms the server supports, when receiving stuff from the client.
  2182. *
  2183. * @return Array
  2184. * @access public
  2185. */
  2186. function getCompressionAlgorithmsClient2Server()
  2187. {
  2188. return $this->compression_algorithms_client_to_server;
  2189. }
  2190. /**
  2191. * Return a list of the compression algorithms the server supports, when sending stuff to the client.
  2192. *
  2193. * @return Array
  2194. * @access public
  2195. */
  2196. function getCompressionAlgorithmsServer2Client()
  2197. {
  2198. return $this->compression_algorithms_server_to_client;
  2199. }
  2200. /**
  2201. * Return a list of the languages the server supports, when sending stuff to the client.
  2202. *
  2203. * @return Array
  2204. * @access public
  2205. */
  2206. function getLanguagesServer2Client()
  2207. {
  2208. return $this->languages_server_to_client;
  2209. }
  2210. /**
  2211. * Return a list of the languages the server supports, when receiving stuff from the client.
  2212. *
  2213. * @return Array
  2214. * @access public
  2215. */
  2216. function getLanguagesClient2Server()
  2217. {
  2218. return $this->languages_client_to_server;
  2219. }
  2220. /**
  2221. * Returns the server public host key.
  2222. *
  2223. * Caching this the first time you connect to a server and checking the result on subsequent connections
  2224. * is recommended. Returns false if the server signature is not signed correctly with the public host key.
  2225. *
  2226. * @return Mixed
  2227. * @access public
  2228. */
  2229. function getServerPublicHostKey()
  2230. {
  2231. $signature = $this->signature;
  2232. $server_public_host_key = $this->server_public_host_key;
  2233. extract(unpack('Nlength', $this->_string_shift($server_public_host_key, 4)));
  2234. $this->_string_shift($server_public_host_key, $length);
  2235. switch ($this->signature_format) {
  2236. case 'ssh-dss':
  2237. $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
  2238. $p = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
  2239. $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
  2240. $q = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
  2241. $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
  2242. $g = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
  2243. $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
  2244. $y = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
  2245. /* The value for 'dss_signature_blob' is encoded as a string containing
  2246. r, followed by s (which are 160-bit integers, without lengths or
  2247. padding, unsigned, and in network byte order). */
  2248. $temp = unpack('Nlength', $this->_string_shift($signature, 4));
  2249. if ($temp['length'] != 40) {
  2250. user_error('Invalid signature', E_USER_NOTICE);
  2251. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  2252. }
  2253. $r = new Math_BigInteger($this->_string_shift($signature, 20), 256);
  2254. $s = new Math_BigInteger($this->_string_shift($signature, 20), 256);
  2255. if ($r->compare($q) >= 0 || $s->compare($q) >= 0) {
  2256. user_error('Invalid signature', E_USER_NOTICE);
  2257. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  2258. }
  2259. $w = $s->modInverse($q);
  2260. $u1 = $w->multiply(new Math_BigInteger(sha1($this->exchange_hash), 16));
  2261. list(, $u1) = $u1->divide($q);
  2262. $u2 = $w->multiply($r);
  2263. list(, $u2) = $u2->divide($q);
  2264. $g = $g->modPow($u1, $p);
  2265. $y = $y->modPow($u2, $p);
  2266. $v = $g->multiply($y);
  2267. list(, $v) = $v->divide($p);
  2268. list(, $v) = $v->divide($q);
  2269. if (!$v->equals($r)) {
  2270. user_error('Bad server signature', E_USER_NOTICE);
  2271. return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE);
  2272. }
  2273. break;
  2274. case 'ssh-rsa':
  2275. $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
  2276. $e = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
  2277. $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
  2278. $n = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
  2279. $nLength = $temp['length'];
  2280. /*
  2281. $temp = unpack('Nlength', $this->_string_shift($signature, 4));
  2282. $signature = $this->_string_shift($signature, $temp['length']);
  2283. $rsa = new Crypt_RSA();
  2284. $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);
  2285. $rsa->loadKey(array('e' => $e, 'n' => $n), CRYPT_RSA_PUBLIC_FORMAT_RAW);
  2286. if (!$rsa->verify($this->exchange_hash, $signature)) {
  2287. user_error('Bad server signature', E_USER_NOTICE);
  2288. return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE);
  2289. }
  2290. */
  2291. $temp = unpack('Nlength', $this->_string_shift($signature, 4));
  2292. $s = new Math_BigInteger($this->_string_shift($signature, $temp['length']), 256);
  2293. // validate an RSA signature per "8.2 RSASSA-PKCS1-v1_5", "5.2.2 RSAVP1", and "9.1 EMSA-PSS" in the
  2294. // following URL:
  2295. // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf
  2296. // also, see SSHRSA.c (rsa2_verifysig) in PuTTy's source.
  2297. if ($s->compare(new Math_BigInteger()) < 0 || $s->compare($n->subtract(new Math_BigInteger(1))) > 0) {
  2298. user_error('Invalid signature', E_USER_NOTICE);
  2299. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  2300. }
  2301. $s = $s->modPow($e, $n);
  2302. $s = $s->toBytes();
  2303. $h = pack('N4H*', 0x00302130, 0x0906052B, 0x0E03021A, 0x05000414, sha1($this->exchange_hash));
  2304. $h = chr(0x01) . str_repeat(chr(0xFF), $nLength - 3 - strlen($h)) . $h;
  2305. if ($s != $h) {
  2306. user_error('Bad server signature', E_USER_NOTICE);
  2307. return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE);
  2308. }
  2309. }
  2310. return $this->server_public_host_key;
  2311. }
  2312. }