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

/lib/Sinner/Phpseclib/Net/SSH2.php

https://bitbucket.org/jgabrielsinner/phpseclibbundle
PHP | 2954 lines | 1561 code | 353 blank | 1040 comment | 257 complexity | 3fc19f305ab9dacd1455e97e36f8041b MD5 | raw file

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

  1. <?php
  2. namespace Sinner\Phpseclib\Net;
  3. use Sinner\Phpseclib\Crypt\Crypt_Hash;
  4. use Sinner\Phpseclib\Crypt\Crypt_AES;
  5. use Sinner\Phpseclib\Crypt\Crypt_RC4;
  6. use Sinner\Phpseclib\Crypt\Crypt_TripleDES;
  7. use Sinner\Phpseclib\Math\Math_BigInteger;
  8. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  9. /**
  10. * Pure-PHP implementation of SSHv2.
  11. *
  12. * PHP versions 4 and 5
  13. *
  14. * Here are some examples of how to use this library:
  15. * <code>
  16. * <?php
  17. * include('Net/SSH2.php');
  18. *
  19. * $ssh = new Net_SSH2('www.domain.tld');
  20. * if (!$ssh->login('username', 'password')) {
  21. * exit('Login Failed');
  22. * }
  23. *
  24. * echo $ssh->exec('pwd');
  25. * echo $ssh->exec('ls -la');
  26. * ?>
  27. * </code>
  28. *
  29. * <code>
  30. * <?php
  31. * include('Crypt/RSA.php');
  32. * include('Net/SSH2.php');
  33. *
  34. * $key = new Crypt_RSA();
  35. * //$key->setPassword('whatever');
  36. * $key->loadKey(file_get_contents('privatekey'));
  37. *
  38. * $ssh = new Net_SSH2('www.domain.tld');
  39. * if (!$ssh->login('username', $key)) {
  40. * exit('Login Failed');
  41. * }
  42. *
  43. * echo $ssh->read('username@username:~$');
  44. * $ssh->write("ls -la\n");
  45. * echo $ssh->read('username@username:~$');
  46. * ?>
  47. * </code>
  48. *
  49. * LICENSE: Permission is hereby granted, free of charge, to any person obtaining a copy
  50. * of this software and associated documentation files (the "Software"), to deal
  51. * in the Software without restriction, including without limitation the rights
  52. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  53. * copies of the Software, and to permit persons to whom the Software is
  54. * furnished to do so, subject to the following conditions:
  55. *
  56. * The above copyright notice and this permission notice shall be included in
  57. * all copies or substantial portions of the Software.
  58. *
  59. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  60. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  61. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  62. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  63. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  64. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  65. * THE SOFTWARE.
  66. *
  67. * @category Net
  68. * @package Net_SSH2
  69. * @author Jim Wigginton <terrafrost@php.net>
  70. * @copyright MMVII Jim Wigginton
  71. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  72. * @version $Id: SSH2.php,v 1.53 2010-10-24 01:24:30 terrafrost Exp $
  73. * @link http://phpseclib.sourceforge.net
  74. */
  75. /**
  76. * Include Math_BigInteger
  77. *
  78. * Used to do Diffie-Hellman key exchange and DSA/RSA signature verification.
  79. */
  80. if (!class_exists('Math_BigInteger')) {
  81. require_once(__DIR__.'/../Math/BigInteger.php');
  82. }
  83. /**
  84. * Include Crypt_Random
  85. */
  86. // the class_exists() will only be called if the crypt_random function hasn't been defined and
  87. // will trigger a call to __autoload() if you're wanting to auto-load classes
  88. // call function_exists() a second time to stop the require_once from being called outside
  89. // of the auto loader
  90. if (!function_exists('crypt_random') && !class_exists('Crypt_Random') && !function_exists('crypt_random')) {
  91. require_once(__DIR__.'/../Crypt/Random.php');
  92. }
  93. /**
  94. * Include Crypt_Hash
  95. */
  96. if (!class_exists('Crypt_Hash')) {
  97. require_once(__DIR__.'/../Crypt/Hash.php');
  98. }
  99. /**
  100. * Include Crypt_TripleDES
  101. */
  102. if (!class_exists('Crypt_TripleDES')) {
  103. require_once(__DIR__.'/../Crypt/TripleDES.php');
  104. }
  105. /**
  106. * Include Crypt_RC4
  107. */
  108. if (!class_exists('Crypt_RC4')) {
  109. require_once(__DIR__.'/../Crypt/RC4.php');
  110. }
  111. /**
  112. * Include Crypt_AES
  113. */
  114. if (!class_exists('Crypt_AES')) {
  115. require_once(__DIR__.'/../Crypt/AES.php');
  116. }
  117. /**#@+
  118. * Execution Bitmap Masks
  119. *
  120. * @see Net_SSH2::bitmap
  121. * @access private
  122. */
  123. define('NET_SSH2_MASK_CONSTRUCTOR', 0x00000001);
  124. define('NET_SSH2_MASK_LOGIN', 0x00000002);
  125. define('NET_SSH2_MASK_SHELL', 0x00000004);
  126. /**#@-*/
  127. /**#@+
  128. * Channel constants
  129. *
  130. * RFC4254 refers not to client and server channels but rather to sender and recipient channels. we don't refer
  131. * to them in that way because RFC4254 toggles the meaning. the client sends a SSH_MSG_CHANNEL_OPEN message with
  132. * a sender channel and the server sends a SSH_MSG_CHANNEL_OPEN_CONFIRMATION in response, with a sender and a
  133. * recepient channel. at first glance, you might conclude that SSH_MSG_CHANNEL_OPEN_CONFIRMATION's sender channel
  134. * would be the same thing as SSH_MSG_CHANNEL_OPEN's sender channel, but it's not, per this snipet:
  135. * The 'recipient channel' is the channel number given in the original
  136. * open request, and 'sender channel' is the channel number allocated by
  137. * the other side.
  138. *
  139. * @see Net_SSH2::_send_channel_packet()
  140. * @see Net_SSH2::_get_channel_packet()
  141. * @access private
  142. */
  143. define('NET_SSH2_CHANNEL_EXEC', 0); // PuTTy uses 0x100
  144. define('NET_SSH2_CHANNEL_SHELL',1);
  145. /**#@-*/
  146. /**#@+
  147. * @access public
  148. * @see Net_SSH2::getLog()
  149. */
  150. /**
  151. * Returns the message numbers
  152. */
  153. define('NET_SSH2_LOG_SIMPLE', 1);
  154. /**
  155. * Returns the message content
  156. */
  157. define('NET_SSH2_LOG_COMPLEX', 2);
  158. /**
  159. * Outputs the content real-time
  160. */
  161. define('NET_SSH2_LOG_REALTIME', 3);
  162. /**
  163. * Dumps the content real-time to a file
  164. */
  165. define('NET_SSH2_LOG_REALTIME_FILE', 4);
  166. /**#@-*/
  167. /**#@+
  168. * @access public
  169. * @see Net_SSH2::read()
  170. */
  171. /**
  172. * Returns when a string matching $expect exactly is found
  173. */
  174. define('NET_SSH2_READ_SIMPLE', 1);
  175. /**
  176. * Returns when a string matching the regular expression $expect is found
  177. */
  178. define('NET_SSH2_READ_REGEX', 2);
  179. /**
  180. * Make sure that the log never gets larger than this
  181. */
  182. define('NET_SSH2_LOG_MAX_SIZE', 1024 * 1024);
  183. /**#@-*/
  184. /**
  185. * Pure-PHP implementation of SSHv2.
  186. *
  187. * @author Jim Wigginton <terrafrost@php.net>
  188. * @version 0.1.0
  189. * @access public
  190. * @package Net_SSH2
  191. */
  192. class Net_SSH2 {
  193. /**
  194. * The SSH identifier
  195. *
  196. * @var String
  197. * @access private
  198. */
  199. protected $identifier = 'SSH-2.0-phpseclib_0.3';
  200. /**
  201. * The Socket Object
  202. *
  203. * @var Object
  204. * @access private
  205. */
  206. protected $fsock;
  207. /**
  208. * Execution Bitmap
  209. *
  210. * The bits that are set represent functions that have been called already. This is used to determine
  211. * if a requisite function has been successfully executed. If not, an error should be thrown.
  212. *
  213. * @var Integer
  214. * @access private
  215. */
  216. protected $bitmap = 0;
  217. /**
  218. * Error information
  219. *
  220. * @see Net_SSH2::getErrors()
  221. * @see Net_SSH2::getLastError()
  222. * @var String
  223. * @access private
  224. */
  225. protected $errors = array();
  226. /**
  227. * Server Identifier
  228. *
  229. * @see Net_SSH2::getServerIdentification()
  230. * @var String
  231. * @access private
  232. */
  233. protected $server_identifier = '';
  234. /**
  235. * Key Exchange Algorithms
  236. *
  237. * @see Net_SSH2::getKexAlgorithims()
  238. * @var Array
  239. * @access private
  240. */
  241. protected $kex_algorithms;
  242. /**
  243. * Server Host Key Algorithms
  244. *
  245. * @see Net_SSH2::getServerHostKeyAlgorithms()
  246. * @var Array
  247. * @access private
  248. */
  249. protected $server_host_key_algorithms;
  250. /**
  251. * Encryption Algorithms: Client to Server
  252. *
  253. * @see Net_SSH2::getEncryptionAlgorithmsClient2Server()
  254. * @var Array
  255. * @access private
  256. */
  257. protected $encryption_algorithms_client_to_server;
  258. /**
  259. * Encryption Algorithms: Server to Client
  260. *
  261. * @see Net_SSH2::getEncryptionAlgorithmsServer2Client()
  262. * @var Array
  263. * @access private
  264. */
  265. protected $encryption_algorithms_server_to_client;
  266. /**
  267. * MAC Algorithms: Client to Server
  268. *
  269. * @see Net_SSH2::getMACAlgorithmsClient2Server()
  270. * @var Array
  271. * @access private
  272. */
  273. protected $mac_algorithms_client_to_server;
  274. /**
  275. * MAC Algorithms: Server to Client
  276. *
  277. * @see Net_SSH2::getMACAlgorithmsServer2Client()
  278. * @var Array
  279. * @access private
  280. */
  281. protected $mac_algorithms_server_to_client;
  282. /**
  283. * Compression Algorithms: Client to Server
  284. *
  285. * @see Net_SSH2::getCompressionAlgorithmsClient2Server()
  286. * @var Array
  287. * @access private
  288. */
  289. protected $compression_algorithms_client_to_server;
  290. /**
  291. * Compression Algorithms: Server to Client
  292. *
  293. * @see Net_SSH2::getCompressionAlgorithmsServer2Client()
  294. * @var Array
  295. * @access private
  296. */
  297. protected $compression_algorithms_server_to_client;
  298. /**
  299. * Languages: Server to Client
  300. *
  301. * @see Net_SSH2::getLanguagesServer2Client()
  302. * @var Array
  303. * @access private
  304. */
  305. protected $languages_server_to_client;
  306. /**
  307. * Languages: Client to Server
  308. *
  309. * @see Net_SSH2::getLanguagesClient2Server()
  310. * @var Array
  311. * @access private
  312. */
  313. protected $languages_client_to_server;
  314. /**
  315. * Block Size for Server to Client Encryption
  316. *
  317. * "Note that the length of the concatenation of 'packet_length',
  318. * 'padding_length', 'payload', and 'random padding' MUST be a multiple
  319. * of the cipher block size or 8, whichever is larger. This constraint
  320. * MUST be enforced, even when using stream ciphers."
  321. *
  322. * -- http://tools.ietf.org/html/rfc4253#section-6
  323. *
  324. * @see Net_SSH2::Net_SSH2()
  325. * @see Net_SSH2::_send_binary_packet()
  326. * @var Integer
  327. * @access private
  328. */
  329. protected $encrypt_block_size = 8;
  330. /**
  331. * Block Size for Client to Server Encryption
  332. *
  333. * @see Net_SSH2::Net_SSH2()
  334. * @see Net_SSH2::_get_binary_packet()
  335. * @var Integer
  336. * @access private
  337. */
  338. protected $decrypt_block_size = 8;
  339. /**
  340. * Server to Client Encryption Object
  341. *
  342. * @see Net_SSH2::_get_binary_packet()
  343. * @var Object
  344. * @access private
  345. */
  346. protected $decrypt = false;
  347. /**
  348. * Client to Server Encryption Object
  349. *
  350. * @see Net_SSH2::_send_binary_packet()
  351. * @var Object
  352. * @access private
  353. */
  354. protected $encrypt = false;
  355. /**
  356. * Client to Server HMAC Object
  357. *
  358. * @see Net_SSH2::_send_binary_packet()
  359. * @var Object
  360. * @access private
  361. */
  362. protected $hmac_create = false;
  363. /**
  364. * Server to Client HMAC Object
  365. *
  366. * @see Net_SSH2::_get_binary_packet()
  367. * @var Object
  368. * @access private
  369. */
  370. protected $hmac_check = false;
  371. /**
  372. * Size of server to client HMAC
  373. *
  374. * 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.
  375. * 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
  376. * append it.
  377. *
  378. * @see Net_SSH2::_get_binary_packet()
  379. * @var Integer
  380. * @access private
  381. */
  382. protected $hmac_size = false;
  383. /**
  384. * Server Public Host Key
  385. *
  386. * @see Net_SSH2::getServerPublicHostKey()
  387. * @var String
  388. * @access private
  389. */
  390. protected $server_public_host_key;
  391. /**
  392. * Session identifer
  393. *
  394. * "The exchange hash H from the first key exchange is additionally
  395. * used as the session identifier, which is a unique identifier for
  396. * this connection."
  397. *
  398. * -- http://tools.ietf.org/html/rfc4253#section-7.2
  399. *
  400. * @see Net_SSH2::_key_exchange()
  401. * @var String
  402. * @access private
  403. */
  404. protected $session_id = false;
  405. /**
  406. * Exchange hash
  407. *
  408. * The current exchange hash
  409. *
  410. * @see Net_SSH2::_key_exchange()
  411. * @var String
  412. * @access private
  413. */
  414. protected $exchange_hash = false;
  415. /**
  416. * Message Numbers
  417. *
  418. * @see Net_SSH2::Net_SSH2()
  419. * @var Array
  420. * @access private
  421. */
  422. protected $message_numbers = array();
  423. /**
  424. * Disconnection Message 'reason codes' defined in RFC4253
  425. *
  426. * @see Net_SSH2::Net_SSH2()
  427. * @var Array
  428. * @access private
  429. */
  430. protected $disconnect_reasons = array();
  431. /**
  432. * SSH_MSG_CHANNEL_OPEN_FAILURE 'reason codes', defined in RFC4254
  433. *
  434. * @see Net_SSH2::Net_SSH2()
  435. * @var Array
  436. * @access private
  437. */
  438. protected $channel_open_failure_reasons = array();
  439. /**
  440. * Terminal Modes
  441. *
  442. * @link http://tools.ietf.org/html/rfc4254#section-8
  443. * @see Net_SSH2::Net_SSH2()
  444. * @var Array
  445. * @access private
  446. */
  447. protected $terminal_modes = array();
  448. /**
  449. * SSH_MSG_CHANNEL_EXTENDED_DATA's data_type_codes
  450. *
  451. * @link http://tools.ietf.org/html/rfc4254#section-5.2
  452. * @see Net_SSH2::Net_SSH2()
  453. * @var Array
  454. * @access private
  455. */
  456. protected $channel_extended_data_type_codes = array();
  457. /**
  458. * Send Sequence Number
  459. *
  460. * See 'Section 6.4. Data Integrity' of rfc4253 for more info.
  461. *
  462. * @see Net_SSH2::_send_binary_packet()
  463. * @var Integer
  464. * @access private
  465. */
  466. protected $send_seq_no = 0;
  467. /**
  468. * Get Sequence Number
  469. *
  470. * See 'Section 6.4. Data Integrity' of rfc4253 for more info.
  471. *
  472. * @see Net_SSH2::_get_binary_packet()
  473. * @var Integer
  474. * @access private
  475. */
  476. protected $get_seq_no = 0;
  477. /**
  478. * Server Channels
  479. *
  480. * Maps client channels to server channels
  481. *
  482. * @see Net_SSH2::_get_channel_packet()
  483. * @see Net_SSH2::exec()
  484. * @var Array
  485. * @access private
  486. */
  487. protected $server_channels = array();
  488. /**
  489. * Channel Buffers
  490. *
  491. * If a client requests a packet from one channel but receives two packets from another those packets should
  492. * be placed in a buffer
  493. *
  494. * @see Net_SSH2::_get_channel_packet()
  495. * @see Net_SSH2::exec()
  496. * @var Array
  497. * @access private
  498. */
  499. protected $channel_buffers = array();
  500. /**
  501. * Channel Status
  502. *
  503. * Contains the type of the last sent message
  504. *
  505. * @see Net_SSH2::_get_channel_packet()
  506. * @var Array
  507. * @access private
  508. */
  509. protected $channel_status = array();
  510. /**
  511. * Packet Size
  512. *
  513. * Maximum packet size indexed by channel
  514. *
  515. * @see Net_SSH2::_send_channel_packet()
  516. * @var Array
  517. * @access private
  518. */
  519. protected $packet_size_client_to_server = array();
  520. /**
  521. * Message Number Log
  522. *
  523. * @see Net_SSH2::getLog()
  524. * @var Array
  525. * @access private
  526. */
  527. protected $message_number_log = array();
  528. /**
  529. * Message Log
  530. *
  531. * @see Net_SSH2::getLog()
  532. * @var Array
  533. * @access private
  534. */
  535. protected $message_log = array();
  536. /**
  537. * The Window Size
  538. *
  539. * Bytes the other party can send before it must wait for the window to be adjusted (0x7FFFFFFF = 4GB)
  540. *
  541. * @var Integer
  542. * @see Net_SSH2::_send_channel_packet()
  543. * @see Net_SSH2::exec()
  544. * @access private
  545. */
  546. protected $window_size = 0x7FFFFFFF;
  547. /**
  548. * Window size
  549. *
  550. * Window size indexed by channel
  551. *
  552. * @see Net_SSH2::_send_channel_packet()
  553. * @var Array
  554. * @access private
  555. */
  556. protected $window_size_client_to_server = array();
  557. /**
  558. * Server signature
  559. *
  560. * Verified against $this->session_id
  561. *
  562. * @see Net_SSH2::getServerPublicHostKey()
  563. * @var String
  564. * @access private
  565. */
  566. protected $signature = '';
  567. /**
  568. * Server signature format
  569. *
  570. * ssh-rsa or ssh-dss.
  571. *
  572. * @see Net_SSH2::getServerPublicHostKey()
  573. * @var String
  574. * @access private
  575. */
  576. protected $signature_format = '';
  577. /**
  578. * Interactive Buffer
  579. *
  580. * @see Net_SSH2::read()
  581. * @var Array
  582. * @access private
  583. */
  584. protected $interactiveBuffer = '';
  585. /**
  586. * Current log size
  587. *
  588. * Should never exceed NET_SSH2_LOG_MAX_SIZE
  589. *
  590. * @see Net_SSH2::_send_binary_packet()
  591. * @see Net_SSH2::_get_binary_packet()
  592. * @var Integer
  593. * @access private
  594. */
  595. protected $log_size;
  596. /**
  597. * Timeout
  598. *
  599. * @see Net_SSH2::setTimeout()
  600. * @access private
  601. */
  602. protected $timeout;
  603. /**
  604. * Current Timeout
  605. *
  606. * @see Net_SSH2::_get_channel_packet()
  607. * @access private
  608. */
  609. protected $curTimeout;
  610. /**
  611. * Real-time log file pointer
  612. *
  613. * @see Net_SSH2::_append_log()
  614. * @access private
  615. */
  616. protected $realtime_log_file;
  617. /**
  618. * Real-time log file size
  619. *
  620. * @see Net_SSH2::_append_log()
  621. * @access private
  622. */
  623. protected $realtime_log_size;
  624. /**
  625. * Has the signature been validated?
  626. *
  627. * @see Net_SSH2::getServerPublicHostKey()
  628. * @access private
  629. */
  630. protected $signature_validated = false;
  631. /**
  632. * Real-time log file wrap boolean
  633. *
  634. * @see Net_SSH2::_append_log()
  635. * @access private
  636. */
  637. protected $realtime_log_wrap;
  638. /**
  639. * Flag to suppress stderr from output
  640. *
  641. * @see Net_SSH2::enableQuietMode()
  642. * @access private
  643. */
  644. protected $quiet_mode = false;
  645. /**
  646. * Default Constructor.
  647. *
  648. * Connects to an SSHv2 server
  649. *
  650. * @param String $host
  651. * @param optional Integer $port
  652. * @param optional Integer $timeout
  653. * @return Net_SSH2
  654. * @access public
  655. */
  656. function Net_SSH2($host, $port = 22, $timeout = 10)
  657. {
  658. $this->message_numbers = array(
  659. 1 => 'NET_SSH2_MSG_DISCONNECT',
  660. 2 => 'NET_SSH2_MSG_IGNORE',
  661. 3 => 'NET_SSH2_MSG_UNIMPLEMENTED',
  662. 4 => 'NET_SSH2_MSG_DEBUG',
  663. 5 => 'NET_SSH2_MSG_SERVICE_REQUEST',
  664. 6 => 'NET_SSH2_MSG_SERVICE_ACCEPT',
  665. 20 => 'NET_SSH2_MSG_KEXINIT',
  666. 21 => 'NET_SSH2_MSG_NEWKEYS',
  667. 30 => 'NET_SSH2_MSG_KEXDH_INIT',
  668. 31 => 'NET_SSH2_MSG_KEXDH_REPLY',
  669. 50 => 'NET_SSH2_MSG_USERAUTH_REQUEST',
  670. 51 => 'NET_SSH2_MSG_USERAUTH_FAILURE',
  671. 52 => 'NET_SSH2_MSG_USERAUTH_SUCCESS',
  672. 53 => 'NET_SSH2_MSG_USERAUTH_BANNER',
  673. 80 => 'NET_SSH2_MSG_GLOBAL_REQUEST',
  674. 81 => 'NET_SSH2_MSG_REQUEST_SUCCESS',
  675. 82 => 'NET_SSH2_MSG_REQUEST_FAILURE',
  676. 90 => 'NET_SSH2_MSG_CHANNEL_OPEN',
  677. 91 => 'NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION',
  678. 92 => 'NET_SSH2_MSG_CHANNEL_OPEN_FAILURE',
  679. 93 => 'NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST',
  680. 94 => 'NET_SSH2_MSG_CHANNEL_DATA',
  681. 95 => 'NET_SSH2_MSG_CHANNEL_EXTENDED_DATA',
  682. 96 => 'NET_SSH2_MSG_CHANNEL_EOF',
  683. 97 => 'NET_SSH2_MSG_CHANNEL_CLOSE',
  684. 98 => 'NET_SSH2_MSG_CHANNEL_REQUEST',
  685. 99 => 'NET_SSH2_MSG_CHANNEL_SUCCESS',
  686. 100 => 'NET_SSH2_MSG_CHANNEL_FAILURE'
  687. );
  688. $this->disconnect_reasons = array(
  689. 1 => 'NET_SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT',
  690. 2 => 'NET_SSH2_DISCONNECT_PROTOCOL_ERROR',
  691. 3 => 'NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED',
  692. 4 => 'NET_SSH2_DISCONNECT_RESERVED',
  693. 5 => 'NET_SSH2_DISCONNECT_MAC_ERROR',
  694. 6 => 'NET_SSH2_DISCONNECT_COMPRESSION_ERROR',
  695. 7 => 'NET_SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE',
  696. 8 => 'NET_SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED',
  697. 9 => 'NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE',
  698. 10 => 'NET_SSH2_DISCONNECT_CONNECTION_LOST',
  699. 11 => 'NET_SSH2_DISCONNECT_BY_APPLICATION',
  700. 12 => 'NET_SSH2_DISCONNECT_TOO_MANY_CONNECTIONS',
  701. 13 => 'NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER',
  702. 14 => 'NET_SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE',
  703. 15 => 'NET_SSH2_DISCONNECT_ILLEGAL_USER_NAME'
  704. );
  705. $this->channel_open_failure_reasons = array(
  706. 1 => 'NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED'
  707. );
  708. $this->terminal_modes = array(
  709. 0 => 'NET_SSH2_TTY_OP_END'
  710. );
  711. $this->channel_extended_data_type_codes = array(
  712. 1 => 'NET_SSH2_EXTENDED_DATA_STDERR'
  713. );
  714. $this->_define_array(
  715. $this->message_numbers,
  716. $this->disconnect_reasons,
  717. $this->channel_open_failure_reasons,
  718. $this->terminal_modes,
  719. $this->channel_extended_data_type_codes,
  720. array(60 => 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ'),
  721. array(60 => 'NET_SSH2_MSG_USERAUTH_PK_OK'),
  722. array(60 => 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST',
  723. 61 => 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE')
  724. );
  725. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  726. $this->fsock = @fsockopen($host, $port, $errno, $errstr, $timeout);
  727. if (!$this->fsock) {
  728. user_error(rtrim("Cannot connect to $host. Error $errno. $errstr"), E_USER_NOTICE);
  729. return;
  730. }
  731. $elapsed = strtok(microtime(), ' ') + strtok('') - $start;
  732. $timeout-= $elapsed;
  733. if ($timeout <= 0) {
  734. user_error(rtrim("Cannot connect to $host. Timeout error"), E_USER_NOTICE);
  735. return;
  736. }
  737. $read = array($this->fsock);
  738. $write = $except = NULL;
  739. $sec = floor($timeout);
  740. $usec = 1000000 * ($timeout - $sec);
  741. // on windows this returns a "Warning: Invalid CRT parameters detected" error
  742. // the !count() is done as a workaround for <https://bugs.php.net/42682>
  743. if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
  744. user_error(rtrim("Cannot connect to $host. Banner timeout"), E_USER_NOTICE);
  745. return;
  746. }
  747. /* According to the SSH2 specs,
  748. "The server MAY send other lines of data before sending the version
  749. string. Each line SHOULD be terminated by a Carriage Return and Line
  750. Feed. Such lines MUST NOT begin with "SSH-", and SHOULD be encoded
  751. in ISO-10646 UTF-8 [RFC3629] (language is not specified). Clients
  752. MUST be able to process such lines." */
  753. $temp = '';
  754. $extra = '';
  755. while (!feof($this->fsock) && !preg_match('#^SSH-(\d\.\d+)#', $temp, $matches)) {
  756. if (substr($temp, -2) == "\r\n") {
  757. $extra.= $temp;
  758. $temp = '';
  759. }
  760. $temp.= fgets($this->fsock, 255);
  761. }
  762. if (feof($this->fsock)) {
  763. user_error('Connection closed by server', E_USER_NOTICE);
  764. return false;
  765. }
  766. $ext = array();
  767. if (extension_loaded('mcrypt')) {
  768. $ext[] = 'mcrypt';
  769. }
  770. if (extension_loaded('gmp')) {
  771. $ext[] = 'gmp';
  772. } else if (extension_loaded('bcmath')) {
  773. $ext[] = 'bcmath';
  774. }
  775. if (!empty($ext)) {
  776. $this->identifier.= ' (' . implode(', ', $ext) . ')';
  777. }
  778. if (defined('NET_SSH2_LOGGING')) {
  779. $this->message_number_log[] = '<-';
  780. $this->message_number_log[] = '->';
  781. if (NET_SSH2_LOGGING == NET_SSH2_LOG_COMPLEX) {
  782. $this->message_log[] = $extra . $temp;
  783. $this->message_log[] = $this->identifier . "\r\n";
  784. }
  785. }
  786. $this->server_identifier = trim($temp, "\r\n");
  787. if (!empty($extra)) {
  788. $this->errors[] = utf8_decode($extra);
  789. }
  790. if ($matches[1] != '1.99' && $matches[1] != '2.0') {
  791. user_error("Cannot connect to SSH $matches[1] servers", E_USER_NOTICE);
  792. return;
  793. }
  794. fputs($this->fsock, $this->identifier . "\r\n");
  795. $response = $this->_get_binary_packet();
  796. if ($response === false) {
  797. user_error('Connection closed by server', E_USER_NOTICE);
  798. return;
  799. }
  800. if (ord($response[0]) != NET_SSH2_MSG_KEXINIT) {
  801. user_error('Expected SSH_MSG_KEXINIT', E_USER_NOTICE);
  802. return;
  803. }
  804. if (!$this->_key_exchange($response)) {
  805. return;
  806. }
  807. $this->bitmap = NET_SSH2_MASK_CONSTRUCTOR;
  808. }
  809. /**
  810. * Key Exchange
  811. *
  812. * @param String $kexinit_payload_server
  813. * @access private
  814. */
  815. function _key_exchange($kexinit_payload_server)
  816. {
  817. static $kex_algorithms = array(
  818. 'diffie-hellman-group1-sha1', // REQUIRED
  819. 'diffie-hellman-group14-sha1' // REQUIRED
  820. );
  821. static $server_host_key_algorithms = array(
  822. 'ssh-rsa', // RECOMMENDED sign Raw RSA Key
  823. 'ssh-dss' // REQUIRED sign Raw DSS Key
  824. );
  825. static $encryption_algorithms = array(
  826. // from <http://tools.ietf.org/html/rfc4345#section-4>:
  827. 'arcfour256',
  828. 'arcfour128',
  829. 'arcfour', // OPTIONAL the ARCFOUR stream cipher with a 128-bit key
  830. 'aes128-cbc', // RECOMMENDED AES with a 128-bit key
  831. 'aes192-cbc', // OPTIONAL AES with a 192-bit key
  832. 'aes256-cbc', // OPTIONAL AES in CBC mode, with a 256-bit key
  833. // from <http://tools.ietf.org/html/rfc4344#section-4>:
  834. 'aes128-ctr', // RECOMMENDED AES (Rijndael) in SDCTR mode, with 128-bit key
  835. 'aes192-ctr', // RECOMMENDED AES with 192-bit key
  836. 'aes256-ctr', // RECOMMENDED AES with 256-bit key
  837. '3des-ctr', // RECOMMENDED Three-key 3DES in SDCTR mode
  838. '3des-cbc', // REQUIRED three-key 3DES in CBC mode
  839. 'none' // OPTIONAL no encryption; NOT RECOMMENDED
  840. );
  841. static $mac_algorithms = array(
  842. 'hmac-sha1-96', // RECOMMENDED first 96 bits of HMAC-SHA1 (digest length = 12, key length = 20)
  843. 'hmac-sha1', // REQUIRED HMAC-SHA1 (digest length = key length = 20)
  844. 'hmac-md5-96', // OPTIONAL first 96 bits of HMAC-MD5 (digest length = 12, key length = 16)
  845. 'hmac-md5', // OPTIONAL HMAC-MD5 (digest length = key length = 16)
  846. 'none' // OPTIONAL no MAC; NOT RECOMMENDED
  847. );
  848. static $compression_algorithms = array(
  849. 'none' // REQUIRED no compression
  850. //'zlib' // OPTIONAL ZLIB (LZ77) compression
  851. );
  852. // some SSH servers have buggy implementations of some of the above algorithms
  853. switch ($this->server_identifier) {
  854. case 'SSH-2.0-SSHD':
  855. $mac_algorithms = array_values(array_diff(
  856. $mac_algorithms,
  857. array('hmac-sha1-96', 'hmac-md5-96')
  858. ));
  859. }
  860. static $str_kex_algorithms, $str_server_host_key_algorithms,
  861. $encryption_algorithms_server_to_client, $mac_algorithms_server_to_client, $compression_algorithms_server_to_client,
  862. $encryption_algorithms_client_to_server, $mac_algorithms_client_to_server, $compression_algorithms_client_to_server;
  863. if (empty($str_kex_algorithms)) {
  864. $str_kex_algorithms = implode(',', $kex_algorithms);
  865. $str_server_host_key_algorithms = implode(',', $server_host_key_algorithms);
  866. $encryption_algorithms_server_to_client = $encryption_algorithms_client_to_server = implode(',', $encryption_algorithms);
  867. $mac_algorithms_server_to_client = $mac_algorithms_client_to_server = implode(',', $mac_algorithms);
  868. $compression_algorithms_server_to_client = $compression_algorithms_client_to_server = implode(',', $compression_algorithms);
  869. }
  870. $client_cookie = '';
  871. for ($i = 0; $i < 16; $i++) {
  872. $client_cookie.= chr(crypt_random(0, 255));
  873. }
  874. $response = $kexinit_payload_server;
  875. $this->_string_shift($response, 1); // skip past the message number (it should be SSH_MSG_KEXINIT)
  876. $server_cookie = $this->_string_shift($response, 16);
  877. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  878. $this->kex_algorithms = explode(',', $this->_string_shift($response, $temp['length']));
  879. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  880. $this->server_host_key_algorithms = explode(',', $this->_string_shift($response, $temp['length']));
  881. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  882. $this->encryption_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
  883. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  884. $this->encryption_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
  885. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  886. $this->mac_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
  887. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  888. $this->mac_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
  889. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  890. $this->compression_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
  891. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  892. $this->compression_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
  893. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  894. $this->languages_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
  895. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  896. $this->languages_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
  897. extract(unpack('Cfirst_kex_packet_follows', $this->_string_shift($response, 1)));
  898. $first_kex_packet_follows = $first_kex_packet_follows != 0;
  899. // the sending of SSH2_MSG_KEXINIT could go in one of two places. this is the second place.
  900. $kexinit_payload_client = pack('Ca*Na*Na*Na*Na*Na*Na*Na*Na*Na*Na*CN',
  901. NET_SSH2_MSG_KEXINIT, $client_cookie, strlen($str_kex_algorithms), $str_kex_algorithms,
  902. strlen($str_server_host_key_algorithms), $str_server_host_key_algorithms, strlen($encryption_algorithms_client_to_server),
  903. $encryption_algorithms_client_to_server, strlen($encryption_algorithms_server_to_client), $encryption_algorithms_server_to_client,
  904. strlen($mac_algorithms_client_to_server), $mac_algorithms_client_to_server, strlen($mac_algorithms_server_to_client),
  905. $mac_algorithms_server_to_client, strlen($compression_algorithms_client_to_server), $compression_algorithms_client_to_server,
  906. strlen($compression_algorithms_server_to_client), $compression_algorithms_server_to_client, 0, '', 0, '',
  907. 0, 0
  908. );
  909. if (!$this->_send_binary_packet($kexinit_payload_client)) {
  910. return false;
  911. }
  912. // here ends the second place.
  913. // we need to decide upon the symmetric encryption algorithms before we do the diffie-hellman key exchange
  914. for ($i = 0; $i < count($encryption_algorithms) && !in_array($encryption_algorithms[$i], $this->encryption_algorithms_server_to_client); $i++);
  915. if ($i == count($encryption_algorithms)) {
  916. user_error('No compatible server to client encryption algorithms found', E_USER_NOTICE);
  917. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  918. }
  919. // we don't initialize any crypto-objects, yet - we do that, later. for now, we need the lengths to make the
  920. // diffie-hellman key exchange as fast as possible
  921. $decrypt = $encryption_algorithms[$i];
  922. switch ($decrypt) {
  923. case '3des-cbc':
  924. case '3des-ctr':
  925. $decryptKeyLength = 24; // eg. 192 / 8
  926. break;
  927. case 'aes256-cbc':
  928. case 'aes256-ctr':
  929. $decryptKeyLength = 32; // eg. 256 / 8
  930. break;
  931. case 'aes192-cbc':
  932. case 'aes192-ctr':
  933. $decryptKeyLength = 24; // eg. 192 / 8
  934. break;
  935. case 'aes128-cbc':
  936. case 'aes128-ctr':
  937. $decryptKeyLength = 16; // eg. 128 / 8
  938. break;
  939. case 'arcfour':
  940. case 'arcfour128':
  941. $decryptKeyLength = 16; // eg. 128 / 8
  942. break;
  943. case 'arcfour256':
  944. $decryptKeyLength = 32; // eg. 128 / 8
  945. break;
  946. case 'none';
  947. $decryptKeyLength = 0;
  948. }
  949. for ($i = 0; $i < count($encryption_algorithms) && !in_array($encryption_algorithms[$i], $this->encryption_algorithms_client_to_server); $i++);
  950. if ($i == count($encryption_algorithms)) {
  951. user_error('No compatible client to server encryption algorithms found', E_USER_NOTICE);
  952. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  953. }
  954. $encrypt = $encryption_algorithms[$i];
  955. switch ($encrypt) {
  956. case '3des-cbc':
  957. case '3des-ctr':
  958. $encryptKeyLength = 24;
  959. break;
  960. case 'aes256-cbc':
  961. case 'aes256-ctr':
  962. $encryptKeyLength = 32;
  963. break;
  964. case 'aes192-cbc':
  965. case 'aes192-ctr':
  966. $encryptKeyLength = 24;
  967. break;
  968. case 'aes128-cbc':
  969. case 'aes128-ctr':
  970. $encryptKeyLength = 16;
  971. break;
  972. case 'arcfour':
  973. case 'arcfour128':
  974. $encryptKeyLength = 16;
  975. break;
  976. case 'arcfour256':
  977. $encryptKeyLength = 32;
  978. break;
  979. case 'none';
  980. $encryptKeyLength = 0;
  981. }
  982. $keyLength = $decryptKeyLength > $encryptKeyLength ? $decryptKeyLength : $encryptKeyLength;
  983. // through diffie-hellman key exchange a symmetric key is obtained
  984. for ($i = 0; $i < count($kex_algorithms) && !in_array($kex_algorithms[$i], $this->kex_algorithms); $i++);
  985. if ($i == count($kex_algorithms)) {
  986. user_error('No compatible key exchange algorithms found', E_USER_NOTICE);
  987. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  988. }
  989. switch ($kex_algorithms[$i]) {
  990. // see http://tools.ietf.org/html/rfc2409#section-6.2 and
  991. // http://tools.ietf.org/html/rfc2412, appendex E
  992. case 'diffie-hellman-group1-sha1':
  993. $p = pack('H256', 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' .
  994. '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' .
  995. '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' .
  996. 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF');
  997. $keyLength = $keyLength < 160 ? $keyLength : 160;
  998. $hash = 'sha1';
  999. break;
  1000. // see http://tools.ietf.org/html/rfc3526#section-3
  1001. case 'diffie-hellman-group14-sha1':
  1002. $p = pack('H512', 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' .
  1003. '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' .
  1004. '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' .
  1005. 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05' .
  1006. '98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB' .
  1007. '9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' .
  1008. 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' .
  1009. '3995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF');
  1010. $keyLength = $keyLength < 160 ? $keyLength : 160;
  1011. $hash = 'sha1';
  1012. }
  1013. $p = new Math_BigInteger($p, 256);
  1014. //$q = $p->bitwise_rightShift(1);
  1015. /* To increase the speed of the key exchange, both client and server may
  1016. reduce the size of their private exponents. It should be at least
  1017. twice as long as the key material that is generated from the shared
  1018. secret. For more details, see the paper by van Oorschot and Wiener
  1019. [VAN-OORSCHOT].
  1020. -- http://tools.ietf.org/html/rfc4419#section-6.2 */
  1021. $q = new Math_BigInteger(1);
  1022. $q = $q->bitwise_leftShift(2 * $keyLength);
  1023. $q = $q->subtract(new Math_BigInteger(1));
  1024. $g = new Math_BigInteger(2);
  1025. $x = new Math_BigInteger();
  1026. $x->setRandomGenerator('crypt_random');
  1027. $x = $x->random(new Math_BigInteger(1), $q);
  1028. $e = $g->modPow($x, $p);
  1029. $eBytes = $e->toBytes(true);
  1030. $data = pack('CNa*', NET_SSH2_MSG_KEXDH_INIT, strlen($eBytes), $eBytes);
  1031. if (!$this->_send_binary_packet($data)) {
  1032. user_error('Connection closed by server', E_USER_NOTICE);
  1033. return false;
  1034. }
  1035. $response = $this->_get_binary_packet();
  1036. if ($response === false) {
  1037. user_error('Connection closed by server', E_USER_NOTICE);
  1038. return false;
  1039. }
  1040. extract(unpack('Ctype', $this->_string_shift($response, 1)));
  1041. if ($type != NET_SSH2_MSG_KEXDH_REPLY) {
  1042. user_error('Expected SSH_MSG_KEXDH_REPLY', E_USER_NOTICE);
  1043. return false;
  1044. }
  1045. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  1046. $this->server_public_host_key = $server_public_host_key = $this->_string_shift($response, $temp['length']);
  1047. $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
  1048. $public_key_format = $this->_string_shift($server_public_host_key, $temp['length']);
  1049. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  1050. $fBytes = $this->_string_shift($response, $temp['length']);
  1051. $f = new Math_BigInteger($fBytes, -256);
  1052. $temp = unpack('Nlength', $this->_string_shift($response, 4));
  1053. $this->signature = $this->_string_shift($response, $temp['length']);
  1054. $temp = unpack('Nlength', $this->_string_shift($this->signature, 4));
  1055. $this->signature_format = $this->_string_shift($this->signature, $temp['length']);
  1056. $key = $f->modPow($x, $p);
  1057. $keyBytes = $key->toBytes(true);
  1058. $this->exchange_hash = pack('Na*Na*Na*Na*Na*Na*Na*Na*',
  1059. strlen($this->identifier), $this->identifier, strlen($this->server_identifier), $this->server_identifier,
  1060. strlen($kexinit_payload_client), $kexinit_payload_client, strlen($kexinit_payload_server),
  1061. $kexinit_payload_server, strlen($this->server_public_host_key), $this->server_public_host_key, strlen($eBytes),
  1062. $eBytes, strlen($fBytes), $fBytes, strlen($keyBytes), $keyBytes
  1063. );
  1064. $this->exchange_hash = pack('H*', $hash($this->exchange_hash));
  1065. if ($this->session_id === false) {
  1066. $this->session_id = $this->exchange_hash;
  1067. }
  1068. for ($i = 0; $i < count($server_host_key_algorithms) && !in_array($server_host_key_algorithms[$i], $this->server_host_key_algorithms); $i++);
  1069. if ($i == count($server_host_key_algorithms)) {
  1070. user_error('No compatible server host key algorithms found', E_USER_NOTICE);
  1071. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1072. }
  1073. if ($public_key_format != $server_host_key_algorithms[$i] || $this->signature_format != $server_host_key_algorithms[$i]) {
  1074. user_error('Sever Host Key Algorithm Mismatch', E_USER_NOTICE);
  1075. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1076. }
  1077. $packet = pack('C',
  1078. NET_SSH2_MSG_NEWKEYS
  1079. );
  1080. if (!$this->_send_binary_packet($packet)) {
  1081. return false;
  1082. }
  1083. $response = $this->_get_binary_packet();
  1084. if ($response === false) {
  1085. user_error('Connection closed by server', E_USER_NOTICE);
  1086. return false;
  1087. }
  1088. extract(unpack('Ctype', $this->_string_shift($response, 1)));
  1089. if ($type != NET_SSH2_MSG_NEWKEYS) {
  1090. user_error('Expected SSH_MSG_NEWKEYS', E_USER_NOTICE);
  1091. return false;
  1092. }
  1093. switch ($encrypt) {
  1094. case '3des-cbc':
  1095. $this->encrypt = new Crypt_TripleDES();
  1096. // $this->encrypt_block_size = 64 / 8 == the default
  1097. break;
  1098. case '3des-ctr':
  1099. $this->encrypt = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
  1100. // $this->encrypt_block_size = 64 / 8 == the default
  1101. break;
  1102. case 'aes256-cbc':
  1103. case 'aes192-cbc':
  1104. case 'aes128-cbc':
  1105. $this->encrypt = new Crypt_AES();
  1106. $this->encrypt_block_size = 16; // eg. 128 / 8
  1107. break;
  1108. case 'aes256-ctr':
  1109. case 'aes192-ctr':
  1110. case 'aes128-ctr':
  1111. $this->encrypt = new Crypt_AES(CRYPT_AES_MODE_CTR);
  1112. $this->encrypt_block_size = 16; // eg. 128 / 8
  1113. break;
  1114. case 'arcfour':
  1115. case 'arcfour128':
  1116. case 'arcfour256':
  1117. $this->encrypt = new Crypt_RC4();
  1118. break;
  1119. case 'none';
  1120. //$this->encrypt = new Crypt_Null();
  1121. }
  1122. switch ($decrypt) {
  1123. case '3des-cbc':
  1124. $this->decrypt = new Crypt_TripleDES();
  1125. break;
  1126. case '3des-ctr':
  1127. $this->decrypt = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
  1128. break;
  1129. case 'aes256-cbc':
  1130. case 'aes192-cbc':
  1131. case 'aes128-cbc':
  1132. $this->decrypt = new Crypt_AES();
  1133. $this->decrypt_block_size = 16;
  1134. break;
  1135. case 'aes256-ctr':
  1136. case 'aes192-ctr':
  1137. case 'aes128-ctr':
  1138. $this->decrypt = new Crypt_AES(CRYPT_AES_MODE_CTR);
  1139. $this->decrypt_block_size = 16;
  1140. break;
  1141. case 'arcfour':
  1142. case 'arcfour128':
  1143. case 'arcfour256':
  1144. $this->decrypt = new Crypt_RC4();
  1145. break;
  1146. case 'none';
  1147. //$this->decrypt = new Crypt_Null();
  1148. }
  1149. $keyBytes = pack('Na*', strlen($keyBytes), $keyBytes);
  1150. if ($this->encrypt) {
  1151. $this->encrypt->enableContinuousBuffer();
  1152. $this->encrypt->disablePadding();
  1153. $iv = pack('H*', $hash($keyBytes . $this->exchange_hash . 'A' . $this->session_id));
  1154. while ($this->encrypt_block_size > strlen($iv)) {
  1155. $iv.= pack('H*', $hash($keyBytes . $this->exchange_hash . $iv));
  1156. }
  1157. $this->encrypt->setIV(substr($iv, 0, $this->encrypt_block_size));
  1158. $key = pack('H*', $hash($keyBytes . $this->exchange_hash . 'C' . $this->session_id));
  1159. while ($encryptKeyLength > strlen($key)) {
  1160. $key.= pack('H*', $hash($keyBytes . $this->exchange_hash . $key));
  1161. }
  1162. $this->encrypt->setKey(substr($key, 0, $encryptKeyLength));
  1163. }
  1164. if ($this->decrypt) {
  1165. $this->decrypt->enableContinuousBuffer();
  1166. $this->decrypt->disablePadding();
  1167. $iv = pack('H*', $hash($keyBytes . $this->exchange_hash . 'B' . $this->session_id));
  1168. while ($this->decrypt_block_size > strlen($iv)) {
  1169. $iv.= pack('H*', $hash($keyBytes . $this->exchange_hash . $iv));
  1170. }
  1171. $this->decrypt->setIV(substr($iv, 0, $this->decrypt_block_size));
  1172. $key = pack('H*', $hash($keyBytes . $this->exchange_hash . 'D' . $this->session_id));
  1173. while ($decryptKeyLength > strlen($key)) {
  1174. $key.= pack('H*', $hash($keyBytes . $this->exchange_hash . $key));
  1175. }
  1176. $this->decrypt->setKey(substr($key, 0, $decryptKeyLength));
  1177. }
  1178. /* The "arcfour128" algorithm is the RC4 cipher, as described in
  1179. [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream
  1180. generated by the cipher MUST be discarded, and the first byte of the
  1181. first encrypted packet MUST be encrypted using the 1537th byte of
  1182. keystream.
  1183. -- http://tools.ietf.org/html/rfc4345#section-4 */
  1184. if ($encrypt == 'arcfour128' || $encrypt == 'arcfour256') {
  1185. $this->encrypt->encrypt(str_repeat("\0", 1536));
  1186. }
  1187. if ($decrypt == 'arcfour128' || $decrypt == 'arcfour256') {
  1188. $this->decrypt->decrypt(str_repeat("\0", 1536));
  1189. }
  1190. for ($i = 0; $i < count($mac_algorithms) && !in_array($mac_algorithms[$i], $this->mac_algorithms_client_to_server); $i++);
  1191. if ($i == count($mac_algorithms)) {
  1192. user_error('No compatible client to server message authentication algorithms found', E_USER_NOTICE);
  1193. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1194. }
  1195. $createKeyLength = 0; // ie. $mac_algorithms[$i] == 'none'
  1196. switch ($mac_algorithms[$i]) {
  1197. case 'hmac-sha1':
  1198. $this->hmac_create = new Crypt_Hash('sha1');
  1199. $createKeyLength = 20;
  1200. break;
  1201. case 'hmac-sha1-96':
  1202. $this->hmac_create = new Crypt_Hash('sha1-96');
  1203. $createKeyLength = 20;
  1204. break;
  1205. case 'hmac-md5':
  1206. $this->hmac_create = new Crypt_Hash('md5');
  1207. $createKeyLength = 16;
  1208. break;
  1209. case 'hmac-md5-96':
  1210. $this->hmac_create = new Crypt_Hash('md5-96');
  1211. $createKeyLength = 16;
  1212. }
  1213. for ($i = 0; $i < count($mac_algorithms) && !in_array($mac_algorithms[$i], $this->mac_algorithms_server_to_client); $i++);
  1214. if ($i == count($mac_algorithms)) {
  1215. user_error('No compatible server to client message authentication algorithms found', E_USER_NOTICE);
  1216. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1217. }
  1218. $checkKeyLength = 0;
  1219. $this->hmac_size = 0;
  1220. switch ($mac_algorithms[$i]) {
  1221. case 'hmac-sha1':
  1222. $this->hmac_check = new Crypt_Hash('sha1');
  1223. $checkKeyLength = 20;
  1224. $this->hmac_size = 20;
  1225. break;
  1226. case 'hmac-sha1-96':
  1227. $this->hmac_check = new Crypt_Hash('sha1-96');
  1228. $checkKeyLength = 20;
  1229. $this->hmac_size = 12;
  1230. break;
  1231. case 'hmac-md5':
  1232. $this->hmac_check = new Crypt_Hash('md5');
  1233. $checkKeyLength = 16;
  1234. $this->hmac_size = 16;
  1235. break;
  1236. case 'hmac-md5-96':
  1237. $this->hmac_check = new Crypt_Hash('md5-96');
  1238. $checkKeyLength = 16;
  1239. $this->hmac_size = 12;
  1240. }
  1241. $key = pack('H*', $hash($keyBytes . $this->exchange_hash . 'E' . $this->session_id));
  1242. while ($createKeyLength > strlen($key)) {
  1243. $key.= pack('H*', $hash($keyBytes . $this->exchange_hash . $key));
  1244. }
  1245. $this->hmac_create->setKey(substr($key, 0, $createKeyLength));
  1246. $key = pack('H*', $hash($keyBytes . $this->exchange_hash . 'F' . $this->session_id));
  1247. while ($checkKeyLength > strlen($key)) {
  1248. $key.= pack('H*', $hash($keyBytes . $this->exchange_hash . $key));
  1249. }
  1250. $this->hmac_check->setKey(substr($key, 0, $checkKeyLength));
  1251. for ($i = 0; $i < count($compression_algorithms) && !in_array($compression_algorithms[$i], $this->compression_algorithms_server_to_client); $i++);
  1252. if ($i == count($compression_algorithms)) {
  1253. user_error('No compatible server to client compression algorithms found', E_USER_NOTICE);
  1254. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1255. }
  1256. $this->decompress = $compression_algorithms[$i] == 'zlib';
  1257. for ($i = 0; $i < count($compression_algorithms) && !in_array($compression_algorithms[$i], $this->compression_algorithms_client_to_server); $i++);
  1258. if ($i == count($compression_algorithms)) {
  1259. user_error('No compatible client to server compression algorithms found', E_USER_NOTICE);
  1260. return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1261. }
  1262. $this->compress = $compression_algorithms[$i] == 'zlib';
  1263. return true;
  1264. }
  1265. /**
  1266. * Login
  1267. *
  1268. * The $password parameter can be a plaintext password or a Crypt_RSA object.
  1269. *
  1270. * @param String $username
  1271. * @param optional String $password
  1272. * @return Boolean
  1273. * @access public
  1274. * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis}
  1275. * by sending dummy SSH_MSG_IGNORE messages.
  1276. */
  1277. function login($username, $password = '')
  1278. {
  1279. if (!($this->bitmap & NET_SSH2_MASK_CONSTRUCTOR)) {
  1280. return false;
  1281. }
  1282. $packet = pack('CNa*',
  1283. NET_SSH2_MSG_SERVICE_REQUEST, strlen('ssh-userauth'), 'ssh-userauth'
  1284. );
  1285. if (!$this->_send_binary_packet($packet)) {
  1286. return false;
  1287. }
  1288. $response = $this->_get_bi

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