PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/system/expressionengine/third_party/updater/libraries/phpseclib/Net/SSH2.php

https://bitbucket.org/studiobreakfast/sync
PHP | 2659 lines | 1408 code | 321 blank | 930 comment | 227 complexity | 7b74b23941e07be4e74004b2552e82e3 MD5 | raw file

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

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