SSH1.php 52 KB

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