PageRenderTime 56ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/apps/files_external/3rdparty/phpseclib/phpseclib/Net/SSH1.php

https://github.com/sezuan/core
PHP | 1577 lines | 690 code | 156 blank | 731 comment | 101 complexity | fd456427c04d6ebbe5adaa7386e75bbd MD5 | raw file
Possible License(s): AGPL-3.0, AGPL-1.0, MPL-2.0-no-copyleft-exception

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Pure-PHP implementation of SSHv1.
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * Here's a short example of how to use this library:
  9. * <code>
  10. * <?php
  11. * include('Net/SSH1.php');
  12. *
  13. * $ssh = new Net_SSH1('www.domain.tld');
  14. * if (!$ssh->login('username', 'password')) {
  15. * exit('Login Failed');
  16. * }
  17. *
  18. * echo $ssh->exec('ls -la');
  19. * ?>
  20. * </code>
  21. *
  22. * Here's another short example:
  23. * <code>
  24. * <?php
  25. * include('Net/SSH1.php');
  26. *
  27. * $ssh = new Net_SSH1('www.domain.tld');
  28. * if (!$ssh->login('username', 'password')) {
  29. * exit('Login Failed');
  30. * }
  31. *
  32. * echo $ssh->read('username@username:~$');
  33. * $ssh->write("ls -la\n");
  34. * echo $ssh->read('username@username:~$');
  35. * ?>
  36. * </code>
  37. *
  38. * More information on the SSHv1 specification can be found by reading
  39. * {@link http://www.snailbook.com/docs/protocol-1.5.txt protocol-1.5.txt}.
  40. *
  41. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  42. * of this software and associated documentation files (the "Software"), to deal
  43. * in the Software without restriction, including without limitation the rights
  44. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  45. * copies of the Software, and to permit persons to whom the Software is
  46. * furnished to do so, subject to the following conditions:
  47. *
  48. * The above copyright notice and this permission notice shall be included in
  49. * all copies or substantial portions of the Software.
  50. *
  51. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  52. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  53. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  54. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  55. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  56. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  57. * THE SOFTWARE.
  58. *
  59. * @category Net
  60. * @package Net_SSH1
  61. * @author Jim Wigginton <terrafrost@php.net>
  62. * @copyright MMVII Jim Wigginton
  63. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  64. * @version $Id: SSH1.php,v 1.15 2010/03/22 22:01:38 terrafrost Exp $
  65. * @link http://phpseclib.sourceforge.net
  66. */
  67. /**
  68. * Include Math_BigInteger
  69. *
  70. * Used to do RSA encryption.
  71. */
  72. if (!class_exists('Math_BigInteger')) {
  73. require_once('Math/BigInteger.php');
  74. }
  75. /**
  76. * Include Crypt_Null
  77. */
  78. //require_once('Crypt/Null.php');
  79. /**
  80. * Include Crypt_DES
  81. */
  82. if (!class_exists('Crypt_DES')) {
  83. require_once('Crypt/DES.php');
  84. }
  85. /**
  86. * Include Crypt_TripleDES
  87. */
  88. if (!class_exists('Crypt_TripleDES')) {
  89. require_once('Crypt/TripleDES.php');
  90. }
  91. /**
  92. * Include Crypt_RC4
  93. */
  94. if (!class_exists('Crypt_RC4')) {
  95. require_once('Crypt/RC4.php');
  96. }
  97. /**
  98. * Include Crypt_Random
  99. */
  100. // the class_exists() will only be called if the crypt_random_string function hasn't been defined and
  101. // will trigger a call to __autoload() if you're wanting to auto-load classes
  102. // call function_exists() a second time to stop the require_once from being called outside
  103. // of the auto loader
  104. if (!function_exists('crypt_random_string') && !class_exists('Crypt_Random') && !function_exists('crypt_random_string')) {
  105. require_once('Crypt/Random.php');
  106. }
  107. /**#@+
  108. * Encryption Methods
  109. *
  110. * @see Net_SSH1::getSupportedCiphers()
  111. * @access public
  112. */
  113. /**
  114. * No encryption
  115. *
  116. * Not supported.
  117. */
  118. define('NET_SSH1_CIPHER_NONE', 0);
  119. /**
  120. * IDEA in CFB mode
  121. *
  122. * Not supported.
  123. */
  124. define('NET_SSH1_CIPHER_IDEA', 1);
  125. /**
  126. * DES in CBC mode
  127. */
  128. define('NET_SSH1_CIPHER_DES', 2);
  129. /**
  130. * Triple-DES in CBC mode
  131. *
  132. * All implementations are required to support this
  133. */
  134. define('NET_SSH1_CIPHER_3DES', 3);
  135. /**
  136. * TRI's Simple Stream encryption CBC
  137. *
  138. * Not supported nor is it defined in the official SSH1 specs. OpenSSH, however, does define it (see cipher.h),
  139. * although it doesn't use it (see cipher.c)
  140. */
  141. define('NET_SSH1_CIPHER_BROKEN_TSS', 4);
  142. /**
  143. * RC4
  144. *
  145. * Not supported.
  146. *
  147. * @internal According to the SSH1 specs:
  148. *
  149. * "The first 16 bytes of the session key are used as the key for
  150. * the server to client direction. The remaining 16 bytes are used
  151. * as the key for the client to server direction. This gives
  152. * independent 128-bit keys for each direction."
  153. *
  154. * This library currently only supports encryption when the same key is being used for both directions. This is
  155. * because there's only one $crypto object. Two could be added ($encrypt and $decrypt, perhaps).
  156. */
  157. define('NET_SSH1_CIPHER_RC4', 5);
  158. /**
  159. * Blowfish
  160. *
  161. * Not supported nor is it defined in the official SSH1 specs. OpenSSH, however, defines it (see cipher.h) and
  162. * uses it (see cipher.c)
  163. */
  164. define('NET_SSH1_CIPHER_BLOWFISH', 6);
  165. /**#@-*/
  166. /**#@+
  167. * Authentication Methods
  168. *
  169. * @see Net_SSH1::getSupportedAuthentications()
  170. * @access public
  171. */
  172. /**
  173. * .rhosts or /etc/hosts.equiv
  174. */
  175. define('NET_SSH1_AUTH_RHOSTS', 1);
  176. /**
  177. * pure RSA authentication
  178. */
  179. define('NET_SSH1_AUTH_RSA', 2);
  180. /**
  181. * password authentication
  182. *
  183. * This is the only method that is supported by this library.
  184. */
  185. define('NET_SSH1_AUTH_PASSWORD', 3);
  186. /**
  187. * .rhosts with RSA host authentication
  188. */
  189. define('NET_SSH1_AUTH_RHOSTS_RSA', 4);
  190. /**#@-*/
  191. /**#@+
  192. * Terminal Modes
  193. *
  194. * @link http://3sp.com/content/developer/maverick-net/docs/Maverick.SSH.PseudoTerminalModesMembers.html
  195. * @access private
  196. */
  197. define('NET_SSH1_TTY_OP_END', 0);
  198. /**#@-*/
  199. /**
  200. * The Response Type
  201. *
  202. * @see Net_SSH1::_get_binary_packet()
  203. * @access private
  204. */
  205. define('NET_SSH1_RESPONSE_TYPE', 1);
  206. /**
  207. * The Response Data
  208. *
  209. * @see Net_SSH1::_get_binary_packet()
  210. * @access private
  211. */
  212. define('NET_SSH1_RESPONSE_DATA', 2);
  213. /**#@+
  214. * Execution Bitmap Masks
  215. *
  216. * @see Net_SSH1::bitmap
  217. * @access private
  218. */
  219. define('NET_SSH1_MASK_CONSTRUCTOR', 0x00000001);
  220. define('NET_SSH1_MASK_LOGIN', 0x00000002);
  221. define('NET_SSH1_MASK_SHELL', 0x00000004);
  222. /**#@-*/
  223. /**#@+
  224. * @access public
  225. * @see Net_SSH1::getLog()
  226. */
  227. /**
  228. * Returns the message numbers
  229. */
  230. define('NET_SSH1_LOG_SIMPLE', 1);
  231. /**
  232. * Returns the message content
  233. */
  234. define('NET_SSH1_LOG_COMPLEX', 2);
  235. /**
  236. * Outputs the content real-time
  237. */
  238. define('NET_SSH2_LOG_REALTIME', 3);
  239. /**
  240. * Dumps the content real-time to a file
  241. */
  242. define('NET_SSH2_LOG_REALTIME_FILE', 4);
  243. /**#@-*/
  244. /**#@+
  245. * @access public
  246. * @see Net_SSH1::read()
  247. */
  248. /**
  249. * Returns when a string matching $expect exactly is found
  250. */
  251. define('NET_SSH1_READ_SIMPLE', 1);
  252. /**
  253. * Returns when a string matching the regular expression $expect is found
  254. */
  255. define('NET_SSH1_READ_REGEX', 2);
  256. /**#@-*/
  257. /**
  258. * Pure-PHP implementation of SSHv1.
  259. *
  260. * @author Jim Wigginton <terrafrost@php.net>
  261. * @version 0.1.0
  262. * @access public
  263. * @package Net_SSH1
  264. */
  265. class Net_SSH1 {
  266. /**
  267. * The SSH identifier
  268. *
  269. * @var String
  270. * @access private
  271. */
  272. var $identifier = 'SSH-1.5-phpseclib';
  273. /**
  274. * The Socket Object
  275. *
  276. * @var Object
  277. * @access private
  278. */
  279. var $fsock;
  280. /**
  281. * The cryptography object
  282. *
  283. * @var Object
  284. * @access private
  285. */
  286. var $crypto = false;
  287. /**
  288. * Execution Bitmap
  289. *
  290. * The bits that are set represent functions that have been called already. This is used to determine
  291. * if a requisite function has been successfully executed. If not, an error should be thrown.
  292. *
  293. * @var Integer
  294. * @access private
  295. */
  296. var $bitmap = 0;
  297. /**
  298. * The Server Key Public Exponent
  299. *
  300. * Logged for debug purposes
  301. *
  302. * @see Net_SSH1::getServerKeyPublicExponent()
  303. * @var String
  304. * @access private
  305. */
  306. var $server_key_public_exponent;
  307. /**
  308. * The Server Key Public Modulus
  309. *
  310. * Logged for debug purposes
  311. *
  312. * @see Net_SSH1::getServerKeyPublicModulus()
  313. * @var String
  314. * @access private
  315. */
  316. var $server_key_public_modulus;
  317. /**
  318. * The Host Key Public Exponent
  319. *
  320. * Logged for debug purposes
  321. *
  322. * @see Net_SSH1::getHostKeyPublicExponent()
  323. * @var String
  324. * @access private
  325. */
  326. var $host_key_public_exponent;
  327. /**
  328. * The Host Key Public Modulus
  329. *
  330. * Logged for debug purposes
  331. *
  332. * @see Net_SSH1::getHostKeyPublicModulus()
  333. * @var String
  334. * @access private
  335. */
  336. var $host_key_public_modulus;
  337. /**
  338. * Supported Ciphers
  339. *
  340. * Logged for debug purposes
  341. *
  342. * @see Net_SSH1::getSupportedCiphers()
  343. * @var Array
  344. * @access private
  345. */
  346. var $supported_ciphers = array(
  347. NET_SSH1_CIPHER_NONE => 'No encryption',
  348. NET_SSH1_CIPHER_IDEA => 'IDEA in CFB mode',
  349. NET_SSH1_CIPHER_DES => 'DES in CBC mode',
  350. NET_SSH1_CIPHER_3DES => 'Triple-DES in CBC mode',
  351. NET_SSH1_CIPHER_BROKEN_TSS => 'TRI\'s Simple Stream encryption CBC',
  352. NET_SSH1_CIPHER_RC4 => 'RC4',
  353. NET_SSH1_CIPHER_BLOWFISH => 'Blowfish'
  354. );
  355. /**
  356. * Supported Authentications
  357. *
  358. * Logged for debug purposes
  359. *
  360. * @see Net_SSH1::getSupportedAuthentications()
  361. * @var Array
  362. * @access private
  363. */
  364. var $supported_authentications = array(
  365. NET_SSH1_AUTH_RHOSTS => '.rhosts or /etc/hosts.equiv',
  366. NET_SSH1_AUTH_RSA => 'pure RSA authentication',
  367. NET_SSH1_AUTH_PASSWORD => 'password authentication',
  368. NET_SSH1_AUTH_RHOSTS_RSA => '.rhosts with RSA host authentication'
  369. );
  370. /**
  371. * Server Identification
  372. *
  373. * @see Net_SSH1::getServerIdentification()
  374. * @var String
  375. * @access private
  376. */
  377. var $server_identification = '';
  378. /**
  379. * Protocol Flags
  380. *
  381. * @see Net_SSH1::Net_SSH1()
  382. * @var Array
  383. * @access private
  384. */
  385. var $protocol_flags = array();
  386. /**
  387. * Protocol Flag Log
  388. *
  389. * @see Net_SSH1::getLog()
  390. * @var Array
  391. * @access private
  392. */
  393. var $protocol_flag_log = array();
  394. /**
  395. * Message Log
  396. *
  397. * @see Net_SSH1::getLog()
  398. * @var Array
  399. * @access private
  400. */
  401. var $message_log = array();
  402. /**
  403. * Real-time log file pointer
  404. *
  405. * @see Net_SSH1::_append_log()
  406. * @var Resource
  407. * @access private
  408. */
  409. var $realtime_log_file;
  410. /**
  411. * Real-time log file size
  412. *
  413. * @see Net_SSH1::_append_log()
  414. * @var Integer
  415. * @access private
  416. */
  417. var $realtime_log_size;
  418. /**
  419. * Real-time log file wrap boolean
  420. *
  421. * @see Net_SSH1::_append_log()
  422. * @var Boolean
  423. * @access private
  424. */
  425. var $realtime_log_wrap;
  426. /**
  427. * Interactive Buffer
  428. *
  429. * @see Net_SSH1::read()
  430. * @var Array
  431. * @access private
  432. */
  433. var $interactiveBuffer = '';
  434. /**
  435. * Timeout
  436. *
  437. * @see Net_SSH1::setTimeout()
  438. * @access private
  439. */
  440. var $timeout;
  441. /**
  442. * Current Timeout
  443. *
  444. * @see Net_SSH2::_get_channel_packet()
  445. * @access private
  446. */
  447. var $curTimeout;
  448. /**
  449. * Default Constructor.
  450. *
  451. * Connects to an SSHv1 server
  452. *
  453. * @param String $host
  454. * @param optional Integer $port
  455. * @param optional Integer $timeout
  456. * @param optional Integer $cipher
  457. * @return Net_SSH1
  458. * @access public
  459. */
  460. function Net_SSH1($host, $port = 22, $timeout = 10, $cipher = NET_SSH1_CIPHER_3DES)
  461. {
  462. $this->protocol_flags = array(
  463. 1 => 'NET_SSH1_MSG_DISCONNECT',
  464. 2 => 'NET_SSH1_SMSG_PUBLIC_KEY',
  465. 3 => 'NET_SSH1_CMSG_SESSION_KEY',
  466. 4 => 'NET_SSH1_CMSG_USER',
  467. 9 => 'NET_SSH1_CMSG_AUTH_PASSWORD',
  468. 10 => 'NET_SSH1_CMSG_REQUEST_PTY',
  469. 12 => 'NET_SSH1_CMSG_EXEC_SHELL',
  470. 13 => 'NET_SSH1_CMSG_EXEC_CMD',
  471. 14 => 'NET_SSH1_SMSG_SUCCESS',
  472. 15 => 'NET_SSH1_SMSG_FAILURE',
  473. 16 => 'NET_SSH1_CMSG_STDIN_DATA',
  474. 17 => 'NET_SSH1_SMSG_STDOUT_DATA',
  475. 18 => 'NET_SSH1_SMSG_STDERR_DATA',
  476. 19 => 'NET_SSH1_CMSG_EOF',
  477. 20 => 'NET_SSH1_SMSG_EXITSTATUS',
  478. 33 => 'NET_SSH1_CMSG_EXIT_CONFIRMATION'
  479. );
  480. $this->_define_array($this->protocol_flags);
  481. $this->fsock = @fsockopen($host, $port, $errno, $errstr, $timeout);
  482. if (!$this->fsock) {
  483. user_error(rtrim("Cannot connect to $host. Error $errno. $errstr"));
  484. return;
  485. }
  486. $this->server_identification = $init_line = fgets($this->fsock, 255);
  487. if (defined('NET_SSH1_LOGGING')) {
  488. $this->_append_log('<-', $this->server_identification);
  489. $this->_append_log('->', $this->identifier . "\r\n");
  490. }
  491. if (!preg_match('#SSH-([0-9\.]+)-(.+)#', $init_line, $parts)) {
  492. user_error('Can only connect to SSH servers');
  493. return;
  494. }
  495. if ($parts[1][0] != 1) {
  496. user_error("Cannot connect to SSH $parts[1] servers");
  497. return;
  498. }
  499. fputs($this->fsock, $this->identifier."\r\n");
  500. $response = $this->_get_binary_packet();
  501. if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_PUBLIC_KEY) {
  502. user_error('Expected SSH_SMSG_PUBLIC_KEY');
  503. return;
  504. }
  505. $anti_spoofing_cookie = $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 8);
  506. $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4);
  507. $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
  508. $server_key_public_exponent = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
  509. $this->server_key_public_exponent = $server_key_public_exponent;
  510. $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
  511. $server_key_public_modulus = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
  512. $this->server_key_public_modulus = $server_key_public_modulus;
  513. $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4);
  514. $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
  515. $host_key_public_exponent = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
  516. $this->host_key_public_exponent = $host_key_public_exponent;
  517. $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
  518. $host_key_public_modulus = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
  519. $this->host_key_public_modulus = $host_key_public_modulus;
  520. $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4);
  521. // get a list of the supported ciphers
  522. extract(unpack('Nsupported_ciphers_mask', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4)));
  523. foreach ($this->supported_ciphers as $mask=>$name) {
  524. if (($supported_ciphers_mask & (1 << $mask)) == 0) {
  525. unset($this->supported_ciphers[$mask]);
  526. }
  527. }
  528. // get a list of the supported authentications
  529. extract(unpack('Nsupported_authentications_mask', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4)));
  530. foreach ($this->supported_authentications as $mask=>$name) {
  531. if (($supported_authentications_mask & (1 << $mask)) == 0) {
  532. unset($this->supported_authentications[$mask]);
  533. }
  534. }
  535. $session_id = pack('H*', md5($host_key_public_modulus->toBytes() . $server_key_public_modulus->toBytes() . $anti_spoofing_cookie));
  536. $session_key = crypt_random_string(32);
  537. $double_encrypted_session_key = $session_key ^ str_pad($session_id, 32, chr(0));
  538. if ($server_key_public_modulus->compare($host_key_public_modulus) < 0) {
  539. $double_encrypted_session_key = $this->_rsa_crypt(
  540. $double_encrypted_session_key,
  541. array(
  542. $server_key_public_exponent,
  543. $server_key_public_modulus
  544. )
  545. );
  546. $double_encrypted_session_key = $this->_rsa_crypt(
  547. $double_encrypted_session_key,
  548. array(
  549. $host_key_public_exponent,
  550. $host_key_public_modulus
  551. )
  552. );
  553. } else {
  554. $double_encrypted_session_key = $this->_rsa_crypt(
  555. $double_encrypted_session_key,
  556. array(
  557. $host_key_public_exponent,
  558. $host_key_public_modulus
  559. )
  560. );
  561. $double_encrypted_session_key = $this->_rsa_crypt(
  562. $double_encrypted_session_key,
  563. array(
  564. $server_key_public_exponent,
  565. $server_key_public_modulus
  566. )
  567. );
  568. }
  569. $cipher = isset($this->supported_ciphers[$cipher]) ? $cipher : NET_SSH1_CIPHER_3DES;
  570. $data = pack('C2a*na*N', NET_SSH1_CMSG_SESSION_KEY, $cipher, $anti_spoofing_cookie, 8 * strlen($double_encrypted_session_key), $double_encrypted_session_key, 0);
  571. if (!$this->_send_binary_packet($data)) {
  572. user_error('Error sending SSH_CMSG_SESSION_KEY');
  573. return;
  574. }
  575. switch ($cipher) {
  576. //case NET_SSH1_CIPHER_NONE:
  577. // $this->crypto = new Crypt_Null();
  578. // break;
  579. case NET_SSH1_CIPHER_DES:
  580. $this->crypto = new Crypt_DES();
  581. $this->crypto->disablePadding();
  582. $this->crypto->enableContinuousBuffer();
  583. $this->crypto->setKey(substr($session_key, 0, 8));
  584. break;
  585. case NET_SSH1_CIPHER_3DES:
  586. $this->crypto = new Crypt_TripleDES(CRYPT_DES_MODE_3CBC);
  587. $this->crypto->disablePadding();
  588. $this->crypto->enableContinuousBuffer();
  589. $this->crypto->setKey(substr($session_key, 0, 24));
  590. break;
  591. //case NET_SSH1_CIPHER_RC4:
  592. // $this->crypto = new Crypt_RC4();
  593. // $this->crypto->enableContinuousBuffer();
  594. // $this->crypto->setKey(substr($session_key, 0, 16));
  595. // break;
  596. }
  597. $response = $this->_get_binary_packet();
  598. if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) {
  599. user_error('Expected SSH_SMSG_SUCCESS');
  600. return;
  601. }
  602. $this->bitmap = NET_SSH1_MASK_CONSTRUCTOR;
  603. }
  604. /**
  605. * Login
  606. *
  607. * @param String $username
  608. * @param optional String $password
  609. * @return Boolean
  610. * @access public
  611. */
  612. function login($username, $password = '')
  613. {
  614. if (!($this->bitmap & NET_SSH1_MASK_CONSTRUCTOR)) {
  615. return false;
  616. }
  617. $data = pack('CNa*', NET_SSH1_CMSG_USER, strlen($username), $username);
  618. if (!$this->_send_binary_packet($data)) {
  619. user_error('Error sending SSH_CMSG_USER');
  620. return false;
  621. }
  622. $response = $this->_get_binary_packet();
  623. if ($response === true) {
  624. return false;
  625. }
  626. if ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_SUCCESS) {
  627. $this->bitmap |= NET_SSH1_MASK_LOGIN;
  628. return true;
  629. } else if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_FAILURE) {
  630. user_error('Expected SSH_SMSG_SUCCESS or SSH_SMSG_FAILURE');
  631. return false;
  632. }
  633. $data = pack('CNa*', NET_SSH1_CMSG_AUTH_PASSWORD, strlen($password), $password);
  634. if (!$this->_send_binary_packet($data)) {
  635. user_error('Error sending SSH_CMSG_AUTH_PASSWORD');
  636. return false;
  637. }
  638. // remove the username and password from the last logged packet
  639. if (defined('NET_SSH1_LOGGING') && NET_SSH1_LOGGING == NET_SSH1_LOG_COMPLEX) {
  640. $data = pack('CNa*', NET_SSH1_CMSG_AUTH_PASSWORD, strlen('password'), 'password');
  641. $this->message_log[count($this->message_log) - 1] = $data;
  642. }
  643. $response = $this->_get_binary_packet();
  644. if ($response === true) {
  645. return false;
  646. }
  647. if ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_SUCCESS) {
  648. $this->bitmap |= NET_SSH1_MASK_LOGIN;
  649. return true;
  650. } else if ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_FAILURE) {
  651. return false;
  652. } else {
  653. user_error('Expected SSH_SMSG_SUCCESS or SSH_SMSG_FAILURE');
  654. return false;
  655. }
  656. }
  657. /**
  658. * Set Timeout
  659. *
  660. * $ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely. setTimeout() makes it so it'll timeout.
  661. * Setting $timeout to false or 0 will mean there is no timeout.
  662. *
  663. * @param Mixed $timeout
  664. */
  665. function setTimeout($timeout)
  666. {
  667. $this->timeout = $this->curTimeout = $timeout;
  668. }
  669. /**
  670. * Executes a command on a non-interactive shell, returns the output, and quits.
  671. *
  672. * An SSH1 server will close the connection after a command has been executed on a non-interactive shell. SSH2
  673. * servers don't, however, this isn't an SSH2 client. The way this works, on the server, is by initiating a
  674. * shell with the -s option, as discussed in the following links:
  675. *
  676. * {@link http://www.faqs.org/docs/bashman/bashref_65.html http://www.faqs.org/docs/bashman/bashref_65.html}
  677. * {@link http://www.faqs.org/docs/bashman/bashref_62.html http://www.faqs.org/docs/bashman/bashref_62.html}
  678. *
  679. * To execute further commands, a new Net_SSH1 object will need to be created.
  680. *
  681. * Returns false on failure and the output, otherwise.
  682. *
  683. * @see Net_SSH1::interactiveRead()
  684. * @see Net_SSH1::interactiveWrite()
  685. * @param String $cmd
  686. * @return mixed
  687. * @access public
  688. */
  689. function exec($cmd, $block = true)
  690. {
  691. if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) {
  692. user_error('Operation disallowed prior to login()');
  693. return false;
  694. }
  695. $data = pack('CNa*', NET_SSH1_CMSG_EXEC_CMD, strlen($cmd), $cmd);
  696. if (!$this->_send_binary_packet($data)) {
  697. user_error('Error sending SSH_CMSG_EXEC_CMD');
  698. return false;
  699. }
  700. if (!$block) {
  701. return true;
  702. }
  703. $output = '';
  704. $response = $this->_get_binary_packet();
  705. if ($response !== false) {
  706. do {
  707. $output.= substr($response[NET_SSH1_RESPONSE_DATA], 4);
  708. $response = $this->_get_binary_packet();
  709. } while (is_array($response) && $response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_EXITSTATUS);
  710. }
  711. $data = pack('C', NET_SSH1_CMSG_EXIT_CONFIRMATION);
  712. // i don't think it's really all that important if this packet gets sent or not.
  713. $this->_send_binary_packet($data);
  714. fclose($this->fsock);
  715. // reset the execution bitmap - a new Net_SSH1 object needs to be created.
  716. $this->bitmap = 0;
  717. return $output;
  718. }
  719. /**
  720. * Creates an interactive shell
  721. *
  722. * @see Net_SSH1::interactiveRead()
  723. * @see Net_SSH1::interactiveWrite()
  724. * @return Boolean
  725. * @access private
  726. */
  727. function _initShell()
  728. {
  729. // connect using the sample parameters in protocol-1.5.txt.
  730. // according to wikipedia.org's entry on text terminals, "the fundamental type of application running on a text
  731. // terminal is a command line interpreter or shell". thus, opening a terminal session to run the shell.
  732. $data = pack('CNa*N4C', NET_SSH1_CMSG_REQUEST_PTY, strlen('vt100'), 'vt100', 24, 80, 0, 0, NET_SSH1_TTY_OP_END);
  733. if (!$this->_send_binary_packet($data)) {
  734. user_error('Error sending SSH_CMSG_REQUEST_PTY');
  735. return false;
  736. }
  737. $response = $this->_get_binary_packet();
  738. if ($response === true) {
  739. return false;
  740. }
  741. if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) {
  742. user_error('Expected SSH_SMSG_SUCCESS');
  743. return false;
  744. }
  745. $data = pack('C', NET_SSH1_CMSG_EXEC_SHELL);
  746. if (!$this->_send_binary_packet($data)) {
  747. user_error('Error sending SSH_CMSG_EXEC_SHELL');
  748. return false;
  749. }
  750. $this->bitmap |= NET_SSH1_MASK_SHELL;
  751. //stream_set_blocking($this->fsock, 0);
  752. return true;
  753. }
  754. /**
  755. * Inputs a command into an interactive shell.
  756. *
  757. * @see Net_SSH1::interactiveWrite()
  758. * @param String $cmd
  759. * @return Boolean
  760. * @access public
  761. */
  762. function write($cmd)
  763. {
  764. return $this->interactiveWrite($cmd);
  765. }
  766. /**
  767. * Returns the output of an interactive shell when there's a match for $expect
  768. *
  769. * $expect can take the form of a string literal or, if $mode == NET_SSH1_READ_REGEX,
  770. * a regular expression.
  771. *
  772. * @see Net_SSH1::write()
  773. * @param String $expect
  774. * @param Integer $mode
  775. * @return Boolean
  776. * @access public
  777. */
  778. function read($expect, $mode = NET_SSH1_READ_SIMPLE)
  779. {
  780. if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) {
  781. user_error('Operation disallowed prior to login()');
  782. return false;
  783. }
  784. if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) {
  785. user_error('Unable to initiate an interactive shell session');
  786. return false;
  787. }
  788. $match = $expect;
  789. while (true) {
  790. if ($mode == NET_SSH1_READ_REGEX) {
  791. preg_match($expect, $this->interactiveBuffer, $matches);
  792. $match = isset($matches[0]) ? $matches[0] : '';
  793. }
  794. $pos = strlen($match) ? strpos($this->interactiveBuffer, $match) : false;
  795. if ($pos !== false) {
  796. return $this->_string_shift($this->interactiveBuffer, $pos + strlen($match));
  797. }
  798. $response = $this->_get_binary_packet();
  799. if ($response === true) {
  800. return $this->_string_shift($this->interactiveBuffer, strlen($this->interactiveBuffer));
  801. }
  802. $this->interactiveBuffer.= substr($response[NET_SSH1_RESPONSE_DATA], 4);
  803. }
  804. }
  805. /**
  806. * Inputs a command into an interactive shell.
  807. *
  808. * @see Net_SSH1::interactiveRead()
  809. * @param String $cmd
  810. * @return Boolean
  811. * @access public
  812. */
  813. function interactiveWrite($cmd)
  814. {
  815. if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) {
  816. user_error('Operation disallowed prior to login()');
  817. return false;
  818. }
  819. if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) {
  820. user_error('Unable to initiate an interactive shell session');
  821. return false;
  822. }
  823. $data = pack('CNa*', NET_SSH1_CMSG_STDIN_DATA, strlen($cmd), $cmd);
  824. if (!$this->_send_binary_packet($data)) {
  825. user_error('Error sending SSH_CMSG_STDIN');
  826. return false;
  827. }
  828. return true;
  829. }
  830. /**
  831. * Returns the output of an interactive shell when no more output is available.
  832. *
  833. * Requires PHP 4.3.0 or later due to the use of the stream_select() function. If you see stuff like
  834. * "", you're seeing ANSI escape codes. According to
  835. * {@link http://support.microsoft.com/kb/101875 How to Enable ANSI.SYS in a Command Window}, "Windows NT
  836. * does not support ANSI escape sequences in Win32 Console applications", so if you're a Windows user,
  837. * there's not going to be much recourse.
  838. *
  839. * @see Net_SSH1::interactiveRead()
  840. * @return String
  841. * @access public
  842. */
  843. function interactiveRead()
  844. {
  845. if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) {
  846. user_error('Operation disallowed prior to login()');
  847. return false;
  848. }
  849. if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) {
  850. user_error('Unable to initiate an interactive shell session');
  851. return false;
  852. }
  853. $read = array($this->fsock);
  854. $write = $except = null;
  855. if (stream_select($read, $write, $except, 0)) {
  856. $response = $this->_get_binary_packet();
  857. return substr($response[NET_SSH1_RESPONSE_DATA], 4);
  858. } else {
  859. return '';
  860. }
  861. }
  862. /**
  863. * Disconnect
  864. *
  865. * @access public
  866. */
  867. function disconnect()
  868. {
  869. $this->_disconnect();
  870. }
  871. /**
  872. * Destructor.
  873. *
  874. * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
  875. * disconnect().
  876. *
  877. * @access public
  878. */
  879. function __destruct()
  880. {
  881. $this->_disconnect();
  882. }
  883. /**
  884. * Disconnect
  885. *
  886. * @param String $msg
  887. * @access private
  888. */
  889. function _disconnect($msg = 'Client Quit')
  890. {
  891. if ($this->bitmap) {
  892. $data = pack('C', NET_SSH1_CMSG_EOF);
  893. $this->_send_binary_packet($data);
  894. /*
  895. $response = $this->_get_binary_packet();
  896. if ($response === true) {
  897. $response = array(NET_SSH1_RESPONSE_TYPE => -1);
  898. }
  899. switch ($response[NET_SSH1_RESPONSE_TYPE]) {
  900. case NET_SSH1_SMSG_EXITSTATUS:
  901. $data = pack('C', NET_SSH1_CMSG_EXIT_CONFIRMATION);
  902. break;
  903. default:
  904. $data = pack('CNa*', NET_SSH1_MSG_DISCONNECT, strlen($msg), $msg);
  905. }
  906. */
  907. $data = pack('CNa*', NET_SSH1_MSG_DISCONNECT, strlen($msg), $msg);
  908. $this->_send_binary_packet($data);
  909. fclose($this->fsock);
  910. $this->bitmap = 0;
  911. }
  912. }
  913. /**
  914. * Gets Binary Packets
  915. *
  916. * See 'The Binary Packet Protocol' of protocol-1.5.txt for more info.
  917. *
  918. * Also, this function could be improved upon by adding detection for the following exploit:
  919. * http://www.securiteam.com/securitynews/5LP042K3FY.html
  920. *
  921. * @see Net_SSH1::_send_binary_packet()
  922. * @return Array
  923. * @access private
  924. */
  925. function _get_binary_packet()
  926. {
  927. if (feof($this->fsock)) {
  928. //user_error('connection closed prematurely');
  929. return false;
  930. }
  931. if ($this->curTimeout) {
  932. $read = array($this->fsock);
  933. $write = $except = NULL;
  934. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  935. $sec = floor($this->curTimeout);
  936. $usec = 1000000 * ($this->curTimeout - $sec);
  937. // on windows this returns a "Warning: Invalid CRT parameters detected" error
  938. if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
  939. //$this->_disconnect('Timeout');
  940. return true;
  941. }
  942. $elapsed = strtok(microtime(), ' ') + strtok('') - $start;
  943. $this->curTimeout-= $elapsed;
  944. }
  945. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  946. $temp = unpack('Nlength', fread($this->fsock, 4));
  947. $padding_length = 8 - ($temp['length'] & 7);
  948. $length = $temp['length'] + $padding_length;
  949. while ($length > 0) {
  950. $temp = fread($this->fsock, $length);
  951. $raw.= $temp;
  952. $length-= strlen($temp);
  953. }
  954. $stop = strtok(microtime(), ' ') + strtok('');
  955. if (strlen($raw) && $this->crypto !== false) {
  956. $raw = $this->crypto->decrypt($raw);
  957. }
  958. $padding = substr($raw, 0, $padding_length);
  959. $type = $raw[$padding_length];
  960. $data = substr($raw, $padding_length + 1, -4);
  961. $temp = unpack('Ncrc', substr($raw, -4));
  962. //if ( $temp['crc'] != $this->_crc($padding . $type . $data) ) {
  963. // user_error('Bad CRC in packet from server');
  964. // return false;
  965. //}
  966. $type = ord($type);
  967. if (defined('NET_SSH1_LOGGING')) {
  968. $temp = isset($this->protocol_flags[$type]) ? $this->protocol_flags[$type] : 'UNKNOWN';
  969. $temp = '<- ' . $temp .
  970. ' (' . round($stop - $start, 4) . 's)';
  971. $this->_append_log($temp, $data);
  972. }
  973. return array(
  974. NET_SSH1_RESPONSE_TYPE => $type,
  975. NET_SSH1_RESPONSE_DATA => $data
  976. );
  977. }
  978. /**
  979. * Sends Binary Packets
  980. *
  981. * Returns true on success, false on failure.
  982. *
  983. * @see Net_SSH1::_get_binary_packet()
  984. * @param String $data
  985. * @return Boolean
  986. * @access private
  987. */
  988. function _send_binary_packet($data)
  989. {
  990. if (feof($this->fsock)) {
  991. //user_error('connection closed prematurely');
  992. return false;
  993. }
  994. $length = strlen($data) + 4;
  995. $padding = crypt_random_string(8 - ($length & 7));
  996. $orig = $data;
  997. $data = $padding . $data;
  998. $data.= pack('N', $this->_crc($data));
  999. if ($this->crypto !== false) {
  1000. $data = $this->crypto->encrypt($data);
  1001. }
  1002. $packet = pack('Na*', $length, $data);
  1003. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  1004. $result = strlen($packet) == fputs($this->fsock, $packet);
  1005. $stop = strtok(microtime(), ' ') + strtok('');
  1006. if (defined('NET_SSH1_LOGGING')) {
  1007. $temp = isset($this->protocol_flags[ord($orig[0])]) ? $this->protocol_flags[ord($orig[0])] : 'UNKNOWN';
  1008. $temp = '-> ' . $temp .
  1009. ' (' . round($stop - $start, 4) . 's)';
  1010. $this->_append_log($temp, $orig);
  1011. }
  1012. return $result;
  1013. }
  1014. /**
  1015. * Cyclic Redundancy Check (CRC)
  1016. *
  1017. * PHP's crc32 function is implemented slightly differently than the one that SSH v1 uses, so
  1018. * we've reimplemented it. A more detailed discussion of the differences can be found after
  1019. * $crc_lookup_table's initialization.
  1020. *
  1021. * @see Net_SSH1::_get_binary_packet()
  1022. * @see Net_SSH1::_send_binary_packet()
  1023. * @param String $data
  1024. * @return Integer
  1025. * @access private
  1026. */
  1027. function _crc($data)
  1028. {
  1029. static $crc_lookup_table = array(
  1030. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
  1031. 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  1032. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
  1033. 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  1034. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
  1035. 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  1036. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
  1037. 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  1038. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
  1039. 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  1040. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
  1041. 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  1042. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
  1043. 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  1044. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
  1045. 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  1046. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
  1047. 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  1048. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
  1049. 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  1050. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
  1051. 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  1052. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
  1053. 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  1054. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
  1055. 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  1056. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
  1057. 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  1058. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
  1059. 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  1060. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
  1061. 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  1062. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
  1063. 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  1064. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
  1065. 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  1066. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
  1067. 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  1068. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
  1069. 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  1070. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
  1071. 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  1072. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
  1073. 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  1074. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
  1075. 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  1076. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
  1077. 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  1078. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
  1079. 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  1080. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
  1081. 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  1082. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
  1083. 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  1084. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
  1085. 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  1086. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
  1087. 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  1088. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
  1089. 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  1090. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
  1091. 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  1092. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
  1093. 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  1094. );
  1095. // For this function to yield the same output as PHP's crc32 function, $crc would have to be
  1096. // set to 0xFFFFFFFF, initially - not 0x00000000 as it currently is.
  1097. $crc = 0x00000000;
  1098. $length = strlen($data);
  1099. for ($i=0;$i<$length;$i++) {
  1100. // We AND $crc >> 8 with 0x00FFFFFF because we want the eight newly added bits to all
  1101. // be zero. PHP, unfortunately, doesn't always do this. 0x80000000 >> 8, as an example,
  1102. // yields 0xFF800000 - not 0x00800000. The following link elaborates:
  1103. // http://www.php.net/manual/en/language.operators.bitwise.php#57281
  1104. $crc = (($crc >> 8) & 0x00FFFFFF) ^ $crc_lookup_table[($crc & 0xFF) ^ ord($data[$i])];
  1105. }
  1106. // In addition to having to set $crc to 0xFFFFFFFF, initially, the return value must be XOR'd with
  1107. // 0xFFFFFFFF for this function to return the same thing that PHP's crc32 function would.
  1108. return $crc;
  1109. }
  1110. /**
  1111. * String Shift
  1112. *
  1113. * Inspired by array_shift
  1114. *
  1115. * @param String $string
  1116. * @param optional Integer $index
  1117. * @return String
  1118. * @access private
  1119. */
  1120. function _string_shift(&$string, $index = 1)
  1121. {
  1122. $substr = substr($string, 0, $index);
  1123. $string = substr($string, $index);
  1124. return $substr;
  1125. }
  1126. /**
  1127. * RSA Encrypt
  1128. *
  1129. * Returns mod(pow($m, $e), $n), where $n should be the product of two (large) primes $p and $q and where $e
  1130. * should be a number with the property that gcd($e, ($p - 1) * ($q - 1)) == 1. Could just make anything that
  1131. * calls this call modexp, instead, but I think this makes things clearer, maybe...
  1132. *
  1133. * @see Net_SSH1::Net_SSH1()
  1134. * @param Math_BigInteger $m
  1135. * @param Array $key
  1136. * @return Math_BigInteger
  1137. * @access private
  1138. */
  1139. function _rsa_crypt($m, $key)
  1140. {
  1141. /*
  1142. if (!class_exists('Crypt_RSA')) {
  1143. require_once('Crypt/RSA.php');
  1144. }
  1145. $rsa = new Crypt_RSA();
  1146. $rsa->loadKey($key, CRYPT_RSA_PUBLIC_FORMAT_RAW);
  1147. $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
  1148. return $rsa->encrypt($m);
  1149. */
  1150. // To quote from protocol-1.5.txt:
  1151. // The most significant byte (which is only partial as the value must be
  1152. // less than the public modulus, which is never a power of two) is zero.
  1153. //
  1154. // The next byte contains the value 2 (which stands for public-key
  1155. // encrypted data in the PKCS standard [PKCS#1]). Then, there are non-
  1156. // zero random bytes to fill any unused space, a zero byte, and the data
  1157. // to be encrypted in the least significant bytes, the last byte of the
  1158. // data in the least significant byte.
  1159. // Presumably the part of PKCS#1 they're refering to is "Section 7.2.1 Encryption Operation",
  1160. // under "7.2 RSAES-PKCS1-v1.5" and "7 Encryption schemes" of the following URL:
  1161. // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf
  1162. $modulus = $key[1]->toBytes();
  1163. $length = strlen($modulus) - strlen($m) - 3;
  1164. $random = '';
  1165. while (strlen($random) != $length) {
  1166. $block = crypt_random_string($length - strlen($random));
  1167. $block = str_replace("\x00", '', $block);
  1168. $random.= $block;
  1169. }
  1170. $temp = chr(0) . chr(2) . $random . chr(0) . $m;
  1171. $m = new Math_BigInteger($temp, 256);
  1172. $m = $m->modPow($key[0], $key[1]);
  1173. return $m->toBytes();
  1174. }
  1175. /**
  1176. * Define Array
  1177. *
  1178. * Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of
  1179. * named constants from it, using the value as the name of the constant and the index as the value of the constant.
  1180. * If any of the constants that would be defined already exists, none of the constants will be defined.
  1181. *
  1182. * @param Array $array
  1183. * @access private
  1184. */
  1185. function _define_array()
  1186. {
  1187. $args = func_get_args();
  1188. foreach ($args as $arg) {
  1189. foreach ($arg as $key=>$value) {
  1190. if (!defined($value)) {
  1191. define($value, $key);
  1192. } else {
  1193. break 2;
  1194. }
  1195. }
  1196. }
  1197. }
  1198. /**
  1199. * Returns a log of the packets that have been sent and received.
  1200. *
  1201. * 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')
  1202. *
  1203. * @access public
  1204. * @return String or Array
  1205. */
  1206. function getLog()
  1207. {
  1208. if (!defined('NET_SSH1_LOGGING')) {
  1209. return false;
  1210. }
  1211. switch (NET_SSH1_LOGGING) {
  1212. case NET_SSH1_LOG_SIMPLE:
  1213. return $this->message_number_log;
  1214. break;
  1215. case NET_SSH1_LOG_COMPLEX:
  1216. return $this->_format_log($this->message_log, $this->protocol_flags_log);
  1217. break;
  1218. default:
  1219. return false;
  1220. }
  1221. }
  1222. /**
  1223. * Formats a log for printing
  1224. *
  1225. * @param Array $message_log
  1226. * @param Array $message_number_log
  1227. * @access private
  1228. * @return String
  1229. */
  1230. function _format_log($message_log, $message_number_log)
  1231. {
  1232. static $boundary = ':', $long_width = 65, $short_width = 16;
  1233. $output = '';
  1234. for ($i = 0; $i < count($message_log); $i++) {
  1235. $output.= $message_number_log[$i] . "\r\n";
  1236. $current_log = $message_log[$i];
  1237. $j = 0;
  1238. do {
  1239. if (strlen($current_log)) {
  1240. $output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 ';
  1241. }
  1242. $fragment = $this->_string_shift($current_log, $short_width);
  1243. $hex = substr(
  1244. preg_replace(
  1245. '#(.)#es',
  1246. '"' . $boundary . '" . str_pad(dechex(ord(substr("\\1", -1))), 2, "0", STR_PAD_LEFT)',
  1247. $fragment),
  1248. strlen($boundary)
  1249. );
  1250. // replace non ASCII printable characters with dots
  1251. // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
  1252. // also replace < with a . since < messes up the output on web browsers
  1253. $raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment);
  1254. $output.= str_pad($hex, $long_width - $short_width, ' ') . $raw . "\r\n";
  1255. $j++;
  1256. } while (strlen($current_log));
  1257. $output.= "\r\n";
  1258. }
  1259. return $output;
  1260. }
  1261. /**
  1262. * Return the server key public exponent
  1263. *
  1264. * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead,
  1265. * the raw bytes. This behavior is similar to PHP's md5() function.
  1266. *
  1267. * @param optional Boolean $raw_output
  1268. * @return String
  1269. * @access public
  1270. */
  1271. function getServerKeyPublicExponent($raw_output = false)
  1272. {
  1273. return $raw_output ? $this->server_key_public_exponent->toBytes() : $this->server_key_public_exponent->toString();
  1274. }
  1275. /**
  1276. * Return the server key public modulus
  1277. *
  1278. * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead,
  1279. * the raw bytes. This behavior is similar to PHP's md5() function.
  1280. *
  1281. * @param optional Boolean $raw_output
  1282. * @return String
  1283. * @access public
  1284. */
  1285. function getServerKeyPublicModulus($raw_output = false)
  1286. {
  1287. return $raw_output ? $this->server_key_public_modulus->toBytes() : $this->server_key_public_modulus->toString();
  1288. }
  1289. /**
  1290. * Return the host key public exponent
  1291. *
  1292. * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead,
  1293. * the raw bytes. This behavior is similar to PHP's md5() function.
  1294. *
  1295. * @param optional Boolean $raw_output
  1296. * @return String
  1297. * @access public
  1298. */
  1299. function getHostKeyPublicExponent($raw_output = false)
  1300. {
  1301. return $raw_output ? $this->host_key_public_exponent->toBytes() : $this->host_key_public_exponent->toString();
  1302. }
  1303. /**
  1304. * Return the host key public modulus
  1305. *
  1306. * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead,
  1307. * the raw bytes. This behavior is similar to PHP's md5() function.
  1308. *
  1309. * @param optional Boolean $raw_output
  1310. * @return String
  1311. * @access public
  1312. */
  1313. function getHostKeyPublicModulus($raw_output = false)
  1314. {
  1315. return $raw_output ? $this->host_key_public_modulus->toBytes() : $this->host_key_public_modulus->toString();
  1316. }
  1317. /**
  1318. * Return a list of ciphers supported by SSH1 server.
  1319. *
  1320. * Just because a cipher is supported by an SSH1 server doesn't mean it's supported by this library. If $raw_output
  1321. * is set to true, returns, instead, an array of constants. ie. instead of array('Triple-DES in CBC mode'), you'll
  1322. * get array(NET_SSH1_CIPHER_3DES).
  1323. *
  1324. * @param optional Boolean $raw_output
  1325. * @return Array
  1326. * @access public
  1327. */
  1328. function getSupportedCiphers($raw_output = false)
  1329. {
  1330. return $raw_output ? array_keys($this->supported_ciphers) : array_values($this->supported_ciphers);
  1331. }
  1332. /**
  1333. * Return a list of authentications supported by SSH1 server.
  1334. *
  1335. * Just because a cipher is supported by an SSH1 server doesn't mean it's supported by this library. If $raw_output
  1336. * is set to true, returns, instead, an array of constants. ie. instead of array('password authentication'), you'll
  1337. * get array(NET_SSH1_AUTH_PASSWORD).
  1338. *
  1339. * @param optional Boolean $raw_output
  1340. * @return Array
  1341. * @access public
  1342. */
  1343. function getSupportedAuthentications($raw_output = false)
  1344. {
  1345. return $raw_output ? array_keys($this->supported_authentications) : array_values($this->supported_authentications);
  1346. }
  1347. /**
  1348. * Return the server identification.
  1349. *
  1350. * @return String
  1351. * @access public
  1352. */
  1353. function getServerIdentification()
  1354. {
  1355. return rtrim($this->server_identification);
  1356. }
  1357. /**
  1358. * Logs data packets
  1359. *
  1360. * Makes sure that only the last 1MB worth of packets will be logged
  1361. *
  1362. * @param String $data
  1363. * @access private
  1364. */
  1365. function _append_log($protocol_flags, $message)
  1366. {
  1367. switch (NET_SSH1_LOGGING) {
  1368. // useful for benchmarks
  1369. case NET_SSH1_LOG_SIMPLE:
  1370. $this->protocol_flags_log[] = $protocol_flags;
  1371. break;
  1372. // the most useful log for SSH1
  1373. case NET_SSH1_LOG_COMPLEX:
  1374. $this->protocol_flags_log[] = $protocol_flags;
  1375. $this->_string_shift($message);
  1376. $this->log_size+= strlen($message);
  1377. $this->message_log[] = $message;
  1378. while ($this->log_size > NET_SSH2_LOG_MAX_SIZE) {
  1379. $this->log_size-= strlen(array_shift($this->message_log));

Large files files are truncated, but you can click here to view the full file