SSH1.php 53 KB

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