SSH2.php 133 KB

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