ssh.c 211 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdarg.h>
  4. #include <assert.h>
  5. #include "putty.h"
  6. #include "tree234.h"
  7. #include "ssh.h"
  8. #ifndef FALSE
  9. #define FALSE 0
  10. #endif
  11. #ifndef TRUE
  12. #define TRUE 1
  13. #endif
  14. #define SSH1_MSG_DISCONNECT 1 /* 0x1 */
  15. #define SSH1_SMSG_PUBLIC_KEY 2 /* 0x2 */
  16. #define SSH1_CMSG_SESSION_KEY 3 /* 0x3 */
  17. #define SSH1_CMSG_USER 4 /* 0x4 */
  18. #define SSH1_CMSG_AUTH_RSA 6 /* 0x6 */
  19. #define SSH1_SMSG_AUTH_RSA_CHALLENGE 7 /* 0x7 */
  20. #define SSH1_CMSG_AUTH_RSA_RESPONSE 8 /* 0x8 */
  21. #define SSH1_CMSG_AUTH_PASSWORD 9 /* 0x9 */
  22. #define SSH1_CMSG_REQUEST_PTY 10 /* 0xa */
  23. #define SSH1_CMSG_WINDOW_SIZE 11 /* 0xb */
  24. #define SSH1_CMSG_EXEC_SHELL 12 /* 0xc */
  25. #define SSH1_CMSG_EXEC_CMD 13 /* 0xd */
  26. #define SSH1_SMSG_SUCCESS 14 /* 0xe */
  27. #define SSH1_SMSG_FAILURE 15 /* 0xf */
  28. #define SSH1_CMSG_STDIN_DATA 16 /* 0x10 */
  29. #define SSH1_SMSG_STDOUT_DATA 17 /* 0x11 */
  30. #define SSH1_SMSG_STDERR_DATA 18 /* 0x12 */
  31. #define SSH1_CMSG_EOF 19 /* 0x13 */
  32. #define SSH1_SMSG_EXIT_STATUS 20 /* 0x14 */
  33. #define SSH1_MSG_CHANNEL_OPEN_CONFIRMATION 21 /* 0x15 */
  34. #define SSH1_MSG_CHANNEL_OPEN_FAILURE 22 /* 0x16 */
  35. #define SSH1_MSG_CHANNEL_DATA 23 /* 0x17 */
  36. #define SSH1_MSG_CHANNEL_CLOSE 24 /* 0x18 */
  37. #define SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION 25 /* 0x19 */
  38. #define SSH1_SMSG_X11_OPEN 27 /* 0x1b */
  39. #define SSH1_CMSG_PORT_FORWARD_REQUEST 28 /* 0x1c */
  40. #define SSH1_MSG_PORT_OPEN 29 /* 0x1d */
  41. #define SSH1_CMSG_AGENT_REQUEST_FORWARDING 30 /* 0x1e */
  42. #define SSH1_SMSG_AGENT_OPEN 31 /* 0x1f */
  43. #define SSH1_MSG_IGNORE 32 /* 0x20 */
  44. #define SSH1_CMSG_EXIT_CONFIRMATION 33 /* 0x21 */
  45. #define SSH1_CMSG_X11_REQUEST_FORWARDING 34 /* 0x22 */
  46. #define SSH1_CMSG_AUTH_RHOSTS_RSA 35 /* 0x23 */
  47. #define SSH1_MSG_DEBUG 36 /* 0x24 */
  48. #define SSH1_CMSG_REQUEST_COMPRESSION 37 /* 0x25 */
  49. #define SSH1_CMSG_AUTH_TIS 39 /* 0x27 */
  50. #define SSH1_SMSG_AUTH_TIS_CHALLENGE 40 /* 0x28 */
  51. #define SSH1_CMSG_AUTH_TIS_RESPONSE 41 /* 0x29 */
  52. #define SSH1_CMSG_AUTH_CCARD 70 /* 0x46 */
  53. #define SSH1_SMSG_AUTH_CCARD_CHALLENGE 71 /* 0x47 */
  54. #define SSH1_CMSG_AUTH_CCARD_RESPONSE 72 /* 0x48 */
  55. #define SSH1_AUTH_TIS 5 /* 0x5 */
  56. #define SSH1_AUTH_CCARD 16 /* 0x10 */
  57. #define SSH1_PROTOFLAG_SCREEN_NUMBER 1 /* 0x1 */
  58. /* Mask for protoflags we will echo back to server if seen */
  59. #define SSH1_PROTOFLAGS_SUPPORTED 0 /* 0x1 */
  60. #define SSH2_MSG_DISCONNECT 1 /* 0x1 */
  61. #define SSH2_MSG_IGNORE 2 /* 0x2 */
  62. #define SSH2_MSG_UNIMPLEMENTED 3 /* 0x3 */
  63. #define SSH2_MSG_DEBUG 4 /* 0x4 */
  64. #define SSH2_MSG_SERVICE_REQUEST 5 /* 0x5 */
  65. #define SSH2_MSG_SERVICE_ACCEPT 6 /* 0x6 */
  66. #define SSH2_MSG_KEXINIT 20 /* 0x14 */
  67. #define SSH2_MSG_NEWKEYS 21 /* 0x15 */
  68. #define SSH2_MSG_KEXDH_INIT 30 /* 0x1e */
  69. #define SSH2_MSG_KEXDH_REPLY 31 /* 0x1f */
  70. #define SSH2_MSG_KEX_DH_GEX_REQUEST 30 /* 0x1e */
  71. #define SSH2_MSG_KEX_DH_GEX_GROUP 31 /* 0x1f */
  72. #define SSH2_MSG_KEX_DH_GEX_INIT 32 /* 0x20 */
  73. #define SSH2_MSG_KEX_DH_GEX_REPLY 33 /* 0x21 */
  74. #define SSH2_MSG_USERAUTH_REQUEST 50 /* 0x32 */
  75. #define SSH2_MSG_USERAUTH_FAILURE 51 /* 0x33 */
  76. #define SSH2_MSG_USERAUTH_SUCCESS 52 /* 0x34 */
  77. #define SSH2_MSG_USERAUTH_BANNER 53 /* 0x35 */
  78. #define SSH2_MSG_USERAUTH_PK_OK 60 /* 0x3c */
  79. #define SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ 60 /* 0x3c */
  80. #define SSH2_MSG_USERAUTH_INFO_REQUEST 60 /* 0x3c */
  81. #define SSH2_MSG_USERAUTH_INFO_RESPONSE 61 /* 0x3d */
  82. #define SSH2_MSG_GLOBAL_REQUEST 80 /* 0x50 */
  83. #define SSH2_MSG_REQUEST_SUCCESS 81 /* 0x51 */
  84. #define SSH2_MSG_REQUEST_FAILURE 82 /* 0x52 */
  85. #define SSH2_MSG_CHANNEL_OPEN 90 /* 0x5a */
  86. #define SSH2_MSG_CHANNEL_OPEN_CONFIRMATION 91 /* 0x5b */
  87. #define SSH2_MSG_CHANNEL_OPEN_FAILURE 92 /* 0x5c */
  88. #define SSH2_MSG_CHANNEL_WINDOW_ADJUST 93 /* 0x5d */
  89. #define SSH2_MSG_CHANNEL_DATA 94 /* 0x5e */
  90. #define SSH2_MSG_CHANNEL_EXTENDED_DATA 95 /* 0x5f */
  91. #define SSH2_MSG_CHANNEL_EOF 96 /* 0x60 */
  92. #define SSH2_MSG_CHANNEL_CLOSE 97 /* 0x61 */
  93. #define SSH2_MSG_CHANNEL_REQUEST 98 /* 0x62 */
  94. #define SSH2_MSG_CHANNEL_SUCCESS 99 /* 0x63 */
  95. #define SSH2_MSG_CHANNEL_FAILURE 100 /* 0x64 */
  96. /*
  97. * Packet type contexts, so that ssh2_pkt_type can correctly decode
  98. * the ambiguous type numbers back into the correct type strings.
  99. */
  100. #define SSH2_PKTCTX_DHGROUP1 0x0001
  101. #define SSH2_PKTCTX_DHGEX 0x0002
  102. #define SSH2_PKTCTX_PUBLICKEY 0x0010
  103. #define SSH2_PKTCTX_PASSWORD 0x0020
  104. #define SSH2_PKTCTX_KBDINTER 0x0040
  105. #define SSH2_PKTCTX_AUTH_MASK 0x00F0
  106. #define SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT 1 /* 0x1 */
  107. #define SSH2_DISCONNECT_PROTOCOL_ERROR 2 /* 0x2 */
  108. #define SSH2_DISCONNECT_KEY_EXCHANGE_FAILED 3 /* 0x3 */
  109. #define SSH2_DISCONNECT_HOST_AUTHENTICATION_FAILED 4 /* 0x4 */
  110. #define SSH2_DISCONNECT_MAC_ERROR 5 /* 0x5 */
  111. #define SSH2_DISCONNECT_COMPRESSION_ERROR 6 /* 0x6 */
  112. #define SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE 7 /* 0x7 */
  113. #define SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED 8 /* 0x8 */
  114. #define SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE 9 /* 0x9 */
  115. #define SSH2_DISCONNECT_CONNECTION_LOST 10 /* 0xa */
  116. #define SSH2_DISCONNECT_BY_APPLICATION 11 /* 0xb */
  117. #define SSH2_DISCONNECT_TOO_MANY_CONNECTIONS 12 /* 0xc */
  118. #define SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER 13 /* 0xd */
  119. #define SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE 14 /* 0xe */
  120. #define SSH2_DISCONNECT_ILLEGAL_USER_NAME 15 /* 0xf */
  121. static const char *const ssh2_disconnect_reasons[] = {
  122. NULL,
  123. "SSH_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT",
  124. "SSH_DISCONNECT_PROTOCOL_ERROR",
  125. "SSH_DISCONNECT_KEY_EXCHANGE_FAILED",
  126. "SSH_DISCONNECT_HOST_AUTHENTICATION_FAILED",
  127. "SSH_DISCONNECT_MAC_ERROR",
  128. "SSH_DISCONNECT_COMPRESSION_ERROR",
  129. "SSH_DISCONNECT_SERVICE_NOT_AVAILABLE",
  130. "SSH_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED",
  131. "SSH_DISCONNECT_HOST_KEY_NOT_VERIFIABLE",
  132. "SSH_DISCONNECT_CONNECTION_LOST",
  133. "SSH_DISCONNECT_BY_APPLICATION",
  134. "SSH_DISCONNECT_TOO_MANY_CONNECTIONS",
  135. "SSH_DISCONNECT_AUTH_CANCELLED_BY_USER",
  136. "SSH_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE",
  137. "SSH_DISCONNECT_ILLEGAL_USER_NAME",
  138. };
  139. #define SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED 1 /* 0x1 */
  140. #define SSH2_OPEN_CONNECT_FAILED 2 /* 0x2 */
  141. #define SSH2_OPEN_UNKNOWN_CHANNEL_TYPE 3 /* 0x3 */
  142. #define SSH2_OPEN_RESOURCE_SHORTAGE 4 /* 0x4 */
  143. #define SSH2_EXTENDED_DATA_STDERR 1 /* 0x1 */
  144. /*
  145. * Various remote-bug flags.
  146. */
  147. #define BUG_CHOKES_ON_SSH1_IGNORE 1
  148. #define BUG_SSH2_HMAC 2
  149. #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
  150. #define BUG_CHOKES_ON_RSA 8
  151. #define BUG_SSH2_RSA_PADDING 16
  152. #define BUG_SSH2_DERIVEKEY 32
  153. #define BUG_SSH2_DH_GEX 64
  154. #define BUG_SSH2_PK_SESSIONID 128
  155. #define translate(x) if (type == x) return #x
  156. #define translatec(x,ctx) if (type == x && (pkt_ctx & ctx)) return #x
  157. static char *ssh1_pkt_type(int type)
  158. {
  159. translate(SSH1_MSG_DISCONNECT);
  160. translate(SSH1_SMSG_PUBLIC_KEY);
  161. translate(SSH1_CMSG_SESSION_KEY);
  162. translate(SSH1_CMSG_USER);
  163. translate(SSH1_CMSG_AUTH_RSA);
  164. translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
  165. translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
  166. translate(SSH1_CMSG_AUTH_PASSWORD);
  167. translate(SSH1_CMSG_REQUEST_PTY);
  168. translate(SSH1_CMSG_WINDOW_SIZE);
  169. translate(SSH1_CMSG_EXEC_SHELL);
  170. translate(SSH1_CMSG_EXEC_CMD);
  171. translate(SSH1_SMSG_SUCCESS);
  172. translate(SSH1_SMSG_FAILURE);
  173. translate(SSH1_CMSG_STDIN_DATA);
  174. translate(SSH1_SMSG_STDOUT_DATA);
  175. translate(SSH1_SMSG_STDERR_DATA);
  176. translate(SSH1_CMSG_EOF);
  177. translate(SSH1_SMSG_EXIT_STATUS);
  178. translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
  179. translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
  180. translate(SSH1_MSG_CHANNEL_DATA);
  181. translate(SSH1_MSG_CHANNEL_CLOSE);
  182. translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
  183. translate(SSH1_SMSG_X11_OPEN);
  184. translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
  185. translate(SSH1_MSG_PORT_OPEN);
  186. translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
  187. translate(SSH1_SMSG_AGENT_OPEN);
  188. translate(SSH1_MSG_IGNORE);
  189. translate(SSH1_CMSG_EXIT_CONFIRMATION);
  190. translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
  191. translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
  192. translate(SSH1_MSG_DEBUG);
  193. translate(SSH1_CMSG_REQUEST_COMPRESSION);
  194. translate(SSH1_CMSG_AUTH_TIS);
  195. translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
  196. translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
  197. translate(SSH1_CMSG_AUTH_CCARD);
  198. translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
  199. translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
  200. return "unknown";
  201. }
  202. static char *ssh2_pkt_type(int pkt_ctx, int type)
  203. {
  204. translate(SSH2_MSG_DISCONNECT);
  205. translate(SSH2_MSG_IGNORE);
  206. translate(SSH2_MSG_UNIMPLEMENTED);
  207. translate(SSH2_MSG_DEBUG);
  208. translate(SSH2_MSG_SERVICE_REQUEST);
  209. translate(SSH2_MSG_SERVICE_ACCEPT);
  210. translate(SSH2_MSG_KEXINIT);
  211. translate(SSH2_MSG_NEWKEYS);
  212. translatec(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP1);
  213. translatec(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP1);
  214. translatec(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
  215. translatec(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
  216. translatec(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
  217. translatec(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
  218. translate(SSH2_MSG_USERAUTH_REQUEST);
  219. translate(SSH2_MSG_USERAUTH_FAILURE);
  220. translate(SSH2_MSG_USERAUTH_SUCCESS);
  221. translate(SSH2_MSG_USERAUTH_BANNER);
  222. translatec(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
  223. translatec(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
  224. translatec(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
  225. translatec(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
  226. translate(SSH2_MSG_GLOBAL_REQUEST);
  227. translate(SSH2_MSG_REQUEST_SUCCESS);
  228. translate(SSH2_MSG_REQUEST_FAILURE);
  229. translate(SSH2_MSG_CHANNEL_OPEN);
  230. translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
  231. translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
  232. translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  233. translate(SSH2_MSG_CHANNEL_DATA);
  234. translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
  235. translate(SSH2_MSG_CHANNEL_EOF);
  236. translate(SSH2_MSG_CHANNEL_CLOSE);
  237. translate(SSH2_MSG_CHANNEL_REQUEST);
  238. translate(SSH2_MSG_CHANNEL_SUCCESS);
  239. translate(SSH2_MSG_CHANNEL_FAILURE);
  240. return "unknown";
  241. }
  242. #undef translate
  243. #undef translatec
  244. #define GET_32BIT(cp) \
  245. (((unsigned long)(unsigned char)(cp)[0] << 24) | \
  246. ((unsigned long)(unsigned char)(cp)[1] << 16) | \
  247. ((unsigned long)(unsigned char)(cp)[2] << 8) | \
  248. ((unsigned long)(unsigned char)(cp)[3]))
  249. #define PUT_32BIT(cp, value) { \
  250. (cp)[0] = (unsigned char)((value) >> 24); \
  251. (cp)[1] = (unsigned char)((value) >> 16); \
  252. (cp)[2] = (unsigned char)((value) >> 8); \
  253. (cp)[3] = (unsigned char)(value); }
  254. /* Enumeration values for fields in SSH-1 packets */
  255. enum {
  256. PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
  257. /* These values are for communicating relevant semantics of
  258. * fields to the packet logging code. */
  259. PKTT_OTHER, PKTT_PASSWORD, PKTT_DATA
  260. };
  261. /*
  262. * Coroutine mechanics for the sillier bits of the code. If these
  263. * macros look impenetrable to you, you might find it helpful to
  264. * read
  265. *
  266. * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
  267. *
  268. * which explains the theory behind these macros.
  269. *
  270. * In particular, if you are getting `case expression not constant'
  271. * errors when building with MS Visual Studio, this is because MS's
  272. * Edit and Continue debugging feature causes their compiler to
  273. * violate ANSI C. To disable Edit and Continue debugging:
  274. *
  275. * - right-click ssh.c in the FileView
  276. * - click Settings
  277. * - select the C/C++ tab and the General category
  278. * - under `Debug info:', select anything _other_ than `Program
  279. * Database for Edit and Continue'.
  280. */
  281. #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
  282. #define crState(t) \
  283. struct t *s; \
  284. if (!ssh->t) ssh->t = snew(struct t); \
  285. s = ssh->t;
  286. #define crFinish(z) } *crLine = 0; return (z); }
  287. #define crFinishV } *crLine = 0; return; }
  288. #define crReturn(z) \
  289. do {\
  290. *crLine =__LINE__; return (z); case __LINE__:;\
  291. } while (0)
  292. #define crReturnV \
  293. do {\
  294. *crLine=__LINE__; return; case __LINE__:;\
  295. } while (0)
  296. #define crStop(z) do{ *crLine = 0; return (z); }while(0)
  297. #define crStopV do{ *crLine = 0; return; }while(0)
  298. #define crWaitUntil(c) do { crReturn(0); } while (!(c))
  299. #define crWaitUntilV(c) do { crReturnV; } while (!(c))
  300. typedef struct ssh_tag *Ssh;
  301. static void ssh2_pkt_init(Ssh, int pkt_type);
  302. static void ssh2_pkt_addbool(Ssh, unsigned char value);
  303. static void ssh2_pkt_adduint32(Ssh, unsigned long value);
  304. static void ssh2_pkt_addstring_start(Ssh);
  305. static void ssh2_pkt_addstring_str(Ssh, char *data);
  306. static void ssh2_pkt_addstring_data(Ssh, char *data, int len);
  307. static void ssh2_pkt_addstring(Ssh, char *data);
  308. static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
  309. static void ssh2_pkt_addmp(Ssh, Bignum b);
  310. static int ssh2_pkt_construct(Ssh);
  311. static void ssh2_pkt_send(Ssh);
  312. static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt);
  313. static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt);
  314. /*
  315. * Buffer management constants. There are several of these for
  316. * various different purposes:
  317. *
  318. * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
  319. * on a local data stream before we throttle the whole SSH
  320. * connection (in SSH1 only). Throttling the whole connection is
  321. * pretty drastic so we set this high in the hope it won't
  322. * happen very often.
  323. *
  324. * - SSH_MAX_BACKLOG is the amount of backlog that must build up
  325. * on the SSH connection itself before we defensively throttle
  326. * _all_ local data streams. This is pretty drastic too (though
  327. * thankfully unlikely in SSH2 since the window mechanism should
  328. * ensure that the server never has any need to throttle its end
  329. * of the connection), so we set this high as well.
  330. *
  331. * - OUR_V2_WINSIZE is the maximum window size we present on SSH2
  332. * channels.
  333. */
  334. #define SSH1_BUFFER_LIMIT 32768
  335. #define SSH_MAX_BACKLOG 32768
  336. #define OUR_V2_WINSIZE 16384
  337. const static struct ssh_kex *kex_algs[] = {
  338. &ssh_diffiehellman_gex,
  339. &ssh_diffiehellman
  340. };
  341. const static struct ssh_signkey *hostkey_algs[] = { &ssh_rsa, &ssh_dss };
  342. static void *nullmac_make_context(void)
  343. {
  344. return NULL;
  345. }
  346. static void nullmac_free_context(void *handle)
  347. {
  348. }
  349. static void nullmac_key(void *handle, unsigned char *key)
  350. {
  351. }
  352. static void nullmac_generate(void *handle, unsigned char *blk, int len,
  353. unsigned long seq)
  354. {
  355. }
  356. static int nullmac_verify(void *handle, unsigned char *blk, int len,
  357. unsigned long seq)
  358. {
  359. return 1;
  360. }
  361. const static struct ssh_mac ssh_mac_none = {
  362. nullmac_make_context, nullmac_free_context, nullmac_key,
  363. nullmac_generate, nullmac_verify, "none", 0
  364. };
  365. const static struct ssh_mac *macs[] = {
  366. &ssh_sha1, &ssh_md5, &ssh_mac_none
  367. };
  368. const static struct ssh_mac *buggymacs[] = {
  369. &ssh_sha1_buggy, &ssh_md5, &ssh_mac_none
  370. };
  371. static void *ssh_comp_none_init(void)
  372. {
  373. return NULL;
  374. }
  375. static void ssh_comp_none_cleanup(void *handle)
  376. {
  377. }
  378. static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
  379. unsigned char **outblock, int *outlen)
  380. {
  381. return 0;
  382. }
  383. static int ssh_comp_none_disable(void *handle)
  384. {
  385. return 0;
  386. }
  387. const static struct ssh_compress ssh_comp_none = {
  388. "none",
  389. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
  390. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
  391. ssh_comp_none_disable, NULL
  392. };
  393. extern const struct ssh_compress ssh_zlib;
  394. const static struct ssh_compress *compressions[] = {
  395. &ssh_zlib, &ssh_comp_none
  396. };
  397. enum { /* channel types */
  398. CHAN_MAINSESSION,
  399. CHAN_X11,
  400. CHAN_AGENT,
  401. CHAN_SOCKDATA,
  402. CHAN_SOCKDATA_DORMANT /* one the remote hasn't confirmed */
  403. };
  404. /*
  405. * 2-3-4 tree storing channels.
  406. */
  407. struct ssh_channel {
  408. Ssh ssh; /* pointer back to main context */
  409. unsigned remoteid, localid;
  410. int type;
  411. /*
  412. * In SSH1, this value contains four bits:
  413. *
  414. * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
  415. * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
  416. * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
  417. * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
  418. *
  419. * A channel is completely finished with when all four bits are set.
  420. */
  421. int closes;
  422. union {
  423. struct ssh1_data_channel {
  424. int throttling;
  425. } v1;
  426. struct ssh2_data_channel {
  427. bufchain outbuffer;
  428. unsigned remwindow, remmaxpkt;
  429. unsigned locwindow;
  430. } v2;
  431. } v;
  432. union {
  433. struct ssh_agent_channel {
  434. unsigned char *message;
  435. unsigned char msglen[4];
  436. unsigned lensofar, totallen;
  437. } a;
  438. struct ssh_x11_channel {
  439. Socket s;
  440. } x11;
  441. struct ssh_pfd_channel {
  442. Socket s;
  443. } pfd;
  444. } u;
  445. };
  446. /*
  447. * 2-3-4 tree storing remote->local port forwardings. SSH 1 and SSH
  448. * 2 use this structure in different ways, reflecting SSH 2's
  449. * altogether saner approach to port forwarding.
  450. *
  451. * In SSH 1, you arrange a remote forwarding by sending the server
  452. * the remote port number, and the local destination host:port.
  453. * When a connection comes in, the server sends you back that
  454. * host:port pair, and you connect to it. This is a ready-made
  455. * security hole if you're not on the ball: a malicious server
  456. * could send you back _any_ host:port pair, so if you trustingly
  457. * connect to the address it gives you then you've just opened the
  458. * entire inside of your corporate network just by connecting
  459. * through it to a dodgy SSH server. Hence, we must store a list of
  460. * host:port pairs we _are_ trying to forward to, and reject a
  461. * connection request from the server if it's not in the list.
  462. *
  463. * In SSH 2, each side of the connection minds its own business and
  464. * doesn't send unnecessary information to the other. You arrange a
  465. * remote forwarding by sending the server just the remote port
  466. * number. When a connection comes in, the server tells you which
  467. * of its ports was connected to; and _you_ have to remember what
  468. * local host:port pair went with that port number.
  469. *
  470. * Hence: in SSH 1 this structure stores host:port pairs we intend
  471. * to allow connections to, and is indexed by those host:port
  472. * pairs. In SSH 2 it stores a mapping from source port to
  473. * destination host:port pair, and is indexed by source port.
  474. */
  475. struct ssh_rportfwd {
  476. unsigned sport, dport;
  477. char dhost[256];
  478. };
  479. struct Packet {
  480. long length;
  481. int type;
  482. unsigned char *data;
  483. unsigned char *body;
  484. long savedpos;
  485. long maxlen;
  486. };
  487. static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
  488. static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt);
  489. static void ssh_size(void *handle, int width, int height);
  490. static void ssh_special(void *handle, Telnet_Special);
  491. static int ssh2_try_send(struct ssh_channel *c);
  492. static void ssh2_add_channel_data(struct ssh_channel *c, char *buf, int len);
  493. static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
  494. static void ssh2_set_window(struct ssh_channel *c, unsigned newwin);
  495. static int ssh_sendbuffer(void *handle);
  496. static void ssh_do_close(Ssh ssh);
  497. static unsigned long ssh_pkt_getuint32(Ssh ssh);
  498. static int ssh2_pkt_getbool(Ssh ssh);
  499. static void ssh_pkt_getstring(Ssh ssh, char **p, int *length);
  500. struct rdpkt1_state_tag {
  501. long len, pad, biglen, to_read;
  502. unsigned long realcrc, gotcrc;
  503. unsigned char *p;
  504. int i;
  505. int chunk;
  506. };
  507. struct rdpkt2_state_tag {
  508. long len, pad, payload, packetlen, maclen;
  509. int i;
  510. int cipherblk;
  511. unsigned long incoming_sequence;
  512. };
  513. struct ssh_tag {
  514. const struct plug_function_table *fn;
  515. /* the above field _must_ be first in the structure */
  516. SHA_State exhash, exhashbase;
  517. Socket s;
  518. void *ldisc;
  519. void *logctx;
  520. unsigned char session_key[32];
  521. int v1_compressing;
  522. int v1_remote_protoflags;
  523. int v1_local_protoflags;
  524. int agentfwd_enabled;
  525. int X11_fwd_enabled;
  526. int remote_bugs;
  527. const struct ssh_cipher *cipher;
  528. void *v1_cipher_ctx;
  529. void *crcda_ctx;
  530. const struct ssh2_cipher *cscipher, *sccipher;
  531. void *cs_cipher_ctx, *sc_cipher_ctx;
  532. const struct ssh_mac *csmac, *scmac;
  533. void *cs_mac_ctx, *sc_mac_ctx;
  534. const struct ssh_compress *cscomp, *sccomp;
  535. void *cs_comp_ctx, *sc_comp_ctx;
  536. const struct ssh_kex *kex;
  537. const struct ssh_signkey *hostkey;
  538. unsigned char v2_session_id[20];
  539. void *kex_ctx;
  540. char *savedhost;
  541. int savedport;
  542. int send_ok;
  543. int echoing, editing;
  544. void *frontend;
  545. int ospeed, ispeed; /* temporaries */
  546. int term_width, term_height;
  547. tree234 *channels; /* indexed by local id */
  548. struct ssh_channel *mainchan; /* primary session channel */
  549. int exitcode;
  550. tree234 *rportfwds;
  551. enum {
  552. SSH_STATE_PREPACKET,
  553. SSH_STATE_BEFORE_SIZE,
  554. SSH_STATE_INTERMED,
  555. SSH_STATE_SESSION,
  556. SSH_STATE_CLOSED
  557. } state;
  558. int size_needed, eof_needed;
  559. struct Packet pktin;
  560. struct Packet pktout;
  561. unsigned char *deferred_send_data;
  562. int deferred_len, deferred_size;
  563. /*
  564. * State associated with packet logging
  565. */
  566. int pktout_logmode;
  567. int pktout_nblanks;
  568. struct logblank_t *pktout_blanks;
  569. /*
  570. * Gross hack: pscp will try to start SFTP but fall back to
  571. * scp1 if that fails. This variable is the means by which
  572. * scp.c can reach into the SSH code and find out which one it
  573. * got.
  574. */
  575. int fallback_cmd;
  576. /*
  577. * Used for username and password input.
  578. */
  579. char *userpass_input_buffer;
  580. int userpass_input_buflen;
  581. int userpass_input_bufpos;
  582. int userpass_input_echo;
  583. char *portfwd_strptr;
  584. int pkt_ctx;
  585. void *x11auth;
  586. int version;
  587. int v1_throttle_count;
  588. int overall_bufsize;
  589. int throttled_all;
  590. int v1_stdout_throttling;
  591. int v2_outgoing_sequence;
  592. int ssh1_rdpkt_crstate;
  593. int ssh2_rdpkt_crstate;
  594. int do_ssh_init_crstate;
  595. int ssh_gotdata_crstate;
  596. int ssh1_protocol_crstate;
  597. int do_ssh1_login_crstate;
  598. int do_ssh2_transport_crstate;
  599. int do_ssh2_authconn_crstate;
  600. void *do_ssh_init_state;
  601. void *do_ssh1_login_state;
  602. void *do_ssh2_transport_state;
  603. void *do_ssh2_authconn_state;
  604. struct rdpkt1_state_tag rdpkt1_state;
  605. struct rdpkt2_state_tag rdpkt2_state;
  606. void (*protocol) (Ssh ssh, unsigned char *in, int inlen, int ispkt);
  607. int (*s_rdpkt) (Ssh ssh, unsigned char **data, int *datalen);
  608. /*
  609. * We maintain a full _copy_ of a Config structure here, not
  610. * merely a pointer to it. That way, when we're passed a new
  611. * one for reconfiguration, we can check the differences and
  612. * potentially reconfigure port forwardings etc in mid-session.
  613. */
  614. Config cfg;
  615. /*
  616. * Used to transfer data back from async agent callbacks.
  617. */
  618. void *agent_response;
  619. int agent_response_len;
  620. };
  621. #define logevent(s) logevent(ssh->frontend, s)
  622. /* logevent, only printf-formatted. */
  623. static void logeventf(Ssh ssh, const char *fmt, ...)
  624. {
  625. va_list ap;
  626. char *buf;
  627. va_start(ap, fmt);
  628. buf = dupvprintf(fmt, ap);
  629. va_end(ap);
  630. logevent(buf);
  631. sfree(buf);
  632. }
  633. #define bombout(msg) \
  634. do { \
  635. char *text = dupprintf msg; \
  636. ssh_do_close(ssh); \
  637. logevent(text); \
  638. connection_fatal(ssh->frontend, "%s", text); \
  639. sfree(text); \
  640. } while (0)
  641. /* Functions to leave bits out of the SSH packet log file. */
  642. static void dont_log_password(Ssh ssh, int blanktype)
  643. {
  644. if (ssh->cfg.logomitpass)
  645. ssh->pktout_logmode = blanktype;
  646. }
  647. static void dont_log_data(Ssh ssh, int blanktype)
  648. {
  649. if (ssh->cfg.logomitdata)
  650. ssh->pktout_logmode = blanktype;
  651. }
  652. static void end_log_omission(Ssh ssh)
  653. {
  654. ssh->pktout_logmode = PKTLOG_EMIT;
  655. }
  656. static int ssh_channelcmp(void *av, void *bv)
  657. {
  658. struct ssh_channel *a = (struct ssh_channel *) av;
  659. struct ssh_channel *b = (struct ssh_channel *) bv;
  660. if (a->localid < b->localid)
  661. return -1;
  662. if (a->localid > b->localid)
  663. return +1;
  664. return 0;
  665. }
  666. static int ssh_channelfind(void *av, void *bv)
  667. {
  668. unsigned *a = (unsigned *) av;
  669. struct ssh_channel *b = (struct ssh_channel *) bv;
  670. if (*a < b->localid)
  671. return -1;
  672. if (*a > b->localid)
  673. return +1;
  674. return 0;
  675. }
  676. static int ssh_rportcmp_ssh1(void *av, void *bv)
  677. {
  678. struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
  679. struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
  680. int i;
  681. if ( (i = strcmp(a->dhost, b->dhost)) != 0)
  682. return i < 0 ? -1 : +1;
  683. if (a->dport > b->dport)
  684. return +1;
  685. if (a->dport < b->dport)
  686. return -1;
  687. return 0;
  688. }
  689. static int ssh_rportcmp_ssh2(void *av, void *bv)
  690. {
  691. struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
  692. struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
  693. if (a->sport > b->sport)
  694. return +1;
  695. if (a->sport < b->sport)
  696. return -1;
  697. return 0;
  698. }
  699. static int alloc_channel_id(Ssh ssh)
  700. {
  701. const unsigned CHANNEL_NUMBER_OFFSET = 256;
  702. unsigned low, high, mid;
  703. int tsize;
  704. struct ssh_channel *c;
  705. /*
  706. * First-fit allocation of channel numbers: always pick the
  707. * lowest unused one. To do this, binary-search using the
  708. * counted B-tree to find the largest channel ID which is in a
  709. * contiguous sequence from the beginning. (Precisely
  710. * everything in that sequence must have ID equal to its tree
  711. * index plus CHANNEL_NUMBER_OFFSET.)
  712. */
  713. tsize = count234(ssh->channels);
  714. low = -1;
  715. high = tsize;
  716. while (high - low > 1) {
  717. mid = (high + low) / 2;
  718. c = index234(ssh->channels, mid);
  719. if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
  720. low = mid; /* this one is fine */
  721. else
  722. high = mid; /* this one is past it */
  723. }
  724. /*
  725. * Now low points to either -1, or the tree index of the
  726. * largest ID in the initial sequence.
  727. */
  728. {
  729. unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
  730. assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
  731. }
  732. return low + 1 + CHANNEL_NUMBER_OFFSET;
  733. }
  734. static void c_write(Ssh ssh, const char *buf, int len)
  735. {
  736. if ((flags & FLAG_STDERR)) {
  737. int i;
  738. for (i = 0; i < len; i++)
  739. if (buf[i] != '\r')
  740. fputc(buf[i], stderr);
  741. return;
  742. }
  743. from_backend(ssh->frontend, 1, buf, len);
  744. }
  745. static void c_write_untrusted(Ssh ssh, const char *buf, int len)
  746. {
  747. int i;
  748. for (i = 0; i < len; i++) {
  749. if (buf[i] == '\n')
  750. c_write(ssh, "\r\n", 2);
  751. else if ((buf[i] & 0x60) || (buf[i] == '\r'))
  752. c_write(ssh, buf + i, 1);
  753. }
  754. }
  755. static void c_write_str(Ssh ssh, const char *buf)
  756. {
  757. c_write(ssh, buf, strlen(buf));
  758. }
  759. /*
  760. * Collect incoming data in the incoming packet buffer.
  761. * Decipher and verify the packet when it is completely read.
  762. * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
  763. * Update the *data and *datalen variables.
  764. * Return the additional nr of bytes needed, or 0 when
  765. * a complete packet is available.
  766. */
  767. static int ssh1_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
  768. {
  769. struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
  770. crBegin(ssh->ssh1_rdpkt_crstate);
  771. next_packet:
  772. ssh->pktin.type = 0;
  773. ssh->pktin.length = 0;
  774. for (st->i = st->len = 0; st->i < 4; st->i++) {
  775. while ((*datalen) == 0)
  776. crReturn(4 - st->i);
  777. st->len = (st->len << 8) + **data;
  778. (*data)++, (*datalen)--;
  779. }
  780. st->pad = 8 - (st->len % 8);
  781. st->biglen = st->len + st->pad;
  782. ssh->pktin.length = st->len - 5;
  783. if (st->biglen < 0) {
  784. bombout(("Extremely large packet length from server suggests"
  785. " data stream corruption"));
  786. crStop(0);
  787. }
  788. if (ssh->pktin.maxlen < st->biglen) {
  789. ssh->pktin.maxlen = st->biglen;
  790. ssh->pktin.data = sresize(ssh->pktin.data, st->biglen + APIEXTRA,
  791. unsigned char);
  792. }
  793. st->to_read = st->biglen;
  794. st->p = ssh->pktin.data;
  795. while (st->to_read > 0) {
  796. st->chunk = st->to_read;
  797. while ((*datalen) == 0)
  798. crReturn(st->to_read);
  799. if (st->chunk > (*datalen))
  800. st->chunk = (*datalen);
  801. memcpy(st->p, *data, st->chunk);
  802. *data += st->chunk;
  803. *datalen -= st->chunk;
  804. st->p += st->chunk;
  805. st->to_read -= st->chunk;
  806. }
  807. if (ssh->cipher && detect_attack(ssh->crcda_ctx, ssh->pktin.data,
  808. st->biglen, NULL)) {
  809. bombout(("Network attack (CRC compensation) detected!"));
  810. crStop(0);
  811. }
  812. if (ssh->cipher)
  813. ssh->cipher->decrypt(ssh->v1_cipher_ctx, ssh->pktin.data, st->biglen);
  814. st->realcrc = crc32_compute(ssh->pktin.data, st->biglen - 4);
  815. st->gotcrc = GET_32BIT(ssh->pktin.data + st->biglen - 4);
  816. if (st->gotcrc != st->realcrc) {
  817. bombout(("Incorrect CRC received on packet"));
  818. crStop(0);
  819. }
  820. ssh->pktin.body = ssh->pktin.data + st->pad + 1;
  821. ssh->pktin.savedpos = 0;
  822. if (ssh->v1_compressing) {
  823. unsigned char *decompblk;
  824. int decomplen;
  825. if (!zlib_decompress_block(ssh->sc_comp_ctx,
  826. ssh->pktin.body - 1, ssh->pktin.length + 1,
  827. &decompblk, &decomplen)) {
  828. bombout(("Zlib decompression encountered invalid data"));
  829. crStop(0);
  830. }
  831. if (ssh->pktin.maxlen < st->pad + decomplen) {
  832. ssh->pktin.maxlen = st->pad + decomplen;
  833. ssh->pktin.data = sresize(ssh->pktin.data,
  834. ssh->pktin.maxlen + APIEXTRA,
  835. unsigned char);
  836. ssh->pktin.body = ssh->pktin.data + st->pad + 1;
  837. }
  838. memcpy(ssh->pktin.body - 1, decompblk, decomplen);
  839. sfree(decompblk);
  840. ssh->pktin.length = decomplen - 1;
  841. }
  842. ssh->pktin.type = ssh->pktin.body[-1];
  843. /*
  844. * Log incoming packet, possibly omitting sensitive fields.
  845. */
  846. if (ssh->logctx) {
  847. int nblanks = 0;
  848. struct logblank_t blank;
  849. if (ssh->cfg.logomitdata) {
  850. int do_blank = FALSE, blank_prefix = 0;
  851. /* "Session data" packets - omit the data field */
  852. if ((ssh->pktin.type == SSH1_SMSG_STDOUT_DATA) ||
  853. (ssh->pktin.type == SSH1_SMSG_STDERR_DATA)) {
  854. do_blank = TRUE; blank_prefix = 0;
  855. } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_DATA) {
  856. do_blank = TRUE; blank_prefix = 4;
  857. }
  858. if (do_blank) {
  859. blank.offset = blank_prefix;
  860. blank.len = ssh->pktin.length;
  861. blank.type = PKTLOG_OMIT;
  862. nblanks = 1;
  863. }
  864. }
  865. log_packet(ssh->logctx,
  866. PKT_INCOMING, ssh->pktin.type,
  867. ssh1_pkt_type(ssh->pktin.type),
  868. ssh->pktin.body, ssh->pktin.length,
  869. nblanks, &blank);
  870. }
  871. if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
  872. ssh->pktin.type == SSH1_SMSG_STDERR_DATA ||
  873. ssh->pktin.type == SSH1_MSG_DEBUG ||
  874. ssh->pktin.type == SSH1_SMSG_AUTH_TIS_CHALLENGE ||
  875. ssh->pktin.type == SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
  876. long stringlen = GET_32BIT(ssh->pktin.body);
  877. if (stringlen + 4 != ssh->pktin.length) {
  878. bombout(("Received data packet with bogus string length"));
  879. crStop(0);
  880. }
  881. }
  882. if (ssh->pktin.type == SSH1_MSG_DEBUG) {
  883. char *buf, *msg;
  884. int msglen;
  885. ssh_pkt_getstring(ssh, &msg, &msglen);
  886. buf = dupprintf("Remote debug message: %.*s", msglen, msg);
  887. logevent(buf);
  888. sfree(buf);
  889. goto next_packet;
  890. } else if (ssh->pktin.type == SSH1_MSG_IGNORE) {
  891. /* do nothing */
  892. goto next_packet;
  893. }
  894. if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
  895. /* log reason code in disconnect message */
  896. char *msg;
  897. int msglen;
  898. ssh_pkt_getstring(ssh, &msg, &msglen);
  899. bombout(("Server sent disconnect message:\n\"%.*s\"", msglen, msg));
  900. crStop(0);
  901. }
  902. crFinish(0);
  903. }
  904. static int ssh2_rdpkt(Ssh ssh, unsigned char **data, int *datalen)
  905. {
  906. struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
  907. crBegin(ssh->ssh2_rdpkt_crstate);
  908. next_packet:
  909. ssh->pktin.type = 0;
  910. ssh->pktin.length = 0;
  911. if (ssh->sccipher)
  912. st->cipherblk = ssh->sccipher->blksize;
  913. else
  914. st->cipherblk = 8;
  915. if (st->cipherblk < 8)
  916. st->cipherblk = 8;
  917. if (ssh->pktin.maxlen < st->cipherblk) {
  918. ssh->pktin.maxlen = st->cipherblk;
  919. ssh->pktin.data = sresize(ssh->pktin.data, st->cipherblk + APIEXTRA,
  920. unsigned char);
  921. }
  922. /*
  923. * Acquire and decrypt the first block of the packet. This will
  924. * contain the length and padding details.
  925. */
  926. for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
  927. while ((*datalen) == 0)
  928. crReturn(st->cipherblk - st->i);
  929. ssh->pktin.data[st->i] = *(*data)++;
  930. (*datalen)--;
  931. }
  932. if (ssh->sccipher)
  933. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  934. ssh->pktin.data, st->cipherblk);
  935. /*
  936. * Now get the length and padding figures.
  937. */
  938. st->len = GET_32BIT(ssh->pktin.data);
  939. st->pad = ssh->pktin.data[4];
  940. /*
  941. * _Completely_ silly lengths should be stomped on before they
  942. * do us any more damage.
  943. */
  944. if (st->len < 0 || st->pad < 0 || st->len + st->pad < 0) {
  945. bombout(("Incoming packet was garbled on decryption"));
  946. crStop(0);
  947. }
  948. /*
  949. * This enables us to deduce the payload length.
  950. */
  951. st->payload = st->len - st->pad - 1;
  952. ssh->pktin.length = st->payload + 5;
  953. /*
  954. * So now we can work out the total packet length.
  955. */
  956. st->packetlen = st->len + 4;
  957. st->maclen = ssh->scmac ? ssh->scmac->len : 0;
  958. /*
  959. * Adjust memory allocation if packet is too big.
  960. */
  961. if (ssh->pktin.maxlen < st->packetlen + st->maclen) {
  962. ssh->pktin.maxlen = st->packetlen + st->maclen;
  963. ssh->pktin.data = sresize(ssh->pktin.data,
  964. ssh->pktin.maxlen + APIEXTRA,
  965. unsigned char);
  966. }
  967. /*
  968. * Read and decrypt the remainder of the packet.
  969. */
  970. for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
  971. st->i++) {
  972. while ((*datalen) == 0)
  973. crReturn(st->packetlen + st->maclen - st->i);
  974. ssh->pktin.data[st->i] = *(*data)++;
  975. (*datalen)--;
  976. }
  977. /* Decrypt everything _except_ the MAC. */
  978. if (ssh->sccipher)
  979. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  980. ssh->pktin.data + st->cipherblk,
  981. st->packetlen - st->cipherblk);
  982. /*
  983. * Check the MAC.
  984. */
  985. if (ssh->scmac
  986. && !ssh->scmac->verify(ssh->sc_mac_ctx, ssh->pktin.data, st->len + 4,
  987. st->incoming_sequence)) {
  988. bombout(("Incorrect MAC received on packet"));
  989. crStop(0);
  990. }
  991. st->incoming_sequence++; /* whether or not we MACed */
  992. /*
  993. * Decompress packet payload.
  994. */
  995. {
  996. unsigned char *newpayload;
  997. int newlen;
  998. if (ssh->sccomp &&
  999. ssh->sccomp->decompress(ssh->sc_comp_ctx,
  1000. ssh->pktin.data + 5, ssh->pktin.length - 5,
  1001. &newpayload, &newlen)) {
  1002. if (ssh->pktin.maxlen < newlen + 5) {
  1003. ssh->pktin.maxlen = newlen + 5;
  1004. ssh->pktin.data = sresize(ssh->pktin.data,
  1005. ssh->pktin.maxlen + APIEXTRA,
  1006. unsigned char);
  1007. }
  1008. ssh->pktin.length = 5 + newlen;
  1009. memcpy(ssh->pktin.data + 5, newpayload, newlen);
  1010. sfree(newpayload);
  1011. }
  1012. }
  1013. ssh->pktin.savedpos = 6;
  1014. ssh->pktin.body = ssh->pktin.data;
  1015. ssh->pktin.type = ssh->pktin.data[5];
  1016. /*
  1017. * Log incoming packet, possibly omitting sensitive fields.
  1018. */
  1019. if (ssh->logctx) {
  1020. int nblanks = 0;
  1021. struct logblank_t blank;
  1022. if (ssh->cfg.logomitdata) {
  1023. int do_blank = FALSE, blank_prefix = 0;
  1024. /* "Session data" packets - omit the data field */
  1025. if (ssh->pktin.type == SSH2_MSG_CHANNEL_DATA) {
  1026. do_blank = TRUE; blank_prefix = 4;
  1027. } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
  1028. do_blank = TRUE; blank_prefix = 8;
  1029. }
  1030. if (do_blank) {
  1031. blank.offset = blank_prefix;
  1032. blank.len = (ssh->pktin.length-6) - blank_prefix;
  1033. blank.type = PKTLOG_OMIT;
  1034. nblanks = 1;
  1035. }
  1036. }
  1037. log_packet(ssh->logctx, PKT_INCOMING, ssh->pktin.type,
  1038. ssh2_pkt_type(ssh->pkt_ctx, ssh->pktin.type),
  1039. ssh->pktin.data+6, ssh->pktin.length-6,
  1040. nblanks, &blank);
  1041. }
  1042. switch (ssh->pktin.type) {
  1043. /*
  1044. * These packets we must handle instantly.
  1045. */
  1046. case SSH2_MSG_DISCONNECT:
  1047. {
  1048. /* log reason code in disconnect message */
  1049. char *buf, *msg;
  1050. int nowlen, reason, msglen;
  1051. reason = ssh_pkt_getuint32(ssh);
  1052. ssh_pkt_getstring(ssh, &msg, &msglen);
  1053. if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
  1054. buf = dupprintf("Received disconnect message (%s)",
  1055. ssh2_disconnect_reasons[reason]);
  1056. } else {
  1057. buf = dupprintf("Received disconnect message (unknown"
  1058. " type %d)", reason);
  1059. }
  1060. logevent(buf);
  1061. sfree(buf);
  1062. buf = dupprintf("Disconnection message text: %n%.*s",
  1063. &nowlen, msglen, msg);
  1064. logevent(buf);
  1065. bombout(("Server sent disconnect message\ntype %d (%s):\n\"%s\"",
  1066. reason,
  1067. (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
  1068. ssh2_disconnect_reasons[reason] : "unknown",
  1069. buf+nowlen));
  1070. sfree(buf);
  1071. crStop(0);
  1072. }
  1073. break;
  1074. case SSH2_MSG_IGNORE:
  1075. goto next_packet;
  1076. case SSH2_MSG_DEBUG:
  1077. {
  1078. /* log the debug message */
  1079. char *buf, *msg;
  1080. int msglen;
  1081. int always_display;
  1082. /* XXX maybe we should actually take notice of this */
  1083. always_display = ssh2_pkt_getbool(ssh);
  1084. ssh_pkt_getstring(ssh, &msg, &msglen);
  1085. buf = dupprintf("Remote debug message: %.*s", msglen, msg);
  1086. logevent(buf);
  1087. sfree(buf);
  1088. }
  1089. goto next_packet;
  1090. /*
  1091. * These packets we need do nothing about here.
  1092. */
  1093. case SSH2_MSG_UNIMPLEMENTED:
  1094. case SSH2_MSG_SERVICE_REQUEST:
  1095. case SSH2_MSG_SERVICE_ACCEPT:
  1096. case SSH2_MSG_KEXINIT:
  1097. case SSH2_MSG_NEWKEYS:
  1098. case SSH2_MSG_KEXDH_INIT:
  1099. case SSH2_MSG_KEXDH_REPLY:
  1100. /* case SSH2_MSG_KEX_DH_GEX_REQUEST: duplicate case value */
  1101. /* case SSH2_MSG_KEX_DH_GEX_GROUP: duplicate case value */
  1102. case SSH2_MSG_KEX_DH_GEX_INIT:
  1103. case SSH2_MSG_KEX_DH_GEX_REPLY:
  1104. case SSH2_MSG_USERAUTH_REQUEST:
  1105. case SSH2_MSG_USERAUTH_FAILURE:
  1106. case SSH2_MSG_USERAUTH_SUCCESS:
  1107. case SSH2_MSG_USERAUTH_BANNER:
  1108. case SSH2_MSG_USERAUTH_PK_OK:
  1109. /* case SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: duplicate case value */
  1110. /* case SSH2_MSG_USERAUTH_INFO_REQUEST: duplicate case value */
  1111. case SSH2_MSG_USERAUTH_INFO_RESPONSE:
  1112. case SSH2_MSG_GLOBAL_REQUEST:
  1113. case SSH2_MSG_REQUEST_SUCCESS:
  1114. case SSH2_MSG_REQUEST_FAILURE:
  1115. case SSH2_MSG_CHANNEL_OPEN:
  1116. case SSH2_MSG_CHANNEL_OPEN_CONFIRMATION:
  1117. case SSH2_MSG_CHANNEL_OPEN_FAILURE:
  1118. case SSH2_MSG_CHANNEL_WINDOW_ADJUST:
  1119. case SSH2_MSG_CHANNEL_DATA:
  1120. case SSH2_MSG_CHANNEL_EXTENDED_DATA:
  1121. case SSH2_MSG_CHANNEL_EOF:
  1122. case SSH2_MSG_CHANNEL_CLOSE:
  1123. case SSH2_MSG_CHANNEL_REQUEST:
  1124. case SSH2_MSG_CHANNEL_SUCCESS:
  1125. case SSH2_MSG_CHANNEL_FAILURE:
  1126. break;
  1127. /*
  1128. * For anything else we send SSH2_MSG_UNIMPLEMENTED.
  1129. */
  1130. default:
  1131. ssh2_pkt_init(ssh, SSH2_MSG_UNIMPLEMENTED);
  1132. ssh2_pkt_adduint32(ssh, st->incoming_sequence - 1);
  1133. ssh2_pkt_send(ssh);
  1134. break;
  1135. }
  1136. crFinish(0);
  1137. }
  1138. static void ssh1_pktout_size(Ssh ssh, int len)
  1139. {
  1140. int pad, biglen;
  1141. len += 5; /* type and CRC */
  1142. pad = 8 - (len % 8);
  1143. biglen = len + pad;
  1144. ssh->pktout.length = len - 5;
  1145. if (ssh->pktout.maxlen < biglen) {
  1146. ssh->pktout.maxlen = biglen;
  1147. #ifdef MSCRYPTOAPI
  1148. /* Allocate enough buffer space for extra block
  1149. * for MS CryptEncrypt() */
  1150. ssh->pktout.data = sresize(ssh->pktout.data, biglen + 12,
  1151. unsigned char);
  1152. #else
  1153. ssh->pktout.data = sresize(ssh->pktout.data, biglen + 4,
  1154. unsigned char);
  1155. #endif
  1156. }
  1157. ssh->pktout.body = ssh->pktout.data + 4 + pad + 1;
  1158. }
  1159. static void s_wrpkt_start(Ssh ssh, int type, int len)
  1160. {
  1161. ssh1_pktout_size(ssh, len);
  1162. ssh->pktout.type = type;
  1163. /* Initialise log omission state */
  1164. ssh->pktout_nblanks = 0;
  1165. ssh->pktout_blanks = NULL;
  1166. }
  1167. static int s_wrpkt_prepare(Ssh ssh)
  1168. {
  1169. int pad, biglen, i;
  1170. unsigned long crc;
  1171. #ifdef __SC__
  1172. /*
  1173. * XXX various versions of SC (including 8.8.4) screw up the
  1174. * register allocation in this function and use the same register
  1175. * (D6) for len and as a temporary, with predictable results. The
  1176. * following sledgehammer prevents this.
  1177. */
  1178. volatile
  1179. #endif
  1180. int len;
  1181. ssh->pktout.body[-1] = ssh->pktout.type;
  1182. if (ssh->logctx)
  1183. log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.type,
  1184. ssh1_pkt_type(ssh->pktout.type),
  1185. ssh->pktout.body, ssh->pktout.length,
  1186. ssh->pktout_nblanks, ssh->pktout_blanks);
  1187. sfree(ssh->pktout_blanks); ssh->pktout_blanks = NULL;
  1188. ssh->pktout_nblanks = 0;
  1189. if (ssh->v1_compressing) {
  1190. unsigned char *compblk;
  1191. int complen;
  1192. zlib_compress_block(ssh->cs_comp_ctx,
  1193. ssh->pktout.body - 1, ssh->pktout.length + 1,
  1194. &compblk, &complen);
  1195. ssh1_pktout_size(ssh, complen - 1);
  1196. memcpy(ssh->pktout.body - 1, compblk, complen);
  1197. sfree(compblk);
  1198. }
  1199. len = ssh->pktout.length + 5; /* type and CRC */
  1200. pad = 8 - (len % 8);
  1201. biglen = len + pad;
  1202. for (i = 0; i < pad; i++)
  1203. ssh->pktout.data[i + 4] = random_byte();
  1204. crc = crc32_compute(ssh->pktout.data + 4, biglen - 4);
  1205. PUT_32BIT(ssh->pktout.data + biglen, crc);
  1206. PUT_32BIT(ssh->pktout.data, len);
  1207. if (ssh->cipher)
  1208. ssh->cipher->encrypt(ssh->v1_cipher_ctx, ssh->pktout.data + 4, biglen);
  1209. return biglen + 4;
  1210. }
  1211. static void s_wrpkt(Ssh ssh)
  1212. {
  1213. int len, backlog;
  1214. len = s_wrpkt_prepare(ssh);
  1215. backlog = sk_write(ssh->s, (char *)ssh->pktout.data, len);
  1216. if (backlog > SSH_MAX_BACKLOG)
  1217. ssh_throttle_all(ssh, 1, backlog);
  1218. }
  1219. static void s_wrpkt_defer(Ssh ssh)
  1220. {
  1221. int len;
  1222. len = s_wrpkt_prepare(ssh);
  1223. if (ssh->deferred_len + len > ssh->deferred_size) {
  1224. ssh->deferred_size = ssh->deferred_len + len + 128;
  1225. ssh->deferred_send_data = sresize(ssh->deferred_send_data,
  1226. ssh->deferred_size,
  1227. unsigned char);
  1228. }
  1229. memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
  1230. ssh->deferred_len += len;
  1231. }
  1232. /*
  1233. * Construct a packet with the specified contents.
  1234. */
  1235. static void construct_packet(Ssh ssh, int pkttype, va_list ap1, va_list ap2)
  1236. {
  1237. unsigned char *p, *argp, argchar;
  1238. unsigned long argint;
  1239. int pktlen, argtype, arglen;
  1240. Bignum bn;
  1241. pktlen = 0;
  1242. while ((argtype = va_arg(ap1, int)) != PKT_END) {
  1243. switch (argtype) {
  1244. case PKT_INT:
  1245. (void) va_arg(ap1, int);
  1246. pktlen += 4;
  1247. break;
  1248. case PKT_CHAR:
  1249. (void) va_arg(ap1, int);
  1250. pktlen++;
  1251. break;
  1252. case PKT_DATA:
  1253. (void) va_arg(ap1, unsigned char *);
  1254. arglen = va_arg(ap1, int);
  1255. pktlen += arglen;
  1256. break;
  1257. case PKT_STR:
  1258. argp = va_arg(ap1, unsigned char *);
  1259. arglen = strlen((char *)argp);
  1260. pktlen += 4 + arglen;
  1261. break;
  1262. case PKT_BIGNUM:
  1263. bn = va_arg(ap1, Bignum);
  1264. pktlen += ssh1_bignum_length(bn);
  1265. break;
  1266. case PKTT_PASSWORD:
  1267. case PKTT_DATA:
  1268. case PKTT_OTHER:
  1269. /* ignore this pass */
  1270. break;
  1271. default:
  1272. assert(0);
  1273. }
  1274. }
  1275. s_wrpkt_start(ssh, pkttype, pktlen);
  1276. p = ssh->pktout.body;
  1277. while ((argtype = va_arg(ap2, int)) != PKT_END) {
  1278. int offset = p - ssh->pktout.body, len = 0;
  1279. switch (argtype) {
  1280. /* Actual fields in the packet */
  1281. case PKT_INT:
  1282. argint = va_arg(ap2, int);
  1283. PUT_32BIT(p, argint);
  1284. len = 4;
  1285. break;
  1286. case PKT_CHAR:
  1287. argchar = (unsigned char) va_arg(ap2, int);
  1288. *p = argchar;
  1289. len = 1;
  1290. break;
  1291. case PKT_DATA:
  1292. argp = va_arg(ap2, unsigned char *);
  1293. arglen = va_arg(ap2, int);
  1294. memcpy(p, argp, arglen);
  1295. len = arglen;
  1296. break;
  1297. case PKT_STR:
  1298. argp = va_arg(ap2, unsigned char *);
  1299. arglen = strlen((char *)argp);
  1300. PUT_32BIT(p, arglen);
  1301. memcpy(p + 4, argp, arglen);
  1302. len = arglen + 4;
  1303. break;
  1304. case PKT_BIGNUM:
  1305. bn = va_arg(ap2, Bignum);
  1306. len = ssh1_write_bignum(p, bn);
  1307. break;
  1308. /* Tokens for modifications to packet logging */
  1309. case PKTT_PASSWORD:
  1310. dont_log_password(ssh, PKTLOG_BLANK);
  1311. break;
  1312. case PKTT_DATA:
  1313. dont_log_data(ssh, PKTLOG_OMIT);
  1314. break;
  1315. case PKTT_OTHER:
  1316. end_log_omission(ssh);
  1317. break;
  1318. }
  1319. p += len;
  1320. /* Deal with logfile omission, if required. */
  1321. if (len && (ssh->pktout_logmode != PKTLOG_EMIT)) {
  1322. ssh->pktout_nblanks++;
  1323. ssh->pktout_blanks = sresize(ssh->pktout_blanks,
  1324. ssh->pktout_nblanks,
  1325. struct logblank_t);
  1326. ssh->pktout_blanks[ssh->pktout_nblanks-1].offset = offset;
  1327. ssh->pktout_blanks[ssh->pktout_nblanks-1].len = len;
  1328. ssh->pktout_blanks[ssh->pktout_nblanks-1].type =
  1329. ssh->pktout_logmode;
  1330. }
  1331. }
  1332. }
  1333. static void send_packet(Ssh ssh, int pkttype, ...)
  1334. {
  1335. va_list ap1, ap2;
  1336. va_start(ap1, pkttype);
  1337. va_start(ap2, pkttype);
  1338. construct_packet(ssh, pkttype, ap1, ap2);
  1339. s_wrpkt(ssh);
  1340. }
  1341. static void defer_packet(Ssh ssh, int pkttype, ...)
  1342. {
  1343. va_list ap1, ap2;
  1344. va_start(ap1, pkttype);
  1345. va_start(ap2, pkttype);
  1346. construct_packet(ssh, pkttype, ap1, ap2);
  1347. s_wrpkt_defer(ssh);
  1348. }
  1349. static int ssh_versioncmp(char *a, char *b)
  1350. {
  1351. char *ae, *be;
  1352. unsigned long av, bv;
  1353. av = strtoul(a, &ae, 10);
  1354. bv = strtoul(b, &be, 10);
  1355. if (av != bv)
  1356. return (av < bv ? -1 : +1);
  1357. if (*ae == '.')
  1358. ae++;
  1359. if (*be == '.')
  1360. be++;
  1361. av = strtoul(ae, &ae, 10);
  1362. bv = strtoul(be, &be, 10);
  1363. if (av != bv)
  1364. return (av < bv ? -1 : +1);
  1365. return 0;
  1366. }
  1367. /*
  1368. * Utility routines for putting an SSH-protocol `string' and
  1369. * `uint32' into a SHA state.
  1370. */
  1371. #include <stdio.h>
  1372. static void sha_string(SHA_State * s, void *str, int len)
  1373. {
  1374. unsigned char lenblk[4];
  1375. PUT_32BIT(lenblk, len);
  1376. SHA_Bytes(s, lenblk, 4);
  1377. SHA_Bytes(s, str, len);
  1378. }
  1379. static void sha_uint32(SHA_State * s, unsigned i)
  1380. {
  1381. unsigned char intblk[4];
  1382. PUT_32BIT(intblk, i);
  1383. SHA_Bytes(s, intblk, 4);
  1384. }
  1385. /*
  1386. * SSH2 packet construction functions.
  1387. */
  1388. static void ssh2_pkt_ensure(Ssh ssh, int length)
  1389. {
  1390. if (ssh->pktout.maxlen < length) {
  1391. ssh->pktout.maxlen = length + 256;
  1392. ssh->pktout.data = sresize(ssh->pktout.data,
  1393. ssh->pktout.maxlen + APIEXTRA,
  1394. unsigned char);
  1395. if (!ssh->pktout.data)
  1396. fatalbox("Out of memory");
  1397. }
  1398. }
  1399. static void ssh2_pkt_adddata(Ssh ssh, void *data, int len)
  1400. {
  1401. if (ssh->pktout_logmode != PKTLOG_EMIT) {
  1402. ssh->pktout_nblanks++;
  1403. ssh->pktout_blanks = sresize(ssh->pktout_blanks, ssh->pktout_nblanks,
  1404. struct logblank_t);
  1405. ssh->pktout_blanks[ssh->pktout_nblanks-1].offset =
  1406. ssh->pktout.length - 6;
  1407. ssh->pktout_blanks[ssh->pktout_nblanks-1].len = len;
  1408. ssh->pktout_blanks[ssh->pktout_nblanks-1].type = ssh->pktout_logmode;
  1409. }
  1410. ssh->pktout.length += len;
  1411. ssh2_pkt_ensure(ssh, ssh->pktout.length);
  1412. memcpy(ssh->pktout.data + ssh->pktout.length - len, data, len);
  1413. }
  1414. static void ssh2_pkt_addbyte(Ssh ssh, unsigned char byte)
  1415. {
  1416. ssh2_pkt_adddata(ssh, &byte, 1);
  1417. }
  1418. static void ssh2_pkt_init(Ssh ssh, int pkt_type)
  1419. {
  1420. ssh->pktout.length = 5;
  1421. ssh->pktout_nblanks = 0; ssh->pktout_blanks = NULL;
  1422. ssh2_pkt_addbyte(ssh, (unsigned char) pkt_type);
  1423. }
  1424. static void ssh2_pkt_addbool(Ssh ssh, unsigned char value)
  1425. {
  1426. ssh2_pkt_adddata(ssh, &value, 1);
  1427. }
  1428. static void ssh2_pkt_adduint32(Ssh ssh, unsigned long value)
  1429. {
  1430. unsigned char x[4];
  1431. PUT_32BIT(x, value);
  1432. ssh2_pkt_adddata(ssh, x, 4);
  1433. }
  1434. static void ssh2_pkt_addstring_start(Ssh ssh)
  1435. {
  1436. ssh2_pkt_adduint32(ssh, 0);
  1437. ssh->pktout.savedpos = ssh->pktout.length;
  1438. }
  1439. static void ssh2_pkt_addstring_str(Ssh ssh, char *data)
  1440. {
  1441. ssh2_pkt_adddata(ssh, data, strlen(data));
  1442. PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
  1443. ssh->pktout.length - ssh->pktout.savedpos);
  1444. }
  1445. static void ssh2_pkt_addstring_data(Ssh ssh, char *data, int len)
  1446. {
  1447. ssh2_pkt_adddata(ssh, data, len);
  1448. PUT_32BIT(ssh->pktout.data + ssh->pktout.savedpos - 4,
  1449. ssh->pktout.length - ssh->pktout.savedpos);
  1450. }
  1451. static void ssh2_pkt_addstring(Ssh ssh, char *data)
  1452. {
  1453. ssh2_pkt_addstring_start(ssh);
  1454. ssh2_pkt_addstring_str(ssh, data);
  1455. }
  1456. static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
  1457. {
  1458. unsigned char *p;
  1459. int i, n = (bignum_bitcount(b) + 7) / 8;
  1460. p = snewn(n + 1, unsigned char);
  1461. if (!p)
  1462. fatalbox("out of memory");
  1463. p[0] = 0;
  1464. for (i = 1; i <= n; i++)
  1465. p[i] = bignum_byte(b, n - i);
  1466. i = 0;
  1467. while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
  1468. i++;
  1469. memmove(p, p + i, n + 1 - i);
  1470. *len = n + 1 - i;
  1471. return p;
  1472. }
  1473. static void ssh2_pkt_addmp(Ssh ssh, Bignum b)
  1474. {
  1475. unsigned char *p;
  1476. int len;
  1477. p = ssh2_mpint_fmt(b, &len);
  1478. ssh2_pkt_addstring_start(ssh);
  1479. ssh2_pkt_addstring_data(ssh, (char *)p, len);
  1480. sfree(p);
  1481. }
  1482. /*
  1483. * Construct an SSH2 final-form packet: compress it, encrypt it,
  1484. * put the MAC on it. Final packet, ready to be sent, is stored in
  1485. * ssh->pktout.data. Total length is returned.
  1486. */
  1487. static int ssh2_pkt_construct(Ssh ssh)
  1488. {
  1489. int cipherblk, maclen, padding, i;
  1490. if (ssh->logctx)
  1491. log_packet(ssh->logctx, PKT_OUTGOING, ssh->pktout.data[5],
  1492. ssh2_pkt_type(ssh->pkt_ctx, ssh->pktout.data[5]),
  1493. ssh->pktout.data + 6, ssh->pktout.length - 6,
  1494. ssh->pktout_nblanks, ssh->pktout_blanks);
  1495. sfree(ssh->pktout_blanks); ssh->pktout_blanks = NULL;
  1496. ssh->pktout_nblanks = 0;
  1497. /*
  1498. * Compress packet payload.
  1499. */
  1500. {
  1501. unsigned char *newpayload;
  1502. int newlen;
  1503. if (ssh->cscomp &&
  1504. ssh->cscomp->compress(ssh->cs_comp_ctx, ssh->pktout.data + 5,
  1505. ssh->pktout.length - 5,
  1506. &newpayload, &newlen)) {
  1507. ssh->pktout.length = 5;
  1508. ssh2_pkt_adddata(ssh, newpayload, newlen);
  1509. sfree(newpayload);
  1510. }
  1511. }
  1512. /*
  1513. * Add padding. At least four bytes, and must also bring total
  1514. * length (minus MAC) up to a multiple of the block size.
  1515. */
  1516. cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
  1517. cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
  1518. padding = 4;
  1519. padding +=
  1520. (cipherblk - (ssh->pktout.length + padding) % cipherblk) % cipherblk;
  1521. maclen = ssh->csmac ? ssh->csmac->len : 0;
  1522. ssh2_pkt_ensure(ssh, ssh->pktout.length + padding + maclen);
  1523. ssh->pktout.data[4] = padding;
  1524. for (i = 0; i < padding; i++)
  1525. ssh->pktout.data[ssh->pktout.length + i] = random_byte();
  1526. PUT_32BIT(ssh->pktout.data, ssh->pktout.length + padding - 4);
  1527. if (ssh->csmac)
  1528. ssh->csmac->generate(ssh->cs_mac_ctx, ssh->pktout.data,
  1529. ssh->pktout.length + padding,
  1530. ssh->v2_outgoing_sequence);
  1531. ssh->v2_outgoing_sequence++; /* whether or not we MACed */
  1532. if (ssh->cscipher)
  1533. ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
  1534. ssh->pktout.data, ssh->pktout.length + padding);
  1535. /* Ready-to-send packet starts at ssh->pktout.data. We return length. */
  1536. return ssh->pktout.length + padding + maclen;
  1537. }
  1538. /*
  1539. * Construct and send an SSH2 packet immediately.
  1540. */
  1541. static void ssh2_pkt_send(Ssh ssh)
  1542. {
  1543. int len;
  1544. int backlog;
  1545. len = ssh2_pkt_construct(ssh);
  1546. backlog = sk_write(ssh->s, (char *)ssh->pktout.data, len);
  1547. if (backlog > SSH_MAX_BACKLOG)
  1548. ssh_throttle_all(ssh, 1, backlog);
  1549. }
  1550. /*
  1551. * Construct an SSH2 packet and add it to a deferred data block.
  1552. * Useful for sending multiple packets in a single sk_write() call,
  1553. * to prevent a traffic-analysing listener from being able to work
  1554. * out the length of any particular packet (such as the password
  1555. * packet).
  1556. *
  1557. * Note that because SSH2 sequence-numbers its packets, this can
  1558. * NOT be used as an m4-style `defer' allowing packets to be
  1559. * constructed in one order and sent in another.
  1560. */
  1561. static void ssh2_pkt_defer(Ssh ssh)
  1562. {
  1563. int len = ssh2_pkt_construct(ssh);
  1564. if (ssh->deferred_len + len > ssh->deferred_size) {
  1565. ssh->deferred_size = ssh->deferred_len + len + 128;
  1566. ssh->deferred_send_data = sresize(ssh->deferred_send_data,
  1567. ssh->deferred_size,
  1568. unsigned char);
  1569. }
  1570. memcpy(ssh->deferred_send_data + ssh->deferred_len, ssh->pktout.data, len);
  1571. ssh->deferred_len += len;
  1572. }
  1573. /*
  1574. * Send the whole deferred data block constructed by
  1575. * ssh2_pkt_defer() or SSH1's defer_packet().
  1576. */
  1577. static void ssh_pkt_defersend(Ssh ssh)
  1578. {
  1579. int backlog;
  1580. backlog = sk_write(ssh->s, (char *)ssh->deferred_send_data,
  1581. ssh->deferred_len);
  1582. ssh->deferred_len = ssh->deferred_size = 0;
  1583. sfree(ssh->deferred_send_data);
  1584. ssh->deferred_send_data = NULL;
  1585. if (backlog > SSH_MAX_BACKLOG)
  1586. ssh_throttle_all(ssh, 1, backlog);
  1587. }
  1588. #if 0
  1589. void bndebug(char *string, Bignum b)
  1590. {
  1591. unsigned char *p;
  1592. int i, len;
  1593. p = ssh2_mpint_fmt(b, &len);
  1594. debug(("%s", string));
  1595. for (i = 0; i < len; i++)
  1596. debug((" %02x", p[i]));
  1597. debug(("\n"));
  1598. sfree(p);
  1599. }
  1600. #endif
  1601. static void sha_mpint(SHA_State * s, Bignum b)
  1602. {
  1603. unsigned char *p;
  1604. int len;
  1605. p = ssh2_mpint_fmt(b, &len);
  1606. sha_string(s, p, len);
  1607. sfree(p);
  1608. }
  1609. /*
  1610. * Packet decode functions for both SSH1 and SSH2.
  1611. */
  1612. static unsigned long ssh_pkt_getuint32(Ssh ssh)
  1613. {
  1614. unsigned long value;
  1615. if (ssh->pktin.length - ssh->pktin.savedpos < 4)
  1616. return 0; /* arrgh, no way to decline (FIXME?) */
  1617. value = GET_32BIT(ssh->pktin.body + ssh->pktin.savedpos);
  1618. ssh->pktin.savedpos += 4;
  1619. return value;
  1620. }
  1621. static int ssh2_pkt_getbool(Ssh ssh)
  1622. {
  1623. unsigned long value;
  1624. if (ssh->pktin.length - ssh->pktin.savedpos < 1)
  1625. return 0; /* arrgh, no way to decline (FIXME?) */
  1626. value = ssh->pktin.body[ssh->pktin.savedpos] != 0;
  1627. ssh->pktin.savedpos++;
  1628. return value;
  1629. }
  1630. static void ssh_pkt_getstring(Ssh ssh, char **p, int *length)
  1631. {
  1632. int len;
  1633. *p = NULL;
  1634. *length = 0;
  1635. if (ssh->pktin.length - ssh->pktin.savedpos < 4)
  1636. return;
  1637. len = GET_32BIT(ssh->pktin.body + ssh->pktin.savedpos);
  1638. if (len < 0)
  1639. return;
  1640. *length = len;
  1641. ssh->pktin.savedpos += 4;
  1642. if (ssh->pktin.length - ssh->pktin.savedpos < *length)
  1643. return;
  1644. *p = (char *)(ssh->pktin.body + ssh->pktin.savedpos);
  1645. ssh->pktin.savedpos += *length;
  1646. }
  1647. static void *ssh_pkt_getdata(Ssh ssh, int length)
  1648. {
  1649. if (ssh->pktin.length - ssh->pktin.savedpos < length)
  1650. return NULL;
  1651. ssh->pktin.savedpos += length;
  1652. return ssh->pktin.body + (ssh->pktin.savedpos - length);
  1653. }
  1654. static int ssh1_pkt_getrsakey(Ssh ssh, struct RSAKey *key,
  1655. unsigned char **keystr)
  1656. {
  1657. int j;
  1658. j = makekey(ssh->pktin.body + ssh->pktin.savedpos,
  1659. ssh->pktin.length - ssh->pktin.savedpos,
  1660. key, keystr, 0);
  1661. if (j < 0)
  1662. return FALSE;
  1663. ssh->pktin.savedpos += j;
  1664. assert(ssh->pktin.savedpos < ssh->pktin.length);
  1665. return TRUE;
  1666. }
  1667. static Bignum ssh1_pkt_getmp(Ssh ssh)
  1668. {
  1669. int j;
  1670. Bignum b;
  1671. j = ssh1_read_bignum(ssh->pktin.body + ssh->pktin.savedpos,
  1672. ssh->pktin.length - ssh->pktin.savedpos, &b);
  1673. if (j < 0)
  1674. return NULL;
  1675. ssh->pktin.savedpos += j;
  1676. return b;
  1677. }
  1678. static Bignum ssh2_pkt_getmp(Ssh ssh)
  1679. {
  1680. char *p;
  1681. int length;
  1682. Bignum b;
  1683. ssh_pkt_getstring(ssh, &p, &length);
  1684. if (!p)
  1685. return NULL;
  1686. if (p[0] & 0x80) {
  1687. bombout(("internal error: Can't handle negative mpints"));
  1688. return NULL;
  1689. }
  1690. b = bignum_from_bytes((unsigned char *)p, length);
  1691. return b;
  1692. }
  1693. /*
  1694. * Helper function to add an SSH2 signature blob to a packet.
  1695. * Expects to be shown the public key blob as well as the signature
  1696. * blob. Normally works just like ssh2_pkt_addstring, but will
  1697. * fiddle with the signature packet if necessary for
  1698. * BUG_SSH2_RSA_PADDING.
  1699. */
  1700. static void ssh2_add_sigblob(Ssh ssh, void *pkblob_v, int pkblob_len,
  1701. void *sigblob_v, int sigblob_len)
  1702. {
  1703. unsigned char *pkblob = (unsigned char *)pkblob_v;
  1704. unsigned char *sigblob = (unsigned char *)sigblob_v;
  1705. /* dmemdump(pkblob, pkblob_len); */
  1706. /* dmemdump(sigblob, sigblob_len); */
  1707. /*
  1708. * See if this is in fact an ssh-rsa signature and a buggy
  1709. * server; otherwise we can just do this the easy way.
  1710. */
  1711. if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) &&
  1712. (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
  1713. int pos, len, siglen;
  1714. /*
  1715. * Find the byte length of the modulus.
  1716. */
  1717. pos = 4+7; /* skip over "ssh-rsa" */
  1718. pos += 4 + GET_32BIT(pkblob+pos); /* skip over exponent */
  1719. len = GET_32BIT(pkblob+pos); /* find length of modulus */
  1720. pos += 4; /* find modulus itself */
  1721. while (len > 0 && pkblob[pos] == 0)
  1722. len--, pos++;
  1723. /* debug(("modulus length is %d\n", len)); */
  1724. /*
  1725. * Now find the signature integer.
  1726. */
  1727. pos = 4+7; /* skip over "ssh-rsa" */
  1728. siglen = GET_32BIT(sigblob+pos);
  1729. /* debug(("signature length is %d\n", siglen)); */
  1730. if (len != siglen) {
  1731. unsigned char newlen[4];
  1732. ssh2_pkt_addstring_start(ssh);
  1733. ssh2_pkt_addstring_data(ssh, (char *)sigblob, pos);
  1734. /* dmemdump(sigblob, pos); */
  1735. pos += 4; /* point to start of actual sig */
  1736. PUT_32BIT(newlen, len);
  1737. ssh2_pkt_addstring_data(ssh, (char *)newlen, 4);
  1738. /* dmemdump(newlen, 4); */
  1739. newlen[0] = 0;
  1740. while (len-- > siglen) {
  1741. ssh2_pkt_addstring_data(ssh, (char *)newlen, 1);
  1742. /* dmemdump(newlen, 1); */
  1743. }
  1744. ssh2_pkt_addstring_data(ssh, (char *)(sigblob+pos), siglen);
  1745. /* dmemdump(sigblob+pos, siglen); */
  1746. return;
  1747. }
  1748. /* Otherwise fall through and do it the easy way. */
  1749. }
  1750. ssh2_pkt_addstring_start(ssh);
  1751. ssh2_pkt_addstring_data(ssh, (char *)sigblob, sigblob_len);
  1752. }
  1753. /*
  1754. * Examine the remote side's version string and compare it against
  1755. * a list of known buggy implementations.
  1756. */
  1757. static void ssh_detect_bugs(Ssh ssh, char *vstring)
  1758. {
  1759. char *imp; /* pointer to implementation part */
  1760. imp = vstring;
  1761. imp += strcspn(imp, "-");
  1762. if (*imp) imp++;
  1763. imp += strcspn(imp, "-");
  1764. if (*imp) imp++;
  1765. ssh->remote_bugs = 0;
  1766. if (ssh->cfg.sshbug_ignore1 == FORCE_ON ||
  1767. (ssh->cfg.sshbug_ignore1 == AUTO &&
  1768. (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
  1769. !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
  1770. !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
  1771. !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
  1772. /*
  1773. * These versions don't support SSH1_MSG_IGNORE, so we have
  1774. * to use a different defence against password length
  1775. * sniffing.
  1776. */
  1777. ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
  1778. logevent("We believe remote version has SSH1 ignore bug");
  1779. }
  1780. if (ssh->cfg.sshbug_plainpw1 == FORCE_ON ||
  1781. (ssh->cfg.sshbug_plainpw1 == AUTO &&
  1782. (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
  1783. /*
  1784. * These versions need a plain password sent; they can't
  1785. * handle having a null and a random length of data after
  1786. * the password.
  1787. */
  1788. ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
  1789. logevent("We believe remote version needs a plain SSH1 password");
  1790. }
  1791. if (ssh->cfg.sshbug_rsa1 == FORCE_ON ||
  1792. (ssh->cfg.sshbug_rsa1 == AUTO &&
  1793. (!strcmp(imp, "Cisco-1.25")))) {
  1794. /*
  1795. * These versions apparently have no clue whatever about
  1796. * RSA authentication and will panic and die if they see
  1797. * an AUTH_RSA message.
  1798. */
  1799. ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
  1800. logevent("We believe remote version can't handle RSA authentication");
  1801. }
  1802. if (ssh->cfg.sshbug_hmac2 == FORCE_ON ||
  1803. (ssh->cfg.sshbug_hmac2 == AUTO &&
  1804. !wc_match("* VShell", imp) &&
  1805. (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
  1806. wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
  1807. wc_match("2.1 *", imp)))) {
  1808. /*
  1809. * These versions have the HMAC bug.
  1810. */
  1811. ssh->remote_bugs |= BUG_SSH2_HMAC;
  1812. logevent("We believe remote version has SSH2 HMAC bug");
  1813. }
  1814. if (ssh->cfg.sshbug_derivekey2 == FORCE_ON ||
  1815. (ssh->cfg.sshbug_derivekey2 == AUTO &&
  1816. !wc_match("* VShell", imp) &&
  1817. (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
  1818. /*
  1819. * These versions have the key-derivation bug (failing to
  1820. * include the literal shared secret in the hashes that
  1821. * generate the keys).
  1822. */
  1823. ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
  1824. logevent("We believe remote version has SSH2 key-derivation bug");
  1825. }
  1826. if (ssh->cfg.sshbug_rsapad2 == FORCE_ON ||
  1827. (ssh->cfg.sshbug_rsapad2 == AUTO &&
  1828. (wc_match("OpenSSH_2.[5-9]*", imp) ||
  1829. wc_match("OpenSSH_3.[0-2]*", imp)))) {
  1830. /*
  1831. * These versions have the SSH2 RSA padding bug.
  1832. */
  1833. ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
  1834. logevent("We believe remote version has SSH2 RSA padding bug");
  1835. }
  1836. if (ssh->cfg.sshbug_pksessid2 == FORCE_ON ||
  1837. (ssh->cfg.sshbug_pksessid2 == AUTO &&
  1838. wc_match("OpenSSH_2.[0-2]*", imp))) {
  1839. /*
  1840. * These versions have the SSH2 session-ID bug in
  1841. * public-key authentication.
  1842. */
  1843. ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
  1844. logevent("We believe remote version has SSH2 public-key-session-ID bug");
  1845. }
  1846. if (ssh->cfg.sshbug_dhgex2 == FORCE_ON) {
  1847. /*
  1848. * User specified the SSH2 DH GEX bug.
  1849. */
  1850. ssh->remote_bugs |= BUG_SSH2_DH_GEX;
  1851. logevent("We believe remote version has SSH2 DH group exchange bug");
  1852. }
  1853. }
  1854. static int do_ssh_init(Ssh ssh, unsigned char c)
  1855. {
  1856. struct do_ssh_init_state {
  1857. int vslen;
  1858. char version[10];
  1859. char *vstring;
  1860. int vstrsize;
  1861. int i;
  1862. int proto1, proto2;
  1863. };
  1864. crState(do_ssh_init_state);
  1865. crBegin(ssh->do_ssh_init_crstate);
  1866. /* Search for the string "SSH-" in the input. */
  1867. s->i = 0;
  1868. while (1) {
  1869. static const int transS[] = { 1, 2, 2, 1 };
  1870. static const int transH[] = { 0, 0, 3, 0 };
  1871. static const int transminus[] = { 0, 0, 0, -1 };
  1872. if (c == 'S')
  1873. s->i = transS[s->i];
  1874. else if (c == 'H')
  1875. s->i = transH[s->i];
  1876. else if (c == '-')
  1877. s->i = transminus[s->i];
  1878. else
  1879. s->i = 0;
  1880. if (s->i < 0)
  1881. break;
  1882. crReturn(1); /* get another character */
  1883. }
  1884. s->vstrsize = 16;
  1885. s->vstring = snewn(s->vstrsize, char);
  1886. strcpy(s->vstring, "SSH-");
  1887. s->vslen = 4;
  1888. s->i = 0;
  1889. while (1) {
  1890. crReturn(1); /* get another char */
  1891. if (s->vslen >= s->vstrsize - 1) {
  1892. s->vstrsize += 16;
  1893. s->vstring = sresize(s->vstring, s->vstrsize, char);
  1894. }
  1895. s->vstring[s->vslen++] = c;
  1896. if (s->i >= 0) {
  1897. if (c == '-') {
  1898. s->version[s->i] = '\0';
  1899. s->i = -1;
  1900. } else if (s->i < sizeof(s->version) - 1)
  1901. s->version[s->i++] = c;
  1902. } else if (c == '\012')
  1903. break;
  1904. }
  1905. ssh->agentfwd_enabled = FALSE;
  1906. ssh->rdpkt2_state.incoming_sequence = 0;
  1907. s->vstring[s->vslen] = 0;
  1908. s->vstring[strcspn(s->vstring, "\r\n")] = '\0';/* remove EOL chars */
  1909. {
  1910. char *vlog;
  1911. vlog = snewn(20 + s->vslen, char);
  1912. sprintf(vlog, "Server version: %s", s->vstring);
  1913. logevent(vlog);
  1914. sfree(vlog);
  1915. }
  1916. ssh_detect_bugs(ssh, s->vstring);
  1917. /*
  1918. * Decide which SSH protocol version to support.
  1919. */
  1920. /* Anything strictly below "2.0" means protocol 1 is supported. */
  1921. s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
  1922. /* Anything greater or equal to "1.99" means protocol 2 is supported. */
  1923. s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
  1924. if (ssh->cfg.sshprot == 0 && !s->proto1) {
  1925. bombout(("SSH protocol version 1 required by user but not provided by server"));
  1926. crStop(0);
  1927. }
  1928. if (ssh->cfg.sshprot == 3 && !s->proto2) {
  1929. bombout(("SSH protocol version 2 required by user but not provided by server"));
  1930. crStop(0);
  1931. }
  1932. if (s->proto2 && (ssh->cfg.sshprot >= 2 || !s->proto1)) {
  1933. /*
  1934. * Use v2 protocol.
  1935. */
  1936. char verstring[80], vlog[100];
  1937. sprintf(verstring, "SSH-2.0-%s", sshver);
  1938. SHA_Init(&ssh->exhashbase);
  1939. /*
  1940. * Hash our version string and their version string.
  1941. */
  1942. sha_string(&ssh->exhashbase, verstring, strlen(verstring));
  1943. sha_string(&ssh->exhashbase, s->vstring, strcspn(s->vstring, "\r\n"));
  1944. sprintf(vlog, "We claim version: %s", verstring);
  1945. logevent(vlog);
  1946. strcat(verstring, "\012");
  1947. logevent("Using SSH protocol version 2");
  1948. sk_write(ssh->s, verstring, strlen(verstring));
  1949. ssh->protocol = ssh2_protocol;
  1950. ssh->version = 2;
  1951. ssh->s_rdpkt = ssh2_rdpkt;
  1952. } else {
  1953. /*
  1954. * Use v1 protocol.
  1955. */
  1956. char verstring[80], vlog[100];
  1957. sprintf(verstring, "SSH-%s-%s",
  1958. (ssh_versioncmp(s->version, "1.5") <= 0 ? s->version : "1.5"),
  1959. sshver);
  1960. sprintf(vlog, "We claim version: %s", verstring);
  1961. logevent(vlog);
  1962. strcat(verstring, "\012");
  1963. logevent("Using SSH protocol version 1");
  1964. sk_write(ssh->s, verstring, strlen(verstring));
  1965. ssh->protocol = ssh1_protocol;
  1966. ssh->version = 1;
  1967. ssh->s_rdpkt = ssh1_rdpkt;
  1968. }
  1969. update_specials_menu(ssh->frontend);
  1970. ssh->state = SSH_STATE_BEFORE_SIZE;
  1971. sfree(s->vstring);
  1972. crFinish(0);
  1973. }
  1974. static void ssh_gotdata(Ssh ssh, unsigned char *data, int datalen)
  1975. {
  1976. crBegin(ssh->ssh_gotdata_crstate);
  1977. /*
  1978. * To begin with, feed the characters one by one to the
  1979. * protocol initialisation / selection function do_ssh_init().
  1980. * When that returns 0, we're done with the initial greeting
  1981. * exchange and can move on to packet discipline.
  1982. */
  1983. while (1) {
  1984. int ret; /* need not be kept across crReturn */
  1985. if (datalen == 0)
  1986. crReturnV; /* more data please */
  1987. ret = do_ssh_init(ssh, *data);
  1988. data++;
  1989. datalen--;
  1990. if (ret == 0)
  1991. break;
  1992. }
  1993. /*
  1994. * We emerge from that loop when the initial negotiation is
  1995. * over and we have selected an s_rdpkt function. Now pass
  1996. * everything to s_rdpkt, and then pass the resulting packets
  1997. * to the proper protocol handler.
  1998. */
  1999. if (datalen == 0)
  2000. crReturnV;
  2001. while (1) {
  2002. while (datalen > 0) {
  2003. if (ssh->s_rdpkt(ssh, &data, &datalen) == 0) {
  2004. if (ssh->state == SSH_STATE_CLOSED) {
  2005. return;
  2006. }
  2007. ssh->protocol(ssh, NULL, 0, 1);
  2008. if (ssh->state == SSH_STATE_CLOSED) {
  2009. return;
  2010. }
  2011. }
  2012. }
  2013. crReturnV;
  2014. }
  2015. crFinishV;
  2016. }
  2017. static void ssh_do_close(Ssh ssh)
  2018. {
  2019. int i;
  2020. struct ssh_channel *c;
  2021. ssh->state = SSH_STATE_CLOSED;
  2022. if (ssh->s) {
  2023. sk_close(ssh->s);
  2024. ssh->s = NULL;
  2025. }
  2026. /*
  2027. * Now we must shut down any port and X forwardings going
  2028. * through this connection.
  2029. */
  2030. if (ssh->channels) {
  2031. for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
  2032. switch (c->type) {
  2033. case CHAN_X11:
  2034. x11_close(c->u.x11.s);
  2035. break;
  2036. case CHAN_SOCKDATA:
  2037. pfd_close(c->u.pfd.s);
  2038. break;
  2039. }
  2040. del234(ssh->channels, c);
  2041. if (ssh->version == 2)
  2042. bufchain_clear(&c->v.v2.outbuffer);
  2043. sfree(c);
  2044. }
  2045. }
  2046. }
  2047. static int ssh_closing(Plug plug, const char *error_msg, int error_code,
  2048. int calling_back)
  2049. {
  2050. Ssh ssh = (Ssh) plug;
  2051. ssh_do_close(ssh);
  2052. if (error_msg) {
  2053. /* A socket error has occurred. */
  2054. logevent(error_msg);
  2055. connection_fatal(ssh->frontend, "%s", error_msg);
  2056. } else {
  2057. /* Otherwise, the remote side closed the connection normally. */
  2058. }
  2059. return 0;
  2060. }
  2061. static int ssh_receive(Plug plug, int urgent, char *data, int len)
  2062. {
  2063. Ssh ssh = (Ssh) plug;
  2064. ssh_gotdata(ssh, (unsigned char *)data, len);
  2065. if (ssh->state == SSH_STATE_CLOSED) {
  2066. ssh_do_close(ssh);
  2067. return 0;
  2068. }
  2069. return 1;
  2070. }
  2071. static void ssh_sent(Plug plug, int bufsize)
  2072. {
  2073. Ssh ssh = (Ssh) plug;
  2074. /*
  2075. * If the send backlog on the SSH socket itself clears, we
  2076. * should unthrottle the whole world if it was throttled.
  2077. */
  2078. if (bufsize < SSH_MAX_BACKLOG)
  2079. ssh_throttle_all(ssh, 0, bufsize);
  2080. }
  2081. /*
  2082. * Connect to specified host and port.
  2083. * Returns an error message, or NULL on success.
  2084. * Also places the canonical host name into `realhost'. It must be
  2085. * freed by the caller.
  2086. */
  2087. static const char *connect_to_host(Ssh ssh, char *host, int port,
  2088. char **realhost, int nodelay, int keepalive)
  2089. {
  2090. static const struct plug_function_table fn_table = {
  2091. ssh_closing,
  2092. ssh_receive,
  2093. ssh_sent,
  2094. NULL
  2095. };
  2096. SockAddr addr;
  2097. const char *err;
  2098. ssh->savedhost = snewn(1 + strlen(host), char);
  2099. if (!ssh->savedhost)
  2100. fatalbox("Out of memory");
  2101. strcpy(ssh->savedhost, host);
  2102. if (port < 0)
  2103. port = 22; /* default ssh port */
  2104. ssh->savedport = port;
  2105. /*
  2106. * Try to find host.
  2107. */
  2108. logeventf(ssh, "Looking up host \"%s\"", host);
  2109. addr = name_lookup(host, port, realhost, &ssh->cfg);
  2110. if ((err = sk_addr_error(addr)) != NULL) {
  2111. sk_addr_free(addr);
  2112. return err;
  2113. }
  2114. /*
  2115. * Open socket.
  2116. */
  2117. {
  2118. char addrbuf[100];
  2119. sk_getaddr(addr, addrbuf, 100);
  2120. logeventf(ssh, "Connecting to %s port %d", addrbuf, port);
  2121. }
  2122. ssh->fn = &fn_table;
  2123. ssh->s = new_connection(addr, *realhost, port,
  2124. 0, 1, nodelay, keepalive, (Plug) ssh, &ssh->cfg);
  2125. if ((err = sk_socket_error(ssh->s)) != NULL) {
  2126. ssh->s = NULL;
  2127. return err;
  2128. }
  2129. return NULL;
  2130. }
  2131. /*
  2132. * Throttle or unthrottle the SSH connection.
  2133. */
  2134. static void ssh1_throttle(Ssh ssh, int adjust)
  2135. {
  2136. int old_count = ssh->v1_throttle_count;
  2137. ssh->v1_throttle_count += adjust;
  2138. assert(ssh->v1_throttle_count >= 0);
  2139. if (ssh->v1_throttle_count && !old_count) {
  2140. sk_set_frozen(ssh->s, 1);
  2141. } else if (!ssh->v1_throttle_count && old_count) {
  2142. sk_set_frozen(ssh->s, 0);
  2143. }
  2144. }
  2145. /*
  2146. * Throttle or unthrottle _all_ local data streams (for when sends
  2147. * on the SSH connection itself back up).
  2148. */
  2149. static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
  2150. {
  2151. int i;
  2152. struct ssh_channel *c;
  2153. if (enable == ssh->throttled_all)
  2154. return;
  2155. ssh->throttled_all = enable;
  2156. ssh->overall_bufsize = bufsize;
  2157. if (!ssh->channels)
  2158. return;
  2159. for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
  2160. switch (c->type) {
  2161. case CHAN_MAINSESSION:
  2162. /*
  2163. * This is treated separately, outside the switch.
  2164. */
  2165. break;
  2166. case CHAN_X11:
  2167. x11_override_throttle(c->u.x11.s, enable);
  2168. break;
  2169. case CHAN_AGENT:
  2170. /* Agent channels require no buffer management. */
  2171. break;
  2172. case CHAN_SOCKDATA:
  2173. pfd_override_throttle(c->u.pfd.s, enable);
  2174. break;
  2175. }
  2176. }
  2177. }
  2178. /*
  2179. * Username and password input, abstracted off into routines
  2180. * reusable in several places - even between SSH1 and SSH2.
  2181. */
  2182. /* Set up a username or password input loop on a given buffer. */
  2183. static void setup_userpass_input(Ssh ssh, char *buffer, int buflen, int echo)
  2184. {
  2185. ssh->userpass_input_buffer = buffer;
  2186. ssh->userpass_input_buflen = buflen;
  2187. ssh->userpass_input_bufpos = 0;
  2188. ssh->userpass_input_echo = echo;
  2189. }
  2190. /*
  2191. * Process some terminal data in the course of username/password
  2192. * input. Returns >0 for success (line of input returned in
  2193. * buffer), <0 for failure (user hit ^C/^D, bomb out and exit), 0
  2194. * for inconclusive (keep waiting for more input please).
  2195. */
  2196. static int process_userpass_input(Ssh ssh, unsigned char *in, int inlen)
  2197. {
  2198. char c;
  2199. while (inlen--) {
  2200. switch (c = *in++) {
  2201. case 10:
  2202. case 13:
  2203. ssh->userpass_input_buffer[ssh->userpass_input_bufpos] = 0;
  2204. ssh->userpass_input_buffer[ssh->userpass_input_buflen-1] = 0;
  2205. return +1;
  2206. break;
  2207. case 8:
  2208. case 127:
  2209. if (ssh->userpass_input_bufpos > 0) {
  2210. if (ssh->userpass_input_echo)
  2211. c_write_str(ssh, "\b \b");
  2212. ssh->userpass_input_bufpos--;
  2213. }
  2214. break;
  2215. case 21:
  2216. case 27:
  2217. while (ssh->userpass_input_bufpos > 0) {
  2218. if (ssh->userpass_input_echo)
  2219. c_write_str(ssh, "\b \b");
  2220. ssh->userpass_input_bufpos--;
  2221. }
  2222. break;
  2223. case 3:
  2224. case 4:
  2225. return -1;
  2226. break;
  2227. default:
  2228. /*
  2229. * This simplistic check for printability is disabled
  2230. * when we're doing password input, because some people
  2231. * have control characters in their passwords.o
  2232. */
  2233. if ((!ssh->userpass_input_echo ||
  2234. (c >= ' ' && c <= '~') ||
  2235. ((unsigned char) c >= 160))
  2236. && ssh->userpass_input_bufpos < ssh->userpass_input_buflen-1) {
  2237. ssh->userpass_input_buffer[ssh->userpass_input_bufpos++] = c;
  2238. if (ssh->userpass_input_echo)
  2239. c_write(ssh, &c, 1);
  2240. }
  2241. break;
  2242. }
  2243. }
  2244. return 0;
  2245. }
  2246. static void ssh_agent_callback(void *sshv, void *reply, int replylen)
  2247. {
  2248. Ssh ssh = (Ssh) sshv;
  2249. ssh->agent_response = reply;
  2250. ssh->agent_response_len = replylen;
  2251. if (ssh->version == 1)
  2252. do_ssh1_login(ssh, NULL, -1, 0);
  2253. else
  2254. do_ssh2_authconn(ssh, NULL, -1, 0);
  2255. }
  2256. static void ssh_agentf_callback(void *cv, void *reply, int replylen)
  2257. {
  2258. struct ssh_channel *c = (struct ssh_channel *)cv;
  2259. Ssh ssh = c->ssh;
  2260. void *sentreply = reply;
  2261. if (!sentreply) {
  2262. /* Fake SSH_AGENT_FAILURE. */
  2263. sentreply = "\0\0\0\1\5";
  2264. replylen = 5;
  2265. }
  2266. if (ssh->version == 2) {
  2267. ssh2_add_channel_data(c, sentreply, replylen);
  2268. ssh2_try_send(c);
  2269. } else {
  2270. send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
  2271. PKT_INT, c->remoteid,
  2272. PKTT_DATA,
  2273. PKT_INT, replylen,
  2274. PKT_DATA, sentreply, replylen,
  2275. PKTT_OTHER,
  2276. PKT_END);
  2277. }
  2278. if (reply)
  2279. sfree(reply);
  2280. }
  2281. /*
  2282. * Handle the key exchange and user authentication phases.
  2283. */
  2284. static int do_ssh1_login(Ssh ssh, unsigned char *in, int inlen, int ispkt)
  2285. {
  2286. int i, j, ret;
  2287. unsigned char cookie[8], *ptr;
  2288. struct RSAKey servkey, hostkey;
  2289. struct MD5Context md5c;
  2290. struct do_ssh1_login_state {
  2291. int len;
  2292. unsigned char *rsabuf, *keystr1, *keystr2;
  2293. unsigned long supported_ciphers_mask, supported_auths_mask;
  2294. int tried_publickey, tried_agent;
  2295. int tis_auth_refused, ccard_auth_refused;
  2296. unsigned char session_id[16];
  2297. int cipher_type;
  2298. char username[100];
  2299. void *publickey_blob;
  2300. int publickey_bloblen;
  2301. char password[100];
  2302. char prompt[200];
  2303. int pos;
  2304. char c;
  2305. int pwpkt_type;
  2306. unsigned char request[5], *response, *p;
  2307. int responselen;
  2308. int keyi, nkeys;
  2309. int authed;
  2310. struct RSAKey key;
  2311. Bignum challenge;
  2312. char *commentp;
  2313. int commentlen;
  2314. };
  2315. crState(do_ssh1_login_state);
  2316. crBegin(ssh->do_ssh1_login_crstate);
  2317. if (!ispkt)
  2318. crWaitUntil(ispkt);
  2319. if (ssh->pktin.type != SSH1_SMSG_PUBLIC_KEY) {
  2320. bombout(("Public key packet not received"));
  2321. crStop(0);
  2322. }
  2323. logevent("Received public keys");
  2324. ptr = ssh_pkt_getdata(ssh, 8);
  2325. if (!ptr) {
  2326. bombout(("SSH1 public key packet stopped before random cookie"));
  2327. crStop(0);
  2328. }
  2329. memcpy(cookie, ptr, 8);
  2330. if (!ssh1_pkt_getrsakey(ssh, &servkey, &s->keystr1) ||
  2331. !ssh1_pkt_getrsakey(ssh, &hostkey, &s->keystr2)) {
  2332. bombout(("Failed to read SSH1 public keys from public key packet"));
  2333. crStop(0);
  2334. }
  2335. /*
  2336. * Log the host key fingerprint.
  2337. */
  2338. {
  2339. char logmsg[80];
  2340. logevent("Host key fingerprint is:");
  2341. strcpy(logmsg, " ");
  2342. hostkey.comment = NULL;
  2343. rsa_fingerprint(logmsg + strlen(logmsg),
  2344. sizeof(logmsg) - strlen(logmsg), &hostkey);
  2345. logevent(logmsg);
  2346. }
  2347. ssh->v1_remote_protoflags = ssh_pkt_getuint32(ssh);
  2348. s->supported_ciphers_mask = ssh_pkt_getuint32(ssh);
  2349. s->supported_auths_mask = ssh_pkt_getuint32(ssh);
  2350. ssh->v1_local_protoflags =
  2351. ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
  2352. ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
  2353. MD5Init(&md5c);
  2354. MD5Update(&md5c, s->keystr2, hostkey.bytes);
  2355. MD5Update(&md5c, s->keystr1, servkey.bytes);
  2356. MD5Update(&md5c, cookie, 8);
  2357. MD5Final(s->session_id, &md5c);
  2358. for (i = 0; i < 32; i++)
  2359. ssh->session_key[i] = random_byte();
  2360. /*
  2361. * Verify that the `bits' and `bytes' parameters match.
  2362. */
  2363. if (hostkey.bits > hostkey.bytes * 8 ||
  2364. servkey.bits > servkey.bytes * 8) {
  2365. bombout(("SSH1 public keys were badly formatted"));
  2366. crStop(0);
  2367. }
  2368. s->len = (hostkey.bytes > servkey.bytes ? hostkey.bytes : servkey.bytes);
  2369. s->rsabuf = snewn(s->len, unsigned char);
  2370. if (!s->rsabuf)
  2371. fatalbox("Out of memory");
  2372. /*
  2373. * Verify the host key.
  2374. */
  2375. {
  2376. /*
  2377. * First format the key into a string.
  2378. */
  2379. int len = rsastr_len(&hostkey);
  2380. char fingerprint[100];
  2381. char *keystr = snewn(len, char);
  2382. if (!keystr)
  2383. fatalbox("Out of memory");
  2384. rsastr_fmt(keystr, &hostkey);
  2385. rsa_fingerprint(fingerprint, sizeof(fingerprint), &hostkey);
  2386. verify_ssh_host_key(ssh->frontend,
  2387. ssh->savedhost, ssh->savedport, "rsa", keystr,
  2388. fingerprint);
  2389. sfree(keystr);
  2390. }
  2391. for (i = 0; i < 32; i++) {
  2392. s->rsabuf[i] = ssh->session_key[i];
  2393. if (i < 16)
  2394. s->rsabuf[i] ^= s->session_id[i];
  2395. }
  2396. if (hostkey.bytes > servkey.bytes) {
  2397. ret = rsaencrypt(s->rsabuf, 32, &servkey);
  2398. if (ret)
  2399. ret = rsaencrypt(s->rsabuf, servkey.bytes, &hostkey);
  2400. } else {
  2401. ret = rsaencrypt(s->rsabuf, 32, &hostkey);
  2402. if (ret)
  2403. ret = rsaencrypt(s->rsabuf, hostkey.bytes, &servkey);
  2404. }
  2405. if (!ret) {
  2406. bombout(("SSH1 public key encryptions failed due to bad formatting"));
  2407. crStop(0);
  2408. }
  2409. logevent("Encrypted session key");
  2410. {
  2411. int cipher_chosen = 0, warn = 0;
  2412. char *cipher_string = NULL;
  2413. int i;
  2414. for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
  2415. int next_cipher = ssh->cfg.ssh_cipherlist[i];
  2416. if (next_cipher == CIPHER_WARN) {
  2417. /* If/when we choose a cipher, warn about it */
  2418. warn = 1;
  2419. } else if (next_cipher == CIPHER_AES) {
  2420. /* XXX Probably don't need to mention this. */
  2421. logevent("AES not supported in SSH1, skipping");
  2422. } else {
  2423. switch (next_cipher) {
  2424. case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
  2425. cipher_string = "3DES"; break;
  2426. case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
  2427. cipher_string = "Blowfish"; break;
  2428. case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
  2429. cipher_string = "single-DES"; break;
  2430. }
  2431. if (s->supported_ciphers_mask & (1 << s->cipher_type))
  2432. cipher_chosen = 1;
  2433. }
  2434. }
  2435. if (!cipher_chosen) {
  2436. if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
  2437. bombout(("Server violates SSH 1 protocol by not "
  2438. "supporting 3DES encryption"));
  2439. else
  2440. /* shouldn't happen */
  2441. bombout(("No supported ciphers found"));
  2442. crStop(0);
  2443. }
  2444. /* Warn about chosen cipher if necessary. */
  2445. if (warn)
  2446. askcipher(ssh->frontend, cipher_string, 0);
  2447. }
  2448. switch (s->cipher_type) {
  2449. case SSH_CIPHER_3DES:
  2450. logevent("Using 3DES encryption");
  2451. break;
  2452. case SSH_CIPHER_DES:
  2453. logevent("Using single-DES encryption");
  2454. break;
  2455. case SSH_CIPHER_BLOWFISH:
  2456. logevent("Using Blowfish encryption");
  2457. break;
  2458. }
  2459. send_packet(ssh, SSH1_CMSG_SESSION_KEY,
  2460. PKT_CHAR, s->cipher_type,
  2461. PKT_DATA, cookie, 8,
  2462. PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
  2463. PKT_DATA, s->rsabuf, s->len,
  2464. PKT_INT, ssh->v1_local_protoflags, PKT_END);
  2465. logevent("Trying to enable encryption...");
  2466. sfree(s->rsabuf);
  2467. ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
  2468. s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
  2469. &ssh_3des);
  2470. ssh->v1_cipher_ctx = ssh->cipher->make_context();
  2471. ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
  2472. logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
  2473. ssh->crcda_ctx = crcda_make_context();
  2474. logevent("Installing CRC compensation attack detector");
  2475. if (servkey.modulus) {
  2476. sfree(servkey.modulus);
  2477. servkey.modulus = NULL;
  2478. }
  2479. if (servkey.exponent) {
  2480. sfree(servkey.exponent);
  2481. servkey.exponent = NULL;
  2482. }
  2483. if (hostkey.modulus) {
  2484. sfree(hostkey.modulus);
  2485. hostkey.modulus = NULL;
  2486. }
  2487. if (hostkey.exponent) {
  2488. sfree(hostkey.exponent);
  2489. hostkey.exponent = NULL;
  2490. }
  2491. crWaitUntil(ispkt);
  2492. if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
  2493. bombout(("Encryption not successfully enabled"));
  2494. crStop(0);
  2495. }
  2496. logevent("Successfully started encryption");
  2497. fflush(stdout);
  2498. {
  2499. if ((flags & FLAG_INTERACTIVE) && !*ssh->cfg.username) {
  2500. if (ssh_get_line && !ssh_getline_pw_only) {
  2501. if (!ssh_get_line("login as: ",
  2502. s->username, sizeof(s->username), FALSE)) {
  2503. /*
  2504. * get_line failed to get a username.
  2505. * Terminate.
  2506. */
  2507. logevent("No username provided. Abandoning session.");
  2508. ssh_closing((Plug)ssh, NULL, 0, 0);
  2509. crStop(1);
  2510. }
  2511. } else {
  2512. int ret; /* need not be kept over crReturn */
  2513. c_write_str(ssh, "login as: ");
  2514. ssh->send_ok = 1;
  2515. setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
  2516. do {
  2517. crWaitUntil(!ispkt);
  2518. ret = process_userpass_input(ssh, in, inlen);
  2519. } while (ret == 0);
  2520. if (ret < 0)
  2521. cleanup_exit(0);
  2522. c_write_str(ssh, "\r\n");
  2523. }
  2524. } else {
  2525. strncpy(s->username, ssh->cfg.username, sizeof(s->username));
  2526. s->username[sizeof(s->username)-1] = '\0';
  2527. }
  2528. send_packet(ssh, SSH1_CMSG_USER, PKT_STR, s->username, PKT_END);
  2529. {
  2530. char userlog[22 + sizeof(s->username)];
  2531. sprintf(userlog, "Sent username \"%s\"", s->username);
  2532. logevent(userlog);
  2533. if (flags & FLAG_INTERACTIVE &&
  2534. (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
  2535. strcat(userlog, "\r\n");
  2536. c_write_str(ssh, userlog);
  2537. }
  2538. }
  2539. }
  2540. crWaitUntil(ispkt);
  2541. if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA)) {
  2542. /* We must not attempt PK auth. Pretend we've already tried it. */
  2543. s->tried_publickey = s->tried_agent = 1;
  2544. } else {
  2545. s->tried_publickey = s->tried_agent = 0;
  2546. }
  2547. s->tis_auth_refused = s->ccard_auth_refused = 0;
  2548. /* Load the public half of ssh->cfg.keyfile so we notice if it's in Pageant */
  2549. if (!filename_is_null(ssh->cfg.keyfile)) {
  2550. if (!rsakey_pubblob(&ssh->cfg.keyfile,
  2551. &s->publickey_blob, &s->publickey_bloblen, NULL))
  2552. s->publickey_blob = NULL;
  2553. } else
  2554. s->publickey_blob = NULL;
  2555. while (ssh->pktin.type == SSH1_SMSG_FAILURE) {
  2556. s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
  2557. if (agent_exists() && !s->tried_agent) {
  2558. /*
  2559. * Attempt RSA authentication using Pageant.
  2560. */
  2561. void *r;
  2562. s->authed = FALSE;
  2563. s->tried_agent = 1;
  2564. logevent("Pageant is running. Requesting keys.");
  2565. /* Request the keys held by the agent. */
  2566. PUT_32BIT(s->request, 1);
  2567. s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
  2568. if (!agent_query(s->request, 5, &r, &s->responselen,
  2569. ssh_agent_callback, ssh)) {
  2570. do {
  2571. crReturn(0);
  2572. if (ispkt) {
  2573. bombout(("Unexpected data from server while waiting"
  2574. " for agent response"));
  2575. crStop(0);
  2576. }
  2577. } while (ispkt || inlen > 0);
  2578. r = ssh->agent_response;
  2579. s->responselen = ssh->agent_response_len;
  2580. }
  2581. s->response = (unsigned char *) r;
  2582. if (s->response && s->responselen >= 5 &&
  2583. s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
  2584. s->p = s->response + 5;
  2585. s->nkeys = GET_32BIT(s->p);
  2586. s->p += 4;
  2587. {
  2588. char buf[64];
  2589. sprintf(buf, "Pageant has %d SSH1 keys", s->nkeys);
  2590. logevent(buf);
  2591. }
  2592. for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
  2593. {
  2594. char buf[64];
  2595. sprintf(buf, "Trying Pageant key #%d", s->keyi);
  2596. logevent(buf);
  2597. }
  2598. if (s->publickey_blob &&
  2599. !memcmp(s->p, s->publickey_blob,
  2600. s->publickey_bloblen)) {
  2601. logevent("This key matches configured key file");
  2602. s->tried_publickey = 1;
  2603. }
  2604. s->p += 4;
  2605. {
  2606. int n, ok = FALSE;
  2607. do { /* do while (0) to make breaking easy */
  2608. n = ssh1_read_bignum
  2609. (s->p, s->responselen-(s->p-s->response),
  2610. &s->key.exponent);
  2611. if (n < 0)
  2612. break;
  2613. s->p += n;
  2614. n = ssh1_read_bignum
  2615. (s->p, s->responselen-(s->p-s->response),
  2616. &s->key.modulus);
  2617. if (n < 0)
  2618. break;
  2619. s->p += n;
  2620. if (s->responselen - (s->p-s->response) < 4)
  2621. break;
  2622. s->commentlen = GET_32BIT(s->p);
  2623. s->p += 4;
  2624. if (s->responselen - (s->p-s->response) <
  2625. s->commentlen)
  2626. break;
  2627. s->commentp = (char *)s->p;
  2628. s->p += s->commentlen;
  2629. ok = TRUE;
  2630. } while (0);
  2631. if (!ok) {
  2632. logevent("Pageant key list packet was truncated");
  2633. break;
  2634. }
  2635. }
  2636. send_packet(ssh, SSH1_CMSG_AUTH_RSA,
  2637. PKT_BIGNUM, s->key.modulus, PKT_END);
  2638. crWaitUntil(ispkt);
  2639. if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
  2640. logevent("Key refused");
  2641. continue;
  2642. }
  2643. logevent("Received RSA challenge");
  2644. if ((s->challenge = ssh1_pkt_getmp(ssh)) == NULL) {
  2645. bombout(("Server's RSA challenge was badly formatted"));
  2646. crStop(0);
  2647. }
  2648. {
  2649. char *agentreq, *q, *ret;
  2650. void *vret;
  2651. int len, retlen;
  2652. len = 1 + 4; /* message type, bit count */
  2653. len += ssh1_bignum_length(s->key.exponent);
  2654. len += ssh1_bignum_length(s->key.modulus);
  2655. len += ssh1_bignum_length(s->challenge);
  2656. len += 16; /* session id */
  2657. len += 4; /* response format */
  2658. agentreq = snewn(4 + len, char);
  2659. PUT_32BIT(agentreq, len);
  2660. q = agentreq + 4;
  2661. *q++ = SSH1_AGENTC_RSA_CHALLENGE;
  2662. PUT_32BIT(q, bignum_bitcount(s->key.modulus));
  2663. q += 4;
  2664. q += ssh1_write_bignum(q, s->key.exponent);
  2665. q += ssh1_write_bignum(q, s->key.modulus);
  2666. q += ssh1_write_bignum(q, s->challenge);
  2667. memcpy(q, s->session_id, 16);
  2668. q += 16;
  2669. PUT_32BIT(q, 1); /* response format */
  2670. if (!agent_query(agentreq, len + 4, &vret, &retlen,
  2671. ssh_agent_callback, ssh)) {
  2672. sfree(agentreq);
  2673. do {
  2674. crReturn(0);
  2675. if (ispkt) {
  2676. bombout(("Unexpected data from server"
  2677. " while waiting for agent"
  2678. " response"));
  2679. crStop(0);
  2680. }
  2681. } while (ispkt || inlen > 0);
  2682. vret = ssh->agent_response;
  2683. retlen = ssh->agent_response_len;
  2684. } else
  2685. sfree(agentreq);
  2686. ret = vret;
  2687. if (ret) {
  2688. if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
  2689. logevent("Sending Pageant's response");
  2690. send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
  2691. PKT_DATA, ret + 5, 16,
  2692. PKT_END);
  2693. sfree(ret);
  2694. crWaitUntil(ispkt);
  2695. if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
  2696. logevent
  2697. ("Pageant's response accepted");
  2698. if (flags & FLAG_VERBOSE) {
  2699. c_write_str(ssh, "Authenticated using"
  2700. " RSA key \"");
  2701. c_write(ssh, s->commentp,
  2702. s->commentlen);
  2703. c_write_str(ssh, "\" from agent\r\n");
  2704. }
  2705. s->authed = TRUE;
  2706. } else
  2707. logevent
  2708. ("Pageant's response not accepted");
  2709. } else {
  2710. logevent
  2711. ("Pageant failed to answer challenge");
  2712. sfree(ret);
  2713. }
  2714. } else {
  2715. logevent("No reply received from Pageant");
  2716. }
  2717. }
  2718. freebn(s->key.exponent);
  2719. freebn(s->key.modulus);
  2720. freebn(s->challenge);
  2721. if (s->authed)
  2722. break;
  2723. }
  2724. sfree(s->response);
  2725. }
  2726. if (s->authed)
  2727. break;
  2728. }
  2729. if (!filename_is_null(ssh->cfg.keyfile) && !s->tried_publickey)
  2730. s->pwpkt_type = SSH1_CMSG_AUTH_RSA;
  2731. if (ssh->cfg.try_tis_auth &&
  2732. (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
  2733. !s->tis_auth_refused) {
  2734. s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
  2735. logevent("Requested TIS authentication");
  2736. send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
  2737. crWaitUntil(ispkt);
  2738. if (ssh->pktin.type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
  2739. logevent("TIS authentication declined");
  2740. if (flags & FLAG_INTERACTIVE)
  2741. c_write_str(ssh, "TIS authentication refused.\r\n");
  2742. s->tis_auth_refused = 1;
  2743. continue;
  2744. } else {
  2745. char *challenge;
  2746. int challengelen;
  2747. ssh_pkt_getstring(ssh, &challenge, &challengelen);
  2748. if (!challenge) {
  2749. bombout(("TIS challenge packet was badly formed"));
  2750. crStop(0);
  2751. }
  2752. logevent("Received TIS challenge");
  2753. if (challengelen > sizeof(s->prompt) - 1)
  2754. challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
  2755. memcpy(s->prompt, challenge, challengelen);
  2756. /* Prompt heuristic comes from OpenSSH */
  2757. strncpy(s->prompt + challengelen,
  2758. memchr(s->prompt, '\n', challengelen) ?
  2759. "": "\r\nResponse: ",
  2760. (sizeof s->prompt) - challengelen);
  2761. s->prompt[(sizeof s->prompt) - 1] = '\0';
  2762. }
  2763. }
  2764. if (ssh->cfg.try_tis_auth &&
  2765. (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
  2766. !s->ccard_auth_refused) {
  2767. s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
  2768. logevent("Requested CryptoCard authentication");
  2769. send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
  2770. crWaitUntil(ispkt);
  2771. if (ssh->pktin.type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
  2772. logevent("CryptoCard authentication declined");
  2773. c_write_str(ssh, "CryptoCard authentication refused.\r\n");
  2774. s->ccard_auth_refused = 1;
  2775. continue;
  2776. } else {
  2777. char *challenge;
  2778. int challengelen;
  2779. ssh_pkt_getstring(ssh, &challenge, &challengelen);
  2780. if (!challenge) {
  2781. bombout(("CryptoCard challenge packet was badly formed"));
  2782. crStop(0);
  2783. }
  2784. logevent("Received CryptoCard challenge");
  2785. if (challengelen > sizeof(s->prompt) - 1)
  2786. challengelen = sizeof(s->prompt) - 1;/* prevent overrun */
  2787. memcpy(s->prompt, challenge, challengelen);
  2788. strncpy(s->prompt + challengelen,
  2789. memchr(s->prompt, '\n', challengelen) ?
  2790. "" : "\r\nResponse: ",
  2791. sizeof(s->prompt) - challengelen);
  2792. s->prompt[sizeof(s->prompt) - 1] = '\0';
  2793. }
  2794. }
  2795. if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
  2796. sprintf(s->prompt, "%.90s@%.90s's password: ",
  2797. s->username, ssh->savedhost);
  2798. }
  2799. if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
  2800. char *comment = NULL;
  2801. int type;
  2802. char msgbuf[256];
  2803. if (flags & FLAG_VERBOSE)
  2804. c_write_str(ssh, "Trying public key authentication.\r\n");
  2805. logeventf(ssh, "Trying public key \"%s\"",
  2806. filename_to_str(&ssh->cfg.keyfile));
  2807. type = key_type(&ssh->cfg.keyfile);
  2808. if (type != SSH_KEYTYPE_SSH1) {
  2809. sprintf(msgbuf, "Key is of wrong type (%s)",
  2810. key_type_to_str(type));
  2811. logevent(msgbuf);
  2812. c_write_str(ssh, msgbuf);
  2813. c_write_str(ssh, "\r\n");
  2814. s->tried_publickey = 1;
  2815. continue;
  2816. }
  2817. if (!rsakey_encrypted(&ssh->cfg.keyfile, &comment)) {
  2818. if (flags & FLAG_VERBOSE)
  2819. c_write_str(ssh, "No passphrase required.\r\n");
  2820. goto tryauth;
  2821. }
  2822. sprintf(s->prompt, "Passphrase for key \"%.100s\": ", comment);
  2823. sfree(comment);
  2824. }
  2825. /*
  2826. * Show password prompt, having first obtained it via a TIS
  2827. * or CryptoCard exchange if we're doing TIS or CryptoCard
  2828. * authentication.
  2829. */
  2830. if (ssh_get_line) {
  2831. if (!ssh_get_line(s->prompt, s->password,
  2832. sizeof(s->password), TRUE)) {
  2833. /*
  2834. * get_line failed to get a password (for example
  2835. * because one was supplied on the command line
  2836. * which has already failed to work). Terminate.
  2837. */
  2838. send_packet(ssh, SSH1_MSG_DISCONNECT,
  2839. PKT_STR, "No more passwords available to try",
  2840. PKT_END);
  2841. logevent("Unable to authenticate");
  2842. connection_fatal(ssh->frontend, "Unable to authenticate");
  2843. ssh_closing((Plug)ssh, NULL, 0, 0);
  2844. crStop(1);
  2845. }
  2846. } else {
  2847. /* Prompt may have come from server. We've munged it a bit, so
  2848. * we know it to be zero-terminated at least once. */
  2849. int ret; /* need not be saved over crReturn */
  2850. c_write_untrusted(ssh, s->prompt, strlen(s->prompt));
  2851. s->pos = 0;
  2852. setup_userpass_input(ssh, s->password, sizeof(s->password), 0);
  2853. do {
  2854. crWaitUntil(!ispkt);
  2855. ret = process_userpass_input(ssh, in, inlen);
  2856. } while (ret == 0);
  2857. if (ret < 0)
  2858. cleanup_exit(0);
  2859. c_write_str(ssh, "\r\n");
  2860. }
  2861. tryauth:
  2862. if (s->pwpkt_type == SSH1_CMSG_AUTH_RSA) {
  2863. /*
  2864. * Try public key authentication with the specified
  2865. * key file.
  2866. */
  2867. s->tried_publickey = 1;
  2868. {
  2869. const char *error = NULL;
  2870. int ret = loadrsakey(&ssh->cfg.keyfile, &s->key, s->password,
  2871. &error);
  2872. if (ret == 0) {
  2873. c_write_str(ssh, "Couldn't load private key from ");
  2874. c_write_str(ssh, filename_to_str(&ssh->cfg.keyfile));
  2875. c_write_str(ssh, " (");
  2876. c_write_str(ssh, error);
  2877. c_write_str(ssh, ").\r\n");
  2878. continue; /* go and try password */
  2879. }
  2880. if (ret == -1) {
  2881. c_write_str(ssh, "Wrong passphrase.\r\n");
  2882. s->tried_publickey = 0;
  2883. continue; /* try again */
  2884. }
  2885. }
  2886. /*
  2887. * Send a public key attempt.
  2888. */
  2889. send_packet(ssh, SSH1_CMSG_AUTH_RSA,
  2890. PKT_BIGNUM, s->key.modulus, PKT_END);
  2891. crWaitUntil(ispkt);
  2892. if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
  2893. c_write_str(ssh, "Server refused our public key.\r\n");
  2894. continue; /* go and try password */
  2895. }
  2896. if (ssh->pktin.type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
  2897. bombout(("Bizarre response to offer of public key"));
  2898. crStop(0);
  2899. }
  2900. {
  2901. int i;
  2902. unsigned char buffer[32];
  2903. Bignum challenge, response;
  2904. if ((challenge = ssh1_pkt_getmp(ssh)) == NULL) {
  2905. bombout(("Server's RSA challenge was badly formatted"));
  2906. crStop(0);
  2907. }
  2908. response = rsadecrypt(challenge, &s->key);
  2909. freebn(s->key.private_exponent);/* burn the evidence */
  2910. for (i = 0; i < 32; i++) {
  2911. buffer[i] = bignum_byte(response, 31 - i);
  2912. }
  2913. MD5Init(&md5c);
  2914. MD5Update(&md5c, buffer, 32);
  2915. MD5Update(&md5c, s->session_id, 16);
  2916. MD5Final(buffer, &md5c);
  2917. send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
  2918. PKT_DATA, buffer, 16, PKT_END);
  2919. freebn(challenge);
  2920. freebn(response);
  2921. }
  2922. crWaitUntil(ispkt);
  2923. if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
  2924. if (flags & FLAG_VERBOSE)
  2925. c_write_str(ssh, "Failed to authenticate with"
  2926. " our public key.\r\n");
  2927. continue; /* go and try password */
  2928. } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
  2929. bombout(("Bizarre response to RSA authentication response"));
  2930. crStop(0);
  2931. }
  2932. break; /* we're through! */
  2933. } else {
  2934. if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
  2935. /*
  2936. * Defence against traffic analysis: we send a
  2937. * whole bunch of packets containing strings of
  2938. * different lengths. One of these strings is the
  2939. * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
  2940. * The others are all random data in
  2941. * SSH1_MSG_IGNORE packets. This way a passive
  2942. * listener can't tell which is the password, and
  2943. * hence can't deduce the password length.
  2944. *
  2945. * Anybody with a password length greater than 16
  2946. * bytes is going to have enough entropy in their
  2947. * password that a listener won't find it _that_
  2948. * much help to know how long it is. So what we'll
  2949. * do is:
  2950. *
  2951. * - if password length < 16, we send 15 packets
  2952. * containing string lengths 1 through 15
  2953. *
  2954. * - otherwise, we let N be the nearest multiple
  2955. * of 8 below the password length, and send 8
  2956. * packets containing string lengths N through
  2957. * N+7. This won't obscure the order of
  2958. * magnitude of the password length, but it will
  2959. * introduce a bit of extra uncertainty.
  2960. *
  2961. * A few servers (the old 1.2.18 through 1.2.22)
  2962. * can't deal with SSH1_MSG_IGNORE. For these
  2963. * servers, we need an alternative defence. We make
  2964. * use of the fact that the password is interpreted
  2965. * as a C string: so we can append a NUL, then some
  2966. * random data.
  2967. *
  2968. * One server (a Cisco one) can deal with neither
  2969. * SSH1_MSG_IGNORE _nor_ a padded password string.
  2970. * For this server we are left with no defences
  2971. * against password length sniffing.
  2972. */
  2973. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE)) {
  2974. /*
  2975. * The server can deal with SSH1_MSG_IGNORE, so
  2976. * we can use the primary defence.
  2977. */
  2978. int bottom, top, pwlen, i;
  2979. char *randomstr;
  2980. pwlen = strlen(s->password);
  2981. if (pwlen < 16) {
  2982. bottom = 0; /* zero length passwords are OK! :-) */
  2983. top = 15;
  2984. } else {
  2985. bottom = pwlen & ~7;
  2986. top = bottom + 7;
  2987. }
  2988. assert(pwlen >= bottom && pwlen <= top);
  2989. randomstr = snewn(top + 1, char);
  2990. for (i = bottom; i <= top; i++) {
  2991. if (i == pwlen) {
  2992. defer_packet(ssh, s->pwpkt_type,
  2993. PKTT_PASSWORD, PKT_STR, s->password,
  2994. PKTT_OTHER, PKT_END);
  2995. } else {
  2996. for (j = 0; j < i; j++) {
  2997. do {
  2998. randomstr[j] = random_byte();
  2999. } while (randomstr[j] == '\0');
  3000. }
  3001. randomstr[i] = '\0';
  3002. defer_packet(ssh, SSH1_MSG_IGNORE,
  3003. PKT_STR, randomstr, PKT_END);
  3004. }
  3005. }
  3006. logevent("Sending password with camouflage packets");
  3007. ssh_pkt_defersend(ssh);
  3008. sfree(randomstr);
  3009. }
  3010. else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
  3011. /*
  3012. * The server can't deal with SSH1_MSG_IGNORE
  3013. * but can deal with padded passwords, so we
  3014. * can use the secondary defence.
  3015. */
  3016. char string[64];
  3017. char *ss;
  3018. int len;
  3019. len = strlen(s->password);
  3020. if (len < sizeof(string)) {
  3021. ss = string;
  3022. strcpy(string, s->password);
  3023. len++; /* cover the zero byte */
  3024. while (len < sizeof(string)) {
  3025. string[len++] = (char) random_byte();
  3026. }
  3027. } else {
  3028. ss = s->password;
  3029. }
  3030. logevent("Sending length-padded password");
  3031. send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
  3032. PKT_INT, len, PKT_DATA, ss, len,
  3033. PKTT_OTHER, PKT_END);
  3034. } else {
  3035. /*
  3036. * The server has _both_
  3037. * BUG_CHOKES_ON_SSH1_IGNORE and
  3038. * BUG_NEEDS_SSH1_PLAIN_PASSWORD. There is
  3039. * therefore nothing we can do.
  3040. */
  3041. int len;
  3042. len = strlen(s->password);
  3043. logevent("Sending unpadded password");
  3044. send_packet(ssh, s->pwpkt_type,
  3045. PKTT_PASSWORD, PKT_INT, len,
  3046. PKT_DATA, s->password, len,
  3047. PKTT_OTHER, PKT_END);
  3048. }
  3049. } else {
  3050. send_packet(ssh, s->pwpkt_type, PKTT_PASSWORD,
  3051. PKT_STR, s->password, PKTT_OTHER, PKT_END);
  3052. }
  3053. }
  3054. logevent("Sent password");
  3055. memset(s->password, 0, strlen(s->password));
  3056. crWaitUntil(ispkt);
  3057. if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
  3058. if (flags & FLAG_VERBOSE)
  3059. c_write_str(ssh, "Access denied\r\n");
  3060. logevent("Authentication refused");
  3061. } else if (ssh->pktin.type != SSH1_SMSG_SUCCESS) {
  3062. bombout(("Strange packet received, type %d", ssh->pktin.type));
  3063. crStop(0);
  3064. }
  3065. }
  3066. logevent("Authentication successful");
  3067. crFinish(1);
  3068. }
  3069. void sshfwd_close(struct ssh_channel *c)
  3070. {
  3071. Ssh ssh = c->ssh;
  3072. if (ssh->state != SSH_STATE_SESSION) {
  3073. assert(ssh->state == SSH_STATE_CLOSED);
  3074. return;
  3075. }
  3076. if (c && !c->closes) {
  3077. /*
  3078. * If the channel's remoteid is -1, we have sent
  3079. * CHANNEL_OPEN for this channel, but it hasn't even been
  3080. * acknowledged by the server. So we must set a close flag
  3081. * on it now, and then when the server acks the channel
  3082. * open, we can close it then.
  3083. */
  3084. if (((int)c->remoteid) != -1) {
  3085. if (ssh->version == 1) {
  3086. send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
  3087. PKT_END);
  3088. } else {
  3089. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
  3090. ssh2_pkt_adduint32(ssh, c->remoteid);
  3091. ssh2_pkt_send(ssh);
  3092. }
  3093. }
  3094. c->closes = 1; /* sent MSG_CLOSE */
  3095. if (c->type == CHAN_X11) {
  3096. c->u.x11.s = NULL;
  3097. logevent("Forwarded X11 connection terminated");
  3098. } else if (c->type == CHAN_SOCKDATA ||
  3099. c->type == CHAN_SOCKDATA_DORMANT) {
  3100. c->u.pfd.s = NULL;
  3101. logevent("Forwarded port closed");
  3102. }
  3103. }
  3104. }
  3105. int sshfwd_write(struct ssh_channel *c, char *buf, int len)
  3106. {
  3107. Ssh ssh = c->ssh;
  3108. if (ssh->state != SSH_STATE_SESSION) {
  3109. assert(ssh->state == SSH_STATE_CLOSED);
  3110. return 0;
  3111. }
  3112. if (ssh->version == 1) {
  3113. send_packet(ssh, SSH1_MSG_CHANNEL_DATA,
  3114. PKT_INT, c->remoteid,
  3115. PKTT_DATA,
  3116. PKT_INT, len, PKT_DATA, buf, len,
  3117. PKTT_OTHER, PKT_END);
  3118. /*
  3119. * In SSH1 we can return 0 here - implying that forwarded
  3120. * connections are never individually throttled - because
  3121. * the only circumstance that can cause throttling will be
  3122. * the whole SSH connection backing up, in which case
  3123. * _everything_ will be throttled as a whole.
  3124. */
  3125. return 0;
  3126. } else {
  3127. ssh2_add_channel_data(c, buf, len);
  3128. return ssh2_try_send(c);
  3129. }
  3130. }
  3131. void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
  3132. {
  3133. Ssh ssh = c->ssh;
  3134. if (ssh->state != SSH_STATE_SESSION) {
  3135. assert(ssh->state == SSH_STATE_CLOSED);
  3136. return;
  3137. }
  3138. if (ssh->version == 1) {
  3139. if (c->v.v1.throttling && bufsize < SSH1_BUFFER_LIMIT) {
  3140. c->v.v1.throttling = 0;
  3141. ssh1_throttle(ssh, -1);
  3142. }
  3143. } else {
  3144. ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
  3145. }
  3146. }
  3147. static void ssh1_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
  3148. {
  3149. crBegin(ssh->ssh1_protocol_crstate);
  3150. random_init();
  3151. while (!do_ssh1_login(ssh, in, inlen, ispkt)) {
  3152. crReturnV;
  3153. }
  3154. if (ssh->state == SSH_STATE_CLOSED)
  3155. crReturnV;
  3156. if (ssh->cfg.agentfwd && agent_exists()) {
  3157. logevent("Requesting agent forwarding");
  3158. send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
  3159. do {
  3160. crReturnV;
  3161. } while (!ispkt);
  3162. if (ssh->pktin.type != SSH1_SMSG_SUCCESS
  3163. && ssh->pktin.type != SSH1_SMSG_FAILURE) {
  3164. bombout(("Protocol confusion"));
  3165. crStopV;
  3166. } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
  3167. logevent("Agent forwarding refused");
  3168. } else {
  3169. logevent("Agent forwarding enabled");
  3170. ssh->agentfwd_enabled = TRUE;
  3171. }
  3172. }
  3173. if (ssh->cfg.x11_forward) {
  3174. char proto[20], data[64];
  3175. logevent("Requesting X11 forwarding");
  3176. ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
  3177. data, sizeof(data), ssh->cfg.x11_auth);
  3178. x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
  3179. if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
  3180. send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
  3181. PKT_STR, proto, PKT_STR, data,
  3182. PKT_INT, x11_get_screen_number(ssh->cfg.x11_display),
  3183. PKT_END);
  3184. } else {
  3185. send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
  3186. PKT_STR, proto, PKT_STR, data, PKT_END);
  3187. }
  3188. do {
  3189. crReturnV;
  3190. } while (!ispkt);
  3191. if (ssh->pktin.type != SSH1_SMSG_SUCCESS
  3192. && ssh->pktin.type != SSH1_SMSG_FAILURE) {
  3193. bombout(("Protocol confusion"));
  3194. crStopV;
  3195. } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
  3196. logevent("X11 forwarding refused");
  3197. } else {
  3198. logevent("X11 forwarding enabled");
  3199. ssh->X11_fwd_enabled = TRUE;
  3200. }
  3201. }
  3202. {
  3203. char type;
  3204. int n;
  3205. int sport,dport,sserv,dserv;
  3206. char sports[256], dports[256], saddr[256], host[256];
  3207. ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
  3208. /* Add port forwardings. */
  3209. ssh->portfwd_strptr = ssh->cfg.portfwd;
  3210. while (*ssh->portfwd_strptr) {
  3211. type = *ssh->portfwd_strptr++;
  3212. saddr[0] = '\0';
  3213. n = 0;
  3214. while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
  3215. if (*ssh->portfwd_strptr == ':') {
  3216. /*
  3217. * We've seen a colon in the middle of the
  3218. * source port number. This means that
  3219. * everything we've seen until now is the
  3220. * source _address_, so we'll move it into
  3221. * saddr and start sports from the beginning
  3222. * again.
  3223. */
  3224. ssh->portfwd_strptr++;
  3225. sports[n] = '\0';
  3226. strcpy(saddr, sports);
  3227. n = 0;
  3228. }
  3229. if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
  3230. }
  3231. sports[n] = 0;
  3232. if (type != 'D') {
  3233. if (*ssh->portfwd_strptr == '\t')
  3234. ssh->portfwd_strptr++;
  3235. n = 0;
  3236. while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
  3237. if (n < 255) host[n++] = *ssh->portfwd_strptr++;
  3238. }
  3239. host[n] = 0;
  3240. if (*ssh->portfwd_strptr == ':')
  3241. ssh->portfwd_strptr++;
  3242. n = 0;
  3243. while (*ssh->portfwd_strptr) {
  3244. if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
  3245. }
  3246. dports[n] = 0;
  3247. ssh->portfwd_strptr++;
  3248. dport = atoi(dports);
  3249. dserv = 0;
  3250. if (dport == 0) {
  3251. dserv = 1;
  3252. dport = net_service_lookup(dports);
  3253. if (!dport) {
  3254. logeventf(ssh, "Service lookup failed for"
  3255. " destination port \"%s\"", dports);
  3256. }
  3257. }
  3258. } else {
  3259. while (*ssh->portfwd_strptr) ssh->portfwd_strptr++;
  3260. dport = dserv = -1;
  3261. ssh->portfwd_strptr++; /* eat the NUL and move to next one */
  3262. }
  3263. sport = atoi(sports);
  3264. sserv = 0;
  3265. if (sport == 0) {
  3266. sserv = 1;
  3267. sport = net_service_lookup(sports);
  3268. if (!sport) {
  3269. logeventf(ssh, "Service lookup failed for source"
  3270. " port \"%s\"", sports);
  3271. }
  3272. }
  3273. if (sport && dport) {
  3274. /* Set up a description of the source port. */
  3275. static char *sportdesc;
  3276. sportdesc = dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
  3277. (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
  3278. (int)(*saddr?1:0), ":",
  3279. (int)(sserv ? strlen(sports) : 0), sports,
  3280. sserv, "(", sport, sserv, ")");
  3281. if (type == 'L') {
  3282. /* Verbose description of the destination port */
  3283. char *dportdesc = dupprintf("%s:%.*s%.*s%d%.*s",
  3284. host,
  3285. (int)(dserv ? strlen(dports) : 0), dports,
  3286. dserv, "(", dport, dserv, ")");
  3287. const char *err = pfd_addforward(host, dport,
  3288. *saddr ? saddr : NULL,
  3289. sport, ssh, &ssh->cfg);
  3290. if (err) {
  3291. logeventf(ssh, "Local port %s forward to %s"
  3292. " failed: %s", sportdesc, dportdesc, err);
  3293. } else {
  3294. logeventf(ssh, "Local port %s forwarding to %s",
  3295. sportdesc, dportdesc);
  3296. }
  3297. sfree(dportdesc);
  3298. } else if (type == 'D') {
  3299. const char *err = pfd_addforward(NULL, -1,
  3300. *saddr ? saddr : NULL,
  3301. sport, ssh, &ssh->cfg);
  3302. if (err) {
  3303. logeventf(ssh, "Local port %s SOCKS dynamic forward"
  3304. " setup failed: %s", sportdesc, err);
  3305. } else {
  3306. logeventf(ssh, "Local port %s doing SOCKS"
  3307. " dynamic forwarding", sportdesc);
  3308. }
  3309. } else {
  3310. struct ssh_rportfwd *pf;
  3311. pf = snew(struct ssh_rportfwd);
  3312. strcpy(pf->dhost, host);
  3313. pf->dport = dport;
  3314. if (*saddr) {
  3315. logeventf(ssh,
  3316. "SSH1 cannot handle source address spec \"%s:%d\"; ignoring",
  3317. saddr, sport);
  3318. }
  3319. if (add234(ssh->rportfwds, pf) != pf) {
  3320. logeventf(ssh,
  3321. "Duplicate remote port forwarding to %s:%d",
  3322. host, dport);
  3323. sfree(pf);
  3324. } else {
  3325. logeventf(ssh, "Requesting remote port %.*s%.*s%d%.*s"
  3326. " forward to %s:%.*s%.*s%d%.*s",
  3327. (int)(sserv ? strlen(sports) : 0), sports,
  3328. sserv, "(", sport, sserv, ")",
  3329. host,
  3330. (int)(dserv ? strlen(dports) : 0), dports,
  3331. dserv, "(", dport, dserv, ")");
  3332. send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
  3333. PKT_INT, sport,
  3334. PKT_STR, host,
  3335. PKT_INT, dport,
  3336. PKT_END);
  3337. do {
  3338. crReturnV;
  3339. } while (!ispkt);
  3340. if (ssh->pktin.type != SSH1_SMSG_SUCCESS
  3341. && ssh->pktin.type != SSH1_SMSG_FAILURE) {
  3342. bombout(("Protocol confusion"));
  3343. crStopV;
  3344. } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
  3345. c_write_str(ssh, "Server refused port"
  3346. " forwarding\r\n");
  3347. }
  3348. logevent("Remote port forwarding enabled");
  3349. }
  3350. }
  3351. sfree(sportdesc);
  3352. }
  3353. }
  3354. }
  3355. if (!ssh->cfg.nopty) {
  3356. /* Unpick the terminal-speed string. */
  3357. /* XXX perhaps we should allow no speeds to be sent. */
  3358. ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
  3359. sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
  3360. /* Send the pty request. */
  3361. send_packet(ssh, SSH1_CMSG_REQUEST_PTY,
  3362. PKT_STR, ssh->cfg.termtype,
  3363. PKT_INT, ssh->term_height,
  3364. PKT_INT, ssh->term_width,
  3365. PKT_INT, 0, PKT_INT, 0, /* width,height in pixels */
  3366. PKT_CHAR, 192, PKT_INT, ssh->ispeed, /* TTY_OP_ISPEED */
  3367. PKT_CHAR, 193, PKT_INT, ssh->ospeed, /* TTY_OP_OSPEED */
  3368. PKT_CHAR, 0, PKT_END);
  3369. ssh->state = SSH_STATE_INTERMED;
  3370. do {
  3371. crReturnV;
  3372. } while (!ispkt);
  3373. if (ssh->pktin.type != SSH1_SMSG_SUCCESS
  3374. && ssh->pktin.type != SSH1_SMSG_FAILURE) {
  3375. bombout(("Protocol confusion"));
  3376. crStopV;
  3377. } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
  3378. c_write_str(ssh, "Server refused to allocate pty\r\n");
  3379. ssh->editing = ssh->echoing = 1;
  3380. }
  3381. logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
  3382. ssh->ospeed, ssh->ispeed);
  3383. } else {
  3384. ssh->editing = ssh->echoing = 1;
  3385. }
  3386. if (ssh->cfg.compression) {
  3387. send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
  3388. do {
  3389. crReturnV;
  3390. } while (!ispkt);
  3391. if (ssh->pktin.type != SSH1_SMSG_SUCCESS
  3392. && ssh->pktin.type != SSH1_SMSG_FAILURE) {
  3393. bombout(("Protocol confusion"));
  3394. crStopV;
  3395. } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
  3396. c_write_str(ssh, "Server refused to compress\r\n");
  3397. }
  3398. logevent("Started compression");
  3399. ssh->v1_compressing = TRUE;
  3400. ssh->cs_comp_ctx = zlib_compress_init();
  3401. logevent("Initialised zlib (RFC1950) compression");
  3402. ssh->sc_comp_ctx = zlib_decompress_init();
  3403. logevent("Initialised zlib (RFC1950) decompression");
  3404. }
  3405. /*
  3406. * Start the shell or command.
  3407. *
  3408. * Special case: if the first-choice command is an SSH2
  3409. * subsystem (hence not usable here) and the second choice
  3410. * exists, we fall straight back to that.
  3411. */
  3412. {
  3413. char *cmd = ssh->cfg.remote_cmd_ptr;
  3414. if (ssh->cfg.ssh_subsys && ssh->cfg.remote_cmd_ptr2) {
  3415. cmd = ssh->cfg.remote_cmd_ptr2;
  3416. ssh->fallback_cmd = TRUE;
  3417. }
  3418. if (*cmd)
  3419. send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
  3420. else
  3421. send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
  3422. logevent("Started session");
  3423. }
  3424. ssh->state = SSH_STATE_SESSION;
  3425. if (ssh->size_needed)
  3426. ssh_size(ssh, ssh->term_width, ssh->term_height);
  3427. if (ssh->eof_needed)
  3428. ssh_special(ssh, TS_EOF);
  3429. if (ssh->ldisc)
  3430. ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
  3431. ssh->send_ok = 1;
  3432. ssh->channels = newtree234(ssh_channelcmp);
  3433. while (1) {
  3434. crReturnV;
  3435. if (ispkt) {
  3436. if (ssh->pktin.type == SSH1_SMSG_STDOUT_DATA ||
  3437. ssh->pktin.type == SSH1_SMSG_STDERR_DATA) {
  3438. char *string;
  3439. int stringlen, bufsize;
  3440. ssh_pkt_getstring(ssh, &string, &stringlen);
  3441. if (string == NULL) {
  3442. bombout(("Incoming terminal data packet was badly formed"));
  3443. crStopV;
  3444. }
  3445. bufsize =
  3446. from_backend(ssh->frontend,
  3447. ssh->pktin.type == SSH1_SMSG_STDERR_DATA,
  3448. string, stringlen);
  3449. if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
  3450. ssh->v1_stdout_throttling = 1;
  3451. ssh1_throttle(ssh, +1);
  3452. }
  3453. } else if (ssh->pktin.type == SSH1_MSG_DISCONNECT) {
  3454. ssh_closing((Plug)ssh, NULL, 0, 0);
  3455. logevent("Received disconnect request");
  3456. crStopV;
  3457. } else if (ssh->pktin.type == SSH1_SMSG_X11_OPEN) {
  3458. /* Remote side is trying to open a channel to talk to our
  3459. * X-Server. Give them back a local channel number. */
  3460. struct ssh_channel *c;
  3461. int remoteid = ssh_pkt_getuint32(ssh);
  3462. logevent("Received X11 connect request");
  3463. /* Refuse if X11 forwarding is disabled. */
  3464. if (!ssh->X11_fwd_enabled) {
  3465. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  3466. PKT_INT, remoteid, PKT_END);
  3467. logevent("Rejected X11 connect request");
  3468. } else {
  3469. c = snew(struct ssh_channel);
  3470. c->ssh = ssh;
  3471. if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
  3472. ssh->x11auth, NULL, -1, &ssh->cfg) != NULL) {
  3473. logevent("Opening X11 forward connection failed");
  3474. sfree(c);
  3475. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  3476. PKT_INT, remoteid, PKT_END);
  3477. } else {
  3478. logevent
  3479. ("Opening X11 forward connection succeeded");
  3480. c->remoteid = remoteid;
  3481. c->localid = alloc_channel_id(ssh);
  3482. c->closes = 0;
  3483. c->v.v1.throttling = 0;
  3484. c->type = CHAN_X11; /* identify channel type */
  3485. add234(ssh->channels, c);
  3486. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  3487. PKT_INT, c->remoteid, PKT_INT,
  3488. c->localid, PKT_END);
  3489. logevent("Opened X11 forward channel");
  3490. }
  3491. }
  3492. } else if (ssh->pktin.type == SSH1_SMSG_AGENT_OPEN) {
  3493. /* Remote side is trying to open a channel to talk to our
  3494. * agent. Give them back a local channel number. */
  3495. struct ssh_channel *c;
  3496. int remoteid = ssh_pkt_getuint32(ssh);
  3497. /* Refuse if agent forwarding is disabled. */
  3498. if (!ssh->agentfwd_enabled) {
  3499. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  3500. PKT_INT, remoteid, PKT_END);
  3501. } else {
  3502. c = snew(struct ssh_channel);
  3503. c->ssh = ssh;
  3504. c->remoteid = remoteid;
  3505. c->localid = alloc_channel_id(ssh);
  3506. c->closes = 0;
  3507. c->v.v1.throttling = 0;
  3508. c->type = CHAN_AGENT; /* identify channel type */
  3509. c->u.a.lensofar = 0;
  3510. add234(ssh->channels, c);
  3511. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  3512. PKT_INT, c->remoteid, PKT_INT, c->localid,
  3513. PKT_END);
  3514. }
  3515. } else if (ssh->pktin.type == SSH1_MSG_PORT_OPEN) {
  3516. /* Remote side is trying to open a channel to talk to a
  3517. * forwarded port. Give them back a local channel number. */
  3518. struct ssh_channel *c;
  3519. struct ssh_rportfwd pf;
  3520. int remoteid;
  3521. int hostsize, port;
  3522. char *host, buf[1024];
  3523. const char *e;
  3524. c = snew(struct ssh_channel);
  3525. c->ssh = ssh;
  3526. remoteid = ssh_pkt_getuint32(ssh);
  3527. ssh_pkt_getstring(ssh, &host, &hostsize);
  3528. port = ssh_pkt_getuint32(ssh);
  3529. if (hostsize >= lenof(pf.dhost))
  3530. hostsize = lenof(pf.dhost)-1;
  3531. memcpy(pf.dhost, host, hostsize);
  3532. pf.dhost[hostsize] = '\0';
  3533. pf.dport = port;
  3534. if (find234(ssh->rportfwds, &pf, NULL) == NULL) {
  3535. sprintf(buf, "Rejected remote port open request for %s:%d",
  3536. pf.dhost, port);
  3537. logevent(buf);
  3538. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  3539. PKT_INT, remoteid, PKT_END);
  3540. } else {
  3541. sprintf(buf, "Received remote port open request for %s:%d",
  3542. pf.dhost, port);
  3543. logevent(buf);
  3544. e = pfd_newconnect(&c->u.pfd.s, pf.dhost, port,
  3545. c, &ssh->cfg);
  3546. if (e != NULL) {
  3547. char buf[256];
  3548. sprintf(buf, "Port open failed: %s", e);
  3549. logevent(buf);
  3550. sfree(c);
  3551. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  3552. PKT_INT, remoteid, PKT_END);
  3553. } else {
  3554. c->remoteid = remoteid;
  3555. c->localid = alloc_channel_id(ssh);
  3556. c->closes = 0;
  3557. c->v.v1.throttling = 0;
  3558. c->type = CHAN_SOCKDATA; /* identify channel type */
  3559. add234(ssh->channels, c);
  3560. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  3561. PKT_INT, c->remoteid, PKT_INT,
  3562. c->localid, PKT_END);
  3563. logevent("Forwarded port opened successfully");
  3564. }
  3565. }
  3566. } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_CONFIRMATION) {
  3567. unsigned int remoteid = ssh_pkt_getuint32(ssh);
  3568. unsigned int localid = ssh_pkt_getuint32(ssh);
  3569. struct ssh_channel *c;
  3570. c = find234(ssh->channels, &remoteid, ssh_channelfind);
  3571. if (c && c->type == CHAN_SOCKDATA_DORMANT) {
  3572. c->remoteid = localid;
  3573. c->type = CHAN_SOCKDATA;
  3574. c->v.v1.throttling = 0;
  3575. pfd_confirm(c->u.pfd.s);
  3576. }
  3577. if (c && c->closes) {
  3578. /*
  3579. * We have a pending close on this channel,
  3580. * which we decided on before the server acked
  3581. * the channel open. So now we know the
  3582. * remoteid, we can close it again.
  3583. */
  3584. send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE,
  3585. PKT_INT, c->remoteid, PKT_END);
  3586. }
  3587. } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_OPEN_FAILURE) {
  3588. unsigned int remoteid = ssh_pkt_getuint32(ssh);
  3589. struct ssh_channel *c;
  3590. c = find234(ssh->channels, &remoteid, ssh_channelfind);
  3591. if (c && c->type == CHAN_SOCKDATA_DORMANT) {
  3592. logevent("Forwarded connection refused by server");
  3593. pfd_close(c->u.pfd.s);
  3594. del234(ssh->channels, c);
  3595. sfree(c);
  3596. }
  3597. } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ||
  3598. ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION) {
  3599. /* Remote side closes a channel. */
  3600. unsigned i = ssh_pkt_getuint32(ssh);
  3601. struct ssh_channel *c;
  3602. c = find234(ssh->channels, &i, ssh_channelfind);
  3603. if (c && ((int)c->remoteid) != -1) {
  3604. int closetype;
  3605. closetype =
  3606. (ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? 1 : 2);
  3607. if ((c->closes == 0) && (c->type == CHAN_X11)) {
  3608. logevent("Forwarded X11 connection terminated");
  3609. assert(c->u.x11.s != NULL);
  3610. x11_close(c->u.x11.s);
  3611. c->u.x11.s = NULL;
  3612. }
  3613. if ((c->closes == 0) && (c->type == CHAN_SOCKDATA)) {
  3614. logevent("Forwarded port closed");
  3615. assert(c->u.pfd.s != NULL);
  3616. pfd_close(c->u.pfd.s);
  3617. c->u.pfd.s = NULL;
  3618. }
  3619. c->closes |= (closetype << 2); /* seen this message */
  3620. if (!(c->closes & closetype)) {
  3621. send_packet(ssh, ssh->pktin.type, PKT_INT, c->remoteid,
  3622. PKT_END);
  3623. c->closes |= closetype; /* sent it too */
  3624. }
  3625. if (c->closes == 15) {
  3626. del234(ssh->channels, c);
  3627. sfree(c);
  3628. }
  3629. } else {
  3630. bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
  3631. ssh->pktin.type == SSH1_MSG_CHANNEL_CLOSE ? "" :
  3632. "_CONFIRMATION", c ? "half-open" : "nonexistent",
  3633. i));
  3634. crStopV;
  3635. }
  3636. } else if (ssh->pktin.type == SSH1_MSG_CHANNEL_DATA) {
  3637. /* Data sent down one of our channels. */
  3638. int i = ssh_pkt_getuint32(ssh);
  3639. char *p;
  3640. int len;
  3641. struct ssh_channel *c;
  3642. ssh_pkt_getstring(ssh, &p, &len);
  3643. c = find234(ssh->channels, &i, ssh_channelfind);
  3644. if (c) {
  3645. int bufsize = 0;
  3646. switch (c->type) {
  3647. case CHAN_X11:
  3648. bufsize = x11_send(c->u.x11.s, p, len);
  3649. break;
  3650. case CHAN_SOCKDATA:
  3651. bufsize = pfd_send(c->u.pfd.s, p, len);
  3652. break;
  3653. case CHAN_AGENT:
  3654. /* Data for an agent message. Buffer it. */
  3655. while (len > 0) {
  3656. if (c->u.a.lensofar < 4) {
  3657. int l = min(4 - c->u.a.lensofar, len);
  3658. memcpy(c->u.a.msglen + c->u.a.lensofar, p,
  3659. l);
  3660. p += l;
  3661. len -= l;
  3662. c->u.a.lensofar += l;
  3663. }
  3664. if (c->u.a.lensofar == 4) {
  3665. c->u.a.totallen =
  3666. 4 + GET_32BIT(c->u.a.msglen);
  3667. c->u.a.message = snewn(c->u.a.totallen,
  3668. unsigned char);
  3669. memcpy(c->u.a.message, c->u.a.msglen, 4);
  3670. }
  3671. if (c->u.a.lensofar >= 4 && len > 0) {
  3672. int l =
  3673. min(c->u.a.totallen - c->u.a.lensofar,
  3674. len);
  3675. memcpy(c->u.a.message + c->u.a.lensofar, p,
  3676. l);
  3677. p += l;
  3678. len -= l;
  3679. c->u.a.lensofar += l;
  3680. }
  3681. if (c->u.a.lensofar == c->u.a.totallen) {
  3682. void *reply;
  3683. int replylen;
  3684. if (agent_query(c->u.a.message,
  3685. c->u.a.totallen,
  3686. &reply, &replylen,
  3687. ssh_agentf_callback, c))
  3688. ssh_agentf_callback(c, reply, replylen);
  3689. sfree(c->u.a.message);
  3690. c->u.a.lensofar = 0;
  3691. }
  3692. }
  3693. bufsize = 0; /* agent channels never back up */
  3694. break;
  3695. }
  3696. if (!c->v.v1.throttling && bufsize > SSH1_BUFFER_LIMIT) {
  3697. c->v.v1.throttling = 1;
  3698. ssh1_throttle(ssh, +1);
  3699. }
  3700. }
  3701. } else if (ssh->pktin.type == SSH1_SMSG_SUCCESS) {
  3702. /* may be from EXEC_SHELL on some servers */
  3703. } else if (ssh->pktin.type == SSH1_SMSG_FAILURE) {
  3704. /* may be from EXEC_SHELL on some servers
  3705. * if no pty is available or in other odd cases. Ignore */
  3706. } else if (ssh->pktin.type == SSH1_SMSG_EXIT_STATUS) {
  3707. char buf[100];
  3708. ssh->exitcode = ssh_pkt_getuint32(ssh);
  3709. sprintf(buf, "Server sent command exit status %d",
  3710. ssh->exitcode);
  3711. logevent(buf);
  3712. send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
  3713. /*
  3714. * In case `helpful' firewalls or proxies tack
  3715. * extra human-readable text on the end of the
  3716. * session which we might mistake for another
  3717. * encrypted packet, we close the session once
  3718. * we've sent EXIT_CONFIRMATION.
  3719. */
  3720. ssh_closing((Plug)ssh, NULL, 0, 0);
  3721. crStopV;
  3722. } else {
  3723. bombout(("Strange packet received: type %d", ssh->pktin.type));
  3724. crStopV;
  3725. }
  3726. } else {
  3727. while (inlen > 0) {
  3728. int len = min(inlen, 512);
  3729. send_packet(ssh, SSH1_CMSG_STDIN_DATA, PKTT_DATA,
  3730. PKT_INT, len, PKT_DATA, in, len,
  3731. PKTT_OTHER, PKT_END);
  3732. in += len;
  3733. inlen -= len;
  3734. }
  3735. }
  3736. }
  3737. crFinishV;
  3738. }
  3739. /*
  3740. * Utility routine for decoding comma-separated strings in KEXINIT.
  3741. */
  3742. static int in_commasep_string(char *needle, char *haystack, int haylen)
  3743. {
  3744. int needlen;
  3745. if (!needle || !haystack) /* protect against null pointers */
  3746. return 0;
  3747. needlen = strlen(needle);
  3748. while (1) {
  3749. /*
  3750. * Is it at the start of the string?
  3751. */
  3752. if (haylen >= needlen && /* haystack is long enough */
  3753. !memcmp(needle, haystack, needlen) && /* initial match */
  3754. (haylen == needlen || haystack[needlen] == ',')
  3755. /* either , or EOS follows */
  3756. )
  3757. return 1;
  3758. /*
  3759. * If not, search for the next comma and resume after that.
  3760. * If no comma found, terminate.
  3761. */
  3762. while (haylen > 0 && *haystack != ',')
  3763. haylen--, haystack++;
  3764. if (haylen == 0)
  3765. return 0;
  3766. haylen--, haystack++; /* skip over comma itself */
  3767. }
  3768. }
  3769. /*
  3770. * SSH2 key creation method.
  3771. */
  3772. static void ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
  3773. unsigned char *sessid, char chr,
  3774. unsigned char *keyspace)
  3775. {
  3776. SHA_State s;
  3777. /* First 20 bytes. */
  3778. SHA_Init(&s);
  3779. if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
  3780. sha_mpint(&s, K);
  3781. SHA_Bytes(&s, H, 20);
  3782. SHA_Bytes(&s, &chr, 1);
  3783. SHA_Bytes(&s, sessid, 20);
  3784. SHA_Final(&s, keyspace);
  3785. /* Next 20 bytes. */
  3786. SHA_Init(&s);
  3787. if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
  3788. sha_mpint(&s, K);
  3789. SHA_Bytes(&s, H, 20);
  3790. SHA_Bytes(&s, keyspace, 20);
  3791. SHA_Final(&s, keyspace + 20);
  3792. }
  3793. /*
  3794. * Handle the SSH2 transport layer.
  3795. */
  3796. static int do_ssh2_transport(Ssh ssh, unsigned char *in, int inlen, int ispkt)
  3797. {
  3798. struct do_ssh2_transport_state {
  3799. int nbits, pbits, warn;
  3800. Bignum p, g, e, f, K;
  3801. int kex_init_value, kex_reply_value;
  3802. const struct ssh_mac **maclist;
  3803. int nmacs;
  3804. const struct ssh2_cipher *cscipher_tobe;
  3805. const struct ssh2_cipher *sccipher_tobe;
  3806. const struct ssh_mac *csmac_tobe;
  3807. const struct ssh_mac *scmac_tobe;
  3808. const struct ssh_compress *cscomp_tobe;
  3809. const struct ssh_compress *sccomp_tobe;
  3810. char *hostkeydata, *sigdata, *keystr, *fingerprint;
  3811. int hostkeylen, siglen;
  3812. void *hkey; /* actual host key */
  3813. unsigned char exchange_hash[20];
  3814. int n_preferred_ciphers;
  3815. const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
  3816. const struct ssh_compress *preferred_comp;
  3817. int first_kex;
  3818. };
  3819. crState(do_ssh2_transport_state);
  3820. crBegin(ssh->do_ssh2_transport_crstate);
  3821. s->cscipher_tobe = s->sccipher_tobe = NULL;
  3822. s->csmac_tobe = s->scmac_tobe = NULL;
  3823. s->cscomp_tobe = s->sccomp_tobe = NULL;
  3824. random_init();
  3825. s->first_kex = 1;
  3826. {
  3827. int i;
  3828. /*
  3829. * Set up the preferred ciphers. (NULL => warn below here)
  3830. */
  3831. s->n_preferred_ciphers = 0;
  3832. for (i = 0; i < CIPHER_MAX; i++) {
  3833. switch (ssh->cfg.ssh_cipherlist[i]) {
  3834. case CIPHER_BLOWFISH:
  3835. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
  3836. break;
  3837. case CIPHER_DES:
  3838. if (ssh->cfg.ssh2_des_cbc) {
  3839. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
  3840. }
  3841. break;
  3842. case CIPHER_3DES:
  3843. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
  3844. break;
  3845. case CIPHER_AES:
  3846. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
  3847. break;
  3848. case CIPHER_WARN:
  3849. /* Flag for later. Don't bother if it's the last in
  3850. * the list. */
  3851. if (i < CIPHER_MAX - 1) {
  3852. s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
  3853. }
  3854. break;
  3855. }
  3856. }
  3857. }
  3858. /*
  3859. * Set up preferred compression.
  3860. */
  3861. if (ssh->cfg.compression)
  3862. s->preferred_comp = &ssh_zlib;
  3863. else
  3864. s->preferred_comp = &ssh_comp_none;
  3865. /*
  3866. * Be prepared to work around the buggy MAC problem.
  3867. */
  3868. if (ssh->remote_bugs & BUG_SSH2_HMAC)
  3869. s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
  3870. else
  3871. s->maclist = macs, s->nmacs = lenof(macs);
  3872. begin_key_exchange:
  3873. {
  3874. int i, j, cipherstr_started;
  3875. /*
  3876. * Construct and send our key exchange packet.
  3877. */
  3878. ssh2_pkt_init(ssh, SSH2_MSG_KEXINIT);
  3879. for (i = 0; i < 16; i++)
  3880. ssh2_pkt_addbyte(ssh, (unsigned char) random_byte());
  3881. /* List key exchange algorithms. */
  3882. ssh2_pkt_addstring_start(ssh);
  3883. for (i = 0; i < lenof(kex_algs); i++) {
  3884. if (kex_algs[i] == &ssh_diffiehellman_gex &&
  3885. (ssh->remote_bugs & BUG_SSH2_DH_GEX))
  3886. continue;
  3887. ssh2_pkt_addstring_str(ssh, kex_algs[i]->name);
  3888. if (i < lenof(kex_algs) - 1)
  3889. ssh2_pkt_addstring_str(ssh, ",");
  3890. }
  3891. /* List server host key algorithms. */
  3892. ssh2_pkt_addstring_start(ssh);
  3893. for (i = 0; i < lenof(hostkey_algs); i++) {
  3894. ssh2_pkt_addstring_str(ssh, hostkey_algs[i]->name);
  3895. if (i < lenof(hostkey_algs) - 1)
  3896. ssh2_pkt_addstring_str(ssh, ",");
  3897. }
  3898. /* List client->server encryption algorithms. */
  3899. ssh2_pkt_addstring_start(ssh);
  3900. cipherstr_started = 0;
  3901. for (i = 0; i < s->n_preferred_ciphers; i++) {
  3902. const struct ssh2_ciphers *c = s->preferred_ciphers[i];
  3903. if (!c) continue; /* warning flag */
  3904. for (j = 0; j < c->nciphers; j++) {
  3905. if (cipherstr_started)
  3906. ssh2_pkt_addstring_str(ssh, ",");
  3907. ssh2_pkt_addstring_str(ssh, c->list[j]->name);
  3908. cipherstr_started = 1;
  3909. }
  3910. }
  3911. /* List server->client encryption algorithms. */
  3912. ssh2_pkt_addstring_start(ssh);
  3913. cipherstr_started = 0;
  3914. for (i = 0; i < s->n_preferred_ciphers; i++) {
  3915. const struct ssh2_ciphers *c = s->preferred_ciphers[i];
  3916. if (!c) continue; /* warning flag */
  3917. for (j = 0; j < c->nciphers; j++) {
  3918. if (cipherstr_started)
  3919. ssh2_pkt_addstring_str(ssh, ",");
  3920. ssh2_pkt_addstring_str(ssh, c->list[j]->name);
  3921. cipherstr_started = 1;
  3922. }
  3923. }
  3924. /* List client->server MAC algorithms. */
  3925. ssh2_pkt_addstring_start(ssh);
  3926. for (i = 0; i < s->nmacs; i++) {
  3927. ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
  3928. if (i < s->nmacs - 1)
  3929. ssh2_pkt_addstring_str(ssh, ",");
  3930. }
  3931. /* List server->client MAC algorithms. */
  3932. ssh2_pkt_addstring_start(ssh);
  3933. for (i = 0; i < s->nmacs; i++) {
  3934. ssh2_pkt_addstring_str(ssh, s->maclist[i]->name);
  3935. if (i < s->nmacs - 1)
  3936. ssh2_pkt_addstring_str(ssh, ",");
  3937. }
  3938. /* List client->server compression algorithms. */
  3939. ssh2_pkt_addstring_start(ssh);
  3940. assert(lenof(compressions) > 1);
  3941. ssh2_pkt_addstring_str(ssh, s->preferred_comp->name);
  3942. for (i = 0; i < lenof(compressions); i++) {
  3943. const struct ssh_compress *c = compressions[i];
  3944. if (c != s->preferred_comp) {
  3945. ssh2_pkt_addstring_str(ssh, ",");
  3946. ssh2_pkt_addstring_str(ssh, c->name);
  3947. }
  3948. }
  3949. /* List server->client compression algorithms. */
  3950. ssh2_pkt_addstring_start(ssh);
  3951. assert(lenof(compressions) > 1);
  3952. ssh2_pkt_addstring_str(ssh, s->preferred_comp->name);
  3953. for (i = 0; i < lenof(compressions); i++) {
  3954. const struct ssh_compress *c = compressions[i];
  3955. if (c != s->preferred_comp) {
  3956. ssh2_pkt_addstring_str(ssh, ",");
  3957. ssh2_pkt_addstring_str(ssh, c->name);
  3958. }
  3959. }
  3960. /* List client->server languages. Empty list. */
  3961. ssh2_pkt_addstring_start(ssh);
  3962. /* List server->client languages. Empty list. */
  3963. ssh2_pkt_addstring_start(ssh);
  3964. /* First KEX packet does _not_ follow, because we're not that brave. */
  3965. ssh2_pkt_addbool(ssh, FALSE);
  3966. /* Reserved. */
  3967. ssh2_pkt_adduint32(ssh, 0);
  3968. }
  3969. ssh->exhash = ssh->exhashbase;
  3970. sha_string(&ssh->exhash, ssh->pktout.data + 5, ssh->pktout.length - 5);
  3971. ssh2_pkt_send(ssh);
  3972. if (!ispkt)
  3973. crWaitUntil(ispkt);
  3974. if (ssh->pktin.length > 5)
  3975. sha_string(&ssh->exhash, ssh->pktin.data + 5, ssh->pktin.length - 5);
  3976. /*
  3977. * Now examine the other side's KEXINIT to see what we're up
  3978. * to.
  3979. */
  3980. {
  3981. char *str;
  3982. int i, j, len;
  3983. if (ssh->pktin.type != SSH2_MSG_KEXINIT) {
  3984. bombout(("expected key exchange packet from server"));
  3985. crStop(0);
  3986. }
  3987. ssh->kex = NULL;
  3988. ssh->hostkey = NULL;
  3989. s->cscipher_tobe = NULL;
  3990. s->sccipher_tobe = NULL;
  3991. s->csmac_tobe = NULL;
  3992. s->scmac_tobe = NULL;
  3993. s->cscomp_tobe = NULL;
  3994. s->sccomp_tobe = NULL;
  3995. ssh->pktin.savedpos += 16; /* skip garbage cookie */
  3996. ssh_pkt_getstring(ssh, &str, &len); /* key exchange algorithms */
  3997. for (i = 0; i < lenof(kex_algs); i++) {
  3998. if (kex_algs[i] == &ssh_diffiehellman_gex &&
  3999. (ssh->remote_bugs & BUG_SSH2_DH_GEX))
  4000. continue;
  4001. if (in_commasep_string(kex_algs[i]->name, str, len)) {
  4002. ssh->kex = kex_algs[i];
  4003. break;
  4004. }
  4005. }
  4006. ssh_pkt_getstring(ssh, &str, &len); /* host key algorithms */
  4007. for (i = 0; i < lenof(hostkey_algs); i++) {
  4008. if (in_commasep_string(hostkey_algs[i]->name, str, len)) {
  4009. ssh->hostkey = hostkey_algs[i];
  4010. break;
  4011. }
  4012. }
  4013. ssh_pkt_getstring(ssh, &str, &len); /* client->server cipher */
  4014. s->warn = 0;
  4015. for (i = 0; i < s->n_preferred_ciphers; i++) {
  4016. const struct ssh2_ciphers *c = s->preferred_ciphers[i];
  4017. if (!c) {
  4018. s->warn = 1;
  4019. } else {
  4020. for (j = 0; j < c->nciphers; j++) {
  4021. if (in_commasep_string(c->list[j]->name, str, len)) {
  4022. s->cscipher_tobe = c->list[j];
  4023. break;
  4024. }
  4025. }
  4026. }
  4027. if (s->cscipher_tobe) {
  4028. if (s->warn)
  4029. askcipher(ssh->frontend, s->cscipher_tobe->name, 1);
  4030. break;
  4031. }
  4032. }
  4033. if (!s->cscipher_tobe) {
  4034. bombout(("Couldn't agree a client-to-server cipher (available: %s)",
  4035. str ? str : "(null)"));
  4036. crStop(0);
  4037. }
  4038. ssh_pkt_getstring(ssh, &str, &len); /* server->client cipher */
  4039. s->warn = 0;
  4040. for (i = 0; i < s->n_preferred_ciphers; i++) {
  4041. const struct ssh2_ciphers *c = s->preferred_ciphers[i];
  4042. if (!c) {
  4043. s->warn = 1;
  4044. } else {
  4045. for (j = 0; j < c->nciphers; j++) {
  4046. if (in_commasep_string(c->list[j]->name, str, len)) {
  4047. s->sccipher_tobe = c->list[j];
  4048. break;
  4049. }
  4050. }
  4051. }
  4052. if (s->sccipher_tobe) {
  4053. if (s->warn)
  4054. askcipher(ssh->frontend, s->sccipher_tobe->name, 2);
  4055. break;
  4056. }
  4057. }
  4058. if (!s->sccipher_tobe) {
  4059. bombout(("Couldn't agree a server-to-client cipher (available: %s)",
  4060. str ? str : "(null)"));
  4061. crStop(0);
  4062. }
  4063. ssh_pkt_getstring(ssh, &str, &len); /* client->server mac */
  4064. for (i = 0; i < s->nmacs; i++) {
  4065. if (in_commasep_string(s->maclist[i]->name, str, len)) {
  4066. s->csmac_tobe = s->maclist[i];
  4067. break;
  4068. }
  4069. }
  4070. ssh_pkt_getstring(ssh, &str, &len); /* server->client mac */
  4071. for (i = 0; i < s->nmacs; i++) {
  4072. if (in_commasep_string(s->maclist[i]->name, str, len)) {
  4073. s->scmac_tobe = s->maclist[i];
  4074. break;
  4075. }
  4076. }
  4077. ssh_pkt_getstring(ssh, &str, &len); /* client->server compression */
  4078. for (i = 0; i < lenof(compressions) + 1; i++) {
  4079. const struct ssh_compress *c =
  4080. i == 0 ? s->preferred_comp : compressions[i - 1];
  4081. if (in_commasep_string(c->name, str, len)) {
  4082. s->cscomp_tobe = c;
  4083. break;
  4084. }
  4085. }
  4086. ssh_pkt_getstring(ssh, &str, &len); /* server->client compression */
  4087. for (i = 0; i < lenof(compressions) + 1; i++) {
  4088. const struct ssh_compress *c =
  4089. i == 0 ? s->preferred_comp : compressions[i - 1];
  4090. if (in_commasep_string(c->name, str, len)) {
  4091. s->sccomp_tobe = c;
  4092. break;
  4093. }
  4094. }
  4095. }
  4096. /*
  4097. * Work out the number of bits of key we will need from the key
  4098. * exchange. We start with the maximum key length of either
  4099. * cipher...
  4100. */
  4101. {
  4102. int csbits, scbits;
  4103. csbits = s->cscipher_tobe->keylen;
  4104. scbits = s->sccipher_tobe->keylen;
  4105. s->nbits = (csbits > scbits ? csbits : scbits);
  4106. }
  4107. /* The keys only have 160-bit entropy, since they're based on
  4108. * a SHA-1 hash. So cap the key size at 160 bits. */
  4109. if (s->nbits > 160)
  4110. s->nbits = 160;
  4111. /*
  4112. * If we're doing Diffie-Hellman group exchange, start by
  4113. * requesting a group.
  4114. */
  4115. if (ssh->kex == &ssh_diffiehellman_gex) {
  4116. logevent("Doing Diffie-Hellman group exchange");
  4117. ssh->pkt_ctx |= SSH2_PKTCTX_DHGEX;
  4118. /*
  4119. * Work out how big a DH group we will need to allow that
  4120. * much data.
  4121. */
  4122. s->pbits = 512 << ((s->nbits - 1) / 64);
  4123. ssh2_pkt_init(ssh, SSH2_MSG_KEX_DH_GEX_REQUEST);
  4124. ssh2_pkt_adduint32(ssh, s->pbits);
  4125. ssh2_pkt_send(ssh);
  4126. crWaitUntil(ispkt);
  4127. if (ssh->pktin.type != SSH2_MSG_KEX_DH_GEX_GROUP) {
  4128. bombout(("expected key exchange group packet from server"));
  4129. crStop(0);
  4130. }
  4131. s->p = ssh2_pkt_getmp(ssh);
  4132. s->g = ssh2_pkt_getmp(ssh);
  4133. ssh->kex_ctx = dh_setup_group(s->p, s->g);
  4134. s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
  4135. s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
  4136. } else {
  4137. ssh->pkt_ctx |= SSH2_PKTCTX_DHGROUP1;
  4138. ssh->kex_ctx = dh_setup_group1();
  4139. s->kex_init_value = SSH2_MSG_KEXDH_INIT;
  4140. s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
  4141. }
  4142. logevent("Doing Diffie-Hellman key exchange");
  4143. /*
  4144. * Now generate and send e for Diffie-Hellman.
  4145. */
  4146. s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
  4147. ssh2_pkt_init(ssh, s->kex_init_value);
  4148. ssh2_pkt_addmp(ssh, s->e);
  4149. ssh2_pkt_send(ssh);
  4150. crWaitUntil(ispkt);
  4151. if (ssh->pktin.type != s->kex_reply_value) {
  4152. bombout(("expected key exchange reply packet from server"));
  4153. crStop(0);
  4154. }
  4155. ssh_pkt_getstring(ssh, &s->hostkeydata, &s->hostkeylen);
  4156. s->f = ssh2_pkt_getmp(ssh);
  4157. ssh_pkt_getstring(ssh, &s->sigdata, &s->siglen);
  4158. s->K = dh_find_K(ssh->kex_ctx, s->f);
  4159. sha_string(&ssh->exhash, s->hostkeydata, s->hostkeylen);
  4160. if (ssh->kex == &ssh_diffiehellman_gex) {
  4161. sha_uint32(&ssh->exhash, s->pbits);
  4162. sha_mpint(&ssh->exhash, s->p);
  4163. sha_mpint(&ssh->exhash, s->g);
  4164. }
  4165. sha_mpint(&ssh->exhash, s->e);
  4166. sha_mpint(&ssh->exhash, s->f);
  4167. sha_mpint(&ssh->exhash, s->K);
  4168. SHA_Final(&ssh->exhash, s->exchange_hash);
  4169. dh_cleanup(ssh->kex_ctx);
  4170. ssh->kex_ctx = NULL;
  4171. #if 0
  4172. debug(("Exchange hash is:\n"));
  4173. dmemdump(s->exchange_hash, 20);
  4174. #endif
  4175. s->hkey = ssh->hostkey->newkey(s->hostkeydata, s->hostkeylen);
  4176. if (!s->hkey ||
  4177. !ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
  4178. (char *)s->exchange_hash, 20)) {
  4179. bombout(("Server's host key did not match the signature supplied"));
  4180. crStop(0);
  4181. }
  4182. /*
  4183. * Authenticate remote host: verify host key. (We've already
  4184. * checked the signature of the exchange hash.)
  4185. */
  4186. s->keystr = ssh->hostkey->fmtkey(s->hkey);
  4187. s->fingerprint = ssh->hostkey->fingerprint(s->hkey);
  4188. verify_ssh_host_key(ssh->frontend,
  4189. ssh->savedhost, ssh->savedport, ssh->hostkey->keytype,
  4190. s->keystr, s->fingerprint);
  4191. if (s->first_kex) { /* don't bother logging this in rekeys */
  4192. logevent("Host key fingerprint is:");
  4193. logevent(s->fingerprint);
  4194. }
  4195. sfree(s->fingerprint);
  4196. sfree(s->keystr);
  4197. ssh->hostkey->freekey(s->hkey);
  4198. /*
  4199. * Send SSH2_MSG_NEWKEYS.
  4200. */
  4201. ssh2_pkt_init(ssh, SSH2_MSG_NEWKEYS);
  4202. ssh2_pkt_send(ssh);
  4203. /*
  4204. * Expect SSH2_MSG_NEWKEYS from server.
  4205. */
  4206. crWaitUntil(ispkt);
  4207. if (ssh->pktin.type != SSH2_MSG_NEWKEYS) {
  4208. bombout(("expected new-keys packet from server"));
  4209. crStop(0);
  4210. }
  4211. /*
  4212. * Create and initialise session keys.
  4213. */
  4214. if (ssh->cs_cipher_ctx)
  4215. ssh->cscipher->free_context(ssh->cs_cipher_ctx);
  4216. ssh->cscipher = s->cscipher_tobe;
  4217. ssh->cs_cipher_ctx = ssh->cscipher->make_context();
  4218. if (ssh->sc_cipher_ctx)
  4219. ssh->sccipher->free_context(ssh->sc_cipher_ctx);
  4220. ssh->sccipher = s->sccipher_tobe;
  4221. ssh->sc_cipher_ctx = ssh->sccipher->make_context();
  4222. if (ssh->cs_mac_ctx)
  4223. ssh->csmac->free_context(ssh->cs_mac_ctx);
  4224. ssh->csmac = s->csmac_tobe;
  4225. ssh->cs_mac_ctx = ssh->csmac->make_context();
  4226. if (ssh->sc_mac_ctx)
  4227. ssh->scmac->free_context(ssh->sc_mac_ctx);
  4228. ssh->scmac = s->scmac_tobe;
  4229. ssh->sc_mac_ctx = ssh->scmac->make_context();
  4230. if (ssh->cs_comp_ctx)
  4231. ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
  4232. ssh->cscomp = s->cscomp_tobe;
  4233. ssh->cs_comp_ctx = ssh->cscomp->compress_init();
  4234. if (ssh->sc_comp_ctx)
  4235. ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
  4236. ssh->sccomp = s->sccomp_tobe;
  4237. ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
  4238. /*
  4239. * Set IVs after keys. Here we use the exchange hash from the
  4240. * _first_ key exchange.
  4241. */
  4242. {
  4243. unsigned char keyspace[40];
  4244. if (s->first_kex)
  4245. memcpy(ssh->v2_session_id, s->exchange_hash,
  4246. sizeof(s->exchange_hash));
  4247. ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'C',keyspace);
  4248. ssh->cscipher->setkey(ssh->cs_cipher_ctx, keyspace);
  4249. ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'D',keyspace);
  4250. ssh->sccipher->setkey(ssh->sc_cipher_ctx, keyspace);
  4251. ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'A',keyspace);
  4252. ssh->cscipher->setiv(ssh->cs_cipher_ctx, keyspace);
  4253. ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'B',keyspace);
  4254. ssh->sccipher->setiv(ssh->sc_cipher_ctx, keyspace);
  4255. ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'E',keyspace);
  4256. ssh->csmac->setkey(ssh->cs_mac_ctx, keyspace);
  4257. ssh2_mkkey(ssh,s->K,s->exchange_hash,ssh->v2_session_id,'F',keyspace);
  4258. ssh->scmac->setkey(ssh->sc_mac_ctx, keyspace);
  4259. }
  4260. logeventf(ssh, "Initialised %.200s client->server encryption",
  4261. ssh->cscipher->text_name);
  4262. logeventf(ssh, "Initialised %.200s server->client encryption",
  4263. ssh->sccipher->text_name);
  4264. logeventf(ssh, "Initialised %.200s client->server MAC algorithm",
  4265. ssh->csmac->text_name);
  4266. logeventf(ssh, "Initialised %.200s server->client MAC algorithm",
  4267. ssh->scmac->text_name);
  4268. if (ssh->cscomp->text_name)
  4269. logeventf(ssh, "Initialised %s compression",
  4270. ssh->cscomp->text_name);
  4271. if (ssh->sccomp->text_name)
  4272. logeventf(ssh, "Initialised %s decompression",
  4273. ssh->sccomp->text_name);
  4274. freebn(s->f);
  4275. freebn(s->K);
  4276. if (ssh->kex == &ssh_diffiehellman_gex) {
  4277. freebn(s->g);
  4278. freebn(s->p);
  4279. }
  4280. /*
  4281. * If this is the first key exchange phase, we must pass the
  4282. * SSH2_MSG_NEWKEYS packet to the next layer, not because it
  4283. * wants to see it but because it will need time to initialise
  4284. * itself before it sees an actual packet. In subsequent key
  4285. * exchange phases, we don't pass SSH2_MSG_NEWKEYS on, because
  4286. * it would only confuse the layer above.
  4287. */
  4288. if (!s->first_kex) {
  4289. crReturn(0);
  4290. }
  4291. s->first_kex = 0;
  4292. /*
  4293. * Now we're encrypting. Begin returning 1 to the protocol main
  4294. * function so that other things can run on top of the
  4295. * transport. If we ever see a KEXINIT, we must go back to the
  4296. * start.
  4297. */
  4298. while (!(ispkt && ssh->pktin.type == SSH2_MSG_KEXINIT)) {
  4299. crReturn(1);
  4300. }
  4301. logevent("Server initiated key re-exchange");
  4302. goto begin_key_exchange;
  4303. crFinish(1);
  4304. }
  4305. /*
  4306. * Add data to an SSH2 channel output buffer.
  4307. */
  4308. static void ssh2_add_channel_data(struct ssh_channel *c, char *buf,
  4309. int len)
  4310. {
  4311. bufchain_add(&c->v.v2.outbuffer, buf, len);
  4312. }
  4313. /*
  4314. * Attempt to send data on an SSH2 channel.
  4315. */
  4316. static int ssh2_try_send(struct ssh_channel *c)
  4317. {
  4318. Ssh ssh = c->ssh;
  4319. while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
  4320. int len;
  4321. void *data;
  4322. bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
  4323. if ((unsigned)len > c->v.v2.remwindow)
  4324. len = c->v.v2.remwindow;
  4325. if ((unsigned)len > c->v.v2.remmaxpkt)
  4326. len = c->v.v2.remmaxpkt;
  4327. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_DATA);
  4328. ssh2_pkt_adduint32(ssh, c->remoteid);
  4329. dont_log_data(ssh, PKTLOG_OMIT);
  4330. ssh2_pkt_addstring_start(ssh);
  4331. ssh2_pkt_addstring_data(ssh, data, len);
  4332. end_log_omission(ssh);
  4333. ssh2_pkt_send(ssh);
  4334. bufchain_consume(&c->v.v2.outbuffer, len);
  4335. c->v.v2.remwindow -= len;
  4336. }
  4337. /*
  4338. * After having sent as much data as we can, return the amount
  4339. * still buffered.
  4340. */
  4341. return bufchain_size(&c->v.v2.outbuffer);
  4342. }
  4343. /*
  4344. * Potentially enlarge the window on an SSH2 channel.
  4345. */
  4346. static void ssh2_set_window(struct ssh_channel *c, unsigned newwin)
  4347. {
  4348. Ssh ssh = c->ssh;
  4349. /*
  4350. * Never send WINDOW_ADJUST for a channel that the remote side
  4351. * already thinks it's closed; there's no point, since it won't
  4352. * be sending any more data anyway.
  4353. */
  4354. if (c->closes != 0)
  4355. return;
  4356. if (newwin > c->v.v2.locwindow) {
  4357. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  4358. ssh2_pkt_adduint32(ssh, c->remoteid);
  4359. ssh2_pkt_adduint32(ssh, newwin - c->v.v2.locwindow);
  4360. ssh2_pkt_send(ssh);
  4361. c->v.v2.locwindow = newwin;
  4362. }
  4363. }
  4364. /*
  4365. * Handle the SSH2 userauth and connection layers.
  4366. */
  4367. static void do_ssh2_authconn(Ssh ssh, unsigned char *in, int inlen, int ispkt)
  4368. {
  4369. struct do_ssh2_authconn_state {
  4370. enum {
  4371. AUTH_INVALID, AUTH_PUBLICKEY_AGENT, AUTH_PUBLICKEY_FILE,
  4372. AUTH_PASSWORD,
  4373. AUTH_KEYBOARD_INTERACTIVE
  4374. } method;
  4375. enum {
  4376. AUTH_TYPE_NONE,
  4377. AUTH_TYPE_PUBLICKEY,
  4378. AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
  4379. AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
  4380. AUTH_TYPE_PASSWORD,
  4381. AUTH_TYPE_KEYBOARD_INTERACTIVE,
  4382. AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
  4383. } type;
  4384. int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
  4385. int tried_pubkey_config, tried_agent, tried_keyb_inter;
  4386. int kbd_inter_running;
  4387. int we_are_in;
  4388. int num_prompts, curr_prompt, echo;
  4389. char username[100];
  4390. int got_username;
  4391. char pwprompt[512];
  4392. char password[100];
  4393. void *publickey_blob;
  4394. int publickey_bloblen;
  4395. unsigned char request[5], *response, *p;
  4396. int responselen;
  4397. int keyi, nkeys;
  4398. int authed;
  4399. char *pkblob, *alg, *commentp;
  4400. int pklen, alglen, commentlen;
  4401. int siglen, retlen, len;
  4402. char *q, *agentreq, *ret;
  4403. int try_send;
  4404. int num_env, env_left, env_ok;
  4405. };
  4406. crState(do_ssh2_authconn_state);
  4407. crBegin(ssh->do_ssh2_authconn_crstate);
  4408. /*
  4409. * Request userauth protocol, and await a response to it.
  4410. */
  4411. ssh2_pkt_init(ssh, SSH2_MSG_SERVICE_REQUEST);
  4412. ssh2_pkt_addstring(ssh, "ssh-userauth");
  4413. ssh2_pkt_send(ssh);
  4414. crWaitUntilV(ispkt);
  4415. if (ssh->pktin.type != SSH2_MSG_SERVICE_ACCEPT) {
  4416. bombout(("Server refused user authentication protocol"));
  4417. crStopV;
  4418. }
  4419. /*
  4420. * We repeat this whole loop, including the username prompt,
  4421. * until we manage a successful authentication. If the user
  4422. * types the wrong _password_, they can be sent back to the
  4423. * beginning to try another username, if this is configured on.
  4424. * (If they specify a username in the config, they are never
  4425. * asked, even if they do give a wrong password.)
  4426. *
  4427. * I think this best serves the needs of
  4428. *
  4429. * - the people who have no configuration, no keys, and just
  4430. * want to try repeated (username,password) pairs until they
  4431. * type both correctly
  4432. *
  4433. * - people who have keys and configuration but occasionally
  4434. * need to fall back to passwords
  4435. *
  4436. * - people with a key held in Pageant, who might not have
  4437. * logged in to a particular machine before; so they want to
  4438. * type a username, and then _either_ their key will be
  4439. * accepted, _or_ they will type a password. If they mistype
  4440. * the username they will want to be able to get back and
  4441. * retype it!
  4442. */
  4443. s->username[0] = '\0';
  4444. s->got_username = FALSE;
  4445. do {
  4446. /*
  4447. * Get a username.
  4448. */
  4449. if (s->got_username && !ssh->cfg.change_username) {
  4450. /*
  4451. * We got a username last time round this loop, and
  4452. * with change_username turned off we don't try to get
  4453. * it again.
  4454. */
  4455. } else if ((flags & FLAG_INTERACTIVE) && !*ssh->cfg.username) {
  4456. if (ssh_get_line && !ssh_getline_pw_only) {
  4457. if (!ssh_get_line("login as: ",
  4458. s->username, sizeof(s->username), FALSE)) {
  4459. /*
  4460. * get_line failed to get a username.
  4461. * Terminate.
  4462. */
  4463. logevent("No username provided. Abandoning session.");
  4464. ssh_closing((Plug)ssh, NULL, 0, 0);
  4465. crStopV;
  4466. }
  4467. } else {
  4468. int ret; /* need not be saved across crReturn */
  4469. c_write_str(ssh, "login as: ");
  4470. ssh->send_ok = 1;
  4471. setup_userpass_input(ssh, s->username, sizeof(s->username), 1);
  4472. do {
  4473. crWaitUntilV(!ispkt);
  4474. ret = process_userpass_input(ssh, in, inlen);
  4475. } while (ret == 0);
  4476. if (ret < 0)
  4477. cleanup_exit(0);
  4478. c_write_str(ssh, "\r\n");
  4479. }
  4480. s->username[strcspn(s->username, "\n\r")] = '\0';
  4481. } else {
  4482. char *stuff;
  4483. strncpy(s->username, ssh->cfg.username, sizeof(s->username));
  4484. s->username[sizeof(s->username)-1] = '\0';
  4485. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  4486. stuff = dupprintf("Using username \"%s\".\r\n", s->username);
  4487. c_write_str(ssh, stuff);
  4488. sfree(stuff);
  4489. }
  4490. }
  4491. s->got_username = TRUE;
  4492. /*
  4493. * Send an authentication request using method "none": (a)
  4494. * just in case it succeeds, and (b) so that we know what
  4495. * authentication methods we can usefully try next.
  4496. */
  4497. ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
  4498. ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
  4499. ssh2_pkt_addstring(ssh, s->username);
  4500. ssh2_pkt_addstring(ssh, "ssh-connection");/* service requested */
  4501. ssh2_pkt_addstring(ssh, "none"); /* method */
  4502. ssh2_pkt_send(ssh);
  4503. s->type = AUTH_TYPE_NONE;
  4504. s->gotit = FALSE;
  4505. s->we_are_in = FALSE;
  4506. s->tried_pubkey_config = FALSE;
  4507. s->tried_agent = FALSE;
  4508. s->tried_keyb_inter = FALSE;
  4509. s->kbd_inter_running = FALSE;
  4510. /* Load the pub half of ssh->cfg.keyfile so we notice if it's in Pageant */
  4511. if (!filename_is_null(ssh->cfg.keyfile)) {
  4512. int keytype;
  4513. logeventf(ssh, "Reading private key file \"%.150s\"",
  4514. filename_to_str(&ssh->cfg.keyfile));
  4515. keytype = key_type(&ssh->cfg.keyfile);
  4516. if (keytype == SSH_KEYTYPE_SSH2) {
  4517. s->publickey_blob =
  4518. ssh2_userkey_loadpub(&ssh->cfg.keyfile, NULL,
  4519. &s->publickey_bloblen, NULL);
  4520. } else {
  4521. char *msgbuf;
  4522. logeventf(ssh, "Unable to use this key file (%s)",
  4523. key_type_to_str(keytype));
  4524. msgbuf = dupprintf("Unable to use key file \"%.150s\""
  4525. " (%s)\r\n",
  4526. filename_to_str(&ssh->cfg.keyfile),
  4527. key_type_to_str(keytype));
  4528. c_write_str(ssh, msgbuf);
  4529. sfree(msgbuf);
  4530. s->publickey_blob = NULL;
  4531. }
  4532. } else
  4533. s->publickey_blob = NULL;
  4534. while (1) {
  4535. /*
  4536. * Wait for the result of the last authentication request.
  4537. */
  4538. if (!s->gotit)
  4539. crWaitUntilV(ispkt);
  4540. while (ssh->pktin.type == SSH2_MSG_USERAUTH_BANNER) {
  4541. char *banner;
  4542. int size;
  4543. /*
  4544. * Don't show the banner if we're operating in
  4545. * non-verbose non-interactive mode. (It's probably
  4546. * a script, which means nobody will read the
  4547. * banner _anyway_, and moreover the printing of
  4548. * the banner will screw up processing on the
  4549. * output of (say) plink.)
  4550. */
  4551. if (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE)) {
  4552. ssh_pkt_getstring(ssh, &banner, &size);
  4553. if (banner)
  4554. c_write_untrusted(ssh, banner, size);
  4555. }
  4556. crWaitUntilV(ispkt);
  4557. }
  4558. if (ssh->pktin.type == SSH2_MSG_USERAUTH_SUCCESS) {
  4559. logevent("Access granted");
  4560. s->we_are_in = TRUE;
  4561. break;
  4562. }
  4563. if (s->kbd_inter_running &&
  4564. ssh->pktin.type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
  4565. /*
  4566. * This is either a further set-of-prompts packet
  4567. * in keyboard-interactive authentication, or it's
  4568. * the same one and we came back here with `gotit'
  4569. * set. In the former case, we must reset the
  4570. * curr_prompt variable.
  4571. */
  4572. if (!s->gotit)
  4573. s->curr_prompt = 0;
  4574. } else if (ssh->pktin.type != SSH2_MSG_USERAUTH_FAILURE) {
  4575. bombout(("Strange packet received during authentication: type %d",
  4576. ssh->pktin.type));
  4577. crStopV;
  4578. }
  4579. s->gotit = FALSE;
  4580. /*
  4581. * OK, we're now sitting on a USERAUTH_FAILURE message, so
  4582. * we can look at the string in it and know what we can
  4583. * helpfully try next.
  4584. */
  4585. if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE) {
  4586. char *methods;
  4587. int methlen;
  4588. ssh_pkt_getstring(ssh, &methods, &methlen);
  4589. s->kbd_inter_running = FALSE;
  4590. if (!ssh2_pkt_getbool(ssh)) {
  4591. /*
  4592. * We have received an unequivocal Access
  4593. * Denied. This can translate to a variety of
  4594. * messages:
  4595. *
  4596. * - if we'd just tried "none" authentication,
  4597. * it's not worth printing anything at all
  4598. *
  4599. * - if we'd just tried a public key _offer_,
  4600. * the message should be "Server refused our
  4601. * key" (or no message at all if the key
  4602. * came from Pageant)
  4603. *
  4604. * - if we'd just tried anything else, the
  4605. * message really should be "Access denied".
  4606. *
  4607. * Additionally, if we'd just tried password
  4608. * authentication, we should break out of this
  4609. * whole loop so as to go back to the username
  4610. * prompt.
  4611. */
  4612. if (s->type == AUTH_TYPE_NONE) {
  4613. /* do nothing */
  4614. } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
  4615. s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
  4616. if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
  4617. c_write_str(ssh, "Server refused our key\r\n");
  4618. logevent("Server refused public key");
  4619. } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
  4620. /* server declined keyboard-interactive; ignore */
  4621. } else {
  4622. c_write_str(ssh, "Access denied\r\n");
  4623. logevent("Access denied");
  4624. if (s->type == AUTH_TYPE_PASSWORD) {
  4625. s->we_are_in = FALSE;
  4626. break;
  4627. }
  4628. }
  4629. } else {
  4630. c_write_str(ssh, "Further authentication required\r\n");
  4631. logevent("Further authentication required");
  4632. }
  4633. s->can_pubkey =
  4634. in_commasep_string("publickey", methods, methlen);
  4635. s->can_passwd =
  4636. in_commasep_string("password", methods, methlen);
  4637. s->can_keyb_inter = ssh->cfg.try_ki_auth &&
  4638. in_commasep_string("keyboard-interactive", methods, methlen);
  4639. }
  4640. s->method = 0;
  4641. ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
  4642. s->need_pw = FALSE;
  4643. /*
  4644. * Most password/passphrase prompts will be
  4645. * non-echoing, so we set this to 0 by default.
  4646. * Exception is that some keyboard-interactive prompts
  4647. * can be echoing, in which case we'll set this to 1.
  4648. */
  4649. s->echo = 0;
  4650. if (!s->method && s->can_pubkey &&
  4651. agent_exists() && !s->tried_agent) {
  4652. /*
  4653. * Attempt public-key authentication using Pageant.
  4654. */
  4655. void *r;
  4656. s->authed = FALSE;
  4657. ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
  4658. ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
  4659. s->tried_agent = TRUE;
  4660. logevent("Pageant is running. Requesting keys.");
  4661. /* Request the keys held by the agent. */
  4662. PUT_32BIT(s->request, 1);
  4663. s->request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
  4664. if (!agent_query(s->request, 5, &r, &s->responselen,
  4665. ssh_agent_callback, ssh)) {
  4666. do {
  4667. crReturnV;
  4668. if (ispkt) {
  4669. bombout(("Unexpected data from server while"
  4670. " waiting for agent response"));
  4671. crStopV;
  4672. }
  4673. } while (ispkt || inlen > 0);
  4674. r = ssh->agent_response;
  4675. s->responselen = ssh->agent_response_len;
  4676. }
  4677. s->response = (unsigned char *) r;
  4678. if (s->response && s->responselen >= 5 &&
  4679. s->response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
  4680. s->p = s->response + 5;
  4681. s->nkeys = GET_32BIT(s->p);
  4682. s->p += 4;
  4683. {
  4684. char buf[64];
  4685. sprintf(buf, "Pageant has %d SSH2 keys", s->nkeys);
  4686. logevent(buf);
  4687. }
  4688. for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
  4689. void *vret;
  4690. {
  4691. char buf[64];
  4692. sprintf(buf, "Trying Pageant key #%d", s->keyi);
  4693. logevent(buf);
  4694. }
  4695. s->pklen = GET_32BIT(s->p);
  4696. s->p += 4;
  4697. if (s->publickey_blob &&
  4698. s->pklen == s->publickey_bloblen &&
  4699. !memcmp(s->p, s->publickey_blob,
  4700. s->publickey_bloblen)) {
  4701. logevent("This key matches configured key file");
  4702. s->tried_pubkey_config = 1;
  4703. }
  4704. s->pkblob = (char *)s->p;
  4705. s->p += s->pklen;
  4706. s->alglen = GET_32BIT(s->pkblob);
  4707. s->alg = s->pkblob + 4;
  4708. s->commentlen = GET_32BIT(s->p);
  4709. s->p += 4;
  4710. s->commentp = (char *)s->p;
  4711. s->p += s->commentlen;
  4712. ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
  4713. ssh2_pkt_addstring(ssh, s->username);
  4714. ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
  4715. ssh2_pkt_addstring(ssh, "publickey"); /* method */
  4716. ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
  4717. ssh2_pkt_addstring_start(ssh);
  4718. ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
  4719. ssh2_pkt_addstring_start(ssh);
  4720. ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
  4721. ssh2_pkt_send(ssh);
  4722. crWaitUntilV(ispkt);
  4723. if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
  4724. logevent("Key refused");
  4725. continue;
  4726. }
  4727. if (flags & FLAG_VERBOSE) {
  4728. c_write_str(ssh, "Authenticating with "
  4729. "public key \"");
  4730. c_write(ssh, s->commentp, s->commentlen);
  4731. c_write_str(ssh, "\" from agent\r\n");
  4732. }
  4733. /*
  4734. * Server is willing to accept the key.
  4735. * Construct a SIGN_REQUEST.
  4736. */
  4737. ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
  4738. ssh2_pkt_addstring(ssh, s->username);
  4739. ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
  4740. ssh2_pkt_addstring(ssh, "publickey"); /* method */
  4741. ssh2_pkt_addbool(ssh, TRUE);
  4742. ssh2_pkt_addstring_start(ssh);
  4743. ssh2_pkt_addstring_data(ssh, s->alg, s->alglen);
  4744. ssh2_pkt_addstring_start(ssh);
  4745. ssh2_pkt_addstring_data(ssh, s->pkblob, s->pklen);
  4746. s->siglen = ssh->pktout.length - 5 + 4 + 20;
  4747. if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
  4748. s->siglen -= 4;
  4749. s->len = 1; /* message type */
  4750. s->len += 4 + s->pklen; /* key blob */
  4751. s->len += 4 + s->siglen; /* data to sign */
  4752. s->len += 4; /* flags */
  4753. s->agentreq = snewn(4 + s->len, char);
  4754. PUT_32BIT(s->agentreq, s->len);
  4755. s->q = s->agentreq + 4;
  4756. *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
  4757. PUT_32BIT(s->q, s->pklen);
  4758. s->q += 4;
  4759. memcpy(s->q, s->pkblob, s->pklen);
  4760. s->q += s->pklen;
  4761. PUT_32BIT(s->q, s->siglen);
  4762. s->q += 4;
  4763. /* Now the data to be signed... */
  4764. if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
  4765. PUT_32BIT(s->q, 20);
  4766. s->q += 4;
  4767. }
  4768. memcpy(s->q, ssh->v2_session_id, 20);
  4769. s->q += 20;
  4770. memcpy(s->q, ssh->pktout.data + 5,
  4771. ssh->pktout.length - 5);
  4772. s->q += ssh->pktout.length - 5;
  4773. /* And finally the (zero) flags word. */
  4774. PUT_32BIT(s->q, 0);
  4775. if (!agent_query(s->agentreq, s->len + 4,
  4776. &vret, &s->retlen,
  4777. ssh_agent_callback, ssh)) {
  4778. do {
  4779. crReturnV;
  4780. if (ispkt) {
  4781. bombout(("Unexpected data from server"
  4782. " while waiting for agent"
  4783. " response"));
  4784. crStopV;
  4785. }
  4786. } while (ispkt || inlen > 0);
  4787. vret = ssh->agent_response;
  4788. s->retlen = ssh->agent_response_len;
  4789. }
  4790. s->ret = vret;
  4791. sfree(s->agentreq);
  4792. if (s->ret) {
  4793. if (s->ret[4] == SSH2_AGENT_SIGN_RESPONSE) {
  4794. logevent("Sending Pageant's response");
  4795. ssh2_add_sigblob(ssh, s->pkblob, s->pklen,
  4796. s->ret + 9,
  4797. GET_32BIT(s->ret + 5));
  4798. ssh2_pkt_send(ssh);
  4799. s->authed = TRUE;
  4800. break;
  4801. } else {
  4802. logevent
  4803. ("Pageant failed to answer challenge");
  4804. sfree(s->ret);
  4805. }
  4806. }
  4807. }
  4808. if (s->authed)
  4809. continue;
  4810. }
  4811. sfree(s->response);
  4812. }
  4813. if (!s->method && s->can_pubkey && s->publickey_blob
  4814. && !s->tried_pubkey_config) {
  4815. unsigned char *pub_blob;
  4816. char *algorithm, *comment;
  4817. int pub_blob_len;
  4818. s->tried_pubkey_config = TRUE;
  4819. ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
  4820. ssh->pkt_ctx |= SSH2_PKTCTX_PUBLICKEY;
  4821. /*
  4822. * Try the public key supplied in the configuration.
  4823. *
  4824. * First, offer the public blob to see if the server is
  4825. * willing to accept it.
  4826. */
  4827. pub_blob =
  4828. (unsigned char *)ssh2_userkey_loadpub(&ssh->cfg.keyfile,
  4829. &algorithm,
  4830. &pub_blob_len,
  4831. NULL);
  4832. if (pub_blob) {
  4833. ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
  4834. ssh2_pkt_addstring(ssh, s->username);
  4835. ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
  4836. ssh2_pkt_addstring(ssh, "publickey"); /* method */
  4837. ssh2_pkt_addbool(ssh, FALSE); /* no signature included */
  4838. ssh2_pkt_addstring(ssh, algorithm);
  4839. ssh2_pkt_addstring_start(ssh);
  4840. ssh2_pkt_addstring_data(ssh, (char *)pub_blob,
  4841. pub_blob_len);
  4842. ssh2_pkt_send(ssh);
  4843. logevent("Offered public key");
  4844. crWaitUntilV(ispkt);
  4845. if (ssh->pktin.type != SSH2_MSG_USERAUTH_PK_OK) {
  4846. s->gotit = TRUE;
  4847. s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
  4848. continue; /* key refused; give up on it */
  4849. }
  4850. logevent("Offer of public key accepted");
  4851. /*
  4852. * Actually attempt a serious authentication using
  4853. * the key.
  4854. */
  4855. if (ssh2_userkey_encrypted(&ssh->cfg.keyfile, &comment)) {
  4856. sprintf(s->pwprompt,
  4857. "Passphrase for key \"%.100s\": ",
  4858. comment);
  4859. s->need_pw = TRUE;
  4860. } else {
  4861. s->need_pw = FALSE;
  4862. }
  4863. if (flags & FLAG_VERBOSE) {
  4864. c_write_str(ssh, "Authenticating with public key \"");
  4865. c_write_str(ssh, comment);
  4866. c_write_str(ssh, "\"\r\n");
  4867. }
  4868. s->method = AUTH_PUBLICKEY_FILE;
  4869. }
  4870. }
  4871. if (!s->method && s->can_keyb_inter && !s->tried_keyb_inter) {
  4872. s->method = AUTH_KEYBOARD_INTERACTIVE;
  4873. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
  4874. s->tried_keyb_inter = TRUE;
  4875. ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
  4876. ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
  4877. ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
  4878. ssh2_pkt_addstring(ssh, s->username);
  4879. ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
  4880. ssh2_pkt_addstring(ssh, "keyboard-interactive"); /* method */
  4881. ssh2_pkt_addstring(ssh, ""); /* lang */
  4882. ssh2_pkt_addstring(ssh, "");
  4883. ssh2_pkt_send(ssh);
  4884. crWaitUntilV(ispkt);
  4885. if (ssh->pktin.type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
  4886. if (ssh->pktin.type == SSH2_MSG_USERAUTH_FAILURE)
  4887. s->gotit = TRUE;
  4888. logevent("Keyboard-interactive authentication refused");
  4889. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
  4890. continue;
  4891. }
  4892. s->kbd_inter_running = TRUE;
  4893. s->curr_prompt = 0;
  4894. }
  4895. if (s->kbd_inter_running) {
  4896. s->method = AUTH_KEYBOARD_INTERACTIVE;
  4897. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
  4898. s->tried_keyb_inter = TRUE;
  4899. ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
  4900. ssh->pkt_ctx |= SSH2_PKTCTX_KBDINTER;
  4901. if (s->curr_prompt == 0) {
  4902. /*
  4903. * We've got a fresh USERAUTH_INFO_REQUEST.
  4904. * Display header data, and start going through
  4905. * the prompts.
  4906. */
  4907. char *name, *inst, *lang;
  4908. int name_len, inst_len, lang_len;
  4909. ssh_pkt_getstring(ssh, &name, &name_len);
  4910. ssh_pkt_getstring(ssh, &inst, &inst_len);
  4911. ssh_pkt_getstring(ssh, &lang, &lang_len);
  4912. if (name_len > 0) {
  4913. c_write_untrusted(ssh, name, name_len);
  4914. c_write_str(ssh, "\r\n");
  4915. }
  4916. if (inst_len > 0) {
  4917. c_write_untrusted(ssh, inst, inst_len);
  4918. c_write_str(ssh, "\r\n");
  4919. }
  4920. s->num_prompts = ssh_pkt_getuint32(ssh);
  4921. }
  4922. /*
  4923. * If there are prompts remaining in the packet,
  4924. * display one and get a response.
  4925. */
  4926. if (s->curr_prompt < s->num_prompts) {
  4927. char *prompt;
  4928. int prompt_len;
  4929. ssh_pkt_getstring(ssh, &prompt, &prompt_len);
  4930. if (prompt_len > 0) {
  4931. static const char trunc[] = "<prompt truncated>: ";
  4932. static const int prlen = sizeof(s->pwprompt) -
  4933. lenof(trunc);
  4934. if (prompt_len > prlen) {
  4935. memcpy(s->pwprompt, prompt, prlen);
  4936. strcpy(s->pwprompt + prlen, trunc);
  4937. } else {
  4938. memcpy(s->pwprompt, prompt, prompt_len);
  4939. s->pwprompt[prompt_len] = '\0';
  4940. }
  4941. } else {
  4942. strcpy(s->pwprompt,
  4943. "<server failed to send prompt>: ");
  4944. }
  4945. s->echo = ssh2_pkt_getbool(ssh);
  4946. s->need_pw = TRUE;
  4947. } else
  4948. s->need_pw = FALSE;
  4949. }
  4950. if (!s->method && s->can_passwd) {
  4951. s->method = AUTH_PASSWORD;
  4952. ssh->pkt_ctx &= ~SSH2_PKTCTX_AUTH_MASK;
  4953. ssh->pkt_ctx |= SSH2_PKTCTX_PASSWORD;
  4954. sprintf(s->pwprompt, "%.90s@%.90s's password: ", s->username,
  4955. ssh->savedhost);
  4956. s->need_pw = TRUE;
  4957. }
  4958. if (s->need_pw) {
  4959. if (ssh_get_line) {
  4960. if (!ssh_get_line(s->pwprompt, s->password,
  4961. sizeof(s->password), TRUE)) {
  4962. /*
  4963. * get_line failed to get a password (for
  4964. * example because one was supplied on the
  4965. * command line which has already failed to
  4966. * work). Terminate.
  4967. */
  4968. ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
  4969. ssh2_pkt_adduint32(ssh,SSH2_DISCONNECT_BY_APPLICATION);
  4970. ssh2_pkt_addstring(ssh, "No more passwords available"
  4971. " to try");
  4972. ssh2_pkt_addstring(ssh, "en"); /* language tag */
  4973. ssh2_pkt_send(ssh);
  4974. logevent("Unable to authenticate");
  4975. connection_fatal(ssh->frontend,
  4976. "Unable to authenticate");
  4977. ssh_closing((Plug)ssh, NULL, 0, 0);
  4978. crStopV;
  4979. }
  4980. } else {
  4981. int ret; /* need not be saved across crReturn */
  4982. c_write_untrusted(ssh, s->pwprompt, strlen(s->pwprompt));
  4983. ssh->send_ok = 1;
  4984. setup_userpass_input(ssh, s->password,
  4985. sizeof(s->password), s->echo);
  4986. do {
  4987. crWaitUntilV(!ispkt);
  4988. ret = process_userpass_input(ssh, in, inlen);
  4989. } while (ret == 0);
  4990. if (ret < 0)
  4991. cleanup_exit(0);
  4992. c_write_str(ssh, "\r\n");
  4993. }
  4994. }
  4995. if (s->method == AUTH_PUBLICKEY_FILE) {
  4996. /*
  4997. * We have our passphrase. Now try the actual authentication.
  4998. */
  4999. struct ssh2_userkey *key;
  5000. const char *error = NULL;
  5001. key = ssh2_load_userkey(&ssh->cfg.keyfile, s->password,
  5002. &error);
  5003. if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
  5004. if (key == SSH2_WRONG_PASSPHRASE) {
  5005. c_write_str(ssh, "Wrong passphrase\r\n");
  5006. s->tried_pubkey_config = FALSE;
  5007. } else {
  5008. c_write_str(ssh, "Unable to load private key (");
  5009. c_write_str(ssh, error);
  5010. c_write_str(ssh, ")\r\n");
  5011. s->tried_pubkey_config = TRUE;
  5012. }
  5013. /* Send a spurious AUTH_NONE to return to the top. */
  5014. ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
  5015. ssh2_pkt_addstring(ssh, s->username);
  5016. ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
  5017. ssh2_pkt_addstring(ssh, "none"); /* method */
  5018. ssh2_pkt_send(ssh);
  5019. s->type = AUTH_TYPE_NONE;
  5020. } else {
  5021. unsigned char *pkblob, *sigblob, *sigdata;
  5022. int pkblob_len, sigblob_len, sigdata_len;
  5023. int p;
  5024. /*
  5025. * We have loaded the private key and the server
  5026. * has announced that it's willing to accept it.
  5027. * Hallelujah. Generate a signature and send it.
  5028. */
  5029. ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
  5030. ssh2_pkt_addstring(ssh, s->username);
  5031. ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
  5032. ssh2_pkt_addstring(ssh, "publickey"); /* method */
  5033. ssh2_pkt_addbool(ssh, TRUE);
  5034. ssh2_pkt_addstring(ssh, key->alg->name);
  5035. pkblob = key->alg->public_blob(key->data, &pkblob_len);
  5036. ssh2_pkt_addstring_start(ssh);
  5037. ssh2_pkt_addstring_data(ssh, (char *)pkblob, pkblob_len);
  5038. /*
  5039. * The data to be signed is:
  5040. *
  5041. * string session-id
  5042. *
  5043. * followed by everything so far placed in the
  5044. * outgoing packet.
  5045. */
  5046. sigdata_len = ssh->pktout.length - 5 + 4 + 20;
  5047. if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
  5048. sigdata_len -= 4;
  5049. sigdata = snewn(sigdata_len, unsigned char);
  5050. p = 0;
  5051. if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
  5052. PUT_32BIT(sigdata+p, 20);
  5053. p += 4;
  5054. }
  5055. memcpy(sigdata+p, ssh->v2_session_id, 20); p += 20;
  5056. memcpy(sigdata+p, ssh->pktout.data + 5,
  5057. ssh->pktout.length - 5);
  5058. p += ssh->pktout.length - 5;
  5059. assert(p == sigdata_len);
  5060. sigblob = key->alg->sign(key->data, (char *)sigdata,
  5061. sigdata_len, &sigblob_len);
  5062. ssh2_add_sigblob(ssh, pkblob, pkblob_len,
  5063. sigblob, sigblob_len);
  5064. sfree(pkblob);
  5065. sfree(sigblob);
  5066. sfree(sigdata);
  5067. ssh2_pkt_send(ssh);
  5068. s->type = AUTH_TYPE_PUBLICKEY;
  5069. key->alg->freekey(key->data);
  5070. }
  5071. } else if (s->method == AUTH_PASSWORD) {
  5072. /*
  5073. * We send the password packet lumped tightly together with
  5074. * an SSH_MSG_IGNORE packet. The IGNORE packet contains a
  5075. * string long enough to make the total length of the two
  5076. * packets constant. This should ensure that a passive
  5077. * listener doing traffic analyis can't work out the length
  5078. * of the password.
  5079. *
  5080. * For this to work, we need an assumption about the
  5081. * maximum length of the password packet. I think 256 is
  5082. * pretty conservative. Anyone using a password longer than
  5083. * that probably doesn't have much to worry about from
  5084. * people who find out how long their password is!
  5085. */
  5086. ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_REQUEST);
  5087. ssh2_pkt_addstring(ssh, s->username);
  5088. ssh2_pkt_addstring(ssh, "ssh-connection"); /* service requested */
  5089. ssh2_pkt_addstring(ssh, "password");
  5090. ssh2_pkt_addbool(ssh, FALSE);
  5091. dont_log_password(ssh, PKTLOG_BLANK);
  5092. ssh2_pkt_addstring(ssh, s->password);
  5093. memset(s->password, 0, sizeof(s->password));
  5094. end_log_omission(ssh);
  5095. ssh2_pkt_defer(ssh);
  5096. /*
  5097. * We'll include a string that's an exact multiple of the
  5098. * cipher block size. If the cipher is NULL for some
  5099. * reason, we don't do this trick at all because we gain
  5100. * nothing by it.
  5101. */
  5102. if (ssh->cscipher) {
  5103. int stringlen, i;
  5104. stringlen = (256 - ssh->deferred_len);
  5105. stringlen += ssh->cscipher->blksize - 1;
  5106. stringlen -= (stringlen % ssh->cscipher->blksize);
  5107. if (ssh->cscomp) {
  5108. /*
  5109. * Temporarily disable actual compression,
  5110. * so we can guarantee to get this string
  5111. * exactly the length we want it. The
  5112. * compression-disabling routine should
  5113. * return an integer indicating how many
  5114. * bytes we should adjust our string length
  5115. * by.
  5116. */
  5117. stringlen -=
  5118. ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
  5119. }
  5120. ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
  5121. ssh2_pkt_addstring_start(ssh);
  5122. for (i = 0; i < stringlen; i++) {
  5123. char c = (char) random_byte();
  5124. ssh2_pkt_addstring_data(ssh, &c, 1);
  5125. }
  5126. ssh2_pkt_defer(ssh);
  5127. }
  5128. ssh_pkt_defersend(ssh);
  5129. logevent("Sent password");
  5130. s->type = AUTH_TYPE_PASSWORD;
  5131. } else if (s->method == AUTH_KEYBOARD_INTERACTIVE) {
  5132. if (s->curr_prompt == 0) {
  5133. ssh2_pkt_init(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE);
  5134. ssh2_pkt_adduint32(ssh, s->num_prompts);
  5135. }
  5136. if (s->need_pw) { /* only add pw if we just got one! */
  5137. dont_log_password(ssh, PKTLOG_BLANK);
  5138. ssh2_pkt_addstring(ssh, s->password);
  5139. memset(s->password, 0, sizeof(s->password));
  5140. end_log_omission(ssh);
  5141. s->curr_prompt++;
  5142. }
  5143. if (s->curr_prompt >= s->num_prompts) {
  5144. ssh2_pkt_send(ssh);
  5145. } else {
  5146. /*
  5147. * If there are prompts remaining, we set
  5148. * `gotit' so that we won't attempt to get
  5149. * another packet. Then we go back round the
  5150. * loop and will end up retrieving another
  5151. * prompt out of the existing packet. Funky or
  5152. * what?
  5153. */
  5154. s->gotit = TRUE;
  5155. }
  5156. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
  5157. } else {
  5158. c_write_str(ssh, "No supported authentication methods"
  5159. " left to try!\r\n");
  5160. logevent("No supported authentications offered."
  5161. " Disconnecting");
  5162. ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
  5163. ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
  5164. ssh2_pkt_addstring(ssh, "No supported authentication"
  5165. " methods available");
  5166. ssh2_pkt_addstring(ssh, "en"); /* language tag */
  5167. ssh2_pkt_send(ssh);
  5168. ssh_closing((Plug)ssh, NULL, 0, 0);
  5169. crStopV;
  5170. }
  5171. }
  5172. } while (!s->we_are_in);
  5173. /*
  5174. * Now we're authenticated for the connection protocol. The
  5175. * connection protocol will automatically have started at this
  5176. * point; there's no need to send SERVICE_REQUEST.
  5177. */
  5178. ssh->channels = newtree234(ssh_channelcmp);
  5179. /*
  5180. * Create the main session channel.
  5181. */
  5182. if (!ssh->cfg.ssh_no_shell) {
  5183. ssh->mainchan = snew(struct ssh_channel);
  5184. ssh->mainchan->ssh = ssh;
  5185. ssh->mainchan->localid = alloc_channel_id(ssh);
  5186. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
  5187. ssh2_pkt_addstring(ssh, "session");
  5188. ssh2_pkt_adduint32(ssh, ssh->mainchan->localid);
  5189. ssh->mainchan->v.v2.locwindow = OUR_V2_WINSIZE;
  5190. ssh2_pkt_adduint32(ssh, ssh->mainchan->v.v2.locwindow);/* our window size */
  5191. ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
  5192. ssh2_pkt_send(ssh);
  5193. crWaitUntilV(ispkt);
  5194. if (ssh->pktin.type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
  5195. bombout(("Server refused to open a session"));
  5196. crStopV;
  5197. /* FIXME: error data comes back in FAILURE packet */
  5198. }
  5199. if (ssh_pkt_getuint32(ssh) != ssh->mainchan->localid) {
  5200. bombout(("Server's channel confirmation cited wrong channel"));
  5201. crStopV;
  5202. }
  5203. ssh->mainchan->remoteid = ssh_pkt_getuint32(ssh);
  5204. ssh->mainchan->type = CHAN_MAINSESSION;
  5205. ssh->mainchan->closes = 0;
  5206. ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(ssh);
  5207. ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(ssh);
  5208. bufchain_init(&ssh->mainchan->v.v2.outbuffer);
  5209. add234(ssh->channels, ssh->mainchan);
  5210. update_specials_menu(ssh->frontend);
  5211. logevent("Opened channel for session");
  5212. } else
  5213. ssh->mainchan = NULL;
  5214. /*
  5215. * Potentially enable X11 forwarding.
  5216. */
  5217. if (ssh->mainchan && ssh->cfg.x11_forward) {
  5218. char proto[20], data[64];
  5219. logevent("Requesting X11 forwarding");
  5220. ssh->x11auth = x11_invent_auth(proto, sizeof(proto),
  5221. data, sizeof(data), ssh->cfg.x11_auth);
  5222. x11_get_real_auth(ssh->x11auth, ssh->cfg.x11_display);
  5223. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
  5224. ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
  5225. ssh2_pkt_addstring(ssh, "x11-req");
  5226. ssh2_pkt_addbool(ssh, 1); /* want reply */
  5227. ssh2_pkt_addbool(ssh, 0); /* many connections */
  5228. ssh2_pkt_addstring(ssh, proto);
  5229. ssh2_pkt_addstring(ssh, data);
  5230. ssh2_pkt_adduint32(ssh, x11_get_screen_number(ssh->cfg.x11_display));
  5231. ssh2_pkt_send(ssh);
  5232. do {
  5233. crWaitUntilV(ispkt);
  5234. if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
  5235. unsigned i = ssh_pkt_getuint32(ssh);
  5236. struct ssh_channel *c;
  5237. c = find234(ssh->channels, &i, ssh_channelfind);
  5238. if (!c)
  5239. continue; /* nonexistent channel */
  5240. c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
  5241. }
  5242. } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  5243. if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
  5244. if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
  5245. bombout(("Unexpected response to X11 forwarding request:"
  5246. " packet type %d", ssh->pktin.type));
  5247. crStopV;
  5248. }
  5249. logevent("X11 forwarding refused");
  5250. } else {
  5251. logevent("X11 forwarding enabled");
  5252. ssh->X11_fwd_enabled = TRUE;
  5253. }
  5254. }
  5255. /*
  5256. * Enable port forwardings.
  5257. */
  5258. {
  5259. char type;
  5260. int n;
  5261. int sport,dport,sserv,dserv;
  5262. char sports[256], dports[256], saddr[256], host[256];
  5263. ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
  5264. /* Add port forwardings. */
  5265. ssh->portfwd_strptr = ssh->cfg.portfwd;
  5266. while (*ssh->portfwd_strptr) {
  5267. type = *ssh->portfwd_strptr++;
  5268. saddr[0] = '\0';
  5269. n = 0;
  5270. while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != '\t') {
  5271. if (*ssh->portfwd_strptr == ':') {
  5272. /*
  5273. * We've seen a colon in the middle of the
  5274. * source port number. This means that
  5275. * everything we've seen until now is the
  5276. * source _address_, so we'll move it into
  5277. * saddr and start sports from the beginning
  5278. * again.
  5279. */
  5280. ssh->portfwd_strptr++;
  5281. sports[n] = '\0';
  5282. strcpy(saddr, sports);
  5283. n = 0;
  5284. }
  5285. if (n < 255) sports[n++] = *ssh->portfwd_strptr++;
  5286. }
  5287. sports[n] = 0;
  5288. if (type != 'D') {
  5289. if (*ssh->portfwd_strptr == '\t')
  5290. ssh->portfwd_strptr++;
  5291. n = 0;
  5292. while (*ssh->portfwd_strptr && *ssh->portfwd_strptr != ':') {
  5293. if (n < 255) host[n++] = *ssh->portfwd_strptr++;
  5294. }
  5295. host[n] = 0;
  5296. if (*ssh->portfwd_strptr == ':')
  5297. ssh->portfwd_strptr++;
  5298. n = 0;
  5299. while (*ssh->portfwd_strptr) {
  5300. if (n < 255) dports[n++] = *ssh->portfwd_strptr++;
  5301. }
  5302. dports[n] = 0;
  5303. ssh->portfwd_strptr++;
  5304. dport = atoi(dports);
  5305. dserv = 0;
  5306. if (dport == 0) {
  5307. dserv = 1;
  5308. dport = net_service_lookup(dports);
  5309. if (!dport) {
  5310. logeventf(ssh, "Service lookup failed for destination"
  5311. " port \"%s\"", dports);
  5312. }
  5313. }
  5314. } else {
  5315. while (*ssh->portfwd_strptr) ssh->portfwd_strptr++;
  5316. dport = dserv = -1;
  5317. ssh->portfwd_strptr++; /* eat the NUL and move to next one */
  5318. }
  5319. sport = atoi(sports);
  5320. sserv = 0;
  5321. if (sport == 0) {
  5322. sserv = 1;
  5323. sport = net_service_lookup(sports);
  5324. if (!sport) {
  5325. logeventf(ssh, "Service lookup failed for source"
  5326. " port \"%s\"", sports);
  5327. }
  5328. }
  5329. if (sport && dport) {
  5330. /* Set up a description of the source port. */
  5331. static char *sportdesc;
  5332. sportdesc = dupprintf("%.*s%.*s%.*s%.*s%d%.*s",
  5333. (int)(*saddr?strlen(saddr):0), *saddr?saddr:NULL,
  5334. (int)(*saddr?1:0), ":",
  5335. (int)(sserv ? strlen(sports) : 0), sports,
  5336. sserv, "(", sport, sserv, ")");
  5337. if (type == 'L') {
  5338. /* Verbose description of the destination port */
  5339. char *dportdesc = dupprintf("%s:%.*s%.*s%d%.*s",
  5340. host,
  5341. (int)(dserv ? strlen(dports) : 0), dports,
  5342. dserv, "(", dport, dserv, ")");
  5343. const char *err = pfd_addforward(host, dport,
  5344. *saddr ? saddr : NULL,
  5345. sport, ssh, &ssh->cfg);
  5346. if (err) {
  5347. logeventf(ssh, "Local port %s forward to %s"
  5348. " failed: %s", sportdesc, dportdesc, err);
  5349. } else {
  5350. logeventf(ssh, "Local port %s forwarding to %s",
  5351. sportdesc, dportdesc);
  5352. }
  5353. sfree(dportdesc);
  5354. } else if (type == 'D') {
  5355. const char *err = pfd_addforward(NULL, -1,
  5356. *saddr ? saddr : NULL,
  5357. sport, ssh, &ssh->cfg);
  5358. if (err) {
  5359. logeventf(ssh, "Local port %s SOCKS dynamic forward"
  5360. " setup failed: %s", sportdesc, err);
  5361. } else {
  5362. logeventf(ssh, "Local port %s doing SOCKS"
  5363. " dynamic forwarding", sportdesc);
  5364. }
  5365. } else {
  5366. struct ssh_rportfwd *pf;
  5367. pf = snew(struct ssh_rportfwd);
  5368. strcpy(pf->dhost, host);
  5369. pf->dport = dport;
  5370. pf->sport = sport;
  5371. if (add234(ssh->rportfwds, pf) != pf) {
  5372. logeventf(ssh, "Duplicate remote port forwarding"
  5373. " to %s:%d", host, dport);
  5374. sfree(pf);
  5375. } else {
  5376. logeventf(ssh, "Requesting remote port %s"
  5377. " forward to %s:%.*s%.*s%d%.*s",
  5378. sportdesc,
  5379. host,
  5380. (int)(dserv ? strlen(dports) : 0), dports,
  5381. dserv, "(", dport, dserv, ")");
  5382. ssh2_pkt_init(ssh, SSH2_MSG_GLOBAL_REQUEST);
  5383. ssh2_pkt_addstring(ssh, "tcpip-forward");
  5384. ssh2_pkt_addbool(ssh, 1);/* want reply */
  5385. if (*saddr) {
  5386. ssh2_pkt_addstring(ssh, saddr);
  5387. } else if (ssh->cfg.rport_acceptall) {
  5388. ssh2_pkt_addstring(ssh, "0.0.0.0");
  5389. } else {
  5390. ssh2_pkt_addstring(ssh, "127.0.0.1");
  5391. }
  5392. ssh2_pkt_adduint32(ssh, sport);
  5393. ssh2_pkt_send(ssh);
  5394. do {
  5395. crWaitUntilV(ispkt);
  5396. if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
  5397. unsigned i = ssh_pkt_getuint32(ssh);
  5398. struct ssh_channel *c;
  5399. c = find234(ssh->channels, &i, ssh_channelfind);
  5400. if (!c)
  5401. continue;/* nonexistent channel */
  5402. c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
  5403. }
  5404. } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  5405. if (ssh->pktin.type != SSH2_MSG_REQUEST_SUCCESS) {
  5406. if (ssh->pktin.type != SSH2_MSG_REQUEST_FAILURE) {
  5407. bombout(("Unexpected response to port "
  5408. "forwarding request: packet type %d",
  5409. ssh->pktin.type));
  5410. crStopV;
  5411. }
  5412. logevent("Server refused this port forwarding");
  5413. } else {
  5414. logevent("Remote port forwarding enabled");
  5415. }
  5416. }
  5417. }
  5418. sfree(sportdesc);
  5419. }
  5420. }
  5421. }
  5422. /*
  5423. * Potentially enable agent forwarding.
  5424. */
  5425. if (ssh->mainchan && ssh->cfg.agentfwd && agent_exists()) {
  5426. logevent("Requesting OpenSSH-style agent forwarding");
  5427. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
  5428. ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
  5429. ssh2_pkt_addstring(ssh, "auth-agent-req@openssh.com");
  5430. ssh2_pkt_addbool(ssh, 1); /* want reply */
  5431. ssh2_pkt_send(ssh);
  5432. do {
  5433. crWaitUntilV(ispkt);
  5434. if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
  5435. unsigned i = ssh_pkt_getuint32(ssh);
  5436. struct ssh_channel *c;
  5437. c = find234(ssh->channels, &i, ssh_channelfind);
  5438. if (!c)
  5439. continue; /* nonexistent channel */
  5440. c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
  5441. }
  5442. } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  5443. if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
  5444. if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
  5445. bombout(("Unexpected response to agent forwarding request:"
  5446. " packet type %d", ssh->pktin.type));
  5447. crStopV;
  5448. }
  5449. logevent("Agent forwarding refused");
  5450. } else {
  5451. logevent("Agent forwarding enabled");
  5452. ssh->agentfwd_enabled = TRUE;
  5453. }
  5454. }
  5455. /*
  5456. * Now allocate a pty for the session.
  5457. */
  5458. if (ssh->mainchan && !ssh->cfg.nopty) {
  5459. /* Unpick the terminal-speed string. */
  5460. /* XXX perhaps we should allow no speeds to be sent. */
  5461. ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
  5462. sscanf(ssh->cfg.termspeed, "%d,%d", &ssh->ospeed, &ssh->ispeed);
  5463. /* Build the pty request. */
  5464. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
  5465. ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
  5466. ssh2_pkt_addstring(ssh, "pty-req");
  5467. ssh2_pkt_addbool(ssh, 1); /* want reply */
  5468. ssh2_pkt_addstring(ssh, ssh->cfg.termtype);
  5469. ssh2_pkt_adduint32(ssh, ssh->term_width);
  5470. ssh2_pkt_adduint32(ssh, ssh->term_height);
  5471. ssh2_pkt_adduint32(ssh, 0); /* pixel width */
  5472. ssh2_pkt_adduint32(ssh, 0); /* pixel height */
  5473. ssh2_pkt_addstring_start(ssh);
  5474. ssh2_pkt_addbyte(ssh, 128); /* TTY_OP_ISPEED */
  5475. ssh2_pkt_adduint32(ssh, ssh->ispeed);
  5476. ssh2_pkt_addbyte(ssh, 129); /* TTY_OP_OSPEED */
  5477. ssh2_pkt_adduint32(ssh, ssh->ospeed);
  5478. ssh2_pkt_addstring_data(ssh, "\0", 1); /* TTY_OP_END */
  5479. ssh2_pkt_send(ssh);
  5480. ssh->state = SSH_STATE_INTERMED;
  5481. do {
  5482. crWaitUntilV(ispkt);
  5483. if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
  5484. unsigned i = ssh_pkt_getuint32(ssh);
  5485. struct ssh_channel *c;
  5486. c = find234(ssh->channels, &i, ssh_channelfind);
  5487. if (!c)
  5488. continue; /* nonexistent channel */
  5489. c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
  5490. }
  5491. } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  5492. if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
  5493. if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
  5494. bombout(("Unexpected response to pty request:"
  5495. " packet type %d", ssh->pktin.type));
  5496. crStopV;
  5497. }
  5498. c_write_str(ssh, "Server refused to allocate pty\r\n");
  5499. ssh->editing = ssh->echoing = 1;
  5500. } else {
  5501. logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
  5502. ssh->ospeed, ssh->ispeed);
  5503. }
  5504. } else {
  5505. ssh->editing = ssh->echoing = 1;
  5506. }
  5507. /*
  5508. * Send environment variables.
  5509. *
  5510. * Simplest thing here is to send all the requests at once, and
  5511. * then wait for a whole bunch of successes or failures.
  5512. */
  5513. if (ssh->mainchan && *ssh->cfg.environmt) {
  5514. char *e = ssh->cfg.environmt;
  5515. char *var, *varend, *val;
  5516. s->num_env = 0;
  5517. while (*e) {
  5518. var = e;
  5519. while (*e && *e != '\t') e++;
  5520. varend = e;
  5521. if (*e == '\t') e++;
  5522. val = e;
  5523. while (*e) e++;
  5524. e++;
  5525. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
  5526. ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
  5527. ssh2_pkt_addstring(ssh, "env");
  5528. ssh2_pkt_addbool(ssh, 1); /* want reply */
  5529. ssh2_pkt_addstring_start(ssh);
  5530. ssh2_pkt_addstring_data(ssh, var, varend-var);
  5531. ssh2_pkt_addstring(ssh, val);
  5532. ssh2_pkt_send(ssh);
  5533. s->num_env++;
  5534. }
  5535. logeventf(ssh, "Sent %d environment variables", s->num_env);
  5536. s->env_ok = 0;
  5537. s->env_left = s->num_env;
  5538. while (s->env_left > 0) {
  5539. do {
  5540. crWaitUntilV(ispkt);
  5541. if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
  5542. unsigned i = ssh_pkt_getuint32(ssh);
  5543. struct ssh_channel *c;
  5544. c = find234(ssh->channels, &i, ssh_channelfind);
  5545. if (!c)
  5546. continue; /* nonexistent channel */
  5547. c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
  5548. }
  5549. } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  5550. if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
  5551. if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
  5552. bombout(("Unexpected response to environment request:"
  5553. " packet type %d", ssh->pktin.type));
  5554. crStopV;
  5555. }
  5556. } else {
  5557. s->env_ok++;
  5558. }
  5559. s->env_left--;
  5560. }
  5561. if (s->env_ok == s->num_env) {
  5562. logevent("All environment variables successfully set");
  5563. } else if (s->env_ok == 0) {
  5564. logevent("All environment variables refused");
  5565. c_write_str(ssh, "Server refused to set environment variables\r\n");
  5566. } else {
  5567. logeventf(ssh, "%d environment variables refused",
  5568. s->num_env - s->env_ok);
  5569. c_write_str(ssh, "Server refused to set all environment variables\r\n");
  5570. }
  5571. }
  5572. /*
  5573. * Start a shell or a remote command. We may have to attempt
  5574. * this twice if the config data has provided a second choice
  5575. * of command.
  5576. */
  5577. if (ssh->mainchan) while (1) {
  5578. int subsys;
  5579. char *cmd;
  5580. if (ssh->fallback_cmd) {
  5581. subsys = ssh->cfg.ssh_subsys2;
  5582. cmd = ssh->cfg.remote_cmd_ptr2;
  5583. } else {
  5584. subsys = ssh->cfg.ssh_subsys;
  5585. cmd = ssh->cfg.remote_cmd_ptr;
  5586. }
  5587. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
  5588. ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid); /* recipient channel */
  5589. if (subsys) {
  5590. ssh2_pkt_addstring(ssh, "subsystem");
  5591. ssh2_pkt_addbool(ssh, 1); /* want reply */
  5592. ssh2_pkt_addstring(ssh, cmd);
  5593. } else if (*cmd) {
  5594. ssh2_pkt_addstring(ssh, "exec");
  5595. ssh2_pkt_addbool(ssh, 1); /* want reply */
  5596. ssh2_pkt_addstring(ssh, cmd);
  5597. } else {
  5598. ssh2_pkt_addstring(ssh, "shell");
  5599. ssh2_pkt_addbool(ssh, 1); /* want reply */
  5600. }
  5601. ssh2_pkt_send(ssh);
  5602. do {
  5603. crWaitUntilV(ispkt);
  5604. if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
  5605. unsigned i = ssh_pkt_getuint32(ssh);
  5606. struct ssh_channel *c;
  5607. c = find234(ssh->channels, &i, ssh_channelfind);
  5608. if (!c)
  5609. continue; /* nonexistent channel */
  5610. c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
  5611. }
  5612. } while (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  5613. if (ssh->pktin.type != SSH2_MSG_CHANNEL_SUCCESS) {
  5614. if (ssh->pktin.type != SSH2_MSG_CHANNEL_FAILURE) {
  5615. bombout(("Unexpected response to shell/command request:"
  5616. " packet type %d", ssh->pktin.type));
  5617. crStopV;
  5618. }
  5619. /*
  5620. * We failed to start the command. If this is the
  5621. * fallback command, we really are finished; if it's
  5622. * not, and if the fallback command exists, try falling
  5623. * back to it before complaining.
  5624. */
  5625. if (!ssh->fallback_cmd && ssh->cfg.remote_cmd_ptr2 != NULL) {
  5626. logevent("Primary command failed; attempting fallback");
  5627. ssh->fallback_cmd = TRUE;
  5628. continue;
  5629. }
  5630. bombout(("Server refused to start a shell/command"));
  5631. crStopV;
  5632. } else {
  5633. logevent("Started a shell/command");
  5634. }
  5635. break;
  5636. }
  5637. ssh->state = SSH_STATE_SESSION;
  5638. if (ssh->size_needed)
  5639. ssh_size(ssh, ssh->term_width, ssh->term_height);
  5640. if (ssh->eof_needed)
  5641. ssh_special(ssh, TS_EOF);
  5642. /*
  5643. * Transfer data!
  5644. */
  5645. if (ssh->ldisc)
  5646. ldisc_send(ssh->ldisc, NULL, 0, 0);/* cause ldisc to notice changes */
  5647. if (ssh->mainchan)
  5648. ssh->send_ok = 1;
  5649. while (1) {
  5650. crReturnV;
  5651. s->try_send = FALSE;
  5652. if (ispkt) {
  5653. if (ssh->pktin.type == SSH2_MSG_CHANNEL_DATA ||
  5654. ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA) {
  5655. char *data;
  5656. int length;
  5657. unsigned i = ssh_pkt_getuint32(ssh);
  5658. struct ssh_channel *c;
  5659. c = find234(ssh->channels, &i, ssh_channelfind);
  5660. if (!c)
  5661. continue; /* nonexistent channel */
  5662. if (ssh->pktin.type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
  5663. ssh_pkt_getuint32(ssh) != SSH2_EXTENDED_DATA_STDERR)
  5664. continue; /* extended but not stderr */
  5665. ssh_pkt_getstring(ssh, &data, &length);
  5666. if (data) {
  5667. int bufsize = 0;
  5668. c->v.v2.locwindow -= length;
  5669. switch (c->type) {
  5670. case CHAN_MAINSESSION:
  5671. bufsize =
  5672. from_backend(ssh->frontend, ssh->pktin.type ==
  5673. SSH2_MSG_CHANNEL_EXTENDED_DATA,
  5674. data, length);
  5675. break;
  5676. case CHAN_X11:
  5677. bufsize = x11_send(c->u.x11.s, data, length);
  5678. break;
  5679. case CHAN_SOCKDATA:
  5680. bufsize = pfd_send(c->u.pfd.s, data, length);
  5681. break;
  5682. case CHAN_AGENT:
  5683. while (length > 0) {
  5684. if (c->u.a.lensofar < 4) {
  5685. int l = min(4 - c->u.a.lensofar, length);
  5686. memcpy(c->u.a.msglen + c->u.a.lensofar,
  5687. data, l);
  5688. data += l;
  5689. length -= l;
  5690. c->u.a.lensofar += l;
  5691. }
  5692. if (c->u.a.lensofar == 4) {
  5693. c->u.a.totallen =
  5694. 4 + GET_32BIT(c->u.a.msglen);
  5695. c->u.a.message = snewn(c->u.a.totallen,
  5696. unsigned char);
  5697. memcpy(c->u.a.message, c->u.a.msglen, 4);
  5698. }
  5699. if (c->u.a.lensofar >= 4 && length > 0) {
  5700. int l =
  5701. min(c->u.a.totallen - c->u.a.lensofar,
  5702. length);
  5703. memcpy(c->u.a.message + c->u.a.lensofar,
  5704. data, l);
  5705. data += l;
  5706. length -= l;
  5707. c->u.a.lensofar += l;
  5708. }
  5709. if (c->u.a.lensofar == c->u.a.totallen) {
  5710. void *reply;
  5711. int replylen;
  5712. if (agent_query(c->u.a.message,
  5713. c->u.a.totallen,
  5714. &reply, &replylen,
  5715. ssh_agentf_callback, c))
  5716. ssh_agentf_callback(c, reply, replylen);
  5717. sfree(c->u.a.message);
  5718. c->u.a.lensofar = 0;
  5719. }
  5720. }
  5721. bufsize = 0;
  5722. break;
  5723. }
  5724. /*
  5725. * If we are not buffering too much data,
  5726. * enlarge the window again at the remote side.
  5727. */
  5728. if (bufsize < OUR_V2_WINSIZE)
  5729. ssh2_set_window(c, OUR_V2_WINSIZE - bufsize);
  5730. }
  5731. } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_EOF) {
  5732. unsigned i = ssh_pkt_getuint32(ssh);
  5733. struct ssh_channel *c;
  5734. c = find234(ssh->channels, &i, ssh_channelfind);
  5735. if (!c)
  5736. continue; /* nonexistent channel */
  5737. if (c->type == CHAN_X11) {
  5738. /*
  5739. * Remote EOF on an X11 channel means we should
  5740. * wrap up and close the channel ourselves.
  5741. */
  5742. x11_close(c->u.x11.s);
  5743. sshfwd_close(c);
  5744. } else if (c->type == CHAN_AGENT) {
  5745. sshfwd_close(c);
  5746. } else if (c->type == CHAN_SOCKDATA) {
  5747. pfd_close(c->u.pfd.s);
  5748. sshfwd_close(c);
  5749. }
  5750. } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_CLOSE) {
  5751. unsigned i = ssh_pkt_getuint32(ssh);
  5752. struct ssh_channel *c;
  5753. c = find234(ssh->channels, &i, ssh_channelfind);
  5754. if (!c || ((int)c->remoteid) == -1) {
  5755. bombout(("Received CHANNEL_CLOSE for %s channel %d\n",
  5756. c ? "half-open" : "nonexistent", i));
  5757. crStopV;
  5758. }
  5759. /* Do pre-close processing on the channel. */
  5760. switch (c->type) {
  5761. case CHAN_MAINSESSION:
  5762. ssh->mainchan = NULL;
  5763. update_specials_menu(ssh->frontend);
  5764. break;
  5765. case CHAN_X11:
  5766. if (c->u.x11.s != NULL)
  5767. x11_close(c->u.x11.s);
  5768. sshfwd_close(c);
  5769. break;
  5770. case CHAN_AGENT:
  5771. sshfwd_close(c);
  5772. break;
  5773. case CHAN_SOCKDATA:
  5774. if (c->u.pfd.s != NULL)
  5775. pfd_close(c->u.pfd.s);
  5776. sshfwd_close(c);
  5777. break;
  5778. }
  5779. if (c->closes == 0) {
  5780. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
  5781. ssh2_pkt_adduint32(ssh, c->remoteid);
  5782. ssh2_pkt_send(ssh);
  5783. }
  5784. del234(ssh->channels, c);
  5785. bufchain_clear(&c->v.v2.outbuffer);
  5786. sfree(c);
  5787. /*
  5788. * See if that was the last channel left open.
  5789. * (This is only our termination condition if we're
  5790. * not running in -N mode.)
  5791. */
  5792. if (!ssh->cfg.ssh_no_shell && count234(ssh->channels) == 0) {
  5793. logevent("All channels closed. Disconnecting");
  5794. #if 0
  5795. /*
  5796. * We used to send SSH_MSG_DISCONNECT here,
  5797. * because I'd believed that _every_ conforming
  5798. * SSH2 connection had to end with a disconnect
  5799. * being sent by at least one side; apparently
  5800. * I was wrong and it's perfectly OK to
  5801. * unceremoniously slam the connection shut
  5802. * when you're done, and indeed OpenSSH feels
  5803. * this is more polite than sending a
  5804. * DISCONNECT. So now we don't.
  5805. */
  5806. ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
  5807. ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
  5808. ssh2_pkt_addstring(ssh, "All open channels closed");
  5809. ssh2_pkt_addstring(ssh, "en"); /* language tag */
  5810. ssh2_pkt_send(ssh);
  5811. #endif
  5812. ssh_closing((Plug)ssh, NULL, 0, 0);
  5813. crStopV;
  5814. }
  5815. continue; /* remote sends close; ignore (FIXME) */
  5816. } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_WINDOW_ADJUST) {
  5817. unsigned i = ssh_pkt_getuint32(ssh);
  5818. struct ssh_channel *c;
  5819. c = find234(ssh->channels, &i, ssh_channelfind);
  5820. if (!c || c->closes)
  5821. continue; /* nonexistent or closing channel */
  5822. c->v.v2.remwindow += ssh_pkt_getuint32(ssh);
  5823. s->try_send = TRUE;
  5824. } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
  5825. unsigned i = ssh_pkt_getuint32(ssh);
  5826. struct ssh_channel *c;
  5827. c = find234(ssh->channels, &i, ssh_channelfind);
  5828. if (!c)
  5829. continue; /* nonexistent channel */
  5830. if (c->type != CHAN_SOCKDATA_DORMANT)
  5831. continue; /* dunno why they're confirming this */
  5832. c->remoteid = ssh_pkt_getuint32(ssh);
  5833. c->type = CHAN_SOCKDATA;
  5834. c->v.v2.remwindow = ssh_pkt_getuint32(ssh);
  5835. c->v.v2.remmaxpkt = ssh_pkt_getuint32(ssh);
  5836. if (c->u.pfd.s)
  5837. pfd_confirm(c->u.pfd.s);
  5838. if (c->closes) {
  5839. /*
  5840. * We have a pending close on this channel,
  5841. * which we decided on before the server acked
  5842. * the channel open. So now we know the
  5843. * remoteid, we can close it again.
  5844. */
  5845. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_CLOSE);
  5846. ssh2_pkt_adduint32(ssh, c->remoteid);
  5847. ssh2_pkt_send(ssh);
  5848. }
  5849. } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN_FAILURE) {
  5850. static const char *const reasons[] = {
  5851. "<unknown reason code>",
  5852. "Administratively prohibited",
  5853. "Connect failed",
  5854. "Unknown channel type",
  5855. "Resource shortage",
  5856. };
  5857. unsigned i = ssh_pkt_getuint32(ssh);
  5858. unsigned reason_code;
  5859. char *reason_string;
  5860. int reason_length;
  5861. char *message;
  5862. struct ssh_channel *c;
  5863. c = find234(ssh->channels, &i, ssh_channelfind);
  5864. if (!c)
  5865. continue; /* nonexistent channel */
  5866. if (c->type != CHAN_SOCKDATA_DORMANT)
  5867. continue; /* dunno why they're failing this */
  5868. reason_code = ssh_pkt_getuint32(ssh);
  5869. if (reason_code >= lenof(reasons))
  5870. reason_code = 0; /* ensure reasons[reason_code] in range */
  5871. ssh_pkt_getstring(ssh, &reason_string, &reason_length);
  5872. message = dupprintf("Forwarded connection refused by"
  5873. " server: %s [%.*s]", reasons[reason_code],
  5874. reason_length, reason_string);
  5875. logevent(message);
  5876. sfree(message);
  5877. pfd_close(c->u.pfd.s);
  5878. del234(ssh->channels, c);
  5879. sfree(c);
  5880. } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_REQUEST) {
  5881. unsigned localid;
  5882. char *type;
  5883. int typelen, want_reply;
  5884. int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
  5885. struct ssh_channel *c;
  5886. localid = ssh_pkt_getuint32(ssh);
  5887. ssh_pkt_getstring(ssh, &type, &typelen);
  5888. want_reply = ssh2_pkt_getbool(ssh);
  5889. /*
  5890. * First, check that the channel exists. Otherwise,
  5891. * we can instantly disconnect with a rude message.
  5892. */
  5893. c = find234(ssh->channels, &localid, ssh_channelfind);
  5894. if (!c) {
  5895. char buf[80];
  5896. sprintf(buf, "Received channel request for nonexistent"
  5897. " channel %d", localid);
  5898. logevent(buf);
  5899. ssh2_pkt_init(ssh, SSH2_MSG_DISCONNECT);
  5900. ssh2_pkt_adduint32(ssh, SSH2_DISCONNECT_BY_APPLICATION);
  5901. ssh2_pkt_addstring(ssh, buf);
  5902. ssh2_pkt_addstring(ssh, "en"); /* language tag */
  5903. ssh2_pkt_send(ssh);
  5904. connection_fatal(ssh->frontend, "%s", buf);
  5905. ssh_closing((Plug)ssh, NULL, 0, 0);
  5906. crStopV;
  5907. }
  5908. /*
  5909. * Having got the channel number, we now look at
  5910. * the request type string to see if it's something
  5911. * we recognise.
  5912. */
  5913. if (c == ssh->mainchan) {
  5914. /*
  5915. * We recognise "exit-status" and "exit-signal" on
  5916. * the primary channel.
  5917. */
  5918. if (typelen == 11 &&
  5919. !memcmp(type, "exit-status", 11)) {
  5920. ssh->exitcode = ssh_pkt_getuint32(ssh);
  5921. logeventf(ssh, "Server sent command exit status %d",
  5922. ssh->exitcode);
  5923. reply = SSH2_MSG_CHANNEL_SUCCESS;
  5924. } else if (typelen == 11 &&
  5925. !memcmp(type, "exit-signal", 11)) {
  5926. int is_plausible = TRUE, is_int = FALSE;
  5927. char *fmt_sig = "", *fmt_msg = "";
  5928. char *msg;
  5929. int msglen = 0, core = FALSE;
  5930. /* ICK: older versions of OpenSSH (e.g. 3.4p1)
  5931. * provide an `int' for the signal, despite its
  5932. * having been a `string' in the drafts since at
  5933. * least 2001. (Fixed in session.c 1.147.) Try to
  5934. * infer which we can safely parse it as. */
  5935. {
  5936. unsigned char *p = ssh->pktin.body +
  5937. ssh->pktin.savedpos;
  5938. long len = ssh->pktin.length - ssh->pktin.savedpos;
  5939. unsigned long num = GET_32BIT(p); /* what is it? */
  5940. /* If it's 0, it hardly matters; assume string */
  5941. if (num == 0) {
  5942. is_int = FALSE;
  5943. } else {
  5944. int maybe_int = FALSE, maybe_str = FALSE;
  5945. #define CHECK_HYPOTHESIS(offset, result) \
  5946. do { \
  5947. long q = offset; \
  5948. if (q >= 0 && q+4 <= len) { \
  5949. q = q + 4 + GET_32BIT(p+q); \
  5950. if (q >= 0 && q+4 <= len && \
  5951. (q = q + 4 + GET_32BIT(p+q)) && q == len) \
  5952. result = TRUE; \
  5953. } \
  5954. } while(0)
  5955. CHECK_HYPOTHESIS(4+1, maybe_int);
  5956. CHECK_HYPOTHESIS(4+num+1, maybe_str);
  5957. #undef CHECK_HYPOTHESIS
  5958. if (maybe_int && !maybe_str)
  5959. is_int = TRUE;
  5960. else if (!maybe_int && maybe_str)
  5961. is_int = FALSE;
  5962. else
  5963. /* Crikey. Either or neither. Panic. */
  5964. is_plausible = FALSE;
  5965. }
  5966. }
  5967. if (is_plausible) {
  5968. if (is_int) {
  5969. /* Old non-standard OpenSSH. */
  5970. int signum = ssh_pkt_getuint32(ssh);
  5971. fmt_sig = dupprintf(" %d", signum);
  5972. } else {
  5973. /* As per the drafts. */
  5974. char *sig;
  5975. int siglen;
  5976. ssh_pkt_getstring(ssh, &sig, &siglen);
  5977. /* Signal name isn't supposed to be blank, but
  5978. * let's cope gracefully if it is. */
  5979. if (siglen) {
  5980. fmt_sig = dupprintf(" \"%.*s\"",
  5981. siglen, sig);
  5982. }
  5983. }
  5984. core = ssh2_pkt_getbool(ssh);
  5985. ssh_pkt_getstring(ssh, &msg, &msglen);
  5986. if (msglen) {
  5987. fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
  5988. }
  5989. /* ignore lang tag */
  5990. } /* else don't attempt to parse */
  5991. logeventf(ssh, "Server exited on signal%s%s%s",
  5992. fmt_sig, core ? " (core dumped)" : "",
  5993. fmt_msg);
  5994. if (*fmt_sig) sfree(fmt_sig);
  5995. if (*fmt_msg) sfree(fmt_msg);
  5996. reply = SSH2_MSG_CHANNEL_SUCCESS;
  5997. }
  5998. } else {
  5999. /*
  6000. * This is a channel request we don't know
  6001. * about, so we now either ignore the request
  6002. * or respond with CHANNEL_FAILURE, depending
  6003. * on want_reply.
  6004. */
  6005. reply = SSH2_MSG_CHANNEL_FAILURE;
  6006. }
  6007. if (want_reply) {
  6008. ssh2_pkt_init(ssh, reply);
  6009. ssh2_pkt_adduint32(ssh, c->remoteid);
  6010. ssh2_pkt_send(ssh);
  6011. }
  6012. } else if (ssh->pktin.type == SSH2_MSG_GLOBAL_REQUEST) {
  6013. char *type;
  6014. int typelen, want_reply;
  6015. ssh_pkt_getstring(ssh, &type, &typelen);
  6016. want_reply = ssh2_pkt_getbool(ssh);
  6017. /*
  6018. * We currently don't support any global requests
  6019. * at all, so we either ignore the request or
  6020. * respond with REQUEST_FAILURE, depending on
  6021. * want_reply.
  6022. */
  6023. if (want_reply) {
  6024. ssh2_pkt_init(ssh, SSH2_MSG_REQUEST_FAILURE);
  6025. ssh2_pkt_send(ssh);
  6026. }
  6027. } else if (ssh->pktin.type == SSH2_MSG_CHANNEL_OPEN) {
  6028. char *type;
  6029. int typelen;
  6030. char *peeraddr;
  6031. int peeraddrlen;
  6032. int peerport;
  6033. char *error = NULL;
  6034. struct ssh_channel *c;
  6035. unsigned remid, winsize, pktsize;
  6036. ssh_pkt_getstring(ssh, &type, &typelen);
  6037. c = snew(struct ssh_channel);
  6038. c->ssh = ssh;
  6039. remid = ssh_pkt_getuint32(ssh);
  6040. winsize = ssh_pkt_getuint32(ssh);
  6041. pktsize = ssh_pkt_getuint32(ssh);
  6042. if (typelen == 3 && !memcmp(type, "x11", 3)) {
  6043. char *addrstr;
  6044. ssh_pkt_getstring(ssh, &peeraddr, &peeraddrlen);
  6045. addrstr = snewn(peeraddrlen+1, char);
  6046. memcpy(addrstr, peeraddr, peeraddrlen);
  6047. addrstr[peeraddrlen] = '\0';
  6048. peerport = ssh_pkt_getuint32(ssh);
  6049. logeventf(ssh, "Received X11 connect request from %s:%d",
  6050. addrstr, peerport);
  6051. if (!ssh->X11_fwd_enabled)
  6052. error = "X11 forwarding is not enabled";
  6053. else if (x11_init(&c->u.x11.s, ssh->cfg.x11_display, c,
  6054. ssh->x11auth, addrstr, peerport,
  6055. &ssh->cfg) != NULL) {
  6056. error = "Unable to open an X11 connection";
  6057. } else {
  6058. logevent("Opening X11 forward connection succeeded");
  6059. c->type = CHAN_X11;
  6060. }
  6061. sfree(addrstr);
  6062. } else if (typelen == 15 &&
  6063. !memcmp(type, "forwarded-tcpip", 15)) {
  6064. struct ssh_rportfwd pf, *realpf;
  6065. char *dummy;
  6066. int dummylen;
  6067. ssh_pkt_getstring(ssh, &dummy, &dummylen);/* skip address */
  6068. pf.sport = ssh_pkt_getuint32(ssh);
  6069. ssh_pkt_getstring(ssh, &peeraddr, &peeraddrlen);
  6070. peerport = ssh_pkt_getuint32(ssh);
  6071. realpf = find234(ssh->rportfwds, &pf, NULL);
  6072. logeventf(ssh, "Received remote port %d open request "
  6073. "from %s:%d", pf.sport, peeraddr, peerport);
  6074. if (realpf == NULL) {
  6075. error = "Remote port is not recognised";
  6076. } else {
  6077. const char *e = pfd_newconnect(&c->u.pfd.s,
  6078. realpf->dhost,
  6079. realpf->dport, c,
  6080. &ssh->cfg);
  6081. logeventf(ssh, "Attempting to forward remote port to "
  6082. "%s:%d", realpf->dhost, realpf->dport);
  6083. if (e != NULL) {
  6084. logeventf(ssh, "Port open failed: %s", e);
  6085. error = "Port open failed";
  6086. } else {
  6087. logevent("Forwarded port opened successfully");
  6088. c->type = CHAN_SOCKDATA;
  6089. }
  6090. }
  6091. } else if (typelen == 22 &&
  6092. !memcmp(type, "auth-agent@openssh.com", 3)) {
  6093. if (!ssh->agentfwd_enabled)
  6094. error = "Agent forwarding is not enabled";
  6095. else {
  6096. c->type = CHAN_AGENT; /* identify channel type */
  6097. c->u.a.lensofar = 0;
  6098. }
  6099. } else {
  6100. error = "Unsupported channel type requested";
  6101. }
  6102. c->remoteid = remid;
  6103. if (error) {
  6104. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_FAILURE);
  6105. ssh2_pkt_adduint32(ssh, c->remoteid);
  6106. ssh2_pkt_adduint32(ssh, SSH2_OPEN_CONNECT_FAILED);
  6107. ssh2_pkt_addstring(ssh, error);
  6108. ssh2_pkt_addstring(ssh, "en"); /* language tag */
  6109. ssh2_pkt_send(ssh);
  6110. logeventf(ssh, "Rejected channel open: %s", error);
  6111. sfree(c);
  6112. } else {
  6113. c->localid = alloc_channel_id(ssh);
  6114. c->closes = 0;
  6115. c->v.v2.locwindow = OUR_V2_WINSIZE;
  6116. c->v.v2.remwindow = winsize;
  6117. c->v.v2.remmaxpkt = pktsize;
  6118. bufchain_init(&c->v.v2.outbuffer);
  6119. add234(ssh->channels, c);
  6120. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
  6121. ssh2_pkt_adduint32(ssh, c->remoteid);
  6122. ssh2_pkt_adduint32(ssh, c->localid);
  6123. ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);
  6124. ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
  6125. ssh2_pkt_send(ssh);
  6126. }
  6127. } else {
  6128. bombout(("Strange packet received: type %d", ssh->pktin.type));
  6129. crStopV;
  6130. }
  6131. } else if (ssh->mainchan) {
  6132. /*
  6133. * We have spare data. Add it to the channel buffer.
  6134. */
  6135. ssh2_add_channel_data(ssh->mainchan, (char *)in, inlen);
  6136. s->try_send = TRUE;
  6137. }
  6138. if (s->try_send) {
  6139. int i;
  6140. struct ssh_channel *c;
  6141. /*
  6142. * Try to send data on all channels if we can.
  6143. */
  6144. for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
  6145. int bufsize;
  6146. if (c->closes)
  6147. continue; /* don't send on closing channels */
  6148. bufsize = ssh2_try_send(c);
  6149. if (bufsize == 0) {
  6150. switch (c->type) {
  6151. case CHAN_MAINSESSION:
  6152. /* stdin need not receive an unthrottle
  6153. * notification since it will be polled */
  6154. break;
  6155. case CHAN_X11:
  6156. x11_unthrottle(c->u.x11.s);
  6157. break;
  6158. case CHAN_AGENT:
  6159. /* agent sockets are request/response and need no
  6160. * buffer management */
  6161. break;
  6162. case CHAN_SOCKDATA:
  6163. pfd_unthrottle(c->u.pfd.s);
  6164. break;
  6165. }
  6166. }
  6167. }
  6168. }
  6169. }
  6170. crFinishV;
  6171. }
  6172. /*
  6173. * Handle the top-level SSH2 protocol.
  6174. */
  6175. static void ssh2_protocol(Ssh ssh, unsigned char *in, int inlen, int ispkt)
  6176. {
  6177. if (do_ssh2_transport(ssh, in, inlen, ispkt) == 0)
  6178. return;
  6179. do_ssh2_authconn(ssh, in, inlen, ispkt);
  6180. }
  6181. /*
  6182. * Called to set up the connection.
  6183. *
  6184. * Returns an error message, or NULL on success.
  6185. */
  6186. static const char *ssh_init(void *frontend_handle, void **backend_handle,
  6187. Config *cfg,
  6188. char *host, int port, char **realhost, int nodelay,
  6189. int keepalive)
  6190. {
  6191. const char *p;
  6192. Ssh ssh;
  6193. ssh = snew(struct ssh_tag);
  6194. ssh->cfg = *cfg; /* STRUCTURE COPY */
  6195. ssh->version = 0; /* when not ready yet */
  6196. ssh->s = NULL;
  6197. ssh->cipher = NULL;
  6198. ssh->v1_cipher_ctx = NULL;
  6199. ssh->crcda_ctx = NULL;
  6200. ssh->cscipher = NULL;
  6201. ssh->cs_cipher_ctx = NULL;
  6202. ssh->sccipher = NULL;
  6203. ssh->sc_cipher_ctx = NULL;
  6204. ssh->csmac = NULL;
  6205. ssh->cs_mac_ctx = NULL;
  6206. ssh->scmac = NULL;
  6207. ssh->sc_mac_ctx = NULL;
  6208. ssh->cscomp = NULL;
  6209. ssh->cs_comp_ctx = NULL;
  6210. ssh->sccomp = NULL;
  6211. ssh->sc_comp_ctx = NULL;
  6212. ssh->kex = NULL;
  6213. ssh->kex_ctx = NULL;
  6214. ssh->hostkey = NULL;
  6215. ssh->exitcode = -1;
  6216. ssh->state = SSH_STATE_PREPACKET;
  6217. ssh->size_needed = FALSE;
  6218. ssh->eof_needed = FALSE;
  6219. ssh->ldisc = NULL;
  6220. ssh->logctx = NULL;
  6221. {
  6222. static const struct Packet empty = { 0, 0, NULL, NULL, 0 };
  6223. ssh->pktin = ssh->pktout = empty;
  6224. }
  6225. ssh->deferred_send_data = NULL;
  6226. ssh->deferred_len = 0;
  6227. ssh->deferred_size = 0;
  6228. ssh->pktout_logmode = PKTLOG_EMIT;
  6229. ssh->pktout_nblanks = 0;
  6230. ssh->pktout_blanks = NULL;
  6231. ssh->fallback_cmd = 0;
  6232. ssh->pkt_ctx = 0;
  6233. ssh->x11auth = NULL;
  6234. ssh->v1_compressing = FALSE;
  6235. ssh->v2_outgoing_sequence = 0;
  6236. ssh->ssh1_rdpkt_crstate = 0;
  6237. ssh->ssh2_rdpkt_crstate = 0;
  6238. ssh->do_ssh_init_crstate = 0;
  6239. ssh->ssh_gotdata_crstate = 0;
  6240. ssh->ssh1_protocol_crstate = 0;
  6241. ssh->do_ssh1_login_crstate = 0;
  6242. ssh->do_ssh2_transport_crstate = 0;
  6243. ssh->do_ssh2_authconn_crstate = 0;
  6244. ssh->do_ssh_init_state = NULL;
  6245. ssh->do_ssh1_login_state = NULL;
  6246. ssh->do_ssh2_transport_state = NULL;
  6247. ssh->do_ssh2_authconn_state = NULL;
  6248. ssh->mainchan = NULL;
  6249. ssh->throttled_all = 0;
  6250. ssh->v1_stdout_throttling = 0;
  6251. *backend_handle = ssh;
  6252. #ifdef MSCRYPTOAPI
  6253. if (crypto_startup() == 0)
  6254. return "Microsoft high encryption pack not installed!";
  6255. #endif
  6256. ssh->frontend = frontend_handle;
  6257. ssh->term_width = ssh->cfg.width;
  6258. ssh->term_height = ssh->cfg.height;
  6259. ssh->channels = NULL;
  6260. ssh->rportfwds = NULL;
  6261. ssh->send_ok = 0;
  6262. ssh->editing = 0;
  6263. ssh->echoing = 0;
  6264. ssh->v1_throttle_count = 0;
  6265. ssh->overall_bufsize = 0;
  6266. ssh->fallback_cmd = 0;
  6267. ssh->protocol = NULL;
  6268. p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
  6269. if (p != NULL)
  6270. return p;
  6271. return NULL;
  6272. }
  6273. static void ssh_free(void *handle)
  6274. {
  6275. Ssh ssh = (Ssh) handle;
  6276. struct ssh_channel *c;
  6277. struct ssh_rportfwd *pf;
  6278. if (ssh->v1_cipher_ctx)
  6279. ssh->cipher->free_context(ssh->v1_cipher_ctx);
  6280. if (ssh->cs_cipher_ctx)
  6281. ssh->cscipher->free_context(ssh->cs_cipher_ctx);
  6282. if (ssh->sc_cipher_ctx)
  6283. ssh->sccipher->free_context(ssh->sc_cipher_ctx);
  6284. if (ssh->cs_mac_ctx)
  6285. ssh->csmac->free_context(ssh->cs_mac_ctx);
  6286. if (ssh->sc_mac_ctx)
  6287. ssh->scmac->free_context(ssh->sc_mac_ctx);
  6288. if (ssh->cs_comp_ctx) {
  6289. if (ssh->cscomp)
  6290. ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
  6291. else
  6292. zlib_compress_cleanup(ssh->cs_comp_ctx);
  6293. }
  6294. if (ssh->sc_comp_ctx) {
  6295. if (ssh->sccomp)
  6296. ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
  6297. else
  6298. zlib_decompress_cleanup(ssh->sc_comp_ctx);
  6299. }
  6300. if (ssh->kex_ctx)
  6301. dh_cleanup(ssh->kex_ctx);
  6302. sfree(ssh->savedhost);
  6303. if (ssh->channels) {
  6304. while ((c = delpos234(ssh->channels, 0)) != NULL) {
  6305. switch (c->type) {
  6306. case CHAN_X11:
  6307. if (c->u.x11.s != NULL)
  6308. x11_close(c->u.x11.s);
  6309. break;
  6310. case CHAN_SOCKDATA:
  6311. if (c->u.pfd.s != NULL)
  6312. pfd_close(c->u.pfd.s);
  6313. break;
  6314. }
  6315. sfree(c);
  6316. }
  6317. freetree234(ssh->channels);
  6318. }
  6319. if (ssh->rportfwds) {
  6320. while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
  6321. sfree(pf);
  6322. freetree234(ssh->rportfwds);
  6323. }
  6324. sfree(ssh->deferred_send_data);
  6325. if (ssh->x11auth)
  6326. x11_free_auth(ssh->x11auth);
  6327. sfree(ssh->do_ssh_init_state);
  6328. sfree(ssh->do_ssh1_login_state);
  6329. sfree(ssh->do_ssh2_transport_state);
  6330. sfree(ssh->do_ssh2_authconn_state);
  6331. if (ssh->pktout.data) {
  6332. sfree(ssh->pktout.data);
  6333. ssh->pktout.data = NULL;
  6334. }
  6335. if (ssh->pktin.data) {
  6336. sfree(ssh->pktin.data);
  6337. ssh->pktin.data = NULL;
  6338. }
  6339. if (ssh->crcda_ctx) {
  6340. crcda_free_context(ssh->crcda_ctx);
  6341. ssh->crcda_ctx = NULL;
  6342. }
  6343. if (ssh->s)
  6344. ssh_do_close(ssh);
  6345. sfree(ssh);
  6346. }
  6347. /*
  6348. * Reconfigure the SSH backend.
  6349. *
  6350. * Currently, this function does nothing very useful. In future,
  6351. * however, we could do some handy things with it. For example, we
  6352. * could make the port forwarding configurer active in the Change
  6353. * Settings box, and this routine could close down existing
  6354. * forwardings and open up new ones in response to changes.
  6355. */
  6356. static void ssh_reconfig(void *handle, Config *cfg)
  6357. {
  6358. Ssh ssh = (Ssh) handle;
  6359. ssh->cfg = *cfg; /* STRUCTURE COPY */
  6360. }
  6361. /*
  6362. * Called to send data down the Telnet connection.
  6363. */
  6364. static int ssh_send(void *handle, char *buf, int len)
  6365. {
  6366. Ssh ssh = (Ssh) handle;
  6367. if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
  6368. return 0;
  6369. ssh->protocol(ssh, (unsigned char *)buf, len, 0);
  6370. return ssh_sendbuffer(ssh);
  6371. }
  6372. /*
  6373. * Called to query the current amount of buffered stdin data.
  6374. */
  6375. static int ssh_sendbuffer(void *handle)
  6376. {
  6377. Ssh ssh = (Ssh) handle;
  6378. int override_value;
  6379. if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
  6380. return 0;
  6381. /*
  6382. * If the SSH socket itself has backed up, add the total backup
  6383. * size on that to any individual buffer on the stdin channel.
  6384. */
  6385. override_value = 0;
  6386. if (ssh->throttled_all)
  6387. override_value = ssh->overall_bufsize;
  6388. if (ssh->version == 1) {
  6389. return override_value;
  6390. } else if (ssh->version == 2) {
  6391. if (!ssh->mainchan || ssh->mainchan->closes > 0)
  6392. return override_value;
  6393. else
  6394. return (override_value +
  6395. bufchain_size(&ssh->mainchan->v.v2.outbuffer));
  6396. }
  6397. return 0;
  6398. }
  6399. /*
  6400. * Called to set the size of the window from SSH's POV.
  6401. */
  6402. static void ssh_size(void *handle, int width, int height)
  6403. {
  6404. Ssh ssh = (Ssh) handle;
  6405. ssh->term_width = width;
  6406. ssh->term_height = height;
  6407. switch (ssh->state) {
  6408. case SSH_STATE_BEFORE_SIZE:
  6409. case SSH_STATE_PREPACKET:
  6410. case SSH_STATE_CLOSED:
  6411. break; /* do nothing */
  6412. case SSH_STATE_INTERMED:
  6413. ssh->size_needed = TRUE; /* buffer for later */
  6414. break;
  6415. case SSH_STATE_SESSION:
  6416. if (!ssh->cfg.nopty) {
  6417. if (ssh->version == 1) {
  6418. send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
  6419. PKT_INT, ssh->term_height,
  6420. PKT_INT, ssh->term_width,
  6421. PKT_INT, 0, PKT_INT, 0, PKT_END);
  6422. } else if (ssh->mainchan) {
  6423. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
  6424. ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
  6425. ssh2_pkt_addstring(ssh, "window-change");
  6426. ssh2_pkt_addbool(ssh, 0);
  6427. ssh2_pkt_adduint32(ssh, ssh->term_width);
  6428. ssh2_pkt_adduint32(ssh, ssh->term_height);
  6429. ssh2_pkt_adduint32(ssh, 0);
  6430. ssh2_pkt_adduint32(ssh, 0);
  6431. ssh2_pkt_send(ssh);
  6432. }
  6433. }
  6434. break;
  6435. }
  6436. }
  6437. /*
  6438. * Return a list of the special codes that make sense in this
  6439. * protocol.
  6440. */
  6441. static const struct telnet_special *ssh_get_specials(void *handle)
  6442. {
  6443. static const struct telnet_special ignore_special[] = {
  6444. {"IGNORE message", TS_NOP},
  6445. };
  6446. static const struct telnet_special ssh2_session_specials[] = {
  6447. {NULL, TS_SEP},
  6448. {"Break", TS_BRK},
  6449. /* These are the signal names defined by draft-ietf-secsh-connect-19.
  6450. * They include all the ISO C signals, but are a subset of the POSIX
  6451. * required signals. */
  6452. {"SIGINT (Interrupt)", TS_SIGINT},
  6453. {"SIGTERM (Terminate)", TS_SIGTERM},
  6454. {"SIGKILL (Kill)", TS_SIGKILL},
  6455. {"SIGQUIT (Quit)", TS_SIGQUIT},
  6456. {"SIGHUP (Hangup)", TS_SIGHUP},
  6457. {"More signals", TS_SUBMENU},
  6458. {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
  6459. {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
  6460. {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
  6461. {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
  6462. {NULL, TS_EXITMENU}
  6463. };
  6464. static const struct telnet_special specials_end[] = {
  6465. {NULL, TS_EXITMENU}
  6466. };
  6467. static struct telnet_special ssh_specials[lenof(ignore_special) +
  6468. lenof(ssh2_session_specials) +
  6469. lenof(specials_end)];
  6470. Ssh ssh = (Ssh) handle;
  6471. int i = 0;
  6472. #define ADD_SPECIALS(name) \
  6473. do { \
  6474. assert((i + lenof(name)) <= lenof(ssh_specials)); \
  6475. memcpy(&ssh_specials[i], name, sizeof name); \
  6476. i += lenof(name); \
  6477. } while(0)
  6478. if (ssh->version == 1) {
  6479. /* Don't bother offering IGNORE if we've decided the remote
  6480. * won't cope with it, since we wouldn't bother sending it if
  6481. * asked anyway. */
  6482. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
  6483. ADD_SPECIALS(ignore_special);
  6484. } else if (ssh->version == 2) {
  6485. /* XXX add rekey, when implemented */
  6486. ADD_SPECIALS(ignore_special);
  6487. if (ssh->mainchan)
  6488. ADD_SPECIALS(ssh2_session_specials);
  6489. } /* else we're not ready yet */
  6490. if (i) {
  6491. ADD_SPECIALS(specials_end);
  6492. return ssh_specials;
  6493. } else {
  6494. return NULL;
  6495. }
  6496. #undef ADD_SPECIALS
  6497. }
  6498. /*
  6499. * Send Telnet special codes. TS_EOF is useful for `plink', so you
  6500. * can send an EOF and collect resulting output (e.g. `plink
  6501. * hostname sort').
  6502. */
  6503. static void ssh_special(void *handle, Telnet_Special code)
  6504. {
  6505. Ssh ssh = (Ssh) handle;
  6506. if (code == TS_EOF) {
  6507. if (ssh->state != SSH_STATE_SESSION) {
  6508. /*
  6509. * Buffer the EOF in case we are pre-SESSION, so we can
  6510. * send it as soon as we reach SESSION.
  6511. */
  6512. if (code == TS_EOF)
  6513. ssh->eof_needed = TRUE;
  6514. return;
  6515. }
  6516. if (ssh->version == 1) {
  6517. send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
  6518. } else if (ssh->mainchan) {
  6519. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_EOF);
  6520. ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
  6521. ssh2_pkt_send(ssh);
  6522. }
  6523. logevent("Sent EOF message");
  6524. } else if (code == TS_PING || code == TS_NOP) {
  6525. if (ssh->state == SSH_STATE_CLOSED
  6526. || ssh->state == SSH_STATE_PREPACKET) return;
  6527. if (ssh->version == 1) {
  6528. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
  6529. send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
  6530. } else {
  6531. ssh2_pkt_init(ssh, SSH2_MSG_IGNORE);
  6532. ssh2_pkt_addstring_start(ssh);
  6533. ssh2_pkt_send(ssh);
  6534. }
  6535. } else if (code == TS_BRK) {
  6536. if (ssh->state == SSH_STATE_CLOSED
  6537. || ssh->state == SSH_STATE_PREPACKET) return;
  6538. if (ssh->version == 1) {
  6539. logevent("Unable to send BREAK signal in SSH1");
  6540. } else if (ssh->mainchan) {
  6541. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
  6542. ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
  6543. ssh2_pkt_addstring(ssh, "break");
  6544. ssh2_pkt_addbool(ssh, 0);
  6545. ssh2_pkt_adduint32(ssh, 0); /* default break length */
  6546. ssh2_pkt_send(ssh);
  6547. }
  6548. } else {
  6549. /* Is is a POSIX signal? */
  6550. char *signame = NULL;
  6551. if (code == TS_SIGABRT) signame = "ABRT";
  6552. if (code == TS_SIGALRM) signame = "ALRM";
  6553. if (code == TS_SIGFPE) signame = "FPE";
  6554. if (code == TS_SIGHUP) signame = "HUP";
  6555. if (code == TS_SIGILL) signame = "ILL";
  6556. if (code == TS_SIGINT) signame = "INT";
  6557. if (code == TS_SIGKILL) signame = "KILL";
  6558. if (code == TS_SIGPIPE) signame = "PIPE";
  6559. if (code == TS_SIGQUIT) signame = "QUIT";
  6560. if (code == TS_SIGSEGV) signame = "SEGV";
  6561. if (code == TS_SIGTERM) signame = "TERM";
  6562. if (code == TS_SIGUSR1) signame = "USR1";
  6563. if (code == TS_SIGUSR2) signame = "USR2";
  6564. /* The SSH-2 protocol does in principle support arbitrary named
  6565. * signals, including signame@domain, but we don't support those. */
  6566. if (signame) {
  6567. /* It's a signal. */
  6568. if (ssh->version == 2 && ssh->mainchan) {
  6569. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_REQUEST);
  6570. ssh2_pkt_adduint32(ssh, ssh->mainchan->remoteid);
  6571. ssh2_pkt_addstring(ssh, "signal");
  6572. ssh2_pkt_addbool(ssh, 0);
  6573. ssh2_pkt_addstring(ssh, signame);
  6574. ssh2_pkt_send(ssh);
  6575. logeventf(ssh, "Sent signal SIG%s", signame);
  6576. }
  6577. } else {
  6578. /* Never heard of it. Do nothing */
  6579. }
  6580. }
  6581. }
  6582. void *new_sock_channel(void *handle, Socket s)
  6583. {
  6584. Ssh ssh = (Ssh) handle;
  6585. struct ssh_channel *c;
  6586. c = snew(struct ssh_channel);
  6587. c->ssh = ssh;
  6588. if (c) {
  6589. c->remoteid = -1; /* to be set when open confirmed */
  6590. c->localid = alloc_channel_id(ssh);
  6591. c->closes = 0;
  6592. c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
  6593. c->u.pfd.s = s;
  6594. bufchain_init(&c->v.v2.outbuffer);
  6595. add234(ssh->channels, c);
  6596. }
  6597. return c;
  6598. }
  6599. /*
  6600. * This is called when stdout/stderr (the entity to which
  6601. * from_backend sends data) manages to clear some backlog.
  6602. */
  6603. static void ssh_unthrottle(void *handle, int bufsize)
  6604. {
  6605. Ssh ssh = (Ssh) handle;
  6606. if (ssh->version == 1) {
  6607. if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
  6608. ssh->v1_stdout_throttling = 0;
  6609. ssh1_throttle(ssh, -1);
  6610. }
  6611. } else {
  6612. if (ssh->mainchan && ssh->mainchan->closes == 0)
  6613. ssh2_set_window(ssh->mainchan, OUR_V2_WINSIZE - bufsize);
  6614. }
  6615. }
  6616. void ssh_send_port_open(void *channel, char *hostname, int port, char *org)
  6617. {
  6618. struct ssh_channel *c = (struct ssh_channel *)channel;
  6619. Ssh ssh = c->ssh;
  6620. logeventf(ssh, "Opening forwarded connection to %s:%d", hostname, port);
  6621. if (ssh->version == 1) {
  6622. send_packet(ssh, SSH1_MSG_PORT_OPEN,
  6623. PKT_INT, c->localid,
  6624. PKT_STR, hostname,
  6625. PKT_INT, port,
  6626. //PKT_STR, <org:orgport>,
  6627. PKT_END);
  6628. } else {
  6629. ssh2_pkt_init(ssh, SSH2_MSG_CHANNEL_OPEN);
  6630. ssh2_pkt_addstring(ssh, "direct-tcpip");
  6631. ssh2_pkt_adduint32(ssh, c->localid);
  6632. c->v.v2.locwindow = OUR_V2_WINSIZE;
  6633. ssh2_pkt_adduint32(ssh, c->v.v2.locwindow);/* our window size */
  6634. ssh2_pkt_adduint32(ssh, 0x4000UL); /* our max pkt size */
  6635. ssh2_pkt_addstring(ssh, hostname);
  6636. ssh2_pkt_adduint32(ssh, port);
  6637. /*
  6638. * We make up values for the originator data; partly it's
  6639. * too much hassle to keep track, and partly I'm not
  6640. * convinced the server should be told details like that
  6641. * about my local network configuration.
  6642. */
  6643. ssh2_pkt_addstring(ssh, "client-side-connection");
  6644. ssh2_pkt_adduint32(ssh, 0);
  6645. ssh2_pkt_send(ssh);
  6646. }
  6647. }
  6648. static Socket ssh_socket(void *handle)
  6649. {
  6650. Ssh ssh = (Ssh) handle;
  6651. return ssh->s;
  6652. }
  6653. static int ssh_sendok(void *handle)
  6654. {
  6655. Ssh ssh = (Ssh) handle;
  6656. return ssh->send_ok;
  6657. }
  6658. static int ssh_ldisc(void *handle, int option)
  6659. {
  6660. Ssh ssh = (Ssh) handle;
  6661. if (option == LD_ECHO)
  6662. return ssh->echoing;
  6663. if (option == LD_EDIT)
  6664. return ssh->editing;
  6665. return FALSE;
  6666. }
  6667. static void ssh_provide_ldisc(void *handle, void *ldisc)
  6668. {
  6669. Ssh ssh = (Ssh) handle;
  6670. ssh->ldisc = ldisc;
  6671. }
  6672. static void ssh_provide_logctx(void *handle, void *logctx)
  6673. {
  6674. Ssh ssh = (Ssh) handle;
  6675. ssh->logctx = logctx;
  6676. }
  6677. static int ssh_return_exitcode(void *handle)
  6678. {
  6679. Ssh ssh = (Ssh) handle;
  6680. if (ssh->s != NULL)
  6681. return -1;
  6682. else
  6683. return (ssh->exitcode >= 0 ? ssh->exitcode : 0);
  6684. }
  6685. /*
  6686. * Gross hack: pscp will try to start SFTP but fall back to scp1 if
  6687. * that fails. This variable is the means by which scp.c can reach
  6688. * into the SSH code and find out which one it got.
  6689. */
  6690. extern int ssh_fallback_cmd(void *handle)
  6691. {
  6692. Ssh ssh = (Ssh) handle;
  6693. return ssh->fallback_cmd;
  6694. }
  6695. Backend ssh_backend = {
  6696. ssh_init,
  6697. ssh_free,
  6698. ssh_reconfig,
  6699. ssh_send,
  6700. ssh_sendbuffer,
  6701. ssh_size,
  6702. ssh_special,
  6703. ssh_get_specials,
  6704. ssh_socket,
  6705. ssh_return_exitcode,
  6706. ssh_sendok,
  6707. ssh_ldisc,
  6708. ssh_provide_ldisc,
  6709. ssh_provide_logctx,
  6710. ssh_unthrottle,
  6711. 22
  6712. };