SSH1.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  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 self::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 self::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 self::_get_binary_packet()
  161. * @access private
  162. */
  163. define('NET_SSH1_RESPONSE_TYPE', 1);
  164. /**
  165. * The Response Data
  166. *
  167. * @see self::_get_binary_packet()
  168. * @access private
  169. */
  170. define('NET_SSH1_RESPONSE_DATA', 2);
  171. /**#@+
  172. * Execution Bitmap Masks
  173. *
  174. * @see self::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 self::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 self::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 int
  253. * @access private
  254. */
  255. var $bitmap = 0;
  256. /**
  257. * The Server Key Public Exponent
  258. *
  259. * Logged for debug purposes
  260. *
  261. * @see self::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 self::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 self::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 self::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 self::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 self::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 self::getServerIdentification()
  333. * @var string
  334. * @access private
  335. */
  336. var $server_identification = '';
  337. /**
  338. * Protocol Flags
  339. *
  340. * @see self::Net_SSH1()
  341. * @var array
  342. * @access private
  343. */
  344. var $protocol_flags = array();
  345. /**
  346. * Protocol Flag Log
  347. *
  348. * @see self::getLog()
  349. * @var array
  350. * @access private
  351. */
  352. var $protocol_flag_log = array();
  353. /**
  354. * Message Log
  355. *
  356. * @see self::getLog()
  357. * @var array
  358. * @access private
  359. */
  360. var $message_log = array();
  361. /**
  362. * Real-time log file pointer
  363. *
  364. * @see self::_append_log()
  365. * @var resource
  366. * @access private
  367. */
  368. var $realtime_log_file;
  369. /**
  370. * Real-time log file size
  371. *
  372. * @see self::_append_log()
  373. * @var int
  374. * @access private
  375. */
  376. var $realtime_log_size;
  377. /**
  378. * Real-time log file wrap boolean
  379. *
  380. * @see self::_append_log()
  381. * @var bool
  382. * @access private
  383. */
  384. var $realtime_log_wrap;
  385. /**
  386. * Interactive Buffer
  387. *
  388. * @see self::read()
  389. * @var array
  390. * @access private
  391. */
  392. var $interactiveBuffer = '';
  393. /**
  394. * Timeout
  395. *
  396. * @see self::setTimeout()
  397. * @access private
  398. */
  399. var $timeout;
  400. /**
  401. * Current Timeout
  402. *
  403. * @see self::_get_channel_packet()
  404. * @access private
  405. */
  406. var $curTimeout;
  407. /**
  408. * Log Boundary
  409. *
  410. * @see self::_format_log()
  411. * @access private
  412. */
  413. var $log_boundary = ':';
  414. /**
  415. * Log Long Width
  416. *
  417. * @see self::_format_log()
  418. * @access private
  419. */
  420. var $log_long_width = 65;
  421. /**
  422. * Log Short Width
  423. *
  424. * @see self::_format_log()
  425. * @access private
  426. */
  427. var $log_short_width = 16;
  428. /**
  429. * Hostname
  430. *
  431. * @see self::Net_SSH1()
  432. * @see self::_connect()
  433. * @var string
  434. * @access private
  435. */
  436. var $host;
  437. /**
  438. * Port Number
  439. *
  440. * @see self::Net_SSH1()
  441. * @see self::_connect()
  442. * @var int
  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 self::Net_SSH1()
  455. * @see self::_connect()
  456. * @var int
  457. * @access private
  458. */
  459. var $connectionTimeout;
  460. /**
  461. * Default cipher
  462. *
  463. * @see self::Net_SSH1()
  464. * @see self::_connect()
  465. * @var int
  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 int $port
  476. * @param int $timeout
  477. * @param int $cipher
  478. * @return Net_SSH1
  479. * @access public
  480. */
  481. function __construct($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. * PHP4 compatible Default Constructor.
  520. *
  521. * @see self::__construct()
  522. * @param string $host
  523. * @param int $port
  524. * @param int $timeout
  525. * @param int $cipher
  526. * @access public
  527. */
  528. function Net_SSH1($host, $port = 22, $timeout = 10, $cipher = NET_SSH1_CIPHER_3DES)
  529. {
  530. $this->__construct($host, $port, $timeout, $cipher);
  531. }
  532. /**
  533. * Connect to an SSHv1 server
  534. *
  535. * @return bool
  536. * @access private
  537. */
  538. function _connect()
  539. {
  540. $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->connectionTimeout);
  541. if (!$this->fsock) {
  542. user_error(rtrim("Cannot connect to {$this->host}:{$this->port}. Error $errno. $errstr"));
  543. return false;
  544. }
  545. $this->server_identification = $init_line = fgets($this->fsock, 255);
  546. if (defined('NET_SSH1_LOGGING')) {
  547. $this->_append_log('<-', $this->server_identification);
  548. $this->_append_log('->', $this->identifier . "\r\n");
  549. }
  550. if (!preg_match('#SSH-([0-9\.]+)-(.+)#', $init_line, $parts)) {
  551. user_error('Can only connect to SSH servers');
  552. return false;
  553. }
  554. if ($parts[1][0] != 1) {
  555. user_error("Cannot connect to SSH $parts[1] servers");
  556. return false;
  557. }
  558. fputs($this->fsock, $this->identifier."\r\n");
  559. $response = $this->_get_binary_packet();
  560. if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_PUBLIC_KEY) {
  561. user_error('Expected SSH_SMSG_PUBLIC_KEY');
  562. return false;
  563. }
  564. $anti_spoofing_cookie = $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 8);
  565. $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4);
  566. if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 2) {
  567. return false;
  568. }
  569. $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
  570. $server_key_public_exponent = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
  571. $this->server_key_public_exponent = $server_key_public_exponent;
  572. if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 2) {
  573. return false;
  574. }
  575. $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
  576. $server_key_public_modulus = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
  577. $this->server_key_public_modulus = $server_key_public_modulus;
  578. $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4);
  579. if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 2) {
  580. return false;
  581. }
  582. $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
  583. $host_key_public_exponent = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
  584. $this->host_key_public_exponent = $host_key_public_exponent;
  585. if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 2) {
  586. return false;
  587. }
  588. $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2));
  589. $host_key_public_modulus = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256);
  590. $this->host_key_public_modulus = $host_key_public_modulus;
  591. $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4);
  592. // get a list of the supported ciphers
  593. if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 4) {
  594. return false;
  595. }
  596. extract(unpack('Nsupported_ciphers_mask', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4)));
  597. foreach ($this->supported_ciphers as $mask => $name) {
  598. if (($supported_ciphers_mask & (1 << $mask)) == 0) {
  599. unset($this->supported_ciphers[$mask]);
  600. }
  601. }
  602. // get a list of the supported authentications
  603. if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 4) {
  604. return false;
  605. }
  606. extract(unpack('Nsupported_authentications_mask', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4)));
  607. foreach ($this->supported_authentications as $mask => $name) {
  608. if (($supported_authentications_mask & (1 << $mask)) == 0) {
  609. unset($this->supported_authentications[$mask]);
  610. }
  611. }
  612. $session_id = pack('H*', md5($host_key_public_modulus->toBytes() . $server_key_public_modulus->toBytes() . $anti_spoofing_cookie));
  613. $session_key = crypt_random_string(32);
  614. $double_encrypted_session_key = $session_key ^ str_pad($session_id, 32, chr(0));
  615. if ($server_key_public_modulus->compare($host_key_public_modulus) < 0) {
  616. $double_encrypted_session_key = $this->_rsa_crypt(
  617. $double_encrypted_session_key,
  618. array(
  619. $server_key_public_exponent,
  620. $server_key_public_modulus
  621. )
  622. );
  623. $double_encrypted_session_key = $this->_rsa_crypt(
  624. $double_encrypted_session_key,
  625. array(
  626. $host_key_public_exponent,
  627. $host_key_public_modulus
  628. )
  629. );
  630. } else {
  631. $double_encrypted_session_key = $this->_rsa_crypt(
  632. $double_encrypted_session_key,
  633. array(
  634. $host_key_public_exponent,
  635. $host_key_public_modulus
  636. )
  637. );
  638. $double_encrypted_session_key = $this->_rsa_crypt(
  639. $double_encrypted_session_key,
  640. array(
  641. $server_key_public_exponent,
  642. $server_key_public_modulus
  643. )
  644. );
  645. }
  646. $cipher = isset($this->supported_ciphers[$this->cipher]) ? $this->cipher : NET_SSH1_CIPHER_3DES;
  647. $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);
  648. if (!$this->_send_binary_packet($data)) {
  649. user_error('Error sending SSH_CMSG_SESSION_KEY');
  650. return false;
  651. }
  652. switch ($cipher) {
  653. //case NET_SSH1_CIPHER_NONE:
  654. // $this->crypto = new Crypt_Null();
  655. // break;
  656. case NET_SSH1_CIPHER_DES:
  657. if (!class_exists('Crypt_DES')) {
  658. include_once 'Crypt/DES.php';
  659. }
  660. $this->crypto = new Crypt_DES();
  661. $this->crypto->disablePadding();
  662. $this->crypto->enableContinuousBuffer();
  663. $this->crypto->setKey(substr($session_key, 0, 8));
  664. break;
  665. case NET_SSH1_CIPHER_3DES:
  666. if (!class_exists('Crypt_TripleDES')) {
  667. include_once 'Crypt/TripleDES.php';
  668. }
  669. $this->crypto = new Crypt_TripleDES(CRYPT_DES_MODE_3CBC);
  670. $this->crypto->disablePadding();
  671. $this->crypto->enableContinuousBuffer();
  672. $this->crypto->setKey(substr($session_key, 0, 24));
  673. break;
  674. //case NET_SSH1_CIPHER_RC4:
  675. // if (!class_exists('Crypt_RC4')) {
  676. // include_once 'Crypt/RC4.php';
  677. // }
  678. // $this->crypto = new Crypt_RC4();
  679. // $this->crypto->enableContinuousBuffer();
  680. // $this->crypto->setKey(substr($session_key, 0, 16));
  681. // break;
  682. }
  683. $response = $this->_get_binary_packet();
  684. if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) {
  685. user_error('Expected SSH_SMSG_SUCCESS');
  686. return false;
  687. }
  688. $this->bitmap = NET_SSH1_MASK_CONNECTED;
  689. return true;
  690. }
  691. /**
  692. * Login
  693. *
  694. * @param string $username
  695. * @param string $password
  696. * @return bool
  697. * @access public
  698. */
  699. function login($username, $password = '')
  700. {
  701. if (!($this->bitmap & NET_SSH1_MASK_CONSTRUCTOR)) {
  702. $this->bitmap |= NET_SSH1_MASK_CONSTRUCTOR;
  703. if (!$this->_connect()) {
  704. return false;
  705. }
  706. }
  707. if (!($this->bitmap & NET_SSH1_MASK_CONNECTED)) {
  708. return false;
  709. }
  710. $data = pack('CNa*', NET_SSH1_CMSG_USER, strlen($username), $username);
  711. if (!$this->_send_binary_packet($data)) {
  712. user_error('Error sending SSH_CMSG_USER');
  713. return false;
  714. }
  715. $response = $this->_get_binary_packet();
  716. if ($response === true) {
  717. return false;
  718. }
  719. if ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_SUCCESS) {
  720. $this->bitmap |= NET_SSH1_MASK_LOGIN;
  721. return true;
  722. } elseif ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_FAILURE) {
  723. user_error('Expected SSH_SMSG_SUCCESS or SSH_SMSG_FAILURE');
  724. return false;
  725. }
  726. $data = pack('CNa*', NET_SSH1_CMSG_AUTH_PASSWORD, strlen($password), $password);
  727. if (!$this->_send_binary_packet($data)) {
  728. user_error('Error sending SSH_CMSG_AUTH_PASSWORD');
  729. return false;
  730. }
  731. // remove the username and password from the last logged packet
  732. if (defined('NET_SSH1_LOGGING') && NET_SSH1_LOGGING == NET_SSH1_LOG_COMPLEX) {
  733. $data = pack('CNa*', NET_SSH1_CMSG_AUTH_PASSWORD, strlen('password'), 'password');
  734. $this->message_log[count($this->message_log) - 1] = $data;
  735. }
  736. $response = $this->_get_binary_packet();
  737. if ($response === true) {
  738. return false;
  739. }
  740. if ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_SUCCESS) {
  741. $this->bitmap |= NET_SSH1_MASK_LOGIN;
  742. return true;
  743. } elseif ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_FAILURE) {
  744. return false;
  745. } else {
  746. user_error('Expected SSH_SMSG_SUCCESS or SSH_SMSG_FAILURE');
  747. return false;
  748. }
  749. }
  750. /**
  751. * Set Timeout
  752. *
  753. * $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.
  754. * Setting $timeout to false or 0 will mean there is no timeout.
  755. *
  756. * @param mixed $timeout
  757. */
  758. function setTimeout($timeout)
  759. {
  760. $this->timeout = $this->curTimeout = $timeout;
  761. }
  762. /**
  763. * Executes a command on a non-interactive shell, returns the output, and quits.
  764. *
  765. * An SSH1 server will close the connection after a command has been executed on a non-interactive shell. SSH2
  766. * servers don't, however, this isn't an SSH2 client. The way this works, on the server, is by initiating a
  767. * shell with the -s option, as discussed in the following links:
  768. *
  769. * {@link http://www.faqs.org/docs/bashman/bashref_65.html http://www.faqs.org/docs/bashman/bashref_65.html}
  770. * {@link http://www.faqs.org/docs/bashman/bashref_62.html http://www.faqs.org/docs/bashman/bashref_62.html}
  771. *
  772. * To execute further commands, a new Net_SSH1 object will need to be created.
  773. *
  774. * Returns false on failure and the output, otherwise.
  775. *
  776. * @see self::interactiveRead()
  777. * @see self::interactiveWrite()
  778. * @param string $cmd
  779. * @return mixed
  780. * @access public
  781. */
  782. function exec($cmd, $block = true)
  783. {
  784. if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) {
  785. user_error('Operation disallowed prior to login()');
  786. return false;
  787. }
  788. $data = pack('CNa*', NET_SSH1_CMSG_EXEC_CMD, strlen($cmd), $cmd);
  789. if (!$this->_send_binary_packet($data)) {
  790. user_error('Error sending SSH_CMSG_EXEC_CMD');
  791. return false;
  792. }
  793. if (!$block) {
  794. return true;
  795. }
  796. $output = '';
  797. $response = $this->_get_binary_packet();
  798. if ($response !== false) {
  799. do {
  800. $output.= substr($response[NET_SSH1_RESPONSE_DATA], 4);
  801. $response = $this->_get_binary_packet();
  802. } while (is_array($response) && $response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_EXITSTATUS);
  803. }
  804. $data = pack('C', NET_SSH1_CMSG_EXIT_CONFIRMATION);
  805. // i don't think it's really all that important if this packet gets sent or not.
  806. $this->_send_binary_packet($data);
  807. fclose($this->fsock);
  808. // reset the execution bitmap - a new Net_SSH1 object needs to be created.
  809. $this->bitmap = 0;
  810. return $output;
  811. }
  812. /**
  813. * Creates an interactive shell
  814. *
  815. * @see self::interactiveRead()
  816. * @see self::interactiveWrite()
  817. * @return bool
  818. * @access private
  819. */
  820. function _initShell()
  821. {
  822. // connect using the sample parameters in protocol-1.5.txt.
  823. // according to wikipedia.org's entry on text terminals, "the fundamental type of application running on a text
  824. // terminal is a command line interpreter or shell". thus, opening a terminal session to run the shell.
  825. $data = pack('CNa*N4C', NET_SSH1_CMSG_REQUEST_PTY, strlen('vt100'), 'vt100', 24, 80, 0, 0, NET_SSH1_TTY_OP_END);
  826. if (!$this->_send_binary_packet($data)) {
  827. user_error('Error sending SSH_CMSG_REQUEST_PTY');
  828. return false;
  829. }
  830. $response = $this->_get_binary_packet();
  831. if ($response === true) {
  832. return false;
  833. }
  834. if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) {
  835. user_error('Expected SSH_SMSG_SUCCESS');
  836. return false;
  837. }
  838. $data = pack('C', NET_SSH1_CMSG_EXEC_SHELL);
  839. if (!$this->_send_binary_packet($data)) {
  840. user_error('Error sending SSH_CMSG_EXEC_SHELL');
  841. return false;
  842. }
  843. $this->bitmap |= NET_SSH1_MASK_SHELL;
  844. //stream_set_blocking($this->fsock, 0);
  845. return true;
  846. }
  847. /**
  848. * Inputs a command into an interactive shell.
  849. *
  850. * @see self::interactiveWrite()
  851. * @param string $cmd
  852. * @return bool
  853. * @access public
  854. */
  855. function write($cmd)
  856. {
  857. return $this->interactiveWrite($cmd);
  858. }
  859. /**
  860. * Returns the output of an interactive shell when there's a match for $expect
  861. *
  862. * $expect can take the form of a string literal or, if $mode == NET_SSH1_READ_REGEX,
  863. * a regular expression.
  864. *
  865. * @see self::write()
  866. * @param string $expect
  867. * @param int $mode
  868. * @return bool
  869. * @access public
  870. */
  871. function read($expect, $mode = NET_SSH1_READ_SIMPLE)
  872. {
  873. if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) {
  874. user_error('Operation disallowed prior to login()');
  875. return false;
  876. }
  877. if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) {
  878. user_error('Unable to initiate an interactive shell session');
  879. return false;
  880. }
  881. $match = $expect;
  882. while (true) {
  883. if ($mode == NET_SSH1_READ_REGEX) {
  884. preg_match($expect, $this->interactiveBuffer, $matches);
  885. $match = isset($matches[0]) ? $matches[0] : '';
  886. }
  887. $pos = strlen($match) ? strpos($this->interactiveBuffer, $match) : false;
  888. if ($pos !== false) {
  889. return $this->_string_shift($this->interactiveBuffer, $pos + strlen($match));
  890. }
  891. $response = $this->_get_binary_packet();
  892. if ($response === true) {
  893. return $this->_string_shift($this->interactiveBuffer, strlen($this->interactiveBuffer));
  894. }
  895. $this->interactiveBuffer.= substr($response[NET_SSH1_RESPONSE_DATA], 4);
  896. }
  897. }
  898. /**
  899. * Inputs a command into an interactive shell.
  900. *
  901. * @see self::interactiveRead()
  902. * @param string $cmd
  903. * @return bool
  904. * @access public
  905. */
  906. function interactiveWrite($cmd)
  907. {
  908. if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) {
  909. user_error('Operation disallowed prior to login()');
  910. return false;
  911. }
  912. if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) {
  913. user_error('Unable to initiate an interactive shell session');
  914. return false;
  915. }
  916. $data = pack('CNa*', NET_SSH1_CMSG_STDIN_DATA, strlen($cmd), $cmd);
  917. if (!$this->_send_binary_packet($data)) {
  918. user_error('Error sending SSH_CMSG_STDIN');
  919. return false;
  920. }
  921. return true;
  922. }
  923. /**
  924. * Returns the output of an interactive shell when no more output is available.
  925. *
  926. * Requires PHP 4.3.0 or later due to the use of the stream_select() function. If you see stuff like
  927. * "^[[00m", you're seeing ANSI escape codes. According to
  928. * {@link http://support.microsoft.com/kb/101875 How to Enable ANSI.SYS in a Command Window}, "Windows NT
  929. * does not support ANSI escape sequences in Win32 Console applications", so if you're a Windows user,
  930. * there's not going to be much recourse.
  931. *
  932. * @see self::interactiveRead()
  933. * @return string
  934. * @access public
  935. */
  936. function interactiveRead()
  937. {
  938. if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) {
  939. user_error('Operation disallowed prior to login()');
  940. return false;
  941. }
  942. if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) {
  943. user_error('Unable to initiate an interactive shell session');
  944. return false;
  945. }
  946. $read = array($this->fsock);
  947. $write = $except = null;
  948. if (stream_select($read, $write, $except, 0)) {
  949. $response = $this->_get_binary_packet();
  950. return substr($response[NET_SSH1_RESPONSE_DATA], 4);
  951. } else {
  952. return '';
  953. }
  954. }
  955. /**
  956. * Disconnect
  957. *
  958. * @access public
  959. */
  960. function disconnect()
  961. {
  962. $this->_disconnect();
  963. }
  964. /**
  965. * Destructor.
  966. *
  967. * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
  968. * disconnect().
  969. *
  970. * @access public
  971. */
  972. function __destruct()
  973. {
  974. $this->_disconnect();
  975. }
  976. /**
  977. * Disconnect
  978. *
  979. * @param string $msg
  980. * @access private
  981. */
  982. function _disconnect($msg = 'Client Quit')
  983. {
  984. if ($this->bitmap) {
  985. $data = pack('C', NET_SSH1_CMSG_EOF);
  986. $this->_send_binary_packet($data);
  987. /*
  988. $response = $this->_get_binary_packet();
  989. if ($response === true) {
  990. $response = array(NET_SSH1_RESPONSE_TYPE => -1);
  991. }
  992. switch ($response[NET_SSH1_RESPONSE_TYPE]) {
  993. case NET_SSH1_SMSG_EXITSTATUS:
  994. $data = pack('C', NET_SSH1_CMSG_EXIT_CONFIRMATION);
  995. break;
  996. default:
  997. $data = pack('CNa*', NET_SSH1_MSG_DISCONNECT, strlen($msg), $msg);
  998. }
  999. */
  1000. $data = pack('CNa*', NET_SSH1_MSG_DISCONNECT, strlen($msg), $msg);
  1001. $this->_send_binary_packet($data);
  1002. fclose($this->fsock);
  1003. $this->bitmap = 0;
  1004. }
  1005. }
  1006. /**
  1007. * Gets Binary Packets
  1008. *
  1009. * See 'The Binary Packet Protocol' of protocol-1.5.txt for more info.
  1010. *
  1011. * Also, this function could be improved upon by adding detection for the following exploit:
  1012. * http://www.securiteam.com/securitynews/5LP042K3FY.html
  1013. *
  1014. * @see self::_send_binary_packet()
  1015. * @return array
  1016. * @access private
  1017. */
  1018. function _get_binary_packet()
  1019. {
  1020. if (feof($this->fsock)) {
  1021. //user_error('connection closed prematurely');
  1022. return false;
  1023. }
  1024. if ($this->curTimeout) {
  1025. $read = array($this->fsock);
  1026. $write = $except = null;
  1027. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  1028. $sec = floor($this->curTimeout);
  1029. $usec = 1000000 * ($this->curTimeout - $sec);
  1030. // on windows this returns a "Warning: Invalid CRT parameters detected" error
  1031. if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
  1032. //$this->_disconnect('Timeout');
  1033. return true;
  1034. }
  1035. $elapsed = strtok(microtime(), ' ') + strtok('') - $start;
  1036. $this->curTimeout-= $elapsed;
  1037. }
  1038. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  1039. $data = fread($this->fsock, 4);
  1040. if (strlen($data) < 4) {
  1041. return false;
  1042. }
  1043. $temp = unpack('Nlength', $data);
  1044. $padding_length = 8 - ($temp['length'] & 7);
  1045. $length = $temp['length'] + $padding_length;
  1046. $raw = '';
  1047. while ($length > 0) {
  1048. $temp = fread($this->fsock, $length);
  1049. if (strlen($temp) != $length) {
  1050. return false;
  1051. }
  1052. $raw.= $temp;
  1053. $length-= strlen($temp);
  1054. }
  1055. $stop = strtok(microtime(), ' ') + strtok('');
  1056. if (strlen($raw) && $this->crypto !== false) {
  1057. $raw = $this->crypto->decrypt($raw);
  1058. }
  1059. $padding = substr($raw, 0, $padding_length);
  1060. $type = $raw[$padding_length];
  1061. $data = substr($raw, $padding_length + 1, -4);
  1062. if (strlen($raw) < 4) {
  1063. return false;
  1064. }
  1065. $temp = unpack('Ncrc', substr($raw, -4));
  1066. //if ( $temp['crc'] != $this->_crc($padding . $type . $data) ) {
  1067. // user_error('Bad CRC in packet from server');
  1068. // return false;
  1069. //}
  1070. $type = ord($type);
  1071. if (defined('NET_SSH1_LOGGING')) {
  1072. $temp = isset($this->protocol_flags[$type]) ? $this->protocol_flags[$type] : 'UNKNOWN';
  1073. $temp = '<- ' . $temp .
  1074. ' (' . round($stop - $start, 4) . 's)';
  1075. $this->_append_log($temp, $data);
  1076. }
  1077. return array(
  1078. NET_SSH1_RESPONSE_TYPE => $type,
  1079. NET_SSH1_RESPONSE_DATA => $data
  1080. );
  1081. }
  1082. /**
  1083. * Sends Binary Packets
  1084. *
  1085. * Returns true on success, false on failure.
  1086. *
  1087. * @see self::_get_binary_packet()
  1088. * @param string $data
  1089. * @return bool
  1090. * @access private
  1091. */
  1092. function _send_binary_packet($data)
  1093. {
  1094. if (feof($this->fsock)) {
  1095. //user_error('connection closed prematurely');
  1096. return false;
  1097. }
  1098. $length = strlen($data) + 4;
  1099. $padding = crypt_random_string(8 - ($length & 7));
  1100. $orig = $data;
  1101. $data = $padding . $data;
  1102. $data.= pack('N', $this->_crc($data));
  1103. if ($this->crypto !== false) {
  1104. $data = $this->crypto->encrypt($data);
  1105. }
  1106. $packet = pack('Na*', $length, $data);
  1107. $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838
  1108. $result = strlen($packet) == fputs($this->fsock, $packet);
  1109. $stop = strtok(microtime(), ' ') + strtok('');
  1110. if (defined('NET_SSH1_LOGGING')) {
  1111. $temp = isset($this->protocol_flags[ord($orig[0])]) ? $this->protocol_flags[ord($orig[0])] : 'UNKNOWN';
  1112. $temp = '-> ' . $temp .
  1113. ' (' . round($stop - $start, 4) . 's)';
  1114. $this->_append_log($temp, $orig);
  1115. }
  1116. return $result;
  1117. }
  1118. /**
  1119. * Cyclic Redundancy Check (CRC)
  1120. *
  1121. * PHP's crc32 function is implemented slightly differently than the one that SSH v1 uses, so
  1122. * we've reimplemented it. A more detailed discussion of the differences can be found after
  1123. * $crc_lookup_table's initialization.
  1124. *
  1125. * @see self::_get_binary_packet()
  1126. * @see self::_send_binary_packet()
  1127. * @param string $data
  1128. * @return int
  1129. * @access private
  1130. */
  1131. function _crc($data)
  1132. {
  1133. static $crc_lookup_table = array(
  1134. 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
  1135. 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
  1136. 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
  1137. 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
  1138. 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
  1139. 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
  1140. 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
  1141. 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
  1142. 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
  1143. 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
  1144. 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
  1145. 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
  1146. 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
  1147. 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
  1148. 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
  1149. 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
  1150. 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
  1151. 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
  1152. 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
  1153. 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
  1154. 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
  1155. 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
  1156. 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
  1157. 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
  1158. 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
  1159. 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
  1160. 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
  1161. 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
  1162. 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
  1163. 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
  1164. 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
  1165. 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
  1166. 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
  1167. 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
  1168. 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
  1169. 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
  1170. 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
  1171. 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
  1172. 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
  1173. 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
  1174. 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
  1175. 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
  1176. 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
  1177. 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
  1178. 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
  1179. 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
  1180. 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
  1181. 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
  1182. 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
  1183. 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
  1184. 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
  1185. 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
  1186. 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
  1187. 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
  1188. 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
  1189. 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
  1190. 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
  1191. 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
  1192. 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
  1193. 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
  1194. 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
  1195. 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
  1196. 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
  1197. 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
  1198. );
  1199. // For this function to yield the same output as PHP's crc32 function, $crc would have to be
  1200. // set to 0xFFFFFFFF, initially - not 0x00000000 as it currently is.
  1201. $crc = 0x00000000;
  1202. $length = strlen($data);
  1203. for ($i=0; $i<$length; $i++) {
  1204. // We AND $crc >> 8 with 0x00FFFFFF because we want the eight newly added bits to all
  1205. // be zero. PHP, unfortunately, doesn't always do this. 0x80000000 >> 8, as an example,
  1206. // yields 0xFF800000 - not 0x00800000. The following link elaborates:
  1207. // http://www.php.net/manual/en/language.operators.bitwise.php#57281
  1208. $crc = (($crc >> 8) & 0x00FFFFFF) ^ $crc_lookup_table[($crc & 0xFF) ^ ord($data[$i])];
  1209. }
  1210. // In addition to having to set $crc to 0xFFFFFFFF, initially, the return value must be XOR'd with
  1211. // 0xFFFFFFFF for this function to return the same thing that PHP's crc32 function would.
  1212. return $crc;
  1213. }
  1214. /**
  1215. * String Shift
  1216. *
  1217. * Inspired by array_shift
  1218. *
  1219. * @param string $string
  1220. * @param int $index
  1221. * @return string
  1222. * @access private
  1223. */
  1224. function _string_shift(&$string, $index = 1)
  1225. {
  1226. $substr = substr($string, 0, $index);
  1227. $string = substr($string, $index);
  1228. return $substr;
  1229. }
  1230. /**
  1231. * RSA Encrypt
  1232. *
  1233. * Returns mod(pow($m, $e), $n), where $n should be the product of two (large) primes $p and $q and where $e
  1234. * should be a number with the property that gcd($e, ($p - 1) * ($q - 1)) == 1. Could just make anything that
  1235. * calls this call modexp, instead, but I think this makes things clearer, maybe...
  1236. *
  1237. * @see self::Net_SSH1()
  1238. * @param Math_BigInteger $m
  1239. * @param array $key
  1240. * @return Math_BigInteger
  1241. * @access private
  1242. */
  1243. function _rsa_crypt($m, $key)
  1244. {
  1245. /*
  1246. if (!class_exists('Crypt_RSA')) {
  1247. include_once 'Crypt/RSA.php';
  1248. }
  1249. $rsa = new Crypt_RSA();
  1250. $rsa->loadKey($key, CRYPT_RSA_PUBLIC_FORMAT_RAW);
  1251. $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
  1252. return $rsa->encrypt($m);
  1253. */
  1254. // To quote from protocol-1.5.txt:
  1255. // The most significant byte (which is only partial as the value must be
  1256. // less than the public modulus, which is never a power of two) is zero.
  1257. //
  1258. // The next byte contains the value 2 (which stands for public-key
  1259. // encrypted data in the PKCS standard [PKCS#1]). Then, there are non-
  1260. // zero random bytes to fill any unused space, a zero byte, and the data
  1261. // to be encrypted in the least significant bytes, the last byte of the
  1262. // data in the least significant byte.
  1263. // Presumably the part of PKCS#1 they're refering to is "Section 7.2.1 Encryption Operation",
  1264. // under "7.2 RSAES-PKCS1-v1.5" and "7 Encryption schemes" of the following URL:
  1265. // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf
  1266. $modulus = $key[1]->toBytes();
  1267. $length = strlen($modulus) - strlen($m) - 3;
  1268. $random = '';
  1269. while (strlen($random) != $length) {
  1270. $block = crypt_random_string($length - strlen($random));
  1271. $block = str_replace("\x00", '', $block);
  1272. $random.= $block;
  1273. }
  1274. $temp = chr(0) . chr(2) . $random . chr(0) . $m;
  1275. $m = new Math_BigInteger($temp, 256);
  1276. $m = $m->modPow($key[0], $key[1]);
  1277. return $m->toBytes();
  1278. }
  1279. /**
  1280. * Define Array
  1281. *
  1282. * Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of
  1283. * named constants from it, using the value as the name of the constant and the index as the value of the constant.
  1284. * If any of the constants that would be defined already exists, none of the constants will be defined.
  1285. *
  1286. * @param array $array
  1287. * @access private
  1288. */
  1289. function _define_array()
  1290. {
  1291. $args = func_get_args();
  1292. foreach ($args as $arg) {
  1293. foreach ($arg as $key => $value) {
  1294. if (!defined($value)) {
  1295. define($value, $key);
  1296. } else {
  1297. break 2;
  1298. }
  1299. }
  1300. }
  1301. }
  1302. /**
  1303. * Returns a log of the packets that have been sent and received.
  1304. *
  1305. * 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')
  1306. *
  1307. * @access public
  1308. * @return array|false|string
  1309. */
  1310. function getLog()
  1311. {
  1312. if (!defined('NET_SSH1_LOGGING')) {
  1313. return false;
  1314. }
  1315. switch (NET_SSH1_LOGGING) {
  1316. case NET_SSH1_LOG_SIMPLE:
  1317. return $this->message_number_log;
  1318. break;
  1319. case NET_SSH1_LOG_COMPLEX:
  1320. return $this->_format_log($this->message_log, $this->protocol_flags_log);
  1321. break;
  1322. default:
  1323. return false;
  1324. }
  1325. }
  1326. /**
  1327. * Formats a log for printing
  1328. *
  1329. * @param array $message_log
  1330. * @param array $message_number_log
  1331. * @access private
  1332. * @return string
  1333. */
  1334. function _format_log($message_log, $message_number_log)
  1335. {
  1336. $output = '';
  1337. for ($i = 0; $i < count($message_log); $i++) {
  1338. $output.= $message_number_log[$i] . "\r\n";
  1339. $current_log = $message_log[$i];
  1340. $j = 0;
  1341. do {
  1342. if (strlen($current_log)) {
  1343. $output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 ';
  1344. }
  1345. $fragment = $this->_string_shift($current_log, $this->log_short_width);
  1346. $hex = substr(preg_replace_callback('#.#s', array($this, '_format_log_helper'), $fragment), strlen($this->log_boundary));
  1347. // replace non ASCII printable characters with dots
  1348. // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
  1349. // also replace < with a . since < messes up the output on web browsers
  1350. $raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment);
  1351. $output.= str_pad($hex, $this->log_long_width - $this->log_short_width, ' ') . $raw . "\r\n";
  1352. $j++;
  1353. } while (strlen($current_log));
  1354. $output.= "\r\n";
  1355. }
  1356. return $output;
  1357. }
  1358. /**
  1359. * Helper function for _format_log
  1360. *
  1361. * For use with preg_replace_callback()
  1362. *
  1363. * @param array $matches
  1364. * @access private
  1365. * @return string
  1366. */
  1367. function _format_log_helper($matches)
  1368. {
  1369. return $this->log_boundary . str_pad(dechex(ord($matches[0])), 2, '0', STR_PAD_LEFT);
  1370. }
  1371. /**
  1372. * Return the server key public exponent
  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 bool $raw_output
  1378. * @return string
  1379. * @access public
  1380. */
  1381. function getServerKeyPublicExponent($raw_output = false)
  1382. {
  1383. return $raw_output ? $this->server_key_public_exponent->toBytes() : $this->server_key_public_exponent->toString();
  1384. }
  1385. /**
  1386. * Return the server key public modulus
  1387. *
  1388. * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead,
  1389. * the raw bytes. This behavior is similar to PHP's md5() function.
  1390. *
  1391. * @param bool $raw_output
  1392. * @return string
  1393. * @access public
  1394. */
  1395. function getServerKeyPublicModulus($raw_output = false)
  1396. {
  1397. return $raw_output ? $this->server_key_public_modulus->toBytes() : $this->server_key_public_modulus->toString();
  1398. }
  1399. /**
  1400. * Return the host key public exponent
  1401. *
  1402. * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead,
  1403. * the raw bytes. This behavior is similar to PHP's md5() function.
  1404. *
  1405. * @param bool $raw_output
  1406. * @return string
  1407. * @access public
  1408. */
  1409. function getHostKeyPublicExponent($raw_output = false)
  1410. {
  1411. return $raw_output ? $this->host_key_public_exponent->toBytes() : $this->host_key_public_exponent->toString();
  1412. }
  1413. /**
  1414. * Return the host key public modulus
  1415. *
  1416. * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead,
  1417. * the raw bytes. This behavior is similar to PHP's md5() function.
  1418. *
  1419. * @param bool $raw_output
  1420. * @return string
  1421. * @access public
  1422. */
  1423. function getHostKeyPublicModulus($raw_output = false)
  1424. {
  1425. return $raw_output ? $this->host_key_public_modulus->toBytes() : $this->host_key_public_modulus->toString();
  1426. }
  1427. /**
  1428. * Return a list of ciphers supported by SSH1 server.
  1429. *
  1430. * Just because a cipher is supported by an SSH1 server doesn't mean it's supported by this library. If $raw_output
  1431. * is set to true, returns, instead, an array of constants. ie. instead of array('Triple-DES in CBC mode'), you'll
  1432. * get array(NET_SSH1_CIPHER_3DES).
  1433. *
  1434. * @param bool $raw_output
  1435. * @return array
  1436. * @access public
  1437. */
  1438. function getSupportedCiphers($raw_output = false)
  1439. {
  1440. return $raw_output ? array_keys($this->supported_ciphers) : array_values($this->supported_ciphers);
  1441. }
  1442. /**
  1443. * Return a list of authentications supported by SSH1 server.
  1444. *
  1445. * Just because a cipher is supported by an SSH1 server doesn't mean it's supported by this library. If $raw_output
  1446. * is set to true, returns, instead, an array of constants. ie. instead of array('password authentication'), you'll
  1447. * get array(NET_SSH1_AUTH_PASSWORD).
  1448. *
  1449. * @param bool $raw_output
  1450. * @return array
  1451. * @access public
  1452. */
  1453. function getSupportedAuthentications($raw_output = false)
  1454. {
  1455. return $raw_output ? array_keys($this->supported_authentications) : array_values($this->supported_authentications);
  1456. }
  1457. /**
  1458. * Return the server identification.
  1459. *
  1460. * @return string
  1461. * @access public
  1462. */
  1463. function getServerIdentification()
  1464. {
  1465. return rtrim($this->server_identification);
  1466. }
  1467. /**
  1468. * Logs data packets
  1469. *
  1470. * Makes sure that only the last 1MB worth of packets will be logged
  1471. *
  1472. * @param string $data
  1473. * @access private
  1474. */
  1475. function _append_log($protocol_flags, $message)
  1476. {
  1477. switch (NET_SSH1_LOGGING) {
  1478. // useful for benchmarks
  1479. case NET_SSH1_LOG_SIMPLE:
  1480. $this->protocol_flags_log[] = $protocol_flags;
  1481. break;
  1482. // the most useful log for SSH1
  1483. case NET_SSH1_LOG_COMPLEX:
  1484. $this->protocol_flags_log[] = $protocol_flags;
  1485. $this->_string_shift($message);
  1486. $this->log_size+= strlen($message);
  1487. $this->message_log[] = $message;
  1488. while ($this->log_size > NET_SSH1_LOG_MAX_SIZE) {
  1489. $this->log_size-= strlen(array_shift($this->message_log));
  1490. array_shift($this->protocol_flags_log);
  1491. }
  1492. break;
  1493. // dump the output out realtime; packets may be interspersed with non packets,
  1494. // passwords won't be filtered out and select other packets may not be correctly
  1495. // identified
  1496. case NET_SSH1_LOG_REALTIME:
  1497. echo "<pre>\r\n" . $this->_format_log(array($message), array($protocol_flags)) . "\r\n</pre>\r\n";
  1498. @flush();
  1499. @ob_flush();
  1500. break;
  1501. // basically the same thing as NET_SSH1_LOG_REALTIME with the caveat that NET_SSH1_LOG_REALTIME_FILE
  1502. // needs to be defined and that the resultant log file will be capped out at NET_SSH1_LOG_MAX_SIZE.
  1503. // the earliest part of the log file is denoted by the first <<< START >>> and is not going to necessarily
  1504. // at the beginning of the file
  1505. case NET_SSH1_LOG_REALTIME_FILE:
  1506. if (!isset($this->realtime_log_file)) {
  1507. // PHP doesn't seem to like using constants in fopen()
  1508. $filename = NET_SSH1_LOG_REALTIME_FILE;
  1509. $fp = fopen($filename, 'w');
  1510. $this->realtime_log_file = $fp;
  1511. }
  1512. if (!is_resource($this->realtime_log_file)) {
  1513. break;
  1514. }
  1515. $entry = $this->_format_log(array($message), array($protocol_flags));
  1516. if ($this->realtime_log_wrap) {
  1517. $temp = "<<< START >>>\r\n";
  1518. $entry.= $temp;
  1519. fseek($this->realtime_log_file, ftell($this->realtime_log_file) - strlen($temp));
  1520. }
  1521. $this->realtime_log_size+= strlen($entry);
  1522. if ($this->realtime_log_size > NET_SSH1_LOG_MAX_SIZE) {
  1523. fseek($this->realtime_log_file, 0);
  1524. $this->realtime_log_size = strlen($entry);
  1525. $this->realtime_log_wrap = true;
  1526. }
  1527. fputs($this->realtime_log_file, $entry);
  1528. }
  1529. }
  1530. }