SSH2.php 148 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441
  1. <?php
  2. /**
  3. * Pure-PHP implementation of SSHv2.
  4. *
  5. * PHP version 5
  6. *
  7. * Here are some examples of how to use this library:
  8. * <code>
  9. * <?php
  10. * include 'vendor/autoload.php';
  11. *
  12. * $ssh = new \phpseclib\Net\SSH2('www.domain.tld');
  13. * if (!$ssh->login('username', 'password')) {
  14. * exit('Login Failed');
  15. * }
  16. *
  17. * echo $ssh->exec('pwd');
  18. * echo $ssh->exec('ls -la');
  19. * ?>
  20. * </code>
  21. *
  22. * <code>
  23. * <?php
  24. * include 'vendor/autoload.php';
  25. *
  26. * $key = new \phpseclib\Crypt\RSA();
  27. * //$key->setPassword('whatever');
  28. * $key->load(file_get_contents('privatekey'));
  29. *
  30. * $ssh = new \phpseclib\Net\SSH2('www.domain.tld');
  31. * if (!$ssh->login('username', $key)) {
  32. * exit('Login Failed');
  33. * }
  34. *
  35. * echo $ssh->read('username@username:~$');
  36. * $ssh->write("ls -la\n");
  37. * echo $ssh->read('username@username:~$');
  38. * ?>
  39. * </code>
  40. *
  41. * @category Net
  42. * @package SSH2
  43. * @author Jim Wigginton <terrafrost@php.net>
  44. * @copyright 2007 Jim Wigginton
  45. * @license http://www.opensource.org/licenses/mit-license.html MIT License
  46. * @link http://phpseclib.sourceforge.net
  47. */
  48. namespace phpseclib\Net;
  49. use ParagonIE\ConstantTime\Base64;
  50. use phpseclib\Crypt\Common\BlockCipher;
  51. use phpseclib\Crypt\Blowfish;
  52. use phpseclib\Crypt\Hash;
  53. use phpseclib\Crypt\Random;
  54. use phpseclib\Crypt\RC4;
  55. use phpseclib\Crypt\Rijndael;
  56. use phpseclib\Crypt\RSA;
  57. use phpseclib\Crypt\TripleDES;
  58. use phpseclib\Crypt\Twofish;
  59. use phpseclib\Math\BigInteger; // Used to do Diffie-Hellman key exchange and DSA/RSA signature verification.
  60. use phpseclib\System\SSH\Agent;
  61. use phpseclib\Exception\NoSupportedAlgorithmsException;
  62. use phpseclib\Common\Functions\Strings;
  63. use phpseclib\Common\Functions\Objects;
  64. /**
  65. * Pure-PHP implementation of SSHv2.
  66. *
  67. * @package SSH2
  68. * @author Jim Wigginton <terrafrost@php.net>
  69. * @access public
  70. */
  71. class SSH2
  72. {
  73. /**#@+
  74. * Execution Bitmap Masks
  75. *
  76. * @see \phpseclib\Net\SSH2::bitmap
  77. * @access private
  78. */
  79. const MASK_CONSTRUCTOR = 0x00000001;
  80. const MASK_CONNECTED = 0x00000002;
  81. const MASK_LOGIN_REQ = 0x00000004;
  82. const MASK_LOGIN = 0x00000008;
  83. const MASK_SHELL = 0x00000010;
  84. const MASK_WINDOW_ADJUST = 0x00000020;
  85. /**#@-*/
  86. /**#@+
  87. * Channel constants
  88. *
  89. * RFC4254 refers not to client and server channels but rather to sender and recipient channels. we don't refer
  90. * to them in that way because RFC4254 toggles the meaning. the client sends a SSH_MSG_CHANNEL_OPEN message with
  91. * a sender channel and the server sends a SSH_MSG_CHANNEL_OPEN_CONFIRMATION in response, with a sender and a
  92. * recepient channel. at first glance, you might conclude that SSH_MSG_CHANNEL_OPEN_CONFIRMATION's sender channel
  93. * would be the same thing as SSH_MSG_CHANNEL_OPEN's sender channel, but it's not, per this snipet:
  94. * The 'recipient channel' is the channel number given in the original
  95. * open request, and 'sender channel' is the channel number allocated by
  96. * the other side.
  97. *
  98. * @see \phpseclib\Net\SSH2::_send_channel_packet()
  99. * @see \phpseclib\Net\SSH2::_get_channel_packet()
  100. * @access private
  101. */
  102. const CHANNEL_EXEC = 0; // PuTTy uses 0x100
  103. const CHANNEL_SHELL = 1;
  104. const CHANNEL_SUBSYSTEM = 2;
  105. const CHANNEL_AGENT_FORWARD = 3;
  106. /**#@-*/
  107. /**#@+
  108. * @access public
  109. * @see \phpseclib\Net\SSH2::getLog()
  110. */
  111. /**
  112. * Returns the message numbers
  113. */
  114. const LOG_SIMPLE = 1;
  115. /**
  116. * Returns the message content
  117. */
  118. const LOG_COMPLEX = 2;
  119. /**
  120. * Outputs the content real-time
  121. */
  122. const LOG_REALTIME = 3;
  123. /**
  124. * Dumps the content real-time to a file
  125. */
  126. const LOG_REALTIME_FILE = 4;
  127. /**#@-*/
  128. /**#@+
  129. * @access public
  130. * @see \phpseclib\Net\SSH2::read()
  131. */
  132. /**
  133. * Returns when a string matching $expect exactly is found
  134. */
  135. const READ_SIMPLE = 1;
  136. /**
  137. * Returns when a string matching the regular expression $expect is found
  138. */
  139. const READ_REGEX = 2;
  140. /**
  141. * Make sure that the log never gets larger than this
  142. */
  143. const LOG_MAX_SIZE = 1048576; // 1024 * 1024
  144. /**#@-*/
  145. /**
  146. * The SSH identifier
  147. *
  148. * @var string
  149. * @access private
  150. */
  151. private $identifier;
  152. /**
  153. * The Socket Object
  154. *
  155. * @var object
  156. * @access private
  157. */
  158. private $fsock;
  159. /**
  160. * Execution Bitmap
  161. *
  162. * The bits that are set represent functions that have been called already. This is used to determine
  163. * if a requisite function has been successfully executed. If not, an error should be thrown.
  164. *
  165. * @var int
  166. * @access private
  167. */
  168. protected $bitmap = 0;
  169. /**
  170. * Error information
  171. *
  172. * @see self::getErrors()
  173. * @see self::getLastError()
  174. * @var array
  175. * @access private
  176. */
  177. private $errors = [];
  178. /**
  179. * Server Identifier
  180. *
  181. * @see self::getServerIdentification()
  182. * @var array|false
  183. * @access private
  184. */
  185. private $server_identifier = false;
  186. /**
  187. * Key Exchange Algorithms
  188. *
  189. * @see self::getKexAlgorithims()
  190. * @var array|false
  191. * @access private
  192. */
  193. private $kex_algorithms = false;
  194. /**
  195. * Minimum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods
  196. *
  197. * @see self::_key_exchange()
  198. * @var int
  199. * @access private
  200. */
  201. private $kex_dh_group_size_min = 1536;
  202. /**
  203. * Preferred Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods
  204. *
  205. * @see self::_key_exchange()
  206. * @var int
  207. * @access private
  208. */
  209. private $kex_dh_group_size_preferred = 2048;
  210. /**
  211. * Maximum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods
  212. *
  213. * @see self::_key_exchange()
  214. * @var int
  215. * @access private
  216. */
  217. private $kex_dh_group_size_max = 4096;
  218. /**
  219. * Server Host Key Algorithms
  220. *
  221. * @see self::getServerHostKeyAlgorithms()
  222. * @var array|false
  223. * @access private
  224. */
  225. private $server_host_key_algorithms = false;
  226. /**
  227. * Encryption Algorithms: Client to Server
  228. *
  229. * @see self::getEncryptionAlgorithmsClient2Server()
  230. * @var array|false
  231. * @access private
  232. */
  233. private $encryption_algorithms_client_to_server = false;
  234. /**
  235. * Encryption Algorithms: Server to Client
  236. *
  237. * @see self::getEncryptionAlgorithmsServer2Client()
  238. * @var array|false
  239. * @access private
  240. */
  241. private $encryption_algorithms_server_to_client = false;
  242. /**
  243. * MAC Algorithms: Client to Server
  244. *
  245. * @see self::getMACAlgorithmsClient2Server()
  246. * @var array|false
  247. * @access private
  248. */
  249. private $mac_algorithms_client_to_server = false;
  250. /**
  251. * MAC Algorithms: Server to Client
  252. *
  253. * @see self::getMACAlgorithmsServer2Client()
  254. * @var array|false
  255. * @access private
  256. */
  257. private $mac_algorithms_server_to_client = false;
  258. /**
  259. * Compression Algorithms: Client to Server
  260. *
  261. * @see self::getCompressionAlgorithmsClient2Server()
  262. * @var array|false
  263. * @access private
  264. */
  265. private $compression_algorithms_client_to_server = false;
  266. /**
  267. * Compression Algorithms: Server to Client
  268. *
  269. * @see self::getCompressionAlgorithmsServer2Client()
  270. * @var array|false
  271. * @access private
  272. */
  273. private $compression_algorithms_server_to_client = false;
  274. /**
  275. * Languages: Server to Client
  276. *
  277. * @see self::getLanguagesServer2Client()
  278. * @var array|false
  279. * @access private
  280. */
  281. private $languages_server_to_client = false;
  282. /**
  283. * Languages: Client to Server
  284. *
  285. * @see self::getLanguagesClient2Server()
  286. * @var array|false
  287. * @access private
  288. */
  289. private $languages_client_to_server = false;
  290. /**
  291. * Block Size for Server to Client Encryption
  292. *
  293. * "Note that the length of the concatenation of 'packet_length',
  294. * 'padding_length', 'payload', and 'random padding' MUST be a multiple
  295. * of the cipher block size or 8, whichever is larger. This constraint
  296. * MUST be enforced, even when using stream ciphers."
  297. *
  298. * -- http://tools.ietf.org/html/rfc4253#section-6
  299. *
  300. * @see self::__construct()
  301. * @see self::_send_binary_packet()
  302. * @var int
  303. * @access private
  304. */
  305. private $encrypt_block_size = 8;
  306. /**
  307. * Block Size for Client to Server Encryption
  308. *
  309. * @see self::__construct()
  310. * @see self::_get_binary_packet()
  311. * @var int
  312. * @access private
  313. */
  314. private $decrypt_block_size = 8;
  315. /**
  316. * Server to Client Encryption Object
  317. *
  318. * @see self::_get_binary_packet()
  319. * @var object
  320. * @access private
  321. */
  322. private $decrypt = false;
  323. /**
  324. * Client to Server Encryption Object
  325. *
  326. * @see self::_send_binary_packet()
  327. * @var object
  328. * @access private
  329. */
  330. private $encrypt = false;
  331. /**
  332. * Client to Server HMAC Object
  333. *
  334. * @see self::_send_binary_packet()
  335. * @var object
  336. * @access private
  337. */
  338. private $hmac_create = false;
  339. /**
  340. * Server to Client HMAC Object
  341. *
  342. * @see self::_get_binary_packet()
  343. * @var object
  344. * @access private
  345. */
  346. private $hmac_check = false;
  347. /**
  348. * Size of server to client HMAC
  349. *
  350. * We need to know how big the HMAC will be for the server to client direction so that we know how many bytes to read.
  351. * For the client to server side, the HMAC object will make the HMAC as long as it needs to be. All we need to do is
  352. * append it.
  353. *
  354. * @see self::_get_binary_packet()
  355. * @var int
  356. * @access private
  357. */
  358. private $hmac_size = false;
  359. /**
  360. * Server Public Host Key
  361. *
  362. * @see self::getServerPublicHostKey()
  363. * @var string
  364. * @access private
  365. */
  366. private $server_public_host_key;
  367. /**
  368. * Session identifier
  369. *
  370. * "The exchange hash H from the first key exchange is additionally
  371. * used as the session identifier, which is a unique identifier for
  372. * this connection."
  373. *
  374. * -- http://tools.ietf.org/html/rfc4253#section-7.2
  375. *
  376. * @see self::_key_exchange()
  377. * @var string
  378. * @access private
  379. */
  380. private $session_id = false;
  381. /**
  382. * Exchange hash
  383. *
  384. * The current exchange hash
  385. *
  386. * @see self::_key_exchange()
  387. * @var string
  388. * @access private
  389. */
  390. private $exchange_hash = false;
  391. /**
  392. * Message Numbers
  393. *
  394. * @see self::__construct()
  395. * @var array
  396. * @access private
  397. */
  398. private $message_numbers = [];
  399. /**
  400. * Disconnection Message 'reason codes' defined in RFC4253
  401. *
  402. * @see self::__construct()
  403. * @var array
  404. * @access private
  405. */
  406. private $disconnect_reasons = [];
  407. /**
  408. * SSH_MSG_CHANNEL_OPEN_FAILURE 'reason codes', defined in RFC4254
  409. *
  410. * @see self::__construct()
  411. * @var array
  412. * @access private
  413. */
  414. private $channel_open_failure_reasons = [];
  415. /**
  416. * Terminal Modes
  417. *
  418. * @link http://tools.ietf.org/html/rfc4254#section-8
  419. * @see self::__construct()
  420. * @var array
  421. * @access private
  422. */
  423. private $terminal_modes = [];
  424. /**
  425. * SSH_MSG_CHANNEL_EXTENDED_DATA's data_type_codes
  426. *
  427. * @link http://tools.ietf.org/html/rfc4254#section-5.2
  428. * @see self::__construct()
  429. * @var array
  430. * @access private
  431. */
  432. private $channel_extended_data_type_codes = [];
  433. /**
  434. * Send Sequence Number
  435. *
  436. * See 'Section 6.4. Data Integrity' of rfc4253 for more info.
  437. *
  438. * @see self::_send_binary_packet()
  439. * @var int
  440. * @access private
  441. */
  442. private $send_seq_no = 0;
  443. /**
  444. * Get Sequence Number
  445. *
  446. * See 'Section 6.4. Data Integrity' of rfc4253 for more info.
  447. *
  448. * @see self::_get_binary_packet()
  449. * @var int
  450. * @access private
  451. */
  452. private $get_seq_no = 0;
  453. /**
  454. * Server Channels
  455. *
  456. * Maps client channels to server channels
  457. *
  458. * @see self::_get_channel_packet()
  459. * @see self::exec()
  460. * @var array
  461. * @access private
  462. */
  463. protected $server_channels = [];
  464. /**
  465. * Channel Buffers
  466. *
  467. * If a client requests a packet from one channel but receives two packets from another those packets should
  468. * be placed in a buffer
  469. *
  470. * @see self::_get_channel_packet()
  471. * @see self::exec()
  472. * @var array
  473. * @access private
  474. */
  475. private $channel_buffers = [];
  476. /**
  477. * Channel Status
  478. *
  479. * Contains the type of the last sent message
  480. *
  481. * @see self::_get_channel_packet()
  482. * @var array
  483. * @access private
  484. */
  485. protected $channel_status = [];
  486. /**
  487. * Packet Size
  488. *
  489. * Maximum packet size indexed by channel
  490. *
  491. * @see self::_send_channel_packet()
  492. * @var array
  493. * @access private
  494. */
  495. private $packet_size_client_to_server = [];
  496. /**
  497. * Message Number Log
  498. *
  499. * @see self::getLog()
  500. * @var array
  501. * @access private
  502. */
  503. private $message_number_log = [];
  504. /**
  505. * Message Log
  506. *
  507. * @see self::getLog()
  508. * @var array
  509. * @access private
  510. */
  511. private $message_log = [];
  512. /**
  513. * The Window Size
  514. *
  515. * Bytes the other party can send before it must wait for the window to be adjusted (0x7FFFFFFF = 2GB)
  516. *
  517. * @var int
  518. * @see self::_send_channel_packet()
  519. * @see self::exec()
  520. * @access private
  521. */
  522. protected $window_size = 0x7FFFFFFF;
  523. /**
  524. * Window size, server to client
  525. *
  526. * Window size indexed by channel
  527. *
  528. * @see self::_send_channel_packet()
  529. * @var array
  530. * @access private
  531. */
  532. protected $window_size_server_to_client = [];
  533. /**
  534. * Window size, client to server
  535. *
  536. * Window size indexed by channel
  537. *
  538. * @see self::_get_channel_packet()
  539. * @var array
  540. * @access private
  541. */
  542. private $window_size_client_to_server = [];
  543. /**
  544. * Server signature
  545. *
  546. * Verified against $this->session_id
  547. *
  548. * @see self::getServerPublicHostKey()
  549. * @var string
  550. * @access private
  551. */
  552. private $signature = '';
  553. /**
  554. * Server signature format
  555. *
  556. * ssh-rsa or ssh-dss.
  557. *
  558. * @see self::getServerPublicHostKey()
  559. * @var string
  560. * @access private
  561. */
  562. private $signature_format = '';
  563. /**
  564. * Interactive Buffer
  565. *
  566. * @see self::read()
  567. * @var array
  568. * @access private
  569. */
  570. private $interactiveBuffer = '';
  571. /**
  572. * Current log size
  573. *
  574. * Should never exceed self::LOG_MAX_SIZE
  575. *
  576. * @see self::_send_binary_packet()
  577. * @see self::_get_binary_packet()
  578. * @var int
  579. * @access private
  580. */
  581. private $log_size;
  582. /**
  583. * Timeout
  584. *
  585. * @see self::setTimeout()
  586. * @access private
  587. */
  588. private $timeout;
  589. /**
  590. * Current Timeout
  591. *
  592. * @see self::_get_channel_packet()
  593. * @access private
  594. */
  595. private $curTimeout;
  596. /**
  597. * Real-time log file pointer
  598. *
  599. * @see self::_append_log()
  600. * @var resource
  601. * @access private
  602. */
  603. private $realtime_log_file;
  604. /**
  605. * Real-time log file size
  606. *
  607. * @see self::_append_log()
  608. * @var int
  609. * @access private
  610. */
  611. private $realtime_log_size;
  612. /**
  613. * Has the signature been validated?
  614. *
  615. * @see self::getServerPublicHostKey()
  616. * @var bool
  617. * @access private
  618. */
  619. private $signature_validated = false;
  620. /**
  621. * Real-time log file wrap boolean
  622. *
  623. * @see self::_append_log()
  624. * @access private
  625. */
  626. private $realtime_log_wrap;
  627. /**
  628. * Flag to suppress stderr from output
  629. *
  630. * @see self::enableQuietMode()
  631. * @access private
  632. */
  633. private $quiet_mode = false;
  634. /**
  635. * Time of first network activity
  636. *
  637. * @var int
  638. * @access private
  639. */
  640. private $last_packet;
  641. /**
  642. * Exit status returned from ssh if any
  643. *
  644. * @var int
  645. * @access private
  646. */
  647. private $exit_status;
  648. /**
  649. * Flag to request a PTY when using exec()
  650. *
  651. * @var bool
  652. * @see self::enablePTY()
  653. * @access private
  654. */
  655. private $request_pty = false;
  656. /**
  657. * Flag set while exec() is running when using enablePTY()
  658. *
  659. * @var bool
  660. * @access private
  661. */
  662. private $in_request_pty_exec = false;
  663. /**
  664. * Flag set after startSubsystem() is called
  665. *
  666. * @var bool
  667. * @access private
  668. */
  669. private $in_subsystem;
  670. /**
  671. * Contents of stdError
  672. *
  673. * @var string
  674. * @access private
  675. */
  676. private $stdErrorLog;
  677. /**
  678. * The Last Interactive Response
  679. *
  680. * @see self::_keyboard_interactive_process()
  681. * @var string
  682. * @access private
  683. */
  684. private $last_interactive_response = '';
  685. /**
  686. * Keyboard Interactive Request / Responses
  687. *
  688. * @see self::_keyboard_interactive_process()
  689. * @var array
  690. * @access private
  691. */
  692. private $keyboard_requests_responses = [];
  693. /**
  694. * Banner Message
  695. *
  696. * Quoting from the RFC, "in some jurisdictions, sending a warning message before
  697. * authentication may be relevant for getting legal protection."
  698. *
  699. * @see self::_filter()
  700. * @see self::getBannerMessage()
  701. * @var string
  702. * @access private
  703. */
  704. private $banner_message = '';
  705. /**
  706. * Did read() timeout or return normally?
  707. *
  708. * @see self::isTimeout()
  709. * @var bool
  710. * @access private
  711. */
  712. private $is_timeout = false;
  713. /**
  714. * Log Boundary
  715. *
  716. * @see self::_format_log()
  717. * @var string
  718. * @access private
  719. */
  720. private $log_boundary = ':';
  721. /**
  722. * Log Long Width
  723. *
  724. * @see self::_format_log()
  725. * @var int
  726. * @access private
  727. */
  728. private $log_long_width = 65;
  729. /**
  730. * Log Short Width
  731. *
  732. * @see self::_format_log()
  733. * @var int
  734. * @access private
  735. */
  736. private $log_short_width = 16;
  737. /**
  738. * Hostname
  739. *
  740. * @see self::__construct()
  741. * @see self::_connect()
  742. * @var string
  743. * @access private
  744. */
  745. private $host;
  746. /**
  747. * Port Number
  748. *
  749. * @see self::__construct()
  750. * @see self::_connect()
  751. * @var int
  752. * @access private
  753. */
  754. private $port;
  755. /**
  756. * Number of columns for terminal window size
  757. *
  758. * @see self::getWindowColumns()
  759. * @see self::setWindowColumns()
  760. * @see self::setWindowSize()
  761. * @var int
  762. * @access private
  763. */
  764. private $windowColumns = 80;
  765. /**
  766. * Number of columns for terminal window size
  767. *
  768. * @see self::getWindowRows()
  769. * @see self::setWindowRows()
  770. * @see self::setWindowSize()
  771. * @var int
  772. * @access private
  773. */
  774. private $windowRows = 24;
  775. /**
  776. * Crypto Engine
  777. *
  778. * @see self::setCryptoEngine()
  779. * @see self::_key_exchange()
  780. * @var int
  781. * @access private
  782. */
  783. private $crypto_engine = false;
  784. /**
  785. * A System_SSH_Agent for use in the SSH2 Agent Forwarding scenario
  786. *
  787. * @var System_SSH_Agent
  788. * @access private
  789. */
  790. private $agent;
  791. /**
  792. * Connection storage to replicates ssh2 extension functionality:
  793. * {@link http://php.net/manual/en/wrappers.ssh2.php#refsect1-wrappers.ssh2-examples}
  794. *
  795. * @var SSH2[]
  796. */
  797. private static $connections;
  798. /**
  799. * Default Constructor.
  800. *
  801. * $host can either be a string, representing the host, or a stream resource.
  802. *
  803. * @param mixed $host
  804. * @param int $port
  805. * @param int $timeout
  806. * @see self::login()
  807. * @return \phpseclib\Net\SSH2
  808. * @access public
  809. */
  810. public function __construct($host, $port = 22, $timeout = 10)
  811. {
  812. $this->message_numbers = [
  813. 1 => 'NET_SSH2_MSG_DISCONNECT',
  814. 2 => 'NET_SSH2_MSG_IGNORE',
  815. 3 => 'NET_SSH2_MSG_UNIMPLEMENTED',
  816. 4 => 'NET_SSH2_MSG_DEBUG',
  817. 5 => 'NET_SSH2_MSG_SERVICE_REQUEST',
  818. 6 => 'NET_SSH2_MSG_SERVICE_ACCEPT',
  819. 20 => 'NET_SSH2_MSG_KEXINIT',
  820. 21 => 'NET_SSH2_MSG_NEWKEYS',
  821. 30 => 'NET_SSH2_MSG_KEXDH_INIT',
  822. 31 => 'NET_SSH2_MSG_KEXDH_REPLY',
  823. 50 => 'NET_SSH2_MSG_USERAUTH_REQUEST',
  824. 51 => 'NET_SSH2_MSG_USERAUTH_FAILURE',
  825. 52 => 'NET_SSH2_MSG_USERAUTH_SUCCESS',
  826. 53 => 'NET_SSH2_MSG_USERAUTH_BANNER',
  827. 80 => 'NET_SSH2_MSG_GLOBAL_REQUEST',
  828. 81 => 'NET_SSH2_MSG_REQUEST_SUCCESS',
  829. 82 => 'NET_SSH2_MSG_REQUEST_FAILURE',
  830. 90 => 'NET_SSH2_MSG_CHANNEL_OPEN',
  831. 91 => 'NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION',
  832. 92 => 'NET_SSH2_MSG_CHANNEL_OPEN_FAILURE',
  833. 93 => 'NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST',
  834. 94 => 'NET_SSH2_MSG_CHANNEL_DATA',
  835. 95 => 'NET_SSH2_MSG_CHANNEL_EXTENDED_DATA',
  836. 96 => 'NET_SSH2_MSG_CHANNEL_EOF',
  837. 97 => 'NET_SSH2_MSG_CHANNEL_CLOSE',
  838. 98 => 'NET_SSH2_MSG_CHANNEL_REQUEST',
  839. 99 => 'NET_SSH2_MSG_CHANNEL_SUCCESS',
  840. 100 => 'NET_SSH2_MSG_CHANNEL_FAILURE'
  841. ];
  842. $this->disconnect_reasons = [
  843. 1 => 'NET_SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT',
  844. 2 => 'NET_SSH2_DISCONNECT_PROTOCOL_ERROR',
  845. 3 => 'NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED',
  846. 4 => 'NET_SSH2_DISCONNECT_RESERVED',
  847. 5 => 'NET_SSH2_DISCONNECT_MAC_ERROR',
  848. 6 => 'NET_SSH2_DISCONNECT_COMPRESSION_ERROR',
  849. 7 => 'NET_SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE',
  850. 8 => 'NET_SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED',
  851. 9 => 'NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE',
  852. 10 => 'NET_SSH2_DISCONNECT_CONNECTION_LOST',
  853. 11 => 'NET_SSH2_DISCONNECT_BY_APPLICATION',
  854. 12 => 'NET_SSH2_DISCONNECT_TOO_MANY_CONNECTIONS',
  855. 13 => 'NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER',
  856. 14 => 'NET_SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE',
  857. 15 => 'NET_SSH2_DISCONNECT_ILLEGAL_USER_NAME'
  858. ];
  859. $this->channel_open_failure_reasons = [
  860. 1 => 'NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED'
  861. ];
  862. $this->terminal_modes = [
  863. 0 => 'NET_SSH2_TTY_OP_END'
  864. ];
  865. $this->channel_extended_data_type_codes = [
  866. 1 => 'NET_SSH2_EXTENDED_DATA_STDERR'
  867. ];
  868. $this->define_array(
  869. $this->message_numbers,
  870. $this->disconnect_reasons,
  871. $this->channel_open_failure_reasons,
  872. $this->terminal_modes,
  873. $this->channel_extended_data_type_codes,
  874. [60 => 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ'],
  875. [60 => 'NET_SSH2_MSG_USERAUTH_PK_OK'],
  876. [60 => 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST',
  877. 61 => 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE'],
  878. // RFC 4419 - diffie-hellman-group-exchange-sha{1,256}
  879. [30 => 'NET_SSH2_MSG_KEXDH_GEX_REQUEST_OLD',
  880. 31 => 'NET_SSH2_MSG_KEXDH_GEX_GROUP',
  881. 32 => 'NET_SSH2_MSG_KEXDH_GEX_INIT',
  882. 33 => 'NET_SSH2_MSG_KEXDH_GEX_REPLY',
  883. 34 => 'NET_SSH2_MSG_KEXDH_GEX_REQUEST'],
  884. // RFC 5656 - Elliptic Curves (for curve25519-sha256@libssh.org)
  885. [30 => 'NET_SSH2_MSG_KEX_ECDH_INIT',
  886. 31 => 'NET_SSH2_MSG_KEX_ECDH_REPLY']
  887. );
  888. self::$connections[$this->getResourceId()] = $this;
  889. if (is_resource($host)) {
  890. $this->fsock = $host;
  891. return;
  892. }
  893. if (is_string($host)) {
  894. $this->host = $host;
  895. $this->port = $port;
  896. $this->timeout = $timeout;
  897. }
  898. }
  899. /**
  900. * Set Crypto Engine Mode
  901. *
  902. * Possible $engine values:
  903. * CRYPT_MODE_INTERNAL, CRYPT_MODE_MCRYPT
  904. *
  905. * @param int $engine
  906. * @access private
  907. */
  908. public function setCryptoEngine($engine)
  909. {
  910. $this->crypto_engine = $engine;
  911. }
  912. /**
  913. * Connect to an SSHv2 server
  914. *
  915. * @return bool
  916. * @throws \UnexpectedValueException on receipt of unexpected packets
  917. * @throws \RuntimeException on other errors
  918. * @access private
  919. */
  920. private function connect()
  921. {
  922. if ($this->bitmap & self::MASK_CONSTRUCTOR) {
  923. return false;
  924. }
  925. $this->bitmap |= self::MASK_CONSTRUCTOR;
  926. $this->curTimeout = $this->timeout;
  927. $this->last_packet = microtime(true);
  928. if (!is_resource($this->fsock)) {
  929. $start = microtime(true);
  930. // with stream_select a timeout of 0 means that no timeout takes place;
  931. // with fsockopen a timeout of 0 means that you instantly timeout
  932. // to resolve this incompatibility a timeout of 100,000 will be used for fsockopen if timeout is 0
  933. $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->curTimeout == 0 ? 100000 : $this->curTimeout);
  934. if (!$this->fsock) {
  935. $host = $this->host . ':' . $this->port;
  936. throw new \RuntimeException(rtrim("Cannot connect to $host. Error $errno. $errstr"));
  937. }
  938. $elapsed = microtime(true) - $start;
  939. $this->curTimeout-= $elapsed;
  940. if ($this->curTimeout <= 0) {
  941. $this->is_timeout = true;
  942. return false;
  943. }
  944. }
  945. $this->identifier = $this->generate_identifier();
  946. fputs($this->fsock, $this->identifier . "\r\n");
  947. /* According to the SSH2 specs,
  948. "The server MAY send other lines of data before sending the version
  949. string. Each line SHOULD be terminated by a Carriage Return and Line
  950. Feed. Such lines MUST NOT begin with "SSH-", and SHOULD be encoded
  951. in ISO-10646 UTF-8 [RFC3629] (language is not specified). Clients
  952. MUST be able to process such lines." */
  953. $data = '';
  954. while (!feof($this->fsock) && !preg_match('#(.*)^(SSH-(\d\.\d+).*)#ms', $data, $matches)) {
  955. $line = '';
  956. while (true) {
  957. if ($this->curTimeout) {
  958. if ($this->curTimeout < 0) {
  959. $this->is_timeout = true;
  960. return false;
  961. }
  962. $read = [$this->fsock];
  963. $write = $except = null;
  964. $start = microtime(true);
  965. $sec = floor($this->curTimeout);
  966. $usec = 1000000 * ($this->curTimeout - $sec);
  967. // on windows this returns a "Warning: Invalid CRT parameters detected" error
  968. // the !count() is done as a workaround for <https://bugs.php.net/42682>
  969. if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
  970. $this->is_timeout = true;
  971. return false;
  972. }
  973. $elapsed = microtime(true) - $start;
  974. $this->curTimeout-= $elapsed;
  975. }
  976. $temp = stream_get_line($this->fsock, 255, "\n");
  977. if (strlen($temp) == 255) {
  978. continue;
  979. }
  980. $line.= "$temp\n";
  981. // quoting RFC4253, "Implementers who wish to maintain
  982. // compatibility with older, undocumented versions of this protocol may
  983. // want to process the identification string without expecting the
  984. // presence of the carriage return character for reasons described in
  985. // Section 5 of this document."
  986. //if (substr($line, -2) == "\r\n") {
  987. // break;
  988. //}
  989. break;
  990. }
  991. $data.= $line;
  992. }
  993. if (feof($this->fsock)) {
  994. throw new \RuntimeException('Connection closed by server');
  995. }
  996. $extra = $matches[1];
  997. if (defined('NET_SSH2_LOGGING')) {
  998. $this->append_log('<-', $matches[0]);
  999. $this->append_log('->', $this->identifier . "\r\n");
  1000. }
  1001. $this->server_identifier = trim($temp, "\r\n");
  1002. if (strlen($extra)) {
  1003. $this->errors[] = utf8_decode($data);
  1004. }
  1005. if ($matches[3] != '1.99' && $matches[3] != '2.0') {
  1006. throw new \RuntimeException("Cannot connect to SSH $matches[1] servers");
  1007. }
  1008. $response = $this->get_binary_packet();
  1009. if ($response === false) {
  1010. throw new \RuntimeException('Connection closed by server');
  1011. }
  1012. if (!strlen($response) || ord($response[0]) != NET_SSH2_MSG_KEXINIT) {
  1013. throw new \UnexpectedValueException('Expected SSH_MSG_KEXINIT');
  1014. }
  1015. if (!$this->key_exchange($response)) {
  1016. return false;
  1017. }
  1018. $this->bitmap|= self::MASK_CONNECTED;
  1019. return true;
  1020. }
  1021. /**
  1022. * Generates the SSH identifier
  1023. *
  1024. * You should overwrite this method in your own class if you want to use another identifier
  1025. *
  1026. * @access protected
  1027. * @return string
  1028. */
  1029. private function generate_identifier()
  1030. {
  1031. $identifier = 'SSH-2.0-phpseclib_2.0';
  1032. $ext = [];
  1033. if (extension_loaded('libsodium')) {
  1034. $ext[] = 'libsodium';
  1035. }
  1036. if (extension_loaded('openssl')) {
  1037. $ext[] = 'openssl';
  1038. } elseif (extension_loaded('mcrypt')) {
  1039. $ext[] = 'mcrypt';
  1040. }
  1041. if (extension_loaded('gmp')) {
  1042. $ext[] = 'gmp';
  1043. } elseif (extension_loaded('bcmath')) {
  1044. $ext[] = 'bcmath';
  1045. }
  1046. if (!empty($ext)) {
  1047. $identifier .= ' (' . implode(', ', $ext) . ')';
  1048. }
  1049. return $identifier;
  1050. }
  1051. /**
  1052. * Key Exchange
  1053. *
  1054. * @param string $kexinit_payload_server
  1055. * @throws \UnexpectedValueException on receipt of unexpected packets
  1056. * @throws \RuntimeException on other errors
  1057. * @throws \phpseclib\Exception\NoSupportedAlgorithmsException when none of the algorithms phpseclib has loaded are compatible
  1058. * @access private
  1059. */
  1060. private function key_exchange($kexinit_payload_server)
  1061. {
  1062. $kex_algorithms = [
  1063. // Elliptic Curve Diffie-Hellman Key Agreement (ECDH) using
  1064. // Curve25519. See doc/curve25519-sha256@libssh.org.txt in the
  1065. // libssh repository for more information.
  1066. 'curve25519-sha256@libssh.org',
  1067. // Diffie-Hellman Key Agreement (DH) using integer modulo prime
  1068. // groups.
  1069. 'diffie-hellman-group1-sha1', // REQUIRED
  1070. 'diffie-hellman-group14-sha1', // REQUIRED
  1071. 'diffie-hellman-group-exchange-sha1', // RFC 4419
  1072. 'diffie-hellman-group-exchange-sha256', // RFC 4419
  1073. ];
  1074. if (!function_exists('\\Sodium\\library_version_major')) {
  1075. $kex_algorithms = array_diff(
  1076. $kex_algorithms,
  1077. ['curve25519-sha256@libssh.org']
  1078. );
  1079. }
  1080. $server_host_key_algorithms = [
  1081. 'ssh-rsa', // RECOMMENDED sign Raw RSA Key
  1082. 'ssh-dss' // REQUIRED sign Raw DSS Key
  1083. ];
  1084. $encryption_algorithms = [
  1085. // from <http://tools.ietf.org/html/rfc4345#section-4>:
  1086. 'arcfour256',
  1087. 'arcfour128',
  1088. //'arcfour', // OPTIONAL the ARCFOUR stream cipher with a 128-bit key
  1089. // CTR modes from <http://tools.ietf.org/html/rfc4344#section-4>:
  1090. 'aes128-ctr', // RECOMMENDED AES (Rijndael) in SDCTR mode, with 128-bit key
  1091. 'aes192-ctr', // RECOMMENDED AES with 192-bit key
  1092. 'aes256-ctr', // RECOMMENDED AES with 256-bit key
  1093. 'twofish128-ctr', // OPTIONAL Twofish in SDCTR mode, with 128-bit key
  1094. 'twofish192-ctr', // OPTIONAL Twofish with 192-bit key
  1095. 'twofish256-ctr', // OPTIONAL Twofish with 256-bit key
  1096. 'aes128-cbc', // RECOMMENDED AES with a 128-bit key
  1097. 'aes192-cbc', // OPTIONAL AES with a 192-bit key
  1098. 'aes256-cbc', // OPTIONAL AES in CBC mode, with a 256-bit key
  1099. 'twofish128-cbc', // OPTIONAL Twofish with a 128-bit key
  1100. 'twofish192-cbc', // OPTIONAL Twofish with a 192-bit key
  1101. 'twofish256-cbc',
  1102. 'twofish-cbc', // OPTIONAL alias for "twofish256-cbc"
  1103. // (this is being retained for historical reasons)
  1104. 'blowfish-ctr', // OPTIONAL Blowfish in SDCTR mode
  1105. 'blowfish-cbc', // OPTIONAL Blowfish in CBC mode
  1106. '3des-ctr', // RECOMMENDED Three-key 3DES in SDCTR mode
  1107. '3des-cbc', // REQUIRED three-key 3DES in CBC mode
  1108. //'none' // OPTIONAL no encryption; NOT RECOMMENDED
  1109. ];
  1110. if (extension_loaded('openssl') && !extension_loaded('mcrypt')) {
  1111. // OpenSSL does not support arcfour256 in any capacity and arcfour128 / arcfour support is limited to
  1112. // instances that do not use continuous buffers
  1113. $encryption_algorithms = array_diff(
  1114. $encryption_algorithms,
  1115. ['arcfour256', 'arcfour128', 'arcfour']
  1116. );
  1117. }
  1118. if (class_exists('\phpseclib\Crypt\RC4') === false) {
  1119. $encryption_algorithms = array_diff(
  1120. $encryption_algorithms,
  1121. ['arcfour256', 'arcfour128', 'arcfour']
  1122. );
  1123. }
  1124. if (class_exists('\phpseclib\Crypt\Rijndael') === false) {
  1125. $encryption_algorithms = array_diff(
  1126. $encryption_algorithms,
  1127. ['aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-cbc', 'aes192-cbc', 'aes256-cbc']
  1128. );
  1129. }
  1130. if (class_exists('\phpseclib\Crypt\Twofish') === false) {
  1131. $encryption_algorithms = array_diff(
  1132. $encryption_algorithms,
  1133. ['twofish128-ctr', 'twofish192-ctr', 'twofish256-ctr', 'twofish128-cbc', 'twofish192-cbc', 'twofish256-cbc', 'twofish-cbc']
  1134. );
  1135. }
  1136. if (class_exists('\phpseclib\Crypt\Blowfish') === false) {
  1137. $encryption_algorithms = array_diff(
  1138. $encryption_algorithms,
  1139. ['blowfish-ctr', 'blowfish-cbc']
  1140. );
  1141. }
  1142. if (class_exists('\phpseclib\Crypt\TripleDES') === false) {
  1143. $encryption_algorithms = array_diff(
  1144. $encryption_algorithms,
  1145. ['3des-ctr', '3des-cbc']
  1146. );
  1147. }
  1148. $encryption_algorithms = array_values($encryption_algorithms);
  1149. $mac_algorithms = [
  1150. // from <http://www.ietf.org/rfc/rfc6668.txt>:
  1151. 'hmac-sha2-256',// RECOMMENDED HMAC-SHA256 (digest length = key length = 32)
  1152. 'hmac-sha1-96', // RECOMMENDED first 96 bits of HMAC-SHA1 (digest length = 12, key length = 20)
  1153. 'hmac-sha1', // REQUIRED HMAC-SHA1 (digest length = key length = 20)
  1154. 'hmac-md5-96', // OPTIONAL first 96 bits of HMAC-MD5 (digest length = 12, key length = 16)
  1155. 'hmac-md5', // OPTIONAL HMAC-MD5 (digest length = key length = 16)
  1156. //'none' // OPTIONAL no MAC; NOT RECOMMENDED
  1157. ];
  1158. $compression_algorithms = [
  1159. 'none' // REQUIRED no compression
  1160. //'zlib' // OPTIONAL ZLIB (LZ77) compression
  1161. ];
  1162. // some SSH servers have buggy implementations of some of the above algorithms
  1163. switch ($this->server_identifier) {
  1164. case 'SSH-2.0-SSHD':
  1165. $mac_algorithms = array_values(array_diff(
  1166. $mac_algorithms,
  1167. ['hmac-sha1-96', 'hmac-md5-96']
  1168. ));
  1169. }
  1170. $str_kex_algorithms = implode(',', $kex_algorithms);
  1171. $str_server_host_key_algorithms = implode(',', $server_host_key_algorithms);
  1172. $encryption_algorithms_server_to_client = $encryption_algorithms_client_to_server = implode(',', $encryption_algorithms);
  1173. $mac_algorithms_server_to_client = $mac_algorithms_client_to_server = implode(',', $mac_algorithms);
  1174. $compression_algorithms_server_to_client = $compression_algorithms_client_to_server = implode(',', $compression_algorithms);
  1175. $client_cookie = Random::string(16);
  1176. $response = $kexinit_payload_server;
  1177. Strings::shift($response, 1); // skip past the message number (it should be SSH_MSG_KEXINIT)
  1178. $server_cookie = Strings::shift($response, 16);
  1179. if (strlen($response) < 4) {
  1180. return false;
  1181. }
  1182. $temp = unpack('Nlength', Strings::shift($response, 4));
  1183. $this->kex_algorithms = explode(',', Strings::shift($response, $temp['length']));
  1184. if (strlen($response) < 4) {
  1185. return false;
  1186. }
  1187. $temp = unpack('Nlength', Strings::shift($response, 4));
  1188. $this->server_host_key_algorithms = explode(',', Strings::shift($response, $temp['length']));
  1189. if (strlen($response) < 4) {
  1190. return false;
  1191. }
  1192. $temp = unpack('Nlength', Strings::shift($response, 4));
  1193. $this->encryption_algorithms_client_to_server = explode(',', Strings::shift($response, $temp['length']));
  1194. if (strlen($response) < 4) {
  1195. return false;
  1196. }
  1197. $temp = unpack('Nlength', Strings::shift($response, 4));
  1198. $this->encryption_algorithms_server_to_client = explode(',', Strings::shift($response, $temp['length']));
  1199. if (strlen($response) < 4) {
  1200. return false;
  1201. }
  1202. $temp = unpack('Nlength', Strings::shift($response, 4));
  1203. $this->mac_algorithms_client_to_server = explode(',', Strings::shift($response, $temp['length']));
  1204. if (strlen($response) < 4) {
  1205. return false;
  1206. }
  1207. $temp = unpack('Nlength', Strings::shift($response, 4));
  1208. $this->mac_algorithms_server_to_client = explode(',', Strings::shift($response, $temp['length']));
  1209. if (strlen($response) < 4) {
  1210. return false;
  1211. }
  1212. $temp = unpack('Nlength', Strings::shift($response, 4));
  1213. $this->compression_algorithms_client_to_server = explode(',', Strings::shift($response, $temp['length']));
  1214. if (strlen($response) < 4) {
  1215. return false;
  1216. }
  1217. $temp = unpack('Nlength', Strings::shift($response, 4));
  1218. $this->compression_algorithms_server_to_client = explode(',', Strings::shift($response, $temp['length']));
  1219. if (strlen($response) < 4) {
  1220. return false;
  1221. }
  1222. $temp = unpack('Nlength', Strings::shift($response, 4));
  1223. $this->languages_client_to_server = explode(',', Strings::shift($response, $temp['length']));
  1224. if (strlen($response) < 4) {
  1225. return false;
  1226. }
  1227. $temp = unpack('Nlength', Strings::shift($response, 4));
  1228. $this->languages_server_to_client = explode(',', Strings::shift($response, $temp['length']));
  1229. if (!strlen($response)) {
  1230. return false;
  1231. }
  1232. extract(unpack('Cfirst_kex_packet_follows', Strings::shift($response, 1)));
  1233. $first_kex_packet_follows = $first_kex_packet_follows != 0;
  1234. // the sending of SSH2_MSG_KEXINIT could go in one of two places. this is the second place.
  1235. $kexinit_payload_client = pack(
  1236. 'Ca*Na*Na*Na*Na*Na*Na*Na*Na*Na*Na*CN',
  1237. NET_SSH2_MSG_KEXINIT,
  1238. $client_cookie,
  1239. strlen($str_kex_algorithms),
  1240. $str_kex_algorithms,
  1241. strlen($str_server_host_key_algorithms),
  1242. $str_server_host_key_algorithms,
  1243. strlen($encryption_algorithms_client_to_server),
  1244. $encryption_algorithms_client_to_server,
  1245. strlen($encryption_algorithms_server_to_client),
  1246. $encryption_algorithms_server_to_client,
  1247. strlen($mac_algorithms_client_to_server),
  1248. $mac_algorithms_client_to_server,
  1249. strlen($mac_algorithms_server_to_client),
  1250. $mac_algorithms_server_to_client,
  1251. strlen($compression_algorithms_client_to_server),
  1252. $compression_algorithms_client_to_server,
  1253. strlen($compression_algorithms_server_to_client),
  1254. $compression_algorithms_server_to_client,
  1255. 0,
  1256. '',
  1257. 0,
  1258. '',
  1259. 0,
  1260. 0
  1261. );
  1262. if (!$this->send_binary_packet($kexinit_payload_client)) {
  1263. return false;
  1264. }
  1265. // here ends the second place.
  1266. // we need to decide upon the symmetric encryption algorithms before we do the diffie-hellman key exchange
  1267. // we don't initialize any crypto-objects, yet - we do that, later. for now, we need the lengths to make the
  1268. // diffie-hellman key exchange as fast as possible
  1269. $decrypt = $this->array_intersect_first($encryption_algorithms, $this->encryption_algorithms_server_to_client);
  1270. $decryptKeyLength = $this->encryption_algorithm_to_key_size($decrypt);
  1271. if ($decryptKeyLength === null) {
  1272. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1273. throw new NoSupportedAlgorithmsException('No compatible server to client encryption algorithms found');
  1274. }
  1275. $encrypt = $this->array_intersect_first($encryption_algorithms, $this->encryption_algorithms_client_to_server);
  1276. $encryptKeyLength = $this->encryption_algorithm_to_key_size($encrypt);
  1277. if ($encryptKeyLength === null) {
  1278. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1279. throw new NoSupportedAlgorithmsException('No compatible client to server encryption algorithms found');
  1280. }
  1281. // through diffie-hellman key exchange a symmetric key is obtained
  1282. $kex_algorithm = $this->array_intersect_first($kex_algorithms, $this->kex_algorithms);
  1283. if ($kex_algorithm === false) {
  1284. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1285. throw new NoSupportedAlgorithmsException('No compatible key exchange algorithms found');
  1286. }
  1287. // Only relevant in diffie-hellman-group-exchange-sha{1,256}, otherwise empty.
  1288. $exchange_hash_rfc4419 = '';
  1289. if ($kex_algorithm === 'curve25519-sha256@libssh.org') {
  1290. $x = Random::string(32);
  1291. $eBytes = \Sodium\crypto_box_publickey_from_secretkey($x);
  1292. $clientKexInitMessage = NET_SSH2_MSG_KEX_ECDH_INIT;
  1293. $serverKexReplyMessage = NET_SSH2_MSG_KEX_ECDH_REPLY;
  1294. $kexHash = new Hash('sha256');
  1295. } else {
  1296. if (strpos($kex_algorithm, 'diffie-hellman-group-exchange') === 0) {
  1297. $dh_group_sizes_packed = pack(
  1298. 'NNN',
  1299. $this->kex_dh_group_size_min,
  1300. $this->kex_dh_group_size_preferred,
  1301. $this->kex_dh_group_size_max
  1302. );
  1303. $packet = pack(
  1304. 'Ca*',
  1305. NET_SSH2_MSG_KEXDH_GEX_REQUEST,
  1306. $dh_group_sizes_packed
  1307. );
  1308. if (!$this->send_binary_packet($packet)) {
  1309. return false;
  1310. }
  1311. $response = $this->get_binary_packet();
  1312. if ($response === false) {
  1313. user_error('Connection closed by server');
  1314. return false;
  1315. }
  1316. extract(unpack('Ctype', Strings::shift($response, 1)));
  1317. if ($type != NET_SSH2_MSG_KEXDH_GEX_GROUP) {
  1318. user_error('Expected SSH_MSG_KEX_DH_GEX_GROUP');
  1319. return false;
  1320. }
  1321. if (strlen($response) < 4) {
  1322. return false;
  1323. }
  1324. extract(unpack('NprimeLength', Strings::shift($response, 4)));
  1325. $primeBytes = Strings::shift($response, $primeLength);
  1326. $prime = new BigInteger($primeBytes, -256);
  1327. if (strlen($response) < 4) {
  1328. return false;
  1329. }
  1330. extract(unpack('NgLength', Strings::shift($response, 4)));
  1331. $gBytes = Strings::shift($response, $gLength);
  1332. $g = new BigInteger($gBytes, -256);
  1333. $exchange_hash_rfc4419 = pack(
  1334. 'a*Na*Na*',
  1335. $dh_group_sizes_packed,
  1336. $primeLength,
  1337. $primeBytes,
  1338. $gLength,
  1339. $gBytes
  1340. );
  1341. $clientKexInitMessage = NET_SSH2_MSG_KEXDH_GEX_INIT;
  1342. $serverKexReplyMessage = NET_SSH2_MSG_KEXDH_GEX_REPLY;
  1343. } else {
  1344. switch ($kex_algorithm) {
  1345. // see http://tools.ietf.org/html/rfc2409#section-6.2 and
  1346. // http://tools.ietf.org/html/rfc2412, appendex E
  1347. case 'diffie-hellman-group1-sha1':
  1348. $prime = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' .
  1349. '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' .
  1350. '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' .
  1351. 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF';
  1352. break;
  1353. // see http://tools.ietf.org/html/rfc3526#section-3
  1354. case 'diffie-hellman-group14-sha1':
  1355. $prime = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' .
  1356. '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' .
  1357. '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' .
  1358. 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05' .
  1359. '98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB' .
  1360. '9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' .
  1361. 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' .
  1362. '3995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF';
  1363. break;
  1364. }
  1365. // For both diffie-hellman-group1-sha1 and diffie-hellman-group14-sha1
  1366. // the generator field element is 2 (decimal) and the hash function is sha1.
  1367. $g = new BigInteger(2);
  1368. $prime = new BigInteger($prime, 16);
  1369. $clientKexInitMessage = NET_SSH2_MSG_KEXDH_INIT;
  1370. $serverKexReplyMessage = NET_SSH2_MSG_KEXDH_REPLY;
  1371. }
  1372. switch ($kex_algorithm) {
  1373. case 'diffie-hellman-group-exchange-sha256':
  1374. $kexHash = new Hash('sha256');
  1375. break;
  1376. default:
  1377. $kexHash = new Hash('sha1');
  1378. }
  1379. /* To increase the speed of the key exchange, both client and server may
  1380. reduce the size of their private exponents. It should be at least
  1381. twice as long as the key material that is generated from the shared
  1382. secret. For more details, see the paper by van Oorschot and Wiener
  1383. [VAN-OORSCHOT].
  1384. -- http://tools.ietf.org/html/rfc4419#section-6.2 */
  1385. $one = new BigInteger(1);
  1386. $keyLength = min($kexHash->getLengthInBytes(), max($encryptKeyLength, $decryptKeyLength));
  1387. $max = $one->bitwise_leftShift(16 * $keyLength); // 2 * 8 * $keyLength
  1388. $max = $max->subtract($one);
  1389. $x = BigInteger::randomRange($one, $max);
  1390. $e = $g->modPow($x, $prime);
  1391. $eBytes = $e->toBytes(true);
  1392. }
  1393. $data = pack('CNa*', $clientKexInitMessage, strlen($eBytes), $eBytes);
  1394. if (!$this->send_binary_packet($data)) {
  1395. throw new \RuntimeException('Connection closed by server');
  1396. }
  1397. $response = $this->get_binary_packet();
  1398. if ($response === false) {
  1399. throw new \RuntimeException('Connection closed by server');
  1400. }
  1401. if (!strlen($response)) {
  1402. return false;
  1403. }
  1404. extract(unpack('Ctype', Strings::shift($response, 1)));
  1405. if ($type != $serverKexReplyMessage) {
  1406. throw new \UnexpectedValueException('Expected SSH_MSG_KEXDH_REPLY');
  1407. }
  1408. if (strlen($response) < 4) {
  1409. return false;
  1410. }
  1411. $temp = unpack('Nlength', Strings::shift($response, 4));
  1412. $this->server_public_host_key = $server_public_host_key = Strings::shift($response, $temp['length']);
  1413. if (strlen($server_public_host_key) < 4) {
  1414. return false;
  1415. }
  1416. $temp = unpack('Nlength', Strings::shift($server_public_host_key, 4));
  1417. $public_key_format = Strings::shift($server_public_host_key, $temp['length']);
  1418. if (strlen($response) < 4) {
  1419. return false;
  1420. }
  1421. $temp = unpack('Nlength', Strings::shift($response, 4));
  1422. $fBytes = Strings::shift($response, $temp['length']);
  1423. if (strlen($response) < 4) {
  1424. return false;
  1425. }
  1426. $temp = unpack('Nlength', Strings::shift($response, 4));
  1427. $this->signature = Strings::shift($response, $temp['length']);
  1428. if (strlen($this->signature) < 4) {
  1429. return false;
  1430. }
  1431. $temp = unpack('Nlength', Strings::shift($this->signature, 4));
  1432. $this->signature_format = Strings::shift($this->signature, $temp['length']);
  1433. if ($kex_algorithm === 'curve25519-sha256@libssh.org') {
  1434. if (strlen($fBytes) !== 32) {
  1435. user_error('Received curve25519 public key of invalid length.');
  1436. return false;
  1437. }
  1438. $key = new BigInteger(\Sodium\crypto_scalarmult($x, $fBytes), 256);
  1439. \Sodium\memzero($x);
  1440. } else {
  1441. $f = new BigInteger($fBytes, -256);
  1442. $key = $f->modPow($x, $prime);
  1443. }
  1444. $keyBytes = $key->toBytes(true);
  1445. $this->exchange_hash = pack(
  1446. 'Na*Na*Na*Na*Na*a*Na*Na*Na*',
  1447. strlen($this->identifier),
  1448. $this->identifier,
  1449. strlen($this->server_identifier),
  1450. $this->server_identifier,
  1451. strlen($kexinit_payload_client),
  1452. $kexinit_payload_client,
  1453. strlen($kexinit_payload_server),
  1454. $kexinit_payload_server,
  1455. strlen($this->server_public_host_key),
  1456. $this->server_public_host_key,
  1457. $exchange_hash_rfc4419,
  1458. strlen($eBytes),
  1459. $eBytes,
  1460. strlen($fBytes),
  1461. $fBytes,
  1462. strlen($keyBytes),
  1463. $keyBytes
  1464. );
  1465. $this->exchange_hash = $kexHash->hash($this->exchange_hash);
  1466. if ($this->session_id === false) {
  1467. $this->session_id = $this->exchange_hash;
  1468. }
  1469. $server_host_key_algorithm = $this->array_intersect_first($server_host_key_algorithms, $this->server_host_key_algorithms);
  1470. if ($server_host_key_algorithm === false) {
  1471. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1472. throw new NoSupportedAlgorithmsException('No compatible server host key algorithms found');
  1473. }
  1474. if ($public_key_format != $server_host_key_algorithm || $this->signature_format != $server_host_key_algorithm) {
  1475. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1476. throw new \RuntimeException('Server Host Key Algorithm Mismatch');
  1477. }
  1478. $packet = pack(
  1479. 'C',
  1480. NET_SSH2_MSG_NEWKEYS
  1481. );
  1482. if (!$this->send_binary_packet($packet)) {
  1483. return false;
  1484. }
  1485. $response = $this->get_binary_packet();
  1486. if ($response === false) {
  1487. throw new \RuntimeException('Connection closed by server');
  1488. }
  1489. if (!strlen($response)) {
  1490. return false;
  1491. }
  1492. extract(unpack('Ctype', Strings::shift($response, 1)));
  1493. if ($type != NET_SSH2_MSG_NEWKEYS) {
  1494. throw new \UnexpectedValueException('Expected SSH_MSG_NEWKEYS');
  1495. }
  1496. $keyBytes = pack('Na*', strlen($keyBytes), $keyBytes);
  1497. $this->encrypt = $this->encryption_algorithm_to_crypt_instance($encrypt);
  1498. if ($this->encrypt) {
  1499. if ($this->crypto_engine) {
  1500. $this->encrypt->setEngine($this->crypto_engine);
  1501. }
  1502. if ($this->encrypt->getBlockLengthInBytes()) {
  1503. $this->encrypt_block_size = $this->encrypt->getBlockLengthInBytes();
  1504. }
  1505. $this->encrypt->enableContinuousBuffer();
  1506. $this->encrypt->disablePadding();
  1507. if ($this->encrypt->usesIV()) {
  1508. $iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'A' . $this->session_id);
  1509. while ($this->encrypt_block_size > strlen($iv)) {
  1510. $iv.= $kexHash->hash($keyBytes . $this->exchange_hash . $iv);
  1511. }
  1512. $this->encrypt->setIV(substr($iv, 0, $this->encrypt_block_size));
  1513. }
  1514. $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'C' . $this->session_id);
  1515. while ($encryptKeyLength > strlen($key)) {
  1516. $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
  1517. }
  1518. $this->encrypt->setKey(substr($key, 0, $encryptKeyLength));
  1519. }
  1520. $this->decrypt = $this->encryption_algorithm_to_crypt_instance($decrypt);
  1521. if ($this->decrypt) {
  1522. if ($this->crypto_engine) {
  1523. $this->decrypt->setEngine($this->crypto_engine);
  1524. }
  1525. if ($this->decrypt->getBlockLengthInBytes()) {
  1526. $this->decrypt_block_size = $this->decrypt->getBlockLengthInBytes();
  1527. }
  1528. $this->decrypt->enableContinuousBuffer();
  1529. $this->decrypt->disablePadding();
  1530. if ($this->decrypt->usesIV()) {
  1531. $iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'B' . $this->session_id);
  1532. while ($this->decrypt_block_size > strlen($iv)) {
  1533. $iv.= $kexHash->hash($keyBytes . $this->exchange_hash . $iv);
  1534. }
  1535. $this->decrypt->setIV(substr($iv, 0, $this->decrypt_block_size));
  1536. }
  1537. $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'D' . $this->session_id);
  1538. while ($decryptKeyLength > strlen($key)) {
  1539. $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
  1540. }
  1541. $this->decrypt->setKey(substr($key, 0, $decryptKeyLength));
  1542. }
  1543. /* The "arcfour128" algorithm is the RC4 cipher, as described in
  1544. [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream
  1545. generated by the cipher MUST be discarded, and the first byte of the
  1546. first encrypted packet MUST be encrypted using the 1537th byte of
  1547. keystream.
  1548. -- http://tools.ietf.org/html/rfc4345#section-4 */
  1549. if ($encrypt == 'arcfour128' || $encrypt == 'arcfour256') {
  1550. $this->encrypt->encrypt(str_repeat("\0", 1536));
  1551. }
  1552. if ($decrypt == 'arcfour128' || $decrypt == 'arcfour256') {
  1553. $this->decrypt->decrypt(str_repeat("\0", 1536));
  1554. }
  1555. $mac_algorithm = $this->array_intersect_first($mac_algorithms, $this->mac_algorithms_client_to_server);
  1556. if ($mac_algorithm === false) {
  1557. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1558. throw new NoSupportedAlgorithmsException('No compatible client to server message authentication algorithms found');
  1559. }
  1560. $createKeyLength = 0; // ie. $mac_algorithm == 'none'
  1561. switch ($mac_algorithm) {
  1562. case 'hmac-sha2-256':
  1563. $this->hmac_create = new Hash('sha256');
  1564. $createKeyLength = 32;
  1565. break;
  1566. case 'hmac-sha1':
  1567. $this->hmac_create = new Hash('sha1');
  1568. $createKeyLength = 20;
  1569. break;
  1570. case 'hmac-sha1-96':
  1571. $this->hmac_create = new Hash('sha1-96');
  1572. $createKeyLength = 20;
  1573. break;
  1574. case 'hmac-md5':
  1575. $this->hmac_create = new Hash('md5');
  1576. $createKeyLength = 16;
  1577. break;
  1578. case 'hmac-md5-96':
  1579. $this->hmac_create = new Hash('md5-96');
  1580. $createKeyLength = 16;
  1581. }
  1582. $mac_algorithm = $this->array_intersect_first($mac_algorithms, $this->mac_algorithms_server_to_client);
  1583. if ($mac_algorithm === false) {
  1584. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1585. throw new NoSupportedAlgorithmsException('No compatible server to client message authentication algorithms found');
  1586. }
  1587. $checkKeyLength = 0;
  1588. $this->hmac_size = 0;
  1589. switch ($mac_algorithm) {
  1590. case 'hmac-sha2-256':
  1591. $this->hmac_check = new Hash('sha256');
  1592. $checkKeyLength = 32;
  1593. $this->hmac_size = 32;
  1594. break;
  1595. case 'hmac-sha1':
  1596. $this->hmac_check = new Hash('sha1');
  1597. $checkKeyLength = 20;
  1598. $this->hmac_size = 20;
  1599. break;
  1600. case 'hmac-sha1-96':
  1601. $this->hmac_check = new Hash('sha1-96');
  1602. $checkKeyLength = 20;
  1603. $this->hmac_size = 12;
  1604. break;
  1605. case 'hmac-md5':
  1606. $this->hmac_check = new Hash('md5');
  1607. $checkKeyLength = 16;
  1608. $this->hmac_size = 16;
  1609. break;
  1610. case 'hmac-md5-96':
  1611. $this->hmac_check = new Hash('md5-96');
  1612. $checkKeyLength = 16;
  1613. $this->hmac_size = 12;
  1614. }
  1615. $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'E' . $this->session_id);
  1616. while ($createKeyLength > strlen($key)) {
  1617. $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
  1618. }
  1619. $this->hmac_create->setKey(substr($key, 0, $createKeyLength));
  1620. $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'F' . $this->session_id);
  1621. while ($checkKeyLength > strlen($key)) {
  1622. $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
  1623. }
  1624. $this->hmac_check->setKey(substr($key, 0, $checkKeyLength));
  1625. $compression_algorithm = $this->array_intersect_first($compression_algorithms, $this->compression_algorithms_server_to_client);
  1626. if ($compression_algorithm === false) {
  1627. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1628. throw new NoSupportedAlgorithmsException('No compatible server to client compression algorithms found');
  1629. }
  1630. $this->decompress = $compression_algorithm == 'zlib';
  1631. $compression_algorithm = $this->array_intersect_first($compression_algorithms, $this->compression_algorithms_client_to_server);
  1632. if ($compression_algorithm === false) {
  1633. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  1634. throw new NoSupportedAlgorithmsException('No compatible client to server compression algorithms found');
  1635. }
  1636. $this->compress = $compression_algorithm == 'zlib';
  1637. return true;
  1638. }
  1639. /**
  1640. * Maps an encryption algorithm name to the number of key bytes.
  1641. *
  1642. * @param string $algorithm Name of the encryption algorithm
  1643. * @return int|null Number of bytes as an integer or null for unknown
  1644. * @access private
  1645. */
  1646. private function encryption_algorithm_to_key_size($algorithm)
  1647. {
  1648. switch ($algorithm) {
  1649. case 'none':
  1650. return 0;
  1651. case 'aes128-cbc':
  1652. case 'aes128-ctr':
  1653. case 'arcfour':
  1654. case 'arcfour128':
  1655. case 'blowfish-cbc':
  1656. case 'blowfish-ctr':
  1657. case 'twofish128-cbc':
  1658. case 'twofish128-ctr':
  1659. return 16;
  1660. case '3des-cbc':
  1661. case '3des-ctr':
  1662. case 'aes192-cbc':
  1663. case 'aes192-ctr':
  1664. case 'twofish192-cbc':
  1665. case 'twofish192-ctr':
  1666. return 24;
  1667. case 'aes256-cbc':
  1668. case 'aes256-ctr':
  1669. case 'arcfour256':
  1670. case 'twofish-cbc':
  1671. case 'twofish256-cbc':
  1672. case 'twofish256-ctr':
  1673. return 32;
  1674. }
  1675. return null;
  1676. }
  1677. /**
  1678. * Maps an encryption algorithm name to an instance of a subclass of
  1679. * \phpseclib\Crypt\Base.
  1680. *
  1681. * @param string $algorithm Name of the encryption algorithm
  1682. * @return mixed Instance of \phpseclib\Crypt\Base or null for unknown
  1683. * @access private
  1684. */
  1685. private function encryption_algorithm_to_crypt_instance($algorithm)
  1686. {
  1687. switch ($algorithm) {
  1688. case '3des-cbc':
  1689. return new TripleDES(BlockCipher::MODE_CBC);
  1690. case '3des-ctr':
  1691. return new TripleDES(BlockCipher::MODE_CTR);
  1692. case 'aes256-cbc':
  1693. case 'aes192-cbc':
  1694. case 'aes128-cbc':
  1695. return new Rijndael(BlockCipher::MODE_CBC);
  1696. case 'aes256-ctr':
  1697. case 'aes192-ctr':
  1698. case 'aes128-ctr':
  1699. return new Rijndael(BlockCipher::MODE_CTR);
  1700. case 'blowfish-cbc':
  1701. return new Blowfish(BlockCipher::MODE_CBC);
  1702. case 'blowfish-ctr':
  1703. return new Blowfish(BlockCipher::MODE_CTR);
  1704. case 'twofish128-cbc':
  1705. case 'twofish192-cbc':
  1706. case 'twofish256-cbc':
  1707. case 'twofish-cbc':
  1708. return new Twofish(BlockCipher::MODE_CBC);
  1709. case 'twofish128-ctr':
  1710. case 'twofish192-ctr':
  1711. case 'twofish256-ctr':
  1712. return new Twofish(BlockCipher::MODE_CTR);
  1713. case 'arcfour':
  1714. case 'arcfour128':
  1715. case 'arcfour256':
  1716. return new RC4();
  1717. }
  1718. return null;
  1719. }
  1720. /**
  1721. * Login
  1722. *
  1723. * The $password parameter can be a plaintext password, a \phpseclib\Crypt\RSA object or an array
  1724. *
  1725. * @param string $username
  1726. * @param mixed $password
  1727. * @param mixed $...
  1728. * @return bool
  1729. * @see self::_login()
  1730. * @access public
  1731. */
  1732. public function login($username)
  1733. {
  1734. $args = func_get_args();
  1735. return call_user_func_array([&$this, 'sublogin'], $args);
  1736. }
  1737. /**
  1738. * Login Helper
  1739. *
  1740. * @param string $username
  1741. * @param mixed $password
  1742. * @param mixed $...
  1743. * @return bool
  1744. * @see self::_login_helper()
  1745. * @access private
  1746. */
  1747. protected function sublogin($username)
  1748. {
  1749. if (!($this->bitmap & self::MASK_CONSTRUCTOR)) {
  1750. if (!$this->connect()) {
  1751. return false;
  1752. }
  1753. }
  1754. $args = array_slice(func_get_args(), 1);
  1755. if (empty($args)) {
  1756. return $this->login_helper($username);
  1757. }
  1758. foreach ($args as $arg) {
  1759. if ($this->login_helper($username, $arg)) {
  1760. return true;
  1761. }
  1762. }
  1763. return false;
  1764. }
  1765. /**
  1766. * Login Helper
  1767. *
  1768. * @param string $username
  1769. * @param string $password
  1770. * @return bool
  1771. * @throws \UnexpectedValueException on receipt of unexpected packets
  1772. * @throws \RuntimeException on other errors
  1773. * @access private
  1774. * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis}
  1775. * by sending dummy SSH_MSG_IGNORE messages.
  1776. */
  1777. private function login_helper($username, $password = null)
  1778. {
  1779. if (!($this->bitmap & self::MASK_CONNECTED)) {
  1780. return false;
  1781. }
  1782. if (!($this->bitmap & self::MASK_LOGIN_REQ)) {
  1783. $packet = pack(
  1784. 'CNa*',
  1785. NET_SSH2_MSG_SERVICE_REQUEST,
  1786. strlen('ssh-userauth'),
  1787. 'ssh-userauth'
  1788. );
  1789. if (!$this->send_binary_packet($packet)) {
  1790. return false;
  1791. }
  1792. $response = $this->get_binary_packet();
  1793. if ($response === false) {
  1794. throw new \RuntimeException('Connection closed by server');
  1795. }
  1796. if (strlen($response) < 4) {
  1797. return false;
  1798. }
  1799. extract(unpack('Ctype', Strings::shift($response, 1)));
  1800. if ($type != NET_SSH2_MSG_SERVICE_ACCEPT) {
  1801. throw new \UnexpectedValueException('Expected SSH_MSG_SERVICE_ACCEPT');
  1802. }
  1803. $this->bitmap |= self::MASK_LOGIN_REQ;
  1804. }
  1805. if (strlen($this->last_interactive_response)) {
  1806. return !is_string($password) && !is_array($password) ? false : $this->keyboard_interactive_process($password);
  1807. }
  1808. if ($password instanceof RSA) {
  1809. return $this->privatekey_login($username, $password);
  1810. } elseif ($password instanceof Agent) {
  1811. return $this->ssh_agent_login($username, $password);
  1812. }
  1813. if (is_array($password)) {
  1814. if ($this->keyboard_interactive_login($username, $password)) {
  1815. $this->bitmap |= self::MASK_LOGIN;
  1816. return true;
  1817. }
  1818. return false;
  1819. }
  1820. if (!isset($password)) {
  1821. $packet = pack(
  1822. 'CNa*Na*Na*',
  1823. NET_SSH2_MSG_USERAUTH_REQUEST,
  1824. strlen($username),
  1825. $username,
  1826. strlen('ssh-connection'),
  1827. 'ssh-connection',
  1828. strlen('none'),
  1829. 'none'
  1830. );
  1831. if (!$this->send_binary_packet($packet)) {
  1832. return false;
  1833. }
  1834. $response = $this->get_binary_packet();
  1835. if ($response === false) {
  1836. throw new \RuntimeException('Connection closed by server');
  1837. }
  1838. if (!strlen($response)) {
  1839. return false;
  1840. }
  1841. extract(unpack('Ctype', Strings::shift($response, 1)));
  1842. switch ($type) {
  1843. case NET_SSH2_MSG_USERAUTH_SUCCESS:
  1844. $this->bitmap |= self::MASK_LOGIN;
  1845. return true;
  1846. //case NET_SSH2_MSG_USERAUTH_FAILURE:
  1847. default:
  1848. return false;
  1849. }
  1850. }
  1851. $packet = pack(
  1852. 'CNa*Na*Na*CNa*',
  1853. NET_SSH2_MSG_USERAUTH_REQUEST,
  1854. strlen($username),
  1855. $username,
  1856. strlen('ssh-connection'),
  1857. 'ssh-connection',
  1858. strlen('password'),
  1859. 'password',
  1860. 0,
  1861. strlen($password),
  1862. $password
  1863. );
  1864. // remove the username and password from the logged packet
  1865. if (!defined('NET_SSH2_LOGGING')) {
  1866. $logged = null;
  1867. } else {
  1868. $logged = pack(
  1869. 'CNa*Na*Na*CNa*',
  1870. NET_SSH2_MSG_USERAUTH_REQUEST,
  1871. strlen('username'),
  1872. 'username',
  1873. strlen('ssh-connection'),
  1874. 'ssh-connection',
  1875. strlen('password'),
  1876. 'password',
  1877. 0,
  1878. strlen('password'),
  1879. 'password'
  1880. );
  1881. }
  1882. if (!$this->send_binary_packet($packet, $logged)) {
  1883. return false;
  1884. }
  1885. $response = $this->get_binary_packet();
  1886. if ($response === false) {
  1887. throw new \RuntimeException('Connection closed by server');
  1888. }
  1889. if (!strlen($response)) {
  1890. return false;
  1891. }
  1892. extract(unpack('Ctype', Strings::shift($response, 1)));
  1893. switch ($type) {
  1894. case NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: // in theory, the password can be changed
  1895. if (defined('NET_SSH2_LOGGING')) {
  1896. $this->message_number_log[count($this->message_number_log) - 1] = 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ';
  1897. }
  1898. if (strlen($response) < 4) {
  1899. return false;
  1900. }
  1901. extract(unpack('Nlength', Strings::shift($response, 4)));
  1902. $this->errors[] = 'SSH_MSG_USERAUTH_PASSWD_CHANGEREQ: ' . utf8_decode(Strings::shift($response, $length));
  1903. return $this->disconnect_helper(NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
  1904. case NET_SSH2_MSG_USERAUTH_FAILURE:
  1905. // can we use keyboard-interactive authentication? if not then either the login is bad or the server employees
  1906. // multi-factor authentication
  1907. if (strlen($response) < 4) {
  1908. return false;
  1909. }
  1910. extract(unpack('Nlength', Strings::shift($response, 4)));
  1911. $auth_methods = explode(',', Strings::shift($response, $length));
  1912. if (!strlen($response)) {
  1913. return false;
  1914. }
  1915. extract(unpack('Cpartial_success', Strings::shift($response, 1)));
  1916. $partial_success = $partial_success != 0;
  1917. if (!$partial_success && in_array('keyboard-interactive', $auth_methods)) {
  1918. if ($this->keyboard_interactive_login($username, $password)) {
  1919. $this->bitmap |= self::MASK_LOGIN;
  1920. return true;
  1921. }
  1922. return false;
  1923. }
  1924. return false;
  1925. case NET_SSH2_MSG_USERAUTH_SUCCESS:
  1926. $this->bitmap |= self::MASK_LOGIN;
  1927. return true;
  1928. }
  1929. return false;
  1930. }
  1931. /**
  1932. * Login via keyboard-interactive authentication
  1933. *
  1934. * See {@link http://tools.ietf.org/html/rfc4256 RFC4256} for details. This is not a full-featured keyboard-interactive authenticator.
  1935. *
  1936. * @param string $username
  1937. * @param string $password
  1938. * @return bool
  1939. * @access private
  1940. */
  1941. private function keyboard_interactive_login($username, $password)
  1942. {
  1943. $packet = pack(
  1944. 'CNa*Na*Na*Na*Na*',
  1945. NET_SSH2_MSG_USERAUTH_REQUEST,
  1946. strlen($username),
  1947. $username,
  1948. strlen('ssh-connection'),
  1949. 'ssh-connection',
  1950. strlen('keyboard-interactive'),
  1951. 'keyboard-interactive',
  1952. 0,
  1953. '',
  1954. 0,
  1955. ''
  1956. );
  1957. if (!$this->send_binary_packet($packet)) {
  1958. return false;
  1959. }
  1960. return $this->keyboard_interactive_process($password);
  1961. }
  1962. /**
  1963. * Handle the keyboard-interactive requests / responses.
  1964. *
  1965. * @param string $responses...
  1966. * @return bool
  1967. * @throws \RuntimeException on connection error
  1968. * @access private
  1969. */
  1970. private function keyboard_interactive_process()
  1971. {
  1972. $responses = func_get_args();
  1973. if (strlen($this->last_interactive_response)) {
  1974. $response = $this->last_interactive_response;
  1975. } else {
  1976. $orig = $response = $this->get_binary_packet();
  1977. if ($response === false) {
  1978. throw new \RuntimeException('Connection closed by server');
  1979. }
  1980. }
  1981. if (!strlen($response)) {
  1982. return false;
  1983. }
  1984. extract(unpack('Ctype', Strings::shift($response, 1)));
  1985. switch ($type) {
  1986. case NET_SSH2_MSG_USERAUTH_INFO_REQUEST:
  1987. if (strlen($response) < 4) {
  1988. return false;
  1989. }
  1990. extract(unpack('Nlength', Strings::shift($response, 4)));
  1991. Strings::shift($response, $length); // name; may be empty
  1992. if (strlen($response) < 4) {
  1993. return false;
  1994. }
  1995. extract(unpack('Nlength', Strings::shift($response, 4)));
  1996. Strings::shift($response, $length); // instruction; may be empty
  1997. if (strlen($response) < 4) {
  1998. return false;
  1999. }
  2000. extract(unpack('Nlength', Strings::shift($response, 4)));
  2001. Strings::shift($response, $length); // language tag; may be empty
  2002. if (strlen($response) < 4) {
  2003. return false;
  2004. }
  2005. extract(unpack('Nnum_prompts', Strings::shift($response, 4)));
  2006. for ($i = 0; $i < count($responses); $i++) {
  2007. if (is_array($responses[$i])) {
  2008. foreach ($responses[$i] as $key => $value) {
  2009. $this->keyboard_requests_responses[$key] = $value;
  2010. }
  2011. unset($responses[$i]);
  2012. }
  2013. }
  2014. $responses = array_values($responses);
  2015. if (isset($this->keyboard_requests_responses)) {
  2016. for ($i = 0; $i < $num_prompts; $i++) {
  2017. if (strlen($response) < 4) {
  2018. return false;
  2019. }
  2020. extract(unpack('Nlength', Strings::shift($response, 4)));
  2021. // prompt - ie. "Password: "; must not be empty
  2022. $prompt = Strings::shift($response, $length);
  2023. //$echo = Strings::shift($response) != chr(0);
  2024. foreach ($this->keyboard_requests_responses as $key => $value) {
  2025. if (substr($prompt, 0, strlen($key)) == $key) {
  2026. $responses[] = $value;
  2027. break;
  2028. }
  2029. }
  2030. }
  2031. }
  2032. // see http://tools.ietf.org/html/rfc4256#section-3.2
  2033. if (strlen($this->last_interactive_response)) {
  2034. $this->last_interactive_response = '';
  2035. } elseif (defined('NET_SSH2_LOGGING')) {
  2036. $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
  2037. 'UNKNOWN',
  2038. 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST',
  2039. $this->message_number_log[count($this->message_number_log) - 1]
  2040. );
  2041. }
  2042. if (!count($responses) && $num_prompts) {
  2043. $this->last_interactive_response = $orig;
  2044. return false;
  2045. }
  2046. /*
  2047. After obtaining the requested information from the user, the client
  2048. MUST respond with an SSH_MSG_USERAUTH_INFO_RESPONSE message.
  2049. */
  2050. // see http://tools.ietf.org/html/rfc4256#section-3.4
  2051. $packet = $logged = pack('CN', NET_SSH2_MSG_USERAUTH_INFO_RESPONSE, count($responses));
  2052. for ($i = 0; $i < count($responses); $i++) {
  2053. $packet.= pack('Na*', strlen($responses[$i]), $responses[$i]);
  2054. $logged.= pack('Na*', strlen('dummy-answer'), 'dummy-answer');
  2055. }
  2056. if (!$this->send_binary_packet($packet, $logged)) {
  2057. return false;
  2058. }
  2059. if (defined('NET_SSH2_LOGGING') && NET_SSH2_LOGGING == self::LOG_COMPLEX) {
  2060. $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
  2061. 'UNKNOWN',
  2062. 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE',
  2063. $this->message_number_log[count($this->message_number_log) - 1]
  2064. );
  2065. }
  2066. /*
  2067. After receiving the response, the server MUST send either an
  2068. SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE, or another
  2069. SSH_MSG_USERAUTH_INFO_REQUEST message.
  2070. */
  2071. // maybe phpseclib should force close the connection after x request / responses? unless something like that is done
  2072. // there could be an infinite loop of request / responses.
  2073. return $this->keyboard_interactive_process();
  2074. case NET_SSH2_MSG_USERAUTH_SUCCESS:
  2075. return true;
  2076. case NET_SSH2_MSG_USERAUTH_FAILURE:
  2077. return false;
  2078. }
  2079. return false;
  2080. }
  2081. /**
  2082. * Login with an ssh-agent provided key
  2083. *
  2084. * @param string $username
  2085. * @param \phpseclib\System\SSH\Agent $agent
  2086. * @return bool
  2087. * @access private
  2088. */
  2089. private function ssh_agent_login($username, $agent)
  2090. {
  2091. $this->agent = $agent;
  2092. $keys = $agent->requestIdentities();
  2093. foreach ($keys as $key) {
  2094. if ($this->privatekey_login($username, $key)) {
  2095. return true;
  2096. }
  2097. }
  2098. return false;
  2099. }
  2100. /**
  2101. * Login with an RSA private key
  2102. *
  2103. * @param string $username
  2104. * @param \phpseclib\Crypt\RSA $password
  2105. * @return bool
  2106. * @throws \RuntimeException on connection error
  2107. * @access private
  2108. * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis}
  2109. * by sending dummy SSH_MSG_IGNORE messages.
  2110. */
  2111. private function privatekey_login($username, $privatekey)
  2112. {
  2113. // see http://tools.ietf.org/html/rfc4253#page-15
  2114. $publickey = $privatekey->getPublicKey('Raw');
  2115. if ($publickey === false) {
  2116. return false;
  2117. }
  2118. $publickey = [
  2119. 'e' => $publickey['e']->toBytes(true),
  2120. 'n' => $publickey['n']->toBytes(true)
  2121. ];
  2122. $publickey = pack(
  2123. 'Na*Na*Na*',
  2124. strlen('ssh-rsa'),
  2125. 'ssh-rsa',
  2126. strlen($publickey['e']),
  2127. $publickey['e'],
  2128. strlen($publickey['n']),
  2129. $publickey['n']
  2130. );
  2131. $part1 = pack(
  2132. 'CNa*Na*Na*',
  2133. NET_SSH2_MSG_USERAUTH_REQUEST,
  2134. strlen($username),
  2135. $username,
  2136. strlen('ssh-connection'),
  2137. 'ssh-connection',
  2138. strlen('publickey'),
  2139. 'publickey'
  2140. );
  2141. $part2 = pack('Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publickey), $publickey);
  2142. $packet = $part1 . chr(0) . $part2;
  2143. if (!$this->send_binary_packet($packet)) {
  2144. return false;
  2145. }
  2146. $response = $this->get_binary_packet();
  2147. if ($response === false) {
  2148. throw new \RuntimeException('Connection closed by server');
  2149. }
  2150. if (!strlen($response)) {
  2151. return false;
  2152. }
  2153. extract(unpack('Ctype', Strings::shift($response, 1)));
  2154. switch ($type) {
  2155. case NET_SSH2_MSG_USERAUTH_FAILURE:
  2156. if (strlen($response) < 4) {
  2157. return false;
  2158. }
  2159. extract(unpack('Nlength', Strings::shift($response, 4)));
  2160. $this->errors[] = 'SSH_MSG_USERAUTH_FAILURE: ' . Strings::shift($response, $length);
  2161. return false;
  2162. case NET_SSH2_MSG_USERAUTH_PK_OK:
  2163. // we'll just take it on faith that the public key blob and the public key algorithm name are as
  2164. // they should be
  2165. if (defined('NET_SSH2_LOGGING') && NET_SSH2_LOGGING == self::LOG_COMPLEX) {
  2166. $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
  2167. 'UNKNOWN',
  2168. 'NET_SSH2_MSG_USERAUTH_PK_OK',
  2169. $this->message_number_log[count($this->message_number_log) - 1]
  2170. );
  2171. }
  2172. }
  2173. $packet = $part1 . chr(1) . $part2;
  2174. $privatekey->setHash('sha1');
  2175. $signature = $privatekey->sign(pack('Na*a*', strlen($this->session_id), $this->session_id, $packet), RSA::PADDING_PKCS1);
  2176. $signature = pack('Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($signature), $signature);
  2177. $packet.= pack('Na*', strlen($signature), $signature);
  2178. if (!$this->send_binary_packet($packet)) {
  2179. return false;
  2180. }
  2181. $response = $this->get_binary_packet();
  2182. if ($response === false) {
  2183. throw new \RuntimeException('Connection closed by server');
  2184. }
  2185. if (!strlen($response)) {
  2186. return false;
  2187. }
  2188. extract(unpack('Ctype', Strings::shift($response, 1)));
  2189. switch ($type) {
  2190. case NET_SSH2_MSG_USERAUTH_FAILURE:
  2191. // either the login is bad or the server employs multi-factor authentication
  2192. return false;
  2193. case NET_SSH2_MSG_USERAUTH_SUCCESS:
  2194. $this->bitmap |= self::MASK_LOGIN;
  2195. return true;
  2196. }
  2197. return false;
  2198. }
  2199. /**
  2200. * Set Timeout
  2201. *
  2202. * $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.
  2203. * Setting $timeout to false or 0 will mean there is no timeout.
  2204. *
  2205. * @param mixed $timeout
  2206. * @access public
  2207. */
  2208. public function setTimeout($timeout)
  2209. {
  2210. $this->timeout = $this->curTimeout = $timeout;
  2211. }
  2212. /**
  2213. * Get the output from stdError
  2214. *
  2215. * @access public
  2216. */
  2217. public function getStdError()
  2218. {
  2219. return $this->stdErrorLog;
  2220. }
  2221. /**
  2222. * Execute Command
  2223. *
  2224. * If $callback is set to false then \phpseclib\Net\SSH2::_get_channel_packet(self::CHANNEL_EXEC) will need to be called manually.
  2225. * In all likelihood, this is not a feature you want to be taking advantage of.
  2226. *
  2227. * @param string $command
  2228. * @param Callback $callback
  2229. * @return string
  2230. * @throws \RuntimeException on connection error
  2231. * @access public
  2232. */
  2233. public function exec($command, $callback = null)
  2234. {
  2235. $this->curTimeout = $this->timeout;
  2236. $this->is_timeout = false;
  2237. $this->stdErrorLog = '';
  2238. if (!$this->isAuthenticated()) {
  2239. return false;
  2240. }
  2241. if ($this->in_request_pty_exec) {
  2242. user_error('If you want to run multiple exec()\'s you will need to disable (and re-enable if appropriate) a PTY for each one.');
  2243. return false;
  2244. }
  2245. // RFC4254 defines the (client) window size as "bytes the other party can send before it must wait for the window to
  2246. // be adjusted". 0x7FFFFFFF is, at 2GB, the max size. technically, it should probably be decremented, but,
  2247. // honestly, if you're transferring more than 2GB, you probably shouldn't be using phpseclib, anyway.
  2248. // see http://tools.ietf.org/html/rfc4254#section-5.2 for more info
  2249. $this->window_size_server_to_client[self::CHANNEL_EXEC] = $this->window_size;
  2250. // 0x8000 is the maximum max packet size, per http://tools.ietf.org/html/rfc4253#section-6.1, although since PuTTy
  2251. // uses 0x4000, that's what will be used here, as well.
  2252. $packet_size = 0x4000;
  2253. $packet = pack(
  2254. 'CNa*N3',
  2255. NET_SSH2_MSG_CHANNEL_OPEN,
  2256. strlen('session'),
  2257. 'session',
  2258. self::CHANNEL_EXEC,
  2259. $this->window_size_server_to_client[self::CHANNEL_EXEC],
  2260. $packet_size
  2261. );
  2262. if (!$this->send_binary_packet($packet)) {
  2263. return false;
  2264. }
  2265. $this->channel_status[self::CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_OPEN;
  2266. $response = $this->get_channel_packet(self::CHANNEL_EXEC);
  2267. if ($response === false) {
  2268. return false;
  2269. }
  2270. if ($this->request_pty === true) {
  2271. $terminal_modes = pack('C', NET_SSH2_TTY_OP_END);
  2272. $packet = pack(
  2273. 'CNNa*CNa*N5a*',
  2274. NET_SSH2_MSG_CHANNEL_REQUEST,
  2275. $this->server_channels[self::CHANNEL_EXEC],
  2276. strlen('pty-req'),
  2277. 'pty-req',
  2278. 1,
  2279. strlen('vt100'),
  2280. 'vt100',
  2281. $this->windowColumns,
  2282. $this->windowRows,
  2283. 0,
  2284. 0,
  2285. strlen($terminal_modes),
  2286. $terminal_modes
  2287. );
  2288. if (!$this->send_binary_packet($packet)) {
  2289. return false;
  2290. }
  2291. $response = $this->get_binary_packet();
  2292. if ($response === false) {
  2293. throw new \RuntimeException('Connection closed by server');
  2294. }
  2295. if (!strlen($response)) {
  2296. return false;
  2297. }
  2298. list(, $type) = unpack('C', Strings::shift($response, 1));
  2299. switch ($type) {
  2300. case NET_SSH2_MSG_CHANNEL_SUCCESS:
  2301. break;
  2302. case NET_SSH2_MSG_CHANNEL_FAILURE:
  2303. default:
  2304. $this->disconnect_helper(NET_SSH2_DISCONNECT_BY_APPLICATION);
  2305. throw new \RuntimeException('Unable to request pseudo-terminal');
  2306. }
  2307. $this->in_request_pty_exec = true;
  2308. }
  2309. // sending a pty-req SSH_MSG_CHANNEL_REQUEST message is unnecessary and, in fact, in most cases, slows things
  2310. // down. the one place where it might be desirable is if you're doing something like \phpseclib\Net\SSH2::exec('ping localhost &').
  2311. // with a pty-req SSH_MSG_CHANNEL_REQUEST, exec() will return immediately and the ping process will then
  2312. // then immediately terminate. without such a request exec() will loop indefinitely. the ping process won't end but
  2313. // neither will your script.
  2314. // although, in theory, the size of SSH_MSG_CHANNEL_REQUEST could exceed the maximum packet size established by
  2315. // SSH_MSG_CHANNEL_OPEN_CONFIRMATION, RFC4254#section-5.1 states that the "maximum packet size" refers to the
  2316. // "maximum size of an individual data packet". ie. SSH_MSG_CHANNEL_DATA. RFC4254#section-5.2 corroborates.
  2317. $packet = pack(
  2318. 'CNNa*CNa*',
  2319. NET_SSH2_MSG_CHANNEL_REQUEST,
  2320. $this->server_channels[self::CHANNEL_EXEC],
  2321. strlen('exec'),
  2322. 'exec',
  2323. 1,
  2324. strlen($command),
  2325. $command
  2326. );
  2327. if (!$this->send_binary_packet($packet)) {
  2328. return false;
  2329. }
  2330. $this->channel_status[self::CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_REQUEST;
  2331. $response = $this->get_channel_packet(self::CHANNEL_EXEC);
  2332. if ($response === false) {
  2333. return false;
  2334. }
  2335. $this->channel_status[self::CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_DATA;
  2336. if ($callback === false || $this->in_request_pty_exec) {
  2337. return true;
  2338. }
  2339. $output = '';
  2340. while (true) {
  2341. $temp = $this->get_channel_packet(self::CHANNEL_EXEC);
  2342. switch (true) {
  2343. case $temp === true:
  2344. return is_callable($callback) ? true : $output;
  2345. case $temp === false:
  2346. return false;
  2347. default:
  2348. if (is_callable($callback)) {
  2349. if (call_user_func($callback, $temp) === true) {
  2350. $this->close_channel(self::CHANNEL_EXEC);
  2351. return true;
  2352. }
  2353. } else {
  2354. $output.= $temp;
  2355. }
  2356. }
  2357. }
  2358. }
  2359. /**
  2360. * Creates an interactive shell
  2361. *
  2362. * @see self::read()
  2363. * @see self::write()
  2364. * @return bool
  2365. * @throws \UnexpectedValueException on receipt of unexpected packets
  2366. * @throws \RuntimeException on other errors
  2367. * @access private
  2368. */
  2369. private function initShell()
  2370. {
  2371. if ($this->in_request_pty_exec === true) {
  2372. return true;
  2373. }
  2374. $this->window_size_server_to_client[self::CHANNEL_SHELL] = $this->window_size;
  2375. $packet_size = 0x4000;
  2376. $packet = pack(
  2377. 'CNa*N3',
  2378. NET_SSH2_MSG_CHANNEL_OPEN,
  2379. strlen('session'),
  2380. 'session',
  2381. self::CHANNEL_SHELL,
  2382. $this->window_size_server_to_client[self::CHANNEL_SHELL],
  2383. $packet_size
  2384. );
  2385. if (!$this->send_binary_packet($packet)) {
  2386. return false;
  2387. }
  2388. $this->channel_status[self::CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_OPEN;
  2389. $response = $this->get_channel_packet(self::CHANNEL_SHELL);
  2390. if ($response === false) {
  2391. return false;
  2392. }
  2393. $terminal_modes = pack('C', NET_SSH2_TTY_OP_END);
  2394. $packet = pack(
  2395. 'CNNa*CNa*N5a*',
  2396. NET_SSH2_MSG_CHANNEL_REQUEST,
  2397. $this->server_channels[self::CHANNEL_SHELL],
  2398. strlen('pty-req'),
  2399. 'pty-req',
  2400. 1,
  2401. strlen('vt100'),
  2402. 'vt100',
  2403. $this->windowColumns,
  2404. $this->windowRows,
  2405. 0,
  2406. 0,
  2407. strlen($terminal_modes),
  2408. $terminal_modes
  2409. );
  2410. if (!$this->send_binary_packet($packet)) {
  2411. return false;
  2412. }
  2413. $response = $this->get_binary_packet();
  2414. if ($response === false) {
  2415. throw new \RuntimeException('Connection closed by server');
  2416. }
  2417. if (!strlen($response)) {
  2418. return false;
  2419. }
  2420. list(, $type) = unpack('C', Strings::shift($response, 1));
  2421. switch ($type) {
  2422. case NET_SSH2_MSG_CHANNEL_SUCCESS:
  2423. // if a pty can't be opened maybe commands can still be executed
  2424. case NET_SSH2_MSG_CHANNEL_FAILURE:
  2425. break;
  2426. default:
  2427. $this->disconnect_helper(NET_SSH2_DISCONNECT_BY_APPLICATION);
  2428. throw new \UnexpectedValueException('Unable to request pseudo-terminal');
  2429. }
  2430. $packet = pack(
  2431. 'CNNa*C',
  2432. NET_SSH2_MSG_CHANNEL_REQUEST,
  2433. $this->server_channels[self::CHANNEL_SHELL],
  2434. strlen('shell'),
  2435. 'shell',
  2436. 1
  2437. );
  2438. if (!$this->send_binary_packet($packet)) {
  2439. return false;
  2440. }
  2441. $this->channel_status[self::CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_REQUEST;
  2442. $response = $this->get_channel_packet(self::CHANNEL_SHELL);
  2443. if ($response === false) {
  2444. return false;
  2445. }
  2446. $this->channel_status[self::CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_DATA;
  2447. $this->bitmap |= self::MASK_SHELL;
  2448. return true;
  2449. }
  2450. /**
  2451. * Return the channel to be used with read() / write()
  2452. *
  2453. * @see self::read()
  2454. * @see self::write()
  2455. * @return int
  2456. * @access public
  2457. */
  2458. private function get_interactive_channel()
  2459. {
  2460. switch (true) {
  2461. case $this->in_subsystem:
  2462. return self::CHANNEL_SUBSYSTEM;
  2463. case $this->in_request_pty_exec:
  2464. return self::CHANNEL_EXEC;
  2465. default:
  2466. return self::CHANNEL_SHELL;
  2467. }
  2468. }
  2469. /**
  2470. * Return an available open channel
  2471. *
  2472. * @return int
  2473. * @access public
  2474. */
  2475. private function get_open_channel()
  2476. {
  2477. $channel = self::CHANNEL_EXEC;
  2478. do {
  2479. if (isset($this->channel_status[$channel]) && $this->channel_status[$channel] == NET_SSH2_MSG_CHANNEL_OPEN) {
  2480. return $channel;
  2481. }
  2482. } while ($channel++ < self::CHANNEL_SUBSYSTEM);
  2483. return false;
  2484. }
  2485. /**
  2486. * Returns the output of an interactive shell
  2487. *
  2488. * Returns when there's a match for $expect, which can take the form of a string literal or,
  2489. * if $mode == self::READ_REGEX, a regular expression.
  2490. *
  2491. * @see self::write()
  2492. * @param string $expect
  2493. * @param int $mode
  2494. * @return string
  2495. * @throws \RuntimeException on connection error
  2496. * @access public
  2497. */
  2498. public function read($expect = '', $mode = self::READ_SIMPLE)
  2499. {
  2500. $this->curTimeout = $this->timeout;
  2501. $this->is_timeout = false;
  2502. if (!$this->isAuthenticated()) {
  2503. throw new \RuntimeException('Operation disallowed prior to login()');
  2504. }
  2505. if (!($this->bitmap & self::MASK_SHELL) && !$this->initShell()) {
  2506. throw new \RuntimeException('Unable to initiate an interactive shell session');
  2507. }
  2508. $channel = $this->get_interactive_channel();
  2509. $match = $expect;
  2510. while (true) {
  2511. if ($mode == self::READ_REGEX) {
  2512. preg_match($expect, substr($this->interactiveBuffer, -1024), $matches);
  2513. $match = isset($matches[0]) ? $matches[0] : '';
  2514. }
  2515. $pos = strlen($match) ? strpos($this->interactiveBuffer, $match) : false;
  2516. if ($pos !== false) {
  2517. return Strings::shift($this->interactiveBuffer, $pos + strlen($match));
  2518. }
  2519. $response = $this->get_channel_packet($channel);
  2520. if (is_bool($response)) {
  2521. $this->in_request_pty_exec = false;
  2522. return $response ? Strings::shift($this->interactiveBuffer, strlen($this->interactiveBuffer)) : false;
  2523. }
  2524. $this->interactiveBuffer.= $response;
  2525. }
  2526. }
  2527. /**
  2528. * Inputs a command into an interactive shell.
  2529. *
  2530. * @see self::read()
  2531. * @param string $cmd
  2532. * @return bool
  2533. * @throws \RuntimeException on connection error
  2534. * @access public
  2535. */
  2536. public function write($cmd)
  2537. {
  2538. if (!$this->isAuthenticated()) {
  2539. throw new \RuntimeException('Operation disallowed prior to login()');
  2540. }
  2541. if (!($this->bitmap & self::MASK_SHELL) && !$this->initShell()) {
  2542. throw new \RuntimeException('Unable to initiate an interactive shell session');
  2543. }
  2544. return $this->send_channel_packet($this->get_interactive_channel(), $cmd);
  2545. }
  2546. /**
  2547. * Start a subsystem.
  2548. *
  2549. * Right now only one subsystem at a time is supported. To support multiple subsystem's stopSubsystem() could accept
  2550. * a string that contained the name of the subsystem, but at that point, only one subsystem of each type could be opened.
  2551. * To support multiple subsystem's of the same name maybe it'd be best if startSubsystem() generated a new channel id and
  2552. * returns that and then that that was passed into stopSubsystem() but that'll be saved for a future date and implemented
  2553. * if there's sufficient demand for such a feature.
  2554. *
  2555. * @see self::stopSubsystem()
  2556. * @param string $subsystem
  2557. * @return bool
  2558. * @access public
  2559. */
  2560. public function startSubsystem($subsystem)
  2561. {
  2562. $this->window_size_server_to_client[self::CHANNEL_SUBSYSTEM] = $this->window_size;
  2563. $packet = pack(
  2564. 'CNa*N3',
  2565. NET_SSH2_MSG_CHANNEL_OPEN,
  2566. strlen('session'),
  2567. 'session',
  2568. self::CHANNEL_SUBSYSTEM,
  2569. $this->window_size,
  2570. 0x4000
  2571. );
  2572. if (!$this->send_binary_packet($packet)) {
  2573. return false;
  2574. }
  2575. $this->channel_status[self::CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_OPEN;
  2576. $response = $this->get_channel_packet(self::CHANNEL_SUBSYSTEM);
  2577. if ($response === false) {
  2578. return false;
  2579. }
  2580. $packet = pack(
  2581. 'CNNa*CNa*',
  2582. NET_SSH2_MSG_CHANNEL_REQUEST,
  2583. $this->server_channels[self::CHANNEL_SUBSYSTEM],
  2584. strlen('subsystem'),
  2585. 'subsystem',
  2586. 1,
  2587. strlen($subsystem),
  2588. $subsystem
  2589. );
  2590. if (!$this->send_binary_packet($packet)) {
  2591. return false;
  2592. }
  2593. $this->channel_status[self::CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_REQUEST;
  2594. $response = $this->get_channel_packet(self::CHANNEL_SUBSYSTEM);
  2595. if ($response === false) {
  2596. return false;
  2597. }
  2598. $this->channel_status[self::CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_DATA;
  2599. $this->bitmap |= self::MASK_SHELL;
  2600. $this->in_subsystem = true;
  2601. return true;
  2602. }
  2603. /**
  2604. * Stops a subsystem.
  2605. *
  2606. * @see self::startSubsystem()
  2607. * @return bool
  2608. * @access public
  2609. */
  2610. public function stopSubsystem()
  2611. {
  2612. $this->in_subsystem = false;
  2613. $this->close_channel(self::CHANNEL_SUBSYSTEM);
  2614. return true;
  2615. }
  2616. /**
  2617. * Closes a channel
  2618. *
  2619. * If read() timed out you might want to just close the channel and have it auto-restart on the next read() call
  2620. *
  2621. * @access public
  2622. */
  2623. public function reset()
  2624. {
  2625. $this->close_channel($this->get_interactive_channel());
  2626. }
  2627. /**
  2628. * Is timeout?
  2629. *
  2630. * Did exec() or read() return because they timed out or because they encountered the end?
  2631. *
  2632. * @access public
  2633. */
  2634. public function isTimeout()
  2635. {
  2636. return $this->is_timeout;
  2637. }
  2638. /**
  2639. * Disconnect
  2640. *
  2641. * @access public
  2642. */
  2643. public function disconnect()
  2644. {
  2645. $this->disconnect_helper(NET_SSH2_DISCONNECT_BY_APPLICATION);
  2646. if (isset($this->realtime_log_file) && is_resource($this->realtime_log_file)) {
  2647. fclose($this->realtime_log_file);
  2648. }
  2649. unset(self::$connections[$this->getResourceId()]);
  2650. }
  2651. /**
  2652. * Destructor.
  2653. *
  2654. * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call
  2655. * disconnect().
  2656. *
  2657. * @access public
  2658. */
  2659. public function __destruct()
  2660. {
  2661. $this->disconnect();
  2662. }
  2663. /**
  2664. * Is the connection still active?
  2665. *
  2666. * @return bool
  2667. * @access public
  2668. */
  2669. public function isConnected()
  2670. {
  2671. return (bool) ($this->bitmap & self::MASK_CONNECTED);
  2672. }
  2673. /**
  2674. * Have you successfully been logged in?
  2675. *
  2676. * @return bool
  2677. * @access public
  2678. */
  2679. public function isAuthenticated()
  2680. {
  2681. return (bool) ($this->bitmap & self::MASK_LOGIN);
  2682. }
  2683. /**
  2684. * Gets Binary Packets
  2685. *
  2686. * See '6. Binary Packet Protocol' of rfc4253 for more info.
  2687. *
  2688. * @see self::_send_binary_packet()
  2689. * @return string
  2690. * @throws \RuntimeException on connection errors
  2691. * @access private
  2692. */
  2693. private function get_binary_packet()
  2694. {
  2695. if (!is_resource($this->fsock) || feof($this->fsock)) {
  2696. $this->bitmap = 0;
  2697. throw new \RuntimeException('Connection closed prematurely');
  2698. }
  2699. $start = microtime(true);
  2700. $raw = stream_get_contents($this->fsock, $this->decrypt_block_size);
  2701. if (!strlen($raw)) {
  2702. return '';
  2703. }
  2704. if ($this->decrypt !== false) {
  2705. $raw = $this->decrypt->decrypt($raw);
  2706. }
  2707. if (strlen($raw) < 5) {
  2708. return false;
  2709. }
  2710. extract(unpack('Npacket_length/Cpadding_length', Strings::shift($raw, 5)));
  2711. $remaining_length = $packet_length + 4 - $this->decrypt_block_size;
  2712. // quoting <http://tools.ietf.org/html/rfc4253#section-6.1>,
  2713. // "implementations SHOULD check that the packet length is reasonable"
  2714. // PuTTY uses 0x9000 as the actual max packet size and so to shall we
  2715. if ($remaining_length < -$this->decrypt_block_size || $remaining_length > 0x9000 || $remaining_length % $this->decrypt_block_size != 0) {
  2716. throw new \RuntimeException('Invalid size');
  2717. }
  2718. $buffer = '';
  2719. while ($remaining_length > 0) {
  2720. $temp = stream_get_contents($this->fsock, $remaining_length);
  2721. if ($temp === false || feof($this->fsock)) {
  2722. $this->bitmap = 0;
  2723. throw new \RuntimeException('Error reading from socket');
  2724. }
  2725. $buffer.= $temp;
  2726. $remaining_length-= strlen($temp);
  2727. }
  2728. $stop = microtime(true);
  2729. if (strlen($buffer)) {
  2730. $raw.= $this->decrypt !== false ? $this->decrypt->decrypt($buffer) : $buffer;
  2731. }
  2732. $payload = Strings::shift($raw, $packet_length - $padding_length - 1);
  2733. $padding = Strings::shift($raw, $padding_length); // should leave $raw empty
  2734. if ($this->hmac_check !== false) {
  2735. $hmac = stream_get_contents($this->fsock, $this->hmac_size);
  2736. if ($hmac === false || strlen($hmac) != $this->hmac_size) {
  2737. $this->bitmap = 0;
  2738. throw new \RuntimeException('Error reading socket');
  2739. } elseif ($hmac != $this->hmac_check->hash(pack('NNCa*', $this->get_seq_no, $packet_length, $padding_length, $payload . $padding))) {
  2740. throw new \RuntimeException('Invalid HMAC');
  2741. }
  2742. }
  2743. //if ($this->decompress) {
  2744. // $payload = gzinflate(substr($payload, 2));
  2745. //}
  2746. $this->get_seq_no++;
  2747. if (defined('NET_SSH2_LOGGING')) {
  2748. $current = microtime(true);
  2749. $message_number = isset($this->message_numbers[ord($payload[0])]) ? $this->message_numbers[ord($payload[0])] : 'UNKNOWN (' . ord($payload[0]) . ')';
  2750. $message_number = '<- ' . $message_number .
  2751. ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)';
  2752. $this->append_log($message_number, $payload);
  2753. $this->last_packet = $current;
  2754. }
  2755. return $this->filter($payload);
  2756. }
  2757. /**
  2758. * Filter Binary Packets
  2759. *
  2760. * Because some binary packets need to be ignored...
  2761. *
  2762. * @see self::_get_binary_packet()
  2763. * @return string
  2764. * @access private
  2765. */
  2766. private function filter($payload)
  2767. {
  2768. switch (ord($payload[0])) {
  2769. case NET_SSH2_MSG_DISCONNECT:
  2770. Strings::shift($payload, 1);
  2771. if (strlen($payload) < 8) {
  2772. return false;
  2773. }
  2774. extract(unpack('Nreason_code/Nlength', Strings::shift($payload, 8)));
  2775. $this->errors[] = 'SSH_MSG_DISCONNECT: ' . $this->disconnect_reasons[$reason_code] . "\r\n" . utf8_decode(Strings::shift($payload, $length));
  2776. $this->bitmap = 0;
  2777. return false;
  2778. case NET_SSH2_MSG_IGNORE:
  2779. $payload = $this->get_binary_packet();
  2780. break;
  2781. case NET_SSH2_MSG_DEBUG:
  2782. Strings::shift($payload, 2);
  2783. if (strlen($payload) < 4) {
  2784. return false;
  2785. }
  2786. extract(unpack('Nlength', Strings::shift($payload, 4)));
  2787. $this->errors[] = 'SSH_MSG_DEBUG: ' . utf8_decode(Strings::shift($payload, $length));
  2788. $payload = $this->get_binary_packet();
  2789. break;
  2790. case NET_SSH2_MSG_UNIMPLEMENTED:
  2791. return false;
  2792. case NET_SSH2_MSG_KEXINIT:
  2793. if ($this->session_id !== false) {
  2794. if (!$this->key_exchange($payload)) {
  2795. $this->bitmap = 0;
  2796. return false;
  2797. }
  2798. $payload = $this->get_binary_packet();
  2799. }
  2800. }
  2801. // see http://tools.ietf.org/html/rfc4252#section-5.4; only called when the encryption has been activated and when we haven't already logged in
  2802. if (($this->bitmap & self::MASK_CONNECTED) && !$this->isAuthenticated() && ord($payload[0]) == NET_SSH2_MSG_USERAUTH_BANNER) {
  2803. Strings::shift($payload, 1);
  2804. if (strlen($payload) < 4) {
  2805. return false;
  2806. }
  2807. extract(unpack('Nlength', Strings::shift($payload, 4)));
  2808. $this->banner_message = utf8_decode(Strings::shift($payload, $length));
  2809. $payload = $this->get_binary_packet();
  2810. }
  2811. // only called when we've already logged in
  2812. if (($this->bitmap & self::MASK_CONNECTED) && $this->isAuthenticated()) {
  2813. switch (ord($payload[0])) {
  2814. case NET_SSH2_MSG_GLOBAL_REQUEST: // see http://tools.ietf.org/html/rfc4254#section-4
  2815. if (strlen($payload) < 4) {
  2816. return false;
  2817. }
  2818. extract(unpack('Nlength', Strings::shift($payload, 4)));
  2819. $this->errors[] = 'SSH_MSG_GLOBAL_REQUEST: ' . Strings::shift($payload, $length);
  2820. if (!$this->send_binary_packet(pack('C', NET_SSH2_MSG_REQUEST_FAILURE))) {
  2821. return $this->disconnect_helper(NET_SSH2_DISCONNECT_BY_APPLICATION);
  2822. }
  2823. $payload = $this->get_binary_packet();
  2824. break;
  2825. case NET_SSH2_MSG_CHANNEL_OPEN: // see http://tools.ietf.org/html/rfc4254#section-5.1
  2826. Strings::shift($payload, 1);
  2827. if (strlen($payload) < 4) {
  2828. return false;
  2829. }
  2830. extract(unpack('Nlength', Strings::shift($payload, 4)));
  2831. $data = Strings::shift($payload, $length);
  2832. if (strlen($payload) < 4) {
  2833. return false;
  2834. }
  2835. extract(unpack('Nserver_channel', Strings::shift($payload, 4)));
  2836. switch ($data) {
  2837. case 'auth-agent':
  2838. case 'auth-agent@openssh.com':
  2839. if (isset($this->agent)) {
  2840. $new_channel = self::CHANNEL_AGENT_FORWARD;
  2841. if (strlen($payload) < 8) {
  2842. return false;
  2843. }
  2844. extract(unpack('Nremote_window_size', Strings::shift($payload, 4)));
  2845. extract(unpack('Nremote_maximum_packet_size', Strings::shift($payload, 4)));
  2846. $this->packet_size_client_to_server[$new_channel] = $remote_window_size;
  2847. $this->window_size_server_to_client[$new_channel] = $remote_maximum_packet_size;
  2848. $this->window_size_client_to_server[$new_channel] = $this->window_size;
  2849. $packet_size = 0x4000;
  2850. $packet = pack(
  2851. 'CN4',
  2852. NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION,
  2853. $server_channel,
  2854. $new_channel,
  2855. $packet_size,
  2856. $packet_size
  2857. );
  2858. $this->server_channels[$new_channel] = $server_channel;
  2859. $this->channel_status[$new_channel] = NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION;
  2860. if (!$this->send_binary_packet($packet)) {
  2861. return false;
  2862. }
  2863. }
  2864. break;
  2865. default:
  2866. $packet = pack(
  2867. 'CN3a*Na*',
  2868. NET_SSH2_MSG_REQUEST_FAILURE,
  2869. $server_channel,
  2870. NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED,
  2871. 0,
  2872. '',
  2873. 0,
  2874. ''
  2875. );
  2876. if (!$this->send_binary_packet($packet)) {
  2877. return $this->disconnect_helper(NET_SSH2_DISCONNECT_BY_APPLICATION);
  2878. }
  2879. }
  2880. $payload = $this->get_binary_packet();
  2881. break;
  2882. case NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST:
  2883. Strings::shift($payload, 1);
  2884. if (strlen($payload) < 8) {
  2885. return false;
  2886. }
  2887. extract(unpack('Nchannel', Strings::shift($payload, 4)));
  2888. extract(unpack('Nwindow_size', Strings::shift($payload, 4)));
  2889. $this->window_size_client_to_server[$channel]+= $window_size;
  2890. $payload = ($this->bitmap & self::MASK_WINDOW_ADJUST) ? true : $this->get_binary_packet();
  2891. }
  2892. }
  2893. return $payload;
  2894. }
  2895. /**
  2896. * Enable Quiet Mode
  2897. *
  2898. * Suppress stderr from output
  2899. *
  2900. * @access public
  2901. */
  2902. public function enableQuietMode()
  2903. {
  2904. $this->quiet_mode = true;
  2905. }
  2906. /**
  2907. * Disable Quiet Mode
  2908. *
  2909. * Show stderr in output
  2910. *
  2911. * @access public
  2912. */
  2913. public function disableQuietMode()
  2914. {
  2915. $this->quiet_mode = false;
  2916. }
  2917. /**
  2918. * Returns whether Quiet Mode is enabled or not
  2919. *
  2920. * @see self::enableQuietMode()
  2921. * @see self::disableQuietMode()
  2922. * @access public
  2923. * @return bool
  2924. */
  2925. public function isQuietModeEnabled()
  2926. {
  2927. return $this->quiet_mode;
  2928. }
  2929. /**
  2930. * Enable request-pty when using exec()
  2931. *
  2932. * @access public
  2933. */
  2934. public function enablePTY()
  2935. {
  2936. $this->request_pty = true;
  2937. }
  2938. /**
  2939. * Disable request-pty when using exec()
  2940. *
  2941. * @access public
  2942. */
  2943. public function disablePTY()
  2944. {
  2945. if ($this->in_request_pty_exec) {
  2946. $this->_close_channel(self::CHANNEL_EXEC);
  2947. $this->in_request_pty_exec = false;
  2948. }
  2949. $this->request_pty = false;
  2950. }
  2951. /**
  2952. * Returns whether request-pty is enabled or not
  2953. *
  2954. * @see self::enablePTY()
  2955. * @see self::disablePTY()
  2956. * @access public
  2957. * @return bool
  2958. */
  2959. public function isPTYEnabled()
  2960. {
  2961. return $this->request_pty;
  2962. }
  2963. /**
  2964. * Gets channel data
  2965. *
  2966. * Returns the data as a string if it's available and false if not.
  2967. *
  2968. * @param $client_channel
  2969. * @return mixed
  2970. * @throws \RuntimeException on connection error
  2971. * @access private
  2972. */
  2973. protected function get_channel_packet($client_channel, $skip_extended = false)
  2974. {
  2975. if (!empty($this->channel_buffers[$client_channel])) {
  2976. return array_shift($this->channel_buffers[$client_channel]);
  2977. }
  2978. while (true) {
  2979. if ($this->curTimeout) {
  2980. if ($this->curTimeout < 0) {
  2981. $this->is_timeout = true;
  2982. return true;
  2983. }
  2984. $read = [$this->fsock];
  2985. $write = $except = null;
  2986. $start = microtime(true);
  2987. $sec = floor($this->curTimeout);
  2988. $usec = 1000000 * ($this->curTimeout - $sec);
  2989. // on windows this returns a "Warning: Invalid CRT parameters detected" error
  2990. if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
  2991. $this->is_timeout = true;
  2992. return true;
  2993. }
  2994. $elapsed = microtime(true) - $start;
  2995. $this->curTimeout-= $elapsed;
  2996. }
  2997. $response = $this->get_binary_packet();
  2998. if ($response === false) {
  2999. throw new \RuntimeException('Connection closed by server');
  3000. }
  3001. if ($client_channel == -1 && $response === true) {
  3002. return true;
  3003. }
  3004. if (!strlen($response)) {
  3005. return '';
  3006. }
  3007. if (!strlen($response)) {
  3008. return false;
  3009. }
  3010. extract(unpack('Ctype', Strings::shift($response, 1)));
  3011. if (strlen($response) < 4) {
  3012. return false;
  3013. }
  3014. if ($type == NET_SSH2_MSG_CHANNEL_OPEN) {
  3015. extract(unpack('Nlength', Strings::shift($response, 4)));
  3016. } else {
  3017. extract(unpack('Nchannel', Strings::shift($response, 4)));
  3018. }
  3019. // will not be setup yet on incoming channel open request
  3020. if (isset($channel) && isset($this->channel_status[$channel]) && isset($this->window_size_server_to_client[$channel])) {
  3021. $this->window_size_server_to_client[$channel]-= strlen($response);
  3022. // resize the window, if appropriate
  3023. if ($this->window_size_server_to_client[$channel] < 0) {
  3024. $packet = pack('CNN', NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST, $this->server_channels[$channel], $this->window_size);
  3025. if (!$this->send_binary_packet($packet)) {
  3026. return false;
  3027. }
  3028. $this->window_size_server_to_client[$channel]+= $this->window_size;
  3029. }
  3030. switch ($this->channel_status[$channel]) {
  3031. case NET_SSH2_MSG_CHANNEL_OPEN:
  3032. switch ($type) {
  3033. case NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
  3034. if (strlen($response) < 4) {
  3035. return false;
  3036. }
  3037. extract(unpack('Nserver_channel', Strings::shift($response, 4)));
  3038. $this->server_channels[$channel] = $server_channel;
  3039. if (strlen($response) < 4) {
  3040. return false;
  3041. }
  3042. extract(unpack('Nwindow_size', Strings::shift($response, 4)));
  3043. if ($window_size < 0) {
  3044. $window_size&= 0x7FFFFFFF;
  3045. $window_size+= 0x80000000;
  3046. }
  3047. $this->window_size_client_to_server[$channel] = $window_size;
  3048. if (strlen($response) < 4) {
  3049. return false;
  3050. }
  3051. $temp = unpack('Npacket_size_client_to_server', Strings::shift($response, 4));
  3052. $this->packet_size_client_to_server[$channel] = $temp['packet_size_client_to_server'];
  3053. $result = $client_channel == $channel ? true : $this->get_channel_packet($client_channel, $skip_extended);
  3054. $this->on_channel_open();
  3055. return $result;
  3056. //case NET_SSH2_MSG_CHANNEL_OPEN_FAILURE:
  3057. default:
  3058. $this->disconnect_helper(NET_SSH2_DISCONNECT_BY_APPLICATION);
  3059. throw new \RuntimeException('Unable to open channel');
  3060. }
  3061. break;
  3062. case NET_SSH2_MSG_CHANNEL_REQUEST:
  3063. switch ($type) {
  3064. case NET_SSH2_MSG_CHANNEL_SUCCESS:
  3065. return true;
  3066. case NET_SSH2_MSG_CHANNEL_FAILURE:
  3067. return false;
  3068. default:
  3069. $this->disconnect_helper(NET_SSH2_DISCONNECT_BY_APPLICATION);
  3070. throw new \RuntimeException('Unable to fulfill channel request');
  3071. }
  3072. case NET_SSH2_MSG_CHANNEL_CLOSE:
  3073. return $type == NET_SSH2_MSG_CHANNEL_CLOSE ? true : $this->get_channel_packet($client_channel, $skip_extended);
  3074. }
  3075. }
  3076. // ie. $this->channel_status[$channel] == NET_SSH2_MSG_CHANNEL_DATA
  3077. switch ($type) {
  3078. case NET_SSH2_MSG_CHANNEL_DATA:
  3079. /*
  3080. if ($channel == self::CHANNEL_EXEC) {
  3081. // SCP requires null packets, such as this, be sent. further, in the case of the ssh.com SSH server
  3082. // this actually seems to make things twice as fast. more to the point, the message right after
  3083. // SSH_MSG_CHANNEL_DATA (usually SSH_MSG_IGNORE) won't block for as long as it would have otherwise.
  3084. // in OpenSSH it slows things down but only by a couple thousandths of a second.
  3085. $this->send_channel_packet($channel, chr(0));
  3086. }
  3087. */
  3088. if (strlen($response) < 4) {
  3089. return false;
  3090. }
  3091. extract(unpack('Nlength', Strings::shift($response, 4)));
  3092. $data = Strings::shift($response, $length);
  3093. if ($channel == self::CHANNEL_AGENT_FORWARD) {
  3094. $agent_response = Objects::callFunc($this->agent, 'forward_data', [$data]);
  3095. if (!is_bool($agent_response)) {
  3096. $this->send_channel_packet($channel, $agent_response);
  3097. }
  3098. break;
  3099. }
  3100. if ($client_channel == $channel) {
  3101. return $data;
  3102. }
  3103. if (!isset($this->channel_buffers[$channel])) {
  3104. $this->channel_buffers[$channel] = [];
  3105. }
  3106. $this->channel_buffers[$channel][] = $data;
  3107. break;
  3108. case NET_SSH2_MSG_CHANNEL_EXTENDED_DATA:
  3109. /*
  3110. if ($client_channel == self::CHANNEL_EXEC) {
  3111. $this->send_channel_packet($client_channel, chr(0));
  3112. }
  3113. */
  3114. // currently, there's only one possible value for $data_type_code: NET_SSH2_EXTENDED_DATA_STDERR
  3115. if (strlen($response) < 8) {
  3116. return false;
  3117. }
  3118. extract(unpack('Ndata_type_code/Nlength', Strings::shift($response, 8)));
  3119. $data = Strings::shift($response, $length);
  3120. $this->stdErrorLog.= $data;
  3121. if ($skip_extended || $this->quiet_mode) {
  3122. break;
  3123. }
  3124. if ($client_channel == $channel) {
  3125. return $data;
  3126. }
  3127. if (!isset($this->channel_buffers[$channel])) {
  3128. $this->channel_buffers[$channel] = [];
  3129. }
  3130. $this->channel_buffers[$channel][] = $data;
  3131. break;
  3132. case NET_SSH2_MSG_CHANNEL_REQUEST:
  3133. if (strlen($response) < 4) {
  3134. return false;
  3135. }
  3136. extract(unpack('Nlength', Strings::shift($response, 4)));
  3137. $value = Strings::shift($response, $length);
  3138. switch ($value) {
  3139. case 'exit-signal':
  3140. Strings::shift($response, 1);
  3141. if (strlen($response) < 4) {
  3142. return false;
  3143. }
  3144. extract(unpack('Nlength', Strings::shift($response, 4)));
  3145. $this->errors[] = 'SSH_MSG_CHANNEL_REQUEST (exit-signal): ' . Strings::shift($response, $length);
  3146. if (strlen($response) < 4) {
  3147. return false;
  3148. }
  3149. Strings::shift($response, 1);
  3150. extract(unpack('Nlength', Strings::shift($response, 4)));
  3151. if ($length) {
  3152. $this->errors[count($this->errors)].= "\r\n" . Strings::shift($response, $length);
  3153. }
  3154. $this->send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_EOF, $this->server_channels[$client_channel]));
  3155. $this->send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$channel]));
  3156. $this->channel_status[$channel] = NET_SSH2_MSG_CHANNEL_EOF;
  3157. break;
  3158. case 'exit-status':
  3159. if (strlen($response) < 5) {
  3160. return false;
  3161. }
  3162. extract(unpack('Cfalse/Nexit_status', Strings::shift($response, 5)));
  3163. $this->exit_status = $exit_status;
  3164. // "The client MAY ignore these messages."
  3165. // -- http://tools.ietf.org/html/rfc4254#section-6.10
  3166. break;
  3167. default:
  3168. // "Some systems may not implement signals, in which case they SHOULD ignore this message."
  3169. // -- http://tools.ietf.org/html/rfc4254#section-6.9
  3170. break;
  3171. }
  3172. break;
  3173. case NET_SSH2_MSG_CHANNEL_CLOSE:
  3174. $this->curTimeout = 0;
  3175. if ($this->bitmap & self::MASK_SHELL) {
  3176. $this->bitmap&= ~self::MASK_SHELL;
  3177. }
  3178. if ($this->channel_status[$channel] != NET_SSH2_MSG_CHANNEL_EOF) {
  3179. $this->send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$channel]));
  3180. }
  3181. $this->channel_status[$channel] = NET_SSH2_MSG_CHANNEL_CLOSE;
  3182. if ($client_channel == $channel) {
  3183. return true;
  3184. }
  3185. case NET_SSH2_MSG_CHANNEL_EOF:
  3186. break;
  3187. default:
  3188. $this->disconnect_helper(NET_SSH2_DISCONNECT_BY_APPLICATION);
  3189. throw new \RuntimeException('Error reading channel data');
  3190. }
  3191. }
  3192. }
  3193. /**
  3194. * Sends Binary Packets
  3195. *
  3196. * See '6. Binary Packet Protocol' of rfc4253 for more info.
  3197. *
  3198. * @param string $data
  3199. * @param string $logged
  3200. * @see self::_get_binary_packet()
  3201. * @return bool
  3202. * @access private
  3203. */
  3204. protected function send_binary_packet($data, $logged = null)
  3205. {
  3206. if (!is_resource($this->fsock) || feof($this->fsock)) {
  3207. $this->bitmap = 0;
  3208. throw new \RuntimeException('Connection closed prematurely');
  3209. }
  3210. //if ($this->compress) {
  3211. // // the -4 removes the checksum:
  3212. // // http://php.net/function.gzcompress#57710
  3213. // $data = substr(gzcompress($data), 0, -4);
  3214. //}
  3215. // 4 (packet length) + 1 (padding length) + 4 (minimal padding amount) == 9
  3216. $packet_length = strlen($data) + 9;
  3217. // round up to the nearest $this->encrypt_block_size
  3218. $packet_length+= (($this->encrypt_block_size - 1) * $packet_length) % $this->encrypt_block_size;
  3219. // subtracting strlen($data) is obvious - subtracting 5 is necessary because of packet_length and padding_length
  3220. $padding_length = $packet_length - strlen($data) - 5;
  3221. $padding = Random::string($padding_length);
  3222. // we subtract 4 from packet_length because the packet_length field isn't supposed to include itself
  3223. $packet = pack('NCa*', $packet_length - 4, $padding_length, $data . $padding);
  3224. $hmac = $this->hmac_create !== false ? $this->hmac_create->hash(pack('Na*', $this->send_seq_no, $packet)) : '';
  3225. $this->send_seq_no++;
  3226. if ($this->encrypt !== false) {
  3227. $packet = $this->encrypt->encrypt($packet);
  3228. }
  3229. $packet.= $hmac;
  3230. $start = microtime(true);
  3231. $result = strlen($packet) == fputs($this->fsock, $packet);
  3232. $stop = microtime(true);
  3233. if (defined('NET_SSH2_LOGGING')) {
  3234. $current = microtime(true);
  3235. $message_number = isset($this->message_numbers[ord($data[0])]) ? $this->message_numbers[ord($data[0])] : 'UNKNOWN (' . ord($data[0]) . ')';
  3236. $message_number = '-> ' . $message_number .
  3237. ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)';
  3238. $this->append_log($message_number, isset($logged) ? $logged : $data);
  3239. $this->last_packet = $current;
  3240. }
  3241. return $result;
  3242. }
  3243. /**
  3244. * Logs data packets
  3245. *
  3246. * Makes sure that only the last 1MB worth of packets will be logged
  3247. *
  3248. * @param string $data
  3249. * @access private
  3250. */
  3251. private function append_log($message_number, $message)
  3252. {
  3253. // remove the byte identifying the message type from all but the first two messages (ie. the identification strings)
  3254. if (strlen($message_number) > 2) {
  3255. Strings::shift($message);
  3256. }
  3257. switch (NET_SSH2_LOGGING) {
  3258. // useful for benchmarks
  3259. case self::LOG_SIMPLE:
  3260. $this->message_number_log[] = $message_number;
  3261. break;
  3262. // the most useful log for SSH2
  3263. case self::LOG_COMPLEX:
  3264. $this->message_number_log[] = $message_number;
  3265. $this->log_size+= strlen($message);
  3266. $this->message_log[] = $message;
  3267. while ($this->log_size > self::LOG_MAX_SIZE) {
  3268. $this->log_size-= strlen(array_shift($this->message_log));
  3269. array_shift($this->message_number_log);
  3270. }
  3271. break;
  3272. // dump the output out realtime; packets may be interspersed with non packets,
  3273. // passwords won't be filtered out and select other packets may not be correctly
  3274. // identified
  3275. case self::LOG_REALTIME:
  3276. switch (PHP_SAPI) {
  3277. case 'cli':
  3278. $start = $stop = "\r\n";
  3279. break;
  3280. default:
  3281. $start = '<pre>';
  3282. $stop = '</pre>';
  3283. }
  3284. echo $start . $this->format_log([$message], [$message_number]) . $stop;
  3285. @flush();
  3286. @ob_flush();
  3287. break;
  3288. // basically the same thing as self::LOG_REALTIME with the caveat that NET_SFTP_LOG_REALTIME_FILENAME
  3289. // needs to be defined and that the resultant log file will be capped out at self::LOG_MAX_SIZE.
  3290. // the earliest part of the log file is denoted by the first <<< START >>> and is not going to necessarily
  3291. // at the beginning of the file
  3292. case self::LOG_REALTIME_FILE:
  3293. if (!isset($this->realtime_log_file)) {
  3294. // PHP doesn't seem to like using constants in fopen()
  3295. $filename = NET_SSH2_LOG_REALTIME_FILENAME;
  3296. $fp = fopen($filename, 'w');
  3297. $this->realtime_log_file = $fp;
  3298. }
  3299. if (!is_resource($this->realtime_log_file)) {
  3300. break;
  3301. }
  3302. $entry = $this->format_log([$message], [$message_number]);
  3303. if ($this->realtime_log_wrap) {
  3304. $temp = "<<< START >>>\r\n";
  3305. $entry.= $temp;
  3306. fseek($this->realtime_log_file, ftell($this->realtime_log_file) - strlen($temp));
  3307. }
  3308. $this->realtime_log_size+= strlen($entry);
  3309. if ($this->realtime_log_size > self::LOG_MAX_SIZE) {
  3310. fseek($this->realtime_log_file, 0);
  3311. $this->realtime_log_size = strlen($entry);
  3312. $this->realtime_log_wrap = true;
  3313. }
  3314. fputs($this->realtime_log_file, $entry);
  3315. }
  3316. }
  3317. /**
  3318. * Sends channel data
  3319. *
  3320. * Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate
  3321. *
  3322. * @param int $client_channel
  3323. * @param string $data
  3324. * @return bool
  3325. * @access private
  3326. */
  3327. protected function send_channel_packet($client_channel, $data)
  3328. {
  3329. while (strlen($data)) {
  3330. if (!$this->window_size_client_to_server[$client_channel]) {
  3331. $this->bitmap^= self::MASK_WINDOW_ADJUST;
  3332. // using an invalid channel will let the buffers be built up for the valid channels
  3333. $this->get_channel_packet(-1);
  3334. $this->bitmap^= self::MASK_WINDOW_ADJUST;
  3335. }
  3336. /* The maximum amount of data allowed is determined by the maximum
  3337. packet size for the channel, and the current window size, whichever
  3338. is smaller.
  3339. -- http://tools.ietf.org/html/rfc4254#section-5.2 */
  3340. $max_size = min(
  3341. $this->packet_size_client_to_server[$client_channel],
  3342. $this->window_size_client_to_server[$client_channel]
  3343. );
  3344. $temp = Strings::shift($data, $max_size);
  3345. $packet = pack(
  3346. 'CN2a*',
  3347. NET_SSH2_MSG_CHANNEL_DATA,
  3348. $this->server_channels[$client_channel],
  3349. strlen($temp),
  3350. $temp
  3351. );
  3352. $this->window_size_client_to_server[$client_channel]-= strlen($temp);
  3353. if (!$this->send_binary_packet($packet)) {
  3354. return false;
  3355. }
  3356. }
  3357. return true;
  3358. }
  3359. /**
  3360. * Closes and flushes a channel
  3361. *
  3362. * \phpseclib\Net\SSH2 doesn't properly close most channels. For exec() channels are normally closed by the server
  3363. * and for SFTP channels are presumably closed when the client disconnects. This functions is intended
  3364. * for SCP more than anything.
  3365. *
  3366. * @param int $client_channel
  3367. * @param bool $want_reply
  3368. * @return bool
  3369. * @access private
  3370. */
  3371. private function close_channel($client_channel, $want_reply = false)
  3372. {
  3373. // see http://tools.ietf.org/html/rfc4254#section-5.3
  3374. $this->send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_EOF, $this->server_channels[$client_channel]));
  3375. if (!$want_reply) {
  3376. $this->send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$client_channel]));
  3377. }
  3378. $this->channel_status[$client_channel] = NET_SSH2_MSG_CHANNEL_CLOSE;
  3379. $this->curTimeout = 0;
  3380. while (!is_bool($this->get_channel_packet($client_channel))) {
  3381. }
  3382. if ($want_reply) {
  3383. $this->send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$client_channel]));
  3384. }
  3385. if ($this->bitmap & self::MASK_SHELL) {
  3386. $this->bitmap&= ~self::MASK_SHELL;
  3387. }
  3388. }
  3389. /**
  3390. * Disconnect
  3391. *
  3392. * @param int $reason
  3393. * @return bool
  3394. * @access private
  3395. */
  3396. private function disconnect_helper($reason)
  3397. {
  3398. if ($this->bitmap & self::MASK_CONNECTED) {
  3399. $data = pack('CNNa*Na*', NET_SSH2_MSG_DISCONNECT, $reason, 0, '', 0, '');
  3400. $this->send_binary_packet($data);
  3401. $this->bitmap = 0;
  3402. fclose($this->fsock);
  3403. return false;
  3404. }
  3405. }
  3406. /**
  3407. * Define Array
  3408. *
  3409. * Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of
  3410. * named constants from it, using the value as the name of the constant and the index as the value of the constant.
  3411. * If any of the constants that would be defined already exists, none of the constants will be defined.
  3412. *
  3413. * @param array $array
  3414. * @access private
  3415. */
  3416. protected function define_array()
  3417. {
  3418. $args = func_get_args();
  3419. foreach ($args as $arg) {
  3420. foreach ($arg as $key => $value) {
  3421. if (!defined($value)) {
  3422. define($value, $key);
  3423. } else {
  3424. break 2;
  3425. }
  3426. }
  3427. }
  3428. }
  3429. /**
  3430. * Returns a log of the packets that have been sent and received.
  3431. *
  3432. * Returns a string if NET_SSH2_LOGGING == self::LOG_COMPLEX, an array if NET_SSH2_LOGGING == self::LOG_SIMPLE and false if !defined('NET_SSH2_LOGGING')
  3433. *
  3434. * @access public
  3435. * @return array|false|string
  3436. */
  3437. public function getLog()
  3438. {
  3439. if (!defined('NET_SSH2_LOGGING')) {
  3440. return false;
  3441. }
  3442. switch (NET_SSH2_LOGGING) {
  3443. case self::LOG_SIMPLE:
  3444. return $this->message_number_log;
  3445. case self::LOG_COMPLEX:
  3446. $log = $this->_format_log($this->message_log, $this->message_number_log);
  3447. return PHP_SAPI == 'cli' ? $log : '<pre>' . $log . '</pre>';
  3448. default:
  3449. return false;
  3450. }
  3451. }
  3452. /**
  3453. * Formats a log for printing
  3454. *
  3455. * @param array $message_log
  3456. * @param array $message_number_log
  3457. * @access private
  3458. * @return string
  3459. */
  3460. protected function format_log($message_log, $message_number_log)
  3461. {
  3462. $output = '';
  3463. for ($i = 0; $i < count($message_log); $i++) {
  3464. $output.= $message_number_log[$i] . "\r\n";
  3465. $current_log = $message_log[$i];
  3466. $j = 0;
  3467. do {
  3468. if (strlen($current_log)) {
  3469. $output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 ';
  3470. }
  3471. $fragment = Strings::shift($current_log, $this->log_short_width);
  3472. $hex = substr(preg_replace_callback('#.#s', [$this, 'format_log_helper'], $fragment), strlen($this->log_boundary));
  3473. // replace non ASCII printable characters with dots
  3474. // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters
  3475. // also replace < with a . since < messes up the output on web browsers
  3476. $raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment);
  3477. $output.= str_pad($hex, $this->log_long_width - $this->log_short_width, ' ') . $raw . "\r\n";
  3478. $j++;
  3479. } while (strlen($current_log));
  3480. $output.= "\r\n";
  3481. }
  3482. return $output;
  3483. }
  3484. /**
  3485. * Helper function for _format_log
  3486. *
  3487. * For use with preg_replace_callback()
  3488. *
  3489. * @param array $matches
  3490. * @access private
  3491. * @return string
  3492. */
  3493. private function format_log_helper($matches)
  3494. {
  3495. return $this->log_boundary . str_pad(dechex(ord($matches[0])), 2, '0', STR_PAD_LEFT);
  3496. }
  3497. /**
  3498. * Helper function for agent->on_channel_open()
  3499. *
  3500. * Used when channels are created to inform agent
  3501. * of said channel opening. Must be called after
  3502. * channel open confirmation received
  3503. *
  3504. * @access private
  3505. */
  3506. private function on_channel_open()
  3507. {
  3508. if (isset($this->agent)) {
  3509. Objects::callFunc($this->agent, 'on_channel_open', [$this]);
  3510. }
  3511. }
  3512. /**
  3513. * Returns the first value of the intersection of two arrays or false if
  3514. * the intersection is empty. The order is defined by the first parameter.
  3515. *
  3516. * @param array $array1
  3517. * @param array $array2
  3518. * @return mixed False if intersection is empty, else intersected value.
  3519. * @access private
  3520. */
  3521. private function array_intersect_first($array1, $array2)
  3522. {
  3523. foreach ($array1 as $value) {
  3524. if (in_array($value, $array2)) {
  3525. return $value;
  3526. }
  3527. }
  3528. return false;
  3529. }
  3530. /**
  3531. * Returns all errors
  3532. *
  3533. * @return string[]
  3534. * @access public
  3535. */
  3536. public function getErrors()
  3537. {
  3538. return $this->errors;
  3539. }
  3540. /**
  3541. * Returns the last error
  3542. *
  3543. * @return string
  3544. * @access public
  3545. */
  3546. public function getLastError()
  3547. {
  3548. $count = count($this->errors);
  3549. if ($count > 0) {
  3550. return $this->errors[$count - 1];
  3551. }
  3552. }
  3553. /**
  3554. * Return the server identification.
  3555. *
  3556. * @return string
  3557. * @access public
  3558. */
  3559. public function getServerIdentification()
  3560. {
  3561. $this->connect();
  3562. return $this->server_identifier;
  3563. }
  3564. /**
  3565. * Return a list of the key exchange algorithms the server supports.
  3566. *
  3567. * @return array
  3568. * @access public
  3569. */
  3570. public function getKexAlgorithms()
  3571. {
  3572. $this->connect();
  3573. return $this->kex_algorithms;
  3574. }
  3575. /**
  3576. * Return a list of the host key (public key) algorithms the server supports.
  3577. *
  3578. * @return array
  3579. * @access public
  3580. */
  3581. public function getServerHostKeyAlgorithms()
  3582. {
  3583. $this->connect();
  3584. return $this->server_host_key_algorithms;
  3585. }
  3586. /**
  3587. * Return a list of the (symmetric key) encryption algorithms the server supports, when receiving stuff from the client.
  3588. *
  3589. * @return array
  3590. * @access public
  3591. */
  3592. public function getEncryptionAlgorithmsClient2Server()
  3593. {
  3594. $this->connect();
  3595. return $this->encryption_algorithms_client_to_server;
  3596. }
  3597. /**
  3598. * Return a list of the (symmetric key) encryption algorithms the server supports, when sending stuff to the client.
  3599. *
  3600. * @return array
  3601. * @access public
  3602. */
  3603. public function getEncryptionAlgorithmsServer2Client()
  3604. {
  3605. $this->connect();
  3606. return $this->encryption_algorithms_server_to_client;
  3607. }
  3608. /**
  3609. * Return a list of the MAC algorithms the server supports, when receiving stuff from the client.
  3610. *
  3611. * @return array
  3612. * @access public
  3613. */
  3614. public function getMACAlgorithmsClient2Server()
  3615. {
  3616. $this->connect();
  3617. return $this->mac_algorithms_client_to_server;
  3618. }
  3619. /**
  3620. * Return a list of the MAC algorithms the server supports, when sending stuff to the client.
  3621. *
  3622. * @return array
  3623. * @access public
  3624. */
  3625. public function getMACAlgorithmsServer2Client()
  3626. {
  3627. $this->connect();
  3628. return $this->mac_algorithms_server_to_client;
  3629. }
  3630. /**
  3631. * Return a list of the compression algorithms the server supports, when receiving stuff from the client.
  3632. *
  3633. * @return array
  3634. * @access public
  3635. */
  3636. public function getCompressionAlgorithmsClient2Server()
  3637. {
  3638. $this->connect();
  3639. return $this->compression_algorithms_client_to_server;
  3640. }
  3641. /**
  3642. * Return a list of the compression algorithms the server supports, when sending stuff to the client.
  3643. *
  3644. * @return array
  3645. * @access public
  3646. */
  3647. public function getCompressionAlgorithmsServer2Client()
  3648. {
  3649. $this->connect();
  3650. return $this->compression_algorithms_server_to_client;
  3651. }
  3652. /**
  3653. * Return a list of the languages the server supports, when sending stuff to the client.
  3654. *
  3655. * @return array
  3656. * @access public
  3657. */
  3658. public function getLanguagesServer2Client()
  3659. {
  3660. $this->connect();
  3661. return $this->languages_server_to_client;
  3662. }
  3663. /**
  3664. * Return a list of the languages the server supports, when receiving stuff from the client.
  3665. *
  3666. * @return array
  3667. * @access public
  3668. */
  3669. public function getLanguagesClient2Server()
  3670. {
  3671. $this->connect();
  3672. return $this->languages_client_to_server;
  3673. }
  3674. /**
  3675. * Returns the banner message.
  3676. *
  3677. * Quoting from the RFC, "in some jurisdictions, sending a warning message before
  3678. * authentication may be relevant for getting legal protection."
  3679. *
  3680. * @return string
  3681. * @access public
  3682. */
  3683. public function getBannerMessage()
  3684. {
  3685. return $this->banner_message;
  3686. }
  3687. /**
  3688. * Returns the server public host key.
  3689. *
  3690. * Caching this the first time you connect to a server and checking the result on subsequent connections
  3691. * is recommended. Returns false if the server signature is not signed correctly with the public host key.
  3692. *
  3693. * @return mixed
  3694. * @throws \RuntimeException on badly formatted keys
  3695. * @throws \phpseclib\Exception\NoSupportedAlgorithmsException when the key isn't in a supported format
  3696. * @access public
  3697. */
  3698. public function getServerPublicHostKey()
  3699. {
  3700. if (!($this->bitmap & self::MASK_CONSTRUCTOR)) {
  3701. if (!$this->connect()) {
  3702. return false;
  3703. }
  3704. }
  3705. $signature = $this->signature;
  3706. $server_public_host_key = $this->server_public_host_key;
  3707. if (strlen($server_public_host_key) < 4) {
  3708. return false;
  3709. }
  3710. extract(unpack('Nlength', Strings::shift($server_public_host_key, 4)));
  3711. Strings::shift($server_public_host_key, $length);
  3712. if ($this->signature_validated) {
  3713. return $this->bitmap ?
  3714. $this->signature_format . ' ' . Base64::encode($this->server_public_host_key) :
  3715. false;
  3716. }
  3717. $this->signature_validated = true;
  3718. switch ($this->signature_format) {
  3719. case 'ssh-dss':
  3720. $zero = new BigInteger();
  3721. if (strlen($server_public_host_key) < 4) {
  3722. return false;
  3723. }
  3724. $temp = unpack('Nlength', Strings::shift($server_public_host_key, 4));
  3725. $p = new BigInteger(Strings::shift($server_public_host_key, $temp['length']), -256);
  3726. if (strlen($server_public_host_key) < 4) {
  3727. return false;
  3728. }
  3729. $temp = unpack('Nlength', Strings::shift($server_public_host_key, 4));
  3730. $q = new BigInteger(Strings::shift($server_public_host_key, $temp['length']), -256);
  3731. if (strlen($server_public_host_key) < 4) {
  3732. return false;
  3733. }
  3734. $temp = unpack('Nlength', Strings::shift($server_public_host_key, 4));
  3735. $g = new BigInteger(Strings::shift($server_public_host_key, $temp['length']), -256);
  3736. if (strlen($server_public_host_key) < 4) {
  3737. return false;
  3738. }
  3739. $temp = unpack('Nlength', Strings::shift($server_public_host_key, 4));
  3740. $y = new BigInteger(Strings::shift($server_public_host_key, $temp['length']), -256);
  3741. /* The value for 'dss_signature_blob' is encoded as a string containing
  3742. r, followed by s (which are 160-bit integers, without lengths or
  3743. padding, unsigned, and in network byte order). */
  3744. $temp = unpack('Nlength', Strings::shift($signature, 4));
  3745. if ($temp['length'] != 40) {
  3746. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  3747. throw new \RuntimeException('Invalid signature');
  3748. }
  3749. $r = new BigInteger(Strings::shift($signature, 20), 256);
  3750. $s = new BigInteger(Strings::shift($signature, 20), 256);
  3751. switch (true) {
  3752. case $r->equals($zero):
  3753. case $r->compare($q) >= 0:
  3754. case $s->equals($zero):
  3755. case $s->compare($q) >= 0:
  3756. $this->disconnectHepler(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  3757. throw new \RuntimeException('Invalid signature');
  3758. }
  3759. $w = $s->modInverse($q);
  3760. $u1 = $w->multiply(new BigInteger(sha1($this->exchange_hash), 16));
  3761. list(, $u1) = $u1->divide($q);
  3762. $u2 = $w->multiply($r);
  3763. list(, $u2) = $u2->divide($q);
  3764. $g = $g->modPow($u1, $p);
  3765. $y = $y->modPow($u2, $p);
  3766. $v = $g->multiply($y);
  3767. list(, $v) = $v->divide($p);
  3768. list(, $v) = $v->divide($q);
  3769. if (!$v->equals($r)) {
  3770. //user_error('Bad server signature');
  3771. return $this->disconnect_helper(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE);
  3772. }
  3773. break;
  3774. case 'ssh-rsa':
  3775. if (strlen($server_public_host_key) < 4) {
  3776. return false;
  3777. }
  3778. $temp = unpack('Nlength', Strings::shift($server_public_host_key, 4));
  3779. $e = new BigInteger(Strings::shift($server_public_host_key, $temp['length']), -256);
  3780. if (strlen($server_public_host_key) < 4) {
  3781. return false;
  3782. }
  3783. $temp = unpack('Nlength', Strings::shift($server_public_host_key, 4));
  3784. $rawN = Strings::shift($server_public_host_key, $temp['length']);
  3785. $n = new BigInteger($rawN, -256);
  3786. $nLength = strlen(ltrim($rawN, "\0"));
  3787. /*
  3788. if (strlen($signature) < 4) {
  3789. return false;
  3790. }
  3791. $temp = unpack('Nlength', Strings::shift($signature, 4));
  3792. $signature = Strings::shift($signature, $temp['length']);
  3793. $rsa = new RSA();
  3794. $rsa->load(['e' => $e, 'n' => $n], 'raw');
  3795. $rsa->setHash('sha1');
  3796. if (!$rsa->verify($this->exchange_hash, $signature, RSA::PADDING_PKCS1)) {
  3797. //user_error('Bad server signature');
  3798. return $this->disconnect_helper(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE);
  3799. }
  3800. */
  3801. if (strlen($signature) < 4) {
  3802. return false;
  3803. }
  3804. $temp = unpack('Nlength', Strings::shift($signature, 4));
  3805. $s = new BigInteger(Strings::shift($signature, $temp['length']), 256);
  3806. // validate an RSA signature per "8.2 RSASSA-PKCS1-v1_5", "5.2.2 RSAVP1", and "9.1 EMSA-PSS" in the
  3807. // following URL:
  3808. // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf
  3809. // also, see SSHRSA.c (rsa2_verifysig) in PuTTy's source.
  3810. if ($s->compare(new BigInteger()) < 0 || $s->compare($n->subtract(new BigInteger(1))) > 0) {
  3811. $this->disconnect_helper(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
  3812. throw new \RuntimeException('Invalid signature');
  3813. }
  3814. $s = $s->modPow($e, $n);
  3815. $s = $s->toBytes();
  3816. $h = pack('N4H*', 0x00302130, 0x0906052B, 0x0E03021A, 0x05000414, sha1($this->exchange_hash));
  3817. $h = chr(0x01) . str_repeat(chr(0xFF), $nLength - 2 - strlen($h)) . $h;
  3818. if ($s != $h) {
  3819. //user_error('Bad server signature');
  3820. return $this->disconnect_helper(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE);
  3821. }
  3822. break;
  3823. default:
  3824. $this->disconnect_helper(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE);
  3825. throw new NoSupportedAlgorithmsException('Unsupported signature format');
  3826. }
  3827. return $this->signature_format . ' ' . Base64::encode($this->server_public_host_key);
  3828. }
  3829. /**
  3830. * Returns the exit status of an SSH command or false.
  3831. *
  3832. * @return false|int
  3833. * @access public
  3834. */
  3835. public function getExitStatus()
  3836. {
  3837. if (is_null($this->exit_status)) {
  3838. return false;
  3839. }
  3840. return $this->exit_status;
  3841. }
  3842. /**
  3843. * Returns the number of columns for the terminal window size.
  3844. *
  3845. * @return int
  3846. * @access public
  3847. */
  3848. public function getWindowColumns()
  3849. {
  3850. return $this->windowColumns;
  3851. }
  3852. /**
  3853. * Returns the number of rows for the terminal window size.
  3854. *
  3855. * @return int
  3856. * @access public
  3857. */
  3858. public function getWindowRows()
  3859. {
  3860. return $this->windowRows;
  3861. }
  3862. /**
  3863. * Sets the number of columns for the terminal window size.
  3864. *
  3865. * @param int $value
  3866. * @access public
  3867. */
  3868. public function setWindowColumns($value)
  3869. {
  3870. $this->windowColumns = $value;
  3871. }
  3872. /**
  3873. * Sets the number of rows for the terminal window size.
  3874. *
  3875. * @param int $value
  3876. * @access public
  3877. */
  3878. public function setWindowRows($value)
  3879. {
  3880. $this->windowRows = $value;
  3881. }
  3882. /**
  3883. * Sets the number of columns and rows for the terminal window size.
  3884. *
  3885. * @param int $columns
  3886. * @param int $rows
  3887. * @access public
  3888. */
  3889. public function setWindowSize($columns = 80, $rows = 24)
  3890. {
  3891. $this->windowColumns = $columns;
  3892. $this->windowRows = $rows;
  3893. }
  3894. /**
  3895. * To String Magic Method
  3896. *
  3897. * @return string
  3898. * @access public
  3899. */
  3900. public function __toString()
  3901. {
  3902. return $this->getResourceId();
  3903. }
  3904. /**
  3905. * Get Resource ID
  3906. *
  3907. * We use {} because that symbols should not be in URL according to
  3908. * {@link http://tools.ietf.org/html/rfc3986#section-2 RFC}.
  3909. * It will safe us from any conflicts, because otherwise regexp will
  3910. * match all alphanumeric domains.
  3911. *
  3912. * @return string
  3913. */
  3914. public function getResourceId()
  3915. {
  3916. return '{' . spl_object_hash($this) . '}';
  3917. }
  3918. /**
  3919. * Return existing connection
  3920. *
  3921. * @param string $id
  3922. *
  3923. * @return bool|SSH2 will return false if no such connection
  3924. */
  3925. public static function getConnectionByResourceId($id)
  3926. {
  3927. return isset(self::$connections[$id]) ? self::$connections[$id] : false;
  3928. }
  3929. /**
  3930. * Return all excising connections
  3931. *
  3932. * @return SSH2[]
  3933. */
  3934. public static function getConnections()
  3935. {
  3936. return self::$connections;
  3937. }
  3938. }