SSH1.php 51 KB

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