1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225 |
- <?php
- namespace phpseclib\Net;
- use ParagonIE\ConstantTime\Base64;
- use phpseclib\Crypt\Base;
- use phpseclib\Crypt\Blowfish;
- use phpseclib\Crypt\Hash;
- use phpseclib\Crypt\Random;
- use phpseclib\Crypt\RC4;
- use phpseclib\Crypt\Rijndael;
- use phpseclib\Crypt\RSA;
- use phpseclib\Crypt\TripleDES;
- use phpseclib\Crypt\Twofish;
- use phpseclib\Math\BigInteger;
- use phpseclib\System\SSH\Agent;
- use phpseclib\Exception\NoSupportedAlgorithmsException;
- class SSH2
- {
-
- const MASK_CONSTRUCTOR = 0x00000001;
- const MASK_CONNECTED = 0x00000002;
- const MASK_LOGIN_REQ = 0x00000004;
- const MASK_LOGIN = 0x00000008;
- const MASK_SHELL = 0x00000010;
- const MASK_WINDOW_ADJUST = 0x00000020;
-
-
- const CHANNEL_EXEC = 0;
- const CHANNEL_SHELL = 1;
- const CHANNEL_SUBSYSTEM = 2;
- const CHANNEL_AGENT_FORWARD = 3;
-
-
-
- const LOG_SIMPLE = 1;
-
- const LOG_COMPLEX = 2;
-
- const LOG_REALTIME = 3;
-
- const LOG_REALTIME_FILE = 4;
-
-
-
- const READ_SIMPLE = 1;
-
- const READ_REGEX = 2;
-
- const LOG_MAX_SIZE = 1048576;
-
-
- var $identifier;
-
- var $fsock;
-
- var $bitmap = 0;
-
- var $errors = array();
-
- var $server_identifier = false;
-
- var $kex_algorithms = false;
-
- var $kex_dh_group_size_min = 1536;
-
- var $kex_dh_group_size_preferred = 2048;
-
- var $kex_dh_group_size_max = 4096;
-
- var $server_host_key_algorithms = false;
-
- var $encryption_algorithms_client_to_server = false;
-
- var $encryption_algorithms_server_to_client = false;
-
- var $mac_algorithms_client_to_server = false;
-
- var $mac_algorithms_server_to_client = false;
-
- var $compression_algorithms_client_to_server = false;
-
- var $compression_algorithms_server_to_client = false;
-
- var $languages_server_to_client = false;
-
- var $languages_client_to_server = false;
-
- var $encrypt_block_size = 8;
-
- var $decrypt_block_size = 8;
-
- var $decrypt = false;
-
- var $encrypt = false;
-
- var $hmac_create = false;
-
- var $hmac_check = false;
-
- var $hmac_size = false;
-
- var $server_public_host_key;
-
- var $session_id = false;
-
- var $exchange_hash = false;
-
- var $message_numbers = array();
-
- var $disconnect_reasons = array();
-
- var $channel_open_failure_reasons = array();
-
- var $terminal_modes = array();
-
- var $channel_extended_data_type_codes = array();
-
- var $send_seq_no = 0;
-
- var $get_seq_no = 0;
-
- var $server_channels = array();
-
- var $channel_buffers = array();
-
- var $channel_status = array();
-
- var $packet_size_client_to_server = array();
-
- var $message_number_log = array();
-
- var $message_log = array();
-
- var $window_size = 0x7FFFFFFF;
-
- var $window_size_server_to_client = array();
-
- var $window_size_client_to_server = array();
-
- var $signature = '';
-
- var $signature_format = '';
-
- var $interactiveBuffer = '';
-
- var $log_size;
-
- var $timeout;
-
- var $curTimeout;
-
- var $realtime_log_file;
-
- var $realtime_log_size;
-
- var $signature_validated = false;
-
- var $realtime_log_wrap;
-
- var $quiet_mode = false;
-
- var $last_packet;
-
- var $exit_status;
-
- var $request_pty = false;
-
- var $in_request_pty_exec = false;
-
- var $in_subsystem;
-
- var $stdErrorLog;
-
- var $last_interactive_response = '';
-
- var $keyboard_requests_responses = array();
-
- var $banner_message = '';
-
- var $is_timeout = false;
-
- var $log_boundary = ':';
-
- var $log_long_width = 65;
-
- var $log_short_width = 16;
-
- var $host;
-
- var $port;
-
- var $windowColumns = 80;
-
- var $windowRows = 24;
-
- var $crypto_engine = false;
-
- var $agent;
-
- static $connections;
-
- function __construct($host, $port = 22, $timeout = 10)
- {
- $this->message_numbers = array(
- 1 => 'NET_SSH2_MSG_DISCONNECT',
- 2 => 'NET_SSH2_MSG_IGNORE',
- 3 => 'NET_SSH2_MSG_UNIMPLEMENTED',
- 4 => 'NET_SSH2_MSG_DEBUG',
- 5 => 'NET_SSH2_MSG_SERVICE_REQUEST',
- 6 => 'NET_SSH2_MSG_SERVICE_ACCEPT',
- 20 => 'NET_SSH2_MSG_KEXINIT',
- 21 => 'NET_SSH2_MSG_NEWKEYS',
- 30 => 'NET_SSH2_MSG_KEXDH_INIT',
- 31 => 'NET_SSH2_MSG_KEXDH_REPLY',
- 50 => 'NET_SSH2_MSG_USERAUTH_REQUEST',
- 51 => 'NET_SSH2_MSG_USERAUTH_FAILURE',
- 52 => 'NET_SSH2_MSG_USERAUTH_SUCCESS',
- 53 => 'NET_SSH2_MSG_USERAUTH_BANNER',
- 80 => 'NET_SSH2_MSG_GLOBAL_REQUEST',
- 81 => 'NET_SSH2_MSG_REQUEST_SUCCESS',
- 82 => 'NET_SSH2_MSG_REQUEST_FAILURE',
- 90 => 'NET_SSH2_MSG_CHANNEL_OPEN',
- 91 => 'NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION',
- 92 => 'NET_SSH2_MSG_CHANNEL_OPEN_FAILURE',
- 93 => 'NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST',
- 94 => 'NET_SSH2_MSG_CHANNEL_DATA',
- 95 => 'NET_SSH2_MSG_CHANNEL_EXTENDED_DATA',
- 96 => 'NET_SSH2_MSG_CHANNEL_EOF',
- 97 => 'NET_SSH2_MSG_CHANNEL_CLOSE',
- 98 => 'NET_SSH2_MSG_CHANNEL_REQUEST',
- 99 => 'NET_SSH2_MSG_CHANNEL_SUCCESS',
- 100 => 'NET_SSH2_MSG_CHANNEL_FAILURE'
- );
- $this->disconnect_reasons = array(
- 1 => 'NET_SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT',
- 2 => 'NET_SSH2_DISCONNECT_PROTOCOL_ERROR',
- 3 => 'NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED',
- 4 => 'NET_SSH2_DISCONNECT_RESERVED',
- 5 => 'NET_SSH2_DISCONNECT_MAC_ERROR',
- 6 => 'NET_SSH2_DISCONNECT_COMPRESSION_ERROR',
- 7 => 'NET_SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE',
- 8 => 'NET_SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED',
- 9 => 'NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE',
- 10 => 'NET_SSH2_DISCONNECT_CONNECTION_LOST',
- 11 => 'NET_SSH2_DISCONNECT_BY_APPLICATION',
- 12 => 'NET_SSH2_DISCONNECT_TOO_MANY_CONNECTIONS',
- 13 => 'NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER',
- 14 => 'NET_SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE',
- 15 => 'NET_SSH2_DISCONNECT_ILLEGAL_USER_NAME'
- );
- $this->channel_open_failure_reasons = array(
- 1 => 'NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED'
- );
- $this->terminal_modes = array(
- 0 => 'NET_SSH2_TTY_OP_END'
- );
- $this->channel_extended_data_type_codes = array(
- 1 => 'NET_SSH2_EXTENDED_DATA_STDERR'
- );
- $this->_define_array(
- $this->message_numbers,
- $this->disconnect_reasons,
- $this->channel_open_failure_reasons,
- $this->terminal_modes,
- $this->channel_extended_data_type_codes,
- array(60 => 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ'),
- array(60 => 'NET_SSH2_MSG_USERAUTH_PK_OK'),
- array(60 => 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST',
- 61 => 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE'),
-
- array(30 => 'NET_SSH2_MSG_KEXDH_GEX_REQUEST_OLD',
- 31 => 'NET_SSH2_MSG_KEXDH_GEX_GROUP',
- 32 => 'NET_SSH2_MSG_KEXDH_GEX_INIT',
- 33 => 'NET_SSH2_MSG_KEXDH_GEX_REPLY',
- 34 => 'NET_SSH2_MSG_KEXDH_GEX_REQUEST'),
-
- array(30 => 'NET_SSH2_MSG_KEX_ECDH_INIT',
- 31 => 'NET_SSH2_MSG_KEX_ECDH_REPLY')
- );
- self::$connections[$this->getResourceId()] = $this;
- if (is_resource($host)) {
- $this->fsock = $host;
- return;
- }
- if (is_string($host)) {
- $this->host = $host;
- $this->port = $port;
- $this->timeout = $timeout;
- }
- }
-
- function setCryptoEngine($engine)
- {
- $this->crypto_engine = $engine;
- }
-
- function _connect()
- {
- if ($this->bitmap & self::MASK_CONSTRUCTOR) {
- return false;
- }
- $this->bitmap |= self::MASK_CONSTRUCTOR;
- $this->curTimeout = $this->timeout;
- $this->last_packet = microtime(true);
- if (!is_resource($this->fsock)) {
- $start = microtime(true);
- $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->curTimeout);
- if (!$this->fsock) {
- $host = $this->host . ':' . $this->port;
- throw new \RuntimeException(rtrim("Cannot connect to $host. Error $errno. $errstr"));
- }
- $elapsed = microtime(true) - $start;
- $this->curTimeout-= $elapsed;
- if ($this->curTimeout <= 0) {
- $this->is_timeout = true;
- return false;
- }
- }
-
- $data = '';
- while (!feof($this->fsock) && !preg_match('#(.*)^(SSH-(\d\.\d+).*)#ms', $data, $matches)) {
- $line = '';
- while (true) {
- if ($this->curTimeout) {
- if ($this->curTimeout < 0) {
- $this->is_timeout = true;
- return false;
- }
- $read = array($this->fsock);
- $write = $except = null;
- $start = microtime(true);
- $sec = floor($this->curTimeout);
- $usec = 1000000 * ($this->curTimeout - $sec);
-
-
- if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
- $this->is_timeout = true;
- return false;
- }
- $elapsed = microtime(true) - $start;
- $this->curTimeout-= $elapsed;
- }
- $temp = stream_get_line($this->fsock, 255, "\n");
- if (strlen($temp) == 255) {
- continue;
- }
- $line.= "$temp\n";
- if (substr($line, -2) == "\r\n") {
- break;
- }
- }
- $data.= $line;
- }
- if (feof($this->fsock)) {
- throw new \RuntimeException('Connection closed by server');
- }
- $extra = $matches[1];
- $this->identifier = $this->_generate_identifier();
- if (defined('NET_SSH2_LOGGING')) {
- $this->_append_log('<-', $matches[0]);
- $this->_append_log('->', $this->identifier . "\r\n");
- }
- $this->server_identifier = trim($temp, "\r\n");
- if (strlen($extra)) {
- $this->errors[] = utf8_decode($data);
- }
- if ($matches[3] != '1.99' && $matches[3] != '2.0') {
- throw new \RuntimeException("Cannot connect to SSH $matches[1] servers");
- }
- fputs($this->fsock, $this->identifier . "\r\n");
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- if (ord($response[0]) != NET_SSH2_MSG_KEXINIT) {
- throw new \UnexpectedValueException('Expected SSH_MSG_KEXINIT');
- }
- if (!$this->_key_exchange($response)) {
- return false;
- }
- $this->bitmap|= self::MASK_CONNECTED;
- return true;
- }
-
- function _generate_identifier()
- {
- $identifier = 'SSH-2.0-phpseclib_2.0';
- $ext = array();
- if (extension_loaded('libsodium')) {
- $ext[] = 'libsodium';
- }
- if (extension_loaded('openssl')) {
- $ext[] = 'openssl';
- } elseif (extension_loaded('mcrypt')) {
- $ext[] = 'mcrypt';
- }
- if (extension_loaded('gmp')) {
- $ext[] = 'gmp';
- } elseif (extension_loaded('bcmath')) {
- $ext[] = 'bcmath';
- }
- if (!empty($ext)) {
- $identifier .= ' (' . implode(', ', $ext) . ')';
- }
- return $identifier;
- }
-
- function _key_exchange($kexinit_payload_server)
- {
- $kex_algorithms = array(
-
-
-
- 'curve25519-sha256@libssh.org',
-
-
- 'diffie-hellman-group1-sha1',
- 'diffie-hellman-group14-sha1',
- 'diffie-hellman-group-exchange-sha1',
- 'diffie-hellman-group-exchange-sha256',
- );
- if (!function_exists('\\Sodium\\library_version_major')) {
- $kex_algorithms = array_diff(
- $kex_algorithms,
- array('curve25519-sha256@libssh.org')
- );
- }
- $server_host_key_algorithms = array(
- 'ssh-rsa',
- 'ssh-dss'
- );
- $encryption_algorithms = array(
-
- 'arcfour256',
- 'arcfour128',
-
-
- 'aes128-ctr',
- 'aes192-ctr',
- 'aes256-ctr',
- 'twofish128-ctr',
- 'twofish192-ctr',
- 'twofish256-ctr',
- 'aes128-cbc',
- 'aes192-cbc',
- 'aes256-cbc',
- 'twofish128-cbc',
- 'twofish192-cbc',
- 'twofish256-cbc',
- 'twofish-cbc',
-
- 'blowfish-ctr',
- 'blowfish-cbc',
- '3des-ctr',
- '3des-cbc',
-
- );
- if (extension_loaded('openssl') && !extension_loaded('mcrypt')) {
-
-
- $encryption_algorithms = array_diff(
- $encryption_algorithms,
- array('arcfour256', 'arcfour128', 'arcfour')
- );
- }
- if (class_exists('\phpseclib\Crypt\RC4') === false) {
- $encryption_algorithms = array_diff(
- $encryption_algorithms,
- array('arcfour256', 'arcfour128', 'arcfour')
- );
- }
- if (class_exists('\phpseclib\Crypt\Rijndael') === false) {
- $encryption_algorithms = array_diff(
- $encryption_algorithms,
- array('aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-cbc', 'aes192-cbc', 'aes256-cbc')
- );
- }
- if (class_exists('\phpseclib\Crypt\Twofish') === false) {
- $encryption_algorithms = array_diff(
- $encryption_algorithms,
- array('twofish128-ctr', 'twofish192-ctr', 'twofish256-ctr', 'twofish128-cbc', 'twofish192-cbc', 'twofish256-cbc', 'twofish-cbc')
- );
- }
- if (class_exists('\phpseclib\Crypt\Blowfish') === false) {
- $encryption_algorithms = array_diff(
- $encryption_algorithms,
- array('blowfish-ctr', 'blowfish-cbc')
- );
- }
- if (class_exists('\phpseclib\Crypt\TripleDES') === false) {
- $encryption_algorithms = array_diff(
- $encryption_algorithms,
- array('3des-ctr', '3des-cbc')
- );
- }
- $encryption_algorithms = array_values($encryption_algorithms);
- $mac_algorithms = array(
-
- 'hmac-sha2-256',
- 'hmac-sha1-96',
- 'hmac-sha1',
- 'hmac-md5-96',
- 'hmac-md5',
-
- );
- $compression_algorithms = array(
- 'none'
-
- );
-
- switch ($this->server_identifier) {
- case 'SSH-2.0-SSHD':
- $mac_algorithms = array_values(array_diff(
- $mac_algorithms,
- array('hmac-sha1-96', 'hmac-md5-96')
- ));
- }
- $str_kex_algorithms = implode(',', $kex_algorithms);
- $str_server_host_key_algorithms = implode(',', $server_host_key_algorithms);
- $encryption_algorithms_server_to_client = $encryption_algorithms_client_to_server = implode(',', $encryption_algorithms);
- $mac_algorithms_server_to_client = $mac_algorithms_client_to_server = implode(',', $mac_algorithms);
- $compression_algorithms_server_to_client = $compression_algorithms_client_to_server = implode(',', $compression_algorithms);
- $client_cookie = Random::string(16);
- $response = $kexinit_payload_server;
- $this->_string_shift($response, 1);
- $server_cookie = $this->_string_shift($response, 16);
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->kex_algorithms = explode(',', $this->_string_shift($response, $temp['length']));
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->server_host_key_algorithms = explode(',', $this->_string_shift($response, $temp['length']));
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->encryption_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->encryption_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->mac_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->mac_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->compression_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->compression_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->languages_client_to_server = explode(',', $this->_string_shift($response, $temp['length']));
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->languages_server_to_client = explode(',', $this->_string_shift($response, $temp['length']));
- extract(unpack('Cfirst_kex_packet_follows', $this->_string_shift($response, 1)));
- $first_kex_packet_follows = $first_kex_packet_follows != 0;
-
- $kexinit_payload_client = pack(
- 'Ca*Na*Na*Na*Na*Na*Na*Na*Na*Na*Na*CN',
- NET_SSH2_MSG_KEXINIT,
- $client_cookie,
- strlen($str_kex_algorithms),
- $str_kex_algorithms,
- strlen($str_server_host_key_algorithms),
- $str_server_host_key_algorithms,
- strlen($encryption_algorithms_client_to_server),
- $encryption_algorithms_client_to_server,
- strlen($encryption_algorithms_server_to_client),
- $encryption_algorithms_server_to_client,
- strlen($mac_algorithms_client_to_server),
- $mac_algorithms_client_to_server,
- strlen($mac_algorithms_server_to_client),
- $mac_algorithms_server_to_client,
- strlen($compression_algorithms_client_to_server),
- $compression_algorithms_client_to_server,
- strlen($compression_algorithms_server_to_client),
- $compression_algorithms_server_to_client,
- 0,
- '',
- 0,
- '',
- 0,
- 0
- );
- if (!$this->_send_binary_packet($kexinit_payload_client)) {
- return false;
- }
-
-
-
-
- $decrypt = $this->_array_intersect_first($encryption_algorithms, $this->encryption_algorithms_server_to_client);
- $decryptKeyLength = $this->_encryption_algorithm_to_key_size($decrypt);
- if ($decryptKeyLength === null) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible server to client encryption algorithms found');
- }
- $encrypt = $this->_array_intersect_first($encryption_algorithms, $this->encryption_algorithms_client_to_server);
- $encryptKeyLength = $this->_encryption_algorithm_to_key_size($encrypt);
- if ($encryptKeyLength === null) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible client to server encryption algorithms found');
- }
-
- $kex_algorithm = $this->_array_intersect_first($kex_algorithms, $this->kex_algorithms);
- if ($kex_algorithm === false) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible key exchange algorithms found');
- }
-
- $exchange_hash_rfc4419 = '';
- if ($kex_algorithm === 'curve25519-sha256@libssh.org') {
- $x = Random::string(32);
- $eBytes = \Sodium\crypto_box_publickey_from_secretkey($x);
- $clientKexInitMessage = NET_SSH2_MSG_KEX_ECDH_INIT;
- $serverKexReplyMessage = NET_SSH2_MSG_KEX_ECDH_REPLY;
- $kexHash = new Hash('sha256');
- } else {
- if (strpos($kex_algorithm, 'diffie-hellman-group-exchange') === 0) {
- $dh_group_sizes_packed = pack(
- 'NNN',
- $this->kex_dh_group_size_min,
- $this->kex_dh_group_size_preferred,
- $this->kex_dh_group_size_max
- );
- $packet = pack(
- 'Ca*',
- NET_SSH2_MSG_KEXDH_GEX_REQUEST,
- $dh_group_sizes_packed
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- user_error('Connection closed by server');
- return false;
- }
- extract(unpack('Ctype', $this->_string_shift($response, 1)));
- if ($type != NET_SSH2_MSG_KEXDH_GEX_GROUP) {
- user_error('Expected SSH_MSG_KEX_DH_GEX_GROUP');
- return false;
- }
- extract(unpack('NprimeLength', $this->_string_shift($response, 4)));
- $primeBytes = $this->_string_shift($response, $primeLength);
- $prime = new BigInteger($primeBytes, -256);
- extract(unpack('NgLength', $this->_string_shift($response, 4)));
- $gBytes = $this->_string_shift($response, $gLength);
- $g = new BigInteger($gBytes, -256);
- $exchange_hash_rfc4419 = pack(
- 'a*Na*Na*',
- $dh_group_sizes_packed,
- $primeLength,
- $primeBytes,
- $gLength,
- $gBytes
- );
- $clientKexInitMessage = NET_SSH2_MSG_KEXDH_GEX_INIT;
- $serverKexReplyMessage = NET_SSH2_MSG_KEXDH_GEX_REPLY;
- } else {
- switch ($kex_algorithm) {
-
-
- case 'diffie-hellman-group1-sha1':
- $prime = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' .
- '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' .
- '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' .
- 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF';
- break;
-
- case 'diffie-hellman-group14-sha1':
- $prime = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' .
- '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' .
- '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' .
- 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05' .
- '98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB' .
- '9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' .
- 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' .
- '3995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF';
- break;
- }
-
-
- $g = new BigInteger(2);
- $prime = new BigInteger($prime, 16);
- $clientKexInitMessage = NET_SSH2_MSG_KEXDH_INIT;
- $serverKexReplyMessage = NET_SSH2_MSG_KEXDH_REPLY;
- }
- switch ($kex_algorithm) {
- case 'diffie-hellman-group-exchange-sha256':
- $kexHash = new Hash('sha256');
- break;
- default:
- $kexHash = new Hash('sha1');
- }
-
- $one = new BigInteger(1);
- $keyLength = min($kexHash->getLength(), max($encryptKeyLength, $decryptKeyLength));
- $max = $one->bitwise_leftShift(16 * $keyLength);
- $max = $max->subtract($one);
- $x = BigInteger::random($one, $max);
- $e = $g->modPow($x, $prime);
- $eBytes = $e->toBytes(true);
- }
- $data = pack('CNa*', $clientKexInitMessage, strlen($eBytes), $eBytes);
- if (!$this->_send_binary_packet($data)) {
- throw new \RuntimeException('Connection closed by server');
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- extract(unpack('Ctype', $this->_string_shift($response, 1)));
- if ($type != $serverKexReplyMessage) {
- throw new \UnexpectedValueException('Expected SSH_MSG_KEXDH_REPLY');
- }
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->server_public_host_key = $server_public_host_key = $this->_string_shift($response, $temp['length']);
- $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
- $public_key_format = $this->_string_shift($server_public_host_key, $temp['length']);
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $fBytes = $this->_string_shift($response, $temp['length']);
- $temp = unpack('Nlength', $this->_string_shift($response, 4));
- $this->signature = $this->_string_shift($response, $temp['length']);
- $temp = unpack('Nlength', $this->_string_shift($this->signature, 4));
- $this->signature_format = $this->_string_shift($this->signature, $temp['length']);
- if ($kex_algorithm === 'curve25519-sha256@libssh.org') {
- if (strlen($fBytes) !== 32) {
- user_error('Received curve25519 public key of invalid length.');
- return false;
- }
- $key = new BigInteger(\Sodium\crypto_scalarmult($x, $fBytes), 256);
- \Sodium\memzero($x);
- } else {
- $f = new BigInteger($fBytes, -256);
- $key = $f->modPow($x, $prime);
- }
- $keyBytes = $key->toBytes(true);
- $this->exchange_hash = pack(
- 'Na*Na*Na*Na*Na*a*Na*Na*Na*',
- strlen($this->identifier),
- $this->identifier,
- strlen($this->server_identifier),
- $this->server_identifier,
- strlen($kexinit_payload_client),
- $kexinit_payload_client,
- strlen($kexinit_payload_server),
- $kexinit_payload_server,
- strlen($this->server_public_host_key),
- $this->server_public_host_key,
- $exchange_hash_rfc4419,
- strlen($eBytes),
- $eBytes,
- strlen($fBytes),
- $fBytes,
- strlen($keyBytes),
- $keyBytes
- );
- $this->exchange_hash = $kexHash->hash($this->exchange_hash);
- if ($this->session_id === false) {
- $this->session_id = $this->exchange_hash;
- }
- $server_host_key_algorithm = $this->_array_intersect_first($server_host_key_algorithms, $this->server_host_key_algorithms);
- if ($server_host_key_algorithm === false) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible server host key algorithms found');
- }
- if ($public_key_format != $server_host_key_algorithm || $this->signature_format != $server_host_key_algorithm) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new \RuntimeException('Server Host Key Algorithm Mismatch');
- }
- $packet = pack(
- 'C',
- NET_SSH2_MSG_NEWKEYS
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- extract(unpack('Ctype', $this->_string_shift($response, 1)));
- if ($type != NET_SSH2_MSG_NEWKEYS) {
- throw new \UnexpectedValueException('Expected SSH_MSG_NEWKEYS');
- }
- $keyBytes = pack('Na*', strlen($keyBytes), $keyBytes);
- $this->encrypt = $this->_encryption_algorithm_to_crypt_instance($encrypt);
- if ($this->encrypt) {
- if ($this->crypto_engine) {
- $this->encrypt->setEngine($this->crypto_engine);
- }
- if ($this->encrypt->block_size) {
- $this->encrypt_block_size = $this->encrypt->block_size;
- }
- $this->encrypt->enableContinuousBuffer();
- $this->encrypt->disablePadding();
- if ($this->encrypt->usesIV()) {
- $iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'A' . $this->session_id);
- while ($this->encrypt_block_size > strlen($iv)) {
- $iv.= $kexHash->hash($keyBytes . $this->exchange_hash . $iv);
- }
- $this->encrypt->setIV(substr($iv, 0, $this->encrypt_block_size));
- }
- $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'C' . $this->session_id);
- while ($encryptKeyLength > strlen($key)) {
- $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
- }
- $this->encrypt->setKey(substr($key, 0, $encryptKeyLength));
- }
- $this->decrypt = $this->_encryption_algorithm_to_crypt_instance($decrypt);
- if ($this->decrypt) {
- if ($this->crypto_engine) {
- $this->decrypt->setEngine($this->crypto_engine);
- }
- if ($this->decrypt->block_size) {
- $this->decrypt_block_size = $this->decrypt->block_size;
- }
- $this->decrypt->enableContinuousBuffer();
- $this->decrypt->disablePadding();
- if ($this->decrypt->usesIV()) {
- $iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'B' . $this->session_id);
- while ($this->decrypt_block_size > strlen($iv)) {
- $iv.= $kexHash->hash($keyBytes . $this->exchange_hash . $iv);
- }
- $this->decrypt->setIV(substr($iv, 0, $this->decrypt_block_size));
- }
- $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'D' . $this->session_id);
- while ($decryptKeyLength > strlen($key)) {
- $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
- }
- $this->decrypt->setKey(substr($key, 0, $decryptKeyLength));
- }
-
- if ($encrypt == 'arcfour128' || $encrypt == 'arcfour256') {
- $this->encrypt->encrypt(str_repeat("\0", 1536));
- }
- if ($decrypt == 'arcfour128' || $decrypt == 'arcfour256') {
- $this->decrypt->decrypt(str_repeat("\0", 1536));
- }
- $mac_algorithm = $this->_array_intersect_first($mac_algorithms, $this->mac_algorithms_client_to_server);
- if ($mac_algorithm === false) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible client to server message authentication algorithms found');
- }
- $createKeyLength = 0;
- switch ($mac_algorithm) {
- case 'hmac-sha2-256':
- $this->hmac_create = new Hash('sha256');
- $createKeyLength = 32;
- break;
- case 'hmac-sha1':
- $this->hmac_create = new Hash('sha1');
- $createKeyLength = 20;
- break;
- case 'hmac-sha1-96':
- $this->hmac_create = new Hash('sha1-96');
- $createKeyLength = 20;
- break;
- case 'hmac-md5':
- $this->hmac_create = new Hash('md5');
- $createKeyLength = 16;
- break;
- case 'hmac-md5-96':
- $this->hmac_create = new Hash('md5-96');
- $createKeyLength = 16;
- }
- $mac_algorithm = $this->_array_intersect_first($mac_algorithms, $this->mac_algorithms_server_to_client);
- if ($mac_algorithm === false) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible server to client message authentication algorithms found');
- }
- $checkKeyLength = 0;
- $this->hmac_size = 0;
- switch ($mac_algorithm) {
- case 'hmac-sha2-256':
- $this->hmac_check = new Hash('sha256');
- $checkKeyLength = 32;
- $this->hmac_size = 32;
- break;
- case 'hmac-sha1':
- $this->hmac_check = new Hash('sha1');
- $checkKeyLength = 20;
- $this->hmac_size = 20;
- break;
- case 'hmac-sha1-96':
- $this->hmac_check = new Hash('sha1-96');
- $checkKeyLength = 20;
- $this->hmac_size = 12;
- break;
- case 'hmac-md5':
- $this->hmac_check = new Hash('md5');
- $checkKeyLength = 16;
- $this->hmac_size = 16;
- break;
- case 'hmac-md5-96':
- $this->hmac_check = new Hash('md5-96');
- $checkKeyLength = 16;
- $this->hmac_size = 12;
- }
- $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'E' . $this->session_id);
- while ($createKeyLength > strlen($key)) {
- $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
- }
- $this->hmac_create->setKey(substr($key, 0, $createKeyLength));
- $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'F' . $this->session_id);
- while ($checkKeyLength > strlen($key)) {
- $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key);
- }
- $this->hmac_check->setKey(substr($key, 0, $checkKeyLength));
- $compression_algorithm = $this->_array_intersect_first($compression_algorithms, $this->compression_algorithms_server_to_client);
- if ($compression_algorithm === false) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible server to client compression algorithms found');
- }
- $this->decompress = $compression_algorithm == 'zlib';
- $compression_algorithm = $this->_array_intersect_first($compression_algorithms, $this->compression_algorithms_client_to_server);
- if ($compression_algorithm === false) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new NoSupportedAlgorithmsException('No compatible client to server compression algorithms found');
- }
- $this->compress = $compression_algorithm == 'zlib';
- return true;
- }
-
- function _encryption_algorithm_to_key_size($algorithm)
- {
- switch ($algorithm) {
- case 'none':
- return 0;
- case 'aes128-cbc':
- case 'aes128-ctr':
- case 'arcfour':
- case 'arcfour128':
- case 'blowfish-cbc':
- case 'blowfish-ctr':
- case 'twofish128-cbc':
- case 'twofish128-ctr':
- return 16;
- case '3des-cbc':
- case '3des-ctr':
- case 'aes192-cbc':
- case 'aes192-ctr':
- case 'twofish192-cbc':
- case 'twofish192-ctr':
- return 24;
- case 'aes256-cbc':
- case 'aes256-ctr':
- case 'arcfour256':
- case 'twofish-cbc':
- case 'twofish256-cbc':
- case 'twofish256-ctr':
- return 32;
- }
- return null;
- }
-
- function _encryption_algorithm_to_crypt_instance($algorithm)
- {
- switch ($algorithm) {
- case '3des-cbc':
- return new TripleDES(Base::MODE_CBC);
- case '3des-ctr':
- return new TripleDES(Base::MODE_CTR);
- case 'aes256-cbc':
- case 'aes192-cbc':
- case 'aes128-cbc':
- return new Rijndael(Base::MODE_CBC);
- case 'aes256-ctr':
- case 'aes192-ctr':
- case 'aes128-ctr':
- return new Rijndael(Base::MODE_CTR);
- case 'blowfish-cbc':
- return new Blowfish(Base::MODE_CBC);
- case 'blowfish-ctr':
- return new Blowfish(Base::MODE_CTR);
- case 'twofish128-cbc':
- case 'twofish192-cbc':
- case 'twofish256-cbc':
- case 'twofish-cbc':
- return new Twofish(Base::MODE_CBC);
- case 'twofish128-ctr':
- case 'twofish192-ctr':
- case 'twofish256-ctr':
- return new Twofish(Base::MODE_CTR);
- case 'arcfour':
- case 'arcfour128':
- case 'arcfour256':
- return new RC4();
- }
- return null;
- }
-
- function login($username)
- {
- $args = func_get_args();
- return call_user_func_array(array(&$this, '_login'), $args);
- }
-
- function _login($username)
- {
- if (!($this->bitmap & self::MASK_CONSTRUCTOR)) {
- if (!$this->_connect()) {
- return false;
- }
- }
- $args = array_slice(func_get_args(), 1);
- if (empty($args)) {
- return $this->_login_helper($username);
- }
- foreach ($args as $arg) {
- if ($this->_login_helper($username, $arg)) {
- return true;
- }
- }
- return false;
- }
-
- function _login_helper($username, $password = null)
- {
- if (!($this->bitmap & self::MASK_CONNECTED)) {
- return false;
- }
- if (!($this->bitmap & self::MASK_LOGIN_REQ)) {
- $packet = pack(
- 'CNa*',
- NET_SSH2_MSG_SERVICE_REQUEST,
- strlen('ssh-userauth'),
- 'ssh-userauth'
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- extract(unpack('Ctype', $this->_string_shift($response, 1)));
- if ($type != NET_SSH2_MSG_SERVICE_ACCEPT) {
- throw new \UnexpectedValueException('Expected SSH_MSG_SERVICE_ACCEPT');
- }
- $this->bitmap |= self::MASK_LOGIN_REQ;
- }
- if (strlen($this->last_interactive_response)) {
- return !is_string($password) && !is_array($password) ? false : $this->_keyboard_interactive_process($password);
- }
- if ($password instanceof RSA) {
- return $this->_privatekey_login($username, $password);
- } elseif ($password instanceof Agent) {
- return $this->_ssh_agent_login($username, $password);
- }
- if (is_array($password)) {
- if ($this->_keyboard_interactive_login($username, $password)) {
- $this->bitmap |= self::MASK_LOGIN;
- return true;
- }
- return false;
- }
- if (!isset($password)) {
- $packet = pack(
- 'CNa*Na*Na*',
- NET_SSH2_MSG_USERAUTH_REQUEST,
- strlen($username),
- $username,
- strlen('ssh-connection'),
- 'ssh-connection',
- strlen('none'),
- 'none'
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- extract(unpack('Ctype', $this->_string_shift($response, 1)));
- switch ($type) {
- case NET_SSH2_MSG_USERAUTH_SUCCESS:
- $this->bitmap |= self::MASK_LOGIN;
- return true;
-
- default:
- return false;
- }
- }
- $packet = pack(
- 'CNa*Na*Na*CNa*',
- NET_SSH2_MSG_USERAUTH_REQUEST,
- strlen($username),
- $username,
- strlen('ssh-connection'),
- 'ssh-connection',
- strlen('password'),
- 'password',
- 0,
- strlen($password),
- $password
- );
-
- if (!defined('NET_SSH2_LOGGING')) {
- $logged = null;
- } else {
- $logged = pack(
- 'CNa*Na*Na*CNa*',
- NET_SSH2_MSG_USERAUTH_REQUEST,
- strlen('username'),
- 'username',
- strlen('ssh-connection'),
- 'ssh-connection',
- strlen('password'),
- 'password',
- 0,
- strlen('password'),
- 'password'
- );
- }
- if (!$this->_send_binary_packet($packet, $logged)) {
- return false;
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- extract(unpack('Ctype', $this->_string_shift($response, 1)));
- switch ($type) {
- case NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ:
- if (defined('NET_SSH2_LOGGING')) {
- $this->message_number_log[count($this->message_number_log) - 1] = 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ';
- }
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- $this->errors[] = 'SSH_MSG_USERAUTH_PASSWD_CHANGEREQ: ' . utf8_decode($this->_string_shift($response, $length));
- return $this->_disconnect(NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER);
- case NET_SSH2_MSG_USERAUTH_FAILURE:
-
-
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- $auth_methods = explode(',', $this->_string_shift($response, $length));
- extract(unpack('Cpartial_success', $this->_string_shift($response, 1)));
- $partial_success = $partial_success != 0;
- if (!$partial_success && in_array('keyboard-interactive', $auth_methods)) {
- if ($this->_keyboard_interactive_login($username, $password)) {
- $this->bitmap |= self::MASK_LOGIN;
- return true;
- }
- return false;
- }
- return false;
- case NET_SSH2_MSG_USERAUTH_SUCCESS:
- $this->bitmap |= self::MASK_LOGIN;
- return true;
- }
- return false;
- }
-
- function _keyboard_interactive_login($username, $password)
- {
- $packet = pack(
- 'CNa*Na*Na*Na*Na*',
- NET_SSH2_MSG_USERAUTH_REQUEST,
- strlen($username),
- $username,
- strlen('ssh-connection'),
- 'ssh-connection',
- strlen('keyboard-interactive'),
- 'keyboard-interactive',
- 0,
- '',
- 0,
- ''
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- return $this->_keyboard_interactive_process($password);
- }
-
- function _keyboard_interactive_process()
- {
- $responses = func_get_args();
- if (strlen($this->last_interactive_response)) {
- $response = $this->last_interactive_response;
- } else {
- $orig = $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- }
- extract(unpack('Ctype', $this->_string_shift($response, 1)));
- switch ($type) {
- case NET_SSH2_MSG_USERAUTH_INFO_REQUEST:
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- $this->_string_shift($response, $length);
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- $this->_string_shift($response, $length);
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- $this->_string_shift($response, $length);
- extract(unpack('Nnum_prompts', $this->_string_shift($response, 4)));
- for ($i = 0; $i < count($responses); $i++) {
- if (is_array($responses[$i])) {
- foreach ($responses[$i] as $key => $value) {
- $this->keyboard_requests_responses[$key] = $value;
- }
- unset($responses[$i]);
- }
- }
- $responses = array_values($responses);
- if (isset($this->keyboard_requests_responses)) {
- for ($i = 0; $i < $num_prompts; $i++) {
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
-
- $prompt = $this->_string_shift($response, $length);
-
- foreach ($this->keyboard_requests_responses as $key => $value) {
- if (substr($prompt, 0, strlen($key)) == $key) {
- $responses[] = $value;
- break;
- }
- }
- }
- }
-
- if (strlen($this->last_interactive_response)) {
- $this->last_interactive_response = '';
- } elseif (defined('NET_SSH2_LOGGING')) {
- $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
- 'UNKNOWN',
- 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST',
- $this->message_number_log[count($this->message_number_log) - 1]
- );
- }
- if (!count($responses) && $num_prompts) {
- $this->last_interactive_response = $orig;
- return false;
- }
-
-
- $packet = $logged = pack('CN', NET_SSH2_MSG_USERAUTH_INFO_RESPONSE, count($responses));
- for ($i = 0; $i < count($responses); $i++) {
- $packet.= pack('Na*', strlen($responses[$i]), $responses[$i]);
- $logged.= pack('Na*', strlen('dummy-answer'), 'dummy-answer');
- }
- if (!$this->_send_binary_packet($packet, $logged)) {
- return false;
- }
- if (defined('NET_SSH2_LOGGING') && NET_SSH2_LOGGING == self::LOG_COMPLEX) {
- $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
- 'UNKNOWN',
- 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE',
- $this->message_number_log[count($this->message_number_log) - 1]
- );
- }
-
-
-
- return $this->_keyboard_interactive_process();
- case NET_SSH2_MSG_USERAUTH_SUCCESS:
- return true;
- case NET_SSH2_MSG_USERAUTH_FAILURE:
- return false;
- }
- return false;
- }
-
- function _ssh_agent_login($username, $agent)
- {
- $this->agent = $agent;
- $keys = $agent->requestIdentities();
- foreach ($keys as $key) {
- if ($this->_privatekey_login($username, $key)) {
- return true;
- }
- }
- return false;
- }
-
- function _privatekey_login($username, $privatekey)
- {
-
- $publickey = $privatekey->getPublicKey('Raw');
- if ($publickey === false) {
- return false;
- }
- $publickey = array(
- 'e' => $publickey['e']->toBytes(true),
- 'n' => $publickey['n']->toBytes(true)
- );
- $publickey = pack(
- 'Na*Na*Na*',
- strlen('ssh-rsa'),
- 'ssh-rsa',
- strlen($publickey['e']),
- $publickey['e'],
- strlen($publickey['n']),
- $publickey['n']
- );
- $part1 = pack(
- 'CNa*Na*Na*',
- NET_SSH2_MSG_USERAUTH_REQUEST,
- strlen($username),
- $username,
- strlen('ssh-connection'),
- 'ssh-connection',
- strlen('publickey'),
- 'publickey'
- );
- $part2 = pack('Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publickey), $publickey);
- $packet = $part1 . chr(0) . $part2;
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- extract(unpack('Ctype', $this->_string_shift($response, 1)));
- switch ($type) {
- case NET_SSH2_MSG_USERAUTH_FAILURE:
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- $this->errors[] = 'SSH_MSG_USERAUTH_FAILURE: ' . $this->_string_shift($response, $length);
- return false;
- case NET_SSH2_MSG_USERAUTH_PK_OK:
-
-
- if (defined('NET_SSH2_LOGGING') && NET_SSH2_LOGGING == self::LOG_COMPLEX) {
- $this->message_number_log[count($this->message_number_log) - 1] = str_replace(
- 'UNKNOWN',
- 'NET_SSH2_MSG_USERAUTH_PK_OK',
- $this->message_number_log[count($this->message_number_log) - 1]
- );
- }
- }
- $packet = $part1 . chr(1) . $part2;
- $privatekey->setHash('sha1');
- $signature = $privatekey->sign(pack('Na*a*', strlen($this->session_id), $this->session_id, $packet), RSA::PADDING_PKCS1);
- $signature = pack('Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($signature), $signature);
- $packet.= pack('Na*', strlen($signature), $signature);
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- extract(unpack('Ctype', $this->_string_shift($response, 1)));
- switch ($type) {
- case NET_SSH2_MSG_USERAUTH_FAILURE:
-
- return false;
- case NET_SSH2_MSG_USERAUTH_SUCCESS:
- $this->bitmap |= self::MASK_LOGIN;
- return true;
- }
- return false;
- }
-
- function setTimeout($timeout)
- {
- $this->timeout = $this->curTimeout = $timeout;
- }
-
- function getStdError()
- {
- return $this->stdErrorLog;
- }
-
- function exec($command, $callback = null)
- {
- $this->curTimeout = $this->timeout;
- $this->is_timeout = false;
- $this->stdErrorLog = '';
- if (!($this->bitmap & self::MASK_LOGIN)) {
- return false;
- }
-
-
-
-
- $this->window_size_server_to_client[self::CHANNEL_EXEC] = $this->window_size;
-
-
- $packet_size = 0x4000;
- $packet = pack(
- 'CNa*N3',
- NET_SSH2_MSG_CHANNEL_OPEN,
- strlen('session'),
- 'session',
- self::CHANNEL_EXEC,
- $this->window_size_server_to_client[self::CHANNEL_EXEC],
- $packet_size
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $this->channel_status[self::CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_OPEN;
- $response = $this->_get_channel_packet(self::CHANNEL_EXEC);
- if ($response === false) {
- return false;
- }
- if ($this->request_pty === true) {
- $terminal_modes = pack('C', NET_SSH2_TTY_OP_END);
- $packet = pack(
- 'CNNa*CNa*N5a*',
- NET_SSH2_MSG_CHANNEL_REQUEST,
- $this->server_channels[self::CHANNEL_EXEC],
- strlen('pty-req'),
- 'pty-req',
- 1,
- strlen('vt100'),
- 'vt100',
- $this->windowColumns,
- $this->windowRows,
- 0,
- 0,
- strlen($terminal_modes),
- $terminal_modes
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- list(, $type) = unpack('C', $this->_string_shift($response, 1));
- switch ($type) {
- case NET_SSH2_MSG_CHANNEL_SUCCESS:
- break;
- case NET_SSH2_MSG_CHANNEL_FAILURE:
- default:
- $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
- throw new \RuntimeException('Unable to request pseudo-terminal');
- }
- $this->in_request_pty_exec = true;
- }
-
-
-
-
-
-
-
-
- $packet = pack(
- 'CNNa*CNa*',
- NET_SSH2_MSG_CHANNEL_REQUEST,
- $this->server_channels[self::CHANNEL_EXEC],
- strlen('exec'),
- 'exec',
- 1,
- strlen($command),
- $command
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $this->channel_status[self::CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_REQUEST;
- $response = $this->_get_channel_packet(self::CHANNEL_EXEC);
- if ($response === false) {
- return false;
- }
- $this->channel_status[self::CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_DATA;
- if ($callback === false || $this->in_request_pty_exec) {
- return true;
- }
- $output = '';
- while (true) {
- $temp = $this->_get_channel_packet(self::CHANNEL_EXEC);
- switch (true) {
- case $temp === true:
- return is_callable($callback) ? true : $output;
- case $temp === false:
- return false;
- default:
- if (is_callable($callback)) {
- if (call_user_func($callback, $temp) === true) {
- $this->_close_channel(self::CHANNEL_EXEC);
- return true;
- }
- } else {
- $output.= $temp;
- }
- }
- }
- }
-
- function _initShell()
- {
- if ($this->in_request_pty_exec === true) {
- return true;
- }
- $this->window_size_server_to_client[self::CHANNEL_SHELL] = $this->window_size;
- $packet_size = 0x4000;
- $packet = pack(
- 'CNa*N3',
- NET_SSH2_MSG_CHANNEL_OPEN,
- strlen('session'),
- 'session',
- self::CHANNEL_SHELL,
- $this->window_size_server_to_client[self::CHANNEL_SHELL],
- $packet_size
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $this->channel_status[self::CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_OPEN;
- $response = $this->_get_channel_packet(self::CHANNEL_SHELL);
- if ($response === false) {
- return false;
- }
- $terminal_modes = pack('C', NET_SSH2_TTY_OP_END);
- $packet = pack(
- 'CNNa*CNa*N5a*',
- NET_SSH2_MSG_CHANNEL_REQUEST,
- $this->server_channels[self::CHANNEL_SHELL],
- strlen('pty-req'),
- 'pty-req',
- 1,
- strlen('vt100'),
- 'vt100',
- $this->windowColumns,
- $this->windowRows,
- 0,
- 0,
- strlen($terminal_modes),
- $terminal_modes
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- list(, $type) = unpack('C', $this->_string_shift($response, 1));
- switch ($type) {
- case NET_SSH2_MSG_CHANNEL_SUCCESS:
-
- case NET_SSH2_MSG_CHANNEL_FAILURE:
- break;
- default:
- $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
- throw new \UnexpectedValueException('Unable to request pseudo-terminal');
- }
- $packet = pack(
- 'CNNa*C',
- NET_SSH2_MSG_CHANNEL_REQUEST,
- $this->server_channels[self::CHANNEL_SHELL],
- strlen('shell'),
- 'shell',
- 1
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $this->channel_status[self::CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_REQUEST;
- $response = $this->_get_channel_packet(self::CHANNEL_SHELL);
- if ($response === false) {
- return false;
- }
- $this->channel_status[self::CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_DATA;
- $this->bitmap |= self::MASK_SHELL;
- return true;
- }
-
- function _get_interactive_channel()
- {
- switch (true) {
- case $this->in_subsystem:
- return self::CHANNEL_SUBSYSTEM;
- case $this->in_request_pty_exec:
- return self::CHANNEL_EXEC;
- default:
- return self::CHANNEL_SHELL;
- }
- }
-
- function _get_open_channel()
- {
- $channel = self::CHANNEL_EXEC;
- do {
- if (isset($this->channel_status[$channel]) && $this->channel_status[$channel] == NET_SSH2_MSG_CHANNEL_OPEN) {
- return $channel;
- }
- } while ($channel++ < self::CHANNEL_SUBSYSTEM);
- return false;
- }
-
- function read($expect = '', $mode = self::READ_SIMPLE)
- {
- $this->curTimeout = $this->timeout;
- $this->is_timeout = false;
- if (!($this->bitmap & self::MASK_LOGIN)) {
- throw new \RuntimeException('Operation disallowed prior to login()');
- }
- if (!($this->bitmap & self::MASK_SHELL) && !$this->_initShell()) {
- throw new \RuntimeException('Unable to initiate an interactive shell session');
- }
- $channel = $this->_get_interactive_channel();
- $match = $expect;
- while (true) {
- if ($mode == self::READ_REGEX) {
- preg_match($expect, substr($this->interactiveBuffer, -1024), $matches);
- $match = isset($matches[0]) ? $matches[0] : '';
- }
- $pos = strlen($match) ? strpos($this->interactiveBuffer, $match) : false;
- if ($pos !== false) {
- return $this->_string_shift($this->interactiveBuffer, $pos + strlen($match));
- }
- $response = $this->_get_channel_packet($channel);
- if (is_bool($response)) {
- $this->in_request_pty_exec = false;
- return $response ? $this->_string_shift($this->interactiveBuffer, strlen($this->interactiveBuffer)) : false;
- }
- $this->interactiveBuffer.= $response;
- }
- }
-
- function write($cmd)
- {
- if (!($this->bitmap & self::MASK_LOGIN)) {
- throw new \RuntimeException('Operation disallowed prior to login()');
- }
- if (!($this->bitmap & self::MASK_SHELL) && !$this->_initShell()) {
- throw new \RuntimeException('Unable to initiate an interactive shell session');
- }
- return $this->_send_channel_packet($this->_get_interactive_channel(), $cmd);
- }
-
- function startSubsystem($subsystem)
- {
- $this->window_size_server_to_client[self::CHANNEL_SUBSYSTEM] = $this->window_size;
- $packet = pack(
- 'CNa*N3',
- NET_SSH2_MSG_CHANNEL_OPEN,
- strlen('session'),
- 'session',
- self::CHANNEL_SUBSYSTEM,
- $this->window_size,
- 0x4000
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $this->channel_status[self::CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_OPEN;
- $response = $this->_get_channel_packet(self::CHANNEL_SUBSYSTEM);
- if ($response === false) {
- return false;
- }
- $packet = pack(
- 'CNNa*CNa*',
- NET_SSH2_MSG_CHANNEL_REQUEST,
- $this->server_channels[self::CHANNEL_SUBSYSTEM],
- strlen('subsystem'),
- 'subsystem',
- 1,
- strlen($subsystem),
- $subsystem
- );
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $this->channel_status[self::CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_REQUEST;
- $response = $this->_get_channel_packet(self::CHANNEL_SUBSYSTEM);
- if ($response === false) {
- return false;
- }
- $this->channel_status[self::CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_DATA;
- $this->bitmap |= self::MASK_SHELL;
- $this->in_subsystem = true;
- return true;
- }
-
- function stopSubsystem()
- {
- $this->in_subsystem = false;
- $this->_close_channel(self::CHANNEL_SUBSYSTEM);
- return true;
- }
-
- function reset()
- {
- $this->_close_channel($this->_get_interactive_channel());
- }
-
- function isTimeout()
- {
- return $this->is_timeout;
- }
-
- function disconnect()
- {
- $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
- if (isset($this->realtime_log_file) && is_resource($this->realtime_log_file)) {
- fclose($this->realtime_log_file);
- }
- unset(self::$connections[$this->getResourceId()]);
- }
-
- function __destruct()
- {
- $this->disconnect();
- }
-
- function isConnected()
- {
- return (bool) ($this->bitmap & self::MASK_CONNECTED);
- }
-
- function isAuthenticated()
- {
- return (bool) ($this->bitmap & self::MASK_LOGIN);
- }
-
- function _get_binary_packet()
- {
- if (!is_resource($this->fsock) || feof($this->fsock)) {
- $this->bitmap = 0;
- throw new \RuntimeException('Connection closed prematurely');
- }
- $start = microtime(true);
- $raw = stream_get_contents($this->fsock, $this->decrypt_block_size);
- if (!strlen($raw)) {
- return '';
- }
- if ($this->decrypt !== false) {
- $raw = $this->decrypt->decrypt($raw);
- }
- if ($raw === false) {
- throw new \RuntimeException('Unable to decrypt content');
- }
- extract(unpack('Npacket_length/Cpadding_length', $this->_string_shift($raw, 5)));
- $remaining_length = $packet_length + 4 - $this->decrypt_block_size;
-
-
-
- if ($remaining_length < -$this->decrypt_block_size || $remaining_length > 0x9000 || $remaining_length % $this->decrypt_block_size != 0) {
- throw new \RuntimeException('Invalid size');
- }
- $buffer = '';
- while ($remaining_length > 0) {
- $temp = stream_get_contents($this->fsock, $remaining_length);
- if ($temp === false || feof($this->fsock)) {
- $this->bitmap = 0;
- throw new \RuntimeException('Error reading from socket');
- }
- $buffer.= $temp;
- $remaining_length-= strlen($temp);
- }
- $stop = microtime(true);
- if (strlen($buffer)) {
- $raw.= $this->decrypt !== false ? $this->decrypt->decrypt($buffer) : $buffer;
- }
- $payload = $this->_string_shift($raw, $packet_length - $padding_length - 1);
- $padding = $this->_string_shift($raw, $padding_length);
- if ($this->hmac_check !== false) {
- $hmac = stream_get_contents($this->fsock, $this->hmac_size);
- if ($hmac === false || strlen($hmac) != $this->hmac_size) {
- $this->bitmap = 0;
- throw new \RuntimeException('Error reading socket');
- } elseif ($hmac != $this->hmac_check->hash(pack('NNCa*', $this->get_seq_no, $packet_length, $padding_length, $payload . $padding))) {
- throw new \RuntimeException('Invalid HMAC');
- }
- }
-
-
-
- $this->get_seq_no++;
- if (defined('NET_SSH2_LOGGING')) {
- $current = microtime(true);
- $message_number = isset($this->message_numbers[ord($payload[0])]) ? $this->message_numbers[ord($payload[0])] : 'UNKNOWN (' . ord($payload[0]) . ')';
- $message_number = '<- ' . $message_number .
- ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)';
- $this->_append_log($message_number, $payload);
- $this->last_packet = $current;
- }
- return $this->_filter($payload);
- }
-
- function _filter($payload)
- {
- switch (ord($payload[0])) {
- case NET_SSH2_MSG_DISCONNECT:
- $this->_string_shift($payload, 1);
- extract(unpack('Nreason_code/Nlength', $this->_string_shift($payload, 8)));
- $this->errors[] = 'SSH_MSG_DISCONNECT: ' . $this->disconnect_reasons[$reason_code] . "\r\n" . utf8_decode($this->_string_shift($payload, $length));
- $this->bitmap = 0;
- return false;
- case NET_SSH2_MSG_IGNORE:
- $payload = $this->_get_binary_packet();
- break;
- case NET_SSH2_MSG_DEBUG:
- $this->_string_shift($payload, 2);
- extract(unpack('Nlength', $this->_string_shift($payload, 4)));
- $this->errors[] = 'SSH_MSG_DEBUG: ' . utf8_decode($this->_string_shift($payload, $length));
- $payload = $this->_get_binary_packet();
- break;
- case NET_SSH2_MSG_UNIMPLEMENTED:
- return false;
- case NET_SSH2_MSG_KEXINIT:
- if ($this->session_id !== false) {
- if (!$this->_key_exchange($payload)) {
- $this->bitmap = 0;
- return false;
- }
- $payload = $this->_get_binary_packet();
- }
- }
-
- if (($this->bitmap & self::MASK_CONNECTED) && !($this->bitmap & self::MASK_LOGIN) && ord($payload[0]) == NET_SSH2_MSG_USERAUTH_BANNER) {
- $this->_string_shift($payload, 1);
- extract(unpack('Nlength', $this->_string_shift($payload, 4)));
- $this->banner_message = utf8_decode($this->_string_shift($payload, $length));
- $payload = $this->_get_binary_packet();
- }
-
- if (($this->bitmap & self::MASK_CONNECTED) && ($this->bitmap & self::MASK_LOGIN)) {
- switch (ord($payload[0])) {
- case NET_SSH2_MSG_GLOBAL_REQUEST:
- extract(unpack('Nlength', $this->_string_shift($payload, 4)));
- $this->errors[] = 'SSH_MSG_GLOBAL_REQUEST: ' . $this->_string_shift($payload, $length);
- if (!$this->_send_binary_packet(pack('C', NET_SSH2_MSG_REQUEST_FAILURE))) {
- return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
- }
- $payload = $this->_get_binary_packet();
- break;
- case NET_SSH2_MSG_CHANNEL_OPEN:
- $this->_string_shift($payload, 1);
- extract(unpack('Nlength', $this->_string_shift($payload, 4)));
- $data = $this->_string_shift($payload, $length);
- extract(unpack('Nserver_channel', $this->_string_shift($payload, 4)));
- switch ($data) {
- case 'auth-agent':
- case 'auth-agent@openssh.com':
- if (isset($this->agent)) {
- $new_channel = self::CHANNEL_AGENT_FORWARD;
- extract(unpack('Nremote_window_size', $this->_string_shift($payload, 4)));
- extract(unpack('Nremote_maximum_packet_size', $this->_string_shift($payload, 4)));
- $this->packet_size_client_to_server[$new_channel] = $remote_window_size;
- $this->window_size_server_to_client[$new_channel] = $remote_maximum_packet_size;
- $this->window_size_client_to_server[$new_channel] = $this->window_size;
- $packet_size = 0x4000;
- $packet = pack(
- 'CN4',
- NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION,
- $server_channel,
- $new_channel,
- $packet_size,
- $packet_size
- );
- $this->server_channels[$new_channel] = $server_channel;
- $this->channel_status[$new_channel] = NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION;
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- }
- break;
- default:
- $packet = pack(
- 'CN3a*Na*',
- NET_SSH2_MSG_REQUEST_FAILURE,
- $server_channel,
- NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED,
- 0,
- '',
- 0,
- ''
- );
- if (!$this->_send_binary_packet($packet)) {
- return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
- }
- }
- $payload = $this->_get_binary_packet();
- break;
- case NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST:
- $this->_string_shift($payload, 1);
- extract(unpack('Nchannel', $this->_string_shift($payload, 4)));
- extract(unpack('Nwindow_size', $this->_string_shift($payload, 4)));
- $this->window_size_client_to_server[$channel]+= $window_size;
- $payload = ($this->bitmap & self::MASK_WINDOW_ADJUST) ? true : $this->_get_binary_packet();
- }
- }
- return $payload;
- }
-
- function enableQuietMode()
- {
- $this->quiet_mode = true;
- }
-
- function disableQuietMode()
- {
- $this->quiet_mode = false;
- }
-
- function isQuietModeEnabled()
- {
- return $this->quiet_mode;
- }
-
- function enablePTY()
- {
- $this->request_pty = true;
- }
-
- function disablePTY()
- {
- $this->request_pty = false;
- }
-
- function isPTYEnabled()
- {
- return $this->request_pty;
- }
-
- function _get_channel_packet($client_channel, $skip_extended = false)
- {
- if (!empty($this->channel_buffers[$client_channel])) {
- return array_shift($this->channel_buffers[$client_channel]);
- }
- while (true) {
- if ($this->curTimeout) {
- if ($this->curTimeout < 0) {
- $this->is_timeout = true;
- return true;
- }
- $read = array($this->fsock);
- $write = $except = null;
- $start = microtime(true);
- $sec = floor($this->curTimeout);
- $usec = 1000000 * ($this->curTimeout - $sec);
-
- if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) {
- $this->is_timeout = true;
- return true;
- }
- $elapsed = microtime(true) - $start;
- $this->curTimeout-= $elapsed;
- }
- $response = $this->_get_binary_packet();
- if ($response === false) {
- throw new \RuntimeException('Connection closed by server');
- }
- if ($client_channel == -1 && $response === true) {
- return true;
- }
- if (!strlen($response)) {
- return '';
- }
- extract(unpack('Ctype', $this->_string_shift($response, 1)));
- if ($type == NET_SSH2_MSG_CHANNEL_OPEN) {
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- } else {
- extract(unpack('Nchannel', $this->_string_shift($response, 4)));
- }
-
- if (isset($channel) && isset($this->channel_status[$channel]) && isset($this->window_size_server_to_client[$channel])) {
- $this->window_size_server_to_client[$channel]-= strlen($response);
-
- if ($this->window_size_server_to_client[$channel] < 0) {
- $packet = pack('CNN', NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST, $this->server_channels[$channel], $this->window_size);
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- $this->window_size_server_to_client[$channel]+= $this->window_size;
- }
- switch ($this->channel_status[$channel]) {
- case NET_SSH2_MSG_CHANNEL_OPEN:
- switch ($type) {
- case NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
- extract(unpack('Nserver_channel', $this->_string_shift($response, 4)));
- $this->server_channels[$channel] = $server_channel;
- extract(unpack('Nwindow_size', $this->_string_shift($response, 4)));
- if ($window_size < 0) {
- $window_size&= 0x7FFFFFFF;
- $window_size+= 0x80000000;
- }
- $this->window_size_client_to_server[$channel] = $window_size;
- $temp = unpack('Npacket_size_client_to_server', $this->_string_shift($response, 4));
- $this->packet_size_client_to_server[$channel] = $temp['packet_size_client_to_server'];
- $result = $client_channel == $channel ? true : $this->_get_channel_packet($client_channel, $skip_extended);
- $this->_on_channel_open();
- return $result;
-
- default:
- $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
- throw new \RuntimeException('Unable to open channel');
- }
- break;
- case NET_SSH2_MSG_CHANNEL_REQUEST:
- switch ($type) {
- case NET_SSH2_MSG_CHANNEL_SUCCESS:
- return true;
- case NET_SSH2_MSG_CHANNEL_FAILURE:
- return false;
- default:
- $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
- throw new \RuntimeException('Unable to fulfill channel request');
- }
- case NET_SSH2_MSG_CHANNEL_CLOSE:
- return $type == NET_SSH2_MSG_CHANNEL_CLOSE ? true : $this->_get_channel_packet($client_channel, $skip_extended);
- }
- }
-
- switch ($type) {
- case NET_SSH2_MSG_CHANNEL_DATA:
-
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- $data = $this->_string_shift($response, $length);
- if ($channel == self::CHANNEL_AGENT_FORWARD) {
- $agent_response = $this->agent->_forward_data($data);
- if (!is_bool($agent_response)) {
- $this->_send_channel_packet($channel, $agent_response);
- }
- break;
- }
- if ($client_channel == $channel) {
- return $data;
- }
- if (!isset($this->channel_buffers[$channel])) {
- $this->channel_buffers[$channel] = array();
- }
- $this->channel_buffers[$channel][] = $data;
- break;
- case NET_SSH2_MSG_CHANNEL_EXTENDED_DATA:
-
-
- extract(unpack('Ndata_type_code/Nlength', $this->_string_shift($response, 8)));
- $data = $this->_string_shift($response, $length);
- $this->stdErrorLog.= $data;
- if ($skip_extended || $this->quiet_mode) {
- break;
- }
- if ($client_channel == $channel) {
- return $data;
- }
- if (!isset($this->channel_buffers[$channel])) {
- $this->channel_buffers[$channel] = array();
- }
- $this->channel_buffers[$channel][] = $data;
- break;
- case NET_SSH2_MSG_CHANNEL_REQUEST:
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- $value = $this->_string_shift($response, $length);
- switch ($value) {
- case 'exit-signal':
- $this->_string_shift($response, 1);
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- $this->errors[] = 'SSH_MSG_CHANNEL_REQUEST (exit-signal): ' . $this->_string_shift($response, $length);
- $this->_string_shift($response, 1);
- extract(unpack('Nlength', $this->_string_shift($response, 4)));
- if ($length) {
- $this->errors[count($this->errors)].= "\r\n" . $this->_string_shift($response, $length);
- }
- $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_EOF, $this->server_channels[$client_channel]));
- $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$channel]));
- $this->channel_status[$channel] = NET_SSH2_MSG_CHANNEL_EOF;
- break;
- case 'exit-status':
- extract(unpack('Cfalse/Nexit_status', $this->_string_shift($response, 5)));
- $this->exit_status = $exit_status;
-
-
- break;
- default:
-
-
- break;
- }
- break;
- case NET_SSH2_MSG_CHANNEL_CLOSE:
- $this->curTimeout = 0;
- if ($this->bitmap & self::MASK_SHELL) {
- $this->bitmap&= ~self::MASK_SHELL;
- }
- if ($this->channel_status[$channel] != NET_SSH2_MSG_CHANNEL_EOF) {
- $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$channel]));
- }
- $this->channel_status[$channel] = NET_SSH2_MSG_CHANNEL_CLOSE;
- return true;
- case NET_SSH2_MSG_CHANNEL_EOF:
- break;
- default:
- $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION);
- throw new \RuntimeException('Error reading channel data');
- }
- }
- }
-
- function _send_binary_packet($data, $logged = null)
- {
- if (!is_resource($this->fsock) || feof($this->fsock)) {
- $this->bitmap = 0;
- throw new \RuntimeException('Connection closed prematurely');
- }
-
-
-
-
-
-
- $packet_length = strlen($data) + 9;
-
- $packet_length+= (($this->encrypt_block_size - 1) * $packet_length) % $this->encrypt_block_size;
-
- $padding_length = $packet_length - strlen($data) - 5;
- $padding = Random::string($padding_length);
-
- $packet = pack('NCa*', $packet_length - 4, $padding_length, $data . $padding);
- $hmac = $this->hmac_create !== false ? $this->hmac_create->hash(pack('Na*', $this->send_seq_no, $packet)) : '';
- $this->send_seq_no++;
- if ($this->encrypt !== false) {
- $packet = $this->encrypt->encrypt($packet);
- }
- $packet.= $hmac;
- $start = microtime(true);
- $result = strlen($packet) == fputs($this->fsock, $packet);
- $stop = microtime(true);
- if (defined('NET_SSH2_LOGGING')) {
- $current = microtime(true);
- $message_number = isset($this->message_numbers[ord($data[0])]) ? $this->message_numbers[ord($data[0])] : 'UNKNOWN (' . ord($data[0]) . ')';
- $message_number = '-> ' . $message_number .
- ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)';
- $this->_append_log($message_number, isset($logged) ? $logged : $data);
- $this->last_packet = $current;
- }
- return $result;
- }
-
- function _append_log($message_number, $message)
- {
-
- if (strlen($message_number) > 2) {
- $this->_string_shift($message);
- }
- switch (NET_SSH2_LOGGING) {
-
- case self::LOG_SIMPLE:
- $this->message_number_log[] = $message_number;
- break;
-
- case self::LOG_COMPLEX:
- $this->message_number_log[] = $message_number;
- $this->log_size+= strlen($message);
- $this->message_log[] = $message;
- while ($this->log_size > self::LOG_MAX_SIZE) {
- $this->log_size-= strlen(array_shift($this->message_log));
- array_shift($this->message_number_log);
- }
- break;
-
-
-
- case self::LOG_REALTIME:
- switch (PHP_SAPI) {
- case 'cli':
- $start = $stop = "\r\n";
- break;
- default:
- $start = '<pre>';
- $stop = '</pre>';
- }
- echo $start . $this->_format_log(array($message), array($message_number)) . $stop;
- @flush();
- @ob_flush();
- break;
-
-
-
-
- case self::LOG_REALTIME_FILE:
- if (!isset($this->realtime_log_file)) {
-
- $filename = NET_SSH2_LOG_REALTIME_FILENAME;
- $fp = fopen($filename, 'w');
- $this->realtime_log_file = $fp;
- }
- if (!is_resource($this->realtime_log_file)) {
- break;
- }
- $entry = $this->_format_log(array($message), array($message_number));
- if ($this->realtime_log_wrap) {
- $temp = "<<< START >>>\r\n";
- $entry.= $temp;
- fseek($this->realtime_log_file, ftell($this->realtime_log_file) - strlen($temp));
- }
- $this->realtime_log_size+= strlen($entry);
- if ($this->realtime_log_size > self::LOG_MAX_SIZE) {
- fseek($this->realtime_log_file, 0);
- $this->realtime_log_size = strlen($entry);
- $this->realtime_log_wrap = true;
- }
- fputs($this->realtime_log_file, $entry);
- }
- }
-
- function _send_channel_packet($client_channel, $data)
- {
- while (strlen($data)) {
- if (!$this->window_size_client_to_server[$client_channel]) {
- $this->bitmap^= self::MASK_WINDOW_ADJUST;
-
- $this->_get_channel_packet(-1);
- $this->bitmap^= self::MASK_WINDOW_ADJUST;
- }
-
- $max_size = min(
- $this->packet_size_client_to_server[$client_channel],
- $this->window_size_client_to_server[$client_channel]
- );
- $temp = $this->_string_shift($data, $max_size);
- $packet = pack(
- 'CN2a*',
- NET_SSH2_MSG_CHANNEL_DATA,
- $this->server_channels[$client_channel],
- strlen($temp),
- $temp
- );
- $this->window_size_client_to_server[$client_channel]-= strlen($temp);
- if (!$this->_send_binary_packet($packet)) {
- return false;
- }
- }
- return true;
- }
-
- function _close_channel($client_channel, $want_reply = false)
- {
-
- $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_EOF, $this->server_channels[$client_channel]));
- if (!$want_reply) {
- $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$client_channel]));
- }
- $this->channel_status[$client_channel] = NET_SSH2_MSG_CHANNEL_CLOSE;
- $this->curTimeout = 0;
- while (!is_bool($this->_get_channel_packet($client_channel))) {
- }
- if ($want_reply) {
- $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$client_channel]));
- }
- if ($this->bitmap & self::MASK_SHELL) {
- $this->bitmap&= ~self::MASK_SHELL;
- }
- }
-
- function _disconnect($reason)
- {
- if ($this->bitmap & self::MASK_CONNECTED) {
- $data = pack('CNNa*Na*', NET_SSH2_MSG_DISCONNECT, $reason, 0, '', 0, '');
- $this->_send_binary_packet($data);
- $this->bitmap = 0;
- fclose($this->fsock);
- return false;
- }
- }
-
- function _string_shift(&$string, $index = 1)
- {
- $substr = substr($string, 0, $index);
- $string = substr($string, $index);
- return $substr;
- }
-
- function _define_array()
- {
- $args = func_get_args();
- foreach ($args as $arg) {
- foreach ($arg as $key => $value) {
- if (!defined($value)) {
- define($value, $key);
- } else {
- break 2;
- }
- }
- }
- }
-
- function getLog()
- {
- if (!defined('NET_SSH2_LOGGING')) {
- return false;
- }
- switch (NET_SSH2_LOGGING) {
- case self::LOG_SIMPLE:
- return $this->message_number_log;
- break;
- case self::LOG_COMPLEX:
- return $this->_format_log($this->message_log, $this->message_number_log);
- break;
- default:
- return false;
- }
- }
-
- function _format_log($message_log, $message_number_log)
- {
- $output = '';
- for ($i = 0; $i < count($message_log); $i++) {
- $output.= $message_number_log[$i] . "\r\n";
- $current_log = $message_log[$i];
- $j = 0;
- do {
- if (strlen($current_log)) {
- $output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 ';
- }
- $fragment = $this->_string_shift($current_log, $this->log_short_width);
- $hex = substr(preg_replace_callback('#.#s', array($this, '_format_log_helper'), $fragment), strlen($this->log_boundary));
-
-
-
- $raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment);
- $output.= str_pad($hex, $this->log_long_width - $this->log_short_width, ' ') . $raw . "\r\n";
- $j++;
- } while (strlen($current_log));
- $output.= "\r\n";
- }
- return $output;
- }
-
- function _format_log_helper($matches)
- {
- return $this->log_boundary . str_pad(dechex(ord($matches[0])), 2, '0', STR_PAD_LEFT);
- }
-
- function _on_channel_open()
- {
- if (isset($this->agent)) {
- $this->agent->_on_channel_open($this);
- }
- }
-
- function _array_intersect_first($array1, $array2)
- {
- foreach ($array1 as $value) {
- if (in_array($value, $array2)) {
- return $value;
- }
- }
- return false;
- }
-
- function getErrors()
- {
- return $this->errors;
- }
-
- function getLastError()
- {
- $count = count($this->errors);
- if ($count > 0) {
- return $this->errors[$count - 1];
- }
- }
-
- function getServerIdentification()
- {
- $this->_connect();
- return $this->server_identifier;
- }
-
- function getKexAlgorithms()
- {
- $this->_connect();
- return $this->kex_algorithms;
- }
-
- function getServerHostKeyAlgorithms()
- {
- $this->_connect();
- return $this->server_host_key_algorithms;
- }
-
- function getEncryptionAlgorithmsClient2Server()
- {
- $this->_connect();
- return $this->encryption_algorithms_client_to_server;
- }
-
- function getEncryptionAlgorithmsServer2Client()
- {
- $this->_connect();
- return $this->encryption_algorithms_server_to_client;
- }
-
- function getMACAlgorithmsClient2Server()
- {
- $this->_connect();
- return $this->mac_algorithms_client_to_server;
- }
-
- function getMACAlgorithmsServer2Client()
- {
- $this->_connect();
- return $this->mac_algorithms_server_to_client;
- }
-
- function getCompressionAlgorithmsClient2Server()
- {
- $this->_connect();
- return $this->compression_algorithms_client_to_server;
- }
-
- function getCompressionAlgorithmsServer2Client()
- {
- $this->_connect();
- return $this->compression_algorithms_server_to_client;
- }
-
- function getLanguagesServer2Client()
- {
- $this->_connect();
- return $this->languages_server_to_client;
- }
-
- function getLanguagesClient2Server()
- {
- $this->_connect();
- return $this->languages_client_to_server;
- }
-
- function getBannerMessage()
- {
- return $this->banner_message;
- }
-
- function getServerPublicHostKey()
- {
- if (!($this->bitmap & self::MASK_CONSTRUCTOR)) {
- if (!$this->_connect()) {
- return false;
- }
- }
- $signature = $this->signature;
- $server_public_host_key = $this->server_public_host_key;
- extract(unpack('Nlength', $this->_string_shift($server_public_host_key, 4)));
- $this->_string_shift($server_public_host_key, $length);
- if ($this->signature_validated) {
- return $this->bitmap ?
- $this->signature_format . ' ' . Base64::encode($this->server_public_host_key) :
- false;
- }
- $this->signature_validated = true;
- switch ($this->signature_format) {
- case 'ssh-dss':
- $zero = new BigInteger();
- $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
- $p = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
- $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
- $q = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
- $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
- $g = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
- $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
- $y = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
-
- $temp = unpack('Nlength', $this->_string_shift($signature, 4));
- if ($temp['length'] != 40) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new \RuntimeException('Invalid signature');
- }
- $r = new BigInteger($this->_string_shift($signature, 20), 256);
- $s = new BigInteger($this->_string_shift($signature, 20), 256);
- switch (true) {
- case $r->equals($zero):
- case $r->compare($q) >= 0:
- case $s->equals($zero):
- case $s->compare($q) >= 0:
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new \RuntimeException('Invalid signature');
- }
- $w = $s->modInverse($q);
- $u1 = $w->multiply(new BigInteger(sha1($this->exchange_hash), 16));
- list(, $u1) = $u1->divide($q);
- $u2 = $w->multiply($r);
- list(, $u2) = $u2->divide($q);
- $g = $g->modPow($u1, $p);
- $y = $y->modPow($u2, $p);
- $v = $g->multiply($y);
- list(, $v) = $v->divide($p);
- list(, $v) = $v->divide($q);
- if (!$v->equals($r)) {
-
- return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE);
- }
- break;
- case 'ssh-rsa':
- $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
- $e = new BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256);
- $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4));
- $rawN = $this->_string_shift($server_public_host_key, $temp['length']);
- $n = new BigInteger($rawN, -256);
- $nLength = strlen(ltrim($rawN, "\0"));
-
- $temp = unpack('Nlength', $this->_string_shift($signature, 4));
- $s = new BigInteger($this->_string_shift($signature, $temp['length']), 256);
-
-
-
-
- if ($s->compare(new BigInteger()) < 0 || $s->compare($n->subtract(new BigInteger(1))) > 0) {
- $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED);
- throw new \RuntimeException('Invalid signature');
- }
- $s = $s->modPow($e, $n);
- $s = $s->toBytes();
- $h = pack('N4H*', 0x00302130, 0x0906052B, 0x0E03021A, 0x05000414, sha1($this->exchange_hash));
- $h = chr(0x01) . str_repeat(chr(0xFF), $nLength - 2 - strlen($h)) . $h;
- if ($s != $h) {
-
- return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE);
- }
- break;
- default:
- $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE);
- throw new NoSupportedAlgorithmsException('Unsupported signature format');
- }
- return $this->signature_format . ' ' . Base64::encode($this->server_public_host_key);
- }
-
- function getExitStatus()
- {
- if (is_null($this->exit_status)) {
- return false;
- }
- return $this->exit_status;
- }
-
- function getWindowColumns()
- {
- return $this->windowColumns;
- }
-
- function getWindowRows()
- {
- return $this->windowRows;
- }
-
- function setWindowColumns($value)
- {
- $this->windowColumns = $value;
- }
-
- function setWindowRows($value)
- {
- $this->windowRows = $value;
- }
-
- function setWindowSize($columns = 80, $rows = 24)
- {
- $this->windowColumns = $columns;
- $this->windowRows = $rows;
- }
-
- function __toString()
- {
- return $this->getResourceId();
- }
-
- function getResourceId()
- {
- return '{' . spl_object_hash($this) . '}';
- }
-
- static function getConnectionByResourceId($id)
- {
- return isset(self::$connections[$id]) ? self::$connections[$id] : false;
- }
-
- static function getConnections()
- {
- return self::$connections;
- }
- }
|