ssh.c 365 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933
  1. /*
  2. * SSH backend.
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <stdarg.h>
  7. #include <assert.h>
  8. #include <limits.h>
  9. #include <signal.h>
  10. #include "putty.h"
  11. #include "tree234.h"
  12. #include "storage.h"
  13. #include "ssh.h"
  14. #ifndef NO_GSSAPI
  15. #include "sshgssc.h"
  16. #include "sshgss.h"
  17. #endif
  18. #ifndef FALSE
  19. #define FALSE 0
  20. #endif
  21. #ifndef TRUE
  22. #define TRUE 1
  23. #endif
  24. /*
  25. * Packet type contexts, so that ssh2_pkt_type can correctly decode
  26. * the ambiguous type numbers back into the correct type strings.
  27. */
  28. typedef enum {
  29. SSH2_PKTCTX_NOKEX,
  30. SSH2_PKTCTX_DHGROUP,
  31. SSH2_PKTCTX_DHGEX,
  32. SSH2_PKTCTX_ECDHKEX,
  33. SSH2_PKTCTX_RSAKEX
  34. } Pkt_KCtx;
  35. typedef enum {
  36. SSH2_PKTCTX_NOAUTH,
  37. SSH2_PKTCTX_PUBLICKEY,
  38. SSH2_PKTCTX_PASSWORD,
  39. SSH2_PKTCTX_GSSAPI,
  40. SSH2_PKTCTX_KBDINTER
  41. } Pkt_ACtx;
  42. static const char *const ssh2_disconnect_reasons[] = {
  43. NULL,
  44. "host not allowed to connect",
  45. "protocol error",
  46. "key exchange failed",
  47. "host authentication failed",
  48. "MAC error",
  49. "compression error",
  50. "service not available",
  51. "protocol version not supported",
  52. "host key not verifiable",
  53. "connection lost",
  54. "by application",
  55. "too many connections",
  56. "auth cancelled by user",
  57. "no more auth methods available",
  58. "illegal user name",
  59. };
  60. /*
  61. * Various remote-bug flags.
  62. */
  63. #define BUG_CHOKES_ON_SSH1_IGNORE 1
  64. #define BUG_SSH2_HMAC 2
  65. #define BUG_NEEDS_SSH1_PLAIN_PASSWORD 4
  66. #define BUG_CHOKES_ON_RSA 8
  67. #define BUG_SSH2_RSA_PADDING 16
  68. #define BUG_SSH2_DERIVEKEY 32
  69. #define BUG_SSH2_REKEY 64
  70. #define BUG_SSH2_PK_SESSIONID 128
  71. #define BUG_SSH2_MAXPKT 256
  72. #define BUG_CHOKES_ON_SSH2_IGNORE 512
  73. #define BUG_CHOKES_ON_WINADJ 1024
  74. #define BUG_SENDS_LATE_REQUEST_REPLY 2048
  75. #define BUG_SSH2_OLDGEX 4096
  76. #define DH_MIN_SIZE 1024
  77. #define DH_MAX_SIZE 8192
  78. /*
  79. * Codes for terminal modes.
  80. * Most of these are the same in SSH-1 and SSH-2.
  81. * This list is derived from RFC 4254 and
  82. * SSH-1 RFC-1.2.31.
  83. */
  84. static const struct ssh_ttymode {
  85. const char* const mode;
  86. int opcode;
  87. enum { TTY_OP_CHAR, TTY_OP_BOOL } type;
  88. } ssh_ttymodes[] = {
  89. /* "V" prefix discarded for special characters relative to SSH specs */
  90. { "INTR", 1, TTY_OP_CHAR },
  91. { "QUIT", 2, TTY_OP_CHAR },
  92. { "ERASE", 3, TTY_OP_CHAR },
  93. { "KILL", 4, TTY_OP_CHAR },
  94. { "EOF", 5, TTY_OP_CHAR },
  95. { "EOL", 6, TTY_OP_CHAR },
  96. { "EOL2", 7, TTY_OP_CHAR },
  97. { "START", 8, TTY_OP_CHAR },
  98. { "STOP", 9, TTY_OP_CHAR },
  99. { "SUSP", 10, TTY_OP_CHAR },
  100. { "DSUSP", 11, TTY_OP_CHAR },
  101. { "REPRINT", 12, TTY_OP_CHAR },
  102. { "WERASE", 13, TTY_OP_CHAR },
  103. { "LNEXT", 14, TTY_OP_CHAR },
  104. { "FLUSH", 15, TTY_OP_CHAR },
  105. { "SWTCH", 16, TTY_OP_CHAR },
  106. { "STATUS", 17, TTY_OP_CHAR },
  107. { "DISCARD", 18, TTY_OP_CHAR },
  108. { "IGNPAR", 30, TTY_OP_BOOL },
  109. { "PARMRK", 31, TTY_OP_BOOL },
  110. { "INPCK", 32, TTY_OP_BOOL },
  111. { "ISTRIP", 33, TTY_OP_BOOL },
  112. { "INLCR", 34, TTY_OP_BOOL },
  113. { "IGNCR", 35, TTY_OP_BOOL },
  114. { "ICRNL", 36, TTY_OP_BOOL },
  115. { "IUCLC", 37, TTY_OP_BOOL },
  116. { "IXON", 38, TTY_OP_BOOL },
  117. { "IXANY", 39, TTY_OP_BOOL },
  118. { "IXOFF", 40, TTY_OP_BOOL },
  119. { "IMAXBEL", 41, TTY_OP_BOOL },
  120. { "IUTF8", 42, TTY_OP_BOOL },
  121. { "ISIG", 50, TTY_OP_BOOL },
  122. { "ICANON", 51, TTY_OP_BOOL },
  123. { "XCASE", 52, TTY_OP_BOOL },
  124. { "ECHO", 53, TTY_OP_BOOL },
  125. { "ECHOE", 54, TTY_OP_BOOL },
  126. { "ECHOK", 55, TTY_OP_BOOL },
  127. { "ECHONL", 56, TTY_OP_BOOL },
  128. { "NOFLSH", 57, TTY_OP_BOOL },
  129. { "TOSTOP", 58, TTY_OP_BOOL },
  130. { "IEXTEN", 59, TTY_OP_BOOL },
  131. { "ECHOCTL", 60, TTY_OP_BOOL },
  132. { "ECHOKE", 61, TTY_OP_BOOL },
  133. { "PENDIN", 62, TTY_OP_BOOL }, /* XXX is this a real mode? */
  134. { "OPOST", 70, TTY_OP_BOOL },
  135. { "OLCUC", 71, TTY_OP_BOOL },
  136. { "ONLCR", 72, TTY_OP_BOOL },
  137. { "OCRNL", 73, TTY_OP_BOOL },
  138. { "ONOCR", 74, TTY_OP_BOOL },
  139. { "ONLRET", 75, TTY_OP_BOOL },
  140. { "CS7", 90, TTY_OP_BOOL },
  141. { "CS8", 91, TTY_OP_BOOL },
  142. { "PARENB", 92, TTY_OP_BOOL },
  143. { "PARODD", 93, TTY_OP_BOOL }
  144. };
  145. /* Miscellaneous other tty-related constants. */
  146. #define SSH_TTY_OP_END 0
  147. /* The opcodes for ISPEED/OSPEED differ between SSH-1 and SSH-2. */
  148. #define SSH1_TTY_OP_ISPEED 192
  149. #define SSH1_TTY_OP_OSPEED 193
  150. #define SSH2_TTY_OP_ISPEED 128
  151. #define SSH2_TTY_OP_OSPEED 129
  152. /* Helper functions for parsing tty-related config. */
  153. static unsigned int ssh_tty_parse_specchar(char *s)
  154. {
  155. unsigned int ret;
  156. if (*s) {
  157. char *next = NULL;
  158. ret = ctrlparse(s, &next);
  159. if (!next) ret = s[0];
  160. } else {
  161. ret = 255; /* special value meaning "don't set" */
  162. }
  163. return ret;
  164. }
  165. static unsigned int ssh_tty_parse_boolean(char *s)
  166. {
  167. if (stricmp(s, "yes") == 0 ||
  168. stricmp(s, "on") == 0 ||
  169. stricmp(s, "true") == 0 ||
  170. stricmp(s, "+") == 0)
  171. return 1; /* true */
  172. else if (stricmp(s, "no") == 0 ||
  173. stricmp(s, "off") == 0 ||
  174. stricmp(s, "false") == 0 ||
  175. stricmp(s, "-") == 0)
  176. return 0; /* false */
  177. else
  178. return (atoi(s) != 0);
  179. }
  180. #define translate(x) if (type == x) return #x
  181. #define translatek(x,ctx) if (type == x && (pkt_kctx == ctx)) return #x
  182. #define translatea(x,ctx) if (type == x && (pkt_actx == ctx)) return #x
  183. static const char *ssh1_pkt_type(int type)
  184. {
  185. translate(SSH1_MSG_DISCONNECT);
  186. translate(SSH1_SMSG_PUBLIC_KEY);
  187. translate(SSH1_CMSG_SESSION_KEY);
  188. translate(SSH1_CMSG_USER);
  189. translate(SSH1_CMSG_AUTH_RSA);
  190. translate(SSH1_SMSG_AUTH_RSA_CHALLENGE);
  191. translate(SSH1_CMSG_AUTH_RSA_RESPONSE);
  192. translate(SSH1_CMSG_AUTH_PASSWORD);
  193. translate(SSH1_CMSG_REQUEST_PTY);
  194. translate(SSH1_CMSG_WINDOW_SIZE);
  195. translate(SSH1_CMSG_EXEC_SHELL);
  196. translate(SSH1_CMSG_EXEC_CMD);
  197. translate(SSH1_SMSG_SUCCESS);
  198. translate(SSH1_SMSG_FAILURE);
  199. translate(SSH1_CMSG_STDIN_DATA);
  200. translate(SSH1_SMSG_STDOUT_DATA);
  201. translate(SSH1_SMSG_STDERR_DATA);
  202. translate(SSH1_CMSG_EOF);
  203. translate(SSH1_SMSG_EXIT_STATUS);
  204. translate(SSH1_MSG_CHANNEL_OPEN_CONFIRMATION);
  205. translate(SSH1_MSG_CHANNEL_OPEN_FAILURE);
  206. translate(SSH1_MSG_CHANNEL_DATA);
  207. translate(SSH1_MSG_CHANNEL_CLOSE);
  208. translate(SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION);
  209. translate(SSH1_SMSG_X11_OPEN);
  210. translate(SSH1_CMSG_PORT_FORWARD_REQUEST);
  211. translate(SSH1_MSG_PORT_OPEN);
  212. translate(SSH1_CMSG_AGENT_REQUEST_FORWARDING);
  213. translate(SSH1_SMSG_AGENT_OPEN);
  214. translate(SSH1_MSG_IGNORE);
  215. translate(SSH1_CMSG_EXIT_CONFIRMATION);
  216. translate(SSH1_CMSG_X11_REQUEST_FORWARDING);
  217. translate(SSH1_CMSG_AUTH_RHOSTS_RSA);
  218. translate(SSH1_MSG_DEBUG);
  219. translate(SSH1_CMSG_REQUEST_COMPRESSION);
  220. translate(SSH1_CMSG_AUTH_TIS);
  221. translate(SSH1_SMSG_AUTH_TIS_CHALLENGE);
  222. translate(SSH1_CMSG_AUTH_TIS_RESPONSE);
  223. translate(SSH1_CMSG_AUTH_CCARD);
  224. translate(SSH1_SMSG_AUTH_CCARD_CHALLENGE);
  225. translate(SSH1_CMSG_AUTH_CCARD_RESPONSE);
  226. return "unknown";
  227. }
  228. static const char *ssh2_pkt_type(Pkt_KCtx pkt_kctx, Pkt_ACtx pkt_actx,
  229. int type)
  230. {
  231. translatea(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE,SSH2_PKTCTX_GSSAPI);
  232. translatea(SSH2_MSG_USERAUTH_GSSAPI_TOKEN,SSH2_PKTCTX_GSSAPI);
  233. translatea(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE,SSH2_PKTCTX_GSSAPI);
  234. translatea(SSH2_MSG_USERAUTH_GSSAPI_ERROR,SSH2_PKTCTX_GSSAPI);
  235. translatea(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK,SSH2_PKTCTX_GSSAPI);
  236. translatea(SSH2_MSG_USERAUTH_GSSAPI_MIC, SSH2_PKTCTX_GSSAPI);
  237. translate(SSH2_MSG_DISCONNECT);
  238. translate(SSH2_MSG_IGNORE);
  239. translate(SSH2_MSG_UNIMPLEMENTED);
  240. translate(SSH2_MSG_DEBUG);
  241. translate(SSH2_MSG_SERVICE_REQUEST);
  242. translate(SSH2_MSG_SERVICE_ACCEPT);
  243. translate(SSH2_MSG_KEXINIT);
  244. translate(SSH2_MSG_NEWKEYS);
  245. translatek(SSH2_MSG_KEXDH_INIT, SSH2_PKTCTX_DHGROUP);
  246. translatek(SSH2_MSG_KEXDH_REPLY, SSH2_PKTCTX_DHGROUP);
  247. translatek(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD, SSH2_PKTCTX_DHGEX);
  248. translatek(SSH2_MSG_KEX_DH_GEX_REQUEST, SSH2_PKTCTX_DHGEX);
  249. translatek(SSH2_MSG_KEX_DH_GEX_GROUP, SSH2_PKTCTX_DHGEX);
  250. translatek(SSH2_MSG_KEX_DH_GEX_INIT, SSH2_PKTCTX_DHGEX);
  251. translatek(SSH2_MSG_KEX_DH_GEX_REPLY, SSH2_PKTCTX_DHGEX);
  252. translatek(SSH2_MSG_KEXRSA_PUBKEY, SSH2_PKTCTX_RSAKEX);
  253. translatek(SSH2_MSG_KEXRSA_SECRET, SSH2_PKTCTX_RSAKEX);
  254. translatek(SSH2_MSG_KEXRSA_DONE, SSH2_PKTCTX_RSAKEX);
  255. translatek(SSH2_MSG_KEX_ECDH_INIT, SSH2_PKTCTX_ECDHKEX);
  256. translatek(SSH2_MSG_KEX_ECDH_REPLY, SSH2_PKTCTX_ECDHKEX);
  257. translate(SSH2_MSG_USERAUTH_REQUEST);
  258. translate(SSH2_MSG_USERAUTH_FAILURE);
  259. translate(SSH2_MSG_USERAUTH_SUCCESS);
  260. translate(SSH2_MSG_USERAUTH_BANNER);
  261. translatea(SSH2_MSG_USERAUTH_PK_OK, SSH2_PKTCTX_PUBLICKEY);
  262. translatea(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, SSH2_PKTCTX_PASSWORD);
  263. translatea(SSH2_MSG_USERAUTH_INFO_REQUEST, SSH2_PKTCTX_KBDINTER);
  264. translatea(SSH2_MSG_USERAUTH_INFO_RESPONSE, SSH2_PKTCTX_KBDINTER);
  265. translate(SSH2_MSG_GLOBAL_REQUEST);
  266. translate(SSH2_MSG_REQUEST_SUCCESS);
  267. translate(SSH2_MSG_REQUEST_FAILURE);
  268. translate(SSH2_MSG_CHANNEL_OPEN);
  269. translate(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
  270. translate(SSH2_MSG_CHANNEL_OPEN_FAILURE);
  271. translate(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  272. translate(SSH2_MSG_CHANNEL_DATA);
  273. translate(SSH2_MSG_CHANNEL_EXTENDED_DATA);
  274. translate(SSH2_MSG_CHANNEL_EOF);
  275. translate(SSH2_MSG_CHANNEL_CLOSE);
  276. translate(SSH2_MSG_CHANNEL_REQUEST);
  277. translate(SSH2_MSG_CHANNEL_SUCCESS);
  278. translate(SSH2_MSG_CHANNEL_FAILURE);
  279. return "unknown";
  280. }
  281. #undef translate
  282. #undef translatec
  283. /* Enumeration values for fields in SSH-1 packets */
  284. enum {
  285. PKT_END, PKT_INT, PKT_CHAR, PKT_DATA, PKT_STR, PKT_BIGNUM,
  286. };
  287. /*
  288. * Coroutine mechanics for the sillier bits of the code. If these
  289. * macros look impenetrable to you, you might find it helpful to
  290. * read
  291. *
  292. * http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
  293. *
  294. * which explains the theory behind these macros.
  295. *
  296. * In particular, if you are getting `case expression not constant'
  297. * errors when building with MS Visual Studio, this is because MS's
  298. * Edit and Continue debugging feature causes their compiler to
  299. * violate ANSI C. To disable Edit and Continue debugging:
  300. *
  301. * - right-click ssh.c in the FileView
  302. * - click Settings
  303. * - select the C/C++ tab and the General category
  304. * - under `Debug info:', select anything _other_ than `Program
  305. * Database for Edit and Continue'.
  306. */
  307. #define crBegin(v) { int *crLine = &v; switch(v) { case 0:;
  308. #define crBeginState crBegin(s->crLine)
  309. #define crStateP(t, v) \
  310. struct t *s; \
  311. if (!(v)) { s = (v) = snew(struct t); s->crLine = 0; } \
  312. s = (v);
  313. #define crState(t) crStateP(t, ssh->t)
  314. #define crFinish(z) } *crLine = 0; return (z); }
  315. #define crFinishV } *crLine = 0; return; }
  316. #define crFinishFree(z) } sfree(s); return (z); }
  317. #define crFinishFreeV } sfree(s); return; }
  318. #define crReturn(z) \
  319. do {\
  320. *crLine =__LINE__; return (z); case __LINE__:;\
  321. } while (0)
  322. #define crReturnV \
  323. do {\
  324. *crLine=__LINE__; return; case __LINE__:;\
  325. } while (0)
  326. #define crStop(z) do{ *crLine = 0; return (z); }while(0)
  327. #define crStopV do{ *crLine = 0; return; }while(0)
  328. #define crWaitUntil(c) do { crReturn(0); } while (!(c))
  329. #define crWaitUntilV(c) do { crReturnV; } while (!(c))
  330. struct Packet;
  331. static struct Packet *ssh1_pkt_init(int pkt_type);
  332. static struct Packet *ssh2_pkt_init(int pkt_type);
  333. static void ssh_pkt_ensure(struct Packet *, int length);
  334. static void ssh_pkt_adddata(struct Packet *, const void *data, int len);
  335. static void ssh_pkt_addbyte(struct Packet *, unsigned char value);
  336. static void ssh2_pkt_addbool(struct Packet *, unsigned char value);
  337. static void ssh_pkt_adduint32(struct Packet *, unsigned long value);
  338. static void ssh_pkt_addstring_start(struct Packet *);
  339. static void ssh_pkt_addstring_str(struct Packet *, const char *data);
  340. static void ssh_pkt_addstring_data(struct Packet *, const char *data, int len);
  341. static void ssh_pkt_addstring(struct Packet *, const char *data);
  342. static unsigned char *ssh2_mpint_fmt(Bignum b, int *len);
  343. static void ssh1_pkt_addmp(struct Packet *, Bignum b);
  344. static void ssh2_pkt_addmp(struct Packet *, Bignum b);
  345. static int ssh2_pkt_construct(Ssh, struct Packet *);
  346. static void ssh2_pkt_send(Ssh, struct Packet *);
  347. static void ssh2_pkt_send_noqueue(Ssh, struct Packet *);
  348. static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
  349. struct Packet *pktin);
  350. static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
  351. struct Packet *pktin);
  352. static void ssh2_channel_check_close(struct ssh_channel *c);
  353. static void ssh_channel_destroy(struct ssh_channel *c);
  354. static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin);
  355. /*
  356. * Buffer management constants. There are several of these for
  357. * various different purposes:
  358. *
  359. * - SSH1_BUFFER_LIMIT is the amount of backlog that must build up
  360. * on a local data stream before we throttle the whole SSH
  361. * connection (in SSH-1 only). Throttling the whole connection is
  362. * pretty drastic so we set this high in the hope it won't
  363. * happen very often.
  364. *
  365. * - SSH_MAX_BACKLOG is the amount of backlog that must build up
  366. * on the SSH connection itself before we defensively throttle
  367. * _all_ local data streams. This is pretty drastic too (though
  368. * thankfully unlikely in SSH-2 since the window mechanism should
  369. * ensure that the server never has any need to throttle its end
  370. * of the connection), so we set this high as well.
  371. *
  372. * - OUR_V2_WINSIZE is the default window size we present on SSH-2
  373. * channels.
  374. *
  375. * - OUR_V2_BIGWIN is the window size we advertise for the only
  376. * channel in a simple connection. It must be <= INT_MAX.
  377. *
  378. * - OUR_V2_MAXPKT is the official "maximum packet size" we send
  379. * to the remote side. This actually has nothing to do with the
  380. * size of the _packet_, but is instead a limit on the amount
  381. * of data we're willing to receive in a single SSH2 channel
  382. * data message.
  383. *
  384. * - OUR_V2_PACKETLIMIT is actually the maximum size of SSH
  385. * _packet_ we're prepared to cope with. It must be a multiple
  386. * of the cipher block size, and must be at least 35000.
  387. */
  388. #define SSH1_BUFFER_LIMIT 32768
  389. #define SSH_MAX_BACKLOG 32768
  390. #define OUR_V2_WINSIZE 16384
  391. #define OUR_V2_BIGWIN 0x7fffffff
  392. #define OUR_V2_MAXPKT 0x4000UL
  393. #define OUR_V2_PACKETLIMIT 0x9000UL
  394. struct ssh_signkey_with_user_pref_id {
  395. const struct ssh_signkey *alg;
  396. int id;
  397. };
  398. const static struct ssh_signkey_with_user_pref_id hostkey_algs[] = {
  399. { &ssh_ecdsa_ed25519, HK_ED25519 },
  400. { &ssh_ecdsa_nistp256, HK_ECDSA },
  401. { &ssh_ecdsa_nistp384, HK_ECDSA },
  402. { &ssh_ecdsa_nistp521, HK_ECDSA },
  403. { &ssh_dss, HK_DSA },
  404. { &ssh_rsa, HK_RSA },
  405. };
  406. const static struct ssh_mac *const macs[] = {
  407. &ssh_hmac_sha256, &ssh_hmac_sha1, &ssh_hmac_sha1_96, &ssh_hmac_md5
  408. };
  409. const static struct ssh_mac *const buggymacs[] = {
  410. &ssh_hmac_sha1_buggy, &ssh_hmac_sha1_96_buggy, &ssh_hmac_md5
  411. };
  412. static void *ssh_comp_none_init(void)
  413. {
  414. return NULL;
  415. }
  416. static void ssh_comp_none_cleanup(void *handle)
  417. {
  418. }
  419. static int ssh_comp_none_block(void *handle, unsigned char *block, int len,
  420. unsigned char **outblock, int *outlen)
  421. {
  422. return 0;
  423. }
  424. static int ssh_comp_none_disable(void *handle)
  425. {
  426. return 0;
  427. }
  428. const static struct ssh_compress ssh_comp_none = {
  429. "none", NULL,
  430. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
  431. ssh_comp_none_init, ssh_comp_none_cleanup, ssh_comp_none_block,
  432. ssh_comp_none_disable, NULL
  433. };
  434. extern const struct ssh_compress ssh_zlib;
  435. const static struct ssh_compress *const compressions[] = {
  436. &ssh_zlib, &ssh_comp_none
  437. };
  438. enum { /* channel types */
  439. CHAN_MAINSESSION,
  440. CHAN_X11,
  441. CHAN_AGENT,
  442. CHAN_SOCKDATA,
  443. CHAN_SOCKDATA_DORMANT, /* one the remote hasn't confirmed */
  444. /*
  445. * CHAN_SHARING indicates a channel which is tracked here on
  446. * behalf of a connection-sharing downstream. We do almost nothing
  447. * with these channels ourselves: all messages relating to them
  448. * get thrown straight to sshshare.c and passed on almost
  449. * unmodified to downstream.
  450. */
  451. CHAN_SHARING,
  452. /*
  453. * CHAN_ZOMBIE is used to indicate a channel for which we've
  454. * already destroyed the local data source: for instance, if a
  455. * forwarded port experiences a socket error on the local side, we
  456. * immediately destroy its local socket and turn the SSH channel
  457. * into CHAN_ZOMBIE.
  458. */
  459. CHAN_ZOMBIE
  460. };
  461. typedef void (*handler_fn_t)(Ssh ssh, struct Packet *pktin);
  462. typedef void (*chandler_fn_t)(Ssh ssh, struct Packet *pktin, void *ctx);
  463. typedef void (*cchandler_fn_t)(struct ssh_channel *, struct Packet *, void *);
  464. /*
  465. * Each channel has a queue of outstanding CHANNEL_REQUESTS and their
  466. * handlers.
  467. */
  468. struct outstanding_channel_request {
  469. cchandler_fn_t handler;
  470. void *ctx;
  471. struct outstanding_channel_request *next;
  472. };
  473. /*
  474. * 2-3-4 tree storing channels.
  475. */
  476. struct ssh_channel {
  477. Ssh ssh; /* pointer back to main context */
  478. unsigned remoteid, localid;
  479. int type;
  480. /* True if we opened this channel but server hasn't confirmed. */
  481. int halfopen;
  482. /*
  483. * In SSH-1, this value contains four bits:
  484. *
  485. * 1 We have sent SSH1_MSG_CHANNEL_CLOSE.
  486. * 2 We have sent SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
  487. * 4 We have received SSH1_MSG_CHANNEL_CLOSE.
  488. * 8 We have received SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION.
  489. *
  490. * A channel is completely finished with when all four bits are set.
  491. *
  492. * In SSH-2, the four bits mean:
  493. *
  494. * 1 We have sent SSH2_MSG_CHANNEL_EOF.
  495. * 2 We have sent SSH2_MSG_CHANNEL_CLOSE.
  496. * 4 We have received SSH2_MSG_CHANNEL_EOF.
  497. * 8 We have received SSH2_MSG_CHANNEL_CLOSE.
  498. *
  499. * A channel is completely finished with when we have both sent
  500. * and received CLOSE.
  501. *
  502. * The symbolic constants below use the SSH-2 terminology, which
  503. * is a bit confusing in SSH-1, but we have to use _something_.
  504. */
  505. #define CLOSES_SENT_EOF 1
  506. #define CLOSES_SENT_CLOSE 2
  507. #define CLOSES_RCVD_EOF 4
  508. #define CLOSES_RCVD_CLOSE 8
  509. int closes;
  510. /*
  511. * This flag indicates that an EOF is pending on the outgoing side
  512. * of the channel: that is, wherever we're getting the data for
  513. * this channel has sent us some data followed by EOF. We can't
  514. * actually send the EOF until we've finished sending the data, so
  515. * we set this flag instead to remind us to do so once our buffer
  516. * is clear.
  517. */
  518. int pending_eof;
  519. /*
  520. * True if this channel is causing the underlying connection to be
  521. * throttled.
  522. */
  523. int throttling_conn;
  524. union {
  525. struct ssh2_data_channel {
  526. bufchain outbuffer;
  527. unsigned remwindow, remmaxpkt;
  528. /* locwindow is signed so we can cope with excess data. */
  529. int locwindow, locmaxwin;
  530. /*
  531. * remlocwin is the amount of local window that we think
  532. * the remote end had available to it after it sent the
  533. * last data packet or window adjust ack.
  534. */
  535. int remlocwin;
  536. /*
  537. * These store the list of channel requests that haven't
  538. * been acked.
  539. */
  540. struct outstanding_channel_request *chanreq_head, *chanreq_tail;
  541. enum { THROTTLED, UNTHROTTLING, UNTHROTTLED } throttle_state;
  542. } v2;
  543. } v;
  544. union {
  545. struct ssh_agent_channel {
  546. unsigned char *message;
  547. unsigned char msglen[4];
  548. unsigned lensofar, totallen;
  549. int outstanding_requests;
  550. } a;
  551. struct ssh_x11_channel {
  552. struct X11Connection *xconn;
  553. int initial;
  554. } x11;
  555. struct ssh_pfd_channel {
  556. struct PortForwarding *pf;
  557. } pfd;
  558. struct ssh_sharing_channel {
  559. void *ctx;
  560. } sharing;
  561. } u;
  562. };
  563. /*
  564. * 2-3-4 tree storing remote->local port forwardings. SSH-1 and SSH-2
  565. * use this structure in different ways, reflecting SSH-2's
  566. * altogether saner approach to port forwarding.
  567. *
  568. * In SSH-1, you arrange a remote forwarding by sending the server
  569. * the remote port number, and the local destination host:port.
  570. * When a connection comes in, the server sends you back that
  571. * host:port pair, and you connect to it. This is a ready-made
  572. * security hole if you're not on the ball: a malicious server
  573. * could send you back _any_ host:port pair, so if you trustingly
  574. * connect to the address it gives you then you've just opened the
  575. * entire inside of your corporate network just by connecting
  576. * through it to a dodgy SSH server. Hence, we must store a list of
  577. * host:port pairs we _are_ trying to forward to, and reject a
  578. * connection request from the server if it's not in the list.
  579. *
  580. * In SSH-2, each side of the connection minds its own business and
  581. * doesn't send unnecessary information to the other. You arrange a
  582. * remote forwarding by sending the server just the remote port
  583. * number. When a connection comes in, the server tells you which
  584. * of its ports was connected to; and _you_ have to remember what
  585. * local host:port pair went with that port number.
  586. *
  587. * Hence, in SSH-1 this structure is indexed by destination
  588. * host:port pair, whereas in SSH-2 it is indexed by source port.
  589. */
  590. struct ssh_portfwd; /* forward declaration */
  591. struct ssh_rportfwd {
  592. unsigned sport, dport;
  593. char *shost, *dhost;
  594. char *sportdesc;
  595. void *share_ctx;
  596. struct ssh_portfwd *pfrec;
  597. };
  598. static void free_rportfwd(struct ssh_rportfwd *pf)
  599. {
  600. if (pf) {
  601. sfree(pf->sportdesc);
  602. sfree(pf->shost);
  603. sfree(pf->dhost);
  604. sfree(pf);
  605. }
  606. }
  607. /*
  608. * Separately to the rportfwd tree (which is for looking up port
  609. * open requests from the server), a tree of _these_ structures is
  610. * used to keep track of all the currently open port forwardings,
  611. * so that we can reconfigure in mid-session if the user requests
  612. * it.
  613. */
  614. struct ssh_portfwd {
  615. enum { DESTROY, KEEP, CREATE } status;
  616. int type;
  617. unsigned sport, dport;
  618. char *saddr, *daddr;
  619. char *sserv, *dserv;
  620. struct ssh_rportfwd *remote;
  621. int addressfamily;
  622. struct PortListener *local;
  623. };
  624. #define free_portfwd(pf) ( \
  625. ((pf) ? (sfree((pf)->saddr), sfree((pf)->daddr), \
  626. sfree((pf)->sserv), sfree((pf)->dserv)) : (void)0 ), sfree(pf) )
  627. struct Packet {
  628. long length; /* length of packet: see below */
  629. long forcepad; /* SSH-2: force padding to at least this length */
  630. int type; /* only used for incoming packets */
  631. unsigned long sequence; /* SSH-2 incoming sequence number */
  632. unsigned char *data; /* allocated storage */
  633. unsigned char *body; /* offset of payload within `data' */
  634. long savedpos; /* dual-purpose saved packet position: see below */
  635. long maxlen; /* amount of storage allocated for `data' */
  636. long encrypted_len; /* for SSH-2 total-size counting */
  637. /*
  638. * A note on the 'length' and 'savedpos' fields above.
  639. *
  640. * Incoming packets are set up so that pkt->length is measured
  641. * relative to pkt->body, which itself points to a few bytes after
  642. * pkt->data (skipping some uninteresting header fields including
  643. * the packet type code). The ssh_pkt_get* functions all expect
  644. * this setup, and they also use pkt->savedpos to indicate how far
  645. * through the packet being decoded they've got - and that, too,
  646. * is an offset from pkt->body rather than pkt->data.
  647. *
  648. * During construction of an outgoing packet, however, pkt->length
  649. * is measured relative to the base pointer pkt->data, and
  650. * pkt->body is not really used for anything until the packet is
  651. * ready for sending. In this mode, pkt->savedpos is reused as a
  652. * temporary variable by the addstring functions, which write out
  653. * a string length field and then keep going back and updating it
  654. * as more data is appended to the subsequent string data field;
  655. * pkt->savedpos stores the offset (again relative to pkt->data)
  656. * of the start of the string data field.
  657. */
  658. /* Extra metadata used in SSH packet logging mode, allowing us to
  659. * log in the packet header line that the packet came from a
  660. * connection-sharing downstream and what if anything unusual was
  661. * done to it. The additional_log_text field is expected to be a
  662. * static string - it will not be freed. */
  663. unsigned downstream_id;
  664. const char *additional_log_text;
  665. };
  666. static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
  667. struct Packet *pktin);
  668. static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
  669. struct Packet *pktin);
  670. static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
  671. struct Packet *pktin);
  672. static void ssh1_protocol_setup(Ssh ssh);
  673. static void ssh2_protocol_setup(Ssh ssh);
  674. static void ssh2_bare_connection_protocol_setup(Ssh ssh);
  675. static void ssh_size(void *handle, int width, int height);
  676. static void ssh_special(void *handle, Telnet_Special);
  677. static int ssh2_try_send(struct ssh_channel *c);
  678. static int ssh_send_channel_data(struct ssh_channel *c,
  679. const char *buf, int len);
  680. static void ssh_throttle_all(Ssh ssh, int enable, int bufsize);
  681. static void ssh2_set_window(struct ssh_channel *c, int newwin);
  682. static int ssh_sendbuffer(void *handle);
  683. static int ssh_do_close(Ssh ssh, int notify_exit);
  684. static unsigned long ssh_pkt_getuint32(struct Packet *pkt);
  685. static int ssh2_pkt_getbool(struct Packet *pkt);
  686. static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length);
  687. static void ssh2_timer(void *ctx, unsigned long now);
  688. static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
  689. struct Packet *pktin);
  690. static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin);
  691. struct rdpkt1_state_tag {
  692. long len, pad, biglen, to_read;
  693. unsigned long realcrc, gotcrc;
  694. unsigned char *p;
  695. int i;
  696. int chunk;
  697. struct Packet *pktin;
  698. };
  699. struct rdpkt2_state_tag {
  700. long len, pad, payload, packetlen, maclen;
  701. int i;
  702. int cipherblk;
  703. unsigned long incoming_sequence;
  704. struct Packet *pktin;
  705. };
  706. struct rdpkt2_bare_state_tag {
  707. char length[4];
  708. long packetlen;
  709. int i;
  710. unsigned long incoming_sequence;
  711. struct Packet *pktin;
  712. };
  713. struct queued_handler;
  714. struct queued_handler {
  715. int msg1, msg2;
  716. chandler_fn_t handler;
  717. void *ctx;
  718. struct queued_handler *next;
  719. };
  720. struct ssh_tag {
  721. const struct plug_function_table *fn;
  722. /* the above field _must_ be first in the structure */
  723. char *v_c, *v_s;
  724. void *exhash;
  725. Socket s;
  726. void *ldisc;
  727. void *logctx;
  728. unsigned char session_key[32];
  729. int v1_compressing;
  730. int v1_remote_protoflags;
  731. int v1_local_protoflags;
  732. int agentfwd_enabled;
  733. int X11_fwd_enabled;
  734. int remote_bugs;
  735. const struct ssh_cipher *cipher;
  736. void *v1_cipher_ctx;
  737. void *crcda_ctx;
  738. const struct ssh2_cipher *cscipher, *sccipher;
  739. void *cs_cipher_ctx, *sc_cipher_ctx;
  740. const struct ssh_mac *csmac, *scmac;
  741. int csmac_etm, scmac_etm;
  742. void *cs_mac_ctx, *sc_mac_ctx;
  743. const struct ssh_compress *cscomp, *sccomp;
  744. void *cs_comp_ctx, *sc_comp_ctx;
  745. const struct ssh_kex *kex;
  746. const struct ssh_signkey *hostkey;
  747. char *hostkey_str; /* string representation, for easy checking in rekeys */
  748. unsigned char v2_session_id[SSH2_KEX_MAX_HASH_LEN];
  749. int v2_session_id_len;
  750. void *kex_ctx;
  751. int bare_connection;
  752. int attempting_connshare;
  753. void *connshare;
  754. char *savedhost;
  755. int savedport;
  756. int send_ok;
  757. int echoing, editing;
  758. int session_started;
  759. void *frontend;
  760. int ospeed, ispeed; /* temporaries */
  761. int term_width, term_height;
  762. tree234 *channels; /* indexed by local id */
  763. struct ssh_channel *mainchan; /* primary session channel */
  764. int ncmode; /* is primary channel direct-tcpip? */
  765. int exitcode;
  766. int close_expected;
  767. int clean_exit;
  768. tree234 *rportfwds, *portfwds;
  769. enum {
  770. SSH_STATE_PREPACKET,
  771. SSH_STATE_BEFORE_SIZE,
  772. SSH_STATE_INTERMED,
  773. SSH_STATE_SESSION,
  774. SSH_STATE_CLOSED
  775. } state;
  776. int size_needed, eof_needed;
  777. int sent_console_eof;
  778. int got_pty; /* affects EOF behaviour on main channel */
  779. struct Packet **queue;
  780. int queuelen, queuesize;
  781. int queueing;
  782. unsigned char *deferred_send_data;
  783. int deferred_len, deferred_size;
  784. /*
  785. * Gross hack: pscp will try to start SFTP but fall back to
  786. * scp1 if that fails. This variable is the means by which
  787. * scp.c can reach into the SSH code and find out which one it
  788. * got.
  789. */
  790. int fallback_cmd;
  791. bufchain banner; /* accumulates banners during do_ssh2_authconn */
  792. Pkt_KCtx pkt_kctx;
  793. Pkt_ACtx pkt_actx;
  794. struct X11Display *x11disp;
  795. struct X11FakeAuth *x11auth;
  796. tree234 *x11authtree;
  797. int version;
  798. int conn_throttle_count;
  799. int overall_bufsize;
  800. int throttled_all;
  801. int v1_stdout_throttling;
  802. unsigned long v2_outgoing_sequence;
  803. int ssh1_rdpkt_crstate;
  804. int ssh2_rdpkt_crstate;
  805. int ssh2_bare_rdpkt_crstate;
  806. int ssh_gotdata_crstate;
  807. int do_ssh1_connection_crstate;
  808. void *do_ssh_init_state;
  809. void *do_ssh1_login_state;
  810. void *do_ssh2_transport_state;
  811. void *do_ssh2_authconn_state;
  812. void *do_ssh_connection_init_state;
  813. struct rdpkt1_state_tag rdpkt1_state;
  814. struct rdpkt2_state_tag rdpkt2_state;
  815. struct rdpkt2_bare_state_tag rdpkt2_bare_state;
  816. /* SSH-1 and SSH-2 use this for different things, but both use it */
  817. int protocol_initial_phase_done;
  818. void (*protocol) (Ssh ssh, const void *vin, int inlen,
  819. struct Packet *pkt);
  820. struct Packet *(*s_rdpkt) (Ssh ssh, const unsigned char **data,
  821. int *datalen);
  822. int (*do_ssh_init)(Ssh ssh, unsigned char c);
  823. /*
  824. * We maintain our own copy of a Conf structure here. That way,
  825. * when we're passed a new one for reconfiguration, we can check
  826. * the differences and potentially reconfigure port forwardings
  827. * etc in mid-session.
  828. */
  829. Conf *conf;
  830. /*
  831. * Values cached out of conf so as to avoid the tree234 lookup
  832. * cost every time they're used.
  833. */
  834. int logomitdata;
  835. /*
  836. * Dynamically allocated username string created during SSH
  837. * login. Stored in here rather than in the coroutine state so
  838. * that it'll be reliably freed if we shut down the SSH session
  839. * at some unexpected moment.
  840. */
  841. char *username;
  842. /*
  843. * Used to transfer data back from async callbacks.
  844. */
  845. void *agent_response;
  846. int agent_response_len;
  847. int user_response;
  848. /*
  849. * The SSH connection can be set as `frozen', meaning we are
  850. * not currently accepting incoming data from the network. This
  851. * is slightly more serious than setting the _socket_ as
  852. * frozen, because we may already have had data passed to us
  853. * from the network which we need to delay processing until
  854. * after the freeze is lifted, so we also need a bufchain to
  855. * store that data.
  856. */
  857. int frozen;
  858. bufchain queued_incoming_data;
  859. /*
  860. * Dispatch table for packet types that we may have to deal
  861. * with at any time.
  862. */
  863. handler_fn_t packet_dispatch[256];
  864. /*
  865. * Queues of one-off handler functions for success/failure
  866. * indications from a request.
  867. */
  868. struct queued_handler *qhead, *qtail;
  869. handler_fn_t q_saved_handler1, q_saved_handler2;
  870. /*
  871. * This module deals with sending keepalives.
  872. */
  873. Pinger pinger;
  874. /*
  875. * Track incoming and outgoing data sizes and time, for
  876. * size-based rekeys.
  877. */
  878. unsigned long incoming_data_size, outgoing_data_size, deferred_data_size;
  879. unsigned long max_data_size;
  880. int kex_in_progress;
  881. unsigned long next_rekey, last_rekey;
  882. const char *deferred_rekey_reason;
  883. /*
  884. * Fully qualified host name, which we need if doing GSSAPI.
  885. */
  886. char *fullhostname;
  887. #ifndef NO_GSSAPI
  888. /*
  889. * GSSAPI libraries for this session.
  890. */
  891. struct ssh_gss_liblist *gsslibs;
  892. #endif
  893. /*
  894. * The last list returned from get_specials.
  895. */
  896. struct telnet_special *specials;
  897. /*
  898. * List of host key algorithms for which we _don't_ have a stored
  899. * host key. These are indices into the main hostkey_algs[] array
  900. */
  901. int uncert_hostkeys[lenof(hostkey_algs)];
  902. int n_uncert_hostkeys;
  903. /*
  904. * Flag indicating that the current rekey is intended to finish
  905. * with a newly cross-certified host key.
  906. */
  907. int cross_certifying;
  908. };
  909. #define logevent(s) logevent(ssh->frontend, s)
  910. /* logevent, only printf-formatted. */
  911. static void logeventf(Ssh ssh, const char *fmt, ...)
  912. {
  913. va_list ap;
  914. char *buf;
  915. va_start(ap, fmt);
  916. buf = dupvprintf(fmt, ap);
  917. va_end(ap);
  918. logevent(buf);
  919. sfree(buf);
  920. }
  921. static void bomb_out(Ssh ssh, char *text)
  922. {
  923. ssh_do_close(ssh, FALSE);
  924. logevent(text);
  925. connection_fatal(ssh->frontend, "%s", text);
  926. sfree(text);
  927. }
  928. #define bombout(msg) bomb_out(ssh, dupprintf msg)
  929. /* Helper function for common bits of parsing ttymodes. */
  930. static void parse_ttymodes(Ssh ssh,
  931. void (*do_mode)(void *data,
  932. const struct ssh_ttymode *mode,
  933. char *val),
  934. void *data)
  935. {
  936. int i;
  937. const struct ssh_ttymode *mode;
  938. char *val;
  939. char default_val[2];
  940. strcpy(default_val, "A");
  941. for (i = 0; i < lenof(ssh_ttymodes); i++) {
  942. mode = ssh_ttymodes + i;
  943. val = conf_get_str_str_opt(ssh->conf, CONF_ttymodes, mode->mode);
  944. if (!val)
  945. val = default_val;
  946. /*
  947. * val[0] is either 'V', indicating that an explicit value
  948. * follows it, or 'A' indicating that we should pass the
  949. * value through from the local environment via get_ttymode.
  950. */
  951. if (val[0] == 'A') {
  952. val = get_ttymode(ssh->frontend, mode->mode);
  953. if (val) {
  954. do_mode(data, mode, val);
  955. sfree(val);
  956. }
  957. } else
  958. do_mode(data, mode, val + 1); /* skip the 'V' */
  959. }
  960. }
  961. static int ssh_channelcmp(void *av, void *bv)
  962. {
  963. struct ssh_channel *a = (struct ssh_channel *) av;
  964. struct ssh_channel *b = (struct ssh_channel *) bv;
  965. if (a->localid < b->localid)
  966. return -1;
  967. if (a->localid > b->localid)
  968. return +1;
  969. return 0;
  970. }
  971. static int ssh_channelfind(void *av, void *bv)
  972. {
  973. unsigned *a = (unsigned *) av;
  974. struct ssh_channel *b = (struct ssh_channel *) bv;
  975. if (*a < b->localid)
  976. return -1;
  977. if (*a > b->localid)
  978. return +1;
  979. return 0;
  980. }
  981. static int ssh_rportcmp_ssh1(void *av, void *bv)
  982. {
  983. struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
  984. struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
  985. int i;
  986. if ( (i = strcmp(a->dhost, b->dhost)) != 0)
  987. return i < 0 ? -1 : +1;
  988. if (a->dport > b->dport)
  989. return +1;
  990. if (a->dport < b->dport)
  991. return -1;
  992. return 0;
  993. }
  994. static int ssh_rportcmp_ssh2(void *av, void *bv)
  995. {
  996. struct ssh_rportfwd *a = (struct ssh_rportfwd *) av;
  997. struct ssh_rportfwd *b = (struct ssh_rportfwd *) bv;
  998. int i;
  999. if ( (i = strcmp(a->shost, b->shost)) != 0)
  1000. return i < 0 ? -1 : +1;
  1001. if (a->sport > b->sport)
  1002. return +1;
  1003. if (a->sport < b->sport)
  1004. return -1;
  1005. return 0;
  1006. }
  1007. /*
  1008. * Special form of strcmp which can cope with NULL inputs. NULL is
  1009. * defined to sort before even the empty string.
  1010. */
  1011. static int nullstrcmp(const char *a, const char *b)
  1012. {
  1013. if (a == NULL && b == NULL)
  1014. return 0;
  1015. if (a == NULL)
  1016. return -1;
  1017. if (b == NULL)
  1018. return +1;
  1019. return strcmp(a, b);
  1020. }
  1021. static int ssh_portcmp(void *av, void *bv)
  1022. {
  1023. struct ssh_portfwd *a = (struct ssh_portfwd *) av;
  1024. struct ssh_portfwd *b = (struct ssh_portfwd *) bv;
  1025. int i;
  1026. if (a->type > b->type)
  1027. return +1;
  1028. if (a->type < b->type)
  1029. return -1;
  1030. if (a->addressfamily > b->addressfamily)
  1031. return +1;
  1032. if (a->addressfamily < b->addressfamily)
  1033. return -1;
  1034. if ( (i = nullstrcmp(a->saddr, b->saddr)) != 0)
  1035. return i < 0 ? -1 : +1;
  1036. if (a->sport > b->sport)
  1037. return +1;
  1038. if (a->sport < b->sport)
  1039. return -1;
  1040. if (a->type != 'D') {
  1041. if ( (i = nullstrcmp(a->daddr, b->daddr)) != 0)
  1042. return i < 0 ? -1 : +1;
  1043. if (a->dport > b->dport)
  1044. return +1;
  1045. if (a->dport < b->dport)
  1046. return -1;
  1047. }
  1048. return 0;
  1049. }
  1050. static int alloc_channel_id(Ssh ssh)
  1051. {
  1052. const unsigned CHANNEL_NUMBER_OFFSET = 256;
  1053. unsigned low, high, mid;
  1054. int tsize;
  1055. struct ssh_channel *c;
  1056. /*
  1057. * First-fit allocation of channel numbers: always pick the
  1058. * lowest unused one. To do this, binary-search using the
  1059. * counted B-tree to find the largest channel ID which is in a
  1060. * contiguous sequence from the beginning. (Precisely
  1061. * everything in that sequence must have ID equal to its tree
  1062. * index plus CHANNEL_NUMBER_OFFSET.)
  1063. */
  1064. tsize = count234(ssh->channels);
  1065. low = -1;
  1066. high = tsize;
  1067. while (high - low > 1) {
  1068. mid = (high + low) / 2;
  1069. c = index234(ssh->channels, mid);
  1070. if (c->localid == mid + CHANNEL_NUMBER_OFFSET)
  1071. low = mid; /* this one is fine */
  1072. else
  1073. high = mid; /* this one is past it */
  1074. }
  1075. /*
  1076. * Now low points to either -1, or the tree index of the
  1077. * largest ID in the initial sequence.
  1078. */
  1079. {
  1080. unsigned i = low + 1 + CHANNEL_NUMBER_OFFSET;
  1081. assert(NULL == find234(ssh->channels, &i, ssh_channelfind));
  1082. }
  1083. return low + 1 + CHANNEL_NUMBER_OFFSET;
  1084. }
  1085. static void c_write_stderr(int trusted, const char *buf, int len)
  1086. {
  1087. int i;
  1088. for (i = 0; i < len; i++)
  1089. if (buf[i] != '\r' && (trusted || buf[i] == '\n' || (buf[i] & 0x60)))
  1090. fputc(buf[i], stderr);
  1091. }
  1092. static void c_write(Ssh ssh, const char *buf, int len)
  1093. {
  1094. if (flags & FLAG_STDERR)
  1095. c_write_stderr(1, buf, len);
  1096. else
  1097. from_backend(ssh->frontend, 1, buf, len);
  1098. }
  1099. static void c_write_untrusted(Ssh ssh, const char *buf, int len)
  1100. {
  1101. if (flags & FLAG_STDERR)
  1102. c_write_stderr(0, buf, len);
  1103. else
  1104. from_backend_untrusted(ssh->frontend, buf, len);
  1105. }
  1106. static void c_write_str(Ssh ssh, const char *buf)
  1107. {
  1108. c_write(ssh, buf, strlen(buf));
  1109. }
  1110. static void ssh_free_packet(struct Packet *pkt)
  1111. {
  1112. sfree(pkt->data);
  1113. sfree(pkt);
  1114. }
  1115. static struct Packet *ssh_new_packet(void)
  1116. {
  1117. struct Packet *pkt = snew(struct Packet);
  1118. pkt->body = pkt->data = NULL;
  1119. pkt->maxlen = 0;
  1120. return pkt;
  1121. }
  1122. static void ssh1_log_incoming_packet(Ssh ssh, struct Packet *pkt)
  1123. {
  1124. int nblanks = 0;
  1125. struct logblank_t blanks[4];
  1126. char *str;
  1127. int slen;
  1128. pkt->savedpos = 0;
  1129. if (ssh->logomitdata &&
  1130. (pkt->type == SSH1_SMSG_STDOUT_DATA ||
  1131. pkt->type == SSH1_SMSG_STDERR_DATA ||
  1132. pkt->type == SSH1_MSG_CHANNEL_DATA)) {
  1133. /* "Session data" packets - omit the data string. */
  1134. if (pkt->type == SSH1_MSG_CHANNEL_DATA)
  1135. ssh_pkt_getuint32(pkt); /* skip channel id */
  1136. blanks[nblanks].offset = pkt->savedpos + 4;
  1137. blanks[nblanks].type = PKTLOG_OMIT;
  1138. ssh_pkt_getstring(pkt, &str, &slen);
  1139. if (str) {
  1140. blanks[nblanks].len = slen;
  1141. nblanks++;
  1142. }
  1143. }
  1144. log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
  1145. ssh1_pkt_type(pkt->type),
  1146. pkt->body, pkt->length, nblanks, blanks, NULL,
  1147. 0, NULL);
  1148. }
  1149. static void ssh1_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
  1150. {
  1151. int nblanks = 0;
  1152. struct logblank_t blanks[4];
  1153. char *str;
  1154. int slen;
  1155. /*
  1156. * For outgoing packets, pkt->length represents the length of the
  1157. * whole packet starting at pkt->data (including some header), and
  1158. * pkt->body refers to the point within that where the log-worthy
  1159. * payload begins. However, incoming packets expect pkt->length to
  1160. * represent only the payload length (that is, it's measured from
  1161. * pkt->body not from pkt->data). Temporarily adjust our outgoing
  1162. * packet to conform to the incoming-packet semantics, so that we
  1163. * can analyse it with the ssh_pkt_get functions.
  1164. */
  1165. pkt->length -= (pkt->body - pkt->data);
  1166. pkt->savedpos = 0;
  1167. if (ssh->logomitdata &&
  1168. (pkt->type == SSH1_CMSG_STDIN_DATA ||
  1169. pkt->type == SSH1_MSG_CHANNEL_DATA)) {
  1170. /* "Session data" packets - omit the data string. */
  1171. if (pkt->type == SSH1_MSG_CHANNEL_DATA)
  1172. ssh_pkt_getuint32(pkt); /* skip channel id */
  1173. blanks[nblanks].offset = pkt->savedpos + 4;
  1174. blanks[nblanks].type = PKTLOG_OMIT;
  1175. ssh_pkt_getstring(pkt, &str, &slen);
  1176. if (str) {
  1177. blanks[nblanks].len = slen;
  1178. nblanks++;
  1179. }
  1180. }
  1181. if ((pkt->type == SSH1_CMSG_AUTH_PASSWORD ||
  1182. pkt->type == SSH1_CMSG_AUTH_TIS_RESPONSE ||
  1183. pkt->type == SSH1_CMSG_AUTH_CCARD_RESPONSE) &&
  1184. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1185. /* If this is a password or similar packet, blank the password(s). */
  1186. blanks[nblanks].offset = 0;
  1187. blanks[nblanks].len = pkt->length;
  1188. blanks[nblanks].type = PKTLOG_BLANK;
  1189. nblanks++;
  1190. } else if (pkt->type == SSH1_CMSG_X11_REQUEST_FORWARDING &&
  1191. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1192. /*
  1193. * If this is an X forwarding request packet, blank the fake
  1194. * auth data.
  1195. *
  1196. * Note that while we blank the X authentication data here, we
  1197. * don't take any special action to blank the start of an X11
  1198. * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
  1199. * an X connection without having session blanking enabled is
  1200. * likely to leak your cookie into the log.
  1201. */
  1202. pkt->savedpos = 0;
  1203. ssh_pkt_getstring(pkt, &str, &slen);
  1204. blanks[nblanks].offset = pkt->savedpos;
  1205. blanks[nblanks].type = PKTLOG_BLANK;
  1206. ssh_pkt_getstring(pkt, &str, &slen);
  1207. if (str) {
  1208. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1209. nblanks++;
  1210. }
  1211. }
  1212. log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[12],
  1213. ssh1_pkt_type(pkt->data[12]),
  1214. pkt->body, pkt->length,
  1215. nblanks, blanks, NULL, 0, NULL);
  1216. /*
  1217. * Undo the above adjustment of pkt->length, to put the packet
  1218. * back in the state we found it.
  1219. */
  1220. pkt->length += (pkt->body - pkt->data);
  1221. }
  1222. /*
  1223. * Collect incoming data in the incoming packet buffer.
  1224. * Decipher and verify the packet when it is completely read.
  1225. * Drop SSH1_MSG_DEBUG and SSH1_MSG_IGNORE packets.
  1226. * Update the *data and *datalen variables.
  1227. * Return a Packet structure when a packet is completed.
  1228. */
  1229. static struct Packet *ssh1_rdpkt(Ssh ssh, const unsigned char **data,
  1230. int *datalen)
  1231. {
  1232. struct rdpkt1_state_tag *st = &ssh->rdpkt1_state;
  1233. crBegin(ssh->ssh1_rdpkt_crstate);
  1234. st->pktin = ssh_new_packet();
  1235. st->pktin->type = 0;
  1236. st->pktin->length = 0;
  1237. for (st->i = st->len = 0; st->i < 4; st->i++) {
  1238. while ((*datalen) == 0)
  1239. crReturn(NULL);
  1240. st->len = (st->len << 8) + **data;
  1241. (*data)++, (*datalen)--;
  1242. }
  1243. st->pad = 8 - (st->len % 8);
  1244. st->biglen = st->len + st->pad;
  1245. st->pktin->length = st->len - 5;
  1246. if (st->biglen < 0) {
  1247. bombout(("Extremely large packet length from server suggests"
  1248. " data stream corruption"));
  1249. ssh_free_packet(st->pktin);
  1250. crStop(NULL);
  1251. }
  1252. st->pktin->maxlen = st->biglen;
  1253. st->pktin->data = snewn(st->biglen + APIEXTRA, unsigned char);
  1254. st->to_read = st->biglen;
  1255. st->p = st->pktin->data;
  1256. while (st->to_read > 0) {
  1257. st->chunk = st->to_read;
  1258. while ((*datalen) == 0)
  1259. crReturn(NULL);
  1260. if (st->chunk > (*datalen))
  1261. st->chunk = (*datalen);
  1262. memcpy(st->p, *data, st->chunk);
  1263. *data += st->chunk;
  1264. *datalen -= st->chunk;
  1265. st->p += st->chunk;
  1266. st->to_read -= st->chunk;
  1267. }
  1268. if (ssh->cipher && detect_attack(ssh->crcda_ctx, st->pktin->data,
  1269. st->biglen, NULL)) {
  1270. bombout(("Network attack (CRC compensation) detected!"));
  1271. ssh_free_packet(st->pktin);
  1272. crStop(NULL);
  1273. }
  1274. if (ssh->cipher)
  1275. ssh->cipher->decrypt(ssh->v1_cipher_ctx, st->pktin->data, st->biglen);
  1276. st->realcrc = crc32_compute(st->pktin->data, st->biglen - 4);
  1277. st->gotcrc = GET_32BIT(st->pktin->data + st->biglen - 4);
  1278. if (st->gotcrc != st->realcrc) {
  1279. bombout(("Incorrect CRC received on packet"));
  1280. ssh_free_packet(st->pktin);
  1281. crStop(NULL);
  1282. }
  1283. st->pktin->body = st->pktin->data + st->pad + 1;
  1284. if (ssh->v1_compressing) {
  1285. unsigned char *decompblk;
  1286. int decomplen;
  1287. if (!zlib_decompress_block(ssh->sc_comp_ctx,
  1288. st->pktin->body - 1, st->pktin->length + 1,
  1289. &decompblk, &decomplen)) {
  1290. bombout(("Zlib decompression encountered invalid data"));
  1291. ssh_free_packet(st->pktin);
  1292. crStop(NULL);
  1293. }
  1294. if (st->pktin->maxlen < st->pad + decomplen) {
  1295. st->pktin->maxlen = st->pad + decomplen;
  1296. st->pktin->data = sresize(st->pktin->data,
  1297. st->pktin->maxlen + APIEXTRA,
  1298. unsigned char);
  1299. st->pktin->body = st->pktin->data + st->pad + 1;
  1300. }
  1301. memcpy(st->pktin->body - 1, decompblk, decomplen);
  1302. sfree(decompblk);
  1303. st->pktin->length = decomplen - 1;
  1304. }
  1305. st->pktin->type = st->pktin->body[-1];
  1306. /*
  1307. * Now pktin->body and pktin->length identify the semantic content
  1308. * of the packet, excluding the initial type byte.
  1309. */
  1310. if (ssh->logctx)
  1311. ssh1_log_incoming_packet(ssh, st->pktin);
  1312. st->pktin->savedpos = 0;
  1313. crFinish(st->pktin);
  1314. }
  1315. static void ssh2_log_incoming_packet(Ssh ssh, struct Packet *pkt)
  1316. {
  1317. int nblanks = 0;
  1318. struct logblank_t blanks[4];
  1319. char *str;
  1320. int slen;
  1321. pkt->savedpos = 0;
  1322. if (ssh->logomitdata &&
  1323. (pkt->type == SSH2_MSG_CHANNEL_DATA ||
  1324. pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
  1325. /* "Session data" packets - omit the data string. */
  1326. ssh_pkt_getuint32(pkt); /* skip channel id */
  1327. if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
  1328. ssh_pkt_getuint32(pkt); /* skip extended data type */
  1329. blanks[nblanks].offset = pkt->savedpos + 4;
  1330. blanks[nblanks].type = PKTLOG_OMIT;
  1331. ssh_pkt_getstring(pkt, &str, &slen);
  1332. if (str) {
  1333. blanks[nblanks].len = slen;
  1334. nblanks++;
  1335. }
  1336. }
  1337. log_packet(ssh->logctx, PKT_INCOMING, pkt->type,
  1338. ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->type),
  1339. pkt->body, pkt->length, nblanks, blanks, &pkt->sequence,
  1340. 0, NULL);
  1341. }
  1342. static void ssh2_log_outgoing_packet(Ssh ssh, struct Packet *pkt)
  1343. {
  1344. int nblanks = 0;
  1345. struct logblank_t blanks[4];
  1346. char *str;
  1347. int slen;
  1348. /*
  1349. * For outgoing packets, pkt->length represents the length of the
  1350. * whole packet starting at pkt->data (including some header), and
  1351. * pkt->body refers to the point within that where the log-worthy
  1352. * payload begins. However, incoming packets expect pkt->length to
  1353. * represent only the payload length (that is, it's measured from
  1354. * pkt->body not from pkt->data). Temporarily adjust our outgoing
  1355. * packet to conform to the incoming-packet semantics, so that we
  1356. * can analyse it with the ssh_pkt_get functions.
  1357. */
  1358. pkt->length -= (pkt->body - pkt->data);
  1359. pkt->savedpos = 0;
  1360. if (ssh->logomitdata &&
  1361. (pkt->type == SSH2_MSG_CHANNEL_DATA ||
  1362. pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)) {
  1363. /* "Session data" packets - omit the data string. */
  1364. ssh_pkt_getuint32(pkt); /* skip channel id */
  1365. if (pkt->type == SSH2_MSG_CHANNEL_EXTENDED_DATA)
  1366. ssh_pkt_getuint32(pkt); /* skip extended data type */
  1367. blanks[nblanks].offset = pkt->savedpos + 4;
  1368. blanks[nblanks].type = PKTLOG_OMIT;
  1369. ssh_pkt_getstring(pkt, &str, &slen);
  1370. if (str) {
  1371. blanks[nblanks].len = slen;
  1372. nblanks++;
  1373. }
  1374. }
  1375. if (pkt->type == SSH2_MSG_USERAUTH_REQUEST &&
  1376. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1377. /* If this is a password packet, blank the password(s). */
  1378. pkt->savedpos = 0;
  1379. ssh_pkt_getstring(pkt, &str, &slen);
  1380. ssh_pkt_getstring(pkt, &str, &slen);
  1381. ssh_pkt_getstring(pkt, &str, &slen);
  1382. if (slen == 8 && !memcmp(str, "password", 8)) {
  1383. ssh2_pkt_getbool(pkt);
  1384. /* Blank the password field. */
  1385. blanks[nblanks].offset = pkt->savedpos;
  1386. blanks[nblanks].type = PKTLOG_BLANK;
  1387. ssh_pkt_getstring(pkt, &str, &slen);
  1388. if (str) {
  1389. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1390. nblanks++;
  1391. /* If there's another password field beyond it (change of
  1392. * password), blank that too. */
  1393. ssh_pkt_getstring(pkt, &str, &slen);
  1394. if (str)
  1395. blanks[nblanks-1].len =
  1396. pkt->savedpos - blanks[nblanks].offset;
  1397. }
  1398. }
  1399. } else if (ssh->pkt_actx == SSH2_PKTCTX_KBDINTER &&
  1400. pkt->type == SSH2_MSG_USERAUTH_INFO_RESPONSE &&
  1401. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1402. /* If this is a keyboard-interactive response packet, blank
  1403. * the responses. */
  1404. pkt->savedpos = 0;
  1405. ssh_pkt_getuint32(pkt);
  1406. blanks[nblanks].offset = pkt->savedpos;
  1407. blanks[nblanks].type = PKTLOG_BLANK;
  1408. while (1) {
  1409. ssh_pkt_getstring(pkt, &str, &slen);
  1410. if (!str)
  1411. break;
  1412. }
  1413. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1414. nblanks++;
  1415. } else if (pkt->type == SSH2_MSG_CHANNEL_REQUEST &&
  1416. conf_get_int(ssh->conf, CONF_logomitpass)) {
  1417. /*
  1418. * If this is an X forwarding request packet, blank the fake
  1419. * auth data.
  1420. *
  1421. * Note that while we blank the X authentication data here, we
  1422. * don't take any special action to blank the start of an X11
  1423. * channel, so using MIT-MAGIC-COOKIE-1 and actually opening
  1424. * an X connection without having session blanking enabled is
  1425. * likely to leak your cookie into the log.
  1426. */
  1427. pkt->savedpos = 0;
  1428. ssh_pkt_getuint32(pkt);
  1429. ssh_pkt_getstring(pkt, &str, &slen);
  1430. if (slen == 7 && !memcmp(str, "x11-req", 0)) {
  1431. ssh2_pkt_getbool(pkt);
  1432. ssh2_pkt_getbool(pkt);
  1433. ssh_pkt_getstring(pkt, &str, &slen);
  1434. blanks[nblanks].offset = pkt->savedpos;
  1435. blanks[nblanks].type = PKTLOG_BLANK;
  1436. ssh_pkt_getstring(pkt, &str, &slen);
  1437. if (str) {
  1438. blanks[nblanks].len = pkt->savedpos - blanks[nblanks].offset;
  1439. nblanks++;
  1440. }
  1441. }
  1442. }
  1443. log_packet(ssh->logctx, PKT_OUTGOING, pkt->data[5],
  1444. ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx, pkt->data[5]),
  1445. pkt->body, pkt->length, nblanks, blanks,
  1446. &ssh->v2_outgoing_sequence,
  1447. pkt->downstream_id, pkt->additional_log_text);
  1448. /*
  1449. * Undo the above adjustment of pkt->length, to put the packet
  1450. * back in the state we found it.
  1451. */
  1452. pkt->length += (pkt->body - pkt->data);
  1453. }
  1454. static struct Packet *ssh2_rdpkt(Ssh ssh, const unsigned char **data,
  1455. int *datalen)
  1456. {
  1457. struct rdpkt2_state_tag *st = &ssh->rdpkt2_state;
  1458. crBegin(ssh->ssh2_rdpkt_crstate);
  1459. st->pktin = ssh_new_packet();
  1460. st->pktin->type = 0;
  1461. st->pktin->length = 0;
  1462. if (ssh->sccipher)
  1463. st->cipherblk = ssh->sccipher->blksize;
  1464. else
  1465. st->cipherblk = 8;
  1466. if (st->cipherblk < 8)
  1467. st->cipherblk = 8;
  1468. st->maclen = ssh->scmac ? ssh->scmac->len : 0;
  1469. if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_IS_CBC) &&
  1470. ssh->scmac && !ssh->scmac_etm) {
  1471. /*
  1472. * When dealing with a CBC-mode cipher, we want to avoid the
  1473. * possibility of an attacker's tweaking the ciphertext stream
  1474. * so as to cause us to feed the same block to the block
  1475. * cipher more than once and thus leak information
  1476. * (VU#958563). The way we do this is not to take any
  1477. * decisions on the basis of anything we've decrypted until
  1478. * we've verified it with a MAC. That includes the packet
  1479. * length, so we just read data and check the MAC repeatedly,
  1480. * and when the MAC passes, see if the length we've got is
  1481. * plausible.
  1482. *
  1483. * This defence is unnecessary in OpenSSH ETM mode, because
  1484. * the whole point of ETM mode is that the attacker can't
  1485. * tweak the ciphertext stream at all without the MAC
  1486. * detecting it before we decrypt anything.
  1487. */
  1488. /* May as well allocate the whole lot now. */
  1489. st->pktin->data = snewn(OUR_V2_PACKETLIMIT + st->maclen + APIEXTRA,
  1490. unsigned char);
  1491. /* Read an amount corresponding to the MAC. */
  1492. for (st->i = 0; st->i < st->maclen; st->i++) {
  1493. while ((*datalen) == 0)
  1494. crReturn(NULL);
  1495. st->pktin->data[st->i] = *(*data)++;
  1496. (*datalen)--;
  1497. }
  1498. st->packetlen = 0;
  1499. {
  1500. unsigned char seq[4];
  1501. ssh->scmac->start(ssh->sc_mac_ctx);
  1502. PUT_32BIT(seq, st->incoming_sequence);
  1503. ssh->scmac->bytes(ssh->sc_mac_ctx, seq, 4);
  1504. }
  1505. for (;;) { /* Once around this loop per cipher block. */
  1506. /* Read another cipher-block's worth, and tack it onto the end. */
  1507. for (st->i = 0; st->i < st->cipherblk; st->i++) {
  1508. while ((*datalen) == 0)
  1509. crReturn(NULL);
  1510. st->pktin->data[st->packetlen+st->maclen+st->i] = *(*data)++;
  1511. (*datalen)--;
  1512. }
  1513. /* Decrypt one more block (a little further back in the stream). */
  1514. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1515. st->pktin->data + st->packetlen,
  1516. st->cipherblk);
  1517. /* Feed that block to the MAC. */
  1518. ssh->scmac->bytes(ssh->sc_mac_ctx,
  1519. st->pktin->data + st->packetlen, st->cipherblk);
  1520. st->packetlen += st->cipherblk;
  1521. /* See if that gives us a valid packet. */
  1522. if (ssh->scmac->verresult(ssh->sc_mac_ctx,
  1523. st->pktin->data + st->packetlen) &&
  1524. ((st->len = toint(GET_32BIT(st->pktin->data))) ==
  1525. st->packetlen-4))
  1526. break;
  1527. if (st->packetlen >= OUR_V2_PACKETLIMIT) {
  1528. bombout(("No valid incoming packet found"));
  1529. ssh_free_packet(st->pktin);
  1530. crStop(NULL);
  1531. }
  1532. }
  1533. st->pktin->maxlen = st->packetlen + st->maclen;
  1534. st->pktin->data = sresize(st->pktin->data,
  1535. st->pktin->maxlen + APIEXTRA,
  1536. unsigned char);
  1537. } else if (ssh->scmac && ssh->scmac_etm) {
  1538. st->pktin->data = snewn(4 + APIEXTRA, unsigned char);
  1539. /*
  1540. * OpenSSH encrypt-then-MAC mode: the packet length is
  1541. * unencrypted, unless the cipher supports length encryption.
  1542. */
  1543. for (st->i = st->len = 0; st->i < 4; st->i++) {
  1544. while ((*datalen) == 0)
  1545. crReturn(NULL);
  1546. st->pktin->data[st->i] = *(*data)++;
  1547. (*datalen)--;
  1548. }
  1549. /* Cipher supports length decryption, so do it */
  1550. if (ssh->sccipher && (ssh->sccipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
  1551. /* Keep the packet the same though, so the MAC passes */
  1552. unsigned char len[4];
  1553. memcpy(len, st->pktin->data, 4);
  1554. ssh->sccipher->decrypt_length(ssh->sc_cipher_ctx, len, 4, st->incoming_sequence);
  1555. st->len = toint(GET_32BIT(len));
  1556. } else {
  1557. st->len = toint(GET_32BIT(st->pktin->data));
  1558. }
  1559. /*
  1560. * _Completely_ silly lengths should be stomped on before they
  1561. * do us any more damage.
  1562. */
  1563. if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
  1564. st->len % st->cipherblk != 0) {
  1565. bombout(("Incoming packet length field was garbled"));
  1566. ssh_free_packet(st->pktin);
  1567. crStop(NULL);
  1568. }
  1569. /*
  1570. * So now we can work out the total packet length.
  1571. */
  1572. st->packetlen = st->len + 4;
  1573. /*
  1574. * Allocate memory for the rest of the packet.
  1575. */
  1576. st->pktin->maxlen = st->packetlen + st->maclen;
  1577. st->pktin->data = sresize(st->pktin->data,
  1578. st->pktin->maxlen + APIEXTRA,
  1579. unsigned char);
  1580. /*
  1581. * Read the remainder of the packet.
  1582. */
  1583. for (st->i = 4; st->i < st->packetlen + st->maclen; st->i++) {
  1584. while ((*datalen) == 0)
  1585. crReturn(NULL);
  1586. st->pktin->data[st->i] = *(*data)++;
  1587. (*datalen)--;
  1588. }
  1589. /*
  1590. * Check the MAC.
  1591. */
  1592. if (ssh->scmac
  1593. && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
  1594. st->len + 4, st->incoming_sequence)) {
  1595. bombout(("Incorrect MAC received on packet"));
  1596. ssh_free_packet(st->pktin);
  1597. crStop(NULL);
  1598. }
  1599. /* Decrypt everything between the length field and the MAC. */
  1600. if (ssh->sccipher)
  1601. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1602. st->pktin->data + 4,
  1603. st->packetlen - 4);
  1604. } else {
  1605. st->pktin->data = snewn(st->cipherblk + APIEXTRA, unsigned char);
  1606. /*
  1607. * Acquire and decrypt the first block of the packet. This will
  1608. * contain the length and padding details.
  1609. */
  1610. for (st->i = st->len = 0; st->i < st->cipherblk; st->i++) {
  1611. while ((*datalen) == 0)
  1612. crReturn(NULL);
  1613. st->pktin->data[st->i] = *(*data)++;
  1614. (*datalen)--;
  1615. }
  1616. if (ssh->sccipher)
  1617. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1618. st->pktin->data, st->cipherblk);
  1619. /*
  1620. * Now get the length figure.
  1621. */
  1622. st->len = toint(GET_32BIT(st->pktin->data));
  1623. /*
  1624. * _Completely_ silly lengths should be stomped on before they
  1625. * do us any more damage.
  1626. */
  1627. if (st->len < 0 || st->len > OUR_V2_PACKETLIMIT ||
  1628. (st->len + 4) % st->cipherblk != 0) {
  1629. bombout(("Incoming packet was garbled on decryption"));
  1630. ssh_free_packet(st->pktin);
  1631. crStop(NULL);
  1632. }
  1633. /*
  1634. * So now we can work out the total packet length.
  1635. */
  1636. st->packetlen = st->len + 4;
  1637. /*
  1638. * Allocate memory for the rest of the packet.
  1639. */
  1640. st->pktin->maxlen = st->packetlen + st->maclen;
  1641. st->pktin->data = sresize(st->pktin->data,
  1642. st->pktin->maxlen + APIEXTRA,
  1643. unsigned char);
  1644. /*
  1645. * Read and decrypt the remainder of the packet.
  1646. */
  1647. for (st->i = st->cipherblk; st->i < st->packetlen + st->maclen;
  1648. st->i++) {
  1649. while ((*datalen) == 0)
  1650. crReturn(NULL);
  1651. st->pktin->data[st->i] = *(*data)++;
  1652. (*datalen)--;
  1653. }
  1654. /* Decrypt everything _except_ the MAC. */
  1655. if (ssh->sccipher)
  1656. ssh->sccipher->decrypt(ssh->sc_cipher_ctx,
  1657. st->pktin->data + st->cipherblk,
  1658. st->packetlen - st->cipherblk);
  1659. /*
  1660. * Check the MAC.
  1661. */
  1662. if (ssh->scmac
  1663. && !ssh->scmac->verify(ssh->sc_mac_ctx, st->pktin->data,
  1664. st->len + 4, st->incoming_sequence)) {
  1665. bombout(("Incorrect MAC received on packet"));
  1666. ssh_free_packet(st->pktin);
  1667. crStop(NULL);
  1668. }
  1669. }
  1670. /* Get and sanity-check the amount of random padding. */
  1671. st->pad = st->pktin->data[4];
  1672. if (st->pad < 4 || st->len - st->pad < 1) {
  1673. bombout(("Invalid padding length on received packet"));
  1674. ssh_free_packet(st->pktin);
  1675. crStop(NULL);
  1676. }
  1677. /*
  1678. * This enables us to deduce the payload length.
  1679. */
  1680. st->payload = st->len - st->pad - 1;
  1681. st->pktin->length = st->payload + 5;
  1682. st->pktin->encrypted_len = st->packetlen;
  1683. st->pktin->sequence = st->incoming_sequence++;
  1684. st->pktin->length = st->packetlen - st->pad;
  1685. assert(st->pktin->length >= 0);
  1686. /*
  1687. * Decompress packet payload.
  1688. */
  1689. {
  1690. unsigned char *newpayload;
  1691. int newlen;
  1692. if (ssh->sccomp &&
  1693. ssh->sccomp->decompress(ssh->sc_comp_ctx,
  1694. st->pktin->data + 5, st->pktin->length - 5,
  1695. &newpayload, &newlen)) {
  1696. if (st->pktin->maxlen < newlen + 5) {
  1697. st->pktin->maxlen = newlen + 5;
  1698. st->pktin->data = sresize(st->pktin->data,
  1699. st->pktin->maxlen + APIEXTRA,
  1700. unsigned char);
  1701. }
  1702. st->pktin->length = 5 + newlen;
  1703. memcpy(st->pktin->data + 5, newpayload, newlen);
  1704. sfree(newpayload);
  1705. }
  1706. }
  1707. /*
  1708. * RFC 4253 doesn't explicitly say that completely empty packets
  1709. * with no type byte are forbidden, so treat them as deserving
  1710. * an SSH_MSG_UNIMPLEMENTED.
  1711. */
  1712. if (st->pktin->length <= 5) { /* == 5 we hope, but robustness */
  1713. ssh2_msg_something_unimplemented(ssh, st->pktin);
  1714. crStop(NULL);
  1715. }
  1716. /*
  1717. * pktin->body and pktin->length should identify the semantic
  1718. * content of the packet, excluding the initial type byte.
  1719. */
  1720. st->pktin->type = st->pktin->data[5];
  1721. st->pktin->body = st->pktin->data + 6;
  1722. st->pktin->length -= 6;
  1723. assert(st->pktin->length >= 0); /* one last double-check */
  1724. if (ssh->logctx)
  1725. ssh2_log_incoming_packet(ssh, st->pktin);
  1726. st->pktin->savedpos = 0;
  1727. crFinish(st->pktin);
  1728. }
  1729. static struct Packet *ssh2_bare_connection_rdpkt(Ssh ssh,
  1730. const unsigned char **data,
  1731. int *datalen)
  1732. {
  1733. struct rdpkt2_bare_state_tag *st = &ssh->rdpkt2_bare_state;
  1734. crBegin(ssh->ssh2_bare_rdpkt_crstate);
  1735. /*
  1736. * Read the packet length field.
  1737. */
  1738. for (st->i = 0; st->i < 4; st->i++) {
  1739. while ((*datalen) == 0)
  1740. crReturn(NULL);
  1741. st->length[st->i] = *(*data)++;
  1742. (*datalen)--;
  1743. }
  1744. st->packetlen = toint(GET_32BIT_MSB_FIRST(st->length));
  1745. if (st->packetlen <= 0 || st->packetlen >= OUR_V2_PACKETLIMIT) {
  1746. bombout(("Invalid packet length received"));
  1747. crStop(NULL);
  1748. }
  1749. st->pktin = ssh_new_packet();
  1750. st->pktin->data = snewn(st->packetlen, unsigned char);
  1751. st->pktin->encrypted_len = st->packetlen;
  1752. st->pktin->sequence = st->incoming_sequence++;
  1753. /*
  1754. * Read the remainder of the packet.
  1755. */
  1756. for (st->i = 0; st->i < st->packetlen; st->i++) {
  1757. while ((*datalen) == 0)
  1758. crReturn(NULL);
  1759. st->pktin->data[st->i] = *(*data)++;
  1760. (*datalen)--;
  1761. }
  1762. /*
  1763. * pktin->body and pktin->length should identify the semantic
  1764. * content of the packet, excluding the initial type byte.
  1765. */
  1766. st->pktin->type = st->pktin->data[0];
  1767. st->pktin->body = st->pktin->data + 1;
  1768. st->pktin->length = st->packetlen - 1;
  1769. /*
  1770. * Log incoming packet, possibly omitting sensitive fields.
  1771. */
  1772. if (ssh->logctx)
  1773. ssh2_log_incoming_packet(ssh, st->pktin);
  1774. st->pktin->savedpos = 0;
  1775. crFinish(st->pktin);
  1776. }
  1777. static int s_wrpkt_prepare(Ssh ssh, struct Packet *pkt, int *offset_p)
  1778. {
  1779. int pad, biglen, i, pktoffs;
  1780. unsigned long crc;
  1781. #ifdef __SC__
  1782. /*
  1783. * XXX various versions of SC (including 8.8.4) screw up the
  1784. * register allocation in this function and use the same register
  1785. * (D6) for len and as a temporary, with predictable results. The
  1786. * following sledgehammer prevents this.
  1787. */
  1788. volatile
  1789. #endif
  1790. int len;
  1791. if (ssh->logctx)
  1792. ssh1_log_outgoing_packet(ssh, pkt);
  1793. if (ssh->v1_compressing) {
  1794. unsigned char *compblk;
  1795. int complen;
  1796. zlib_compress_block(ssh->cs_comp_ctx,
  1797. pkt->data + 12, pkt->length - 12,
  1798. &compblk, &complen);
  1799. ssh_pkt_ensure(pkt, complen + 2); /* just in case it's got bigger */
  1800. memcpy(pkt->data + 12, compblk, complen);
  1801. sfree(compblk);
  1802. pkt->length = complen + 12;
  1803. }
  1804. ssh_pkt_ensure(pkt, pkt->length + 4); /* space for CRC */
  1805. pkt->length += 4;
  1806. len = pkt->length - 4 - 8; /* len(type+data+CRC) */
  1807. pad = 8 - (len % 8);
  1808. pktoffs = 8 - pad;
  1809. biglen = len + pad; /* len(padding+type+data+CRC) */
  1810. for (i = pktoffs; i < 4+8; i++)
  1811. pkt->data[i] = random_byte();
  1812. crc = crc32_compute(pkt->data + pktoffs + 4, biglen - 4); /* all ex len */
  1813. PUT_32BIT(pkt->data + pktoffs + 4 + biglen - 4, crc);
  1814. PUT_32BIT(pkt->data + pktoffs, len);
  1815. if (ssh->cipher)
  1816. ssh->cipher->encrypt(ssh->v1_cipher_ctx,
  1817. pkt->data + pktoffs + 4, biglen);
  1818. if (offset_p) *offset_p = pktoffs;
  1819. return biglen + 4; /* len(length+padding+type+data+CRC) */
  1820. }
  1821. static int s_write(Ssh ssh, void *data, int len)
  1822. {
  1823. if (ssh->logctx)
  1824. log_packet(ssh->logctx, PKT_OUTGOING, -1, NULL, data, len,
  1825. 0, NULL, NULL, 0, NULL);
  1826. if (!ssh->s)
  1827. return 0;
  1828. return sk_write(ssh->s, (char *)data, len);
  1829. }
  1830. static void s_wrpkt(Ssh ssh, struct Packet *pkt)
  1831. {
  1832. int len, backlog, offset;
  1833. len = s_wrpkt_prepare(ssh, pkt, &offset);
  1834. backlog = s_write(ssh, pkt->data + offset, len);
  1835. if (backlog > SSH_MAX_BACKLOG)
  1836. ssh_throttle_all(ssh, 1, backlog);
  1837. ssh_free_packet(pkt);
  1838. }
  1839. static void s_wrpkt_defer(Ssh ssh, struct Packet *pkt)
  1840. {
  1841. int len, offset;
  1842. len = s_wrpkt_prepare(ssh, pkt, &offset);
  1843. if (ssh->deferred_len + len > ssh->deferred_size) {
  1844. ssh->deferred_size = ssh->deferred_len + len + 128;
  1845. ssh->deferred_send_data = sresize(ssh->deferred_send_data,
  1846. ssh->deferred_size,
  1847. unsigned char);
  1848. }
  1849. memcpy(ssh->deferred_send_data + ssh->deferred_len,
  1850. pkt->data + offset, len);
  1851. ssh->deferred_len += len;
  1852. ssh_free_packet(pkt);
  1853. }
  1854. /*
  1855. * Construct a SSH-1 packet with the specified contents.
  1856. * (This all-at-once interface used to be the only one, but now SSH-1
  1857. * packets can also be constructed incrementally.)
  1858. */
  1859. static struct Packet *construct_packet(Ssh ssh, int pkttype, va_list ap)
  1860. {
  1861. int argtype;
  1862. Bignum bn;
  1863. struct Packet *pkt;
  1864. pkt = ssh1_pkt_init(pkttype);
  1865. while ((argtype = va_arg(ap, int)) != PKT_END) {
  1866. unsigned char *argp, argchar;
  1867. char *sargp;
  1868. unsigned long argint;
  1869. int arglen;
  1870. switch (argtype) {
  1871. /* Actual fields in the packet */
  1872. case PKT_INT:
  1873. argint = va_arg(ap, int);
  1874. ssh_pkt_adduint32(pkt, argint);
  1875. break;
  1876. case PKT_CHAR:
  1877. argchar = (unsigned char) va_arg(ap, int);
  1878. ssh_pkt_addbyte(pkt, argchar);
  1879. break;
  1880. case PKT_DATA:
  1881. argp = va_arg(ap, unsigned char *);
  1882. arglen = va_arg(ap, int);
  1883. ssh_pkt_adddata(pkt, argp, arglen);
  1884. break;
  1885. case PKT_STR:
  1886. sargp = va_arg(ap, char *);
  1887. ssh_pkt_addstring(pkt, sargp);
  1888. break;
  1889. case PKT_BIGNUM:
  1890. bn = va_arg(ap, Bignum);
  1891. ssh1_pkt_addmp(pkt, bn);
  1892. break;
  1893. }
  1894. }
  1895. return pkt;
  1896. }
  1897. static void send_packet(Ssh ssh, int pkttype, ...)
  1898. {
  1899. struct Packet *pkt;
  1900. va_list ap;
  1901. va_start(ap, pkttype);
  1902. pkt = construct_packet(ssh, pkttype, ap);
  1903. va_end(ap);
  1904. s_wrpkt(ssh, pkt);
  1905. }
  1906. static void defer_packet(Ssh ssh, int pkttype, ...)
  1907. {
  1908. struct Packet *pkt;
  1909. va_list ap;
  1910. va_start(ap, pkttype);
  1911. pkt = construct_packet(ssh, pkttype, ap);
  1912. va_end(ap);
  1913. s_wrpkt_defer(ssh, pkt);
  1914. }
  1915. static int ssh_versioncmp(const char *a, const char *b)
  1916. {
  1917. char *ae, *be;
  1918. unsigned long av, bv;
  1919. av = strtoul(a, &ae, 10);
  1920. bv = strtoul(b, &be, 10);
  1921. if (av != bv)
  1922. return (av < bv ? -1 : +1);
  1923. if (*ae == '.')
  1924. ae++;
  1925. if (*be == '.')
  1926. be++;
  1927. av = strtoul(ae, &ae, 10);
  1928. bv = strtoul(be, &be, 10);
  1929. if (av != bv)
  1930. return (av < bv ? -1 : +1);
  1931. return 0;
  1932. }
  1933. /*
  1934. * Utility routines for putting an SSH-protocol `string' and
  1935. * `uint32' into a hash state.
  1936. */
  1937. static void hash_string(const struct ssh_hash *h, void *s, void *str, int len)
  1938. {
  1939. unsigned char lenblk[4];
  1940. PUT_32BIT(lenblk, len);
  1941. h->bytes(s, lenblk, 4);
  1942. h->bytes(s, str, len);
  1943. }
  1944. static void hash_uint32(const struct ssh_hash *h, void *s, unsigned i)
  1945. {
  1946. unsigned char intblk[4];
  1947. PUT_32BIT(intblk, i);
  1948. h->bytes(s, intblk, 4);
  1949. }
  1950. /*
  1951. * Packet construction functions. Mostly shared between SSH-1 and SSH-2.
  1952. */
  1953. static void ssh_pkt_ensure(struct Packet *pkt, int length)
  1954. {
  1955. if (pkt->maxlen < length) {
  1956. unsigned char *body = pkt->body;
  1957. int offset = body ? body - pkt->data : 0;
  1958. pkt->maxlen = length + 256;
  1959. pkt->data = sresize(pkt->data, pkt->maxlen + APIEXTRA, unsigned char);
  1960. if (body) pkt->body = pkt->data + offset;
  1961. }
  1962. }
  1963. static void ssh_pkt_adddata(struct Packet *pkt, const void *data, int len)
  1964. {
  1965. pkt->length += len;
  1966. ssh_pkt_ensure(pkt, pkt->length);
  1967. memcpy(pkt->data + pkt->length - len, data, len);
  1968. }
  1969. static void ssh_pkt_addbyte(struct Packet *pkt, unsigned char byte)
  1970. {
  1971. ssh_pkt_adddata(pkt, &byte, 1);
  1972. }
  1973. static void ssh2_pkt_addbool(struct Packet *pkt, unsigned char value)
  1974. {
  1975. ssh_pkt_adddata(pkt, &value, 1);
  1976. }
  1977. static void ssh_pkt_adduint32(struct Packet *pkt, unsigned long value)
  1978. {
  1979. unsigned char x[4];
  1980. PUT_32BIT(x, value);
  1981. ssh_pkt_adddata(pkt, x, 4);
  1982. }
  1983. static void ssh_pkt_addstring_start(struct Packet *pkt)
  1984. {
  1985. ssh_pkt_adduint32(pkt, 0);
  1986. pkt->savedpos = pkt->length;
  1987. }
  1988. static void ssh_pkt_addstring_data(struct Packet *pkt, const char *data,
  1989. int len)
  1990. {
  1991. ssh_pkt_adddata(pkt, data, len);
  1992. PUT_32BIT(pkt->data + pkt->savedpos - 4, pkt->length - pkt->savedpos);
  1993. }
  1994. static void ssh_pkt_addstring_str(struct Packet *pkt, const char *data)
  1995. {
  1996. ssh_pkt_addstring_data(pkt, data, strlen(data));
  1997. }
  1998. static void ssh_pkt_addstring(struct Packet *pkt, const char *data)
  1999. {
  2000. ssh_pkt_addstring_start(pkt);
  2001. ssh_pkt_addstring_str(pkt, data);
  2002. }
  2003. static void ssh1_pkt_addmp(struct Packet *pkt, Bignum b)
  2004. {
  2005. int len = ssh1_bignum_length(b);
  2006. unsigned char *data = snewn(len, unsigned char);
  2007. (void) ssh1_write_bignum(data, b);
  2008. ssh_pkt_adddata(pkt, data, len);
  2009. sfree(data);
  2010. }
  2011. static unsigned char *ssh2_mpint_fmt(Bignum b, int *len)
  2012. {
  2013. unsigned char *p;
  2014. int i, n = (bignum_bitcount(b) + 7) / 8;
  2015. p = snewn(n + 1, unsigned char);
  2016. p[0] = 0;
  2017. for (i = 1; i <= n; i++)
  2018. p[i] = bignum_byte(b, n - i);
  2019. i = 0;
  2020. while (i <= n && p[i] == 0 && (p[i + 1] & 0x80) == 0)
  2021. i++;
  2022. memmove(p, p + i, n + 1 - i);
  2023. *len = n + 1 - i;
  2024. return p;
  2025. }
  2026. static void ssh2_pkt_addmp(struct Packet *pkt, Bignum b)
  2027. {
  2028. unsigned char *p;
  2029. int len;
  2030. p = ssh2_mpint_fmt(b, &len);
  2031. ssh_pkt_addstring_start(pkt);
  2032. ssh_pkt_addstring_data(pkt, (char *)p, len);
  2033. sfree(p);
  2034. }
  2035. static struct Packet *ssh1_pkt_init(int pkt_type)
  2036. {
  2037. struct Packet *pkt = ssh_new_packet();
  2038. pkt->length = 4 + 8; /* space for length + max padding */
  2039. ssh_pkt_addbyte(pkt, pkt_type);
  2040. pkt->body = pkt->data + pkt->length;
  2041. pkt->type = pkt_type;
  2042. pkt->downstream_id = 0;
  2043. pkt->additional_log_text = NULL;
  2044. return pkt;
  2045. }
  2046. /* For legacy code (SSH-1 and -2 packet construction used to be separate) */
  2047. #define ssh2_pkt_ensure(pkt, length) ssh_pkt_ensure(pkt, length)
  2048. #define ssh2_pkt_adddata(pkt, data, len) ssh_pkt_adddata(pkt, data, len)
  2049. #define ssh2_pkt_addbyte(pkt, byte) ssh_pkt_addbyte(pkt, byte)
  2050. #define ssh2_pkt_adduint32(pkt, value) ssh_pkt_adduint32(pkt, value)
  2051. #define ssh2_pkt_addstring_start(pkt) ssh_pkt_addstring_start(pkt)
  2052. #define ssh2_pkt_addstring_str(pkt, data) ssh_pkt_addstring_str(pkt, data)
  2053. #define ssh2_pkt_addstring_data(pkt, data, len) ssh_pkt_addstring_data(pkt, data, len)
  2054. #define ssh2_pkt_addstring(pkt, data) ssh_pkt_addstring(pkt, data)
  2055. static struct Packet *ssh2_pkt_init(int pkt_type)
  2056. {
  2057. struct Packet *pkt = ssh_new_packet();
  2058. pkt->length = 5; /* space for packet length + padding length */
  2059. pkt->forcepad = 0;
  2060. pkt->type = pkt_type;
  2061. ssh_pkt_addbyte(pkt, (unsigned char) pkt_type);
  2062. pkt->body = pkt->data + pkt->length; /* after packet type */
  2063. pkt->downstream_id = 0;
  2064. pkt->additional_log_text = NULL;
  2065. return pkt;
  2066. }
  2067. /*
  2068. * Construct an SSH-2 final-form packet: compress it, encrypt it,
  2069. * put the MAC on it. Final packet, ready to be sent, is stored in
  2070. * pkt->data. Total length is returned.
  2071. */
  2072. static int ssh2_pkt_construct(Ssh ssh, struct Packet *pkt)
  2073. {
  2074. int cipherblk, maclen, padding, unencrypted_prefix, i;
  2075. if (ssh->logctx)
  2076. ssh2_log_outgoing_packet(ssh, pkt);
  2077. if (ssh->bare_connection) {
  2078. /*
  2079. * Trivial packet construction for the bare connection
  2080. * protocol.
  2081. */
  2082. PUT_32BIT(pkt->data + 1, pkt->length - 5);
  2083. pkt->body = pkt->data + 1;
  2084. ssh->v2_outgoing_sequence++; /* only for diagnostics, really */
  2085. return pkt->length - 1;
  2086. }
  2087. /*
  2088. * Compress packet payload.
  2089. */
  2090. {
  2091. unsigned char *newpayload;
  2092. int newlen;
  2093. if (ssh->cscomp &&
  2094. ssh->cscomp->compress(ssh->cs_comp_ctx, pkt->data + 5,
  2095. pkt->length - 5,
  2096. &newpayload, &newlen)) {
  2097. pkt->length = 5;
  2098. ssh2_pkt_adddata(pkt, newpayload, newlen);
  2099. sfree(newpayload);
  2100. }
  2101. }
  2102. /*
  2103. * Add padding. At least four bytes, and must also bring total
  2104. * length (minus MAC) up to a multiple of the block size.
  2105. * If pkt->forcepad is set, make sure the packet is at least that size
  2106. * after padding.
  2107. */
  2108. cipherblk = ssh->cscipher ? ssh->cscipher->blksize : 8; /* block size */
  2109. cipherblk = cipherblk < 8 ? 8 : cipherblk; /* or 8 if blksize < 8 */
  2110. padding = 4;
  2111. unencrypted_prefix = (ssh->csmac && ssh->csmac_etm) ? 4 : 0;
  2112. if (pkt->length + padding < pkt->forcepad)
  2113. padding = pkt->forcepad - pkt->length;
  2114. padding +=
  2115. (cipherblk - (pkt->length - unencrypted_prefix + padding) % cipherblk)
  2116. % cipherblk;
  2117. assert(padding <= 255);
  2118. maclen = ssh->csmac ? ssh->csmac->len : 0;
  2119. ssh2_pkt_ensure(pkt, pkt->length + padding + maclen);
  2120. pkt->data[4] = padding;
  2121. for (i = 0; i < padding; i++)
  2122. pkt->data[pkt->length + i] = random_byte();
  2123. PUT_32BIT(pkt->data, pkt->length + padding - 4);
  2124. /* Encrypt length if the scheme requires it */
  2125. if (ssh->cscipher && (ssh->cscipher->flags & SSH_CIPHER_SEPARATE_LENGTH)) {
  2126. ssh->cscipher->encrypt_length(ssh->cs_cipher_ctx, pkt->data, 4,
  2127. ssh->v2_outgoing_sequence);
  2128. }
  2129. if (ssh->csmac && ssh->csmac_etm) {
  2130. /*
  2131. * OpenSSH-defined encrypt-then-MAC protocol.
  2132. */
  2133. if (ssh->cscipher)
  2134. ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
  2135. pkt->data + 4, pkt->length + padding - 4);
  2136. ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
  2137. pkt->length + padding,
  2138. ssh->v2_outgoing_sequence);
  2139. } else {
  2140. /*
  2141. * SSH-2 standard protocol.
  2142. */
  2143. if (ssh->csmac)
  2144. ssh->csmac->generate(ssh->cs_mac_ctx, pkt->data,
  2145. pkt->length + padding,
  2146. ssh->v2_outgoing_sequence);
  2147. if (ssh->cscipher)
  2148. ssh->cscipher->encrypt(ssh->cs_cipher_ctx,
  2149. pkt->data, pkt->length + padding);
  2150. }
  2151. ssh->v2_outgoing_sequence++; /* whether or not we MACed */
  2152. pkt->encrypted_len = pkt->length + padding;
  2153. /* Ready-to-send packet starts at pkt->data. We return length. */
  2154. pkt->body = pkt->data;
  2155. return pkt->length + padding + maclen;
  2156. }
  2157. /*
  2158. * Routines called from the main SSH code to send packets. There
  2159. * are quite a few of these, because we have two separate
  2160. * mechanisms for delaying the sending of packets:
  2161. *
  2162. * - In order to send an IGNORE message and a password message in
  2163. * a single fixed-length blob, we require the ability to
  2164. * concatenate the encrypted forms of those two packets _into_ a
  2165. * single blob and then pass it to our <network.h> transport
  2166. * layer in one go. Hence, there's a deferment mechanism which
  2167. * works after packet encryption.
  2168. *
  2169. * - In order to avoid sending any connection-layer messages
  2170. * during repeat key exchange, we have to queue up any such
  2171. * outgoing messages _before_ they are encrypted (and in
  2172. * particular before they're allocated sequence numbers), and
  2173. * then send them once we've finished.
  2174. *
  2175. * I call these mechanisms `defer' and `queue' respectively, so as
  2176. * to distinguish them reasonably easily.
  2177. *
  2178. * The functions send_noqueue() and defer_noqueue() free the packet
  2179. * structure they are passed. Every outgoing packet goes through
  2180. * precisely one of these functions in its life; packets passed to
  2181. * ssh2_pkt_send() or ssh2_pkt_defer() either go straight to one of
  2182. * these or get queued, and then when the queue is later emptied
  2183. * the packets are all passed to defer_noqueue().
  2184. *
  2185. * When using a CBC-mode cipher, it's necessary to ensure that an
  2186. * attacker can't provide data to be encrypted using an IV that they
  2187. * know. We ensure this by prefixing each packet that might contain
  2188. * user data with an SSH_MSG_IGNORE. This is done using the deferral
  2189. * mechanism, so in this case send_noqueue() ends up redirecting to
  2190. * defer_noqueue(). If you don't like this inefficiency, don't use
  2191. * CBC.
  2192. */
  2193. static void ssh2_pkt_defer_noqueue(Ssh, struct Packet *, int);
  2194. static void ssh_pkt_defersend(Ssh);
  2195. /*
  2196. * Send an SSH-2 packet immediately, without queuing or deferring.
  2197. */
  2198. static void ssh2_pkt_send_noqueue(Ssh ssh, struct Packet *pkt)
  2199. {
  2200. int len;
  2201. int backlog;
  2202. if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC)) {
  2203. /* We need to send two packets, so use the deferral mechanism. */
  2204. ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
  2205. ssh_pkt_defersend(ssh);
  2206. return;
  2207. }
  2208. len = ssh2_pkt_construct(ssh, pkt);
  2209. backlog = s_write(ssh, pkt->body, len);
  2210. if (backlog > SSH_MAX_BACKLOG)
  2211. ssh_throttle_all(ssh, 1, backlog);
  2212. ssh->outgoing_data_size += pkt->encrypted_len;
  2213. if (!ssh->kex_in_progress &&
  2214. !ssh->bare_connection &&
  2215. ssh->max_data_size != 0 &&
  2216. ssh->outgoing_data_size > ssh->max_data_size)
  2217. do_ssh2_transport(ssh, "too much data sent", -1, NULL);
  2218. ssh_free_packet(pkt);
  2219. }
  2220. /*
  2221. * Defer an SSH-2 packet.
  2222. */
  2223. static void ssh2_pkt_defer_noqueue(Ssh ssh, struct Packet *pkt, int noignore)
  2224. {
  2225. int len;
  2226. if (ssh->cscipher != NULL && (ssh->cscipher->flags & SSH_CIPHER_IS_CBC) &&
  2227. ssh->deferred_len == 0 && !noignore &&
  2228. !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
  2229. /*
  2230. * Interpose an SSH_MSG_IGNORE to ensure that user data don't
  2231. * get encrypted with a known IV.
  2232. */
  2233. struct Packet *ipkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
  2234. ssh2_pkt_addstring_start(ipkt);
  2235. ssh2_pkt_defer_noqueue(ssh, ipkt, TRUE);
  2236. }
  2237. len = ssh2_pkt_construct(ssh, pkt);
  2238. if (ssh->deferred_len + len > ssh->deferred_size) {
  2239. ssh->deferred_size = ssh->deferred_len + len + 128;
  2240. ssh->deferred_send_data = sresize(ssh->deferred_send_data,
  2241. ssh->deferred_size,
  2242. unsigned char);
  2243. }
  2244. memcpy(ssh->deferred_send_data + ssh->deferred_len, pkt->body, len);
  2245. ssh->deferred_len += len;
  2246. ssh->deferred_data_size += pkt->encrypted_len;
  2247. ssh_free_packet(pkt);
  2248. }
  2249. /*
  2250. * Queue an SSH-2 packet.
  2251. */
  2252. static void ssh2_pkt_queue(Ssh ssh, struct Packet *pkt)
  2253. {
  2254. assert(ssh->queueing);
  2255. if (ssh->queuelen >= ssh->queuesize) {
  2256. ssh->queuesize = ssh->queuelen + 32;
  2257. ssh->queue = sresize(ssh->queue, ssh->queuesize, struct Packet *);
  2258. }
  2259. ssh->queue[ssh->queuelen++] = pkt;
  2260. }
  2261. /*
  2262. * Either queue or send a packet, depending on whether queueing is
  2263. * set.
  2264. */
  2265. static void ssh2_pkt_send(Ssh ssh, struct Packet *pkt)
  2266. {
  2267. if (ssh->queueing)
  2268. ssh2_pkt_queue(ssh, pkt);
  2269. else
  2270. ssh2_pkt_send_noqueue(ssh, pkt);
  2271. }
  2272. /*
  2273. * Either queue or defer a packet, depending on whether queueing is
  2274. * set.
  2275. */
  2276. static void ssh2_pkt_defer(Ssh ssh, struct Packet *pkt)
  2277. {
  2278. if (ssh->queueing)
  2279. ssh2_pkt_queue(ssh, pkt);
  2280. else
  2281. ssh2_pkt_defer_noqueue(ssh, pkt, FALSE);
  2282. }
  2283. /*
  2284. * Send the whole deferred data block constructed by
  2285. * ssh2_pkt_defer() or SSH-1's defer_packet().
  2286. *
  2287. * The expected use of the defer mechanism is that you call
  2288. * ssh2_pkt_defer() a few times, then call ssh_pkt_defersend(). If
  2289. * not currently queueing, this simply sets up deferred_send_data
  2290. * and then sends it. If we _are_ currently queueing, the calls to
  2291. * ssh2_pkt_defer() put the deferred packets on to the queue
  2292. * instead, and therefore ssh_pkt_defersend() has no deferred data
  2293. * to send. Hence, there's no need to make it conditional on
  2294. * ssh->queueing.
  2295. */
  2296. static void ssh_pkt_defersend(Ssh ssh)
  2297. {
  2298. int backlog;
  2299. backlog = s_write(ssh, ssh->deferred_send_data, ssh->deferred_len);
  2300. ssh->deferred_len = ssh->deferred_size = 0;
  2301. sfree(ssh->deferred_send_data);
  2302. ssh->deferred_send_data = NULL;
  2303. if (backlog > SSH_MAX_BACKLOG)
  2304. ssh_throttle_all(ssh, 1, backlog);
  2305. if (ssh->version == 2) {
  2306. ssh->outgoing_data_size += ssh->deferred_data_size;
  2307. ssh->deferred_data_size = 0;
  2308. if (!ssh->kex_in_progress &&
  2309. !ssh->bare_connection &&
  2310. ssh->max_data_size != 0 &&
  2311. ssh->outgoing_data_size > ssh->max_data_size)
  2312. do_ssh2_transport(ssh, "too much data sent", -1, NULL);
  2313. }
  2314. }
  2315. /*
  2316. * Send a packet whose length needs to be disguised (typically
  2317. * passwords or keyboard-interactive responses).
  2318. */
  2319. static void ssh2_pkt_send_with_padding(Ssh ssh, struct Packet *pkt,
  2320. int padsize)
  2321. {
  2322. #if 0
  2323. if (0) {
  2324. /*
  2325. * The simplest way to do this is to adjust the
  2326. * variable-length padding field in the outgoing packet.
  2327. *
  2328. * Currently compiled out, because some Cisco SSH servers
  2329. * don't like excessively padded packets (bah, why's it
  2330. * always Cisco?)
  2331. */
  2332. pkt->forcepad = padsize;
  2333. ssh2_pkt_send(ssh, pkt);
  2334. } else
  2335. #endif
  2336. {
  2337. /*
  2338. * If we can't do that, however, an alternative approach is
  2339. * to use the pkt_defer mechanism to bundle the packet
  2340. * tightly together with an SSH_MSG_IGNORE such that their
  2341. * combined length is a constant. So first we construct the
  2342. * final form of this packet and defer its sending.
  2343. */
  2344. ssh2_pkt_defer(ssh, pkt);
  2345. /*
  2346. * Now construct an SSH_MSG_IGNORE which includes a string
  2347. * that's an exact multiple of the cipher block size. (If
  2348. * the cipher is NULL so that the block size is
  2349. * unavailable, we don't do this trick at all, because we
  2350. * gain nothing by it.)
  2351. */
  2352. if (ssh->cscipher &&
  2353. !(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
  2354. int stringlen, i;
  2355. stringlen = (256 - ssh->deferred_len);
  2356. stringlen += ssh->cscipher->blksize - 1;
  2357. stringlen -= (stringlen % ssh->cscipher->blksize);
  2358. if (ssh->cscomp) {
  2359. /*
  2360. * Temporarily disable actual compression, so we
  2361. * can guarantee to get this string exactly the
  2362. * length we want it. The compression-disabling
  2363. * routine should return an integer indicating how
  2364. * many bytes we should adjust our string length
  2365. * by.
  2366. */
  2367. stringlen -=
  2368. ssh->cscomp->disable_compression(ssh->cs_comp_ctx);
  2369. }
  2370. pkt = ssh2_pkt_init(SSH2_MSG_IGNORE);
  2371. ssh2_pkt_addstring_start(pkt);
  2372. for (i = 0; i < stringlen; i++) {
  2373. char c = (char) random_byte();
  2374. ssh2_pkt_addstring_data(pkt, &c, 1);
  2375. }
  2376. ssh2_pkt_defer(ssh, pkt);
  2377. }
  2378. ssh_pkt_defersend(ssh);
  2379. }
  2380. }
  2381. /*
  2382. * Send all queued SSH-2 packets. We send them by means of
  2383. * ssh2_pkt_defer_noqueue(), in case they included a pair of
  2384. * packets that needed to be lumped together.
  2385. */
  2386. static void ssh2_pkt_queuesend(Ssh ssh)
  2387. {
  2388. int i;
  2389. assert(!ssh->queueing);
  2390. for (i = 0; i < ssh->queuelen; i++)
  2391. ssh2_pkt_defer_noqueue(ssh, ssh->queue[i], FALSE);
  2392. ssh->queuelen = 0;
  2393. ssh_pkt_defersend(ssh);
  2394. }
  2395. #if 0
  2396. void bndebug(char *string, Bignum b)
  2397. {
  2398. unsigned char *p;
  2399. int i, len;
  2400. p = ssh2_mpint_fmt(b, &len);
  2401. debug(("%s", string));
  2402. for (i = 0; i < len; i++)
  2403. debug((" %02x", p[i]));
  2404. debug(("\n"));
  2405. sfree(p);
  2406. }
  2407. #endif
  2408. static void hash_mpint(const struct ssh_hash *h, void *s, Bignum b)
  2409. {
  2410. unsigned char *p;
  2411. int len;
  2412. p = ssh2_mpint_fmt(b, &len);
  2413. hash_string(h, s, p, len);
  2414. sfree(p);
  2415. }
  2416. /*
  2417. * Packet decode functions for both SSH-1 and SSH-2.
  2418. */
  2419. static unsigned long ssh_pkt_getuint32(struct Packet *pkt)
  2420. {
  2421. unsigned long value;
  2422. if (pkt->length - pkt->savedpos < 4)
  2423. return 0; /* arrgh, no way to decline (FIXME?) */
  2424. value = GET_32BIT(pkt->body + pkt->savedpos);
  2425. pkt->savedpos += 4;
  2426. return value;
  2427. }
  2428. static int ssh2_pkt_getbool(struct Packet *pkt)
  2429. {
  2430. unsigned long value;
  2431. if (pkt->length - pkt->savedpos < 1)
  2432. return 0; /* arrgh, no way to decline (FIXME?) */
  2433. value = pkt->body[pkt->savedpos] != 0;
  2434. pkt->savedpos++;
  2435. return value;
  2436. }
  2437. static void ssh_pkt_getstring(struct Packet *pkt, char **p, int *length)
  2438. {
  2439. int len;
  2440. *p = NULL;
  2441. *length = 0;
  2442. if (pkt->length - pkt->savedpos < 4)
  2443. return;
  2444. len = toint(GET_32BIT(pkt->body + pkt->savedpos));
  2445. if (len < 0)
  2446. return;
  2447. *length = len;
  2448. pkt->savedpos += 4;
  2449. if (pkt->length - pkt->savedpos < *length)
  2450. return;
  2451. *p = (char *)(pkt->body + pkt->savedpos);
  2452. pkt->savedpos += *length;
  2453. }
  2454. static void *ssh_pkt_getdata(struct Packet *pkt, int length)
  2455. {
  2456. if (pkt->length - pkt->savedpos < length)
  2457. return NULL;
  2458. pkt->savedpos += length;
  2459. return pkt->body + (pkt->savedpos - length);
  2460. }
  2461. static int ssh1_pkt_getrsakey(struct Packet *pkt, struct RSAKey *key,
  2462. const unsigned char **keystr)
  2463. {
  2464. int j;
  2465. j = makekey(pkt->body + pkt->savedpos,
  2466. pkt->length - pkt->savedpos,
  2467. key, keystr, 0);
  2468. if (j < 0)
  2469. return FALSE;
  2470. pkt->savedpos += j;
  2471. assert(pkt->savedpos < pkt->length);
  2472. return TRUE;
  2473. }
  2474. static Bignum ssh1_pkt_getmp(struct Packet *pkt)
  2475. {
  2476. int j;
  2477. Bignum b;
  2478. j = ssh1_read_bignum(pkt->body + pkt->savedpos,
  2479. pkt->length - pkt->savedpos, &b);
  2480. if (j < 0)
  2481. return NULL;
  2482. pkt->savedpos += j;
  2483. return b;
  2484. }
  2485. static Bignum ssh2_pkt_getmp(struct Packet *pkt)
  2486. {
  2487. char *p;
  2488. int length;
  2489. Bignum b;
  2490. ssh_pkt_getstring(pkt, &p, &length);
  2491. if (!p)
  2492. return NULL;
  2493. if (p[0] & 0x80)
  2494. return NULL;
  2495. b = bignum_from_bytes((unsigned char *)p, length);
  2496. return b;
  2497. }
  2498. /*
  2499. * Helper function to add an SSH-2 signature blob to a packet.
  2500. * Expects to be shown the public key blob as well as the signature
  2501. * blob. Normally works just like ssh2_pkt_addstring, but will
  2502. * fiddle with the signature packet if necessary for
  2503. * BUG_SSH2_RSA_PADDING.
  2504. */
  2505. static void ssh2_add_sigblob(Ssh ssh, struct Packet *pkt,
  2506. void *pkblob_v, int pkblob_len,
  2507. void *sigblob_v, int sigblob_len)
  2508. {
  2509. unsigned char *pkblob = (unsigned char *)pkblob_v;
  2510. unsigned char *sigblob = (unsigned char *)sigblob_v;
  2511. /* dmemdump(pkblob, pkblob_len); */
  2512. /* dmemdump(sigblob, sigblob_len); */
  2513. /*
  2514. * See if this is in fact an ssh-rsa signature and a buggy
  2515. * server; otherwise we can just do this the easy way.
  2516. */
  2517. if ((ssh->remote_bugs & BUG_SSH2_RSA_PADDING) && pkblob_len > 4+7+4 &&
  2518. (GET_32BIT(pkblob) == 7 && !memcmp(pkblob+4, "ssh-rsa", 7))) {
  2519. int pos, len, siglen;
  2520. /*
  2521. * Find the byte length of the modulus.
  2522. */
  2523. pos = 4+7; /* skip over "ssh-rsa" */
  2524. len = toint(GET_32BIT(pkblob+pos)); /* get length of exponent */
  2525. if (len < 0 || len > pkblob_len - pos - 4)
  2526. goto give_up;
  2527. pos += 4 + len; /* skip over exponent */
  2528. if (pkblob_len - pos < 4)
  2529. goto give_up;
  2530. len = toint(GET_32BIT(pkblob+pos)); /* find length of modulus */
  2531. if (len < 0 || len > pkblob_len - pos - 4)
  2532. goto give_up;
  2533. pos += 4; /* find modulus itself */
  2534. while (len > 0 && pkblob[pos] == 0)
  2535. len--, pos++;
  2536. /* debug(("modulus length is %d\n", len)); */
  2537. /*
  2538. * Now find the signature integer.
  2539. */
  2540. pos = 4+7; /* skip over "ssh-rsa" */
  2541. if (sigblob_len < pos+4)
  2542. goto give_up;
  2543. siglen = toint(GET_32BIT(sigblob+pos));
  2544. if (siglen != sigblob_len - pos - 4)
  2545. goto give_up;
  2546. /* debug(("signature length is %d\n", siglen)); */
  2547. if (len != siglen) {
  2548. unsigned char newlen[4];
  2549. ssh2_pkt_addstring_start(pkt);
  2550. ssh2_pkt_addstring_data(pkt, (char *)sigblob, pos);
  2551. /* dmemdump(sigblob, pos); */
  2552. pos += 4; /* point to start of actual sig */
  2553. PUT_32BIT(newlen, len);
  2554. ssh2_pkt_addstring_data(pkt, (char *)newlen, 4);
  2555. /* dmemdump(newlen, 4); */
  2556. newlen[0] = 0;
  2557. while (len-- > siglen) {
  2558. ssh2_pkt_addstring_data(pkt, (char *)newlen, 1);
  2559. /* dmemdump(newlen, 1); */
  2560. }
  2561. ssh2_pkt_addstring_data(pkt, (char *)(sigblob+pos), siglen);
  2562. /* dmemdump(sigblob+pos, siglen); */
  2563. return;
  2564. }
  2565. /* Otherwise fall through and do it the easy way. We also come
  2566. * here as a fallback if we discover above that the key blob
  2567. * is misformatted in some way. */
  2568. give_up:;
  2569. }
  2570. ssh2_pkt_addstring_start(pkt);
  2571. ssh2_pkt_addstring_data(pkt, (char *)sigblob, sigblob_len);
  2572. }
  2573. /*
  2574. * Examine the remote side's version string and compare it against
  2575. * a list of known buggy implementations.
  2576. */
  2577. static void ssh_detect_bugs(Ssh ssh, char *vstring)
  2578. {
  2579. char *imp; /* pointer to implementation part */
  2580. imp = vstring;
  2581. imp += strcspn(imp, "-");
  2582. if (*imp) imp++;
  2583. imp += strcspn(imp, "-");
  2584. if (*imp) imp++;
  2585. ssh->remote_bugs = 0;
  2586. /*
  2587. * General notes on server version strings:
  2588. * - Not all servers reporting "Cisco-1.25" have all the bugs listed
  2589. * here -- in particular, we've heard of one that's perfectly happy
  2590. * with SSH1_MSG_IGNOREs -- but this string never seems to change,
  2591. * so we can't distinguish them.
  2592. */
  2593. if (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == FORCE_ON ||
  2594. (conf_get_int(ssh->conf, CONF_sshbug_ignore1) == AUTO &&
  2595. (!strcmp(imp, "1.2.18") || !strcmp(imp, "1.2.19") ||
  2596. !strcmp(imp, "1.2.20") || !strcmp(imp, "1.2.21") ||
  2597. !strcmp(imp, "1.2.22") || !strcmp(imp, "Cisco-1.25") ||
  2598. !strcmp(imp, "OSU_1.4alpha3") || !strcmp(imp, "OSU_1.5alpha4")))) {
  2599. /*
  2600. * These versions don't support SSH1_MSG_IGNORE, so we have
  2601. * to use a different defence against password length
  2602. * sniffing.
  2603. */
  2604. ssh->remote_bugs |= BUG_CHOKES_ON_SSH1_IGNORE;
  2605. logevent("We believe remote version has SSH-1 ignore bug");
  2606. }
  2607. if (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == FORCE_ON ||
  2608. (conf_get_int(ssh->conf, CONF_sshbug_plainpw1) == AUTO &&
  2609. (!strcmp(imp, "Cisco-1.25") || !strcmp(imp, "OSU_1.4alpha3")))) {
  2610. /*
  2611. * These versions need a plain password sent; they can't
  2612. * handle having a null and a random length of data after
  2613. * the password.
  2614. */
  2615. ssh->remote_bugs |= BUG_NEEDS_SSH1_PLAIN_PASSWORD;
  2616. logevent("We believe remote version needs a plain SSH-1 password");
  2617. }
  2618. if (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == FORCE_ON ||
  2619. (conf_get_int(ssh->conf, CONF_sshbug_rsa1) == AUTO &&
  2620. (!strcmp(imp, "Cisco-1.25")))) {
  2621. /*
  2622. * These versions apparently have no clue whatever about
  2623. * RSA authentication and will panic and die if they see
  2624. * an AUTH_RSA message.
  2625. */
  2626. ssh->remote_bugs |= BUG_CHOKES_ON_RSA;
  2627. logevent("We believe remote version can't handle SSH-1 RSA authentication");
  2628. }
  2629. if (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == FORCE_ON ||
  2630. (conf_get_int(ssh->conf, CONF_sshbug_hmac2) == AUTO &&
  2631. !wc_match("* VShell", imp) &&
  2632. (wc_match("2.1.0*", imp) || wc_match("2.0.*", imp) ||
  2633. wc_match("2.2.0*", imp) || wc_match("2.3.0*", imp) ||
  2634. wc_match("2.1 *", imp)))) {
  2635. /*
  2636. * These versions have the HMAC bug.
  2637. */
  2638. ssh->remote_bugs |= BUG_SSH2_HMAC;
  2639. logevent("We believe remote version has SSH-2 HMAC bug");
  2640. }
  2641. if (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == FORCE_ON ||
  2642. (conf_get_int(ssh->conf, CONF_sshbug_derivekey2) == AUTO &&
  2643. !wc_match("* VShell", imp) &&
  2644. (wc_match("2.0.0*", imp) || wc_match("2.0.10*", imp) ))) {
  2645. /*
  2646. * These versions have the key-derivation bug (failing to
  2647. * include the literal shared secret in the hashes that
  2648. * generate the keys).
  2649. */
  2650. ssh->remote_bugs |= BUG_SSH2_DERIVEKEY;
  2651. logevent("We believe remote version has SSH-2 key-derivation bug");
  2652. }
  2653. if (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == FORCE_ON ||
  2654. (conf_get_int(ssh->conf, CONF_sshbug_rsapad2) == AUTO &&
  2655. (wc_match("OpenSSH_2.[5-9]*", imp) ||
  2656. wc_match("OpenSSH_3.[0-2]*", imp) ||
  2657. wc_match("mod_sftp/0.[0-8]*", imp) ||
  2658. wc_match("mod_sftp/0.9.[0-8]", imp)))) {
  2659. /*
  2660. * These versions have the SSH-2 RSA padding bug.
  2661. */
  2662. ssh->remote_bugs |= BUG_SSH2_RSA_PADDING;
  2663. logevent("We believe remote version has SSH-2 RSA padding bug");
  2664. }
  2665. if (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == FORCE_ON ||
  2666. (conf_get_int(ssh->conf, CONF_sshbug_pksessid2) == AUTO &&
  2667. wc_match("OpenSSH_2.[0-2]*", imp))) {
  2668. /*
  2669. * These versions have the SSH-2 session-ID bug in
  2670. * public-key authentication.
  2671. */
  2672. ssh->remote_bugs |= BUG_SSH2_PK_SESSIONID;
  2673. logevent("We believe remote version has SSH-2 public-key-session-ID bug");
  2674. }
  2675. if (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == FORCE_ON ||
  2676. (conf_get_int(ssh->conf, CONF_sshbug_rekey2) == AUTO &&
  2677. (wc_match("DigiSSH_2.0", imp) ||
  2678. wc_match("OpenSSH_2.[0-4]*", imp) ||
  2679. wc_match("OpenSSH_2.5.[0-3]*", imp) ||
  2680. wc_match("Sun_SSH_1.0", imp) ||
  2681. wc_match("Sun_SSH_1.0.1", imp) ||
  2682. /* All versions <= 1.2.6 (they changed their format in 1.2.7) */
  2683. wc_match("WeOnlyDo-*", imp)))) {
  2684. /*
  2685. * These versions have the SSH-2 rekey bug.
  2686. */
  2687. ssh->remote_bugs |= BUG_SSH2_REKEY;
  2688. logevent("We believe remote version has SSH-2 rekey bug");
  2689. }
  2690. if (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == FORCE_ON ||
  2691. (conf_get_int(ssh->conf, CONF_sshbug_maxpkt2) == AUTO &&
  2692. (wc_match("1.36_sshlib GlobalSCAPE", imp) ||
  2693. wc_match("1.36 sshlib: GlobalScape", imp)))) {
  2694. /*
  2695. * This version ignores our makpkt and needs to be throttled.
  2696. */
  2697. ssh->remote_bugs |= BUG_SSH2_MAXPKT;
  2698. logevent("We believe remote version ignores SSH-2 maximum packet size");
  2699. }
  2700. if (conf_get_int(ssh->conf, CONF_sshbug_ignore2) == FORCE_ON) {
  2701. /*
  2702. * Servers that don't support SSH2_MSG_IGNORE. Currently,
  2703. * none detected automatically.
  2704. */
  2705. ssh->remote_bugs |= BUG_CHOKES_ON_SSH2_IGNORE;
  2706. logevent("We believe remote version has SSH-2 ignore bug");
  2707. }
  2708. if (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == FORCE_ON ||
  2709. (conf_get_int(ssh->conf, CONF_sshbug_oldgex2) == AUTO &&
  2710. (wc_match("OpenSSH_2.[235]*", imp)))) {
  2711. /*
  2712. * These versions only support the original (pre-RFC4419)
  2713. * SSH-2 GEX request, and disconnect with a protocol error if
  2714. * we use the newer version.
  2715. */
  2716. ssh->remote_bugs |= BUG_SSH2_OLDGEX;
  2717. logevent("We believe remote version has outdated SSH-2 GEX");
  2718. }
  2719. if (conf_get_int(ssh->conf, CONF_sshbug_winadj) == FORCE_ON) {
  2720. /*
  2721. * Servers that don't support our winadj request for one
  2722. * reason or another. Currently, none detected automatically.
  2723. */
  2724. ssh->remote_bugs |= BUG_CHOKES_ON_WINADJ;
  2725. logevent("We believe remote version has winadj bug");
  2726. }
  2727. if (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == FORCE_ON ||
  2728. (conf_get_int(ssh->conf, CONF_sshbug_chanreq) == AUTO &&
  2729. (wc_match("OpenSSH_[2-5].*", imp) ||
  2730. wc_match("OpenSSH_6.[0-6]*", imp) ||
  2731. wc_match("dropbear_0.[2-4][0-9]*", imp) ||
  2732. wc_match("dropbear_0.5[01]*", imp)))) {
  2733. /*
  2734. * These versions have the SSH-2 channel request bug.
  2735. * OpenSSH 6.7 and above do not:
  2736. * https://bugzilla.mindrot.org/show_bug.cgi?id=1818
  2737. * dropbear_0.52 and above do not:
  2738. * https://secure.ucc.asn.au/hg/dropbear/rev/cd02449b709c
  2739. */
  2740. ssh->remote_bugs |= BUG_SENDS_LATE_REQUEST_REPLY;
  2741. logevent("We believe remote version has SSH-2 channel request bug");
  2742. }
  2743. }
  2744. /*
  2745. * The `software version' part of an SSH version string is required
  2746. * to contain no spaces or minus signs.
  2747. */
  2748. static void ssh_fix_verstring(char *str)
  2749. {
  2750. /* Eat "<protoversion>-". */
  2751. while (*str && *str != '-') str++;
  2752. assert(*str == '-'); str++;
  2753. /* Convert minus signs and spaces in the remaining string into
  2754. * underscores. */
  2755. while (*str) {
  2756. if (*str == '-' || *str == ' ')
  2757. *str = '_';
  2758. str++;
  2759. }
  2760. }
  2761. /*
  2762. * Send an appropriate SSH version string.
  2763. */
  2764. static void ssh_send_verstring(Ssh ssh, const char *protoname, char *svers)
  2765. {
  2766. char *verstring;
  2767. if (ssh->version == 2) {
  2768. /*
  2769. * Construct a v2 version string.
  2770. */
  2771. verstring = dupprintf("%s2.0-%s\015\012", protoname, sshver);
  2772. } else {
  2773. /*
  2774. * Construct a v1 version string.
  2775. */
  2776. assert(!strcmp(protoname, "SSH-")); /* no v1 bare connection protocol */
  2777. verstring = dupprintf("SSH-%s-%s\012",
  2778. (ssh_versioncmp(svers, "1.5") <= 0 ?
  2779. svers : "1.5"),
  2780. sshver);
  2781. }
  2782. ssh_fix_verstring(verstring + strlen(protoname));
  2783. #ifdef FUZZING
  2784. /* FUZZING make PuTTY insecure, so make live use difficult. */
  2785. verstring[0] = 'I';
  2786. #endif
  2787. if (ssh->version == 2) {
  2788. size_t len;
  2789. /*
  2790. * Record our version string.
  2791. */
  2792. len = strcspn(verstring, "\015\012");
  2793. ssh->v_c = snewn(len + 1, char);
  2794. memcpy(ssh->v_c, verstring, len);
  2795. ssh->v_c[len] = 0;
  2796. }
  2797. logeventf(ssh, "We claim version: %.*s",
  2798. strcspn(verstring, "\015\012"), verstring);
  2799. s_write(ssh, verstring, strlen(verstring));
  2800. sfree(verstring);
  2801. }
  2802. static int do_ssh_init(Ssh ssh, unsigned char c)
  2803. {
  2804. static const char protoname[] = "SSH-";
  2805. struct do_ssh_init_state {
  2806. int crLine;
  2807. int vslen;
  2808. char version[10];
  2809. char *vstring;
  2810. int vstrsize;
  2811. int i;
  2812. int proto1, proto2;
  2813. };
  2814. crState(do_ssh_init_state);
  2815. crBeginState;
  2816. /* Search for a line beginning with the protocol name prefix in
  2817. * the input. */
  2818. for (;;) {
  2819. for (s->i = 0; protoname[s->i]; s->i++) {
  2820. if ((char)c != protoname[s->i]) goto no;
  2821. crReturn(1);
  2822. }
  2823. break;
  2824. no:
  2825. while (c != '\012')
  2826. crReturn(1);
  2827. crReturn(1);
  2828. }
  2829. ssh->session_started = TRUE;
  2830. s->vstrsize = sizeof(protoname) + 16;
  2831. s->vstring = snewn(s->vstrsize, char);
  2832. strcpy(s->vstring, protoname);
  2833. s->vslen = strlen(protoname);
  2834. s->i = 0;
  2835. while (1) {
  2836. if (s->vslen >= s->vstrsize - 1) {
  2837. s->vstrsize += 16;
  2838. s->vstring = sresize(s->vstring, s->vstrsize, char);
  2839. }
  2840. s->vstring[s->vslen++] = c;
  2841. if (s->i >= 0) {
  2842. if (c == '-') {
  2843. s->version[s->i] = '\0';
  2844. s->i = -1;
  2845. } else if (s->i < sizeof(s->version) - 1)
  2846. s->version[s->i++] = c;
  2847. } else if (c == '\012')
  2848. break;
  2849. crReturn(1); /* get another char */
  2850. }
  2851. ssh->agentfwd_enabled = FALSE;
  2852. ssh->rdpkt2_state.incoming_sequence = 0;
  2853. s->vstring[s->vslen] = 0;
  2854. s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
  2855. logeventf(ssh, "Server version: %s", s->vstring);
  2856. ssh_detect_bugs(ssh, s->vstring);
  2857. /*
  2858. * Decide which SSH protocol version to support.
  2859. */
  2860. /* Anything strictly below "2.0" means protocol 1 is supported. */
  2861. s->proto1 = ssh_versioncmp(s->version, "2.0") < 0;
  2862. /* Anything greater or equal to "1.99" means protocol 2 is supported. */
  2863. s->proto2 = ssh_versioncmp(s->version, "1.99") >= 0;
  2864. if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
  2865. if (!s->proto1) {
  2866. bombout(("SSH protocol version 1 required by our configuration "
  2867. "but not provided by server"));
  2868. crStop(0);
  2869. }
  2870. } else if (conf_get_int(ssh->conf, CONF_sshprot) == 3) {
  2871. if (!s->proto2) {
  2872. bombout(("SSH protocol version 2 required by our configuration "
  2873. "but server only provides (old, insecure) SSH-1"));
  2874. crStop(0);
  2875. }
  2876. } else {
  2877. /* No longer support values 1 or 2 for CONF_sshprot */
  2878. assert(!"Unexpected value for CONF_sshprot");
  2879. }
  2880. if (s->proto2 && (conf_get_int(ssh->conf, CONF_sshprot) >= 2 || !s->proto1))
  2881. ssh->version = 2;
  2882. else
  2883. ssh->version = 1;
  2884. logeventf(ssh, "Using SSH protocol version %d", ssh->version);
  2885. /* Send the version string, if we haven't already */
  2886. if (conf_get_int(ssh->conf, CONF_sshprot) != 3)
  2887. ssh_send_verstring(ssh, protoname, s->version);
  2888. if (ssh->version == 2) {
  2889. size_t len;
  2890. /*
  2891. * Record their version string.
  2892. */
  2893. len = strcspn(s->vstring, "\015\012");
  2894. ssh->v_s = snewn(len + 1, char);
  2895. memcpy(ssh->v_s, s->vstring, len);
  2896. ssh->v_s[len] = 0;
  2897. /*
  2898. * Initialise SSH-2 protocol.
  2899. */
  2900. ssh->protocol = ssh2_protocol;
  2901. ssh2_protocol_setup(ssh);
  2902. ssh->s_rdpkt = ssh2_rdpkt;
  2903. } else {
  2904. /*
  2905. * Initialise SSH-1 protocol.
  2906. */
  2907. ssh->protocol = ssh1_protocol;
  2908. ssh1_protocol_setup(ssh);
  2909. ssh->s_rdpkt = ssh1_rdpkt;
  2910. }
  2911. if (ssh->version == 2)
  2912. do_ssh2_transport(ssh, NULL, -1, NULL);
  2913. update_specials_menu(ssh->frontend);
  2914. ssh->state = SSH_STATE_BEFORE_SIZE;
  2915. ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
  2916. sfree(s->vstring);
  2917. crFinish(0);
  2918. }
  2919. static int do_ssh_connection_init(Ssh ssh, unsigned char c)
  2920. {
  2921. /*
  2922. * Ordinary SSH begins with the banner "SSH-x.y-...". This is just
  2923. * the ssh-connection part, extracted and given a trivial binary
  2924. * packet protocol, so we replace 'SSH-' at the start with a new
  2925. * name. In proper SSH style (though of course this part of the
  2926. * proper SSH protocol _isn't_ subject to this kind of
  2927. * DNS-domain-based extension), we define the new name in our
  2928. * extension space.
  2929. */
  2930. static const char protoname[] =
  2931. "SSHCONNECTION@putty.projects.tartarus.org-";
  2932. struct do_ssh_connection_init_state {
  2933. int crLine;
  2934. int vslen;
  2935. char version[10];
  2936. char *vstring;
  2937. int vstrsize;
  2938. int i;
  2939. };
  2940. crState(do_ssh_connection_init_state);
  2941. crBeginState;
  2942. /* Search for a line beginning with the protocol name prefix in
  2943. * the input. */
  2944. for (;;) {
  2945. for (s->i = 0; protoname[s->i]; s->i++) {
  2946. if ((char)c != protoname[s->i]) goto no;
  2947. crReturn(1);
  2948. }
  2949. break;
  2950. no:
  2951. while (c != '\012')
  2952. crReturn(1);
  2953. crReturn(1);
  2954. }
  2955. s->vstrsize = sizeof(protoname) + 16;
  2956. s->vstring = snewn(s->vstrsize, char);
  2957. strcpy(s->vstring, protoname);
  2958. s->vslen = strlen(protoname);
  2959. s->i = 0;
  2960. while (1) {
  2961. if (s->vslen >= s->vstrsize - 1) {
  2962. s->vstrsize += 16;
  2963. s->vstring = sresize(s->vstring, s->vstrsize, char);
  2964. }
  2965. s->vstring[s->vslen++] = c;
  2966. if (s->i >= 0) {
  2967. if (c == '-') {
  2968. s->version[s->i] = '\0';
  2969. s->i = -1;
  2970. } else if (s->i < sizeof(s->version) - 1)
  2971. s->version[s->i++] = c;
  2972. } else if (c == '\012')
  2973. break;
  2974. crReturn(1); /* get another char */
  2975. }
  2976. ssh->agentfwd_enabled = FALSE;
  2977. ssh->rdpkt2_bare_state.incoming_sequence = 0;
  2978. s->vstring[s->vslen] = 0;
  2979. s->vstring[strcspn(s->vstring, "\015\012")] = '\0';/* remove EOL chars */
  2980. logeventf(ssh, "Server version: %s", s->vstring);
  2981. ssh_detect_bugs(ssh, s->vstring);
  2982. /*
  2983. * Decide which SSH protocol version to support. This is easy in
  2984. * bare ssh-connection mode: only 2.0 is legal.
  2985. */
  2986. if (ssh_versioncmp(s->version, "2.0") < 0) {
  2987. bombout(("Server announces compatibility with SSH-1 in bare ssh-connection protocol"));
  2988. crStop(0);
  2989. }
  2990. if (conf_get_int(ssh->conf, CONF_sshprot) == 0) {
  2991. bombout(("Bare ssh-connection protocol cannot be run in SSH-1-only mode"));
  2992. crStop(0);
  2993. }
  2994. ssh->version = 2;
  2995. logeventf(ssh, "Using bare ssh-connection protocol");
  2996. /* Send the version string, if we haven't already */
  2997. ssh_send_verstring(ssh, protoname, s->version);
  2998. /*
  2999. * Initialise bare connection protocol.
  3000. */
  3001. ssh->protocol = ssh2_bare_connection_protocol;
  3002. ssh2_bare_connection_protocol_setup(ssh);
  3003. ssh->s_rdpkt = ssh2_bare_connection_rdpkt;
  3004. update_specials_menu(ssh->frontend);
  3005. ssh->state = SSH_STATE_BEFORE_SIZE;
  3006. ssh->pinger = pinger_new(ssh->conf, &ssh_backend, ssh);
  3007. /*
  3008. * Get authconn (really just conn) under way.
  3009. */
  3010. do_ssh2_authconn(ssh, NULL, 0, NULL);
  3011. sfree(s->vstring);
  3012. crFinish(0);
  3013. }
  3014. static void ssh_process_incoming_data(Ssh ssh,
  3015. const unsigned char **data, int *datalen)
  3016. {
  3017. struct Packet *pktin;
  3018. pktin = ssh->s_rdpkt(ssh, data, datalen);
  3019. if (pktin) {
  3020. ssh->protocol(ssh, NULL, 0, pktin);
  3021. ssh_free_packet(pktin);
  3022. }
  3023. }
  3024. static void ssh_queue_incoming_data(Ssh ssh,
  3025. const unsigned char **data, int *datalen)
  3026. {
  3027. bufchain_add(&ssh->queued_incoming_data, *data, *datalen);
  3028. *data += *datalen;
  3029. *datalen = 0;
  3030. }
  3031. static void ssh_process_queued_incoming_data(Ssh ssh)
  3032. {
  3033. void *vdata;
  3034. const unsigned char *data;
  3035. int len, origlen;
  3036. while (!ssh->frozen && bufchain_size(&ssh->queued_incoming_data)) {
  3037. bufchain_prefix(&ssh->queued_incoming_data, &vdata, &len);
  3038. data = vdata;
  3039. origlen = len;
  3040. while (!ssh->frozen && len > 0)
  3041. ssh_process_incoming_data(ssh, &data, &len);
  3042. if (origlen > len)
  3043. bufchain_consume(&ssh->queued_incoming_data, origlen - len);
  3044. }
  3045. }
  3046. static void ssh_set_frozen(Ssh ssh, int frozen)
  3047. {
  3048. if (ssh->s)
  3049. sk_set_frozen(ssh->s, frozen);
  3050. ssh->frozen = frozen;
  3051. }
  3052. static void ssh_gotdata(Ssh ssh, const unsigned char *data, int datalen)
  3053. {
  3054. /* Log raw data, if we're in that mode. */
  3055. if (ssh->logctx)
  3056. log_packet(ssh->logctx, PKT_INCOMING, -1, NULL, data, datalen,
  3057. 0, NULL, NULL, 0, NULL);
  3058. crBegin(ssh->ssh_gotdata_crstate);
  3059. /*
  3060. * To begin with, feed the characters one by one to the
  3061. * protocol initialisation / selection function do_ssh_init().
  3062. * When that returns 0, we're done with the initial greeting
  3063. * exchange and can move on to packet discipline.
  3064. */
  3065. while (1) {
  3066. int ret; /* need not be kept across crReturn */
  3067. if (datalen == 0)
  3068. crReturnV; /* more data please */
  3069. ret = ssh->do_ssh_init(ssh, *data);
  3070. data++;
  3071. datalen--;
  3072. if (ret == 0)
  3073. break;
  3074. }
  3075. /*
  3076. * We emerge from that loop when the initial negotiation is
  3077. * over and we have selected an s_rdpkt function. Now pass
  3078. * everything to s_rdpkt, and then pass the resulting packets
  3079. * to the proper protocol handler.
  3080. */
  3081. while (1) {
  3082. while (bufchain_size(&ssh->queued_incoming_data) > 0 || datalen > 0) {
  3083. if (ssh->frozen) {
  3084. ssh_queue_incoming_data(ssh, &data, &datalen);
  3085. /* This uses up all data and cannot cause anything interesting
  3086. * to happen; indeed, for anything to happen at all, we must
  3087. * return, so break out. */
  3088. break;
  3089. } else if (bufchain_size(&ssh->queued_incoming_data) > 0) {
  3090. /* This uses up some or all data, and may freeze the
  3091. * session. */
  3092. ssh_process_queued_incoming_data(ssh);
  3093. } else {
  3094. /* This uses up some or all data, and may freeze the
  3095. * session. */
  3096. ssh_process_incoming_data(ssh, &data, &datalen);
  3097. }
  3098. /* FIXME this is probably EBW. */
  3099. if (ssh->state == SSH_STATE_CLOSED)
  3100. return;
  3101. }
  3102. /* We're out of data. Go and get some more. */
  3103. crReturnV;
  3104. }
  3105. crFinishV;
  3106. }
  3107. static int ssh_do_close(Ssh ssh, int notify_exit)
  3108. {
  3109. int ret = 0;
  3110. struct ssh_channel *c;
  3111. ssh->state = SSH_STATE_CLOSED;
  3112. expire_timer_context(ssh);
  3113. if (ssh->s) {
  3114. sk_close(ssh->s);
  3115. ssh->s = NULL;
  3116. if (notify_exit)
  3117. notify_remote_exit(ssh->frontend);
  3118. else
  3119. ret = 1;
  3120. }
  3121. /*
  3122. * Now we must shut down any port- and X-forwarded channels going
  3123. * through this connection.
  3124. */
  3125. if (ssh->channels) {
  3126. while (NULL != (c = index234(ssh->channels, 0))) {
  3127. switch (c->type) {
  3128. case CHAN_X11:
  3129. x11_close(c->u.x11.xconn);
  3130. break;
  3131. case CHAN_SOCKDATA:
  3132. case CHAN_SOCKDATA_DORMANT:
  3133. pfd_close(c->u.pfd.pf);
  3134. break;
  3135. }
  3136. del234(ssh->channels, c); /* moving next one to index 0 */
  3137. if (ssh->version == 2)
  3138. bufchain_clear(&c->v.v2.outbuffer);
  3139. sfree(c);
  3140. }
  3141. }
  3142. /*
  3143. * Go through port-forwardings, and close any associated
  3144. * listening sockets.
  3145. */
  3146. if (ssh->portfwds) {
  3147. struct ssh_portfwd *pf;
  3148. while (NULL != (pf = index234(ssh->portfwds, 0))) {
  3149. /* Dispose of any listening socket. */
  3150. if (pf->local)
  3151. pfl_terminate(pf->local);
  3152. del234(ssh->portfwds, pf); /* moving next one to index 0 */
  3153. free_portfwd(pf);
  3154. }
  3155. freetree234(ssh->portfwds);
  3156. ssh->portfwds = NULL;
  3157. }
  3158. /*
  3159. * Also stop attempting to connection-share.
  3160. */
  3161. if (ssh->connshare) {
  3162. sharestate_free(ssh->connshare);
  3163. ssh->connshare = NULL;
  3164. }
  3165. return ret;
  3166. }
  3167. static void ssh_socket_log(Plug plug, int type, SockAddr addr, int port,
  3168. const char *error_msg, int error_code)
  3169. {
  3170. Ssh ssh = (Ssh) plug;
  3171. /*
  3172. * While we're attempting connection sharing, don't loudly log
  3173. * everything that happens. Real TCP connections need to be logged
  3174. * when we _start_ trying to connect, because it might be ages
  3175. * before they respond if something goes wrong; but connection
  3176. * sharing is local and quick to respond, and it's sufficient to
  3177. * simply wait and see whether it worked afterwards.
  3178. */
  3179. if (!ssh->attempting_connshare)
  3180. backend_socket_log(ssh->frontend, type, addr, port,
  3181. error_msg, error_code, ssh->conf,
  3182. ssh->session_started);
  3183. }
  3184. void ssh_connshare_log(Ssh ssh, int event, const char *logtext,
  3185. const char *ds_err, const char *us_err)
  3186. {
  3187. if (event == SHARE_NONE) {
  3188. /* In this case, 'logtext' is an error message indicating a
  3189. * reason why connection sharing couldn't be set up _at all_.
  3190. * Failing that, ds_err and us_err indicate why we couldn't be
  3191. * a downstream and an upstream respectively. */
  3192. if (logtext) {
  3193. logeventf(ssh, "Could not set up connection sharing: %s", logtext);
  3194. } else {
  3195. if (ds_err)
  3196. logeventf(ssh, "Could not set up connection sharing"
  3197. " as downstream: %s", ds_err);
  3198. if (us_err)
  3199. logeventf(ssh, "Could not set up connection sharing"
  3200. " as upstream: %s", us_err);
  3201. }
  3202. } else if (event == SHARE_DOWNSTREAM) {
  3203. /* In this case, 'logtext' is a local endpoint address */
  3204. logeventf(ssh, "Using existing shared connection at %s", logtext);
  3205. /* Also we should mention this in the console window to avoid
  3206. * confusing users as to why this window doesn't behave the
  3207. * usual way. */
  3208. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  3209. c_write_str(ssh,"Reusing a shared connection to this server.\r\n");
  3210. }
  3211. } else if (event == SHARE_UPSTREAM) {
  3212. /* In this case, 'logtext' is a local endpoint address too */
  3213. logeventf(ssh, "Sharing this connection at %s", logtext);
  3214. }
  3215. }
  3216. static int ssh_closing(Plug plug, const char *error_msg, int error_code,
  3217. int calling_back)
  3218. {
  3219. Ssh ssh = (Ssh) plug;
  3220. int need_notify = ssh_do_close(ssh, FALSE);
  3221. if (!error_msg) {
  3222. if (!ssh->close_expected)
  3223. error_msg = "Server unexpectedly closed network connection";
  3224. else
  3225. error_msg = "Server closed network connection";
  3226. }
  3227. if (ssh->close_expected && ssh->clean_exit && ssh->exitcode < 0)
  3228. ssh->exitcode = 0;
  3229. if (need_notify)
  3230. notify_remote_exit(ssh->frontend);
  3231. if (error_msg)
  3232. logevent(error_msg);
  3233. if (!ssh->close_expected || !ssh->clean_exit)
  3234. connection_fatal(ssh->frontend, "%s", error_msg);
  3235. return 0;
  3236. }
  3237. static int ssh_receive(Plug plug, int urgent, char *data, int len)
  3238. {
  3239. Ssh ssh = (Ssh) plug;
  3240. ssh_gotdata(ssh, (unsigned char *)data, len);
  3241. if (ssh->state == SSH_STATE_CLOSED) {
  3242. ssh_do_close(ssh, TRUE);
  3243. return 0;
  3244. }
  3245. return 1;
  3246. }
  3247. static void ssh_sent(Plug plug, int bufsize)
  3248. {
  3249. Ssh ssh = (Ssh) plug;
  3250. /*
  3251. * If the send backlog on the SSH socket itself clears, we
  3252. * should unthrottle the whole world if it was throttled.
  3253. */
  3254. if (bufsize < SSH_MAX_BACKLOG)
  3255. ssh_throttle_all(ssh, 0, bufsize);
  3256. }
  3257. static void ssh_hostport_setup(const char *host, int port, Conf *conf,
  3258. char **savedhost, int *savedport,
  3259. char **loghost_ret)
  3260. {
  3261. char *loghost = conf_get_str(conf, CONF_loghost);
  3262. if (loghost_ret)
  3263. *loghost_ret = loghost;
  3264. if (*loghost) {
  3265. char *tmphost;
  3266. char *colon;
  3267. tmphost = dupstr(loghost);
  3268. *savedport = 22; /* default ssh port */
  3269. /*
  3270. * A colon suffix on the hostname string also lets us affect
  3271. * savedport. (Unless there are multiple colons, in which case
  3272. * we assume this is an unbracketed IPv6 literal.)
  3273. */
  3274. colon = host_strrchr(tmphost, ':');
  3275. if (colon && colon == host_strchr(tmphost, ':')) {
  3276. *colon++ = '\0';
  3277. if (*colon)
  3278. *savedport = atoi(colon);
  3279. }
  3280. *savedhost = host_strduptrim(tmphost);
  3281. sfree(tmphost);
  3282. } else {
  3283. *savedhost = host_strduptrim(host);
  3284. if (port < 0)
  3285. port = 22; /* default ssh port */
  3286. *savedport = port;
  3287. }
  3288. }
  3289. static int ssh_test_for_upstream(const char *host, int port, Conf *conf)
  3290. {
  3291. char *savedhost;
  3292. int savedport;
  3293. int ret;
  3294. random_ref(); /* platform may need this to determine share socket name */
  3295. ssh_hostport_setup(host, port, conf, &savedhost, &savedport, NULL);
  3296. ret = ssh_share_test_for_upstream(savedhost, savedport, conf);
  3297. sfree(savedhost);
  3298. random_unref();
  3299. return ret;
  3300. }
  3301. /*
  3302. * Connect to specified host and port.
  3303. * Returns an error message, or NULL on success.
  3304. * Also places the canonical host name into `realhost'. It must be
  3305. * freed by the caller.
  3306. */
  3307. static const char *connect_to_host(Ssh ssh, const char *host, int port,
  3308. char **realhost, int nodelay, int keepalive)
  3309. {
  3310. static const struct plug_function_table fn_table = {
  3311. ssh_socket_log,
  3312. ssh_closing,
  3313. ssh_receive,
  3314. ssh_sent,
  3315. NULL
  3316. };
  3317. SockAddr addr;
  3318. const char *err;
  3319. char *loghost;
  3320. int addressfamily, sshprot;
  3321. ssh_hostport_setup(host, port, ssh->conf,
  3322. &ssh->savedhost, &ssh->savedport, &loghost);
  3323. ssh->fn = &fn_table; /* make 'ssh' usable as a Plug */
  3324. /*
  3325. * Try connection-sharing, in case that means we don't open a
  3326. * socket after all. ssh_connection_sharing_init will connect to a
  3327. * previously established upstream if it can, and failing that,
  3328. * establish a listening socket for _us_ to be the upstream. In
  3329. * the latter case it will return NULL just as if it had done
  3330. * nothing, because here we only need to care if we're a
  3331. * downstream and need to do our connection setup differently.
  3332. */
  3333. ssh->connshare = NULL;
  3334. ssh->attempting_connshare = TRUE; /* affects socket logging behaviour */
  3335. ssh->s = ssh_connection_sharing_init(ssh->savedhost, ssh->savedport,
  3336. ssh->conf, ssh, &ssh->connshare);
  3337. ssh->attempting_connshare = FALSE;
  3338. if (ssh->s != NULL) {
  3339. /*
  3340. * We are a downstream.
  3341. */
  3342. ssh->bare_connection = TRUE;
  3343. ssh->do_ssh_init = do_ssh_connection_init;
  3344. ssh->fullhostname = NULL;
  3345. *realhost = dupstr(host); /* best we can do */
  3346. } else {
  3347. /*
  3348. * We're not a downstream, so open a normal socket.
  3349. */
  3350. ssh->do_ssh_init = do_ssh_init;
  3351. /*
  3352. * Try to find host.
  3353. */
  3354. addressfamily = conf_get_int(ssh->conf, CONF_addressfamily);
  3355. addr = name_lookup(host, port, realhost, ssh->conf, addressfamily,
  3356. ssh->frontend, "SSH connection");
  3357. if ((err = sk_addr_error(addr)) != NULL) {
  3358. sk_addr_free(addr);
  3359. return err;
  3360. }
  3361. ssh->fullhostname = dupstr(*realhost); /* save in case of GSSAPI */
  3362. ssh->s = new_connection(addr, *realhost, port,
  3363. 0, 1, nodelay, keepalive,
  3364. (Plug) ssh, ssh->conf);
  3365. if ((err = sk_socket_error(ssh->s)) != NULL) {
  3366. ssh->s = NULL;
  3367. notify_remote_exit(ssh->frontend);
  3368. return err;
  3369. }
  3370. }
  3371. /*
  3372. * The SSH version number is always fixed (since we no longer support
  3373. * fallback between versions), so set it now, and if it's SSH-2,
  3374. * send the version string now too.
  3375. */
  3376. sshprot = conf_get_int(ssh->conf, CONF_sshprot);
  3377. assert(sshprot == 0 || sshprot == 3);
  3378. if (sshprot == 0)
  3379. /* SSH-1 only */
  3380. ssh->version = 1;
  3381. if (sshprot == 3 && !ssh->bare_connection) {
  3382. /* SSH-2 only */
  3383. ssh->version = 2;
  3384. ssh_send_verstring(ssh, "SSH-", NULL);
  3385. }
  3386. /*
  3387. * loghost, if configured, overrides realhost.
  3388. */
  3389. if (*loghost) {
  3390. sfree(*realhost);
  3391. *realhost = dupstr(loghost);
  3392. }
  3393. return NULL;
  3394. }
  3395. /*
  3396. * Throttle or unthrottle the SSH connection.
  3397. */
  3398. static void ssh_throttle_conn(Ssh ssh, int adjust)
  3399. {
  3400. int old_count = ssh->conn_throttle_count;
  3401. ssh->conn_throttle_count += adjust;
  3402. assert(ssh->conn_throttle_count >= 0);
  3403. if (ssh->conn_throttle_count && !old_count) {
  3404. ssh_set_frozen(ssh, 1);
  3405. } else if (!ssh->conn_throttle_count && old_count) {
  3406. ssh_set_frozen(ssh, 0);
  3407. }
  3408. }
  3409. /*
  3410. * Throttle or unthrottle _all_ local data streams (for when sends
  3411. * on the SSH connection itself back up).
  3412. */
  3413. static void ssh_throttle_all(Ssh ssh, int enable, int bufsize)
  3414. {
  3415. int i;
  3416. struct ssh_channel *c;
  3417. if (enable == ssh->throttled_all)
  3418. return;
  3419. ssh->throttled_all = enable;
  3420. ssh->overall_bufsize = bufsize;
  3421. if (!ssh->channels)
  3422. return;
  3423. for (i = 0; NULL != (c = index234(ssh->channels, i)); i++) {
  3424. switch (c->type) {
  3425. case CHAN_MAINSESSION:
  3426. /*
  3427. * This is treated separately, outside the switch.
  3428. */
  3429. break;
  3430. case CHAN_X11:
  3431. x11_override_throttle(c->u.x11.xconn, enable);
  3432. break;
  3433. case CHAN_AGENT:
  3434. /* Agent channels require no buffer management. */
  3435. break;
  3436. case CHAN_SOCKDATA:
  3437. pfd_override_throttle(c->u.pfd.pf, enable);
  3438. break;
  3439. }
  3440. }
  3441. }
  3442. static void ssh_agent_callback(void *sshv, void *reply, int replylen)
  3443. {
  3444. Ssh ssh = (Ssh) sshv;
  3445. ssh->agent_response = reply;
  3446. ssh->agent_response_len = replylen;
  3447. if (ssh->version == 1)
  3448. do_ssh1_login(ssh, NULL, -1, NULL);
  3449. else
  3450. do_ssh2_authconn(ssh, NULL, -1, NULL);
  3451. }
  3452. static void ssh_dialog_callback(void *sshv, int ret)
  3453. {
  3454. Ssh ssh = (Ssh) sshv;
  3455. ssh->user_response = ret;
  3456. if (ssh->version == 1)
  3457. do_ssh1_login(ssh, NULL, -1, NULL);
  3458. else
  3459. do_ssh2_transport(ssh, NULL, -1, NULL);
  3460. /*
  3461. * This may have unfrozen the SSH connection, so do a
  3462. * queued-data run.
  3463. */
  3464. ssh_process_queued_incoming_data(ssh);
  3465. }
  3466. static void ssh_agentf_callback(void *cv, void *reply, int replylen)
  3467. {
  3468. struct ssh_channel *c = (struct ssh_channel *)cv;
  3469. const void *sentreply = reply;
  3470. c->u.a.outstanding_requests--;
  3471. if (!sentreply) {
  3472. /* Fake SSH_AGENT_FAILURE. */
  3473. sentreply = "\0\0\0\1\5";
  3474. replylen = 5;
  3475. }
  3476. ssh_send_channel_data(c, sentreply, replylen);
  3477. if (reply)
  3478. sfree(reply);
  3479. /*
  3480. * If we've already seen an incoming EOF but haven't sent an
  3481. * outgoing one, this may be the moment to send it.
  3482. */
  3483. if (c->u.a.outstanding_requests == 0 && (c->closes & CLOSES_RCVD_EOF))
  3484. sshfwd_write_eof(c);
  3485. }
  3486. /*
  3487. * Client-initiated disconnection. Send a DISCONNECT if `wire_reason'
  3488. * non-NULL, otherwise just close the connection. `client_reason' == NULL
  3489. * => log `wire_reason'.
  3490. */
  3491. static void ssh_disconnect(Ssh ssh, const char *client_reason,
  3492. const char *wire_reason,
  3493. int code, int clean_exit)
  3494. {
  3495. char *error;
  3496. if (!client_reason)
  3497. client_reason = wire_reason;
  3498. if (client_reason)
  3499. error = dupprintf("Disconnected: %s", client_reason);
  3500. else
  3501. error = dupstr("Disconnected");
  3502. if (wire_reason) {
  3503. if (ssh->version == 1) {
  3504. send_packet(ssh, SSH1_MSG_DISCONNECT, PKT_STR, wire_reason,
  3505. PKT_END);
  3506. } else if (ssh->version == 2) {
  3507. struct Packet *pktout = ssh2_pkt_init(SSH2_MSG_DISCONNECT);
  3508. ssh2_pkt_adduint32(pktout, code);
  3509. ssh2_pkt_addstring(pktout, wire_reason);
  3510. ssh2_pkt_addstring(pktout, "en"); /* language tag */
  3511. ssh2_pkt_send_noqueue(ssh, pktout);
  3512. }
  3513. }
  3514. ssh->close_expected = TRUE;
  3515. ssh->clean_exit = clean_exit;
  3516. ssh_closing((Plug)ssh, error, 0, 0);
  3517. sfree(error);
  3518. }
  3519. int verify_ssh_manual_host_key(Ssh ssh, const char *fingerprint,
  3520. const struct ssh_signkey *ssh2keytype,
  3521. void *ssh2keydata)
  3522. {
  3523. if (!conf_get_str_nthstrkey(ssh->conf, CONF_ssh_manual_hostkeys, 0)) {
  3524. return -1; /* no manual keys configured */
  3525. }
  3526. if (fingerprint) {
  3527. /*
  3528. * The fingerprint string we've been given will have things
  3529. * like 'ssh-rsa 2048' at the front of it. Strip those off and
  3530. * narrow down to just the colon-separated hex block at the
  3531. * end of the string.
  3532. */
  3533. const char *p = strrchr(fingerprint, ' ');
  3534. fingerprint = p ? p+1 : fingerprint;
  3535. /* Quick sanity checks, including making sure it's in lowercase */
  3536. assert(strlen(fingerprint) == 16*3 - 1);
  3537. assert(fingerprint[2] == ':');
  3538. assert(fingerprint[strspn(fingerprint, "0123456789abcdef:")] == 0);
  3539. if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
  3540. fingerprint))
  3541. return 1; /* success */
  3542. }
  3543. if (ssh2keydata) {
  3544. /*
  3545. * Construct the base64-encoded public key blob and see if
  3546. * that's listed.
  3547. */
  3548. unsigned char *binblob;
  3549. char *base64blob;
  3550. int binlen, atoms, i;
  3551. binblob = ssh2keytype->public_blob(ssh2keydata, &binlen);
  3552. atoms = (binlen + 2) / 3;
  3553. base64blob = snewn(atoms * 4 + 1, char);
  3554. for (i = 0; i < atoms; i++)
  3555. base64_encode_atom(binblob + 3*i, binlen - 3*i, base64blob + 4*i);
  3556. base64blob[atoms * 4] = '\0';
  3557. sfree(binblob);
  3558. if (conf_get_str_str_opt(ssh->conf, CONF_ssh_manual_hostkeys,
  3559. base64blob)) {
  3560. sfree(base64blob);
  3561. return 1; /* success */
  3562. }
  3563. sfree(base64blob);
  3564. }
  3565. return 0;
  3566. }
  3567. /*
  3568. * Handle the key exchange and user authentication phases.
  3569. */
  3570. static int do_ssh1_login(Ssh ssh, const unsigned char *in, int inlen,
  3571. struct Packet *pktin)
  3572. {
  3573. int i, j, ret;
  3574. unsigned char cookie[8], *ptr;
  3575. struct MD5Context md5c;
  3576. struct do_ssh1_login_state {
  3577. int crLine;
  3578. int len;
  3579. unsigned char *rsabuf;
  3580. const unsigned char *keystr1, *keystr2;
  3581. unsigned long supported_ciphers_mask, supported_auths_mask;
  3582. int tried_publickey, tried_agent;
  3583. int tis_auth_refused, ccard_auth_refused;
  3584. unsigned char session_id[16];
  3585. int cipher_type;
  3586. void *publickey_blob;
  3587. int publickey_bloblen;
  3588. char *publickey_comment;
  3589. int privatekey_available, privatekey_encrypted;
  3590. prompts_t *cur_prompt;
  3591. char c;
  3592. int pwpkt_type;
  3593. unsigned char request[5], *response, *p;
  3594. int responselen;
  3595. int keyi, nkeys;
  3596. int authed;
  3597. struct RSAKey key;
  3598. Bignum challenge;
  3599. char *commentp;
  3600. int commentlen;
  3601. int dlgret;
  3602. Filename *keyfile;
  3603. struct RSAKey servkey, hostkey;
  3604. };
  3605. crState(do_ssh1_login_state);
  3606. crBeginState;
  3607. if (!pktin)
  3608. crWaitUntil(pktin);
  3609. if (pktin->type != SSH1_SMSG_PUBLIC_KEY) {
  3610. bombout(("Public key packet not received"));
  3611. crStop(0);
  3612. }
  3613. logevent("Received public keys");
  3614. ptr = ssh_pkt_getdata(pktin, 8);
  3615. if (!ptr) {
  3616. bombout(("SSH-1 public key packet stopped before random cookie"));
  3617. crStop(0);
  3618. }
  3619. memcpy(cookie, ptr, 8);
  3620. if (!ssh1_pkt_getrsakey(pktin, &s->servkey, &s->keystr1) ||
  3621. !ssh1_pkt_getrsakey(pktin, &s->hostkey, &s->keystr2)) {
  3622. bombout(("Failed to read SSH-1 public keys from public key packet"));
  3623. crStop(0);
  3624. }
  3625. /*
  3626. * Log the host key fingerprint.
  3627. */
  3628. {
  3629. char logmsg[80];
  3630. logevent("Host key fingerprint is:");
  3631. strcpy(logmsg, " ");
  3632. s->hostkey.comment = NULL;
  3633. rsa_fingerprint(logmsg + strlen(logmsg),
  3634. sizeof(logmsg) - strlen(logmsg), &s->hostkey);
  3635. logevent(logmsg);
  3636. }
  3637. ssh->v1_remote_protoflags = ssh_pkt_getuint32(pktin);
  3638. s->supported_ciphers_mask = ssh_pkt_getuint32(pktin);
  3639. s->supported_auths_mask = ssh_pkt_getuint32(pktin);
  3640. if ((ssh->remote_bugs & BUG_CHOKES_ON_RSA))
  3641. s->supported_auths_mask &= ~(1 << SSH1_AUTH_RSA);
  3642. ssh->v1_local_protoflags =
  3643. ssh->v1_remote_protoflags & SSH1_PROTOFLAGS_SUPPORTED;
  3644. ssh->v1_local_protoflags |= SSH1_PROTOFLAG_SCREEN_NUMBER;
  3645. MD5Init(&md5c);
  3646. MD5Update(&md5c, s->keystr2, s->hostkey.bytes);
  3647. MD5Update(&md5c, s->keystr1, s->servkey.bytes);
  3648. MD5Update(&md5c, cookie, 8);
  3649. MD5Final(s->session_id, &md5c);
  3650. for (i = 0; i < 32; i++)
  3651. ssh->session_key[i] = random_byte();
  3652. /*
  3653. * Verify that the `bits' and `bytes' parameters match.
  3654. */
  3655. if (s->hostkey.bits > s->hostkey.bytes * 8 ||
  3656. s->servkey.bits > s->servkey.bytes * 8) {
  3657. bombout(("SSH-1 public keys were badly formatted"));
  3658. crStop(0);
  3659. }
  3660. s->len = (s->hostkey.bytes > s->servkey.bytes ?
  3661. s->hostkey.bytes : s->servkey.bytes);
  3662. s->rsabuf = snewn(s->len, unsigned char);
  3663. /*
  3664. * Verify the host key.
  3665. */
  3666. {
  3667. /*
  3668. * First format the key into a string.
  3669. */
  3670. int len = rsastr_len(&s->hostkey);
  3671. char fingerprint[100];
  3672. char *keystr = snewn(len, char);
  3673. rsastr_fmt(keystr, &s->hostkey);
  3674. rsa_fingerprint(fingerprint, sizeof(fingerprint), &s->hostkey);
  3675. /* First check against manually configured host keys. */
  3676. s->dlgret = verify_ssh_manual_host_key(ssh, fingerprint, NULL, NULL);
  3677. if (s->dlgret == 0) { /* did not match */
  3678. bombout(("Host key did not appear in manually configured list"));
  3679. sfree(keystr);
  3680. crStop(0);
  3681. } else if (s->dlgret < 0) { /* none configured; use standard handling */
  3682. ssh_set_frozen(ssh, 1);
  3683. s->dlgret = verify_ssh_host_key(ssh->frontend,
  3684. ssh->savedhost, ssh->savedport,
  3685. "rsa", keystr, fingerprint,
  3686. ssh_dialog_callback, ssh);
  3687. sfree(keystr);
  3688. #ifdef FUZZING
  3689. s->dlgret = 1;
  3690. #endif
  3691. if (s->dlgret < 0) {
  3692. do {
  3693. crReturn(0);
  3694. if (pktin) {
  3695. bombout(("Unexpected data from server while waiting"
  3696. " for user host key response"));
  3697. crStop(0);
  3698. }
  3699. } while (pktin || inlen > 0);
  3700. s->dlgret = ssh->user_response;
  3701. }
  3702. ssh_set_frozen(ssh, 0);
  3703. if (s->dlgret == 0) {
  3704. ssh_disconnect(ssh, "User aborted at host key verification",
  3705. NULL, 0, TRUE);
  3706. crStop(0);
  3707. }
  3708. } else {
  3709. sfree(keystr);
  3710. }
  3711. }
  3712. for (i = 0; i < 32; i++) {
  3713. s->rsabuf[i] = ssh->session_key[i];
  3714. if (i < 16)
  3715. s->rsabuf[i] ^= s->session_id[i];
  3716. }
  3717. if (s->hostkey.bytes > s->servkey.bytes) {
  3718. ret = rsaencrypt(s->rsabuf, 32, &s->servkey);
  3719. if (ret)
  3720. ret = rsaencrypt(s->rsabuf, s->servkey.bytes, &s->hostkey);
  3721. } else {
  3722. ret = rsaencrypt(s->rsabuf, 32, &s->hostkey);
  3723. if (ret)
  3724. ret = rsaencrypt(s->rsabuf, s->hostkey.bytes, &s->servkey);
  3725. }
  3726. if (!ret) {
  3727. bombout(("SSH-1 public key encryptions failed due to bad formatting"));
  3728. crStop(0);
  3729. }
  3730. logevent("Encrypted session key");
  3731. {
  3732. int cipher_chosen = 0, warn = 0;
  3733. const char *cipher_string = NULL;
  3734. int i;
  3735. for (i = 0; !cipher_chosen && i < CIPHER_MAX; i++) {
  3736. int next_cipher = conf_get_int_int(ssh->conf,
  3737. CONF_ssh_cipherlist, i);
  3738. if (next_cipher == CIPHER_WARN) {
  3739. /* If/when we choose a cipher, warn about it */
  3740. warn = 1;
  3741. } else if (next_cipher == CIPHER_AES) {
  3742. /* XXX Probably don't need to mention this. */
  3743. logevent("AES not supported in SSH-1, skipping");
  3744. } else {
  3745. switch (next_cipher) {
  3746. case CIPHER_3DES: s->cipher_type = SSH_CIPHER_3DES;
  3747. cipher_string = "3DES"; break;
  3748. case CIPHER_BLOWFISH: s->cipher_type = SSH_CIPHER_BLOWFISH;
  3749. cipher_string = "Blowfish"; break;
  3750. case CIPHER_DES: s->cipher_type = SSH_CIPHER_DES;
  3751. cipher_string = "single-DES"; break;
  3752. }
  3753. if (s->supported_ciphers_mask & (1 << s->cipher_type))
  3754. cipher_chosen = 1;
  3755. }
  3756. }
  3757. if (!cipher_chosen) {
  3758. if ((s->supported_ciphers_mask & (1 << SSH_CIPHER_3DES)) == 0)
  3759. bombout(("Server violates SSH-1 protocol by not "
  3760. "supporting 3DES encryption"));
  3761. else
  3762. /* shouldn't happen */
  3763. bombout(("No supported ciphers found"));
  3764. crStop(0);
  3765. }
  3766. /* Warn about chosen cipher if necessary. */
  3767. if (warn) {
  3768. ssh_set_frozen(ssh, 1);
  3769. s->dlgret = askalg(ssh->frontend, "cipher", cipher_string,
  3770. ssh_dialog_callback, ssh);
  3771. if (s->dlgret < 0) {
  3772. do {
  3773. crReturn(0);
  3774. if (pktin) {
  3775. bombout(("Unexpected data from server while waiting"
  3776. " for user response"));
  3777. crStop(0);
  3778. }
  3779. } while (pktin || inlen > 0);
  3780. s->dlgret = ssh->user_response;
  3781. }
  3782. ssh_set_frozen(ssh, 0);
  3783. if (s->dlgret == 0) {
  3784. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  3785. 0, TRUE);
  3786. crStop(0);
  3787. }
  3788. }
  3789. }
  3790. switch (s->cipher_type) {
  3791. case SSH_CIPHER_3DES:
  3792. logevent("Using 3DES encryption");
  3793. break;
  3794. case SSH_CIPHER_DES:
  3795. logevent("Using single-DES encryption");
  3796. break;
  3797. case SSH_CIPHER_BLOWFISH:
  3798. logevent("Using Blowfish encryption");
  3799. break;
  3800. }
  3801. send_packet(ssh, SSH1_CMSG_SESSION_KEY,
  3802. PKT_CHAR, s->cipher_type,
  3803. PKT_DATA, cookie, 8,
  3804. PKT_CHAR, (s->len * 8) >> 8, PKT_CHAR, (s->len * 8) & 0xFF,
  3805. PKT_DATA, s->rsabuf, s->len,
  3806. PKT_INT, ssh->v1_local_protoflags, PKT_END);
  3807. logevent("Trying to enable encryption...");
  3808. sfree(s->rsabuf);
  3809. ssh->cipher = (s->cipher_type == SSH_CIPHER_BLOWFISH ? &ssh_blowfish_ssh1 :
  3810. s->cipher_type == SSH_CIPHER_DES ? &ssh_des :
  3811. &ssh_3des);
  3812. ssh->v1_cipher_ctx = ssh->cipher->make_context();
  3813. ssh->cipher->sesskey(ssh->v1_cipher_ctx, ssh->session_key);
  3814. logeventf(ssh, "Initialised %s encryption", ssh->cipher->text_name);
  3815. ssh->crcda_ctx = crcda_make_context();
  3816. logevent("Installing CRC compensation attack detector");
  3817. if (s->servkey.modulus) {
  3818. sfree(s->servkey.modulus);
  3819. s->servkey.modulus = NULL;
  3820. }
  3821. if (s->servkey.exponent) {
  3822. sfree(s->servkey.exponent);
  3823. s->servkey.exponent = NULL;
  3824. }
  3825. if (s->hostkey.modulus) {
  3826. sfree(s->hostkey.modulus);
  3827. s->hostkey.modulus = NULL;
  3828. }
  3829. if (s->hostkey.exponent) {
  3830. sfree(s->hostkey.exponent);
  3831. s->hostkey.exponent = NULL;
  3832. }
  3833. crWaitUntil(pktin);
  3834. if (pktin->type != SSH1_SMSG_SUCCESS) {
  3835. bombout(("Encryption not successfully enabled"));
  3836. crStop(0);
  3837. }
  3838. logevent("Successfully started encryption");
  3839. fflush(stdout); /* FIXME eh? */
  3840. {
  3841. if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
  3842. int ret; /* need not be kept over crReturn */
  3843. s->cur_prompt = new_prompts(ssh->frontend);
  3844. s->cur_prompt->to_server = TRUE;
  3845. s->cur_prompt->name = dupstr("SSH login name");
  3846. add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
  3847. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  3848. while (ret < 0) {
  3849. ssh->send_ok = 1;
  3850. crWaitUntil(!pktin);
  3851. ret = get_userpass_input(s->cur_prompt, in, inlen);
  3852. ssh->send_ok = 0;
  3853. }
  3854. if (!ret) {
  3855. /*
  3856. * Failed to get a username. Terminate.
  3857. */
  3858. free_prompts(s->cur_prompt);
  3859. ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
  3860. crStop(0);
  3861. }
  3862. ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
  3863. free_prompts(s->cur_prompt);
  3864. }
  3865. send_packet(ssh, SSH1_CMSG_USER, PKT_STR, ssh->username, PKT_END);
  3866. {
  3867. char *userlog = dupprintf("Sent username \"%s\"", ssh->username);
  3868. logevent(userlog);
  3869. if (flags & FLAG_INTERACTIVE &&
  3870. (!((flags & FLAG_STDERR) && (flags & FLAG_VERBOSE)))) {
  3871. c_write_str(ssh, userlog);
  3872. c_write_str(ssh, "\r\n");
  3873. }
  3874. sfree(userlog);
  3875. }
  3876. }
  3877. crWaitUntil(pktin);
  3878. if ((s->supported_auths_mask & (1 << SSH1_AUTH_RSA)) == 0) {
  3879. /* We must not attempt PK auth. Pretend we've already tried it. */
  3880. s->tried_publickey = s->tried_agent = 1;
  3881. } else {
  3882. s->tried_publickey = s->tried_agent = 0;
  3883. }
  3884. s->tis_auth_refused = s->ccard_auth_refused = 0;
  3885. /*
  3886. * Load the public half of any configured keyfile for later use.
  3887. */
  3888. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  3889. if (!filename_is_null(s->keyfile)) {
  3890. int keytype;
  3891. logeventf(ssh, "Reading key file \"%.150s\"",
  3892. filename_to_str(s->keyfile));
  3893. keytype = key_type(s->keyfile);
  3894. if (keytype == SSH_KEYTYPE_SSH1 ||
  3895. keytype == SSH_KEYTYPE_SSH1_PUBLIC) {
  3896. const char *error;
  3897. if (rsakey_pubblob(s->keyfile,
  3898. &s->publickey_blob, &s->publickey_bloblen,
  3899. &s->publickey_comment, &error)) {
  3900. s->privatekey_available = (keytype == SSH_KEYTYPE_SSH1);
  3901. if (!s->privatekey_available)
  3902. logeventf(ssh, "Key file contains public key only");
  3903. s->privatekey_encrypted = rsakey_encrypted(s->keyfile,
  3904. NULL);
  3905. } else {
  3906. char *msgbuf;
  3907. logeventf(ssh, "Unable to load key (%s)", error);
  3908. msgbuf = dupprintf("Unable to load key file "
  3909. "\"%.150s\" (%s)\r\n",
  3910. filename_to_str(s->keyfile),
  3911. error);
  3912. c_write_str(ssh, msgbuf);
  3913. sfree(msgbuf);
  3914. s->publickey_blob = NULL;
  3915. }
  3916. } else {
  3917. char *msgbuf;
  3918. logeventf(ssh, "Unable to use this key file (%s)",
  3919. key_type_to_str(keytype));
  3920. msgbuf = dupprintf("Unable to use key file \"%.150s\""
  3921. " (%s)\r\n",
  3922. filename_to_str(s->keyfile),
  3923. key_type_to_str(keytype));
  3924. c_write_str(ssh, msgbuf);
  3925. sfree(msgbuf);
  3926. s->publickey_blob = NULL;
  3927. }
  3928. } else
  3929. s->publickey_blob = NULL;
  3930. while (pktin->type == SSH1_SMSG_FAILURE) {
  3931. s->pwpkt_type = SSH1_CMSG_AUTH_PASSWORD;
  3932. if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists() && !s->tried_agent) {
  3933. /*
  3934. * Attempt RSA authentication using Pageant.
  3935. */
  3936. void *r;
  3937. s->authed = FALSE;
  3938. s->tried_agent = 1;
  3939. logevent("Pageant is running. Requesting keys.");
  3940. /* Request the keys held by the agent. */
  3941. PUT_32BIT(s->request, 1);
  3942. s->request[4] = SSH1_AGENTC_REQUEST_RSA_IDENTITIES;
  3943. if (!agent_query(s->request, 5, &r, &s->responselen,
  3944. ssh_agent_callback, ssh)) {
  3945. do {
  3946. crReturn(0);
  3947. if (pktin) {
  3948. bombout(("Unexpected data from server while waiting"
  3949. " for agent response"));
  3950. crStop(0);
  3951. }
  3952. } while (pktin || inlen > 0);
  3953. r = ssh->agent_response;
  3954. s->responselen = ssh->agent_response_len;
  3955. }
  3956. s->response = (unsigned char *) r;
  3957. if (s->response && s->responselen >= 5 &&
  3958. s->response[4] == SSH1_AGENT_RSA_IDENTITIES_ANSWER) {
  3959. s->p = s->response + 5;
  3960. s->nkeys = toint(GET_32BIT(s->p));
  3961. if (s->nkeys < 0) {
  3962. logeventf(ssh, "Pageant reported negative key count %d",
  3963. s->nkeys);
  3964. s->nkeys = 0;
  3965. }
  3966. s->p += 4;
  3967. logeventf(ssh, "Pageant has %d SSH-1 keys", s->nkeys);
  3968. for (s->keyi = 0; s->keyi < s->nkeys; s->keyi++) {
  3969. unsigned char *pkblob = s->p;
  3970. s->p += 4;
  3971. {
  3972. int n, ok = FALSE;
  3973. do { /* do while (0) to make breaking easy */
  3974. n = ssh1_read_bignum
  3975. (s->p, toint(s->responselen-(s->p-s->response)),
  3976. &s->key.exponent);
  3977. if (n < 0)
  3978. break;
  3979. s->p += n;
  3980. n = ssh1_read_bignum
  3981. (s->p, toint(s->responselen-(s->p-s->response)),
  3982. &s->key.modulus);
  3983. if (n < 0)
  3984. break;
  3985. s->p += n;
  3986. if (s->responselen - (s->p-s->response) < 4)
  3987. break;
  3988. s->commentlen = toint(GET_32BIT(s->p));
  3989. s->p += 4;
  3990. if (s->commentlen < 0 ||
  3991. toint(s->responselen - (s->p-s->response)) <
  3992. s->commentlen)
  3993. break;
  3994. s->commentp = (char *)s->p;
  3995. s->p += s->commentlen;
  3996. ok = TRUE;
  3997. } while (0);
  3998. if (!ok) {
  3999. logevent("Pageant key list packet was truncated");
  4000. break;
  4001. }
  4002. }
  4003. if (s->publickey_blob) {
  4004. if (!memcmp(pkblob, s->publickey_blob,
  4005. s->publickey_bloblen)) {
  4006. logeventf(ssh, "Pageant key #%d matches "
  4007. "configured key file", s->keyi);
  4008. s->tried_publickey = 1;
  4009. } else
  4010. /* Skip non-configured key */
  4011. continue;
  4012. }
  4013. logeventf(ssh, "Trying Pageant key #%d", s->keyi);
  4014. send_packet(ssh, SSH1_CMSG_AUTH_RSA,
  4015. PKT_BIGNUM, s->key.modulus, PKT_END);
  4016. crWaitUntil(pktin);
  4017. if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
  4018. logevent("Key refused");
  4019. continue;
  4020. }
  4021. logevent("Received RSA challenge");
  4022. if ((s->challenge = ssh1_pkt_getmp(pktin)) == NULL) {
  4023. bombout(("Server's RSA challenge was badly formatted"));
  4024. crStop(0);
  4025. }
  4026. {
  4027. char *agentreq, *q, *ret;
  4028. void *vret;
  4029. int len, retlen;
  4030. len = 1 + 4; /* message type, bit count */
  4031. len += ssh1_bignum_length(s->key.exponent);
  4032. len += ssh1_bignum_length(s->key.modulus);
  4033. len += ssh1_bignum_length(s->challenge);
  4034. len += 16; /* session id */
  4035. len += 4; /* response format */
  4036. agentreq = snewn(4 + len, char);
  4037. PUT_32BIT(agentreq, len);
  4038. q = agentreq + 4;
  4039. *q++ = SSH1_AGENTC_RSA_CHALLENGE;
  4040. PUT_32BIT(q, bignum_bitcount(s->key.modulus));
  4041. q += 4;
  4042. q += ssh1_write_bignum(q, s->key.exponent);
  4043. q += ssh1_write_bignum(q, s->key.modulus);
  4044. q += ssh1_write_bignum(q, s->challenge);
  4045. memcpy(q, s->session_id, 16);
  4046. q += 16;
  4047. PUT_32BIT(q, 1); /* response format */
  4048. if (!agent_query(agentreq, len + 4, &vret, &retlen,
  4049. ssh_agent_callback, ssh)) {
  4050. sfree(agentreq);
  4051. do {
  4052. crReturn(0);
  4053. if (pktin) {
  4054. bombout(("Unexpected data from server"
  4055. " while waiting for agent"
  4056. " response"));
  4057. crStop(0);
  4058. }
  4059. } while (pktin || inlen > 0);
  4060. vret = ssh->agent_response;
  4061. retlen = ssh->agent_response_len;
  4062. } else
  4063. sfree(agentreq);
  4064. ret = vret;
  4065. if (ret) {
  4066. if (ret[4] == SSH1_AGENT_RSA_RESPONSE) {
  4067. logevent("Sending Pageant's response");
  4068. send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
  4069. PKT_DATA, ret + 5, 16,
  4070. PKT_END);
  4071. sfree(ret);
  4072. crWaitUntil(pktin);
  4073. if (pktin->type == SSH1_SMSG_SUCCESS) {
  4074. logevent
  4075. ("Pageant's response accepted");
  4076. if (flags & FLAG_VERBOSE) {
  4077. c_write_str(ssh, "Authenticated using"
  4078. " RSA key \"");
  4079. c_write(ssh, s->commentp,
  4080. s->commentlen);
  4081. c_write_str(ssh, "\" from agent\r\n");
  4082. }
  4083. s->authed = TRUE;
  4084. } else
  4085. logevent
  4086. ("Pageant's response not accepted");
  4087. } else {
  4088. logevent
  4089. ("Pageant failed to answer challenge");
  4090. sfree(ret);
  4091. }
  4092. } else {
  4093. logevent("No reply received from Pageant");
  4094. }
  4095. }
  4096. freebn(s->key.exponent);
  4097. freebn(s->key.modulus);
  4098. freebn(s->challenge);
  4099. if (s->authed)
  4100. break;
  4101. }
  4102. sfree(s->response);
  4103. if (s->publickey_blob && !s->tried_publickey)
  4104. logevent("Configured key file not in Pageant");
  4105. } else {
  4106. logevent("Failed to get reply from Pageant");
  4107. }
  4108. if (s->authed)
  4109. break;
  4110. }
  4111. if (s->publickey_blob && s->privatekey_available &&
  4112. !s->tried_publickey) {
  4113. /*
  4114. * Try public key authentication with the specified
  4115. * key file.
  4116. */
  4117. int got_passphrase; /* need not be kept over crReturn */
  4118. if (flags & FLAG_VERBOSE)
  4119. c_write_str(ssh, "Trying public key authentication.\r\n");
  4120. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  4121. logeventf(ssh, "Trying public key \"%s\"",
  4122. filename_to_str(s->keyfile));
  4123. s->tried_publickey = 1;
  4124. got_passphrase = FALSE;
  4125. while (!got_passphrase) {
  4126. /*
  4127. * Get a passphrase, if necessary.
  4128. */
  4129. char *passphrase = NULL; /* only written after crReturn */
  4130. const char *error;
  4131. if (!s->privatekey_encrypted) {
  4132. if (flags & FLAG_VERBOSE)
  4133. c_write_str(ssh, "No passphrase required.\r\n");
  4134. passphrase = NULL;
  4135. } else {
  4136. int ret; /* need not be kept over crReturn */
  4137. s->cur_prompt = new_prompts(ssh->frontend);
  4138. s->cur_prompt->to_server = FALSE;
  4139. s->cur_prompt->name = dupstr("SSH key passphrase");
  4140. add_prompt(s->cur_prompt,
  4141. dupprintf("Passphrase for key \"%.100s\": ",
  4142. s->publickey_comment), FALSE);
  4143. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  4144. while (ret < 0) {
  4145. ssh->send_ok = 1;
  4146. crWaitUntil(!pktin);
  4147. ret = get_userpass_input(s->cur_prompt, in, inlen);
  4148. ssh->send_ok = 0;
  4149. }
  4150. if (!ret) {
  4151. /* Failed to get a passphrase. Terminate. */
  4152. free_prompts(s->cur_prompt);
  4153. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  4154. 0, TRUE);
  4155. crStop(0);
  4156. }
  4157. passphrase = dupstr(s->cur_prompt->prompts[0]->result);
  4158. free_prompts(s->cur_prompt);
  4159. }
  4160. /*
  4161. * Try decrypting key with passphrase.
  4162. */
  4163. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  4164. ret = loadrsakey(s->keyfile, &s->key, passphrase,
  4165. &error);
  4166. if (passphrase) {
  4167. smemclr(passphrase, strlen(passphrase));
  4168. sfree(passphrase);
  4169. }
  4170. if (ret == 1) {
  4171. /* Correct passphrase. */
  4172. got_passphrase = TRUE;
  4173. } else if (ret == 0) {
  4174. c_write_str(ssh, "Couldn't load private key from ");
  4175. c_write_str(ssh, filename_to_str(s->keyfile));
  4176. c_write_str(ssh, " (");
  4177. c_write_str(ssh, error);
  4178. c_write_str(ssh, ").\r\n");
  4179. got_passphrase = FALSE;
  4180. break; /* go and try something else */
  4181. } else if (ret == -1) {
  4182. c_write_str(ssh, "Wrong passphrase.\r\n"); /* FIXME */
  4183. got_passphrase = FALSE;
  4184. /* and try again */
  4185. } else {
  4186. assert(0 && "unexpected return from loadrsakey()");
  4187. got_passphrase = FALSE; /* placate optimisers */
  4188. }
  4189. }
  4190. if (got_passphrase) {
  4191. /*
  4192. * Send a public key attempt.
  4193. */
  4194. send_packet(ssh, SSH1_CMSG_AUTH_RSA,
  4195. PKT_BIGNUM, s->key.modulus, PKT_END);
  4196. crWaitUntil(pktin);
  4197. if (pktin->type == SSH1_SMSG_FAILURE) {
  4198. c_write_str(ssh, "Server refused our public key.\r\n");
  4199. continue; /* go and try something else */
  4200. }
  4201. if (pktin->type != SSH1_SMSG_AUTH_RSA_CHALLENGE) {
  4202. bombout(("Bizarre response to offer of public key"));
  4203. crStop(0);
  4204. }
  4205. {
  4206. int i;
  4207. unsigned char buffer[32];
  4208. Bignum challenge, response;
  4209. if ((challenge = ssh1_pkt_getmp(pktin)) == NULL) {
  4210. bombout(("Server's RSA challenge was badly formatted"));
  4211. crStop(0);
  4212. }
  4213. response = rsadecrypt(challenge, &s->key);
  4214. freebn(s->key.private_exponent);/* burn the evidence */
  4215. for (i = 0; i < 32; i++) {
  4216. buffer[i] = bignum_byte(response, 31 - i);
  4217. }
  4218. MD5Init(&md5c);
  4219. MD5Update(&md5c, buffer, 32);
  4220. MD5Update(&md5c, s->session_id, 16);
  4221. MD5Final(buffer, &md5c);
  4222. send_packet(ssh, SSH1_CMSG_AUTH_RSA_RESPONSE,
  4223. PKT_DATA, buffer, 16, PKT_END);
  4224. freebn(challenge);
  4225. freebn(response);
  4226. }
  4227. crWaitUntil(pktin);
  4228. if (pktin->type == SSH1_SMSG_FAILURE) {
  4229. if (flags & FLAG_VERBOSE)
  4230. c_write_str(ssh, "Failed to authenticate with"
  4231. " our public key.\r\n");
  4232. continue; /* go and try something else */
  4233. } else if (pktin->type != SSH1_SMSG_SUCCESS) {
  4234. bombout(("Bizarre response to RSA authentication response"));
  4235. crStop(0);
  4236. }
  4237. break; /* we're through! */
  4238. }
  4239. }
  4240. /*
  4241. * Otherwise, try various forms of password-like authentication.
  4242. */
  4243. s->cur_prompt = new_prompts(ssh->frontend);
  4244. if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
  4245. (s->supported_auths_mask & (1 << SSH1_AUTH_TIS)) &&
  4246. !s->tis_auth_refused) {
  4247. s->pwpkt_type = SSH1_CMSG_AUTH_TIS_RESPONSE;
  4248. logevent("Requested TIS authentication");
  4249. send_packet(ssh, SSH1_CMSG_AUTH_TIS, PKT_END);
  4250. crWaitUntil(pktin);
  4251. if (pktin->type != SSH1_SMSG_AUTH_TIS_CHALLENGE) {
  4252. logevent("TIS authentication declined");
  4253. if (flags & FLAG_INTERACTIVE)
  4254. c_write_str(ssh, "TIS authentication refused.\r\n");
  4255. s->tis_auth_refused = 1;
  4256. continue;
  4257. } else {
  4258. char *challenge;
  4259. int challengelen;
  4260. char *instr_suf, *prompt;
  4261. ssh_pkt_getstring(pktin, &challenge, &challengelen);
  4262. if (!challenge) {
  4263. bombout(("TIS challenge packet was badly formed"));
  4264. crStop(0);
  4265. }
  4266. logevent("Received TIS challenge");
  4267. s->cur_prompt->to_server = TRUE;
  4268. s->cur_prompt->name = dupstr("SSH TIS authentication");
  4269. /* Prompt heuristic comes from OpenSSH */
  4270. if (memchr(challenge, '\n', challengelen)) {
  4271. instr_suf = dupstr("");
  4272. prompt = dupprintf("%.*s", challengelen, challenge);
  4273. } else {
  4274. instr_suf = dupprintf("%.*s", challengelen, challenge);
  4275. prompt = dupstr("Response: ");
  4276. }
  4277. s->cur_prompt->instruction =
  4278. dupprintf("Using TIS authentication.%s%s",
  4279. (*instr_suf) ? "\n" : "",
  4280. instr_suf);
  4281. s->cur_prompt->instr_reqd = TRUE;
  4282. add_prompt(s->cur_prompt, prompt, FALSE);
  4283. sfree(instr_suf);
  4284. }
  4285. }
  4286. if (conf_get_int(ssh->conf, CONF_try_tis_auth) &&
  4287. (s->supported_auths_mask & (1 << SSH1_AUTH_CCARD)) &&
  4288. !s->ccard_auth_refused) {
  4289. s->pwpkt_type = SSH1_CMSG_AUTH_CCARD_RESPONSE;
  4290. logevent("Requested CryptoCard authentication");
  4291. send_packet(ssh, SSH1_CMSG_AUTH_CCARD, PKT_END);
  4292. crWaitUntil(pktin);
  4293. if (pktin->type != SSH1_SMSG_AUTH_CCARD_CHALLENGE) {
  4294. logevent("CryptoCard authentication declined");
  4295. c_write_str(ssh, "CryptoCard authentication refused.\r\n");
  4296. s->ccard_auth_refused = 1;
  4297. continue;
  4298. } else {
  4299. char *challenge;
  4300. int challengelen;
  4301. char *instr_suf, *prompt;
  4302. ssh_pkt_getstring(pktin, &challenge, &challengelen);
  4303. if (!challenge) {
  4304. bombout(("CryptoCard challenge packet was badly formed"));
  4305. crStop(0);
  4306. }
  4307. logevent("Received CryptoCard challenge");
  4308. s->cur_prompt->to_server = TRUE;
  4309. s->cur_prompt->name = dupstr("SSH CryptoCard authentication");
  4310. s->cur_prompt->name_reqd = FALSE;
  4311. /* Prompt heuristic comes from OpenSSH */
  4312. if (memchr(challenge, '\n', challengelen)) {
  4313. instr_suf = dupstr("");
  4314. prompt = dupprintf("%.*s", challengelen, challenge);
  4315. } else {
  4316. instr_suf = dupprintf("%.*s", challengelen, challenge);
  4317. prompt = dupstr("Response: ");
  4318. }
  4319. s->cur_prompt->instruction =
  4320. dupprintf("Using CryptoCard authentication.%s%s",
  4321. (*instr_suf) ? "\n" : "",
  4322. instr_suf);
  4323. s->cur_prompt->instr_reqd = TRUE;
  4324. add_prompt(s->cur_prompt, prompt, FALSE);
  4325. sfree(instr_suf);
  4326. }
  4327. }
  4328. if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
  4329. if ((s->supported_auths_mask & (1 << SSH1_AUTH_PASSWORD)) == 0) {
  4330. bombout(("No supported authentication methods available"));
  4331. crStop(0);
  4332. }
  4333. s->cur_prompt->to_server = TRUE;
  4334. s->cur_prompt->name = dupstr("SSH password");
  4335. add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
  4336. ssh->username, ssh->savedhost),
  4337. FALSE);
  4338. }
  4339. /*
  4340. * Show password prompt, having first obtained it via a TIS
  4341. * or CryptoCard exchange if we're doing TIS or CryptoCard
  4342. * authentication.
  4343. */
  4344. {
  4345. int ret; /* need not be kept over crReturn */
  4346. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  4347. while (ret < 0) {
  4348. ssh->send_ok = 1;
  4349. crWaitUntil(!pktin);
  4350. ret = get_userpass_input(s->cur_prompt, in, inlen);
  4351. ssh->send_ok = 0;
  4352. }
  4353. if (!ret) {
  4354. /*
  4355. * Failed to get a password (for example
  4356. * because one was supplied on the command line
  4357. * which has already failed to work). Terminate.
  4358. */
  4359. free_prompts(s->cur_prompt);
  4360. ssh_disconnect(ssh, NULL, "Unable to authenticate", 0, TRUE);
  4361. crStop(0);
  4362. }
  4363. }
  4364. if (s->pwpkt_type == SSH1_CMSG_AUTH_PASSWORD) {
  4365. /*
  4366. * Defence against traffic analysis: we send a
  4367. * whole bunch of packets containing strings of
  4368. * different lengths. One of these strings is the
  4369. * password, in a SSH1_CMSG_AUTH_PASSWORD packet.
  4370. * The others are all random data in
  4371. * SSH1_MSG_IGNORE packets. This way a passive
  4372. * listener can't tell which is the password, and
  4373. * hence can't deduce the password length.
  4374. *
  4375. * Anybody with a password length greater than 16
  4376. * bytes is going to have enough entropy in their
  4377. * password that a listener won't find it _that_
  4378. * much help to know how long it is. So what we'll
  4379. * do is:
  4380. *
  4381. * - if password length < 16, we send 15 packets
  4382. * containing string lengths 1 through 15
  4383. *
  4384. * - otherwise, we let N be the nearest multiple
  4385. * of 8 below the password length, and send 8
  4386. * packets containing string lengths N through
  4387. * N+7. This won't obscure the order of
  4388. * magnitude of the password length, but it will
  4389. * introduce a bit of extra uncertainty.
  4390. *
  4391. * A few servers can't deal with SSH1_MSG_IGNORE, at
  4392. * least in this context. For these servers, we need
  4393. * an alternative defence. We make use of the fact
  4394. * that the password is interpreted as a C string:
  4395. * so we can append a NUL, then some random data.
  4396. *
  4397. * A few servers can deal with neither SSH1_MSG_IGNORE
  4398. * here _nor_ a padded password string.
  4399. * For these servers we are left with no defences
  4400. * against password length sniffing.
  4401. */
  4402. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE) &&
  4403. !(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
  4404. /*
  4405. * The server can deal with SSH1_MSG_IGNORE, so
  4406. * we can use the primary defence.
  4407. */
  4408. int bottom, top, pwlen, i;
  4409. char *randomstr;
  4410. pwlen = strlen(s->cur_prompt->prompts[0]->result);
  4411. if (pwlen < 16) {
  4412. bottom = 0; /* zero length passwords are OK! :-) */
  4413. top = 15;
  4414. } else {
  4415. bottom = pwlen & ~7;
  4416. top = bottom + 7;
  4417. }
  4418. assert(pwlen >= bottom && pwlen <= top);
  4419. randomstr = snewn(top + 1, char);
  4420. for (i = bottom; i <= top; i++) {
  4421. if (i == pwlen) {
  4422. defer_packet(ssh, s->pwpkt_type,
  4423. PKT_STR,s->cur_prompt->prompts[0]->result,
  4424. PKT_END);
  4425. } else {
  4426. for (j = 0; j < i; j++) {
  4427. do {
  4428. randomstr[j] = random_byte();
  4429. } while (randomstr[j] == '\0');
  4430. }
  4431. randomstr[i] = '\0';
  4432. defer_packet(ssh, SSH1_MSG_IGNORE,
  4433. PKT_STR, randomstr, PKT_END);
  4434. }
  4435. }
  4436. logevent("Sending password with camouflage packets");
  4437. ssh_pkt_defersend(ssh);
  4438. sfree(randomstr);
  4439. }
  4440. else if (!(ssh->remote_bugs & BUG_NEEDS_SSH1_PLAIN_PASSWORD)) {
  4441. /*
  4442. * The server can't deal with SSH1_MSG_IGNORE
  4443. * but can deal with padded passwords, so we
  4444. * can use the secondary defence.
  4445. */
  4446. char string[64];
  4447. char *ss;
  4448. int len;
  4449. len = strlen(s->cur_prompt->prompts[0]->result);
  4450. if (len < sizeof(string)) {
  4451. ss = string;
  4452. strcpy(string, s->cur_prompt->prompts[0]->result);
  4453. len++; /* cover the zero byte */
  4454. while (len < sizeof(string)) {
  4455. string[len++] = (char) random_byte();
  4456. }
  4457. } else {
  4458. ss = s->cur_prompt->prompts[0]->result;
  4459. }
  4460. logevent("Sending length-padded password");
  4461. send_packet(ssh, s->pwpkt_type,
  4462. PKT_INT, len, PKT_DATA, ss, len,
  4463. PKT_END);
  4464. } else {
  4465. /*
  4466. * The server is believed unable to cope with
  4467. * any of our password camouflage methods.
  4468. */
  4469. int len;
  4470. len = strlen(s->cur_prompt->prompts[0]->result);
  4471. logevent("Sending unpadded password");
  4472. send_packet(ssh, s->pwpkt_type,
  4473. PKT_INT, len,
  4474. PKT_DATA, s->cur_prompt->prompts[0]->result, len,
  4475. PKT_END);
  4476. }
  4477. } else {
  4478. send_packet(ssh, s->pwpkt_type,
  4479. PKT_STR, s->cur_prompt->prompts[0]->result,
  4480. PKT_END);
  4481. }
  4482. logevent("Sent password");
  4483. free_prompts(s->cur_prompt);
  4484. crWaitUntil(pktin);
  4485. if (pktin->type == SSH1_SMSG_FAILURE) {
  4486. if (flags & FLAG_VERBOSE)
  4487. c_write_str(ssh, "Access denied\r\n");
  4488. logevent("Authentication refused");
  4489. } else if (pktin->type != SSH1_SMSG_SUCCESS) {
  4490. bombout(("Strange packet received, type %d", pktin->type));
  4491. crStop(0);
  4492. }
  4493. }
  4494. /* Clear up */
  4495. if (s->publickey_blob) {
  4496. sfree(s->publickey_blob);
  4497. sfree(s->publickey_comment);
  4498. }
  4499. logevent("Authentication successful");
  4500. crFinish(1);
  4501. }
  4502. static void ssh_channel_try_eof(struct ssh_channel *c)
  4503. {
  4504. Ssh ssh = c->ssh;
  4505. assert(c->pending_eof); /* precondition for calling us */
  4506. if (c->halfopen)
  4507. return; /* can't close: not even opened yet */
  4508. if (ssh->version == 2 && bufchain_size(&c->v.v2.outbuffer) > 0)
  4509. return; /* can't send EOF: pending outgoing data */
  4510. c->pending_eof = FALSE; /* we're about to send it */
  4511. if (ssh->version == 1) {
  4512. send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
  4513. PKT_END);
  4514. c->closes |= CLOSES_SENT_EOF;
  4515. } else {
  4516. struct Packet *pktout;
  4517. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_EOF);
  4518. ssh2_pkt_adduint32(pktout, c->remoteid);
  4519. ssh2_pkt_send(ssh, pktout);
  4520. c->closes |= CLOSES_SENT_EOF;
  4521. ssh2_channel_check_close(c);
  4522. }
  4523. }
  4524. Conf *sshfwd_get_conf(struct ssh_channel *c)
  4525. {
  4526. Ssh ssh = c->ssh;
  4527. return ssh->conf;
  4528. }
  4529. void sshfwd_write_eof(struct ssh_channel *c)
  4530. {
  4531. Ssh ssh = c->ssh;
  4532. if (ssh->state == SSH_STATE_CLOSED)
  4533. return;
  4534. if (c->closes & CLOSES_SENT_EOF)
  4535. return;
  4536. c->pending_eof = TRUE;
  4537. ssh_channel_try_eof(c);
  4538. }
  4539. void sshfwd_unclean_close(struct ssh_channel *c, const char *err)
  4540. {
  4541. Ssh ssh = c->ssh;
  4542. if (ssh->state == SSH_STATE_CLOSED)
  4543. return;
  4544. switch (c->type) {
  4545. case CHAN_X11:
  4546. x11_close(c->u.x11.xconn);
  4547. logeventf(ssh, "Forwarded X11 connection terminated due to local "
  4548. "error: %s", err);
  4549. break;
  4550. case CHAN_SOCKDATA:
  4551. case CHAN_SOCKDATA_DORMANT:
  4552. pfd_close(c->u.pfd.pf);
  4553. logeventf(ssh, "Forwarded port closed due to local error: %s", err);
  4554. break;
  4555. }
  4556. c->type = CHAN_ZOMBIE;
  4557. c->pending_eof = FALSE; /* this will confuse a zombie channel */
  4558. ssh2_channel_check_close(c);
  4559. }
  4560. int sshfwd_write(struct ssh_channel *c, char *buf, int len)
  4561. {
  4562. Ssh ssh = c->ssh;
  4563. if (ssh->state == SSH_STATE_CLOSED)
  4564. return 0;
  4565. return ssh_send_channel_data(c, buf, len);
  4566. }
  4567. void sshfwd_unthrottle(struct ssh_channel *c, int bufsize)
  4568. {
  4569. Ssh ssh = c->ssh;
  4570. int buflimit;
  4571. if (ssh->state == SSH_STATE_CLOSED)
  4572. return;
  4573. if (ssh->version == 1) {
  4574. buflimit = SSH1_BUFFER_LIMIT;
  4575. } else {
  4576. buflimit = c->v.v2.locmaxwin;
  4577. ssh2_set_window(c, bufsize < buflimit ? buflimit - bufsize : 0);
  4578. }
  4579. if (c->throttling_conn && bufsize <= buflimit) {
  4580. c->throttling_conn = 0;
  4581. ssh_throttle_conn(ssh, -1);
  4582. }
  4583. }
  4584. static void ssh_queueing_handler(Ssh ssh, struct Packet *pktin)
  4585. {
  4586. struct queued_handler *qh = ssh->qhead;
  4587. assert(qh != NULL);
  4588. assert(pktin->type == qh->msg1 || pktin->type == qh->msg2);
  4589. if (qh->msg1 > 0) {
  4590. assert(ssh->packet_dispatch[qh->msg1] == ssh_queueing_handler);
  4591. ssh->packet_dispatch[qh->msg1] = ssh->q_saved_handler1;
  4592. }
  4593. if (qh->msg2 > 0) {
  4594. assert(ssh->packet_dispatch[qh->msg2] == ssh_queueing_handler);
  4595. ssh->packet_dispatch[qh->msg2] = ssh->q_saved_handler2;
  4596. }
  4597. if (qh->next) {
  4598. ssh->qhead = qh->next;
  4599. if (ssh->qhead->msg1 > 0) {
  4600. ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
  4601. ssh->packet_dispatch[ssh->qhead->msg1] = ssh_queueing_handler;
  4602. }
  4603. if (ssh->qhead->msg2 > 0) {
  4604. ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
  4605. ssh->packet_dispatch[ssh->qhead->msg2] = ssh_queueing_handler;
  4606. }
  4607. } else {
  4608. ssh->qhead = ssh->qtail = NULL;
  4609. }
  4610. qh->handler(ssh, pktin, qh->ctx);
  4611. sfree(qh);
  4612. }
  4613. static void ssh_queue_handler(Ssh ssh, int msg1, int msg2,
  4614. chandler_fn_t handler, void *ctx)
  4615. {
  4616. struct queued_handler *qh;
  4617. qh = snew(struct queued_handler);
  4618. qh->msg1 = msg1;
  4619. qh->msg2 = msg2;
  4620. qh->handler = handler;
  4621. qh->ctx = ctx;
  4622. qh->next = NULL;
  4623. if (ssh->qtail == NULL) {
  4624. ssh->qhead = qh;
  4625. if (qh->msg1 > 0) {
  4626. ssh->q_saved_handler1 = ssh->packet_dispatch[ssh->qhead->msg1];
  4627. ssh->packet_dispatch[qh->msg1] = ssh_queueing_handler;
  4628. }
  4629. if (qh->msg2 > 0) {
  4630. ssh->q_saved_handler2 = ssh->packet_dispatch[ssh->qhead->msg2];
  4631. ssh->packet_dispatch[qh->msg2] = ssh_queueing_handler;
  4632. }
  4633. } else {
  4634. ssh->qtail->next = qh;
  4635. }
  4636. ssh->qtail = qh;
  4637. }
  4638. static void ssh_rportfwd_succfail(Ssh ssh, struct Packet *pktin, void *ctx)
  4639. {
  4640. struct ssh_rportfwd *rpf, *pf = (struct ssh_rportfwd *)ctx;
  4641. if (pktin->type == (ssh->version == 1 ? SSH1_SMSG_SUCCESS :
  4642. SSH2_MSG_REQUEST_SUCCESS)) {
  4643. logeventf(ssh, "Remote port forwarding from %s enabled",
  4644. pf->sportdesc);
  4645. } else {
  4646. logeventf(ssh, "Remote port forwarding from %s refused",
  4647. pf->sportdesc);
  4648. rpf = del234(ssh->rportfwds, pf);
  4649. assert(rpf == pf);
  4650. pf->pfrec->remote = NULL;
  4651. free_rportfwd(pf);
  4652. }
  4653. }
  4654. int ssh_alloc_sharing_rportfwd(Ssh ssh, const char *shost, int sport,
  4655. void *share_ctx)
  4656. {
  4657. struct ssh_rportfwd *pf = snew(struct ssh_rportfwd);
  4658. pf->dhost = NULL;
  4659. pf->dport = 0;
  4660. pf->share_ctx = share_ctx;
  4661. pf->shost = dupstr(shost);
  4662. pf->sport = sport;
  4663. pf->sportdesc = NULL;
  4664. if (!ssh->rportfwds) {
  4665. assert(ssh->version == 2);
  4666. ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
  4667. }
  4668. if (add234(ssh->rportfwds, pf) != pf) {
  4669. sfree(pf->shost);
  4670. sfree(pf);
  4671. return FALSE;
  4672. }
  4673. return TRUE;
  4674. }
  4675. static void ssh_sharing_global_request_response(Ssh ssh, struct Packet *pktin,
  4676. void *ctx)
  4677. {
  4678. share_got_pkt_from_server(ctx, pktin->type,
  4679. pktin->body, pktin->length);
  4680. }
  4681. void ssh_sharing_queue_global_request(Ssh ssh, void *share_ctx)
  4682. {
  4683. ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS, SSH2_MSG_REQUEST_FAILURE,
  4684. ssh_sharing_global_request_response, share_ctx);
  4685. }
  4686. static void ssh_setup_portfwd(Ssh ssh, Conf *conf)
  4687. {
  4688. struct ssh_portfwd *epf;
  4689. int i;
  4690. char *key, *val;
  4691. if (!ssh->portfwds) {
  4692. ssh->portfwds = newtree234(ssh_portcmp);
  4693. } else {
  4694. /*
  4695. * Go through the existing port forwardings and tag them
  4696. * with status==DESTROY. Any that we want to keep will be
  4697. * re-enabled (status==KEEP) as we go through the
  4698. * configuration and find out which bits are the same as
  4699. * they were before.
  4700. */
  4701. struct ssh_portfwd *epf;
  4702. int i;
  4703. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  4704. epf->status = DESTROY;
  4705. }
  4706. for (val = conf_get_str_strs(conf, CONF_portfwd, NULL, &key);
  4707. val != NULL;
  4708. val = conf_get_str_strs(conf, CONF_portfwd, key, &key)) {
  4709. char *kp, *kp2, *vp, *vp2;
  4710. char address_family, type;
  4711. int sport,dport,sserv,dserv;
  4712. char *sports, *dports, *saddr, *host;
  4713. kp = key;
  4714. address_family = 'A';
  4715. type = 'L';
  4716. if (*kp == 'A' || *kp == '4' || *kp == '6')
  4717. address_family = *kp++;
  4718. if (*kp == 'L' || *kp == 'R')
  4719. type = *kp++;
  4720. if ((kp2 = host_strchr(kp, ':')) != NULL) {
  4721. /*
  4722. * There's a colon in the middle of the source port
  4723. * string, which means that the part before it is
  4724. * actually a source address.
  4725. */
  4726. char *saddr_tmp = dupprintf("%.*s", (int)(kp2 - kp), kp);
  4727. saddr = host_strduptrim(saddr_tmp);
  4728. sfree(saddr_tmp);
  4729. sports = kp2+1;
  4730. } else {
  4731. saddr = NULL;
  4732. sports = kp;
  4733. }
  4734. sport = atoi(sports);
  4735. sserv = 0;
  4736. if (sport == 0) {
  4737. sserv = 1;
  4738. sport = net_service_lookup(sports);
  4739. if (!sport) {
  4740. logeventf(ssh, "Service lookup failed for source"
  4741. " port \"%s\"", sports);
  4742. }
  4743. }
  4744. if (type == 'L' && !strcmp(val, "D")) {
  4745. /* dynamic forwarding */
  4746. host = NULL;
  4747. dports = NULL;
  4748. dport = -1;
  4749. dserv = 0;
  4750. type = 'D';
  4751. } else {
  4752. /* ordinary forwarding */
  4753. vp = val;
  4754. vp2 = vp + host_strcspn(vp, ":");
  4755. host = dupprintf("%.*s", (int)(vp2 - vp), vp);
  4756. if (*vp2)
  4757. vp2++;
  4758. dports = vp2;
  4759. dport = atoi(dports);
  4760. dserv = 0;
  4761. if (dport == 0) {
  4762. dserv = 1;
  4763. dport = net_service_lookup(dports);
  4764. if (!dport) {
  4765. logeventf(ssh, "Service lookup failed for destination"
  4766. " port \"%s\"", dports);
  4767. }
  4768. }
  4769. }
  4770. if (sport && dport) {
  4771. /* Set up a description of the source port. */
  4772. struct ssh_portfwd *pfrec, *epfrec;
  4773. pfrec = snew(struct ssh_portfwd);
  4774. pfrec->type = type;
  4775. pfrec->saddr = saddr;
  4776. pfrec->sserv = sserv ? dupstr(sports) : NULL;
  4777. pfrec->sport = sport;
  4778. pfrec->daddr = host;
  4779. pfrec->dserv = dserv ? dupstr(dports) : NULL;
  4780. pfrec->dport = dport;
  4781. pfrec->local = NULL;
  4782. pfrec->remote = NULL;
  4783. pfrec->addressfamily = (address_family == '4' ? ADDRTYPE_IPV4 :
  4784. address_family == '6' ? ADDRTYPE_IPV6 :
  4785. ADDRTYPE_UNSPEC);
  4786. epfrec = add234(ssh->portfwds, pfrec);
  4787. if (epfrec != pfrec) {
  4788. if (epfrec->status == DESTROY) {
  4789. /*
  4790. * We already have a port forwarding up and running
  4791. * with precisely these parameters. Hence, no need
  4792. * to do anything; simply re-tag the existing one
  4793. * as KEEP.
  4794. */
  4795. epfrec->status = KEEP;
  4796. }
  4797. /*
  4798. * Anything else indicates that there was a duplicate
  4799. * in our input, which we'll silently ignore.
  4800. */
  4801. free_portfwd(pfrec);
  4802. } else {
  4803. pfrec->status = CREATE;
  4804. }
  4805. } else {
  4806. sfree(saddr);
  4807. sfree(host);
  4808. }
  4809. }
  4810. /*
  4811. * Now go through and destroy any port forwardings which were
  4812. * not re-enabled.
  4813. */
  4814. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  4815. if (epf->status == DESTROY) {
  4816. char *message;
  4817. message = dupprintf("%s port forwarding from %s%s%d",
  4818. epf->type == 'L' ? "local" :
  4819. epf->type == 'R' ? "remote" : "dynamic",
  4820. epf->saddr ? epf->saddr : "",
  4821. epf->saddr ? ":" : "",
  4822. epf->sport);
  4823. if (epf->type != 'D') {
  4824. char *msg2 = dupprintf("%s to %s:%d", message,
  4825. epf->daddr, epf->dport);
  4826. sfree(message);
  4827. message = msg2;
  4828. }
  4829. logeventf(ssh, "Cancelling %s", message);
  4830. sfree(message);
  4831. /* epf->remote or epf->local may be NULL if setting up a
  4832. * forwarding failed. */
  4833. if (epf->remote) {
  4834. struct ssh_rportfwd *rpf = epf->remote;
  4835. struct Packet *pktout;
  4836. /*
  4837. * Cancel the port forwarding at the server
  4838. * end.
  4839. */
  4840. if (ssh->version == 1) {
  4841. /*
  4842. * We cannot cancel listening ports on the
  4843. * server side in SSH-1! There's no message
  4844. * to support it. Instead, we simply remove
  4845. * the rportfwd record from the local end
  4846. * so that any connections the server tries
  4847. * to make on it are rejected.
  4848. */
  4849. } else {
  4850. pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
  4851. ssh2_pkt_addstring(pktout, "cancel-tcpip-forward");
  4852. ssh2_pkt_addbool(pktout, 0);/* _don't_ want reply */
  4853. if (epf->saddr) {
  4854. ssh2_pkt_addstring(pktout, epf->saddr);
  4855. } else if (conf_get_int(conf, CONF_rport_acceptall)) {
  4856. /* XXX: rport_acceptall may not represent
  4857. * what was used to open the original connection,
  4858. * since it's reconfigurable. */
  4859. ssh2_pkt_addstring(pktout, "");
  4860. } else {
  4861. ssh2_pkt_addstring(pktout, "localhost");
  4862. }
  4863. ssh2_pkt_adduint32(pktout, epf->sport);
  4864. ssh2_pkt_send(ssh, pktout);
  4865. }
  4866. del234(ssh->rportfwds, rpf);
  4867. free_rportfwd(rpf);
  4868. } else if (epf->local) {
  4869. pfl_terminate(epf->local);
  4870. }
  4871. delpos234(ssh->portfwds, i);
  4872. free_portfwd(epf);
  4873. i--; /* so we don't skip one in the list */
  4874. }
  4875. /*
  4876. * And finally, set up any new port forwardings (status==CREATE).
  4877. */
  4878. for (i = 0; (epf = index234(ssh->portfwds, i)) != NULL; i++)
  4879. if (epf->status == CREATE) {
  4880. char *sportdesc, *dportdesc;
  4881. sportdesc = dupprintf("%s%s%s%s%d%s",
  4882. epf->saddr ? epf->saddr : "",
  4883. epf->saddr ? ":" : "",
  4884. epf->sserv ? epf->sserv : "",
  4885. epf->sserv ? "(" : "",
  4886. epf->sport,
  4887. epf->sserv ? ")" : "");
  4888. if (epf->type == 'D') {
  4889. dportdesc = NULL;
  4890. } else {
  4891. dportdesc = dupprintf("%s:%s%s%d%s",
  4892. epf->daddr,
  4893. epf->dserv ? epf->dserv : "",
  4894. epf->dserv ? "(" : "",
  4895. epf->dport,
  4896. epf->dserv ? ")" : "");
  4897. }
  4898. if (epf->type == 'L') {
  4899. char *err = pfl_listen(epf->daddr, epf->dport,
  4900. epf->saddr, epf->sport,
  4901. ssh, conf, &epf->local,
  4902. epf->addressfamily);
  4903. logeventf(ssh, "Local %sport %s forwarding to %s%s%s",
  4904. epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
  4905. epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
  4906. sportdesc, dportdesc,
  4907. err ? " failed: " : "", err ? err : "");
  4908. if (err)
  4909. sfree(err);
  4910. } else if (epf->type == 'D') {
  4911. char *err = pfl_listen(NULL, -1, epf->saddr, epf->sport,
  4912. ssh, conf, &epf->local,
  4913. epf->addressfamily);
  4914. logeventf(ssh, "Local %sport %s SOCKS dynamic forwarding%s%s",
  4915. epf->addressfamily == ADDRTYPE_IPV4 ? "IPv4 " :
  4916. epf->addressfamily == ADDRTYPE_IPV6 ? "IPv6 " : "",
  4917. sportdesc,
  4918. err ? " failed: " : "", err ? err : "");
  4919. if (err)
  4920. sfree(err);
  4921. } else {
  4922. struct ssh_rportfwd *pf;
  4923. /*
  4924. * Ensure the remote port forwardings tree exists.
  4925. */
  4926. if (!ssh->rportfwds) {
  4927. if (ssh->version == 1)
  4928. ssh->rportfwds = newtree234(ssh_rportcmp_ssh1);
  4929. else
  4930. ssh->rportfwds = newtree234(ssh_rportcmp_ssh2);
  4931. }
  4932. pf = snew(struct ssh_rportfwd);
  4933. pf->share_ctx = NULL;
  4934. pf->dhost = dupstr(epf->daddr);
  4935. pf->dport = epf->dport;
  4936. if (epf->saddr) {
  4937. pf->shost = dupstr(epf->saddr);
  4938. } else if (conf_get_int(conf, CONF_rport_acceptall)) {
  4939. pf->shost = dupstr("");
  4940. } else {
  4941. pf->shost = dupstr("localhost");
  4942. }
  4943. pf->sport = epf->sport;
  4944. if (add234(ssh->rportfwds, pf) != pf) {
  4945. logeventf(ssh, "Duplicate remote port forwarding to %s:%d",
  4946. epf->daddr, epf->dport);
  4947. sfree(pf);
  4948. } else {
  4949. logeventf(ssh, "Requesting remote port %s"
  4950. " forward to %s", sportdesc, dportdesc);
  4951. pf->sportdesc = sportdesc;
  4952. sportdesc = NULL;
  4953. epf->remote = pf;
  4954. pf->pfrec = epf;
  4955. if (ssh->version == 1) {
  4956. send_packet(ssh, SSH1_CMSG_PORT_FORWARD_REQUEST,
  4957. PKT_INT, epf->sport,
  4958. PKT_STR, epf->daddr,
  4959. PKT_INT, epf->dport,
  4960. PKT_END);
  4961. ssh_queue_handler(ssh, SSH1_SMSG_SUCCESS,
  4962. SSH1_SMSG_FAILURE,
  4963. ssh_rportfwd_succfail, pf);
  4964. } else {
  4965. struct Packet *pktout;
  4966. pktout = ssh2_pkt_init(SSH2_MSG_GLOBAL_REQUEST);
  4967. ssh2_pkt_addstring(pktout, "tcpip-forward");
  4968. ssh2_pkt_addbool(pktout, 1);/* want reply */
  4969. ssh2_pkt_addstring(pktout, pf->shost);
  4970. ssh2_pkt_adduint32(pktout, pf->sport);
  4971. ssh2_pkt_send(ssh, pktout);
  4972. ssh_queue_handler(ssh, SSH2_MSG_REQUEST_SUCCESS,
  4973. SSH2_MSG_REQUEST_FAILURE,
  4974. ssh_rportfwd_succfail, pf);
  4975. }
  4976. }
  4977. }
  4978. sfree(sportdesc);
  4979. sfree(dportdesc);
  4980. }
  4981. }
  4982. static void ssh1_smsg_stdout_stderr_data(Ssh ssh, struct Packet *pktin)
  4983. {
  4984. char *string;
  4985. int stringlen, bufsize;
  4986. ssh_pkt_getstring(pktin, &string, &stringlen);
  4987. if (string == NULL) {
  4988. bombout(("Incoming terminal data packet was badly formed"));
  4989. return;
  4990. }
  4991. bufsize = from_backend(ssh->frontend, pktin->type == SSH1_SMSG_STDERR_DATA,
  4992. string, stringlen);
  4993. if (!ssh->v1_stdout_throttling && bufsize > SSH1_BUFFER_LIMIT) {
  4994. ssh->v1_stdout_throttling = 1;
  4995. ssh_throttle_conn(ssh, +1);
  4996. }
  4997. }
  4998. static void ssh1_smsg_x11_open(Ssh ssh, struct Packet *pktin)
  4999. {
  5000. /* Remote side is trying to open a channel to talk to our
  5001. * X-Server. Give them back a local channel number. */
  5002. struct ssh_channel *c;
  5003. int remoteid = ssh_pkt_getuint32(pktin);
  5004. logevent("Received X11 connect request");
  5005. /* Refuse if X11 forwarding is disabled. */
  5006. if (!ssh->X11_fwd_enabled) {
  5007. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5008. PKT_INT, remoteid, PKT_END);
  5009. logevent("Rejected X11 connect request");
  5010. } else {
  5011. c = snew(struct ssh_channel);
  5012. c->ssh = ssh;
  5013. c->u.x11.xconn = x11_init(ssh->x11authtree, c, NULL, -1);
  5014. c->remoteid = remoteid;
  5015. c->halfopen = FALSE;
  5016. c->localid = alloc_channel_id(ssh);
  5017. c->closes = 0;
  5018. c->pending_eof = FALSE;
  5019. c->throttling_conn = 0;
  5020. c->type = CHAN_X11; /* identify channel type */
  5021. add234(ssh->channels, c);
  5022. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  5023. PKT_INT, c->remoteid, PKT_INT,
  5024. c->localid, PKT_END);
  5025. logevent("Opened X11 forward channel");
  5026. }
  5027. }
  5028. static void ssh1_smsg_agent_open(Ssh ssh, struct Packet *pktin)
  5029. {
  5030. /* Remote side is trying to open a channel to talk to our
  5031. * agent. Give them back a local channel number. */
  5032. struct ssh_channel *c;
  5033. int remoteid = ssh_pkt_getuint32(pktin);
  5034. /* Refuse if agent forwarding is disabled. */
  5035. if (!ssh->agentfwd_enabled) {
  5036. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5037. PKT_INT, remoteid, PKT_END);
  5038. } else {
  5039. c = snew(struct ssh_channel);
  5040. c->ssh = ssh;
  5041. c->remoteid = remoteid;
  5042. c->halfopen = FALSE;
  5043. c->localid = alloc_channel_id(ssh);
  5044. c->closes = 0;
  5045. c->pending_eof = FALSE;
  5046. c->throttling_conn = 0;
  5047. c->type = CHAN_AGENT; /* identify channel type */
  5048. c->u.a.lensofar = 0;
  5049. c->u.a.message = NULL;
  5050. c->u.a.outstanding_requests = 0;
  5051. add234(ssh->channels, c);
  5052. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  5053. PKT_INT, c->remoteid, PKT_INT, c->localid,
  5054. PKT_END);
  5055. }
  5056. }
  5057. static void ssh1_msg_port_open(Ssh ssh, struct Packet *pktin)
  5058. {
  5059. /* Remote side is trying to open a channel to talk to a
  5060. * forwarded port. Give them back a local channel number. */
  5061. struct ssh_rportfwd pf, *pfp;
  5062. int remoteid;
  5063. int hostsize, port;
  5064. char *host;
  5065. char *err;
  5066. remoteid = ssh_pkt_getuint32(pktin);
  5067. ssh_pkt_getstring(pktin, &host, &hostsize);
  5068. port = ssh_pkt_getuint32(pktin);
  5069. pf.dhost = dupprintf("%.*s", hostsize, NULLTOEMPTY(host));
  5070. pf.dport = port;
  5071. pfp = find234(ssh->rportfwds, &pf, NULL);
  5072. if (pfp == NULL) {
  5073. logeventf(ssh, "Rejected remote port open request for %s:%d",
  5074. pf.dhost, port);
  5075. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5076. PKT_INT, remoteid, PKT_END);
  5077. } else {
  5078. struct ssh_channel *c = snew(struct ssh_channel);
  5079. c->ssh = ssh;
  5080. logeventf(ssh, "Received remote port open request for %s:%d",
  5081. pf.dhost, port);
  5082. err = pfd_connect(&c->u.pfd.pf, pf.dhost, port,
  5083. c, ssh->conf, pfp->pfrec->addressfamily);
  5084. if (err != NULL) {
  5085. logeventf(ssh, "Port open failed: %s", err);
  5086. sfree(err);
  5087. sfree(c);
  5088. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_FAILURE,
  5089. PKT_INT, remoteid, PKT_END);
  5090. } else {
  5091. c->remoteid = remoteid;
  5092. c->halfopen = FALSE;
  5093. c->localid = alloc_channel_id(ssh);
  5094. c->closes = 0;
  5095. c->pending_eof = FALSE;
  5096. c->throttling_conn = 0;
  5097. c->type = CHAN_SOCKDATA; /* identify channel type */
  5098. add234(ssh->channels, c);
  5099. send_packet(ssh, SSH1_MSG_CHANNEL_OPEN_CONFIRMATION,
  5100. PKT_INT, c->remoteid, PKT_INT,
  5101. c->localid, PKT_END);
  5102. logevent("Forwarded port opened successfully");
  5103. }
  5104. }
  5105. sfree(pf.dhost);
  5106. }
  5107. static void ssh1_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
  5108. {
  5109. unsigned int remoteid = ssh_pkt_getuint32(pktin);
  5110. unsigned int localid = ssh_pkt_getuint32(pktin);
  5111. struct ssh_channel *c;
  5112. c = find234(ssh->channels, &remoteid, ssh_channelfind);
  5113. if (c && c->type == CHAN_SOCKDATA_DORMANT) {
  5114. c->remoteid = localid;
  5115. c->halfopen = FALSE;
  5116. c->type = CHAN_SOCKDATA;
  5117. c->throttling_conn = 0;
  5118. pfd_confirm(c->u.pfd.pf);
  5119. }
  5120. if (c && c->pending_eof) {
  5121. /*
  5122. * We have a pending close on this channel,
  5123. * which we decided on before the server acked
  5124. * the channel open. So now we know the
  5125. * remoteid, we can close it again.
  5126. */
  5127. ssh_channel_try_eof(c);
  5128. }
  5129. }
  5130. static void ssh1_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
  5131. {
  5132. unsigned int remoteid = ssh_pkt_getuint32(pktin);
  5133. struct ssh_channel *c;
  5134. c = find234(ssh->channels, &remoteid, ssh_channelfind);
  5135. if (c && c->type == CHAN_SOCKDATA_DORMANT) {
  5136. logevent("Forwarded connection refused by server");
  5137. pfd_close(c->u.pfd.pf);
  5138. del234(ssh->channels, c);
  5139. sfree(c);
  5140. }
  5141. }
  5142. static void ssh1_msg_channel_close(Ssh ssh, struct Packet *pktin)
  5143. {
  5144. /* Remote side closes a channel. */
  5145. unsigned i = ssh_pkt_getuint32(pktin);
  5146. struct ssh_channel *c;
  5147. c = find234(ssh->channels, &i, ssh_channelfind);
  5148. if (c && !c->halfopen) {
  5149. if (pktin->type == SSH1_MSG_CHANNEL_CLOSE &&
  5150. !(c->closes & CLOSES_RCVD_EOF)) {
  5151. /*
  5152. * Received CHANNEL_CLOSE, which we translate into
  5153. * outgoing EOF.
  5154. */
  5155. int send_close = FALSE;
  5156. c->closes |= CLOSES_RCVD_EOF;
  5157. switch (c->type) {
  5158. case CHAN_X11:
  5159. if (c->u.x11.xconn)
  5160. x11_send_eof(c->u.x11.xconn);
  5161. else
  5162. send_close = TRUE;
  5163. break;
  5164. case CHAN_SOCKDATA:
  5165. if (c->u.pfd.pf)
  5166. pfd_send_eof(c->u.pfd.pf);
  5167. else
  5168. send_close = TRUE;
  5169. break;
  5170. case CHAN_AGENT:
  5171. send_close = TRUE;
  5172. break;
  5173. }
  5174. if (send_close && !(c->closes & CLOSES_SENT_EOF)) {
  5175. send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE, PKT_INT, c->remoteid,
  5176. PKT_END);
  5177. c->closes |= CLOSES_SENT_EOF;
  5178. }
  5179. }
  5180. if (pktin->type == SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION &&
  5181. !(c->closes & CLOSES_RCVD_CLOSE)) {
  5182. if (!(c->closes & CLOSES_SENT_EOF)) {
  5183. bombout(("Received CHANNEL_CLOSE_CONFIRMATION for channel %d"
  5184. " for which we never sent CHANNEL_CLOSE\n", i));
  5185. }
  5186. c->closes |= CLOSES_RCVD_CLOSE;
  5187. }
  5188. if (!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) &&
  5189. !(c->closes & CLOSES_SENT_CLOSE)) {
  5190. send_packet(ssh, SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION,
  5191. PKT_INT, c->remoteid, PKT_END);
  5192. c->closes |= CLOSES_SENT_CLOSE;
  5193. }
  5194. if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes))
  5195. ssh_channel_destroy(c);
  5196. } else {
  5197. bombout(("Received CHANNEL_CLOSE%s for %s channel %d\n",
  5198. pktin->type == SSH1_MSG_CHANNEL_CLOSE ? "" :
  5199. "_CONFIRMATION", c ? "half-open" : "nonexistent",
  5200. i));
  5201. }
  5202. }
  5203. /*
  5204. * Handle incoming data on an SSH-1 or SSH-2 agent-forwarding channel.
  5205. */
  5206. static int ssh_agent_channel_data(struct ssh_channel *c, char *data,
  5207. int length)
  5208. {
  5209. while (length > 0) {
  5210. if (c->u.a.lensofar < 4) {
  5211. unsigned int l = min(4 - c->u.a.lensofar, (unsigned)length);
  5212. memcpy(c->u.a.msglen + c->u.a.lensofar, data, l);
  5213. data += l;
  5214. length -= l;
  5215. c->u.a.lensofar += l;
  5216. }
  5217. if (c->u.a.lensofar == 4) {
  5218. c->u.a.totallen = 4 + GET_32BIT(c->u.a.msglen);
  5219. c->u.a.message = snewn(c->u.a.totallen, unsigned char);
  5220. memcpy(c->u.a.message, c->u.a.msglen, 4);
  5221. }
  5222. if (c->u.a.lensofar >= 4 && length > 0) {
  5223. unsigned int l = min(c->u.a.totallen - c->u.a.lensofar,
  5224. (unsigned)length);
  5225. memcpy(c->u.a.message + c->u.a.lensofar, data, l);
  5226. data += l;
  5227. length -= l;
  5228. c->u.a.lensofar += l;
  5229. }
  5230. if (c->u.a.lensofar == c->u.a.totallen) {
  5231. void *reply;
  5232. int replylen;
  5233. c->u.a.outstanding_requests++;
  5234. if (agent_query(c->u.a.message, c->u.a.totallen, &reply, &replylen,
  5235. ssh_agentf_callback, c))
  5236. ssh_agentf_callback(c, reply, replylen);
  5237. sfree(c->u.a.message);
  5238. c->u.a.message = NULL;
  5239. c->u.a.lensofar = 0;
  5240. }
  5241. }
  5242. return 0; /* agent channels never back up */
  5243. }
  5244. static void ssh1_msg_channel_data(Ssh ssh, struct Packet *pktin)
  5245. {
  5246. /* Data sent down one of our channels. */
  5247. int i = ssh_pkt_getuint32(pktin);
  5248. char *p;
  5249. int len;
  5250. struct ssh_channel *c;
  5251. ssh_pkt_getstring(pktin, &p, &len);
  5252. c = find234(ssh->channels, &i, ssh_channelfind);
  5253. if (c) {
  5254. int bufsize = 0;
  5255. switch (c->type) {
  5256. case CHAN_X11:
  5257. bufsize = x11_send(c->u.x11.xconn, p, len);
  5258. break;
  5259. case CHAN_SOCKDATA:
  5260. bufsize = pfd_send(c->u.pfd.pf, p, len);
  5261. break;
  5262. case CHAN_AGENT:
  5263. bufsize = ssh_agent_channel_data(c, p, len);
  5264. break;
  5265. }
  5266. if (!c->throttling_conn && bufsize > SSH1_BUFFER_LIMIT) {
  5267. c->throttling_conn = 1;
  5268. ssh_throttle_conn(ssh, +1);
  5269. }
  5270. }
  5271. }
  5272. static void ssh1_smsg_exit_status(Ssh ssh, struct Packet *pktin)
  5273. {
  5274. ssh->exitcode = ssh_pkt_getuint32(pktin);
  5275. logeventf(ssh, "Server sent command exit status %d", ssh->exitcode);
  5276. send_packet(ssh, SSH1_CMSG_EXIT_CONFIRMATION, PKT_END);
  5277. /*
  5278. * In case `helpful' firewalls or proxies tack
  5279. * extra human-readable text on the end of the
  5280. * session which we might mistake for another
  5281. * encrypted packet, we close the session once
  5282. * we've sent EXIT_CONFIRMATION.
  5283. */
  5284. ssh_disconnect(ssh, NULL, NULL, 0, TRUE);
  5285. }
  5286. /* Helper function to deal with sending tty modes for REQUEST_PTY */
  5287. static void ssh1_send_ttymode(void *data,
  5288. const struct ssh_ttymode *mode, char *val)
  5289. {
  5290. struct Packet *pktout = (struct Packet *)data;
  5291. unsigned int arg = 0;
  5292. switch (mode->type) {
  5293. case TTY_OP_CHAR:
  5294. arg = ssh_tty_parse_specchar(val);
  5295. break;
  5296. case TTY_OP_BOOL:
  5297. arg = ssh_tty_parse_boolean(val);
  5298. break;
  5299. }
  5300. ssh2_pkt_addbyte(pktout, mode->opcode);
  5301. ssh2_pkt_addbyte(pktout, arg);
  5302. }
  5303. int ssh_agent_forwarding_permitted(Ssh ssh)
  5304. {
  5305. return conf_get_int(ssh->conf, CONF_agentfwd) && agent_exists();
  5306. }
  5307. static void do_ssh1_connection(Ssh ssh, const unsigned char *in, int inlen,
  5308. struct Packet *pktin)
  5309. {
  5310. crBegin(ssh->do_ssh1_connection_crstate);
  5311. ssh->packet_dispatch[SSH1_SMSG_STDOUT_DATA] =
  5312. ssh->packet_dispatch[SSH1_SMSG_STDERR_DATA] =
  5313. ssh1_smsg_stdout_stderr_data;
  5314. ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_CONFIRMATION] =
  5315. ssh1_msg_channel_open_confirmation;
  5316. ssh->packet_dispatch[SSH1_MSG_CHANNEL_OPEN_FAILURE] =
  5317. ssh1_msg_channel_open_failure;
  5318. ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE] =
  5319. ssh->packet_dispatch[SSH1_MSG_CHANNEL_CLOSE_CONFIRMATION] =
  5320. ssh1_msg_channel_close;
  5321. ssh->packet_dispatch[SSH1_MSG_CHANNEL_DATA] = ssh1_msg_channel_data;
  5322. ssh->packet_dispatch[SSH1_SMSG_EXIT_STATUS] = ssh1_smsg_exit_status;
  5323. if (ssh_agent_forwarding_permitted(ssh)) {
  5324. logevent("Requesting agent forwarding");
  5325. send_packet(ssh, SSH1_CMSG_AGENT_REQUEST_FORWARDING, PKT_END);
  5326. do {
  5327. crReturnV;
  5328. } while (!pktin);
  5329. if (pktin->type != SSH1_SMSG_SUCCESS
  5330. && pktin->type != SSH1_SMSG_FAILURE) {
  5331. bombout(("Protocol confusion"));
  5332. crStopV;
  5333. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5334. logevent("Agent forwarding refused");
  5335. } else {
  5336. logevent("Agent forwarding enabled");
  5337. ssh->agentfwd_enabled = TRUE;
  5338. ssh->packet_dispatch[SSH1_SMSG_AGENT_OPEN] = ssh1_smsg_agent_open;
  5339. }
  5340. }
  5341. if (conf_get_int(ssh->conf, CONF_x11_forward)) {
  5342. ssh->x11disp =
  5343. x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
  5344. ssh->conf);
  5345. if (!ssh->x11disp) {
  5346. /* FIXME: return an error message from x11_setup_display */
  5347. logevent("X11 forwarding not enabled: unable to"
  5348. " initialise X display");
  5349. } else {
  5350. ssh->x11auth = x11_invent_fake_auth
  5351. (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
  5352. ssh->x11auth->disp = ssh->x11disp;
  5353. logevent("Requesting X11 forwarding");
  5354. if (ssh->v1_local_protoflags & SSH1_PROTOFLAG_SCREEN_NUMBER) {
  5355. send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
  5356. PKT_STR, ssh->x11auth->protoname,
  5357. PKT_STR, ssh->x11auth->datastring,
  5358. PKT_INT, ssh->x11disp->screennum,
  5359. PKT_END);
  5360. } else {
  5361. send_packet(ssh, SSH1_CMSG_X11_REQUEST_FORWARDING,
  5362. PKT_STR, ssh->x11auth->protoname,
  5363. PKT_STR, ssh->x11auth->datastring,
  5364. PKT_END);
  5365. }
  5366. do {
  5367. crReturnV;
  5368. } while (!pktin);
  5369. if (pktin->type != SSH1_SMSG_SUCCESS
  5370. && pktin->type != SSH1_SMSG_FAILURE) {
  5371. bombout(("Protocol confusion"));
  5372. crStopV;
  5373. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5374. logevent("X11 forwarding refused");
  5375. } else {
  5376. logevent("X11 forwarding enabled");
  5377. ssh->X11_fwd_enabled = TRUE;
  5378. ssh->packet_dispatch[SSH1_SMSG_X11_OPEN] = ssh1_smsg_x11_open;
  5379. }
  5380. }
  5381. }
  5382. ssh_setup_portfwd(ssh, ssh->conf);
  5383. ssh->packet_dispatch[SSH1_MSG_PORT_OPEN] = ssh1_msg_port_open;
  5384. if (!conf_get_int(ssh->conf, CONF_nopty)) {
  5385. struct Packet *pkt;
  5386. /* Unpick the terminal-speed string. */
  5387. /* XXX perhaps we should allow no speeds to be sent. */
  5388. ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
  5389. sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
  5390. /* Send the pty request. */
  5391. pkt = ssh1_pkt_init(SSH1_CMSG_REQUEST_PTY);
  5392. ssh_pkt_addstring(pkt, conf_get_str(ssh->conf, CONF_termtype));
  5393. ssh_pkt_adduint32(pkt, ssh->term_height);
  5394. ssh_pkt_adduint32(pkt, ssh->term_width);
  5395. ssh_pkt_adduint32(pkt, 0); /* width in pixels */
  5396. ssh_pkt_adduint32(pkt, 0); /* height in pixels */
  5397. parse_ttymodes(ssh, ssh1_send_ttymode, (void *)pkt);
  5398. ssh_pkt_addbyte(pkt, SSH1_TTY_OP_ISPEED);
  5399. ssh_pkt_adduint32(pkt, ssh->ispeed);
  5400. ssh_pkt_addbyte(pkt, SSH1_TTY_OP_OSPEED);
  5401. ssh_pkt_adduint32(pkt, ssh->ospeed);
  5402. ssh_pkt_addbyte(pkt, SSH_TTY_OP_END);
  5403. s_wrpkt(ssh, pkt);
  5404. ssh->state = SSH_STATE_INTERMED;
  5405. do {
  5406. crReturnV;
  5407. } while (!pktin);
  5408. if (pktin->type != SSH1_SMSG_SUCCESS
  5409. && pktin->type != SSH1_SMSG_FAILURE) {
  5410. bombout(("Protocol confusion"));
  5411. crStopV;
  5412. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5413. c_write_str(ssh, "Server refused to allocate pty\r\n");
  5414. ssh->editing = ssh->echoing = 1;
  5415. } else {
  5416. logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
  5417. ssh->ospeed, ssh->ispeed);
  5418. ssh->got_pty = TRUE;
  5419. }
  5420. } else {
  5421. ssh->editing = ssh->echoing = 1;
  5422. }
  5423. if (conf_get_int(ssh->conf, CONF_compression)) {
  5424. send_packet(ssh, SSH1_CMSG_REQUEST_COMPRESSION, PKT_INT, 6, PKT_END);
  5425. do {
  5426. crReturnV;
  5427. } while (!pktin);
  5428. if (pktin->type != SSH1_SMSG_SUCCESS
  5429. && pktin->type != SSH1_SMSG_FAILURE) {
  5430. bombout(("Protocol confusion"));
  5431. crStopV;
  5432. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5433. c_write_str(ssh, "Server refused to compress\r\n");
  5434. }
  5435. logevent("Started compression");
  5436. ssh->v1_compressing = TRUE;
  5437. ssh->cs_comp_ctx = zlib_compress_init();
  5438. logevent("Initialised zlib (RFC1950) compression");
  5439. ssh->sc_comp_ctx = zlib_decompress_init();
  5440. logevent("Initialised zlib (RFC1950) decompression");
  5441. }
  5442. /*
  5443. * Start the shell or command.
  5444. *
  5445. * Special case: if the first-choice command is an SSH-2
  5446. * subsystem (hence not usable here) and the second choice
  5447. * exists, we fall straight back to that.
  5448. */
  5449. {
  5450. char *cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
  5451. if (conf_get_int(ssh->conf, CONF_ssh_subsys) &&
  5452. conf_get_str(ssh->conf, CONF_remote_cmd2)) {
  5453. cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
  5454. ssh->fallback_cmd = TRUE;
  5455. }
  5456. if (*cmd)
  5457. send_packet(ssh, SSH1_CMSG_EXEC_CMD, PKT_STR, cmd, PKT_END);
  5458. else
  5459. send_packet(ssh, SSH1_CMSG_EXEC_SHELL, PKT_END);
  5460. logevent("Started session");
  5461. }
  5462. ssh->state = SSH_STATE_SESSION;
  5463. if (ssh->size_needed)
  5464. ssh_size(ssh, ssh->term_width, ssh->term_height);
  5465. if (ssh->eof_needed)
  5466. ssh_special(ssh, TS_EOF);
  5467. if (ssh->ldisc)
  5468. ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
  5469. ssh->send_ok = 1;
  5470. ssh->channels = newtree234(ssh_channelcmp);
  5471. while (1) {
  5472. /*
  5473. * By this point, most incoming packets are already being
  5474. * handled by the dispatch table, and we need only pay
  5475. * attention to the unusual ones.
  5476. */
  5477. crReturnV;
  5478. if (pktin) {
  5479. if (pktin->type == SSH1_SMSG_SUCCESS) {
  5480. /* may be from EXEC_SHELL on some servers */
  5481. } else if (pktin->type == SSH1_SMSG_FAILURE) {
  5482. /* may be from EXEC_SHELL on some servers
  5483. * if no pty is available or in other odd cases. Ignore */
  5484. } else {
  5485. bombout(("Strange packet received: type %d", pktin->type));
  5486. crStopV;
  5487. }
  5488. } else {
  5489. while (inlen > 0) {
  5490. int len = min(inlen, 512);
  5491. send_packet(ssh, SSH1_CMSG_STDIN_DATA,
  5492. PKT_INT, len, PKT_DATA, in, len,
  5493. PKT_END);
  5494. in += len;
  5495. inlen -= len;
  5496. }
  5497. }
  5498. }
  5499. crFinishV;
  5500. }
  5501. /*
  5502. * Handle the top-level SSH-2 protocol.
  5503. */
  5504. static void ssh1_msg_debug(Ssh ssh, struct Packet *pktin)
  5505. {
  5506. char *msg;
  5507. int msglen;
  5508. ssh_pkt_getstring(pktin, &msg, &msglen);
  5509. logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
  5510. }
  5511. static void ssh1_msg_disconnect(Ssh ssh, struct Packet *pktin)
  5512. {
  5513. /* log reason code in disconnect message */
  5514. char *msg;
  5515. int msglen;
  5516. ssh_pkt_getstring(pktin, &msg, &msglen);
  5517. bombout(("Server sent disconnect message:\n\"%.*s\"",
  5518. msglen, NULLTOEMPTY(msg)));
  5519. }
  5520. static void ssh_msg_ignore(Ssh ssh, struct Packet *pktin)
  5521. {
  5522. /* Do nothing, because we're ignoring it! Duhh. */
  5523. }
  5524. static void ssh1_protocol_setup(Ssh ssh)
  5525. {
  5526. int i;
  5527. /*
  5528. * Most messages are handled by the coroutines.
  5529. */
  5530. for (i = 0; i < 256; i++)
  5531. ssh->packet_dispatch[i] = NULL;
  5532. /*
  5533. * These special message types we install handlers for.
  5534. */
  5535. ssh->packet_dispatch[SSH1_MSG_DISCONNECT] = ssh1_msg_disconnect;
  5536. ssh->packet_dispatch[SSH1_MSG_IGNORE] = ssh_msg_ignore;
  5537. ssh->packet_dispatch[SSH1_MSG_DEBUG] = ssh1_msg_debug;
  5538. }
  5539. static void ssh1_protocol(Ssh ssh, const void *vin, int inlen,
  5540. struct Packet *pktin)
  5541. {
  5542. const unsigned char *in = (const unsigned char *)vin;
  5543. if (ssh->state == SSH_STATE_CLOSED)
  5544. return;
  5545. if (pktin && ssh->packet_dispatch[pktin->type]) {
  5546. ssh->packet_dispatch[pktin->type](ssh, pktin);
  5547. return;
  5548. }
  5549. if (!ssh->protocol_initial_phase_done) {
  5550. if (do_ssh1_login(ssh, in, inlen, pktin))
  5551. ssh->protocol_initial_phase_done = TRUE;
  5552. else
  5553. return;
  5554. }
  5555. do_ssh1_connection(ssh, in, inlen, pktin);
  5556. }
  5557. /*
  5558. * Utility routines for decoding comma-separated strings in KEXINIT.
  5559. */
  5560. static int first_in_commasep_string(char const *needle, char const *haystack,
  5561. int haylen)
  5562. {
  5563. int needlen;
  5564. if (!needle || !haystack) /* protect against null pointers */
  5565. return 0;
  5566. needlen = strlen(needle);
  5567. if (haylen >= needlen && /* haystack is long enough */
  5568. !memcmp(needle, haystack, needlen) && /* initial match */
  5569. (haylen == needlen || haystack[needlen] == ',')
  5570. /* either , or EOS follows */
  5571. )
  5572. return 1;
  5573. return 0;
  5574. }
  5575. static int in_commasep_string(char const *needle, char const *haystack,
  5576. int haylen)
  5577. {
  5578. char *p;
  5579. if (!needle || !haystack) /* protect against null pointers */
  5580. return 0;
  5581. /*
  5582. * Is it at the start of the string?
  5583. */
  5584. if (first_in_commasep_string(needle, haystack, haylen))
  5585. return 1;
  5586. /*
  5587. * If not, search for the next comma and resume after that.
  5588. * If no comma found, terminate.
  5589. */
  5590. p = memchr(haystack, ',', haylen);
  5591. if (!p) return 0;
  5592. /* + 1 to skip over comma */
  5593. return in_commasep_string(needle, p + 1, haylen - (p + 1 - haystack));
  5594. }
  5595. /*
  5596. * Add a value to the comma-separated string at the end of the packet.
  5597. */
  5598. static void ssh2_pkt_addstring_commasep(struct Packet *pkt, const char *data)
  5599. {
  5600. if (pkt->length - pkt->savedpos > 0)
  5601. ssh_pkt_addstring_str(pkt, ",");
  5602. ssh_pkt_addstring_str(pkt, data);
  5603. }
  5604. /*
  5605. * SSH-2 key derivation (RFC 4253 section 7.2).
  5606. */
  5607. static unsigned char *ssh2_mkkey(Ssh ssh, Bignum K, unsigned char *H,
  5608. char chr, int keylen)
  5609. {
  5610. const struct ssh_hash *h = ssh->kex->hash;
  5611. int keylen_padded;
  5612. unsigned char *key;
  5613. void *s, *s2;
  5614. if (keylen == 0)
  5615. return NULL;
  5616. /* Round up to the next multiple of hash length. */
  5617. keylen_padded = ((keylen + h->hlen - 1) / h->hlen) * h->hlen;
  5618. key = snewn(keylen_padded, unsigned char);
  5619. /* First hlen bytes. */
  5620. s = h->init();
  5621. if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
  5622. hash_mpint(h, s, K);
  5623. h->bytes(s, H, h->hlen);
  5624. h->bytes(s, &chr, 1);
  5625. h->bytes(s, ssh->v2_session_id, ssh->v2_session_id_len);
  5626. h->final(s, key);
  5627. /* Subsequent blocks of hlen bytes. */
  5628. if (keylen_padded > h->hlen) {
  5629. int offset;
  5630. s = h->init();
  5631. if (!(ssh->remote_bugs & BUG_SSH2_DERIVEKEY))
  5632. hash_mpint(h, s, K);
  5633. h->bytes(s, H, h->hlen);
  5634. for (offset = h->hlen; offset < keylen_padded; offset += h->hlen) {
  5635. h->bytes(s, key + offset - h->hlen, h->hlen);
  5636. s2 = h->copy(s);
  5637. h->final(s2, key + offset);
  5638. }
  5639. h->free(s);
  5640. }
  5641. /* Now clear any extra bytes of key material beyond the length
  5642. * we're officially returning, because the caller won't know to
  5643. * smemclr those. */
  5644. if (keylen_padded > keylen)
  5645. smemclr(key + keylen, keylen_padded - keylen);
  5646. return key;
  5647. }
  5648. /*
  5649. * Structure for constructing KEXINIT algorithm lists.
  5650. */
  5651. #define MAXKEXLIST 16
  5652. struct kexinit_algorithm {
  5653. const char *name;
  5654. union {
  5655. struct {
  5656. const struct ssh_kex *kex;
  5657. int warn;
  5658. } kex;
  5659. struct {
  5660. const struct ssh_signkey *hostkey;
  5661. int warn;
  5662. } hk;
  5663. struct {
  5664. const struct ssh2_cipher *cipher;
  5665. int warn;
  5666. } cipher;
  5667. struct {
  5668. const struct ssh_mac *mac;
  5669. int etm;
  5670. } mac;
  5671. const struct ssh_compress *comp;
  5672. } u;
  5673. };
  5674. /*
  5675. * Find a slot in a KEXINIT algorithm list to use for a new algorithm.
  5676. * If the algorithm is already in the list, return a pointer to its
  5677. * entry, otherwise return an entry from the end of the list.
  5678. * This assumes that every time a particular name is passed in, it
  5679. * comes from the same string constant. If this isn't true, this
  5680. * function may need to be rewritten to use strcmp() instead.
  5681. */
  5682. static struct kexinit_algorithm *ssh2_kexinit_addalg(struct kexinit_algorithm
  5683. *list, const char *name)
  5684. {
  5685. int i;
  5686. for (i = 0; i < MAXKEXLIST; i++)
  5687. if (list[i].name == NULL || list[i].name == name) {
  5688. list[i].name = name;
  5689. return &list[i];
  5690. }
  5691. assert(!"No space in KEXINIT list");
  5692. return NULL;
  5693. }
  5694. /*
  5695. * Handle the SSH-2 transport layer.
  5696. */
  5697. static void do_ssh2_transport(Ssh ssh, const void *vin, int inlen,
  5698. struct Packet *pktin)
  5699. {
  5700. const unsigned char *in = (const unsigned char *)vin;
  5701. enum kexlist {
  5702. KEXLIST_KEX, KEXLIST_HOSTKEY, KEXLIST_CSCIPHER, KEXLIST_SCCIPHER,
  5703. KEXLIST_CSMAC, KEXLIST_SCMAC, KEXLIST_CSCOMP, KEXLIST_SCCOMP,
  5704. NKEXLIST
  5705. };
  5706. const char * kexlist_descr[NKEXLIST] = {
  5707. "key exchange algorithm", "host key algorithm",
  5708. "client-to-server cipher", "server-to-client cipher",
  5709. "client-to-server MAC", "server-to-client MAC",
  5710. "client-to-server compression method",
  5711. "server-to-client compression method" };
  5712. struct do_ssh2_transport_state {
  5713. int crLine;
  5714. int nbits, pbits, warn_kex, warn_hk, warn_cscipher, warn_sccipher;
  5715. Bignum p, g, e, f, K;
  5716. void *our_kexinit;
  5717. int our_kexinitlen;
  5718. int kex_init_value, kex_reply_value;
  5719. const struct ssh_mac *const *maclist;
  5720. int nmacs;
  5721. const struct ssh2_cipher *cscipher_tobe;
  5722. const struct ssh2_cipher *sccipher_tobe;
  5723. const struct ssh_mac *csmac_tobe;
  5724. const struct ssh_mac *scmac_tobe;
  5725. int csmac_etm_tobe, scmac_etm_tobe;
  5726. const struct ssh_compress *cscomp_tobe;
  5727. const struct ssh_compress *sccomp_tobe;
  5728. char *hostkeydata, *sigdata, *rsakeydata, *keystr, *fingerprint;
  5729. int hostkeylen, siglen, rsakeylen;
  5730. void *hkey; /* actual host key */
  5731. void *rsakey; /* for RSA kex */
  5732. void *eckey; /* for ECDH kex */
  5733. unsigned char exchange_hash[SSH2_KEX_MAX_HASH_LEN];
  5734. int n_preferred_kex;
  5735. const struct ssh_kexes *preferred_kex[KEX_MAX];
  5736. int n_preferred_hk;
  5737. int preferred_hk[HK_MAX];
  5738. int n_preferred_ciphers;
  5739. const struct ssh2_ciphers *preferred_ciphers[CIPHER_MAX];
  5740. const struct ssh_compress *preferred_comp;
  5741. int userauth_succeeded; /* for delayed compression */
  5742. int pending_compression;
  5743. int got_session_id, activated_authconn;
  5744. struct Packet *pktout;
  5745. int dlgret;
  5746. int guessok;
  5747. int ignorepkt;
  5748. struct kexinit_algorithm kexlists[NKEXLIST][MAXKEXLIST];
  5749. };
  5750. crState(do_ssh2_transport_state);
  5751. assert(!ssh->bare_connection);
  5752. assert(ssh->version == 2);
  5753. crBeginState;
  5754. s->cscipher_tobe = s->sccipher_tobe = NULL;
  5755. s->csmac_tobe = s->scmac_tobe = NULL;
  5756. s->cscomp_tobe = s->sccomp_tobe = NULL;
  5757. s->got_session_id = s->activated_authconn = FALSE;
  5758. s->userauth_succeeded = FALSE;
  5759. s->pending_compression = FALSE;
  5760. /*
  5761. * Be prepared to work around the buggy MAC problem.
  5762. */
  5763. if (ssh->remote_bugs & BUG_SSH2_HMAC)
  5764. s->maclist = buggymacs, s->nmacs = lenof(buggymacs);
  5765. else
  5766. s->maclist = macs, s->nmacs = lenof(macs);
  5767. begin_key_exchange:
  5768. ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
  5769. {
  5770. int i, j, k, warn;
  5771. struct kexinit_algorithm *alg;
  5772. /*
  5773. * Set up the preferred key exchange. (NULL => warn below here)
  5774. */
  5775. s->n_preferred_kex = 0;
  5776. for (i = 0; i < KEX_MAX; i++) {
  5777. switch (conf_get_int_int(ssh->conf, CONF_ssh_kexlist, i)) {
  5778. case KEX_DHGEX:
  5779. s->preferred_kex[s->n_preferred_kex++] =
  5780. &ssh_diffiehellman_gex;
  5781. break;
  5782. case KEX_DHGROUP14:
  5783. s->preferred_kex[s->n_preferred_kex++] =
  5784. &ssh_diffiehellman_group14;
  5785. break;
  5786. case KEX_DHGROUP1:
  5787. s->preferred_kex[s->n_preferred_kex++] =
  5788. &ssh_diffiehellman_group1;
  5789. break;
  5790. case KEX_RSA:
  5791. s->preferred_kex[s->n_preferred_kex++] =
  5792. &ssh_rsa_kex;
  5793. break;
  5794. case KEX_ECDH:
  5795. s->preferred_kex[s->n_preferred_kex++] =
  5796. &ssh_ecdh_kex;
  5797. break;
  5798. case KEX_WARN:
  5799. /* Flag for later. Don't bother if it's the last in
  5800. * the list. */
  5801. if (i < KEX_MAX - 1) {
  5802. s->preferred_kex[s->n_preferred_kex++] = NULL;
  5803. }
  5804. break;
  5805. }
  5806. }
  5807. /*
  5808. * Set up the preferred host key types. These are just the ids
  5809. * in the enum in putty.h, so 'warn below here' is indicated
  5810. * by HK_WARN.
  5811. */
  5812. s->n_preferred_hk = 0;
  5813. for (i = 0; i < HK_MAX; i++) {
  5814. int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, i);
  5815. /* As above, don't bother with HK_WARN if it's last in the
  5816. * list */
  5817. if (id != HK_WARN || i < HK_MAX - 1)
  5818. s->preferred_hk[s->n_preferred_hk++] = id;
  5819. }
  5820. /*
  5821. * Set up the preferred ciphers. (NULL => warn below here)
  5822. */
  5823. s->n_preferred_ciphers = 0;
  5824. for (i = 0; i < CIPHER_MAX; i++) {
  5825. switch (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i)) {
  5826. case CIPHER_BLOWFISH:
  5827. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_blowfish;
  5828. break;
  5829. case CIPHER_DES:
  5830. if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc)) {
  5831. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_des;
  5832. }
  5833. break;
  5834. case CIPHER_3DES:
  5835. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_3des;
  5836. break;
  5837. case CIPHER_AES:
  5838. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_aes;
  5839. break;
  5840. case CIPHER_ARCFOUR:
  5841. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_arcfour;
  5842. break;
  5843. case CIPHER_CHACHA20:
  5844. s->preferred_ciphers[s->n_preferred_ciphers++] = &ssh2_ccp;
  5845. break;
  5846. case CIPHER_WARN:
  5847. /* Flag for later. Don't bother if it's the last in
  5848. * the list. */
  5849. if (i < CIPHER_MAX - 1) {
  5850. s->preferred_ciphers[s->n_preferred_ciphers++] = NULL;
  5851. }
  5852. break;
  5853. }
  5854. }
  5855. /*
  5856. * Set up preferred compression.
  5857. */
  5858. if (conf_get_int(ssh->conf, CONF_compression))
  5859. s->preferred_comp = &ssh_zlib;
  5860. else
  5861. s->preferred_comp = &ssh_comp_none;
  5862. /*
  5863. * Enable queueing of outgoing auth- or connection-layer
  5864. * packets while we are in the middle of a key exchange.
  5865. */
  5866. ssh->queueing = TRUE;
  5867. /*
  5868. * Flag that KEX is in progress.
  5869. */
  5870. ssh->kex_in_progress = TRUE;
  5871. for (i = 0; i < NKEXLIST; i++)
  5872. for (j = 0; j < MAXKEXLIST; j++)
  5873. s->kexlists[i][j].name = NULL;
  5874. /* List key exchange algorithms. */
  5875. warn = FALSE;
  5876. for (i = 0; i < s->n_preferred_kex; i++) {
  5877. const struct ssh_kexes *k = s->preferred_kex[i];
  5878. if (!k) warn = TRUE;
  5879. else for (j = 0; j < k->nkexes; j++) {
  5880. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_KEX],
  5881. k->list[j]->name);
  5882. alg->u.kex.kex = k->list[j];
  5883. alg->u.kex.warn = warn;
  5884. }
  5885. }
  5886. /* List server host key algorithms. */
  5887. if (!s->got_session_id) {
  5888. /*
  5889. * In the first key exchange, we list all the algorithms
  5890. * we're prepared to cope with, but prefer those algorithms
  5891. * for which we have a host key for this host.
  5892. *
  5893. * If the host key algorithm is below the warning
  5894. * threshold, we warn even if we did already have a key
  5895. * for it, on the basis that if the user has just
  5896. * reconfigured that host key type to be warned about,
  5897. * they surely _do_ want to be alerted that a server
  5898. * they're actually connecting to is using it.
  5899. */
  5900. warn = FALSE;
  5901. for (i = 0; i < s->n_preferred_hk; i++) {
  5902. if (s->preferred_hk[i] == HK_WARN)
  5903. warn = TRUE;
  5904. for (j = 0; j < lenof(hostkey_algs); j++) {
  5905. if (hostkey_algs[j].id != s->preferred_hk[i])
  5906. continue;
  5907. if (have_ssh_host_key(ssh->savedhost, ssh->savedport,
  5908. hostkey_algs[j].alg->keytype)) {
  5909. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  5910. hostkey_algs[j].alg->name);
  5911. alg->u.hk.hostkey = hostkey_algs[j].alg;
  5912. alg->u.hk.warn = warn;
  5913. }
  5914. }
  5915. }
  5916. warn = FALSE;
  5917. for (i = 0; i < s->n_preferred_hk; i++) {
  5918. if (s->preferred_hk[i] == HK_WARN)
  5919. warn = TRUE;
  5920. for (j = 0; j < lenof(hostkey_algs); j++) {
  5921. if (hostkey_algs[j].id != s->preferred_hk[i])
  5922. continue;
  5923. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  5924. hostkey_algs[j].alg->name);
  5925. alg->u.hk.hostkey = hostkey_algs[j].alg;
  5926. alg->u.hk.warn = warn;
  5927. }
  5928. }
  5929. } else {
  5930. /*
  5931. * In subsequent key exchanges, we list only the kex
  5932. * algorithm that was selected in the first key exchange,
  5933. * so that we keep getting the same host key and hence
  5934. * don't have to interrupt the user's session to ask for
  5935. * reverification.
  5936. */
  5937. assert(ssh->kex);
  5938. alg = ssh2_kexinit_addalg(s->kexlists[KEXLIST_HOSTKEY],
  5939. ssh->hostkey->name);
  5940. alg->u.hk.hostkey = ssh->hostkey;
  5941. alg->u.hk.warn = FALSE;
  5942. }
  5943. /* List encryption algorithms (client->server then server->client). */
  5944. for (k = KEXLIST_CSCIPHER; k <= KEXLIST_SCCIPHER; k++) {
  5945. warn = FALSE;
  5946. #ifdef FUZZING
  5947. alg = ssh2_kexinit_addalg(s->kexlists[k], "none");
  5948. alg->u.cipher.cipher = NULL;
  5949. alg->u.cipher.warn = warn;
  5950. #endif /* FUZZING */
  5951. for (i = 0; i < s->n_preferred_ciphers; i++) {
  5952. const struct ssh2_ciphers *c = s->preferred_ciphers[i];
  5953. if (!c) warn = TRUE;
  5954. else for (j = 0; j < c->nciphers; j++) {
  5955. alg = ssh2_kexinit_addalg(s->kexlists[k],
  5956. c->list[j]->name);
  5957. alg->u.cipher.cipher = c->list[j];
  5958. alg->u.cipher.warn = warn;
  5959. }
  5960. }
  5961. }
  5962. /* List MAC algorithms (client->server then server->client). */
  5963. for (j = KEXLIST_CSMAC; j <= KEXLIST_SCMAC; j++) {
  5964. #ifdef FUZZING
  5965. alg = ssh2_kexinit_addalg(s->kexlists[j], "none");
  5966. alg->u.mac.mac = NULL;
  5967. alg->u.mac.etm = FALSE;
  5968. #endif /* FUZZING */
  5969. for (i = 0; i < s->nmacs; i++) {
  5970. alg = ssh2_kexinit_addalg(s->kexlists[j], s->maclist[i]->name);
  5971. alg->u.mac.mac = s->maclist[i];
  5972. alg->u.mac.etm = FALSE;
  5973. }
  5974. for (i = 0; i < s->nmacs; i++)
  5975. /* For each MAC, there may also be an ETM version,
  5976. * which we list second. */
  5977. if (s->maclist[i]->etm_name) {
  5978. alg = ssh2_kexinit_addalg(s->kexlists[j],
  5979. s->maclist[i]->etm_name);
  5980. alg->u.mac.mac = s->maclist[i];
  5981. alg->u.mac.etm = TRUE;
  5982. }
  5983. }
  5984. /* List client->server compression algorithms,
  5985. * then server->client compression algorithms. (We use the
  5986. * same set twice.) */
  5987. for (j = KEXLIST_CSCOMP; j <= KEXLIST_SCCOMP; j++) {
  5988. assert(lenof(compressions) > 1);
  5989. /* Prefer non-delayed versions */
  5990. alg = ssh2_kexinit_addalg(s->kexlists[j], s->preferred_comp->name);
  5991. alg->u.comp = s->preferred_comp;
  5992. /* We don't even list delayed versions of algorithms until
  5993. * they're allowed to be used, to avoid a race. See the end of
  5994. * this function. */
  5995. if (s->userauth_succeeded && s->preferred_comp->delayed_name) {
  5996. alg = ssh2_kexinit_addalg(s->kexlists[j],
  5997. s->preferred_comp->delayed_name);
  5998. alg->u.comp = s->preferred_comp;
  5999. }
  6000. for (i = 0; i < lenof(compressions); i++) {
  6001. const struct ssh_compress *c = compressions[i];
  6002. alg = ssh2_kexinit_addalg(s->kexlists[j], c->name);
  6003. alg->u.comp = c;
  6004. if (s->userauth_succeeded && c->delayed_name) {
  6005. alg = ssh2_kexinit_addalg(s->kexlists[j], c->delayed_name);
  6006. alg->u.comp = c;
  6007. }
  6008. }
  6009. }
  6010. /*
  6011. * Construct and send our key exchange packet.
  6012. */
  6013. s->pktout = ssh2_pkt_init(SSH2_MSG_KEXINIT);
  6014. for (i = 0; i < 16; i++)
  6015. ssh2_pkt_addbyte(s->pktout, (unsigned char) random_byte());
  6016. for (i = 0; i < NKEXLIST; i++) {
  6017. ssh2_pkt_addstring_start(s->pktout);
  6018. for (j = 0; j < MAXKEXLIST; j++) {
  6019. if (s->kexlists[i][j].name == NULL) break;
  6020. ssh2_pkt_addstring_commasep(s->pktout, s->kexlists[i][j].name);
  6021. }
  6022. }
  6023. /* List client->server languages. Empty list. */
  6024. ssh2_pkt_addstring_start(s->pktout);
  6025. /* List server->client languages. Empty list. */
  6026. ssh2_pkt_addstring_start(s->pktout);
  6027. /* First KEX packet does _not_ follow, because we're not that brave. */
  6028. ssh2_pkt_addbool(s->pktout, FALSE);
  6029. /* Reserved. */
  6030. ssh2_pkt_adduint32(s->pktout, 0);
  6031. }
  6032. s->our_kexinitlen = s->pktout->length - 5;
  6033. s->our_kexinit = snewn(s->our_kexinitlen, unsigned char);
  6034. memcpy(s->our_kexinit, s->pktout->data + 5, s->our_kexinitlen);
  6035. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6036. if (!pktin)
  6037. crWaitUntilV(pktin);
  6038. /*
  6039. * Now examine the other side's KEXINIT to see what we're up
  6040. * to.
  6041. */
  6042. {
  6043. char *str;
  6044. int i, j, len;
  6045. if (pktin->type != SSH2_MSG_KEXINIT) {
  6046. bombout(("expected key exchange packet from server"));
  6047. crStopV;
  6048. }
  6049. ssh->kex = NULL;
  6050. ssh->hostkey = NULL;
  6051. s->cscipher_tobe = NULL;
  6052. s->sccipher_tobe = NULL;
  6053. s->csmac_tobe = NULL;
  6054. s->scmac_tobe = NULL;
  6055. s->cscomp_tobe = NULL;
  6056. s->sccomp_tobe = NULL;
  6057. s->warn_kex = s->warn_hk = FALSE;
  6058. s->warn_cscipher = s->warn_sccipher = FALSE;
  6059. pktin->savedpos += 16; /* skip garbage cookie */
  6060. s->guessok = FALSE;
  6061. for (i = 0; i < NKEXLIST; i++) {
  6062. ssh_pkt_getstring(pktin, &str, &len);
  6063. if (!str) {
  6064. bombout(("KEXINIT packet was incomplete"));
  6065. crStopV;
  6066. }
  6067. /* If we've already selected a cipher which requires a
  6068. * particular MAC, then just select that, and don't even
  6069. * bother looking through the server's KEXINIT string for
  6070. * MACs. */
  6071. if (i == KEXLIST_CSMAC && s->cscipher_tobe &&
  6072. s->cscipher_tobe->required_mac) {
  6073. s->csmac_tobe = s->cscipher_tobe->required_mac;
  6074. s->csmac_etm_tobe = !!(s->csmac_tobe->etm_name);
  6075. goto matched;
  6076. }
  6077. if (i == KEXLIST_SCMAC && s->sccipher_tobe &&
  6078. s->sccipher_tobe->required_mac) {
  6079. s->scmac_tobe = s->sccipher_tobe->required_mac;
  6080. s->scmac_etm_tobe = !!(s->scmac_tobe->etm_name);
  6081. goto matched;
  6082. }
  6083. for (j = 0; j < MAXKEXLIST; j++) {
  6084. struct kexinit_algorithm *alg = &s->kexlists[i][j];
  6085. if (alg->name == NULL) break;
  6086. if (in_commasep_string(alg->name, str, len)) {
  6087. /* We've found a matching algorithm. */
  6088. if (i == KEXLIST_KEX || i == KEXLIST_HOSTKEY) {
  6089. /* Check if we might need to ignore first kex pkt */
  6090. if (j != 0 ||
  6091. !first_in_commasep_string(alg->name, str, len))
  6092. s->guessok = FALSE;
  6093. }
  6094. if (i == KEXLIST_KEX) {
  6095. ssh->kex = alg->u.kex.kex;
  6096. s->warn_kex = alg->u.kex.warn;
  6097. } else if (i == KEXLIST_HOSTKEY) {
  6098. ssh->hostkey = alg->u.hk.hostkey;
  6099. s->warn_hk = alg->u.hk.warn;
  6100. } else if (i == KEXLIST_CSCIPHER) {
  6101. s->cscipher_tobe = alg->u.cipher.cipher;
  6102. s->warn_cscipher = alg->u.cipher.warn;
  6103. } else if (i == KEXLIST_SCCIPHER) {
  6104. s->sccipher_tobe = alg->u.cipher.cipher;
  6105. s->warn_sccipher = alg->u.cipher.warn;
  6106. } else if (i == KEXLIST_CSMAC) {
  6107. s->csmac_tobe = alg->u.mac.mac;
  6108. s->csmac_etm_tobe = alg->u.mac.etm;
  6109. } else if (i == KEXLIST_SCMAC) {
  6110. s->scmac_tobe = alg->u.mac.mac;
  6111. s->scmac_etm_tobe = alg->u.mac.etm;
  6112. } else if (i == KEXLIST_CSCOMP) {
  6113. s->cscomp_tobe = alg->u.comp;
  6114. } else if (i == KEXLIST_SCCOMP) {
  6115. s->sccomp_tobe = alg->u.comp;
  6116. }
  6117. goto matched;
  6118. }
  6119. if ((i == KEXLIST_CSCOMP || i == KEXLIST_SCCOMP) &&
  6120. in_commasep_string(alg->u.comp->delayed_name, str, len))
  6121. s->pending_compression = TRUE; /* try this later */
  6122. }
  6123. bombout(("Couldn't agree a %s (available: %.*s)",
  6124. kexlist_descr[i], len, str));
  6125. crStopV;
  6126. matched:;
  6127. if (i == KEXLIST_HOSTKEY) {
  6128. int j;
  6129. /*
  6130. * In addition to deciding which host key we're
  6131. * actually going to use, we should make a list of the
  6132. * host keys offered by the server which we _don't_
  6133. * have cached. These will be offered as cross-
  6134. * certification options by ssh_get_specials.
  6135. *
  6136. * We also count the key we're currently using for KEX
  6137. * as one we've already got, because by the time this
  6138. * menu becomes visible, it will be.
  6139. */
  6140. ssh->n_uncert_hostkeys = 0;
  6141. for (j = 0; j < lenof(hostkey_algs); j++) {
  6142. if (hostkey_algs[j].alg != ssh->hostkey &&
  6143. in_commasep_string(hostkey_algs[j].alg->name,
  6144. str, len) &&
  6145. !have_ssh_host_key(ssh->savedhost, ssh->savedport,
  6146. hostkey_algs[j].alg->keytype)) {
  6147. ssh->uncert_hostkeys[ssh->n_uncert_hostkeys++] = j;
  6148. }
  6149. }
  6150. }
  6151. }
  6152. if (s->pending_compression) {
  6153. logevent("Server supports delayed compression; "
  6154. "will try this later");
  6155. }
  6156. ssh_pkt_getstring(pktin, &str, &len); /* client->server language */
  6157. ssh_pkt_getstring(pktin, &str, &len); /* server->client language */
  6158. s->ignorepkt = ssh2_pkt_getbool(pktin) && !s->guessok;
  6159. ssh->exhash = ssh->kex->hash->init();
  6160. hash_string(ssh->kex->hash, ssh->exhash, ssh->v_c, strlen(ssh->v_c));
  6161. hash_string(ssh->kex->hash, ssh->exhash, ssh->v_s, strlen(ssh->v_s));
  6162. hash_string(ssh->kex->hash, ssh->exhash,
  6163. s->our_kexinit, s->our_kexinitlen);
  6164. sfree(s->our_kexinit);
  6165. /* Include the type byte in the hash of server's KEXINIT */
  6166. hash_string(ssh->kex->hash, ssh->exhash,
  6167. pktin->body - 1, pktin->length + 1);
  6168. if (s->warn_kex) {
  6169. ssh_set_frozen(ssh, 1);
  6170. s->dlgret = askalg(ssh->frontend, "key-exchange algorithm",
  6171. ssh->kex->name,
  6172. ssh_dialog_callback, ssh);
  6173. if (s->dlgret < 0) {
  6174. do {
  6175. crReturnV;
  6176. if (pktin) {
  6177. bombout(("Unexpected data from server while"
  6178. " waiting for user response"));
  6179. crStopV;
  6180. }
  6181. } while (pktin || inlen > 0);
  6182. s->dlgret = ssh->user_response;
  6183. }
  6184. ssh_set_frozen(ssh, 0);
  6185. if (s->dlgret == 0) {
  6186. ssh_disconnect(ssh, "User aborted at kex warning", NULL,
  6187. 0, TRUE);
  6188. crStopV;
  6189. }
  6190. }
  6191. if (s->warn_hk) {
  6192. int j, k;
  6193. char *betteralgs;
  6194. ssh_set_frozen(ssh, 1);
  6195. /*
  6196. * Change warning box wording depending on why we chose a
  6197. * warning-level host key algorithm. If it's because
  6198. * that's all we have *cached*, use the askhk mechanism,
  6199. * and list the host keys we could usefully cross-certify.
  6200. * Otherwise, use askalg for the standard wording.
  6201. */
  6202. betteralgs = NULL;
  6203. for (j = 0; j < ssh->n_uncert_hostkeys; j++) {
  6204. const struct ssh_signkey_with_user_pref_id *hktype =
  6205. &hostkey_algs[ssh->uncert_hostkeys[j]];
  6206. int better = FALSE;
  6207. for (k = 0; k < HK_MAX; k++) {
  6208. int id = conf_get_int_int(ssh->conf, CONF_ssh_hklist, k);
  6209. if (id == HK_WARN) {
  6210. break;
  6211. } else if (id == hktype->id) {
  6212. better = TRUE;
  6213. break;
  6214. }
  6215. }
  6216. if (better) {
  6217. if (betteralgs) {
  6218. char *old_ba = betteralgs;
  6219. betteralgs = dupcat(betteralgs, ",",
  6220. hktype->alg->name,
  6221. (const char *)NULL);
  6222. sfree(old_ba);
  6223. } else {
  6224. betteralgs = dupstr(hktype->alg->name);
  6225. }
  6226. }
  6227. }
  6228. if (betteralgs) {
  6229. s->dlgret = askhk(ssh->frontend, ssh->hostkey->name,
  6230. betteralgs, ssh_dialog_callback, ssh);
  6231. sfree(betteralgs);
  6232. } else {
  6233. s->dlgret = askalg(ssh->frontend, "host key type",
  6234. ssh->hostkey->name,
  6235. ssh_dialog_callback, ssh);
  6236. }
  6237. if (s->dlgret < 0) {
  6238. do {
  6239. crReturnV;
  6240. if (pktin) {
  6241. bombout(("Unexpected data from server while"
  6242. " waiting for user response"));
  6243. crStopV;
  6244. }
  6245. } while (pktin || inlen > 0);
  6246. s->dlgret = ssh->user_response;
  6247. }
  6248. ssh_set_frozen(ssh, 0);
  6249. if (s->dlgret == 0) {
  6250. ssh_disconnect(ssh, "User aborted at host key warning", NULL,
  6251. 0, TRUE);
  6252. crStopV;
  6253. }
  6254. }
  6255. if (s->warn_cscipher) {
  6256. ssh_set_frozen(ssh, 1);
  6257. s->dlgret = askalg(ssh->frontend,
  6258. "client-to-server cipher",
  6259. s->cscipher_tobe->name,
  6260. ssh_dialog_callback, ssh);
  6261. if (s->dlgret < 0) {
  6262. do {
  6263. crReturnV;
  6264. if (pktin) {
  6265. bombout(("Unexpected data from server while"
  6266. " waiting for user response"));
  6267. crStopV;
  6268. }
  6269. } while (pktin || inlen > 0);
  6270. s->dlgret = ssh->user_response;
  6271. }
  6272. ssh_set_frozen(ssh, 0);
  6273. if (s->dlgret == 0) {
  6274. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  6275. 0, TRUE);
  6276. crStopV;
  6277. }
  6278. }
  6279. if (s->warn_sccipher) {
  6280. ssh_set_frozen(ssh, 1);
  6281. s->dlgret = askalg(ssh->frontend,
  6282. "server-to-client cipher",
  6283. s->sccipher_tobe->name,
  6284. ssh_dialog_callback, ssh);
  6285. if (s->dlgret < 0) {
  6286. do {
  6287. crReturnV;
  6288. if (pktin) {
  6289. bombout(("Unexpected data from server while"
  6290. " waiting for user response"));
  6291. crStopV;
  6292. }
  6293. } while (pktin || inlen > 0);
  6294. s->dlgret = ssh->user_response;
  6295. }
  6296. ssh_set_frozen(ssh, 0);
  6297. if (s->dlgret == 0) {
  6298. ssh_disconnect(ssh, "User aborted at cipher warning", NULL,
  6299. 0, TRUE);
  6300. crStopV;
  6301. }
  6302. }
  6303. if (s->ignorepkt) /* first_kex_packet_follows */
  6304. crWaitUntilV(pktin); /* Ignore packet */
  6305. }
  6306. if (ssh->kex->main_type == KEXTYPE_DH) {
  6307. /*
  6308. * Work out the number of bits of key we will need from the
  6309. * key exchange. We start with the maximum key length of
  6310. * either cipher...
  6311. */
  6312. {
  6313. int csbits, scbits;
  6314. csbits = s->cscipher_tobe ? s->cscipher_tobe->real_keybits : 0;
  6315. scbits = s->sccipher_tobe ? s->sccipher_tobe->real_keybits : 0;
  6316. s->nbits = (csbits > scbits ? csbits : scbits);
  6317. }
  6318. /* The keys only have hlen-bit entropy, since they're based on
  6319. * a hash. So cap the key size at hlen bits. */
  6320. if (s->nbits > ssh->kex->hash->hlen * 8)
  6321. s->nbits = ssh->kex->hash->hlen * 8;
  6322. /*
  6323. * If we're doing Diffie-Hellman group exchange, start by
  6324. * requesting a group.
  6325. */
  6326. if (dh_is_gex(ssh->kex)) {
  6327. logevent("Doing Diffie-Hellman group exchange");
  6328. ssh->pkt_kctx = SSH2_PKTCTX_DHGEX;
  6329. /*
  6330. * Work out how big a DH group we will need to allow that
  6331. * much data.
  6332. */
  6333. s->pbits = 512 << ((s->nbits - 1) / 64);
  6334. if (s->pbits < DH_MIN_SIZE)
  6335. s->pbits = DH_MIN_SIZE;
  6336. if (s->pbits > DH_MAX_SIZE)
  6337. s->pbits = DH_MAX_SIZE;
  6338. if ((ssh->remote_bugs & BUG_SSH2_OLDGEX)) {
  6339. s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST_OLD);
  6340. ssh2_pkt_adduint32(s->pktout, s->pbits);
  6341. } else {
  6342. s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_DH_GEX_REQUEST);
  6343. ssh2_pkt_adduint32(s->pktout, DH_MIN_SIZE);
  6344. ssh2_pkt_adduint32(s->pktout, s->pbits);
  6345. ssh2_pkt_adduint32(s->pktout, DH_MAX_SIZE);
  6346. }
  6347. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6348. crWaitUntilV(pktin);
  6349. if (pktin->type != SSH2_MSG_KEX_DH_GEX_GROUP) {
  6350. bombout(("expected key exchange group packet from server"));
  6351. crStopV;
  6352. }
  6353. s->p = ssh2_pkt_getmp(pktin);
  6354. s->g = ssh2_pkt_getmp(pktin);
  6355. if (!s->p || !s->g) {
  6356. bombout(("unable to read mp-ints from incoming group packet"));
  6357. crStopV;
  6358. }
  6359. ssh->kex_ctx = dh_setup_gex(s->p, s->g);
  6360. s->kex_init_value = SSH2_MSG_KEX_DH_GEX_INIT;
  6361. s->kex_reply_value = SSH2_MSG_KEX_DH_GEX_REPLY;
  6362. } else {
  6363. ssh->pkt_kctx = SSH2_PKTCTX_DHGROUP;
  6364. ssh->kex_ctx = dh_setup_group(ssh->kex);
  6365. s->kex_init_value = SSH2_MSG_KEXDH_INIT;
  6366. s->kex_reply_value = SSH2_MSG_KEXDH_REPLY;
  6367. logeventf(ssh, "Using Diffie-Hellman with standard group \"%s\"",
  6368. ssh->kex->groupname);
  6369. }
  6370. logeventf(ssh, "Doing Diffie-Hellman key exchange with hash %s",
  6371. ssh->kex->hash->text_name);
  6372. /*
  6373. * Now generate and send e for Diffie-Hellman.
  6374. */
  6375. set_busy_status(ssh->frontend, BUSY_CPU); /* this can take a while */
  6376. s->e = dh_create_e(ssh->kex_ctx, s->nbits * 2);
  6377. s->pktout = ssh2_pkt_init(s->kex_init_value);
  6378. ssh2_pkt_addmp(s->pktout, s->e);
  6379. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6380. set_busy_status(ssh->frontend, BUSY_WAITING); /* wait for server */
  6381. crWaitUntilV(pktin);
  6382. if (pktin->type != s->kex_reply_value) {
  6383. bombout(("expected key exchange reply packet from server"));
  6384. crStopV;
  6385. }
  6386. set_busy_status(ssh->frontend, BUSY_CPU); /* cogitate */
  6387. ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
  6388. if (!s->hostkeydata) {
  6389. bombout(("unable to parse key exchange reply packet"));
  6390. crStopV;
  6391. }
  6392. s->hkey = ssh->hostkey->newkey(ssh->hostkey,
  6393. s->hostkeydata, s->hostkeylen);
  6394. s->f = ssh2_pkt_getmp(pktin);
  6395. if (!s->f) {
  6396. bombout(("unable to parse key exchange reply packet"));
  6397. crStopV;
  6398. }
  6399. ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
  6400. if (!s->sigdata) {
  6401. bombout(("unable to parse key exchange reply packet"));
  6402. crStopV;
  6403. }
  6404. {
  6405. const char *err = dh_validate_f(ssh->kex_ctx, s->f);
  6406. if (err) {
  6407. bombout(("key exchange reply failed validation: %s", err));
  6408. crStopV;
  6409. }
  6410. }
  6411. s->K = dh_find_K(ssh->kex_ctx, s->f);
  6412. /* We assume everything from now on will be quick, and it might
  6413. * involve user interaction. */
  6414. set_busy_status(ssh->frontend, BUSY_NOT);
  6415. hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
  6416. if (dh_is_gex(ssh->kex)) {
  6417. if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
  6418. hash_uint32(ssh->kex->hash, ssh->exhash, DH_MIN_SIZE);
  6419. hash_uint32(ssh->kex->hash, ssh->exhash, s->pbits);
  6420. if (!(ssh->remote_bugs & BUG_SSH2_OLDGEX))
  6421. hash_uint32(ssh->kex->hash, ssh->exhash, DH_MAX_SIZE);
  6422. hash_mpint(ssh->kex->hash, ssh->exhash, s->p);
  6423. hash_mpint(ssh->kex->hash, ssh->exhash, s->g);
  6424. }
  6425. hash_mpint(ssh->kex->hash, ssh->exhash, s->e);
  6426. hash_mpint(ssh->kex->hash, ssh->exhash, s->f);
  6427. dh_cleanup(ssh->kex_ctx);
  6428. freebn(s->f);
  6429. if (dh_is_gex(ssh->kex)) {
  6430. freebn(s->g);
  6431. freebn(s->p);
  6432. }
  6433. } else if (ssh->kex->main_type == KEXTYPE_ECDH) {
  6434. logeventf(ssh, "Doing ECDH key exchange with curve %s and hash %s",
  6435. ssh_ecdhkex_curve_textname(ssh->kex),
  6436. ssh->kex->hash->text_name);
  6437. ssh->pkt_kctx = SSH2_PKTCTX_ECDHKEX;
  6438. s->eckey = ssh_ecdhkex_newkey(ssh->kex);
  6439. if (!s->eckey) {
  6440. bombout(("Unable to generate key for ECDH"));
  6441. crStopV;
  6442. }
  6443. {
  6444. char *publicPoint;
  6445. int publicPointLength;
  6446. publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
  6447. if (!publicPoint) {
  6448. ssh_ecdhkex_freekey(s->eckey);
  6449. bombout(("Unable to encode public key for ECDH"));
  6450. crStopV;
  6451. }
  6452. s->pktout = ssh2_pkt_init(SSH2_MSG_KEX_ECDH_INIT);
  6453. ssh2_pkt_addstring_start(s->pktout);
  6454. ssh2_pkt_addstring_data(s->pktout, publicPoint, publicPointLength);
  6455. sfree(publicPoint);
  6456. }
  6457. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6458. crWaitUntilV(pktin);
  6459. if (pktin->type != SSH2_MSG_KEX_ECDH_REPLY) {
  6460. ssh_ecdhkex_freekey(s->eckey);
  6461. bombout(("expected ECDH reply packet from server"));
  6462. crStopV;
  6463. }
  6464. ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
  6465. if (!s->hostkeydata) {
  6466. bombout(("unable to parse ECDH reply packet"));
  6467. crStopV;
  6468. }
  6469. hash_string(ssh->kex->hash, ssh->exhash, s->hostkeydata, s->hostkeylen);
  6470. s->hkey = ssh->hostkey->newkey(ssh->hostkey,
  6471. s->hostkeydata, s->hostkeylen);
  6472. {
  6473. char *publicPoint;
  6474. int publicPointLength;
  6475. publicPoint = ssh_ecdhkex_getpublic(s->eckey, &publicPointLength);
  6476. if (!publicPoint) {
  6477. ssh_ecdhkex_freekey(s->eckey);
  6478. bombout(("Unable to encode public key for ECDH hash"));
  6479. crStopV;
  6480. }
  6481. hash_string(ssh->kex->hash, ssh->exhash,
  6482. publicPoint, publicPointLength);
  6483. sfree(publicPoint);
  6484. }
  6485. {
  6486. char *keydata;
  6487. int keylen;
  6488. ssh_pkt_getstring(pktin, &keydata, &keylen);
  6489. if (!keydata) {
  6490. bombout(("unable to parse ECDH reply packet"));
  6491. crStopV;
  6492. }
  6493. hash_string(ssh->kex->hash, ssh->exhash, keydata, keylen);
  6494. s->K = ssh_ecdhkex_getkey(s->eckey, keydata, keylen);
  6495. if (!s->K) {
  6496. ssh_ecdhkex_freekey(s->eckey);
  6497. bombout(("point received in ECDH was not valid"));
  6498. crStopV;
  6499. }
  6500. }
  6501. ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
  6502. if (!s->sigdata) {
  6503. bombout(("unable to parse key exchange reply packet"));
  6504. crStopV;
  6505. }
  6506. ssh_ecdhkex_freekey(s->eckey);
  6507. } else {
  6508. logeventf(ssh, "Doing RSA key exchange with hash %s",
  6509. ssh->kex->hash->text_name);
  6510. ssh->pkt_kctx = SSH2_PKTCTX_RSAKEX;
  6511. /*
  6512. * RSA key exchange. First expect a KEXRSA_PUBKEY packet
  6513. * from the server.
  6514. */
  6515. crWaitUntilV(pktin);
  6516. if (pktin->type != SSH2_MSG_KEXRSA_PUBKEY) {
  6517. bombout(("expected RSA public key packet from server"));
  6518. crStopV;
  6519. }
  6520. ssh_pkt_getstring(pktin, &s->hostkeydata, &s->hostkeylen);
  6521. if (!s->hostkeydata) {
  6522. bombout(("unable to parse RSA public key packet"));
  6523. crStopV;
  6524. }
  6525. hash_string(ssh->kex->hash, ssh->exhash,
  6526. s->hostkeydata, s->hostkeylen);
  6527. s->hkey = ssh->hostkey->newkey(ssh->hostkey,
  6528. s->hostkeydata, s->hostkeylen);
  6529. {
  6530. char *keydata;
  6531. ssh_pkt_getstring(pktin, &keydata, &s->rsakeylen);
  6532. if (!keydata) {
  6533. bombout(("unable to parse RSA public key packet"));
  6534. crStopV;
  6535. }
  6536. s->rsakeydata = snewn(s->rsakeylen, char);
  6537. memcpy(s->rsakeydata, keydata, s->rsakeylen);
  6538. }
  6539. s->rsakey = ssh_rsakex_newkey(s->rsakeydata, s->rsakeylen);
  6540. if (!s->rsakey) {
  6541. sfree(s->rsakeydata);
  6542. bombout(("unable to parse RSA public key from server"));
  6543. crStopV;
  6544. }
  6545. hash_string(ssh->kex->hash, ssh->exhash, s->rsakeydata, s->rsakeylen);
  6546. /*
  6547. * Next, set up a shared secret K, of precisely KLEN -
  6548. * 2*HLEN - 49 bits, where KLEN is the bit length of the
  6549. * RSA key modulus and HLEN is the bit length of the hash
  6550. * we're using.
  6551. */
  6552. {
  6553. int klen = ssh_rsakex_klen(s->rsakey);
  6554. int nbits = klen - (2*ssh->kex->hash->hlen*8 + 49);
  6555. int i, byte = 0;
  6556. unsigned char *kstr1, *kstr2, *outstr;
  6557. int kstr1len, kstr2len, outstrlen;
  6558. s->K = bn_power_2(nbits - 1);
  6559. for (i = 0; i < nbits; i++) {
  6560. if ((i & 7) == 0) {
  6561. byte = random_byte();
  6562. }
  6563. bignum_set_bit(s->K, i, (byte >> (i & 7)) & 1);
  6564. }
  6565. /*
  6566. * Encode this as an mpint.
  6567. */
  6568. kstr1 = ssh2_mpint_fmt(s->K, &kstr1len);
  6569. kstr2 = snewn(kstr2len = 4 + kstr1len, unsigned char);
  6570. PUT_32BIT(kstr2, kstr1len);
  6571. memcpy(kstr2 + 4, kstr1, kstr1len);
  6572. /*
  6573. * Encrypt it with the given RSA key.
  6574. */
  6575. outstrlen = (klen + 7) / 8;
  6576. outstr = snewn(outstrlen, unsigned char);
  6577. ssh_rsakex_encrypt(ssh->kex->hash, kstr2, kstr2len,
  6578. outstr, outstrlen, s->rsakey);
  6579. /*
  6580. * And send it off in a return packet.
  6581. */
  6582. s->pktout = ssh2_pkt_init(SSH2_MSG_KEXRSA_SECRET);
  6583. ssh2_pkt_addstring_start(s->pktout);
  6584. ssh2_pkt_addstring_data(s->pktout, (char *)outstr, outstrlen);
  6585. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6586. hash_string(ssh->kex->hash, ssh->exhash, outstr, outstrlen);
  6587. sfree(kstr2);
  6588. sfree(kstr1);
  6589. sfree(outstr);
  6590. }
  6591. ssh_rsakex_freekey(s->rsakey);
  6592. crWaitUntilV(pktin);
  6593. if (pktin->type != SSH2_MSG_KEXRSA_DONE) {
  6594. sfree(s->rsakeydata);
  6595. bombout(("expected signature packet from server"));
  6596. crStopV;
  6597. }
  6598. ssh_pkt_getstring(pktin, &s->sigdata, &s->siglen);
  6599. if (!s->sigdata) {
  6600. bombout(("unable to parse signature packet"));
  6601. crStopV;
  6602. }
  6603. sfree(s->rsakeydata);
  6604. }
  6605. hash_mpint(ssh->kex->hash, ssh->exhash, s->K);
  6606. assert(ssh->kex->hash->hlen <= sizeof(s->exchange_hash));
  6607. ssh->kex->hash->final(ssh->exhash, s->exchange_hash);
  6608. ssh->kex_ctx = NULL;
  6609. #if 0
  6610. debug(("Exchange hash is:\n"));
  6611. dmemdump(s->exchange_hash, ssh->kex->hash->hlen);
  6612. #endif
  6613. if (!s->hkey) {
  6614. bombout(("Server's host key is invalid"));
  6615. crStopV;
  6616. }
  6617. if (!ssh->hostkey->verifysig(s->hkey, s->sigdata, s->siglen,
  6618. (char *)s->exchange_hash,
  6619. ssh->kex->hash->hlen)) {
  6620. #ifndef FUZZING
  6621. bombout(("Server's host key did not match the signature supplied"));
  6622. crStopV;
  6623. #endif
  6624. }
  6625. s->keystr = ssh->hostkey->fmtkey(s->hkey);
  6626. if (!s->got_session_id) {
  6627. /*
  6628. * Make a note of any other host key formats that are available.
  6629. */
  6630. {
  6631. int i, j, nkeys = 0;
  6632. char *list = NULL;
  6633. for (i = 0; i < lenof(hostkey_algs); i++) {
  6634. if (hostkey_algs[i].alg == ssh->hostkey)
  6635. continue;
  6636. for (j = 0; j < ssh->n_uncert_hostkeys; j++)
  6637. if (ssh->uncert_hostkeys[j] == i)
  6638. break;
  6639. if (j < ssh->n_uncert_hostkeys) {
  6640. char *newlist;
  6641. if (list)
  6642. newlist = dupprintf("%s/%s", list,
  6643. hostkey_algs[i].alg->name);
  6644. else
  6645. newlist = dupprintf("%s", hostkey_algs[i].alg->name);
  6646. sfree(list);
  6647. list = newlist;
  6648. nkeys++;
  6649. }
  6650. }
  6651. if (list) {
  6652. logeventf(ssh,
  6653. "Server also has %s host key%s, but we "
  6654. "don't know %s", list,
  6655. nkeys > 1 ? "s" : "",
  6656. nkeys > 1 ? "any of them" : "it");
  6657. sfree(list);
  6658. }
  6659. }
  6660. /*
  6661. * Authenticate remote host: verify host key. (We've already
  6662. * checked the signature of the exchange hash.)
  6663. */
  6664. s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
  6665. logevent("Host key fingerprint is:");
  6666. logevent(s->fingerprint);
  6667. /* First check against manually configured host keys. */
  6668. s->dlgret = verify_ssh_manual_host_key(ssh, s->fingerprint,
  6669. ssh->hostkey, s->hkey);
  6670. if (s->dlgret == 0) { /* did not match */
  6671. bombout(("Host key did not appear in manually configured list"));
  6672. crStopV;
  6673. } else if (s->dlgret < 0) { /* none configured; use standard handling */
  6674. ssh_set_frozen(ssh, 1);
  6675. s->dlgret = verify_ssh_host_key(ssh->frontend,
  6676. ssh->savedhost, ssh->savedport,
  6677. ssh->hostkey->keytype, s->keystr,
  6678. s->fingerprint,
  6679. ssh_dialog_callback, ssh);
  6680. #ifdef FUZZING
  6681. s->dlgret = 1;
  6682. #endif
  6683. if (s->dlgret < 0) {
  6684. do {
  6685. crReturnV;
  6686. if (pktin) {
  6687. bombout(("Unexpected data from server while waiting"
  6688. " for user host key response"));
  6689. crStopV;
  6690. }
  6691. } while (pktin || inlen > 0);
  6692. s->dlgret = ssh->user_response;
  6693. }
  6694. ssh_set_frozen(ssh, 0);
  6695. if (s->dlgret == 0) {
  6696. ssh_disconnect(ssh, "Aborted at host key verification", NULL,
  6697. 0, TRUE);
  6698. crStopV;
  6699. }
  6700. }
  6701. sfree(s->fingerprint);
  6702. /*
  6703. * Save this host key, to check against the one presented in
  6704. * subsequent rekeys.
  6705. */
  6706. ssh->hostkey_str = s->keystr;
  6707. } else if (ssh->cross_certifying) {
  6708. s->fingerprint = ssh2_fingerprint(ssh->hostkey, s->hkey);
  6709. logevent("Storing additional host key for this host:");
  6710. logevent(s->fingerprint);
  6711. store_host_key(ssh->savedhost, ssh->savedport,
  6712. ssh->hostkey->keytype, s->keystr);
  6713. ssh->cross_certifying = FALSE;
  6714. /*
  6715. * Don't forget to store the new key as the one we'll be
  6716. * re-checking in future normal rekeys.
  6717. */
  6718. ssh->hostkey_str = s->keystr;
  6719. } else {
  6720. /*
  6721. * In a rekey, we never present an interactive host key
  6722. * verification request to the user. Instead, we simply
  6723. * enforce that the key we're seeing this time is identical to
  6724. * the one we saw before.
  6725. */
  6726. if (strcmp(ssh->hostkey_str, s->keystr)) {
  6727. #ifndef FUZZING
  6728. bombout(("Host key was different in repeat key exchange"));
  6729. crStopV;
  6730. #endif
  6731. }
  6732. sfree(s->keystr);
  6733. }
  6734. ssh->hostkey->freekey(s->hkey);
  6735. /*
  6736. * The exchange hash from the very first key exchange is also
  6737. * the session id, used in session key construction and
  6738. * authentication.
  6739. */
  6740. if (!s->got_session_id) {
  6741. assert(sizeof(s->exchange_hash) <= sizeof(ssh->v2_session_id));
  6742. memcpy(ssh->v2_session_id, s->exchange_hash,
  6743. sizeof(s->exchange_hash));
  6744. ssh->v2_session_id_len = ssh->kex->hash->hlen;
  6745. assert(ssh->v2_session_id_len <= sizeof(ssh->v2_session_id));
  6746. s->got_session_id = TRUE;
  6747. }
  6748. /*
  6749. * Send SSH2_MSG_NEWKEYS.
  6750. */
  6751. s->pktout = ssh2_pkt_init(SSH2_MSG_NEWKEYS);
  6752. ssh2_pkt_send_noqueue(ssh, s->pktout);
  6753. ssh->outgoing_data_size = 0; /* start counting from here */
  6754. /*
  6755. * We've sent client NEWKEYS, so create and initialise
  6756. * client-to-server session keys.
  6757. */
  6758. if (ssh->cs_cipher_ctx)
  6759. ssh->cscipher->free_context(ssh->cs_cipher_ctx);
  6760. ssh->cscipher = s->cscipher_tobe;
  6761. if (ssh->cscipher) ssh->cs_cipher_ctx = ssh->cscipher->make_context();
  6762. if (ssh->cs_mac_ctx)
  6763. ssh->csmac->free_context(ssh->cs_mac_ctx);
  6764. ssh->csmac = s->csmac_tobe;
  6765. ssh->csmac_etm = s->csmac_etm_tobe;
  6766. if (ssh->csmac)
  6767. ssh->cs_mac_ctx = ssh->csmac->make_context(ssh->cs_cipher_ctx);
  6768. if (ssh->cs_comp_ctx)
  6769. ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
  6770. ssh->cscomp = s->cscomp_tobe;
  6771. ssh->cs_comp_ctx = ssh->cscomp->compress_init();
  6772. /*
  6773. * Set IVs on client-to-server keys. Here we use the exchange
  6774. * hash from the _first_ key exchange.
  6775. */
  6776. if (ssh->cscipher) {
  6777. unsigned char *key;
  6778. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'C',
  6779. ssh->cscipher->padded_keybytes);
  6780. ssh->cscipher->setkey(ssh->cs_cipher_ctx, key);
  6781. smemclr(key, ssh->cscipher->padded_keybytes);
  6782. sfree(key);
  6783. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'A',
  6784. ssh->cscipher->blksize);
  6785. ssh->cscipher->setiv(ssh->cs_cipher_ctx, key);
  6786. smemclr(key, ssh->cscipher->blksize);
  6787. sfree(key);
  6788. }
  6789. if (ssh->csmac) {
  6790. unsigned char *key;
  6791. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'E',
  6792. ssh->csmac->keylen);
  6793. ssh->csmac->setkey(ssh->cs_mac_ctx, key);
  6794. smemclr(key, ssh->csmac->keylen);
  6795. sfree(key);
  6796. }
  6797. if (ssh->cscipher)
  6798. logeventf(ssh, "Initialised %.200s client->server encryption",
  6799. ssh->cscipher->text_name);
  6800. if (ssh->csmac)
  6801. logeventf(ssh, "Initialised %.200s client->server MAC algorithm%s%s",
  6802. ssh->csmac->text_name,
  6803. ssh->csmac_etm ? " (in ETM mode)" : "",
  6804. ssh->cscipher->required_mac ? " (required by cipher)" : "");
  6805. if (ssh->cscomp->text_name)
  6806. logeventf(ssh, "Initialised %s compression",
  6807. ssh->cscomp->text_name);
  6808. /*
  6809. * Now our end of the key exchange is complete, we can send all
  6810. * our queued higher-layer packets.
  6811. */
  6812. ssh->queueing = FALSE;
  6813. ssh2_pkt_queuesend(ssh);
  6814. /*
  6815. * Expect SSH2_MSG_NEWKEYS from server.
  6816. */
  6817. crWaitUntilV(pktin);
  6818. if (pktin->type != SSH2_MSG_NEWKEYS) {
  6819. bombout(("expected new-keys packet from server"));
  6820. crStopV;
  6821. }
  6822. ssh->incoming_data_size = 0; /* start counting from here */
  6823. /*
  6824. * We've seen server NEWKEYS, so create and initialise
  6825. * server-to-client session keys.
  6826. */
  6827. if (ssh->sc_cipher_ctx)
  6828. ssh->sccipher->free_context(ssh->sc_cipher_ctx);
  6829. if (s->sccipher_tobe) {
  6830. ssh->sccipher = s->sccipher_tobe;
  6831. ssh->sc_cipher_ctx = ssh->sccipher->make_context();
  6832. }
  6833. if (ssh->sc_mac_ctx)
  6834. ssh->scmac->free_context(ssh->sc_mac_ctx);
  6835. if (s->scmac_tobe) {
  6836. ssh->scmac = s->scmac_tobe;
  6837. ssh->scmac_etm = s->scmac_etm_tobe;
  6838. ssh->sc_mac_ctx = ssh->scmac->make_context(ssh->sc_cipher_ctx);
  6839. }
  6840. if (ssh->sc_comp_ctx)
  6841. ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
  6842. ssh->sccomp = s->sccomp_tobe;
  6843. ssh->sc_comp_ctx = ssh->sccomp->decompress_init();
  6844. /*
  6845. * Set IVs on server-to-client keys. Here we use the exchange
  6846. * hash from the _first_ key exchange.
  6847. */
  6848. if (ssh->sccipher) {
  6849. unsigned char *key;
  6850. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'D',
  6851. ssh->sccipher->padded_keybytes);
  6852. ssh->sccipher->setkey(ssh->sc_cipher_ctx, key);
  6853. smemclr(key, ssh->sccipher->padded_keybytes);
  6854. sfree(key);
  6855. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'B',
  6856. ssh->sccipher->blksize);
  6857. ssh->sccipher->setiv(ssh->sc_cipher_ctx, key);
  6858. smemclr(key, ssh->sccipher->blksize);
  6859. sfree(key);
  6860. }
  6861. if (ssh->scmac) {
  6862. unsigned char *key;
  6863. key = ssh2_mkkey(ssh, s->K, s->exchange_hash, 'F',
  6864. ssh->scmac->keylen);
  6865. ssh->scmac->setkey(ssh->sc_mac_ctx, key);
  6866. smemclr(key, ssh->scmac->keylen);
  6867. sfree(key);
  6868. }
  6869. if (ssh->sccipher)
  6870. logeventf(ssh, "Initialised %.200s server->client encryption",
  6871. ssh->sccipher->text_name);
  6872. if (ssh->scmac)
  6873. logeventf(ssh, "Initialised %.200s server->client MAC algorithm%s%s",
  6874. ssh->scmac->text_name,
  6875. ssh->scmac_etm ? " (in ETM mode)" : "",
  6876. ssh->sccipher->required_mac ? " (required by cipher)" : "");
  6877. if (ssh->sccomp->text_name)
  6878. logeventf(ssh, "Initialised %s decompression",
  6879. ssh->sccomp->text_name);
  6880. /*
  6881. * Free shared secret.
  6882. */
  6883. freebn(s->K);
  6884. /*
  6885. * Update the specials menu to list the remaining uncertified host
  6886. * keys.
  6887. */
  6888. update_specials_menu(ssh->frontend);
  6889. /*
  6890. * Key exchange is over. Loop straight back round if we have a
  6891. * deferred rekey reason.
  6892. */
  6893. if (ssh->deferred_rekey_reason) {
  6894. logevent(ssh->deferred_rekey_reason);
  6895. pktin = NULL;
  6896. ssh->deferred_rekey_reason = NULL;
  6897. goto begin_key_exchange;
  6898. }
  6899. /*
  6900. * Otherwise, schedule a timer for our next rekey.
  6901. */
  6902. ssh->kex_in_progress = FALSE;
  6903. ssh->last_rekey = GETTICKCOUNT();
  6904. if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0)
  6905. ssh->next_rekey = schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
  6906. ssh2_timer, ssh);
  6907. /*
  6908. * Now we're encrypting. Begin returning 1 to the protocol main
  6909. * function so that other things can run on top of the
  6910. * transport. If we ever see a KEXINIT, we must go back to the
  6911. * start.
  6912. *
  6913. * We _also_ go back to the start if we see pktin==NULL and
  6914. * inlen negative, because this is a special signal meaning
  6915. * `initiate client-driven rekey', and `in' contains a message
  6916. * giving the reason for the rekey.
  6917. *
  6918. * inlen==-1 means always initiate a rekey;
  6919. * inlen==-2 means that userauth has completed successfully and
  6920. * we should consider rekeying (for delayed compression).
  6921. */
  6922. while (!((pktin && pktin->type == SSH2_MSG_KEXINIT) ||
  6923. (!pktin && inlen < 0))) {
  6924. wait_for_rekey:
  6925. if (!ssh->protocol_initial_phase_done) {
  6926. ssh->protocol_initial_phase_done = TRUE;
  6927. /*
  6928. * Allow authconn to initialise itself.
  6929. */
  6930. do_ssh2_authconn(ssh, NULL, 0, NULL);
  6931. }
  6932. crReturnV;
  6933. }
  6934. if (pktin) {
  6935. logevent("Server initiated key re-exchange");
  6936. } else {
  6937. if (inlen == -2) {
  6938. /*
  6939. * authconn has seen a USERAUTH_SUCCEEDED. Time to enable
  6940. * delayed compression, if it's available.
  6941. *
  6942. * draft-miller-secsh-compression-delayed-00 says that you
  6943. * negotiate delayed compression in the first key exchange, and
  6944. * both sides start compressing when the server has sent
  6945. * USERAUTH_SUCCESS. This has a race condition -- the server
  6946. * can't know when the client has seen it, and thus which incoming
  6947. * packets it should treat as compressed.
  6948. *
  6949. * Instead, we do the initial key exchange without offering the
  6950. * delayed methods, but note if the server offers them; when we
  6951. * get here, if a delayed method was available that was higher
  6952. * on our list than what we got, we initiate a rekey in which we
  6953. * _do_ list the delayed methods (and hopefully get it as a
  6954. * result). Subsequent rekeys will do the same.
  6955. */
  6956. assert(!s->userauth_succeeded); /* should only happen once */
  6957. s->userauth_succeeded = TRUE;
  6958. if (!s->pending_compression)
  6959. /* Can't see any point rekeying. */
  6960. goto wait_for_rekey; /* this is utterly horrid */
  6961. /* else fall through to rekey... */
  6962. s->pending_compression = FALSE;
  6963. }
  6964. /*
  6965. * Now we've decided to rekey.
  6966. *
  6967. * Special case: if the server bug is set that doesn't
  6968. * allow rekeying, we give a different log message and
  6969. * continue waiting. (If such a server _initiates_ a rekey,
  6970. * we process it anyway!)
  6971. */
  6972. if ((ssh->remote_bugs & BUG_SSH2_REKEY)) {
  6973. logeventf(ssh, "Server bug prevents key re-exchange (%s)",
  6974. (char *)in);
  6975. /* Reset the counters, so that at least this message doesn't
  6976. * hit the event log _too_ often. */
  6977. ssh->outgoing_data_size = 0;
  6978. ssh->incoming_data_size = 0;
  6979. if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0) {
  6980. ssh->next_rekey =
  6981. schedule_timer(conf_get_int(ssh->conf, CONF_ssh_rekey_time)*60*TICKSPERSEC,
  6982. ssh2_timer, ssh);
  6983. }
  6984. goto wait_for_rekey; /* this is still utterly horrid */
  6985. } else {
  6986. logeventf(ssh, "Initiating key re-exchange (%s)", (char *)in);
  6987. }
  6988. }
  6989. goto begin_key_exchange;
  6990. crFinishV;
  6991. }
  6992. /*
  6993. * Send data on an SSH channel. In SSH-2, this involves buffering it
  6994. * first.
  6995. */
  6996. static int ssh_send_channel_data(struct ssh_channel *c, const char *buf,
  6997. int len)
  6998. {
  6999. if (c->ssh->version == 2) {
  7000. bufchain_add(&c->v.v2.outbuffer, buf, len);
  7001. return ssh2_try_send(c);
  7002. } else {
  7003. send_packet(c->ssh, SSH1_MSG_CHANNEL_DATA,
  7004. PKT_INT, c->remoteid,
  7005. PKT_INT, len,
  7006. PKT_DATA, buf, len,
  7007. PKT_END);
  7008. /*
  7009. * In SSH-1 we can return 0 here - implying that channels are
  7010. * never individually throttled - because the only
  7011. * circumstance that can cause throttling will be the whole
  7012. * SSH connection backing up, in which case _everything_ will
  7013. * be throttled as a whole.
  7014. */
  7015. return 0;
  7016. }
  7017. }
  7018. /*
  7019. * Attempt to send data on an SSH-2 channel.
  7020. */
  7021. static int ssh2_try_send(struct ssh_channel *c)
  7022. {
  7023. Ssh ssh = c->ssh;
  7024. struct Packet *pktout;
  7025. int ret;
  7026. while (c->v.v2.remwindow > 0 && bufchain_size(&c->v.v2.outbuffer) > 0) {
  7027. int len;
  7028. void *data;
  7029. bufchain_prefix(&c->v.v2.outbuffer, &data, &len);
  7030. if ((unsigned)len > c->v.v2.remwindow)
  7031. len = c->v.v2.remwindow;
  7032. if ((unsigned)len > c->v.v2.remmaxpkt)
  7033. len = c->v.v2.remmaxpkt;
  7034. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_DATA);
  7035. ssh2_pkt_adduint32(pktout, c->remoteid);
  7036. ssh2_pkt_addstring_start(pktout);
  7037. ssh2_pkt_addstring_data(pktout, data, len);
  7038. ssh2_pkt_send(ssh, pktout);
  7039. bufchain_consume(&c->v.v2.outbuffer, len);
  7040. c->v.v2.remwindow -= len;
  7041. }
  7042. /*
  7043. * After having sent as much data as we can, return the amount
  7044. * still buffered.
  7045. */
  7046. ret = bufchain_size(&c->v.v2.outbuffer);
  7047. /*
  7048. * And if there's no data pending but we need to send an EOF, send
  7049. * it.
  7050. */
  7051. if (!ret && c->pending_eof)
  7052. ssh_channel_try_eof(c);
  7053. return ret;
  7054. }
  7055. static void ssh2_try_send_and_unthrottle(Ssh ssh, struct ssh_channel *c)
  7056. {
  7057. int bufsize;
  7058. if (c->closes & CLOSES_SENT_EOF)
  7059. return; /* don't send on channels we've EOFed */
  7060. bufsize = ssh2_try_send(c);
  7061. if (bufsize == 0) {
  7062. switch (c->type) {
  7063. case CHAN_MAINSESSION:
  7064. /* stdin need not receive an unthrottle
  7065. * notification since it will be polled */
  7066. break;
  7067. case CHAN_X11:
  7068. x11_unthrottle(c->u.x11.xconn);
  7069. break;
  7070. case CHAN_AGENT:
  7071. /* agent sockets are request/response and need no
  7072. * buffer management */
  7073. break;
  7074. case CHAN_SOCKDATA:
  7075. pfd_unthrottle(c->u.pfd.pf);
  7076. break;
  7077. }
  7078. }
  7079. }
  7080. static int ssh_is_simple(Ssh ssh)
  7081. {
  7082. /*
  7083. * We use the 'simple' variant of the SSH protocol if we're asked
  7084. * to, except not if we're also doing connection-sharing (either
  7085. * tunnelling our packets over an upstream or expecting to be
  7086. * tunnelled over ourselves), since then the assumption that we
  7087. * have only one channel to worry about is not true after all.
  7088. */
  7089. return (conf_get_int(ssh->conf, CONF_ssh_simple) &&
  7090. !ssh->bare_connection && !ssh->connshare);
  7091. }
  7092. /*
  7093. * Set up most of a new ssh_channel for SSH-2.
  7094. */
  7095. static void ssh2_channel_init(struct ssh_channel *c)
  7096. {
  7097. Ssh ssh = c->ssh;
  7098. c->localid = alloc_channel_id(ssh);
  7099. c->closes = 0;
  7100. c->pending_eof = FALSE;
  7101. c->throttling_conn = FALSE;
  7102. c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
  7103. ssh_is_simple(ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE;
  7104. c->v.v2.chanreq_head = NULL;
  7105. c->v.v2.throttle_state = UNTHROTTLED;
  7106. bufchain_init(&c->v.v2.outbuffer);
  7107. }
  7108. /*
  7109. * Construct the common parts of a CHANNEL_OPEN.
  7110. */
  7111. static struct Packet *ssh2_chanopen_init(struct ssh_channel *c,
  7112. const char *type)
  7113. {
  7114. struct Packet *pktout;
  7115. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN);
  7116. ssh2_pkt_addstring(pktout, type);
  7117. ssh2_pkt_adduint32(pktout, c->localid);
  7118. ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);/* our window size */
  7119. ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
  7120. return pktout;
  7121. }
  7122. /*
  7123. * CHANNEL_FAILURE doesn't come with any indication of what message
  7124. * caused it, so we have to keep track of the outstanding
  7125. * CHANNEL_REQUESTs ourselves.
  7126. */
  7127. static void ssh2_queue_chanreq_handler(struct ssh_channel *c,
  7128. cchandler_fn_t handler, void *ctx)
  7129. {
  7130. struct outstanding_channel_request *ocr =
  7131. snew(struct outstanding_channel_request);
  7132. assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
  7133. ocr->handler = handler;
  7134. ocr->ctx = ctx;
  7135. ocr->next = NULL;
  7136. if (!c->v.v2.chanreq_head)
  7137. c->v.v2.chanreq_head = ocr;
  7138. else
  7139. c->v.v2.chanreq_tail->next = ocr;
  7140. c->v.v2.chanreq_tail = ocr;
  7141. }
  7142. /*
  7143. * Construct the common parts of a CHANNEL_REQUEST. If handler is not
  7144. * NULL then a reply will be requested and the handler will be called
  7145. * when it arrives. The returned packet is ready to have any
  7146. * request-specific data added and be sent. Note that if a handler is
  7147. * provided, it's essential that the request actually be sent.
  7148. *
  7149. * The handler will usually be passed the response packet in pktin. If
  7150. * pktin is NULL, this means that no reply will ever be forthcoming
  7151. * (e.g. because the entire connection is being destroyed, or because
  7152. * the server initiated channel closure before we saw the response)
  7153. * and the handler should free any storage it's holding.
  7154. */
  7155. static struct Packet *ssh2_chanreq_init(struct ssh_channel *c,
  7156. const char *type,
  7157. cchandler_fn_t handler, void *ctx)
  7158. {
  7159. struct Packet *pktout;
  7160. assert(!(c->closes & (CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE)));
  7161. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_REQUEST);
  7162. ssh2_pkt_adduint32(pktout, c->remoteid);
  7163. ssh2_pkt_addstring(pktout, type);
  7164. ssh2_pkt_addbool(pktout, handler != NULL);
  7165. if (handler != NULL)
  7166. ssh2_queue_chanreq_handler(c, handler, ctx);
  7167. return pktout;
  7168. }
  7169. /*
  7170. * Potentially enlarge the window on an SSH-2 channel.
  7171. */
  7172. static void ssh2_handle_winadj_response(struct ssh_channel *, struct Packet *,
  7173. void *);
  7174. static void ssh2_set_window(struct ssh_channel *c, int newwin)
  7175. {
  7176. Ssh ssh = c->ssh;
  7177. /*
  7178. * Never send WINDOW_ADJUST for a channel that the remote side has
  7179. * already sent EOF on; there's no point, since it won't be
  7180. * sending any more data anyway. Ditto if _we've_ already sent
  7181. * CLOSE.
  7182. */
  7183. if (c->closes & (CLOSES_RCVD_EOF | CLOSES_SENT_CLOSE))
  7184. return;
  7185. /*
  7186. * Also, never widen the window for an X11 channel when we're
  7187. * still waiting to see its initial auth and may yet hand it off
  7188. * to a downstream.
  7189. */
  7190. if (c->type == CHAN_X11 && c->u.x11.initial)
  7191. return;
  7192. /*
  7193. * If the remote end has a habit of ignoring maxpkt, limit the
  7194. * window so that it has no choice (assuming it doesn't ignore the
  7195. * window as well).
  7196. */
  7197. if ((ssh->remote_bugs & BUG_SSH2_MAXPKT) && newwin > OUR_V2_MAXPKT)
  7198. newwin = OUR_V2_MAXPKT;
  7199. /*
  7200. * Only send a WINDOW_ADJUST if there's significantly more window
  7201. * available than the other end thinks there is. This saves us
  7202. * sending a WINDOW_ADJUST for every character in a shell session.
  7203. *
  7204. * "Significant" is arbitrarily defined as half the window size.
  7205. */
  7206. if (newwin / 2 >= c->v.v2.locwindow) {
  7207. struct Packet *pktout;
  7208. unsigned *up;
  7209. /*
  7210. * In order to keep track of how much window the client
  7211. * actually has available, we'd like it to acknowledge each
  7212. * WINDOW_ADJUST. We can't do that directly, so we accompany
  7213. * it with a CHANNEL_REQUEST that has to be acknowledged.
  7214. *
  7215. * This is only necessary if we're opening the window wide.
  7216. * If we're not, then throughput is being constrained by
  7217. * something other than the maximum window size anyway.
  7218. */
  7219. if (newwin == c->v.v2.locmaxwin &&
  7220. !(ssh->remote_bugs & BUG_CHOKES_ON_WINADJ)) {
  7221. up = snew(unsigned);
  7222. *up = newwin - c->v.v2.locwindow;
  7223. pktout = ssh2_chanreq_init(c, "winadj@putty.projects.tartarus.org",
  7224. ssh2_handle_winadj_response, up);
  7225. ssh2_pkt_send(ssh, pktout);
  7226. if (c->v.v2.throttle_state != UNTHROTTLED)
  7227. c->v.v2.throttle_state = UNTHROTTLING;
  7228. } else {
  7229. /* Pretend the WINDOW_ADJUST was acked immediately. */
  7230. c->v.v2.remlocwin = newwin;
  7231. c->v.v2.throttle_state = THROTTLED;
  7232. }
  7233. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_WINDOW_ADJUST);
  7234. ssh2_pkt_adduint32(pktout, c->remoteid);
  7235. ssh2_pkt_adduint32(pktout, newwin - c->v.v2.locwindow);
  7236. ssh2_pkt_send(ssh, pktout);
  7237. c->v.v2.locwindow = newwin;
  7238. }
  7239. }
  7240. /*
  7241. * Find the channel associated with a message. If there's no channel,
  7242. * or it's not properly open, make a noise about it and return NULL.
  7243. */
  7244. static struct ssh_channel *ssh2_channel_msg(Ssh ssh, struct Packet *pktin)
  7245. {
  7246. unsigned localid = ssh_pkt_getuint32(pktin);
  7247. struct ssh_channel *c;
  7248. c = find234(ssh->channels, &localid, ssh_channelfind);
  7249. if (!c ||
  7250. (c->type != CHAN_SHARING && c->halfopen &&
  7251. pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION &&
  7252. pktin->type != SSH2_MSG_CHANNEL_OPEN_FAILURE)) {
  7253. char *buf = dupprintf("Received %s for %s channel %u",
  7254. ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
  7255. pktin->type),
  7256. c ? "half-open" : "nonexistent", localid);
  7257. ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
  7258. sfree(buf);
  7259. return NULL;
  7260. }
  7261. return c;
  7262. }
  7263. static void ssh2_handle_winadj_response(struct ssh_channel *c,
  7264. struct Packet *pktin, void *ctx)
  7265. {
  7266. unsigned *sizep = ctx;
  7267. /*
  7268. * Winadj responses should always be failures. However, at least
  7269. * one server ("boks_sshd") is known to return SUCCESS for channel
  7270. * requests it's never heard of, such as "winadj@putty". Raised
  7271. * with foxt.com as bug 090916-090424, but for the sake of a quiet
  7272. * life, we don't worry about what kind of response we got.
  7273. */
  7274. c->v.v2.remlocwin += *sizep;
  7275. sfree(sizep);
  7276. /*
  7277. * winadj messages are only sent when the window is fully open, so
  7278. * if we get an ack of one, we know any pending unthrottle is
  7279. * complete.
  7280. */
  7281. if (c->v.v2.throttle_state == UNTHROTTLING)
  7282. c->v.v2.throttle_state = UNTHROTTLED;
  7283. }
  7284. static void ssh2_msg_channel_response(Ssh ssh, struct Packet *pktin)
  7285. {
  7286. struct ssh_channel *c = ssh2_channel_msg(ssh, pktin);
  7287. struct outstanding_channel_request *ocr;
  7288. if (!c) return;
  7289. if (c->type == CHAN_SHARING) {
  7290. share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
  7291. pktin->body, pktin->length);
  7292. return;
  7293. }
  7294. ocr = c->v.v2.chanreq_head;
  7295. if (!ocr) {
  7296. ssh2_msg_unexpected(ssh, pktin);
  7297. return;
  7298. }
  7299. ocr->handler(c, pktin, ocr->ctx);
  7300. c->v.v2.chanreq_head = ocr->next;
  7301. sfree(ocr);
  7302. /*
  7303. * We may now initiate channel-closing procedures, if that
  7304. * CHANNEL_REQUEST was the last thing outstanding before we send
  7305. * CHANNEL_CLOSE.
  7306. */
  7307. ssh2_channel_check_close(c);
  7308. }
  7309. static void ssh2_msg_channel_window_adjust(Ssh ssh, struct Packet *pktin)
  7310. {
  7311. struct ssh_channel *c;
  7312. c = ssh2_channel_msg(ssh, pktin);
  7313. if (!c)
  7314. return;
  7315. if (c->type == CHAN_SHARING) {
  7316. share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
  7317. pktin->body, pktin->length);
  7318. return;
  7319. }
  7320. if (!(c->closes & CLOSES_SENT_EOF)) {
  7321. c->v.v2.remwindow += ssh_pkt_getuint32(pktin);
  7322. ssh2_try_send_and_unthrottle(ssh, c);
  7323. }
  7324. }
  7325. static void ssh2_msg_channel_data(Ssh ssh, struct Packet *pktin)
  7326. {
  7327. char *data;
  7328. int length;
  7329. struct ssh_channel *c;
  7330. c = ssh2_channel_msg(ssh, pktin);
  7331. if (!c)
  7332. return;
  7333. if (c->type == CHAN_SHARING) {
  7334. share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
  7335. pktin->body, pktin->length);
  7336. return;
  7337. }
  7338. if (pktin->type == SSH2_MSG_CHANNEL_EXTENDED_DATA &&
  7339. ssh_pkt_getuint32(pktin) != SSH2_EXTENDED_DATA_STDERR)
  7340. return; /* extended but not stderr */
  7341. ssh_pkt_getstring(pktin, &data, &length);
  7342. if (data) {
  7343. int bufsize = 0;
  7344. c->v.v2.locwindow -= length;
  7345. c->v.v2.remlocwin -= length;
  7346. switch (c->type) {
  7347. case CHAN_MAINSESSION:
  7348. bufsize =
  7349. from_backend(ssh->frontend, pktin->type ==
  7350. SSH2_MSG_CHANNEL_EXTENDED_DATA,
  7351. data, length);
  7352. break;
  7353. case CHAN_X11:
  7354. bufsize = x11_send(c->u.x11.xconn, data, length);
  7355. break;
  7356. case CHAN_SOCKDATA:
  7357. bufsize = pfd_send(c->u.pfd.pf, data, length);
  7358. break;
  7359. case CHAN_AGENT:
  7360. bufsize = ssh_agent_channel_data(c, data, length);
  7361. break;
  7362. }
  7363. /*
  7364. * If it looks like the remote end hit the end of its window,
  7365. * and we didn't want it to do that, think about using a
  7366. * larger window.
  7367. */
  7368. if (c->v.v2.remlocwin <= 0 && c->v.v2.throttle_state == UNTHROTTLED &&
  7369. c->v.v2.locmaxwin < 0x40000000)
  7370. c->v.v2.locmaxwin += OUR_V2_WINSIZE;
  7371. /*
  7372. * If we are not buffering too much data,
  7373. * enlarge the window again at the remote side.
  7374. * If we are buffering too much, we may still
  7375. * need to adjust the window if the server's
  7376. * sent excess data.
  7377. */
  7378. ssh2_set_window(c, bufsize < c->v.v2.locmaxwin ?
  7379. c->v.v2.locmaxwin - bufsize : 0);
  7380. /*
  7381. * If we're either buffering way too much data, or if we're
  7382. * buffering anything at all and we're in "simple" mode,
  7383. * throttle the whole channel.
  7384. */
  7385. if ((bufsize > c->v.v2.locmaxwin || (ssh_is_simple(ssh) && bufsize>0))
  7386. && !c->throttling_conn) {
  7387. c->throttling_conn = 1;
  7388. ssh_throttle_conn(ssh, +1);
  7389. }
  7390. }
  7391. }
  7392. static void ssh_check_termination(Ssh ssh)
  7393. {
  7394. if (ssh->version == 2 &&
  7395. !conf_get_int(ssh->conf, CONF_ssh_no_shell) &&
  7396. (ssh->channels && count234(ssh->channels) == 0) &&
  7397. !(ssh->connshare && share_ndownstreams(ssh->connshare) > 0)) {
  7398. /*
  7399. * We used to send SSH_MSG_DISCONNECT here, because I'd
  7400. * believed that _every_ conforming SSH-2 connection had to
  7401. * end with a disconnect being sent by at least one side;
  7402. * apparently I was wrong and it's perfectly OK to
  7403. * unceremoniously slam the connection shut when you're done,
  7404. * and indeed OpenSSH feels this is more polite than sending a
  7405. * DISCONNECT. So now we don't.
  7406. */
  7407. ssh_disconnect(ssh, "All channels closed", NULL, 0, TRUE);
  7408. }
  7409. }
  7410. void ssh_sharing_downstream_connected(Ssh ssh, unsigned id,
  7411. const char *peerinfo)
  7412. {
  7413. if (peerinfo)
  7414. logeventf(ssh, "Connection sharing downstream #%u connected from %s",
  7415. id, peerinfo);
  7416. else
  7417. logeventf(ssh, "Connection sharing downstream #%u connected", id);
  7418. }
  7419. void ssh_sharing_downstream_disconnected(Ssh ssh, unsigned id)
  7420. {
  7421. logeventf(ssh, "Connection sharing downstream #%u disconnected", id);
  7422. ssh_check_termination(ssh);
  7423. }
  7424. void ssh_sharing_logf(Ssh ssh, unsigned id, const char *logfmt, ...)
  7425. {
  7426. va_list ap;
  7427. char *buf;
  7428. va_start(ap, logfmt);
  7429. buf = dupvprintf(logfmt, ap);
  7430. va_end(ap);
  7431. if (id)
  7432. logeventf(ssh, "Connection sharing downstream #%u: %s", id, buf);
  7433. else
  7434. logeventf(ssh, "Connection sharing: %s", buf);
  7435. sfree(buf);
  7436. }
  7437. static void ssh_channel_destroy(struct ssh_channel *c)
  7438. {
  7439. Ssh ssh = c->ssh;
  7440. switch (c->type) {
  7441. case CHAN_MAINSESSION:
  7442. ssh->mainchan = NULL;
  7443. update_specials_menu(ssh->frontend);
  7444. break;
  7445. case CHAN_X11:
  7446. if (c->u.x11.xconn != NULL)
  7447. x11_close(c->u.x11.xconn);
  7448. logevent("Forwarded X11 connection terminated");
  7449. break;
  7450. case CHAN_AGENT:
  7451. sfree(c->u.a.message);
  7452. break;
  7453. case CHAN_SOCKDATA:
  7454. if (c->u.pfd.pf != NULL)
  7455. pfd_close(c->u.pfd.pf);
  7456. logevent("Forwarded port closed");
  7457. break;
  7458. }
  7459. del234(ssh->channels, c);
  7460. if (ssh->version == 2) {
  7461. bufchain_clear(&c->v.v2.outbuffer);
  7462. assert(c->v.v2.chanreq_head == NULL);
  7463. }
  7464. sfree(c);
  7465. /*
  7466. * If that was the last channel left open, we might need to
  7467. * terminate.
  7468. */
  7469. ssh_check_termination(ssh);
  7470. }
  7471. static void ssh2_channel_check_close(struct ssh_channel *c)
  7472. {
  7473. Ssh ssh = c->ssh;
  7474. struct Packet *pktout;
  7475. if (c->halfopen) {
  7476. /*
  7477. * If we've sent out our own CHANNEL_OPEN but not yet seen
  7478. * either OPEN_CONFIRMATION or OPEN_FAILURE in response, then
  7479. * it's too early to be sending close messages of any kind.
  7480. */
  7481. return;
  7482. }
  7483. if ((!((CLOSES_SENT_EOF | CLOSES_RCVD_EOF) & ~c->closes) ||
  7484. c->type == CHAN_ZOMBIE) &&
  7485. !c->v.v2.chanreq_head &&
  7486. !(c->closes & CLOSES_SENT_CLOSE)) {
  7487. /*
  7488. * We have both sent and received EOF (or the channel is a
  7489. * zombie), and we have no outstanding channel requests, which
  7490. * means the channel is in final wind-up. But we haven't sent
  7491. * CLOSE, so let's do so now.
  7492. */
  7493. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_CLOSE);
  7494. ssh2_pkt_adduint32(pktout, c->remoteid);
  7495. ssh2_pkt_send(ssh, pktout);
  7496. c->closes |= CLOSES_SENT_EOF | CLOSES_SENT_CLOSE;
  7497. }
  7498. if (!((CLOSES_SENT_CLOSE | CLOSES_RCVD_CLOSE) & ~c->closes)) {
  7499. assert(c->v.v2.chanreq_head == NULL);
  7500. /*
  7501. * We have both sent and received CLOSE, which means we're
  7502. * completely done with the channel.
  7503. */
  7504. ssh_channel_destroy(c);
  7505. }
  7506. }
  7507. static void ssh2_channel_got_eof(struct ssh_channel *c)
  7508. {
  7509. if (c->closes & CLOSES_RCVD_EOF)
  7510. return; /* already seen EOF */
  7511. c->closes |= CLOSES_RCVD_EOF;
  7512. if (c->type == CHAN_X11) {
  7513. x11_send_eof(c->u.x11.xconn);
  7514. } else if (c->type == CHAN_AGENT) {
  7515. if (c->u.a.outstanding_requests == 0) {
  7516. /* Manufacture an outgoing EOF in response to the incoming one. */
  7517. sshfwd_write_eof(c);
  7518. }
  7519. } else if (c->type == CHAN_SOCKDATA) {
  7520. pfd_send_eof(c->u.pfd.pf);
  7521. } else if (c->type == CHAN_MAINSESSION) {
  7522. Ssh ssh = c->ssh;
  7523. if (!ssh->sent_console_eof &&
  7524. (from_backend_eof(ssh->frontend) || ssh->got_pty)) {
  7525. /*
  7526. * Either from_backend_eof told us that the front end
  7527. * wants us to close the outgoing side of the connection
  7528. * as soon as we see EOF from the far end, or else we've
  7529. * unilaterally decided to do that because we've allocated
  7530. * a remote pty and hence EOF isn't a particularly
  7531. * meaningful concept.
  7532. */
  7533. sshfwd_write_eof(c);
  7534. }
  7535. ssh->sent_console_eof = TRUE;
  7536. }
  7537. ssh2_channel_check_close(c);
  7538. }
  7539. static void ssh2_msg_channel_eof(Ssh ssh, struct Packet *pktin)
  7540. {
  7541. struct ssh_channel *c;
  7542. c = ssh2_channel_msg(ssh, pktin);
  7543. if (!c)
  7544. return;
  7545. if (c->type == CHAN_SHARING) {
  7546. share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
  7547. pktin->body, pktin->length);
  7548. return;
  7549. }
  7550. ssh2_channel_got_eof(c);
  7551. }
  7552. static void ssh2_msg_channel_close(Ssh ssh, struct Packet *pktin)
  7553. {
  7554. struct ssh_channel *c;
  7555. c = ssh2_channel_msg(ssh, pktin);
  7556. if (!c)
  7557. return;
  7558. if (c->type == CHAN_SHARING) {
  7559. share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
  7560. pktin->body, pktin->length);
  7561. return;
  7562. }
  7563. /*
  7564. * When we receive CLOSE on a channel, we assume it comes with an
  7565. * implied EOF if we haven't seen EOF yet.
  7566. */
  7567. ssh2_channel_got_eof(c);
  7568. if (!(ssh->remote_bugs & BUG_SENDS_LATE_REQUEST_REPLY)) {
  7569. /*
  7570. * It also means we stop expecting to see replies to any
  7571. * outstanding channel requests, so clean those up too.
  7572. * (ssh_chanreq_init will enforce by assertion that we don't
  7573. * subsequently put anything back on this list.)
  7574. */
  7575. while (c->v.v2.chanreq_head) {
  7576. struct outstanding_channel_request *ocr = c->v.v2.chanreq_head;
  7577. ocr->handler(c, NULL, ocr->ctx);
  7578. c->v.v2.chanreq_head = ocr->next;
  7579. sfree(ocr);
  7580. }
  7581. }
  7582. /*
  7583. * And we also send an outgoing EOF, if we haven't already, on the
  7584. * assumption that CLOSE is a pretty forceful announcement that
  7585. * the remote side is doing away with the entire channel. (If it
  7586. * had wanted to send us EOF and continue receiving data from us,
  7587. * it would have just sent CHANNEL_EOF.)
  7588. */
  7589. if (!(c->closes & CLOSES_SENT_EOF)) {
  7590. /*
  7591. * Make sure we don't read any more from whatever our local
  7592. * data source is for this channel.
  7593. */
  7594. switch (c->type) {
  7595. case CHAN_MAINSESSION:
  7596. ssh->send_ok = 0; /* stop trying to read from stdin */
  7597. break;
  7598. case CHAN_X11:
  7599. x11_override_throttle(c->u.x11.xconn, 1);
  7600. break;
  7601. case CHAN_SOCKDATA:
  7602. pfd_override_throttle(c->u.pfd.pf, 1);
  7603. break;
  7604. }
  7605. /*
  7606. * Abandon any buffered data we still wanted to send to this
  7607. * channel. Receiving a CHANNEL_CLOSE is an indication that
  7608. * the server really wants to get on and _destroy_ this
  7609. * channel, and it isn't going to send us any further
  7610. * WINDOW_ADJUSTs to permit us to send pending stuff.
  7611. */
  7612. bufchain_clear(&c->v.v2.outbuffer);
  7613. /*
  7614. * Send outgoing EOF.
  7615. */
  7616. sshfwd_write_eof(c);
  7617. }
  7618. /*
  7619. * Now process the actual close.
  7620. */
  7621. if (!(c->closes & CLOSES_RCVD_CLOSE)) {
  7622. c->closes |= CLOSES_RCVD_CLOSE;
  7623. ssh2_channel_check_close(c);
  7624. }
  7625. }
  7626. static void ssh2_msg_channel_open_confirmation(Ssh ssh, struct Packet *pktin)
  7627. {
  7628. struct ssh_channel *c;
  7629. c = ssh2_channel_msg(ssh, pktin);
  7630. if (!c)
  7631. return;
  7632. if (c->type == CHAN_SHARING) {
  7633. share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
  7634. pktin->body, pktin->length);
  7635. return;
  7636. }
  7637. assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
  7638. c->remoteid = ssh_pkt_getuint32(pktin);
  7639. c->halfopen = FALSE;
  7640. c->v.v2.remwindow = ssh_pkt_getuint32(pktin);
  7641. c->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
  7642. if (c->type == CHAN_SOCKDATA_DORMANT) {
  7643. c->type = CHAN_SOCKDATA;
  7644. if (c->u.pfd.pf)
  7645. pfd_confirm(c->u.pfd.pf);
  7646. } else if (c->type == CHAN_ZOMBIE) {
  7647. /*
  7648. * This case can occur if a local socket error occurred
  7649. * between us sending out CHANNEL_OPEN and receiving
  7650. * OPEN_CONFIRMATION. In this case, all we can do is
  7651. * immediately initiate close proceedings now that we know the
  7652. * server's id to put in the close message.
  7653. */
  7654. ssh2_channel_check_close(c);
  7655. } else {
  7656. /*
  7657. * We never expect to receive OPEN_CONFIRMATION for any
  7658. * *other* channel type (since only local-to-remote port
  7659. * forwardings cause us to send CHANNEL_OPEN after the main
  7660. * channel is live - all other auxiliary channel types are
  7661. * initiated from the server end). It's safe to enforce this
  7662. * by assertion rather than by ssh_disconnect, because the
  7663. * real point is that we never constructed a half-open channel
  7664. * structure in the first place with any type other than the
  7665. * above.
  7666. */
  7667. assert(!"Funny channel type in ssh2_msg_channel_open_confirmation");
  7668. }
  7669. if (c->pending_eof)
  7670. ssh_channel_try_eof(c); /* in case we had a pending EOF */
  7671. }
  7672. static void ssh2_msg_channel_open_failure(Ssh ssh, struct Packet *pktin)
  7673. {
  7674. static const char *const reasons[] = {
  7675. "<unknown reason code>",
  7676. "Administratively prohibited",
  7677. "Connect failed",
  7678. "Unknown channel type",
  7679. "Resource shortage",
  7680. };
  7681. unsigned reason_code;
  7682. char *reason_string;
  7683. int reason_length;
  7684. struct ssh_channel *c;
  7685. c = ssh2_channel_msg(ssh, pktin);
  7686. if (!c)
  7687. return;
  7688. if (c->type == CHAN_SHARING) {
  7689. share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
  7690. pktin->body, pktin->length);
  7691. return;
  7692. }
  7693. assert(c->halfopen); /* ssh2_channel_msg will have enforced this */
  7694. if (c->type == CHAN_SOCKDATA_DORMANT) {
  7695. reason_code = ssh_pkt_getuint32(pktin);
  7696. if (reason_code >= lenof(reasons))
  7697. reason_code = 0; /* ensure reasons[reason_code] in range */
  7698. ssh_pkt_getstring(pktin, &reason_string, &reason_length);
  7699. logeventf(ssh, "Forwarded connection refused by server: %s [%.*s]",
  7700. reasons[reason_code], reason_length,
  7701. NULLTOEMPTY(reason_string));
  7702. pfd_close(c->u.pfd.pf);
  7703. } else if (c->type == CHAN_ZOMBIE) {
  7704. /*
  7705. * This case can occur if a local socket error occurred
  7706. * between us sending out CHANNEL_OPEN and receiving
  7707. * OPEN_FAILURE. In this case, we need do nothing except allow
  7708. * the code below to throw the half-open channel away.
  7709. */
  7710. } else {
  7711. /*
  7712. * We never expect to receive OPEN_FAILURE for any *other*
  7713. * channel type (since only local-to-remote port forwardings
  7714. * cause us to send CHANNEL_OPEN after the main channel is
  7715. * live - all other auxiliary channel types are initiated from
  7716. * the server end). It's safe to enforce this by assertion
  7717. * rather than by ssh_disconnect, because the real point is
  7718. * that we never constructed a half-open channel structure in
  7719. * the first place with any type other than the above.
  7720. */
  7721. assert(!"Funny channel type in ssh2_msg_channel_open_failure");
  7722. }
  7723. del234(ssh->channels, c);
  7724. sfree(c);
  7725. }
  7726. static void ssh2_msg_channel_request(Ssh ssh, struct Packet *pktin)
  7727. {
  7728. char *type;
  7729. int typelen, want_reply;
  7730. int reply = SSH2_MSG_CHANNEL_FAILURE; /* default */
  7731. struct ssh_channel *c;
  7732. struct Packet *pktout;
  7733. c = ssh2_channel_msg(ssh, pktin);
  7734. if (!c)
  7735. return;
  7736. if (c->type == CHAN_SHARING) {
  7737. share_got_pkt_from_server(c->u.sharing.ctx, pktin->type,
  7738. pktin->body, pktin->length);
  7739. return;
  7740. }
  7741. ssh_pkt_getstring(pktin, &type, &typelen);
  7742. want_reply = ssh2_pkt_getbool(pktin);
  7743. if (c->closes & CLOSES_SENT_CLOSE) {
  7744. /*
  7745. * We don't reply to channel requests after we've sent
  7746. * CHANNEL_CLOSE for the channel, because our reply might
  7747. * cross in the network with the other side's CHANNEL_CLOSE
  7748. * and arrive after they have wound the channel up completely.
  7749. */
  7750. want_reply = FALSE;
  7751. }
  7752. /*
  7753. * Having got the channel number, we now look at
  7754. * the request type string to see if it's something
  7755. * we recognise.
  7756. */
  7757. if (c == ssh->mainchan) {
  7758. /*
  7759. * We recognise "exit-status" and "exit-signal" on
  7760. * the primary channel.
  7761. */
  7762. if (typelen == 11 &&
  7763. !memcmp(type, "exit-status", 11)) {
  7764. ssh->exitcode = ssh_pkt_getuint32(pktin);
  7765. logeventf(ssh, "Server sent command exit status %d",
  7766. ssh->exitcode);
  7767. reply = SSH2_MSG_CHANNEL_SUCCESS;
  7768. } else if (typelen == 11 &&
  7769. !memcmp(type, "exit-signal", 11)) {
  7770. int is_plausible = TRUE, is_int = FALSE;
  7771. char *fmt_sig = NULL, *fmt_msg = NULL;
  7772. char *msg;
  7773. int msglen = 0, core = FALSE;
  7774. /* ICK: older versions of OpenSSH (e.g. 3.4p1)
  7775. * provide an `int' for the signal, despite its
  7776. * having been a `string' in the drafts of RFC 4254 since at
  7777. * least 2001. (Fixed in session.c 1.147.) Try to
  7778. * infer which we can safely parse it as. */
  7779. {
  7780. unsigned char *p = pktin->body +
  7781. pktin->savedpos;
  7782. long len = pktin->length - pktin->savedpos;
  7783. unsigned long num = GET_32BIT(p); /* what is it? */
  7784. /* If it's 0, it hardly matters; assume string */
  7785. if (num == 0) {
  7786. is_int = FALSE;
  7787. } else {
  7788. int maybe_int = FALSE, maybe_str = FALSE;
  7789. #define CHECK_HYPOTHESIS(offset, result) \
  7790. do \
  7791. { \
  7792. int q = toint(offset); \
  7793. if (q >= 0 && q+4 <= len) { \
  7794. q = toint(q + 4 + GET_32BIT(p+q)); \
  7795. if (q >= 0 && q+4 <= len && \
  7796. ((q = toint(q + 4 + GET_32BIT(p+q))) != 0) && \
  7797. q == len) \
  7798. result = TRUE; \
  7799. } \
  7800. } while(0)
  7801. CHECK_HYPOTHESIS(4+1, maybe_int);
  7802. CHECK_HYPOTHESIS(4+num+1, maybe_str);
  7803. #undef CHECK_HYPOTHESIS
  7804. if (maybe_int && !maybe_str)
  7805. is_int = TRUE;
  7806. else if (!maybe_int && maybe_str)
  7807. is_int = FALSE;
  7808. else
  7809. /* Crikey. Either or neither. Panic. */
  7810. is_plausible = FALSE;
  7811. }
  7812. }
  7813. ssh->exitcode = 128; /* means `unknown signal' */
  7814. if (is_plausible) {
  7815. if (is_int) {
  7816. /* Old non-standard OpenSSH. */
  7817. int signum = ssh_pkt_getuint32(pktin);
  7818. fmt_sig = dupprintf(" %d", signum);
  7819. ssh->exitcode = 128 + signum;
  7820. } else {
  7821. /* As per RFC 4254. */
  7822. char *sig;
  7823. int siglen;
  7824. ssh_pkt_getstring(pktin, &sig, &siglen);
  7825. /* Signal name isn't supposed to be blank, but
  7826. * let's cope gracefully if it is. */
  7827. if (siglen) {
  7828. fmt_sig = dupprintf(" \"%.*s\"",
  7829. siglen, sig);
  7830. }
  7831. /*
  7832. * Really hideous method of translating the
  7833. * signal description back into a locally
  7834. * meaningful number.
  7835. */
  7836. if (0)
  7837. ;
  7838. #define TRANSLATE_SIGNAL(s) \
  7839. else if (siglen == lenof(#s)-1 && !memcmp(sig, #s, siglen)) \
  7840. ssh->exitcode = 128 + SIG ## s
  7841. #ifdef SIGABRT
  7842. TRANSLATE_SIGNAL(ABRT);
  7843. #endif
  7844. #ifdef SIGALRM
  7845. TRANSLATE_SIGNAL(ALRM);
  7846. #endif
  7847. #ifdef SIGFPE
  7848. TRANSLATE_SIGNAL(FPE);
  7849. #endif
  7850. #ifdef SIGHUP
  7851. TRANSLATE_SIGNAL(HUP);
  7852. #endif
  7853. #ifdef SIGILL
  7854. TRANSLATE_SIGNAL(ILL);
  7855. #endif
  7856. #ifdef SIGINT
  7857. TRANSLATE_SIGNAL(INT);
  7858. #endif
  7859. #ifdef SIGKILL
  7860. TRANSLATE_SIGNAL(KILL);
  7861. #endif
  7862. #ifdef SIGPIPE
  7863. TRANSLATE_SIGNAL(PIPE);
  7864. #endif
  7865. #ifdef SIGQUIT
  7866. TRANSLATE_SIGNAL(QUIT);
  7867. #endif
  7868. #ifdef SIGSEGV
  7869. TRANSLATE_SIGNAL(SEGV);
  7870. #endif
  7871. #ifdef SIGTERM
  7872. TRANSLATE_SIGNAL(TERM);
  7873. #endif
  7874. #ifdef SIGUSR1
  7875. TRANSLATE_SIGNAL(USR1);
  7876. #endif
  7877. #ifdef SIGUSR2
  7878. TRANSLATE_SIGNAL(USR2);
  7879. #endif
  7880. #undef TRANSLATE_SIGNAL
  7881. else
  7882. ssh->exitcode = 128;
  7883. }
  7884. core = ssh2_pkt_getbool(pktin);
  7885. ssh_pkt_getstring(pktin, &msg, &msglen);
  7886. if (msglen) {
  7887. fmt_msg = dupprintf(" (\"%.*s\")", msglen, msg);
  7888. }
  7889. /* ignore lang tag */
  7890. } /* else don't attempt to parse */
  7891. logeventf(ssh, "Server exited on signal%s%s%s",
  7892. fmt_sig ? fmt_sig : "",
  7893. core ? " (core dumped)" : "",
  7894. fmt_msg ? fmt_msg : "");
  7895. sfree(fmt_sig);
  7896. sfree(fmt_msg);
  7897. reply = SSH2_MSG_CHANNEL_SUCCESS;
  7898. }
  7899. } else {
  7900. /*
  7901. * This is a channel request we don't know
  7902. * about, so we now either ignore the request
  7903. * or respond with CHANNEL_FAILURE, depending
  7904. * on want_reply.
  7905. */
  7906. reply = SSH2_MSG_CHANNEL_FAILURE;
  7907. }
  7908. if (want_reply) {
  7909. pktout = ssh2_pkt_init(reply);
  7910. ssh2_pkt_adduint32(pktout, c->remoteid);
  7911. ssh2_pkt_send(ssh, pktout);
  7912. }
  7913. }
  7914. static void ssh2_msg_global_request(Ssh ssh, struct Packet *pktin)
  7915. {
  7916. char *type;
  7917. int typelen, want_reply;
  7918. struct Packet *pktout;
  7919. ssh_pkt_getstring(pktin, &type, &typelen);
  7920. want_reply = ssh2_pkt_getbool(pktin);
  7921. /*
  7922. * We currently don't support any global requests
  7923. * at all, so we either ignore the request or
  7924. * respond with REQUEST_FAILURE, depending on
  7925. * want_reply.
  7926. */
  7927. if (want_reply) {
  7928. pktout = ssh2_pkt_init(SSH2_MSG_REQUEST_FAILURE);
  7929. ssh2_pkt_send(ssh, pktout);
  7930. }
  7931. }
  7932. struct X11FakeAuth *ssh_sharing_add_x11_display(Ssh ssh, int authtype,
  7933. void *share_cs,
  7934. void *share_chan)
  7935. {
  7936. struct X11FakeAuth *auth;
  7937. /*
  7938. * Make up a new set of fake X11 auth data, and add it to the tree
  7939. * of currently valid ones with an indication of the sharing
  7940. * context that it's relevant to.
  7941. */
  7942. auth = x11_invent_fake_auth(ssh->x11authtree, authtype);
  7943. auth->share_cs = share_cs;
  7944. auth->share_chan = share_chan;
  7945. return auth;
  7946. }
  7947. void ssh_sharing_remove_x11_display(Ssh ssh, struct X11FakeAuth *auth)
  7948. {
  7949. del234(ssh->x11authtree, auth);
  7950. x11_free_fake_auth(auth);
  7951. }
  7952. static void ssh2_msg_channel_open(Ssh ssh, struct Packet *pktin)
  7953. {
  7954. char *type;
  7955. int typelen;
  7956. char *peeraddr;
  7957. int peeraddrlen;
  7958. int peerport;
  7959. const char *error = NULL;
  7960. struct ssh_channel *c;
  7961. unsigned remid, winsize, pktsize;
  7962. unsigned our_winsize_override = 0;
  7963. struct Packet *pktout;
  7964. ssh_pkt_getstring(pktin, &type, &typelen);
  7965. c = snew(struct ssh_channel);
  7966. c->ssh = ssh;
  7967. remid = ssh_pkt_getuint32(pktin);
  7968. winsize = ssh_pkt_getuint32(pktin);
  7969. pktsize = ssh_pkt_getuint32(pktin);
  7970. if (typelen == 3 && !memcmp(type, "x11", 3)) {
  7971. char *addrstr;
  7972. ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
  7973. addrstr = dupprintf("%.*s", peeraddrlen, NULLTOEMPTY(peeraddr));
  7974. peerport = ssh_pkt_getuint32(pktin);
  7975. logeventf(ssh, "Received X11 connect request from %s:%d",
  7976. addrstr, peerport);
  7977. if (!ssh->X11_fwd_enabled && !ssh->connshare)
  7978. error = "X11 forwarding is not enabled";
  7979. else {
  7980. c->u.x11.xconn = x11_init(ssh->x11authtree, c,
  7981. addrstr, peerport);
  7982. c->type = CHAN_X11;
  7983. c->u.x11.initial = TRUE;
  7984. /*
  7985. * If we are a connection-sharing upstream, then we should
  7986. * initially present a very small window, adequate to take
  7987. * the X11 initial authorisation packet but not much more.
  7988. * Downstream will then present us a larger window (by
  7989. * fiat of the connection-sharing protocol) and we can
  7990. * guarantee to send a positive-valued WINDOW_ADJUST.
  7991. */
  7992. if (ssh->connshare)
  7993. our_winsize_override = 128;
  7994. logevent("Opened X11 forward channel");
  7995. }
  7996. sfree(addrstr);
  7997. } else if (typelen == 15 &&
  7998. !memcmp(type, "forwarded-tcpip", 15)) {
  7999. struct ssh_rportfwd pf, *realpf;
  8000. char *shost;
  8001. int shostlen;
  8002. ssh_pkt_getstring(pktin, &shost, &shostlen);/* skip address */
  8003. pf.shost = dupprintf("%.*s", shostlen, NULLTOEMPTY(shost));
  8004. pf.sport = ssh_pkt_getuint32(pktin);
  8005. ssh_pkt_getstring(pktin, &peeraddr, &peeraddrlen);
  8006. peerport = ssh_pkt_getuint32(pktin);
  8007. realpf = find234(ssh->rportfwds, &pf, NULL);
  8008. logeventf(ssh, "Received remote port %s:%d open request "
  8009. "from %.*s:%d", pf.shost, pf.sport,
  8010. peeraddrlen, NULLTOEMPTY(peeraddr), peerport);
  8011. sfree(pf.shost);
  8012. if (realpf == NULL) {
  8013. error = "Remote port is not recognised";
  8014. } else {
  8015. char *err;
  8016. if (realpf->share_ctx) {
  8017. /*
  8018. * This port forwarding is on behalf of a
  8019. * connection-sharing downstream, so abandon our own
  8020. * channel-open procedure and just pass the message on
  8021. * to sshshare.c.
  8022. */
  8023. share_got_pkt_from_server(realpf->share_ctx, pktin->type,
  8024. pktin->body, pktin->length);
  8025. sfree(c);
  8026. return;
  8027. }
  8028. err = pfd_connect(&c->u.pfd.pf, realpf->dhost, realpf->dport,
  8029. c, ssh->conf, realpf->pfrec->addressfamily);
  8030. logeventf(ssh, "Attempting to forward remote port to "
  8031. "%s:%d", realpf->dhost, realpf->dport);
  8032. if (err != NULL) {
  8033. logeventf(ssh, "Port open failed: %s", err);
  8034. sfree(err);
  8035. error = "Port open failed";
  8036. } else {
  8037. logevent("Forwarded port opened successfully");
  8038. c->type = CHAN_SOCKDATA;
  8039. }
  8040. }
  8041. } else if (typelen == 22 &&
  8042. !memcmp(type, "auth-agent@openssh.com", 22)) {
  8043. if (!ssh->agentfwd_enabled)
  8044. error = "Agent forwarding is not enabled";
  8045. else {
  8046. c->type = CHAN_AGENT; /* identify channel type */
  8047. c->u.a.lensofar = 0;
  8048. c->u.a.message = NULL;
  8049. c->u.a.outstanding_requests = 0;
  8050. }
  8051. } else {
  8052. error = "Unsupported channel type requested";
  8053. }
  8054. c->remoteid = remid;
  8055. c->halfopen = FALSE;
  8056. if (error) {
  8057. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_FAILURE);
  8058. ssh2_pkt_adduint32(pktout, c->remoteid);
  8059. ssh2_pkt_adduint32(pktout, SSH2_OPEN_CONNECT_FAILED);
  8060. ssh2_pkt_addstring(pktout, error);
  8061. ssh2_pkt_addstring(pktout, "en"); /* language tag */
  8062. ssh2_pkt_send(ssh, pktout);
  8063. logeventf(ssh, "Rejected channel open: %s", error);
  8064. sfree(c);
  8065. } else {
  8066. ssh2_channel_init(c);
  8067. c->v.v2.remwindow = winsize;
  8068. c->v.v2.remmaxpkt = pktsize;
  8069. if (our_winsize_override) {
  8070. c->v.v2.locwindow = c->v.v2.locmaxwin = c->v.v2.remlocwin =
  8071. our_winsize_override;
  8072. }
  8073. add234(ssh->channels, c);
  8074. pktout = ssh2_pkt_init(SSH2_MSG_CHANNEL_OPEN_CONFIRMATION);
  8075. ssh2_pkt_adduint32(pktout, c->remoteid);
  8076. ssh2_pkt_adduint32(pktout, c->localid);
  8077. ssh2_pkt_adduint32(pktout, c->v.v2.locwindow);
  8078. ssh2_pkt_adduint32(pktout, OUR_V2_MAXPKT); /* our max pkt size */
  8079. ssh2_pkt_send(ssh, pktout);
  8080. }
  8081. }
  8082. void sshfwd_x11_sharing_handover(struct ssh_channel *c,
  8083. void *share_cs, void *share_chan,
  8084. const char *peer_addr, int peer_port,
  8085. int endian, int protomajor, int protominor,
  8086. const void *initial_data, int initial_len)
  8087. {
  8088. /*
  8089. * This function is called when we've just discovered that an X
  8090. * forwarding channel on which we'd been handling the initial auth
  8091. * ourselves turns out to be destined for a connection-sharing
  8092. * downstream. So we turn the channel into a CHAN_SHARING, meaning
  8093. * that we completely stop tracking windows and buffering data and
  8094. * just pass more or less unmodified SSH messages back and forth.
  8095. */
  8096. c->type = CHAN_SHARING;
  8097. c->u.sharing.ctx = share_cs;
  8098. share_setup_x11_channel(share_cs, share_chan,
  8099. c->localid, c->remoteid, c->v.v2.remwindow,
  8100. c->v.v2.remmaxpkt, c->v.v2.locwindow,
  8101. peer_addr, peer_port, endian,
  8102. protomajor, protominor,
  8103. initial_data, initial_len);
  8104. }
  8105. void sshfwd_x11_is_local(struct ssh_channel *c)
  8106. {
  8107. /*
  8108. * This function is called when we've just discovered that an X
  8109. * forwarding channel is _not_ destined for a connection-sharing
  8110. * downstream but we're going to handle it ourselves. We stop
  8111. * presenting a cautiously small window and go into ordinary data
  8112. * exchange mode.
  8113. */
  8114. c->u.x11.initial = FALSE;
  8115. ssh2_set_window(c, ssh_is_simple(c->ssh) ? OUR_V2_BIGWIN : OUR_V2_WINSIZE);
  8116. }
  8117. /*
  8118. * Buffer banner messages for later display at some convenient point,
  8119. * if we're going to display them.
  8120. */
  8121. static void ssh2_msg_userauth_banner(Ssh ssh, struct Packet *pktin)
  8122. {
  8123. /* Arbitrary limit to prevent unbounded inflation of buffer */
  8124. if (conf_get_int(ssh->conf, CONF_ssh_show_banner) &&
  8125. bufchain_size(&ssh->banner) <= 131072) {
  8126. char *banner = NULL;
  8127. int size = 0;
  8128. ssh_pkt_getstring(pktin, &banner, &size);
  8129. if (banner)
  8130. bufchain_add(&ssh->banner, banner, size);
  8131. }
  8132. }
  8133. /* Helper function to deal with sending tty modes for "pty-req" */
  8134. static void ssh2_send_ttymode(void *data,
  8135. const struct ssh_ttymode *mode, char *val)
  8136. {
  8137. struct Packet *pktout = (struct Packet *)data;
  8138. unsigned int arg = 0;
  8139. switch (mode->type) {
  8140. case TTY_OP_CHAR:
  8141. arg = ssh_tty_parse_specchar(val);
  8142. break;
  8143. case TTY_OP_BOOL:
  8144. arg = ssh_tty_parse_boolean(val);
  8145. break;
  8146. }
  8147. ssh2_pkt_addbyte(pktout, mode->opcode);
  8148. ssh2_pkt_adduint32(pktout, arg);
  8149. }
  8150. static void ssh2_setup_x11(struct ssh_channel *c, struct Packet *pktin,
  8151. void *ctx)
  8152. {
  8153. struct ssh2_setup_x11_state {
  8154. int crLine;
  8155. };
  8156. Ssh ssh = c->ssh;
  8157. struct Packet *pktout;
  8158. crStateP(ssh2_setup_x11_state, ctx);
  8159. crBeginState;
  8160. logevent("Requesting X11 forwarding");
  8161. pktout = ssh2_chanreq_init(ssh->mainchan, "x11-req",
  8162. ssh2_setup_x11, s);
  8163. ssh2_pkt_addbool(pktout, 0); /* many connections */
  8164. ssh2_pkt_addstring(pktout, ssh->x11auth->protoname);
  8165. ssh2_pkt_addstring(pktout, ssh->x11auth->datastring);
  8166. ssh2_pkt_adduint32(pktout, ssh->x11disp->screennum);
  8167. ssh2_pkt_send(ssh, pktout);
  8168. /* Wait to be called back with either a response packet, or NULL
  8169. * meaning clean up and free our data */
  8170. crReturnV;
  8171. if (pktin) {
  8172. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  8173. logevent("X11 forwarding enabled");
  8174. ssh->X11_fwd_enabled = TRUE;
  8175. } else
  8176. logevent("X11 forwarding refused");
  8177. }
  8178. crFinishFreeV;
  8179. }
  8180. static void ssh2_setup_agent(struct ssh_channel *c, struct Packet *pktin,
  8181. void *ctx)
  8182. {
  8183. struct ssh2_setup_agent_state {
  8184. int crLine;
  8185. };
  8186. Ssh ssh = c->ssh;
  8187. struct Packet *pktout;
  8188. crStateP(ssh2_setup_agent_state, ctx);
  8189. crBeginState;
  8190. logevent("Requesting OpenSSH-style agent forwarding");
  8191. pktout = ssh2_chanreq_init(ssh->mainchan, "auth-agent-req@openssh.com",
  8192. ssh2_setup_agent, s);
  8193. ssh2_pkt_send(ssh, pktout);
  8194. /* Wait to be called back with either a response packet, or NULL
  8195. * meaning clean up and free our data */
  8196. crReturnV;
  8197. if (pktin) {
  8198. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  8199. logevent("Agent forwarding enabled");
  8200. ssh->agentfwd_enabled = TRUE;
  8201. } else
  8202. logevent("Agent forwarding refused");
  8203. }
  8204. crFinishFreeV;
  8205. }
  8206. static void ssh2_setup_pty(struct ssh_channel *c, struct Packet *pktin,
  8207. void *ctx)
  8208. {
  8209. struct ssh2_setup_pty_state {
  8210. int crLine;
  8211. };
  8212. Ssh ssh = c->ssh;
  8213. struct Packet *pktout;
  8214. crStateP(ssh2_setup_pty_state, ctx);
  8215. crBeginState;
  8216. /* Unpick the terminal-speed string. */
  8217. /* XXX perhaps we should allow no speeds to be sent. */
  8218. ssh->ospeed = 38400; ssh->ispeed = 38400; /* last-resort defaults */
  8219. sscanf(conf_get_str(ssh->conf, CONF_termspeed), "%d,%d", &ssh->ospeed, &ssh->ispeed);
  8220. /* Build the pty request. */
  8221. pktout = ssh2_chanreq_init(ssh->mainchan, "pty-req",
  8222. ssh2_setup_pty, s);
  8223. ssh2_pkt_addstring(pktout, conf_get_str(ssh->conf, CONF_termtype));
  8224. ssh2_pkt_adduint32(pktout, ssh->term_width);
  8225. ssh2_pkt_adduint32(pktout, ssh->term_height);
  8226. ssh2_pkt_adduint32(pktout, 0); /* pixel width */
  8227. ssh2_pkt_adduint32(pktout, 0); /* pixel height */
  8228. ssh2_pkt_addstring_start(pktout);
  8229. parse_ttymodes(ssh, ssh2_send_ttymode, (void *)pktout);
  8230. ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_ISPEED);
  8231. ssh2_pkt_adduint32(pktout, ssh->ispeed);
  8232. ssh2_pkt_addbyte(pktout, SSH2_TTY_OP_OSPEED);
  8233. ssh2_pkt_adduint32(pktout, ssh->ospeed);
  8234. ssh2_pkt_addstring_data(pktout, "\0", 1); /* TTY_OP_END */
  8235. ssh2_pkt_send(ssh, pktout);
  8236. ssh->state = SSH_STATE_INTERMED;
  8237. /* Wait to be called back with either a response packet, or NULL
  8238. * meaning clean up and free our data */
  8239. crReturnV;
  8240. if (pktin) {
  8241. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS) {
  8242. logeventf(ssh, "Allocated pty (ospeed %dbps, ispeed %dbps)",
  8243. ssh->ospeed, ssh->ispeed);
  8244. ssh->got_pty = TRUE;
  8245. } else {
  8246. c_write_str(ssh, "Server refused to allocate pty\r\n");
  8247. ssh->editing = ssh->echoing = 1;
  8248. }
  8249. }
  8250. crFinishFreeV;
  8251. }
  8252. static void ssh2_setup_env(struct ssh_channel *c, struct Packet *pktin,
  8253. void *ctx)
  8254. {
  8255. struct ssh2_setup_env_state {
  8256. int crLine;
  8257. int num_env, env_left, env_ok;
  8258. };
  8259. Ssh ssh = c->ssh;
  8260. struct Packet *pktout;
  8261. crStateP(ssh2_setup_env_state, ctx);
  8262. crBeginState;
  8263. /*
  8264. * Send environment variables.
  8265. *
  8266. * Simplest thing here is to send all the requests at once, and
  8267. * then wait for a whole bunch of successes or failures.
  8268. */
  8269. s->num_env = 0;
  8270. {
  8271. char *key, *val;
  8272. for (val = conf_get_str_strs(ssh->conf, CONF_environmt, NULL, &key);
  8273. val != NULL;
  8274. val = conf_get_str_strs(ssh->conf, CONF_environmt, key, &key)) {
  8275. pktout = ssh2_chanreq_init(ssh->mainchan, "env", ssh2_setup_env, s);
  8276. ssh2_pkt_addstring(pktout, key);
  8277. ssh2_pkt_addstring(pktout, val);
  8278. ssh2_pkt_send(ssh, pktout);
  8279. s->num_env++;
  8280. }
  8281. if (s->num_env)
  8282. logeventf(ssh, "Sent %d environment variables", s->num_env);
  8283. }
  8284. if (s->num_env) {
  8285. s->env_ok = 0;
  8286. s->env_left = s->num_env;
  8287. while (s->env_left > 0) {
  8288. /* Wait to be called back with either a response packet,
  8289. * or NULL meaning clean up and free our data */
  8290. crReturnV;
  8291. if (!pktin) goto out;
  8292. if (pktin->type == SSH2_MSG_CHANNEL_SUCCESS)
  8293. s->env_ok++;
  8294. s->env_left--;
  8295. }
  8296. if (s->env_ok == s->num_env) {
  8297. logevent("All environment variables successfully set");
  8298. } else if (s->env_ok == 0) {
  8299. logevent("All environment variables refused");
  8300. c_write_str(ssh, "Server refused to set environment variables\r\n");
  8301. } else {
  8302. logeventf(ssh, "%d environment variables refused",
  8303. s->num_env - s->env_ok);
  8304. c_write_str(ssh, "Server refused to set all environment variables\r\n");
  8305. }
  8306. }
  8307. out:;
  8308. crFinishFreeV;
  8309. }
  8310. /*
  8311. * Handle the SSH-2 userauth and connection layers.
  8312. */
  8313. static void ssh2_msg_authconn(Ssh ssh, struct Packet *pktin)
  8314. {
  8315. do_ssh2_authconn(ssh, NULL, 0, pktin);
  8316. }
  8317. static void ssh2_response_authconn(struct ssh_channel *c, struct Packet *pktin,
  8318. void *ctx)
  8319. {
  8320. if (pktin)
  8321. do_ssh2_authconn(c->ssh, NULL, 0, pktin);
  8322. }
  8323. static void do_ssh2_authconn(Ssh ssh, const unsigned char *in, int inlen,
  8324. struct Packet *pktin)
  8325. {
  8326. struct do_ssh2_authconn_state {
  8327. int crLine;
  8328. enum {
  8329. AUTH_TYPE_NONE,
  8330. AUTH_TYPE_PUBLICKEY,
  8331. AUTH_TYPE_PUBLICKEY_OFFER_LOUD,
  8332. AUTH_TYPE_PUBLICKEY_OFFER_QUIET,
  8333. AUTH_TYPE_PASSWORD,
  8334. AUTH_TYPE_GSSAPI, /* always QUIET */
  8335. AUTH_TYPE_KEYBOARD_INTERACTIVE,
  8336. AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET
  8337. } type;
  8338. int done_service_req;
  8339. int gotit, need_pw, can_pubkey, can_passwd, can_keyb_inter;
  8340. int tried_pubkey_config, done_agent;
  8341. #ifndef NO_GSSAPI
  8342. int can_gssapi;
  8343. int tried_gssapi;
  8344. #endif
  8345. int kbd_inter_refused;
  8346. int we_are_in, userauth_success;
  8347. prompts_t *cur_prompt;
  8348. int num_prompts;
  8349. char *username;
  8350. char *password;
  8351. int got_username;
  8352. void *publickey_blob;
  8353. int publickey_bloblen;
  8354. int privatekey_available, privatekey_encrypted;
  8355. char *publickey_algorithm;
  8356. char *publickey_comment;
  8357. unsigned char agent_request[5], *agent_response, *agentp;
  8358. int agent_responselen;
  8359. unsigned char *pkblob_in_agent;
  8360. int keyi, nkeys;
  8361. char *pkblob, *alg, *commentp;
  8362. int pklen, alglen, commentlen;
  8363. int siglen, retlen, len;
  8364. char *q, *agentreq, *ret;
  8365. struct Packet *pktout;
  8366. Filename *keyfile;
  8367. #ifndef NO_GSSAPI
  8368. struct ssh_gss_library *gsslib;
  8369. Ssh_gss_ctx gss_ctx;
  8370. Ssh_gss_buf gss_buf;
  8371. Ssh_gss_buf gss_rcvtok, gss_sndtok;
  8372. Ssh_gss_name gss_srv_name;
  8373. Ssh_gss_stat gss_stat;
  8374. #endif
  8375. };
  8376. crState(do_ssh2_authconn_state);
  8377. crBeginState;
  8378. /* Register as a handler for all the messages this coroutine handles. */
  8379. ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_authconn;
  8380. ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_authconn;
  8381. ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_authconn;
  8382. ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_authconn;
  8383. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_authconn;
  8384. ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_authconn;
  8385. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_authconn; duplicate case value */
  8386. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_authconn; duplicate case value */
  8387. ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_authconn;
  8388. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_authconn;
  8389. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_authconn;
  8390. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_authconn;
  8391. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_authconn;
  8392. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_authconn;
  8393. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_authconn;
  8394. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_authconn;
  8395. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_authconn;
  8396. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_authconn;
  8397. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_authconn;
  8398. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_authconn;
  8399. s->done_service_req = FALSE;
  8400. s->we_are_in = s->userauth_success = FALSE;
  8401. s->agent_response = NULL;
  8402. #ifndef NO_GSSAPI
  8403. s->tried_gssapi = FALSE;
  8404. #endif
  8405. if (!ssh->bare_connection) {
  8406. if (!conf_get_int(ssh->conf, CONF_ssh_no_userauth)) {
  8407. /*
  8408. * Request userauth protocol, and await a response to it.
  8409. */
  8410. s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
  8411. ssh2_pkt_addstring(s->pktout, "ssh-userauth");
  8412. ssh2_pkt_send(ssh, s->pktout);
  8413. crWaitUntilV(pktin);
  8414. if (pktin->type == SSH2_MSG_SERVICE_ACCEPT)
  8415. s->done_service_req = TRUE;
  8416. }
  8417. if (!s->done_service_req) {
  8418. /*
  8419. * Request connection protocol directly, without authentication.
  8420. */
  8421. s->pktout = ssh2_pkt_init(SSH2_MSG_SERVICE_REQUEST);
  8422. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  8423. ssh2_pkt_send(ssh, s->pktout);
  8424. crWaitUntilV(pktin);
  8425. if (pktin->type == SSH2_MSG_SERVICE_ACCEPT) {
  8426. s->we_are_in = TRUE; /* no auth required */
  8427. } else {
  8428. bombout(("Server refused service request"));
  8429. crStopV;
  8430. }
  8431. }
  8432. } else {
  8433. s->we_are_in = TRUE;
  8434. }
  8435. /* Arrange to be able to deal with any BANNERs that come in.
  8436. * (We do this now as packets may come in during the next bit.) */
  8437. bufchain_init(&ssh->banner);
  8438. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] =
  8439. ssh2_msg_userauth_banner;
  8440. /*
  8441. * Misc one-time setup for authentication.
  8442. */
  8443. s->publickey_blob = NULL;
  8444. if (!s->we_are_in) {
  8445. /*
  8446. * Load the public half of any configured public key file
  8447. * for later use.
  8448. */
  8449. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  8450. if (!filename_is_null(s->keyfile)) {
  8451. int keytype;
  8452. logeventf(ssh, "Reading key file \"%.150s\"",
  8453. filename_to_str(s->keyfile));
  8454. keytype = key_type(s->keyfile);
  8455. if (keytype == SSH_KEYTYPE_SSH2 ||
  8456. keytype == SSH_KEYTYPE_SSH2_PUBLIC_RFC4716 ||
  8457. keytype == SSH_KEYTYPE_SSH2_PUBLIC_OPENSSH) {
  8458. const char *error;
  8459. s->publickey_blob =
  8460. ssh2_userkey_loadpub(s->keyfile,
  8461. &s->publickey_algorithm,
  8462. &s->publickey_bloblen,
  8463. &s->publickey_comment, &error);
  8464. if (s->publickey_blob) {
  8465. s->privatekey_available = (keytype == SSH_KEYTYPE_SSH2);
  8466. if (!s->privatekey_available)
  8467. logeventf(ssh, "Key file contains public key only");
  8468. s->privatekey_encrypted =
  8469. ssh2_userkey_encrypted(s->keyfile, NULL);
  8470. } else {
  8471. char *msgbuf;
  8472. logeventf(ssh, "Unable to load key (%s)",
  8473. error);
  8474. msgbuf = dupprintf("Unable to load key file "
  8475. "\"%.150s\" (%s)\r\n",
  8476. filename_to_str(s->keyfile),
  8477. error);
  8478. c_write_str(ssh, msgbuf);
  8479. sfree(msgbuf);
  8480. }
  8481. } else {
  8482. char *msgbuf;
  8483. logeventf(ssh, "Unable to use this key file (%s)",
  8484. key_type_to_str(keytype));
  8485. msgbuf = dupprintf("Unable to use key file \"%.150s\""
  8486. " (%s)\r\n",
  8487. filename_to_str(s->keyfile),
  8488. key_type_to_str(keytype));
  8489. c_write_str(ssh, msgbuf);
  8490. sfree(msgbuf);
  8491. s->publickey_blob = NULL;
  8492. }
  8493. }
  8494. /*
  8495. * Find out about any keys Pageant has (but if there's a
  8496. * public key configured, filter out all others).
  8497. */
  8498. s->nkeys = 0;
  8499. s->agent_response = NULL;
  8500. s->pkblob_in_agent = NULL;
  8501. if (conf_get_int(ssh->conf, CONF_tryagent) && agent_exists()) {
  8502. void *r;
  8503. logevent("Pageant is running. Requesting keys.");
  8504. /* Request the keys held by the agent. */
  8505. PUT_32BIT(s->agent_request, 1);
  8506. s->agent_request[4] = SSH2_AGENTC_REQUEST_IDENTITIES;
  8507. if (!agent_query(s->agent_request, 5, &r, &s->agent_responselen,
  8508. ssh_agent_callback, ssh)) {
  8509. do {
  8510. crReturnV;
  8511. if (pktin) {
  8512. bombout(("Unexpected data from server while"
  8513. " waiting for agent response"));
  8514. crStopV;
  8515. }
  8516. } while (pktin || inlen > 0);
  8517. r = ssh->agent_response;
  8518. s->agent_responselen = ssh->agent_response_len;
  8519. }
  8520. s->agent_response = (unsigned char *) r;
  8521. if (s->agent_response && s->agent_responselen >= 5 &&
  8522. s->agent_response[4] == SSH2_AGENT_IDENTITIES_ANSWER) {
  8523. int keyi;
  8524. unsigned char *p;
  8525. p = s->agent_response + 5;
  8526. s->nkeys = toint(GET_32BIT(p));
  8527. /*
  8528. * Vet the Pageant response to ensure that the key
  8529. * count and blob lengths make sense.
  8530. */
  8531. if (s->nkeys < 0) {
  8532. logeventf(ssh, "Pageant response contained a negative"
  8533. " key count %d", s->nkeys);
  8534. s->nkeys = 0;
  8535. goto done_agent_query;
  8536. } else {
  8537. unsigned char *q = p + 4;
  8538. int lenleft = s->agent_responselen - 5 - 4;
  8539. for (keyi = 0; keyi < s->nkeys; keyi++) {
  8540. int bloblen, commentlen;
  8541. if (lenleft < 4) {
  8542. logeventf(ssh, "Pageant response was truncated");
  8543. s->nkeys = 0;
  8544. goto done_agent_query;
  8545. }
  8546. bloblen = toint(GET_32BIT(q));
  8547. if (bloblen < 0 || bloblen > lenleft) {
  8548. logeventf(ssh, "Pageant response was truncated");
  8549. s->nkeys = 0;
  8550. goto done_agent_query;
  8551. }
  8552. lenleft -= 4 + bloblen;
  8553. q += 4 + bloblen;
  8554. commentlen = toint(GET_32BIT(q));
  8555. if (commentlen < 0 || commentlen > lenleft) {
  8556. logeventf(ssh, "Pageant response was truncated");
  8557. s->nkeys = 0;
  8558. goto done_agent_query;
  8559. }
  8560. lenleft -= 4 + commentlen;
  8561. q += 4 + commentlen;
  8562. }
  8563. }
  8564. p += 4;
  8565. logeventf(ssh, "Pageant has %d SSH-2 keys", s->nkeys);
  8566. if (s->publickey_blob) {
  8567. /* See if configured key is in agent. */
  8568. for (keyi = 0; keyi < s->nkeys; keyi++) {
  8569. s->pklen = toint(GET_32BIT(p));
  8570. if (s->pklen == s->publickey_bloblen &&
  8571. !memcmp(p+4, s->publickey_blob,
  8572. s->publickey_bloblen)) {
  8573. logeventf(ssh, "Pageant key #%d matches "
  8574. "configured key file", keyi);
  8575. s->keyi = keyi;
  8576. s->pkblob_in_agent = p;
  8577. break;
  8578. }
  8579. p += 4 + s->pklen;
  8580. p += toint(GET_32BIT(p)) + 4; /* comment */
  8581. }
  8582. if (!s->pkblob_in_agent) {
  8583. logevent("Configured key file not in Pageant");
  8584. s->nkeys = 0;
  8585. }
  8586. }
  8587. } else {
  8588. logevent("Failed to get reply from Pageant");
  8589. }
  8590. done_agent_query:;
  8591. }
  8592. }
  8593. /*
  8594. * We repeat this whole loop, including the username prompt,
  8595. * until we manage a successful authentication. If the user
  8596. * types the wrong _password_, they can be sent back to the
  8597. * beginning to try another username, if this is configured on.
  8598. * (If they specify a username in the config, they are never
  8599. * asked, even if they do give a wrong password.)
  8600. *
  8601. * I think this best serves the needs of
  8602. *
  8603. * - the people who have no configuration, no keys, and just
  8604. * want to try repeated (username,password) pairs until they
  8605. * type both correctly
  8606. *
  8607. * - people who have keys and configuration but occasionally
  8608. * need to fall back to passwords
  8609. *
  8610. * - people with a key held in Pageant, who might not have
  8611. * logged in to a particular machine before; so they want to
  8612. * type a username, and then _either_ their key will be
  8613. * accepted, _or_ they will type a password. If they mistype
  8614. * the username they will want to be able to get back and
  8615. * retype it!
  8616. */
  8617. s->got_username = FALSE;
  8618. while (!s->we_are_in) {
  8619. /*
  8620. * Get a username.
  8621. */
  8622. if (s->got_username && !conf_get_int(ssh->conf, CONF_change_username)) {
  8623. /*
  8624. * We got a username last time round this loop, and
  8625. * with change_username turned off we don't try to get
  8626. * it again.
  8627. */
  8628. } else if ((ssh->username = get_remote_username(ssh->conf)) == NULL) {
  8629. int ret; /* need not be kept over crReturn */
  8630. s->cur_prompt = new_prompts(ssh->frontend);
  8631. s->cur_prompt->to_server = TRUE;
  8632. s->cur_prompt->name = dupstr("SSH login name");
  8633. add_prompt(s->cur_prompt, dupstr("login as: "), TRUE);
  8634. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  8635. while (ret < 0) {
  8636. ssh->send_ok = 1;
  8637. crWaitUntilV(!pktin);
  8638. ret = get_userpass_input(s->cur_prompt, in, inlen);
  8639. ssh->send_ok = 0;
  8640. }
  8641. if (!ret) {
  8642. /*
  8643. * get_userpass_input() failed to get a username.
  8644. * Terminate.
  8645. */
  8646. free_prompts(s->cur_prompt);
  8647. ssh_disconnect(ssh, "No username provided", NULL, 0, TRUE);
  8648. crStopV;
  8649. }
  8650. ssh->username = dupstr(s->cur_prompt->prompts[0]->result);
  8651. free_prompts(s->cur_prompt);
  8652. } else {
  8653. char *stuff;
  8654. if ((flags & FLAG_VERBOSE) || (flags & FLAG_INTERACTIVE)) {
  8655. stuff = dupprintf("Using username \"%s\".\r\n", ssh->username);
  8656. c_write_str(ssh, stuff);
  8657. sfree(stuff);
  8658. }
  8659. }
  8660. s->got_username = TRUE;
  8661. /*
  8662. * Send an authentication request using method "none": (a)
  8663. * just in case it succeeds, and (b) so that we know what
  8664. * authentication methods we can usefully try next.
  8665. */
  8666. ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
  8667. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  8668. ssh2_pkt_addstring(s->pktout, ssh->username);
  8669. ssh2_pkt_addstring(s->pktout, "ssh-connection");/* service requested */
  8670. ssh2_pkt_addstring(s->pktout, "none"); /* method */
  8671. ssh2_pkt_send(ssh, s->pktout);
  8672. s->type = AUTH_TYPE_NONE;
  8673. s->gotit = FALSE;
  8674. s->we_are_in = FALSE;
  8675. s->tried_pubkey_config = FALSE;
  8676. s->kbd_inter_refused = FALSE;
  8677. /* Reset agent request state. */
  8678. s->done_agent = FALSE;
  8679. if (s->agent_response) {
  8680. if (s->pkblob_in_agent) {
  8681. s->agentp = s->pkblob_in_agent;
  8682. } else {
  8683. s->agentp = s->agent_response + 5 + 4;
  8684. s->keyi = 0;
  8685. }
  8686. }
  8687. while (1) {
  8688. char *methods = NULL;
  8689. int methlen = 0;
  8690. /*
  8691. * Wait for the result of the last authentication request.
  8692. */
  8693. if (!s->gotit)
  8694. crWaitUntilV(pktin);
  8695. /*
  8696. * Now is a convenient point to spew any banner material
  8697. * that we've accumulated. (This should ensure that when
  8698. * we exit the auth loop, we haven't any left to deal
  8699. * with.)
  8700. */
  8701. {
  8702. int size = bufchain_size(&ssh->banner);
  8703. /*
  8704. * Don't show the banner if we're operating in
  8705. * non-verbose non-interactive mode. (It's probably
  8706. * a script, which means nobody will read the
  8707. * banner _anyway_, and moreover the printing of
  8708. * the banner will screw up processing on the
  8709. * output of (say) plink.)
  8710. */
  8711. if (size && (flags & (FLAG_VERBOSE | FLAG_INTERACTIVE))) {
  8712. char *banner = snewn(size, char);
  8713. bufchain_fetch(&ssh->banner, banner, size);
  8714. c_write_untrusted(ssh, banner, size);
  8715. sfree(banner);
  8716. }
  8717. bufchain_clear(&ssh->banner);
  8718. }
  8719. if (pktin->type == SSH2_MSG_USERAUTH_SUCCESS) {
  8720. logevent("Access granted");
  8721. s->we_are_in = s->userauth_success = TRUE;
  8722. break;
  8723. }
  8724. if (pktin->type != SSH2_MSG_USERAUTH_FAILURE && s->type != AUTH_TYPE_GSSAPI) {
  8725. bombout(("Strange packet received during authentication: "
  8726. "type %d", pktin->type));
  8727. crStopV;
  8728. }
  8729. s->gotit = FALSE;
  8730. /*
  8731. * OK, we're now sitting on a USERAUTH_FAILURE message, so
  8732. * we can look at the string in it and know what we can
  8733. * helpfully try next.
  8734. */
  8735. if (pktin->type == SSH2_MSG_USERAUTH_FAILURE) {
  8736. ssh_pkt_getstring(pktin, &methods, &methlen);
  8737. if (!ssh2_pkt_getbool(pktin)) {
  8738. /*
  8739. * We have received an unequivocal Access
  8740. * Denied. This can translate to a variety of
  8741. * messages, or no message at all.
  8742. *
  8743. * For forms of authentication which are attempted
  8744. * implicitly, by which I mean without printing
  8745. * anything in the window indicating that we're
  8746. * trying them, we should never print 'Access
  8747. * denied'.
  8748. *
  8749. * If we do print a message saying that we're
  8750. * attempting some kind of authentication, it's OK
  8751. * to print a followup message saying it failed -
  8752. * but the message may sometimes be more specific
  8753. * than simply 'Access denied'.
  8754. *
  8755. * Additionally, if we'd just tried password
  8756. * authentication, we should break out of this
  8757. * whole loop so as to go back to the username
  8758. * prompt (iff we're configured to allow
  8759. * username change attempts).
  8760. */
  8761. if (s->type == AUTH_TYPE_NONE) {
  8762. /* do nothing */
  8763. } else if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD ||
  8764. s->type == AUTH_TYPE_PUBLICKEY_OFFER_QUIET) {
  8765. if (s->type == AUTH_TYPE_PUBLICKEY_OFFER_LOUD)
  8766. c_write_str(ssh, "Server refused our key\r\n");
  8767. logevent("Server refused our key");
  8768. } else if (s->type == AUTH_TYPE_PUBLICKEY) {
  8769. /* This _shouldn't_ happen except by a
  8770. * protocol bug causing client and server to
  8771. * disagree on what is a correct signature. */
  8772. c_write_str(ssh, "Server refused public-key signature"
  8773. " despite accepting key!\r\n");
  8774. logevent("Server refused public-key signature"
  8775. " despite accepting key!");
  8776. } else if (s->type==AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET) {
  8777. /* quiet, so no c_write */
  8778. logevent("Server refused keyboard-interactive authentication");
  8779. } else if (s->type==AUTH_TYPE_GSSAPI) {
  8780. /* always quiet, so no c_write */
  8781. /* also, the code down in the GSSAPI block has
  8782. * already logged this in the Event Log */
  8783. } else if (s->type == AUTH_TYPE_KEYBOARD_INTERACTIVE) {
  8784. logevent("Keyboard-interactive authentication failed");
  8785. c_write_str(ssh, "Access denied\r\n");
  8786. } else {
  8787. assert(s->type == AUTH_TYPE_PASSWORD);
  8788. logevent("Password authentication failed");
  8789. c_write_str(ssh, "Access denied\r\n");
  8790. if (conf_get_int(ssh->conf, CONF_change_username)) {
  8791. /* XXX perhaps we should allow
  8792. * keyboard-interactive to do this too? */
  8793. s->we_are_in = FALSE;
  8794. break;
  8795. }
  8796. }
  8797. } else {
  8798. c_write_str(ssh, "Further authentication required\r\n");
  8799. logevent("Further authentication required");
  8800. }
  8801. s->can_pubkey =
  8802. in_commasep_string("publickey", methods, methlen);
  8803. s->can_passwd =
  8804. in_commasep_string("password", methods, methlen);
  8805. s->can_keyb_inter = conf_get_int(ssh->conf, CONF_try_ki_auth) &&
  8806. in_commasep_string("keyboard-interactive", methods, methlen);
  8807. #ifndef NO_GSSAPI
  8808. if (conf_get_int(ssh->conf, CONF_try_gssapi_auth) &&
  8809. in_commasep_string("gssapi-with-mic", methods, methlen)) {
  8810. /* Try loading the GSS libraries and see if we
  8811. * have any. */
  8812. if (!ssh->gsslibs)
  8813. ssh->gsslibs = ssh_gss_setup(ssh->conf);
  8814. s->can_gssapi = (ssh->gsslibs->nlibraries > 0);
  8815. } else {
  8816. /* No point in even bothering to try to load the
  8817. * GSS libraries, if the user configuration and
  8818. * server aren't both prepared to attempt GSSAPI
  8819. * auth in the first place. */
  8820. s->can_gssapi = FALSE;
  8821. }
  8822. #endif
  8823. }
  8824. ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
  8825. if (s->can_pubkey && !s->done_agent && s->nkeys) {
  8826. /*
  8827. * Attempt public-key authentication using a key from Pageant.
  8828. */
  8829. ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
  8830. logeventf(ssh, "Trying Pageant key #%d", s->keyi);
  8831. /* Unpack key from agent response */
  8832. s->pklen = toint(GET_32BIT(s->agentp));
  8833. s->agentp += 4;
  8834. s->pkblob = (char *)s->agentp;
  8835. s->agentp += s->pklen;
  8836. s->alglen = toint(GET_32BIT(s->pkblob));
  8837. s->alg = s->pkblob + 4;
  8838. s->commentlen = toint(GET_32BIT(s->agentp));
  8839. s->agentp += 4;
  8840. s->commentp = (char *)s->agentp;
  8841. s->agentp += s->commentlen;
  8842. /* s->agentp now points at next key, if any */
  8843. /* See if server will accept it */
  8844. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  8845. ssh2_pkt_addstring(s->pktout, ssh->username);
  8846. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  8847. /* service requested */
  8848. ssh2_pkt_addstring(s->pktout, "publickey");
  8849. /* method */
  8850. ssh2_pkt_addbool(s->pktout, FALSE); /* no signature included */
  8851. ssh2_pkt_addstring_start(s->pktout);
  8852. ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
  8853. ssh2_pkt_addstring_start(s->pktout);
  8854. ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
  8855. ssh2_pkt_send(ssh, s->pktout);
  8856. s->type = AUTH_TYPE_PUBLICKEY_OFFER_QUIET;
  8857. crWaitUntilV(pktin);
  8858. if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
  8859. /* Offer of key refused. */
  8860. s->gotit = TRUE;
  8861. } else {
  8862. void *vret;
  8863. if (flags & FLAG_VERBOSE) {
  8864. c_write_str(ssh, "Authenticating with "
  8865. "public key \"");
  8866. c_write(ssh, s->commentp, s->commentlen);
  8867. c_write_str(ssh, "\" from agent\r\n");
  8868. }
  8869. /*
  8870. * Server is willing to accept the key.
  8871. * Construct a SIGN_REQUEST.
  8872. */
  8873. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  8874. ssh2_pkt_addstring(s->pktout, ssh->username);
  8875. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  8876. /* service requested */
  8877. ssh2_pkt_addstring(s->pktout, "publickey");
  8878. /* method */
  8879. ssh2_pkt_addbool(s->pktout, TRUE); /* signature included */
  8880. ssh2_pkt_addstring_start(s->pktout);
  8881. ssh2_pkt_addstring_data(s->pktout, s->alg, s->alglen);
  8882. ssh2_pkt_addstring_start(s->pktout);
  8883. ssh2_pkt_addstring_data(s->pktout, s->pkblob, s->pklen);
  8884. /* Ask agent for signature. */
  8885. s->siglen = s->pktout->length - 5 + 4 +
  8886. ssh->v2_session_id_len;
  8887. if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
  8888. s->siglen -= 4;
  8889. s->len = 1; /* message type */
  8890. s->len += 4 + s->pklen; /* key blob */
  8891. s->len += 4 + s->siglen; /* data to sign */
  8892. s->len += 4; /* flags */
  8893. s->agentreq = snewn(4 + s->len, char);
  8894. PUT_32BIT(s->agentreq, s->len);
  8895. s->q = s->agentreq + 4;
  8896. *s->q++ = SSH2_AGENTC_SIGN_REQUEST;
  8897. PUT_32BIT(s->q, s->pklen);
  8898. s->q += 4;
  8899. memcpy(s->q, s->pkblob, s->pklen);
  8900. s->q += s->pklen;
  8901. PUT_32BIT(s->q, s->siglen);
  8902. s->q += 4;
  8903. /* Now the data to be signed... */
  8904. if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
  8905. PUT_32BIT(s->q, ssh->v2_session_id_len);
  8906. s->q += 4;
  8907. }
  8908. memcpy(s->q, ssh->v2_session_id,
  8909. ssh->v2_session_id_len);
  8910. s->q += ssh->v2_session_id_len;
  8911. memcpy(s->q, s->pktout->data + 5,
  8912. s->pktout->length - 5);
  8913. s->q += s->pktout->length - 5;
  8914. /* And finally the (zero) flags word. */
  8915. PUT_32BIT(s->q, 0);
  8916. if (!agent_query(s->agentreq, s->len + 4,
  8917. &vret, &s->retlen,
  8918. ssh_agent_callback, ssh)) {
  8919. do {
  8920. crReturnV;
  8921. if (pktin) {
  8922. bombout(("Unexpected data from server"
  8923. " while waiting for agent"
  8924. " response"));
  8925. crStopV;
  8926. }
  8927. } while (pktin || inlen > 0);
  8928. vret = ssh->agent_response;
  8929. s->retlen = ssh->agent_response_len;
  8930. }
  8931. s->ret = vret;
  8932. sfree(s->agentreq);
  8933. if (s->ret) {
  8934. if (s->retlen >= 9 &&
  8935. s->ret[4] == SSH2_AGENT_SIGN_RESPONSE &&
  8936. GET_32BIT(s->ret + 5) <= (unsigned)(s->retlen-9)) {
  8937. logevent("Sending Pageant's response");
  8938. ssh2_add_sigblob(ssh, s->pktout,
  8939. s->pkblob, s->pklen,
  8940. s->ret + 9,
  8941. GET_32BIT(s->ret + 5));
  8942. ssh2_pkt_send(ssh, s->pktout);
  8943. s->type = AUTH_TYPE_PUBLICKEY;
  8944. } else {
  8945. /* FIXME: less drastic response */
  8946. bombout(("Pageant failed to answer challenge"));
  8947. crStopV;
  8948. }
  8949. }
  8950. }
  8951. /* Do we have any keys left to try? */
  8952. if (s->pkblob_in_agent) {
  8953. s->done_agent = TRUE;
  8954. s->tried_pubkey_config = TRUE;
  8955. } else {
  8956. s->keyi++;
  8957. if (s->keyi >= s->nkeys)
  8958. s->done_agent = TRUE;
  8959. }
  8960. } else if (s->can_pubkey && s->publickey_blob &&
  8961. s->privatekey_available && !s->tried_pubkey_config) {
  8962. struct ssh2_userkey *key; /* not live over crReturn */
  8963. char *passphrase; /* not live over crReturn */
  8964. ssh->pkt_actx = SSH2_PKTCTX_PUBLICKEY;
  8965. s->tried_pubkey_config = TRUE;
  8966. /*
  8967. * Try the public key supplied in the configuration.
  8968. *
  8969. * First, offer the public blob to see if the server is
  8970. * willing to accept it.
  8971. */
  8972. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  8973. ssh2_pkt_addstring(s->pktout, ssh->username);
  8974. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  8975. /* service requested */
  8976. ssh2_pkt_addstring(s->pktout, "publickey"); /* method */
  8977. ssh2_pkt_addbool(s->pktout, FALSE);
  8978. /* no signature included */
  8979. ssh2_pkt_addstring(s->pktout, s->publickey_algorithm);
  8980. ssh2_pkt_addstring_start(s->pktout);
  8981. ssh2_pkt_addstring_data(s->pktout,
  8982. (char *)s->publickey_blob,
  8983. s->publickey_bloblen);
  8984. ssh2_pkt_send(ssh, s->pktout);
  8985. logevent("Offered public key");
  8986. crWaitUntilV(pktin);
  8987. if (pktin->type != SSH2_MSG_USERAUTH_PK_OK) {
  8988. /* Key refused. Give up. */
  8989. s->gotit = TRUE; /* reconsider message next loop */
  8990. s->type = AUTH_TYPE_PUBLICKEY_OFFER_LOUD;
  8991. continue; /* process this new message */
  8992. }
  8993. logevent("Offer of public key accepted");
  8994. /*
  8995. * Actually attempt a serious authentication using
  8996. * the key.
  8997. */
  8998. if (flags & FLAG_VERBOSE) {
  8999. c_write_str(ssh, "Authenticating with public key \"");
  9000. c_write_str(ssh, s->publickey_comment);
  9001. c_write_str(ssh, "\"\r\n");
  9002. }
  9003. key = NULL;
  9004. while (!key) {
  9005. const char *error; /* not live over crReturn */
  9006. if (s->privatekey_encrypted) {
  9007. /*
  9008. * Get a passphrase from the user.
  9009. */
  9010. int ret; /* need not be kept over crReturn */
  9011. s->cur_prompt = new_prompts(ssh->frontend);
  9012. s->cur_prompt->to_server = FALSE;
  9013. s->cur_prompt->name = dupstr("SSH key passphrase");
  9014. add_prompt(s->cur_prompt,
  9015. dupprintf("Passphrase for key \"%.100s\": ",
  9016. s->publickey_comment),
  9017. FALSE);
  9018. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9019. while (ret < 0) {
  9020. ssh->send_ok = 1;
  9021. crWaitUntilV(!pktin);
  9022. ret = get_userpass_input(s->cur_prompt,
  9023. in, inlen);
  9024. ssh->send_ok = 0;
  9025. }
  9026. if (!ret) {
  9027. /* Failed to get a passphrase. Terminate. */
  9028. free_prompts(s->cur_prompt);
  9029. ssh_disconnect(ssh, NULL,
  9030. "Unable to authenticate",
  9031. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9032. TRUE);
  9033. crStopV;
  9034. }
  9035. passphrase =
  9036. dupstr(s->cur_prompt->prompts[0]->result);
  9037. free_prompts(s->cur_prompt);
  9038. } else {
  9039. passphrase = NULL; /* no passphrase needed */
  9040. }
  9041. /*
  9042. * Try decrypting the key.
  9043. */
  9044. s->keyfile = conf_get_filename(ssh->conf, CONF_keyfile);
  9045. key = ssh2_load_userkey(s->keyfile, passphrase, &error);
  9046. if (passphrase) {
  9047. /* burn the evidence */
  9048. smemclr(passphrase, strlen(passphrase));
  9049. sfree(passphrase);
  9050. }
  9051. if (key == SSH2_WRONG_PASSPHRASE || key == NULL) {
  9052. if (passphrase &&
  9053. (key == SSH2_WRONG_PASSPHRASE)) {
  9054. c_write_str(ssh, "Wrong passphrase\r\n");
  9055. key = NULL;
  9056. /* and loop again */
  9057. } else {
  9058. c_write_str(ssh, "Unable to load private key (");
  9059. c_write_str(ssh, error);
  9060. c_write_str(ssh, ")\r\n");
  9061. key = NULL;
  9062. break; /* try something else */
  9063. }
  9064. }
  9065. }
  9066. if (key) {
  9067. unsigned char *pkblob, *sigblob, *sigdata;
  9068. int pkblob_len, sigblob_len, sigdata_len;
  9069. int p;
  9070. /*
  9071. * We have loaded the private key and the server
  9072. * has announced that it's willing to accept it.
  9073. * Hallelujah. Generate a signature and send it.
  9074. */
  9075. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9076. ssh2_pkt_addstring(s->pktout, ssh->username);
  9077. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9078. /* service requested */
  9079. ssh2_pkt_addstring(s->pktout, "publickey");
  9080. /* method */
  9081. ssh2_pkt_addbool(s->pktout, TRUE);
  9082. /* signature follows */
  9083. ssh2_pkt_addstring(s->pktout, key->alg->name);
  9084. pkblob = key->alg->public_blob(key->data,
  9085. &pkblob_len);
  9086. ssh2_pkt_addstring_start(s->pktout);
  9087. ssh2_pkt_addstring_data(s->pktout, (char *)pkblob,
  9088. pkblob_len);
  9089. /*
  9090. * The data to be signed is:
  9091. *
  9092. * string session-id
  9093. *
  9094. * followed by everything so far placed in the
  9095. * outgoing packet.
  9096. */
  9097. sigdata_len = s->pktout->length - 5 + 4 +
  9098. ssh->v2_session_id_len;
  9099. if (ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)
  9100. sigdata_len -= 4;
  9101. sigdata = snewn(sigdata_len, unsigned char);
  9102. p = 0;
  9103. if (!(ssh->remote_bugs & BUG_SSH2_PK_SESSIONID)) {
  9104. PUT_32BIT(sigdata+p, ssh->v2_session_id_len);
  9105. p += 4;
  9106. }
  9107. memcpy(sigdata+p, ssh->v2_session_id,
  9108. ssh->v2_session_id_len);
  9109. p += ssh->v2_session_id_len;
  9110. memcpy(sigdata+p, s->pktout->data + 5,
  9111. s->pktout->length - 5);
  9112. p += s->pktout->length - 5;
  9113. assert(p == sigdata_len);
  9114. sigblob = key->alg->sign(key->data, (char *)sigdata,
  9115. sigdata_len, &sigblob_len);
  9116. ssh2_add_sigblob(ssh, s->pktout, pkblob, pkblob_len,
  9117. sigblob, sigblob_len);
  9118. sfree(pkblob);
  9119. sfree(sigblob);
  9120. sfree(sigdata);
  9121. ssh2_pkt_send(ssh, s->pktout);
  9122. logevent("Sent public key signature");
  9123. s->type = AUTH_TYPE_PUBLICKEY;
  9124. key->alg->freekey(key->data);
  9125. sfree(key->comment);
  9126. sfree(key);
  9127. }
  9128. #ifndef NO_GSSAPI
  9129. } else if (s->can_gssapi && !s->tried_gssapi) {
  9130. /* GSSAPI Authentication */
  9131. int micoffset, len;
  9132. char *data;
  9133. Ssh_gss_buf mic;
  9134. s->type = AUTH_TYPE_GSSAPI;
  9135. s->tried_gssapi = TRUE;
  9136. s->gotit = TRUE;
  9137. ssh->pkt_actx = SSH2_PKTCTX_GSSAPI;
  9138. /*
  9139. * Pick the highest GSS library on the preference
  9140. * list.
  9141. */
  9142. {
  9143. int i, j;
  9144. s->gsslib = NULL;
  9145. for (i = 0; i < ngsslibs; i++) {
  9146. int want_id = conf_get_int_int(ssh->conf,
  9147. CONF_ssh_gsslist, i);
  9148. for (j = 0; j < ssh->gsslibs->nlibraries; j++)
  9149. if (ssh->gsslibs->libraries[j].id == want_id) {
  9150. s->gsslib = &ssh->gsslibs->libraries[j];
  9151. goto got_gsslib; /* double break */
  9152. }
  9153. }
  9154. got_gsslib:
  9155. /*
  9156. * We always expect to have found something in
  9157. * the above loop: we only came here if there
  9158. * was at least one viable GSS library, and the
  9159. * preference list should always mention
  9160. * everything and only change the order.
  9161. */
  9162. assert(s->gsslib);
  9163. }
  9164. if (s->gsslib->gsslogmsg)
  9165. logevent(s->gsslib->gsslogmsg);
  9166. /* Sending USERAUTH_REQUEST with "gssapi-with-mic" method */
  9167. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9168. ssh2_pkt_addstring(s->pktout, ssh->username);
  9169. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9170. ssh2_pkt_addstring(s->pktout, "gssapi-with-mic");
  9171. logevent("Attempting GSSAPI authentication");
  9172. /* add mechanism info */
  9173. s->gsslib->indicate_mech(s->gsslib, &s->gss_buf);
  9174. /* number of GSSAPI mechanisms */
  9175. ssh2_pkt_adduint32(s->pktout,1);
  9176. /* length of OID + 2 */
  9177. ssh2_pkt_adduint32(s->pktout, s->gss_buf.length + 2);
  9178. ssh2_pkt_addbyte(s->pktout, SSH2_GSS_OIDTYPE);
  9179. /* length of OID */
  9180. ssh2_pkt_addbyte(s->pktout, (unsigned char) s->gss_buf.length);
  9181. ssh_pkt_adddata(s->pktout, s->gss_buf.value,
  9182. s->gss_buf.length);
  9183. ssh2_pkt_send(ssh, s->pktout);
  9184. crWaitUntilV(pktin);
  9185. if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_RESPONSE) {
  9186. logevent("GSSAPI authentication request refused");
  9187. continue;
  9188. }
  9189. /* check returned packet ... */
  9190. ssh_pkt_getstring(pktin, &data, &len);
  9191. s->gss_rcvtok.value = data;
  9192. s->gss_rcvtok.length = len;
  9193. if (s->gss_rcvtok.length != s->gss_buf.length + 2 ||
  9194. ((char *)s->gss_rcvtok.value)[0] != SSH2_GSS_OIDTYPE ||
  9195. ((char *)s->gss_rcvtok.value)[1] != s->gss_buf.length ||
  9196. memcmp((char *)s->gss_rcvtok.value + 2,
  9197. s->gss_buf.value,s->gss_buf.length) ) {
  9198. logevent("GSSAPI authentication - wrong response from server");
  9199. continue;
  9200. }
  9201. /* now start running */
  9202. s->gss_stat = s->gsslib->import_name(s->gsslib,
  9203. ssh->fullhostname,
  9204. &s->gss_srv_name);
  9205. if (s->gss_stat != SSH_GSS_OK) {
  9206. if (s->gss_stat == SSH_GSS_BAD_HOST_NAME)
  9207. logevent("GSSAPI import name failed - Bad service name");
  9208. else
  9209. logevent("GSSAPI import name failed");
  9210. continue;
  9211. }
  9212. /* fetch TGT into GSS engine */
  9213. s->gss_stat = s->gsslib->acquire_cred(s->gsslib, &s->gss_ctx);
  9214. if (s->gss_stat != SSH_GSS_OK) {
  9215. logevent("GSSAPI authentication failed to get credentials");
  9216. s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
  9217. continue;
  9218. }
  9219. /* initial tokens are empty */
  9220. SSH_GSS_CLEAR_BUF(&s->gss_rcvtok);
  9221. SSH_GSS_CLEAR_BUF(&s->gss_sndtok);
  9222. /* now enter the loop */
  9223. do {
  9224. s->gss_stat = s->gsslib->init_sec_context
  9225. (s->gsslib,
  9226. &s->gss_ctx,
  9227. s->gss_srv_name,
  9228. conf_get_int(ssh->conf, CONF_gssapifwd),
  9229. &s->gss_rcvtok,
  9230. &s->gss_sndtok);
  9231. if (s->gss_stat!=SSH_GSS_S_COMPLETE &&
  9232. s->gss_stat!=SSH_GSS_S_CONTINUE_NEEDED) {
  9233. logevent("GSSAPI authentication initialisation failed");
  9234. if (s->gsslib->display_status(s->gsslib, s->gss_ctx,
  9235. &s->gss_buf) == SSH_GSS_OK) {
  9236. logevent(s->gss_buf.value);
  9237. sfree(s->gss_buf.value);
  9238. }
  9239. break;
  9240. }
  9241. logevent("GSSAPI authentication initialised");
  9242. /* Client and server now exchange tokens until GSSAPI
  9243. * no longer says CONTINUE_NEEDED */
  9244. if (s->gss_sndtok.length != 0) {
  9245. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_TOKEN);
  9246. ssh_pkt_addstring_start(s->pktout);
  9247. ssh_pkt_addstring_data(s->pktout,s->gss_sndtok.value,s->gss_sndtok.length);
  9248. ssh2_pkt_send(ssh, s->pktout);
  9249. s->gsslib->free_tok(s->gsslib, &s->gss_sndtok);
  9250. }
  9251. if (s->gss_stat == SSH_GSS_S_CONTINUE_NEEDED) {
  9252. crWaitUntilV(pktin);
  9253. if (pktin->type != SSH2_MSG_USERAUTH_GSSAPI_TOKEN) {
  9254. logevent("GSSAPI authentication - bad server response");
  9255. s->gss_stat = SSH_GSS_FAILURE;
  9256. break;
  9257. }
  9258. ssh_pkt_getstring(pktin, &data, &len);
  9259. s->gss_rcvtok.value = data;
  9260. s->gss_rcvtok.length = len;
  9261. }
  9262. } while (s-> gss_stat == SSH_GSS_S_CONTINUE_NEEDED);
  9263. if (s->gss_stat != SSH_GSS_OK) {
  9264. s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
  9265. s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
  9266. continue;
  9267. }
  9268. logevent("GSSAPI authentication loop finished OK");
  9269. /* Now send the MIC */
  9270. s->pktout = ssh2_pkt_init(0);
  9271. micoffset = s->pktout->length;
  9272. ssh_pkt_addstring_start(s->pktout);
  9273. ssh_pkt_addstring_data(s->pktout, (char *)ssh->v2_session_id, ssh->v2_session_id_len);
  9274. ssh_pkt_addbyte(s->pktout, SSH2_MSG_USERAUTH_REQUEST);
  9275. ssh_pkt_addstring(s->pktout, ssh->username);
  9276. ssh_pkt_addstring(s->pktout, "ssh-connection");
  9277. ssh_pkt_addstring(s->pktout, "gssapi-with-mic");
  9278. s->gss_buf.value = (char *)s->pktout->data + micoffset;
  9279. s->gss_buf.length = s->pktout->length - micoffset;
  9280. s->gsslib->get_mic(s->gsslib, s->gss_ctx, &s->gss_buf, &mic);
  9281. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_GSSAPI_MIC);
  9282. ssh_pkt_addstring_start(s->pktout);
  9283. ssh_pkt_addstring_data(s->pktout, mic.value, mic.length);
  9284. ssh2_pkt_send(ssh, s->pktout);
  9285. s->gsslib->free_mic(s->gsslib, &mic);
  9286. s->gotit = FALSE;
  9287. s->gsslib->release_name(s->gsslib, &s->gss_srv_name);
  9288. s->gsslib->release_cred(s->gsslib, &s->gss_ctx);
  9289. continue;
  9290. #endif
  9291. } else if (s->can_keyb_inter && !s->kbd_inter_refused) {
  9292. /*
  9293. * Keyboard-interactive authentication.
  9294. */
  9295. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE;
  9296. ssh->pkt_actx = SSH2_PKTCTX_KBDINTER;
  9297. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9298. ssh2_pkt_addstring(s->pktout, ssh->username);
  9299. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9300. /* service requested */
  9301. ssh2_pkt_addstring(s->pktout, "keyboard-interactive");
  9302. /* method */
  9303. ssh2_pkt_addstring(s->pktout, ""); /* lang */
  9304. ssh2_pkt_addstring(s->pktout, ""); /* submethods */
  9305. ssh2_pkt_send(ssh, s->pktout);
  9306. logevent("Attempting keyboard-interactive authentication");
  9307. crWaitUntilV(pktin);
  9308. if (pktin->type != SSH2_MSG_USERAUTH_INFO_REQUEST) {
  9309. /* Server is not willing to do keyboard-interactive
  9310. * at all (or, bizarrely but legally, accepts the
  9311. * user without actually issuing any prompts).
  9312. * Give up on it entirely. */
  9313. s->gotit = TRUE;
  9314. s->type = AUTH_TYPE_KEYBOARD_INTERACTIVE_QUIET;
  9315. s->kbd_inter_refused = TRUE; /* don't try it again */
  9316. continue;
  9317. }
  9318. /*
  9319. * Loop while the server continues to send INFO_REQUESTs.
  9320. */
  9321. while (pktin->type == SSH2_MSG_USERAUTH_INFO_REQUEST) {
  9322. char *name, *inst, *lang;
  9323. int name_len, inst_len, lang_len;
  9324. int i;
  9325. /*
  9326. * We've got a fresh USERAUTH_INFO_REQUEST.
  9327. * Get the preamble and start building a prompt.
  9328. */
  9329. ssh_pkt_getstring(pktin, &name, &name_len);
  9330. ssh_pkt_getstring(pktin, &inst, &inst_len);
  9331. ssh_pkt_getstring(pktin, &lang, &lang_len);
  9332. s->cur_prompt = new_prompts(ssh->frontend);
  9333. s->cur_prompt->to_server = TRUE;
  9334. /*
  9335. * Get any prompt(s) from the packet.
  9336. */
  9337. s->num_prompts = ssh_pkt_getuint32(pktin);
  9338. for (i = 0; i < s->num_prompts; i++) {
  9339. char *prompt;
  9340. int prompt_len;
  9341. int echo;
  9342. static char noprompt[] =
  9343. "<server failed to send prompt>: ";
  9344. ssh_pkt_getstring(pktin, &prompt, &prompt_len);
  9345. echo = ssh2_pkt_getbool(pktin);
  9346. if (!prompt_len) {
  9347. prompt = noprompt;
  9348. prompt_len = lenof(noprompt)-1;
  9349. }
  9350. add_prompt(s->cur_prompt,
  9351. dupprintf("%.*s", prompt_len, prompt),
  9352. echo);
  9353. }
  9354. if (name_len) {
  9355. /* FIXME: better prefix to distinguish from
  9356. * local prompts? */
  9357. s->cur_prompt->name =
  9358. dupprintf("SSH server: %.*s", name_len, name);
  9359. s->cur_prompt->name_reqd = TRUE;
  9360. } else {
  9361. s->cur_prompt->name =
  9362. dupstr("SSH server authentication");
  9363. s->cur_prompt->name_reqd = FALSE;
  9364. }
  9365. /* We add a prefix to try to make it clear that a prompt
  9366. * has come from the server.
  9367. * FIXME: ugly to print "Using..." in prompt _every_
  9368. * time round. Can this be done more subtly? */
  9369. /* Special case: for reasons best known to themselves,
  9370. * some servers send k-i requests with no prompts and
  9371. * nothing to display. Keep quiet in this case. */
  9372. if (s->num_prompts || name_len || inst_len) {
  9373. s->cur_prompt->instruction =
  9374. dupprintf("Using keyboard-interactive authentication.%s%.*s",
  9375. inst_len ? "\n" : "", inst_len, inst);
  9376. s->cur_prompt->instr_reqd = TRUE;
  9377. } else {
  9378. s->cur_prompt->instr_reqd = FALSE;
  9379. }
  9380. /*
  9381. * Display any instructions, and get the user's
  9382. * response(s).
  9383. */
  9384. {
  9385. int ret; /* not live over crReturn */
  9386. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9387. while (ret < 0) {
  9388. ssh->send_ok = 1;
  9389. crWaitUntilV(!pktin);
  9390. ret = get_userpass_input(s->cur_prompt, in, inlen);
  9391. ssh->send_ok = 0;
  9392. }
  9393. if (!ret) {
  9394. /*
  9395. * Failed to get responses. Terminate.
  9396. */
  9397. free_prompts(s->cur_prompt);
  9398. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  9399. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9400. TRUE);
  9401. crStopV;
  9402. }
  9403. }
  9404. /*
  9405. * Send the response(s) to the server.
  9406. */
  9407. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_INFO_RESPONSE);
  9408. ssh2_pkt_adduint32(s->pktout, s->num_prompts);
  9409. for (i=0; i < s->num_prompts; i++) {
  9410. ssh2_pkt_addstring(s->pktout,
  9411. s->cur_prompt->prompts[i]->result);
  9412. }
  9413. ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
  9414. /*
  9415. * Free the prompts structure from this iteration.
  9416. * If there's another, a new one will be allocated
  9417. * when we return to the top of this while loop.
  9418. */
  9419. free_prompts(s->cur_prompt);
  9420. /*
  9421. * Get the next packet in case it's another
  9422. * INFO_REQUEST.
  9423. */
  9424. crWaitUntilV(pktin);
  9425. }
  9426. /*
  9427. * We should have SUCCESS or FAILURE now.
  9428. */
  9429. s->gotit = TRUE;
  9430. } else if (s->can_passwd) {
  9431. /*
  9432. * Plain old password authentication.
  9433. */
  9434. int ret; /* not live over crReturn */
  9435. int changereq_first_time; /* not live over crReturn */
  9436. ssh->pkt_actx = SSH2_PKTCTX_PASSWORD;
  9437. s->cur_prompt = new_prompts(ssh->frontend);
  9438. s->cur_prompt->to_server = TRUE;
  9439. s->cur_prompt->name = dupstr("SSH password");
  9440. add_prompt(s->cur_prompt, dupprintf("%s@%s's password: ",
  9441. ssh->username,
  9442. ssh->savedhost),
  9443. FALSE);
  9444. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9445. while (ret < 0) {
  9446. ssh->send_ok = 1;
  9447. crWaitUntilV(!pktin);
  9448. ret = get_userpass_input(s->cur_prompt, in, inlen);
  9449. ssh->send_ok = 0;
  9450. }
  9451. if (!ret) {
  9452. /*
  9453. * Failed to get responses. Terminate.
  9454. */
  9455. free_prompts(s->cur_prompt);
  9456. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  9457. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9458. TRUE);
  9459. crStopV;
  9460. }
  9461. /*
  9462. * Squirrel away the password. (We may need it later if
  9463. * asked to change it.)
  9464. */
  9465. s->password = dupstr(s->cur_prompt->prompts[0]->result);
  9466. free_prompts(s->cur_prompt);
  9467. /*
  9468. * Send the password packet.
  9469. *
  9470. * We pad out the password packet to 256 bytes to make
  9471. * it harder for an attacker to find the length of the
  9472. * user's password.
  9473. *
  9474. * Anyone using a password longer than 256 bytes
  9475. * probably doesn't have much to worry about from
  9476. * people who find out how long their password is!
  9477. */
  9478. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9479. ssh2_pkt_addstring(s->pktout, ssh->username);
  9480. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9481. /* service requested */
  9482. ssh2_pkt_addstring(s->pktout, "password");
  9483. ssh2_pkt_addbool(s->pktout, FALSE);
  9484. ssh2_pkt_addstring(s->pktout, s->password);
  9485. ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
  9486. logevent("Sent password");
  9487. s->type = AUTH_TYPE_PASSWORD;
  9488. /*
  9489. * Wait for next packet, in case it's a password change
  9490. * request.
  9491. */
  9492. crWaitUntilV(pktin);
  9493. changereq_first_time = TRUE;
  9494. while (pktin->type == SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ) {
  9495. /*
  9496. * We're being asked for a new password
  9497. * (perhaps not for the first time).
  9498. * Loop until the server accepts it.
  9499. */
  9500. int got_new = FALSE; /* not live over crReturn */
  9501. char *prompt; /* not live over crReturn */
  9502. int prompt_len; /* not live over crReturn */
  9503. {
  9504. const char *msg;
  9505. if (changereq_first_time)
  9506. msg = "Server requested password change";
  9507. else
  9508. msg = "Server rejected new password";
  9509. logevent(msg);
  9510. c_write_str(ssh, msg);
  9511. c_write_str(ssh, "\r\n");
  9512. }
  9513. ssh_pkt_getstring(pktin, &prompt, &prompt_len);
  9514. s->cur_prompt = new_prompts(ssh->frontend);
  9515. s->cur_prompt->to_server = TRUE;
  9516. s->cur_prompt->name = dupstr("New SSH password");
  9517. s->cur_prompt->instruction =
  9518. dupprintf("%.*s", prompt_len, NULLTOEMPTY(prompt));
  9519. s->cur_prompt->instr_reqd = TRUE;
  9520. /*
  9521. * There's no explicit requirement in the protocol
  9522. * for the "old" passwords in the original and
  9523. * password-change messages to be the same, and
  9524. * apparently some Cisco kit supports password change
  9525. * by the user entering a blank password originally
  9526. * and the real password subsequently, so,
  9527. * reluctantly, we prompt for the old password again.
  9528. *
  9529. * (On the other hand, some servers don't even bother
  9530. * to check this field.)
  9531. */
  9532. add_prompt(s->cur_prompt,
  9533. dupstr("Current password (blank for previously entered password): "),
  9534. FALSE);
  9535. add_prompt(s->cur_prompt, dupstr("Enter new password: "),
  9536. FALSE);
  9537. add_prompt(s->cur_prompt, dupstr("Confirm new password: "),
  9538. FALSE);
  9539. /*
  9540. * Loop until the user manages to enter the same
  9541. * password twice.
  9542. */
  9543. while (!got_new) {
  9544. ret = get_userpass_input(s->cur_prompt, NULL, 0);
  9545. while (ret < 0) {
  9546. ssh->send_ok = 1;
  9547. crWaitUntilV(!pktin);
  9548. ret = get_userpass_input(s->cur_prompt, in, inlen);
  9549. ssh->send_ok = 0;
  9550. }
  9551. if (!ret) {
  9552. /*
  9553. * Failed to get responses. Terminate.
  9554. */
  9555. /* burn the evidence */
  9556. free_prompts(s->cur_prompt);
  9557. smemclr(s->password, strlen(s->password));
  9558. sfree(s->password);
  9559. ssh_disconnect(ssh, NULL, "Unable to authenticate",
  9560. SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER,
  9561. TRUE);
  9562. crStopV;
  9563. }
  9564. /*
  9565. * If the user specified a new original password
  9566. * (IYSWIM), overwrite any previously specified
  9567. * one.
  9568. * (A side effect is that the user doesn't have to
  9569. * re-enter it if they louse up the new password.)
  9570. */
  9571. if (s->cur_prompt->prompts[0]->result[0]) {
  9572. smemclr(s->password, strlen(s->password));
  9573. /* burn the evidence */
  9574. sfree(s->password);
  9575. s->password =
  9576. dupstr(s->cur_prompt->prompts[0]->result);
  9577. }
  9578. /*
  9579. * Check the two new passwords match.
  9580. */
  9581. got_new = (strcmp(s->cur_prompt->prompts[1]->result,
  9582. s->cur_prompt->prompts[2]->result)
  9583. == 0);
  9584. if (!got_new)
  9585. /* They don't. Silly user. */
  9586. c_write_str(ssh, "Passwords do not match\r\n");
  9587. }
  9588. /*
  9589. * Send the new password (along with the old one).
  9590. * (see above for padding rationale)
  9591. */
  9592. s->pktout = ssh2_pkt_init(SSH2_MSG_USERAUTH_REQUEST);
  9593. ssh2_pkt_addstring(s->pktout, ssh->username);
  9594. ssh2_pkt_addstring(s->pktout, "ssh-connection");
  9595. /* service requested */
  9596. ssh2_pkt_addstring(s->pktout, "password");
  9597. ssh2_pkt_addbool(s->pktout, TRUE);
  9598. ssh2_pkt_addstring(s->pktout, s->password);
  9599. ssh2_pkt_addstring(s->pktout,
  9600. s->cur_prompt->prompts[1]->result);
  9601. free_prompts(s->cur_prompt);
  9602. ssh2_pkt_send_with_padding(ssh, s->pktout, 256);
  9603. logevent("Sent new password");
  9604. /*
  9605. * Now see what the server has to say about it.
  9606. * (If it's CHANGEREQ again, it's not happy with the
  9607. * new password.)
  9608. */
  9609. crWaitUntilV(pktin);
  9610. changereq_first_time = FALSE;
  9611. }
  9612. /*
  9613. * We need to reexamine the current pktin at the top
  9614. * of the loop. Either:
  9615. * - we weren't asked to change password at all, in
  9616. * which case it's a SUCCESS or FAILURE with the
  9617. * usual meaning
  9618. * - we sent a new password, and the server was
  9619. * either OK with it (SUCCESS or FAILURE w/partial
  9620. * success) or unhappy with the _old_ password
  9621. * (FAILURE w/o partial success)
  9622. * In any of these cases, we go back to the top of
  9623. * the loop and start again.
  9624. */
  9625. s->gotit = TRUE;
  9626. /*
  9627. * We don't need the old password any more, in any
  9628. * case. Burn the evidence.
  9629. */
  9630. smemclr(s->password, strlen(s->password));
  9631. sfree(s->password);
  9632. } else {
  9633. char *str = dupprintf("No supported authentication methods available"
  9634. " (server sent: %.*s)",
  9635. methlen, methods);
  9636. ssh_disconnect(ssh, str,
  9637. "No supported authentication methods available",
  9638. SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
  9639. FALSE);
  9640. sfree(str);
  9641. crStopV;
  9642. }
  9643. }
  9644. }
  9645. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = NULL;
  9646. /* Clear up various bits and pieces from authentication. */
  9647. if (s->publickey_blob) {
  9648. sfree(s->publickey_algorithm);
  9649. sfree(s->publickey_blob);
  9650. sfree(s->publickey_comment);
  9651. }
  9652. if (s->agent_response)
  9653. sfree(s->agent_response);
  9654. if (s->userauth_success && !ssh->bare_connection) {
  9655. /*
  9656. * We've just received USERAUTH_SUCCESS, and we haven't sent any
  9657. * packets since. Signal the transport layer to consider enacting
  9658. * delayed compression.
  9659. *
  9660. * (Relying on we_are_in is not sufficient, as
  9661. * draft-miller-secsh-compression-delayed is quite clear that it
  9662. * triggers on USERAUTH_SUCCESS specifically, and we_are_in can
  9663. * become set for other reasons.)
  9664. */
  9665. do_ssh2_transport(ssh, "enabling delayed compression", -2, NULL);
  9666. }
  9667. ssh->channels = newtree234(ssh_channelcmp);
  9668. /*
  9669. * Set up handlers for some connection protocol messages, so we
  9670. * don't have to handle them repeatedly in this coroutine.
  9671. */
  9672. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] =
  9673. ssh2_msg_channel_window_adjust;
  9674. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] =
  9675. ssh2_msg_global_request;
  9676. /*
  9677. * Create the main session channel.
  9678. */
  9679. if (conf_get_int(ssh->conf, CONF_ssh_no_shell)) {
  9680. ssh->mainchan = NULL;
  9681. } else {
  9682. ssh->mainchan = snew(struct ssh_channel);
  9683. ssh->mainchan->ssh = ssh;
  9684. ssh2_channel_init(ssh->mainchan);
  9685. if (*conf_get_str(ssh->conf, CONF_ssh_nc_host)) {
  9686. /*
  9687. * Just start a direct-tcpip channel and use it as the main
  9688. * channel.
  9689. */
  9690. ssh_send_port_open(ssh->mainchan,
  9691. conf_get_str(ssh->conf, CONF_ssh_nc_host),
  9692. conf_get_int(ssh->conf, CONF_ssh_nc_port),
  9693. "main channel");
  9694. ssh->ncmode = TRUE;
  9695. } else {
  9696. s->pktout = ssh2_chanopen_init(ssh->mainchan, "session");
  9697. logevent("Opening session as main channel");
  9698. ssh2_pkt_send(ssh, s->pktout);
  9699. ssh->ncmode = FALSE;
  9700. }
  9701. crWaitUntilV(pktin);
  9702. if (pktin->type != SSH2_MSG_CHANNEL_OPEN_CONFIRMATION) {
  9703. bombout(("Server refused to open channel"));
  9704. crStopV;
  9705. /* FIXME: error data comes back in FAILURE packet */
  9706. }
  9707. if (ssh_pkt_getuint32(pktin) != ssh->mainchan->localid) {
  9708. bombout(("Server's channel confirmation cited wrong channel"));
  9709. crStopV;
  9710. }
  9711. ssh->mainchan->remoteid = ssh_pkt_getuint32(pktin);
  9712. ssh->mainchan->halfopen = FALSE;
  9713. ssh->mainchan->type = CHAN_MAINSESSION;
  9714. ssh->mainchan->v.v2.remwindow = ssh_pkt_getuint32(pktin);
  9715. ssh->mainchan->v.v2.remmaxpkt = ssh_pkt_getuint32(pktin);
  9716. add234(ssh->channels, ssh->mainchan);
  9717. update_specials_menu(ssh->frontend);
  9718. logevent("Opened main channel");
  9719. }
  9720. /*
  9721. * Now we have a channel, make dispatch table entries for
  9722. * general channel-based messages.
  9723. */
  9724. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] =
  9725. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] =
  9726. ssh2_msg_channel_data;
  9727. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_channel_eof;
  9728. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_channel_close;
  9729. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] =
  9730. ssh2_msg_channel_open_confirmation;
  9731. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] =
  9732. ssh2_msg_channel_open_failure;
  9733. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] =
  9734. ssh2_msg_channel_request;
  9735. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] =
  9736. ssh2_msg_channel_open;
  9737. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_channel_response;
  9738. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_channel_response;
  9739. /*
  9740. * Now the connection protocol is properly up and running, with
  9741. * all those dispatch table entries, so it's safe to let
  9742. * downstreams start trying to open extra channels through us.
  9743. */
  9744. if (ssh->connshare)
  9745. share_activate(ssh->connshare, ssh->v_s);
  9746. if (ssh->mainchan && ssh_is_simple(ssh)) {
  9747. /*
  9748. * This message indicates to the server that we promise
  9749. * not to try to run any other channel in parallel with
  9750. * this one, so it's safe for it to advertise a very large
  9751. * window and leave the flow control to TCP.
  9752. */
  9753. s->pktout = ssh2_chanreq_init(ssh->mainchan,
  9754. "simple@putty.projects.tartarus.org",
  9755. NULL, NULL);
  9756. ssh2_pkt_send(ssh, s->pktout);
  9757. }
  9758. /*
  9759. * Enable port forwardings.
  9760. */
  9761. ssh_setup_portfwd(ssh, ssh->conf);
  9762. if (ssh->mainchan && !ssh->ncmode) {
  9763. /*
  9764. * Send the CHANNEL_REQUESTS for the main session channel.
  9765. * Each one is handled by its own little asynchronous
  9766. * co-routine.
  9767. */
  9768. /* Potentially enable X11 forwarding. */
  9769. if (conf_get_int(ssh->conf, CONF_x11_forward)) {
  9770. ssh->x11disp =
  9771. x11_setup_display(conf_get_str(ssh->conf, CONF_x11_display),
  9772. ssh->conf);
  9773. if (!ssh->x11disp) {
  9774. /* FIXME: return an error message from x11_setup_display */
  9775. logevent("X11 forwarding not enabled: unable to"
  9776. " initialise X display");
  9777. } else {
  9778. ssh->x11auth = x11_invent_fake_auth
  9779. (ssh->x11authtree, conf_get_int(ssh->conf, CONF_x11_auth));
  9780. ssh->x11auth->disp = ssh->x11disp;
  9781. ssh2_setup_x11(ssh->mainchan, NULL, NULL);
  9782. }
  9783. }
  9784. /* Potentially enable agent forwarding. */
  9785. if (ssh_agent_forwarding_permitted(ssh))
  9786. ssh2_setup_agent(ssh->mainchan, NULL, NULL);
  9787. /* Now allocate a pty for the session. */
  9788. if (!conf_get_int(ssh->conf, CONF_nopty))
  9789. ssh2_setup_pty(ssh->mainchan, NULL, NULL);
  9790. /* Send environment variables. */
  9791. ssh2_setup_env(ssh->mainchan, NULL, NULL);
  9792. /*
  9793. * Start a shell or a remote command. We may have to attempt
  9794. * this twice if the config data has provided a second choice
  9795. * of command.
  9796. */
  9797. while (1) {
  9798. int subsys;
  9799. char *cmd;
  9800. if (ssh->fallback_cmd) {
  9801. subsys = conf_get_int(ssh->conf, CONF_ssh_subsys2);
  9802. cmd = conf_get_str(ssh->conf, CONF_remote_cmd2);
  9803. } else {
  9804. subsys = conf_get_int(ssh->conf, CONF_ssh_subsys);
  9805. cmd = conf_get_str(ssh->conf, CONF_remote_cmd);
  9806. }
  9807. if (subsys) {
  9808. s->pktout = ssh2_chanreq_init(ssh->mainchan, "subsystem",
  9809. ssh2_response_authconn, NULL);
  9810. ssh2_pkt_addstring(s->pktout, cmd);
  9811. } else if (*cmd) {
  9812. s->pktout = ssh2_chanreq_init(ssh->mainchan, "exec",
  9813. ssh2_response_authconn, NULL);
  9814. ssh2_pkt_addstring(s->pktout, cmd);
  9815. } else {
  9816. s->pktout = ssh2_chanreq_init(ssh->mainchan, "shell",
  9817. ssh2_response_authconn, NULL);
  9818. }
  9819. ssh2_pkt_send(ssh, s->pktout);
  9820. crWaitUntilV(pktin);
  9821. if (pktin->type != SSH2_MSG_CHANNEL_SUCCESS) {
  9822. if (pktin->type != SSH2_MSG_CHANNEL_FAILURE) {
  9823. bombout(("Unexpected response to shell/command request:"
  9824. " packet type %d", pktin->type));
  9825. crStopV;
  9826. }
  9827. /*
  9828. * We failed to start the command. If this is the
  9829. * fallback command, we really are finished; if it's
  9830. * not, and if the fallback command exists, try falling
  9831. * back to it before complaining.
  9832. */
  9833. if (!ssh->fallback_cmd &&
  9834. *conf_get_str(ssh->conf, CONF_remote_cmd2)) {
  9835. logevent("Primary command failed; attempting fallback");
  9836. ssh->fallback_cmd = TRUE;
  9837. continue;
  9838. }
  9839. bombout(("Server refused to start a shell/command"));
  9840. crStopV;
  9841. } else {
  9842. logevent("Started a shell/command");
  9843. }
  9844. break;
  9845. }
  9846. } else {
  9847. ssh->editing = ssh->echoing = TRUE;
  9848. }
  9849. ssh->state = SSH_STATE_SESSION;
  9850. if (ssh->size_needed)
  9851. ssh_size(ssh, ssh->term_width, ssh->term_height);
  9852. if (ssh->eof_needed)
  9853. ssh_special(ssh, TS_EOF);
  9854. /*
  9855. * Transfer data!
  9856. */
  9857. if (ssh->ldisc)
  9858. ldisc_echoedit_update(ssh->ldisc); /* cause ldisc to notice changes */
  9859. if (ssh->mainchan)
  9860. ssh->send_ok = 1;
  9861. while (1) {
  9862. crReturnV;
  9863. if (pktin) {
  9864. /*
  9865. * _All_ the connection-layer packets we expect to
  9866. * receive are now handled by the dispatch table.
  9867. * Anything that reaches here must be bogus.
  9868. */
  9869. bombout(("Strange packet received: type %d", pktin->type));
  9870. crStopV;
  9871. } else if (ssh->mainchan) {
  9872. /*
  9873. * We have spare data. Add it to the channel buffer.
  9874. */
  9875. ssh_send_channel_data(ssh->mainchan, (char *)in, inlen);
  9876. }
  9877. }
  9878. crFinishV;
  9879. }
  9880. /*
  9881. * Handlers for SSH-2 messages that might arrive at any moment.
  9882. */
  9883. static void ssh2_msg_disconnect(Ssh ssh, struct Packet *pktin)
  9884. {
  9885. /* log reason code in disconnect message */
  9886. char *buf, *msg;
  9887. int reason, msglen;
  9888. reason = ssh_pkt_getuint32(pktin);
  9889. ssh_pkt_getstring(pktin, &msg, &msglen);
  9890. if (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) {
  9891. buf = dupprintf("Received disconnect message (%s)",
  9892. ssh2_disconnect_reasons[reason]);
  9893. } else {
  9894. buf = dupprintf("Received disconnect message (unknown"
  9895. " type %d)", reason);
  9896. }
  9897. logevent(buf);
  9898. sfree(buf);
  9899. buf = dupprintf("Disconnection message text: %.*s",
  9900. msglen, NULLTOEMPTY(msg));
  9901. logevent(buf);
  9902. bombout(("Server sent disconnect message\ntype %d (%s):\n\"%.*s\"",
  9903. reason,
  9904. (reason > 0 && reason < lenof(ssh2_disconnect_reasons)) ?
  9905. ssh2_disconnect_reasons[reason] : "unknown",
  9906. msglen, NULLTOEMPTY(msg)));
  9907. sfree(buf);
  9908. }
  9909. static void ssh2_msg_debug(Ssh ssh, struct Packet *pktin)
  9910. {
  9911. /* log the debug message */
  9912. char *msg;
  9913. int msglen;
  9914. /* XXX maybe we should actually take notice of the return value */
  9915. ssh2_pkt_getbool(pktin);
  9916. ssh_pkt_getstring(pktin, &msg, &msglen);
  9917. logeventf(ssh, "Remote debug message: %.*s", msglen, NULLTOEMPTY(msg));
  9918. }
  9919. static void ssh2_msg_transport(Ssh ssh, struct Packet *pktin)
  9920. {
  9921. do_ssh2_transport(ssh, NULL, 0, pktin);
  9922. }
  9923. /*
  9924. * Called if we receive a packet that isn't allowed by the protocol.
  9925. * This only applies to packets whose meaning PuTTY understands.
  9926. * Entirely unknown packets are handled below.
  9927. */
  9928. static void ssh2_msg_unexpected(Ssh ssh, struct Packet *pktin)
  9929. {
  9930. char *buf = dupprintf("Server protocol violation: unexpected %s packet",
  9931. ssh2_pkt_type(ssh->pkt_kctx, ssh->pkt_actx,
  9932. pktin->type));
  9933. ssh_disconnect(ssh, NULL, buf, SSH2_DISCONNECT_PROTOCOL_ERROR, FALSE);
  9934. sfree(buf);
  9935. }
  9936. static void ssh2_msg_something_unimplemented(Ssh ssh, struct Packet *pktin)
  9937. {
  9938. struct Packet *pktout;
  9939. pktout = ssh2_pkt_init(SSH2_MSG_UNIMPLEMENTED);
  9940. ssh2_pkt_adduint32(pktout, pktin->sequence);
  9941. /*
  9942. * UNIMPLEMENTED messages MUST appear in the same order as the
  9943. * messages they respond to. Hence, never queue them.
  9944. */
  9945. ssh2_pkt_send_noqueue(ssh, pktout);
  9946. }
  9947. /*
  9948. * Handle the top-level SSH-2 protocol.
  9949. */
  9950. static void ssh2_protocol_setup(Ssh ssh)
  9951. {
  9952. int i;
  9953. /*
  9954. * Most messages cause SSH2_MSG_UNIMPLEMENTED.
  9955. */
  9956. for (i = 0; i < 256; i++)
  9957. ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
  9958. /*
  9959. * Initially, we only accept transport messages (and a few generic
  9960. * ones). do_ssh2_authconn will add more when it starts.
  9961. * Messages that are understood but not currently acceptable go to
  9962. * ssh2_msg_unexpected.
  9963. */
  9964. ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
  9965. ssh->packet_dispatch[SSH2_MSG_SERVICE_REQUEST] = ssh2_msg_unexpected;
  9966. ssh->packet_dispatch[SSH2_MSG_SERVICE_ACCEPT] = ssh2_msg_unexpected;
  9967. ssh->packet_dispatch[SSH2_MSG_KEXINIT] = ssh2_msg_transport;
  9968. ssh->packet_dispatch[SSH2_MSG_NEWKEYS] = ssh2_msg_transport;
  9969. ssh->packet_dispatch[SSH2_MSG_KEXDH_INIT] = ssh2_msg_transport;
  9970. ssh->packet_dispatch[SSH2_MSG_KEXDH_REPLY] = ssh2_msg_transport;
  9971. /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REQUEST] = ssh2_msg_transport; duplicate case value */
  9972. /* ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_GROUP] = ssh2_msg_transport; duplicate case value */
  9973. ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_INIT] = ssh2_msg_transport;
  9974. ssh->packet_dispatch[SSH2_MSG_KEX_DH_GEX_REPLY] = ssh2_msg_transport;
  9975. ssh->packet_dispatch[SSH2_MSG_USERAUTH_REQUEST] = ssh2_msg_unexpected;
  9976. ssh->packet_dispatch[SSH2_MSG_USERAUTH_FAILURE] = ssh2_msg_unexpected;
  9977. ssh->packet_dispatch[SSH2_MSG_USERAUTH_SUCCESS] = ssh2_msg_unexpected;
  9978. ssh->packet_dispatch[SSH2_MSG_USERAUTH_BANNER] = ssh2_msg_unexpected;
  9979. ssh->packet_dispatch[SSH2_MSG_USERAUTH_PK_OK] = ssh2_msg_unexpected;
  9980. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ] = ssh2_msg_unexpected; duplicate case value */
  9981. /* ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_REQUEST] = ssh2_msg_unexpected; duplicate case value */
  9982. ssh->packet_dispatch[SSH2_MSG_USERAUTH_INFO_RESPONSE] = ssh2_msg_unexpected;
  9983. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
  9984. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
  9985. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
  9986. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
  9987. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
  9988. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
  9989. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
  9990. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
  9991. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
  9992. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
  9993. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
  9994. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
  9995. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
  9996. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
  9997. /*
  9998. * These messages have a special handler from the start.
  9999. */
  10000. ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
  10001. ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore; /* shared with SSH-1 */
  10002. ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
  10003. }
  10004. static void ssh2_bare_connection_protocol_setup(Ssh ssh)
  10005. {
  10006. int i;
  10007. /*
  10008. * Most messages cause SSH2_MSG_UNIMPLEMENTED.
  10009. */
  10010. for (i = 0; i < 256; i++)
  10011. ssh->packet_dispatch[i] = ssh2_msg_something_unimplemented;
  10012. /*
  10013. * Initially, we set all ssh-connection messages to 'unexpected';
  10014. * do_ssh2_authconn will fill things in properly. We also handle a
  10015. * couple of messages from the transport protocol which aren't
  10016. * related to key exchange (UNIMPLEMENTED, IGNORE, DEBUG,
  10017. * DISCONNECT).
  10018. */
  10019. ssh->packet_dispatch[SSH2_MSG_GLOBAL_REQUEST] = ssh2_msg_unexpected;
  10020. ssh->packet_dispatch[SSH2_MSG_REQUEST_SUCCESS] = ssh2_msg_unexpected;
  10021. ssh->packet_dispatch[SSH2_MSG_REQUEST_FAILURE] = ssh2_msg_unexpected;
  10022. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN] = ssh2_msg_unexpected;
  10023. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_CONFIRMATION] = ssh2_msg_unexpected;
  10024. ssh->packet_dispatch[SSH2_MSG_CHANNEL_OPEN_FAILURE] = ssh2_msg_unexpected;
  10025. ssh->packet_dispatch[SSH2_MSG_CHANNEL_WINDOW_ADJUST] = ssh2_msg_unexpected;
  10026. ssh->packet_dispatch[SSH2_MSG_CHANNEL_DATA] = ssh2_msg_unexpected;
  10027. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EXTENDED_DATA] = ssh2_msg_unexpected;
  10028. ssh->packet_dispatch[SSH2_MSG_CHANNEL_EOF] = ssh2_msg_unexpected;
  10029. ssh->packet_dispatch[SSH2_MSG_CHANNEL_CLOSE] = ssh2_msg_unexpected;
  10030. ssh->packet_dispatch[SSH2_MSG_CHANNEL_REQUEST] = ssh2_msg_unexpected;
  10031. ssh->packet_dispatch[SSH2_MSG_CHANNEL_SUCCESS] = ssh2_msg_unexpected;
  10032. ssh->packet_dispatch[SSH2_MSG_CHANNEL_FAILURE] = ssh2_msg_unexpected;
  10033. ssh->packet_dispatch[SSH2_MSG_UNIMPLEMENTED] = ssh2_msg_unexpected;
  10034. /*
  10035. * These messages have a special handler from the start.
  10036. */
  10037. ssh->packet_dispatch[SSH2_MSG_DISCONNECT] = ssh2_msg_disconnect;
  10038. ssh->packet_dispatch[SSH2_MSG_IGNORE] = ssh_msg_ignore;
  10039. ssh->packet_dispatch[SSH2_MSG_DEBUG] = ssh2_msg_debug;
  10040. }
  10041. static void ssh2_timer(void *ctx, unsigned long now)
  10042. {
  10043. Ssh ssh = (Ssh)ctx;
  10044. if (ssh->state == SSH_STATE_CLOSED)
  10045. return;
  10046. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10047. conf_get_int(ssh->conf, CONF_ssh_rekey_time) != 0 &&
  10048. now == ssh->next_rekey) {
  10049. do_ssh2_transport(ssh, "timeout", -1, NULL);
  10050. }
  10051. }
  10052. static void ssh2_protocol(Ssh ssh, const void *vin, int inlen,
  10053. struct Packet *pktin)
  10054. {
  10055. const unsigned char *in = (const unsigned char *)vin;
  10056. if (ssh->state == SSH_STATE_CLOSED)
  10057. return;
  10058. if (pktin) {
  10059. ssh->incoming_data_size += pktin->encrypted_len;
  10060. if (!ssh->kex_in_progress &&
  10061. ssh->max_data_size != 0 &&
  10062. ssh->incoming_data_size > ssh->max_data_size)
  10063. do_ssh2_transport(ssh, "too much data received", -1, NULL);
  10064. }
  10065. if (pktin)
  10066. ssh->packet_dispatch[pktin->type](ssh, pktin);
  10067. else if (!ssh->protocol_initial_phase_done)
  10068. do_ssh2_transport(ssh, in, inlen, pktin);
  10069. else
  10070. do_ssh2_authconn(ssh, in, inlen, pktin);
  10071. }
  10072. static void ssh2_bare_connection_protocol(Ssh ssh, const void *vin, int inlen,
  10073. struct Packet *pktin)
  10074. {
  10075. const unsigned char *in = (const unsigned char *)vin;
  10076. if (ssh->state == SSH_STATE_CLOSED)
  10077. return;
  10078. if (pktin)
  10079. ssh->packet_dispatch[pktin->type](ssh, pktin);
  10080. else
  10081. do_ssh2_authconn(ssh, in, inlen, pktin);
  10082. }
  10083. static void ssh_cache_conf_values(Ssh ssh)
  10084. {
  10085. ssh->logomitdata = conf_get_int(ssh->conf, CONF_logomitdata);
  10086. }
  10087. /*
  10088. * Called to set up the connection.
  10089. *
  10090. * Returns an error message, or NULL on success.
  10091. */
  10092. static const char *ssh_init(void *frontend_handle, void **backend_handle,
  10093. Conf *conf,
  10094. const char *host, int port, char **realhost,
  10095. int nodelay, int keepalive)
  10096. {
  10097. const char *p;
  10098. Ssh ssh;
  10099. ssh = snew(struct ssh_tag);
  10100. ssh->conf = conf_copy(conf);
  10101. ssh_cache_conf_values(ssh);
  10102. ssh->version = 0; /* when not ready yet */
  10103. ssh->s = NULL;
  10104. ssh->cipher = NULL;
  10105. ssh->v1_cipher_ctx = NULL;
  10106. ssh->crcda_ctx = NULL;
  10107. ssh->cscipher = NULL;
  10108. ssh->cs_cipher_ctx = NULL;
  10109. ssh->sccipher = NULL;
  10110. ssh->sc_cipher_ctx = NULL;
  10111. ssh->csmac = NULL;
  10112. ssh->cs_mac_ctx = NULL;
  10113. ssh->scmac = NULL;
  10114. ssh->sc_mac_ctx = NULL;
  10115. ssh->cscomp = NULL;
  10116. ssh->cs_comp_ctx = NULL;
  10117. ssh->sccomp = NULL;
  10118. ssh->sc_comp_ctx = NULL;
  10119. ssh->kex = NULL;
  10120. ssh->kex_ctx = NULL;
  10121. ssh->hostkey = NULL;
  10122. ssh->hostkey_str = NULL;
  10123. ssh->exitcode = -1;
  10124. ssh->close_expected = FALSE;
  10125. ssh->clean_exit = FALSE;
  10126. ssh->state = SSH_STATE_PREPACKET;
  10127. ssh->size_needed = FALSE;
  10128. ssh->eof_needed = FALSE;
  10129. ssh->ldisc = NULL;
  10130. ssh->logctx = NULL;
  10131. ssh->deferred_send_data = NULL;
  10132. ssh->deferred_len = 0;
  10133. ssh->deferred_size = 0;
  10134. ssh->fallback_cmd = 0;
  10135. ssh->pkt_kctx = SSH2_PKTCTX_NOKEX;
  10136. ssh->pkt_actx = SSH2_PKTCTX_NOAUTH;
  10137. ssh->x11disp = NULL;
  10138. ssh->x11auth = NULL;
  10139. ssh->x11authtree = newtree234(x11_authcmp);
  10140. ssh->v1_compressing = FALSE;
  10141. ssh->v2_outgoing_sequence = 0;
  10142. ssh->ssh1_rdpkt_crstate = 0;
  10143. ssh->ssh2_rdpkt_crstate = 0;
  10144. ssh->ssh2_bare_rdpkt_crstate = 0;
  10145. ssh->ssh_gotdata_crstate = 0;
  10146. ssh->do_ssh1_connection_crstate = 0;
  10147. ssh->do_ssh_init_state = NULL;
  10148. ssh->do_ssh_connection_init_state = NULL;
  10149. ssh->do_ssh1_login_state = NULL;
  10150. ssh->do_ssh2_transport_state = NULL;
  10151. ssh->do_ssh2_authconn_state = NULL;
  10152. ssh->v_c = NULL;
  10153. ssh->v_s = NULL;
  10154. ssh->mainchan = NULL;
  10155. ssh->throttled_all = 0;
  10156. ssh->v1_stdout_throttling = 0;
  10157. ssh->queue = NULL;
  10158. ssh->queuelen = ssh->queuesize = 0;
  10159. ssh->queueing = FALSE;
  10160. ssh->qhead = ssh->qtail = NULL;
  10161. ssh->deferred_rekey_reason = NULL;
  10162. bufchain_init(&ssh->queued_incoming_data);
  10163. ssh->frozen = FALSE;
  10164. ssh->username = NULL;
  10165. ssh->sent_console_eof = FALSE;
  10166. ssh->got_pty = FALSE;
  10167. ssh->bare_connection = FALSE;
  10168. ssh->X11_fwd_enabled = FALSE;
  10169. ssh->connshare = NULL;
  10170. ssh->attempting_connshare = FALSE;
  10171. ssh->session_started = FALSE;
  10172. ssh->specials = NULL;
  10173. ssh->n_uncert_hostkeys = 0;
  10174. ssh->cross_certifying = FALSE;
  10175. *backend_handle = ssh;
  10176. #ifdef MSCRYPTOAPI
  10177. if (crypto_startup() == 0)
  10178. return "Microsoft high encryption pack not installed!";
  10179. #endif
  10180. ssh->frontend = frontend_handle;
  10181. ssh->term_width = conf_get_int(ssh->conf, CONF_width);
  10182. ssh->term_height = conf_get_int(ssh->conf, CONF_height);
  10183. ssh->channels = NULL;
  10184. ssh->rportfwds = NULL;
  10185. ssh->portfwds = NULL;
  10186. ssh->send_ok = 0;
  10187. ssh->editing = 0;
  10188. ssh->echoing = 0;
  10189. ssh->conn_throttle_count = 0;
  10190. ssh->overall_bufsize = 0;
  10191. ssh->fallback_cmd = 0;
  10192. ssh->protocol = NULL;
  10193. ssh->protocol_initial_phase_done = FALSE;
  10194. ssh->pinger = NULL;
  10195. ssh->incoming_data_size = ssh->outgoing_data_size =
  10196. ssh->deferred_data_size = 0L;
  10197. ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
  10198. CONF_ssh_rekey_data));
  10199. ssh->kex_in_progress = FALSE;
  10200. #ifndef NO_GSSAPI
  10201. ssh->gsslibs = NULL;
  10202. #endif
  10203. random_ref(); /* do this now - may be needed by sharing setup code */
  10204. p = connect_to_host(ssh, host, port, realhost, nodelay, keepalive);
  10205. if (p != NULL) {
  10206. random_unref();
  10207. return p;
  10208. }
  10209. return NULL;
  10210. }
  10211. static void ssh_free(void *handle)
  10212. {
  10213. Ssh ssh = (Ssh) handle;
  10214. struct ssh_channel *c;
  10215. struct ssh_rportfwd *pf;
  10216. struct X11FakeAuth *auth;
  10217. if (ssh->v1_cipher_ctx)
  10218. ssh->cipher->free_context(ssh->v1_cipher_ctx);
  10219. if (ssh->cs_cipher_ctx)
  10220. ssh->cscipher->free_context(ssh->cs_cipher_ctx);
  10221. if (ssh->sc_cipher_ctx)
  10222. ssh->sccipher->free_context(ssh->sc_cipher_ctx);
  10223. if (ssh->cs_mac_ctx)
  10224. ssh->csmac->free_context(ssh->cs_mac_ctx);
  10225. if (ssh->sc_mac_ctx)
  10226. ssh->scmac->free_context(ssh->sc_mac_ctx);
  10227. if (ssh->cs_comp_ctx) {
  10228. if (ssh->cscomp)
  10229. ssh->cscomp->compress_cleanup(ssh->cs_comp_ctx);
  10230. else
  10231. zlib_compress_cleanup(ssh->cs_comp_ctx);
  10232. }
  10233. if (ssh->sc_comp_ctx) {
  10234. if (ssh->sccomp)
  10235. ssh->sccomp->decompress_cleanup(ssh->sc_comp_ctx);
  10236. else
  10237. zlib_decompress_cleanup(ssh->sc_comp_ctx);
  10238. }
  10239. if (ssh->kex_ctx)
  10240. dh_cleanup(ssh->kex_ctx);
  10241. sfree(ssh->savedhost);
  10242. while (ssh->queuelen-- > 0)
  10243. ssh_free_packet(ssh->queue[ssh->queuelen]);
  10244. sfree(ssh->queue);
  10245. while (ssh->qhead) {
  10246. struct queued_handler *qh = ssh->qhead;
  10247. ssh->qhead = qh->next;
  10248. sfree(qh);
  10249. }
  10250. ssh->qhead = ssh->qtail = NULL;
  10251. if (ssh->channels) {
  10252. while ((c = delpos234(ssh->channels, 0)) != NULL) {
  10253. switch (c->type) {
  10254. case CHAN_X11:
  10255. if (c->u.x11.xconn != NULL)
  10256. x11_close(c->u.x11.xconn);
  10257. break;
  10258. case CHAN_SOCKDATA:
  10259. case CHAN_SOCKDATA_DORMANT:
  10260. if (c->u.pfd.pf != NULL)
  10261. pfd_close(c->u.pfd.pf);
  10262. break;
  10263. }
  10264. if (ssh->version == 2) {
  10265. struct outstanding_channel_request *ocr, *nocr;
  10266. ocr = c->v.v2.chanreq_head;
  10267. while (ocr) {
  10268. ocr->handler(c, NULL, ocr->ctx);
  10269. nocr = ocr->next;
  10270. sfree(ocr);
  10271. ocr = nocr;
  10272. }
  10273. bufchain_clear(&c->v.v2.outbuffer);
  10274. }
  10275. sfree(c);
  10276. }
  10277. freetree234(ssh->channels);
  10278. ssh->channels = NULL;
  10279. }
  10280. if (ssh->connshare)
  10281. sharestate_free(ssh->connshare);
  10282. if (ssh->rportfwds) {
  10283. while ((pf = delpos234(ssh->rportfwds, 0)) != NULL)
  10284. free_rportfwd(pf);
  10285. freetree234(ssh->rportfwds);
  10286. ssh->rportfwds = NULL;
  10287. }
  10288. sfree(ssh->deferred_send_data);
  10289. if (ssh->x11disp)
  10290. x11_free_display(ssh->x11disp);
  10291. while ((auth = delpos234(ssh->x11authtree, 0)) != NULL)
  10292. x11_free_fake_auth(auth);
  10293. freetree234(ssh->x11authtree);
  10294. sfree(ssh->do_ssh_init_state);
  10295. sfree(ssh->do_ssh1_login_state);
  10296. sfree(ssh->do_ssh2_transport_state);
  10297. sfree(ssh->do_ssh2_authconn_state);
  10298. sfree(ssh->v_c);
  10299. sfree(ssh->v_s);
  10300. sfree(ssh->fullhostname);
  10301. sfree(ssh->hostkey_str);
  10302. sfree(ssh->specials);
  10303. if (ssh->crcda_ctx) {
  10304. crcda_free_context(ssh->crcda_ctx);
  10305. ssh->crcda_ctx = NULL;
  10306. }
  10307. if (ssh->s)
  10308. ssh_do_close(ssh, TRUE);
  10309. expire_timer_context(ssh);
  10310. if (ssh->pinger)
  10311. pinger_free(ssh->pinger);
  10312. bufchain_clear(&ssh->queued_incoming_data);
  10313. sfree(ssh->username);
  10314. conf_free(ssh->conf);
  10315. #ifndef NO_GSSAPI
  10316. if (ssh->gsslibs)
  10317. ssh_gss_cleanup(ssh->gsslibs);
  10318. #endif
  10319. sfree(ssh);
  10320. random_unref();
  10321. }
  10322. /*
  10323. * Reconfigure the SSH backend.
  10324. */
  10325. static void ssh_reconfig(void *handle, Conf *conf)
  10326. {
  10327. Ssh ssh = (Ssh) handle;
  10328. const char *rekeying = NULL;
  10329. int rekey_mandatory = FALSE;
  10330. unsigned long old_max_data_size;
  10331. int i, rekey_time;
  10332. pinger_reconfig(ssh->pinger, ssh->conf, conf);
  10333. if (ssh->portfwds)
  10334. ssh_setup_portfwd(ssh, conf);
  10335. rekey_time = conf_get_int(conf, CONF_ssh_rekey_time);
  10336. if (conf_get_int(ssh->conf, CONF_ssh_rekey_time) != rekey_time &&
  10337. rekey_time != 0) {
  10338. unsigned long new_next = ssh->last_rekey + rekey_time*60*TICKSPERSEC;
  10339. unsigned long now = GETTICKCOUNT();
  10340. if (now - ssh->last_rekey > rekey_time*60*TICKSPERSEC) {
  10341. rekeying = "timeout shortened";
  10342. } else {
  10343. ssh->next_rekey = schedule_timer(new_next - now, ssh2_timer, ssh);
  10344. }
  10345. }
  10346. old_max_data_size = ssh->max_data_size;
  10347. ssh->max_data_size = parse_blocksize(conf_get_str(ssh->conf,
  10348. CONF_ssh_rekey_data));
  10349. if (old_max_data_size != ssh->max_data_size &&
  10350. ssh->max_data_size != 0) {
  10351. if (ssh->outgoing_data_size > ssh->max_data_size ||
  10352. ssh->incoming_data_size > ssh->max_data_size)
  10353. rekeying = "data limit lowered";
  10354. }
  10355. if (conf_get_int(ssh->conf, CONF_compression) !=
  10356. conf_get_int(conf, CONF_compression)) {
  10357. rekeying = "compression setting changed";
  10358. rekey_mandatory = TRUE;
  10359. }
  10360. for (i = 0; i < CIPHER_MAX; i++)
  10361. if (conf_get_int_int(ssh->conf, CONF_ssh_cipherlist, i) !=
  10362. conf_get_int_int(conf, CONF_ssh_cipherlist, i)) {
  10363. rekeying = "cipher settings changed";
  10364. rekey_mandatory = TRUE;
  10365. }
  10366. if (conf_get_int(ssh->conf, CONF_ssh2_des_cbc) !=
  10367. conf_get_int(conf, CONF_ssh2_des_cbc)) {
  10368. rekeying = "cipher settings changed";
  10369. rekey_mandatory = TRUE;
  10370. }
  10371. conf_free(ssh->conf);
  10372. ssh->conf = conf_copy(conf);
  10373. ssh_cache_conf_values(ssh);
  10374. if (!ssh->bare_connection && rekeying) {
  10375. if (!ssh->kex_in_progress) {
  10376. do_ssh2_transport(ssh, rekeying, -1, NULL);
  10377. } else if (rekey_mandatory) {
  10378. ssh->deferred_rekey_reason = rekeying;
  10379. }
  10380. }
  10381. }
  10382. /*
  10383. * Called to send data down the SSH connection.
  10384. */
  10385. static int ssh_send(void *handle, const char *buf, int len)
  10386. {
  10387. Ssh ssh = (Ssh) handle;
  10388. if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
  10389. return 0;
  10390. ssh->protocol(ssh, (const unsigned char *)buf, len, 0);
  10391. return ssh_sendbuffer(ssh);
  10392. }
  10393. /*
  10394. * Called to query the current amount of buffered stdin data.
  10395. */
  10396. static int ssh_sendbuffer(void *handle)
  10397. {
  10398. Ssh ssh = (Ssh) handle;
  10399. int override_value;
  10400. if (ssh == NULL || ssh->s == NULL || ssh->protocol == NULL)
  10401. return 0;
  10402. /*
  10403. * If the SSH socket itself has backed up, add the total backup
  10404. * size on that to any individual buffer on the stdin channel.
  10405. */
  10406. override_value = 0;
  10407. if (ssh->throttled_all)
  10408. override_value = ssh->overall_bufsize;
  10409. if (ssh->version == 1) {
  10410. return override_value;
  10411. } else if (ssh->version == 2) {
  10412. if (!ssh->mainchan)
  10413. return override_value;
  10414. else
  10415. return (override_value +
  10416. bufchain_size(&ssh->mainchan->v.v2.outbuffer));
  10417. }
  10418. return 0;
  10419. }
  10420. /*
  10421. * Called to set the size of the window from SSH's POV.
  10422. */
  10423. static void ssh_size(void *handle, int width, int height)
  10424. {
  10425. Ssh ssh = (Ssh) handle;
  10426. struct Packet *pktout;
  10427. ssh->term_width = width;
  10428. ssh->term_height = height;
  10429. switch (ssh->state) {
  10430. case SSH_STATE_BEFORE_SIZE:
  10431. case SSH_STATE_PREPACKET:
  10432. case SSH_STATE_CLOSED:
  10433. break; /* do nothing */
  10434. case SSH_STATE_INTERMED:
  10435. ssh->size_needed = TRUE; /* buffer for later */
  10436. break;
  10437. case SSH_STATE_SESSION:
  10438. if (!conf_get_int(ssh->conf, CONF_nopty)) {
  10439. if (ssh->version == 1) {
  10440. send_packet(ssh, SSH1_CMSG_WINDOW_SIZE,
  10441. PKT_INT, ssh->term_height,
  10442. PKT_INT, ssh->term_width,
  10443. PKT_INT, 0, PKT_INT, 0, PKT_END);
  10444. } else if (ssh->mainchan) {
  10445. pktout = ssh2_chanreq_init(ssh->mainchan, "window-change",
  10446. NULL, NULL);
  10447. ssh2_pkt_adduint32(pktout, ssh->term_width);
  10448. ssh2_pkt_adduint32(pktout, ssh->term_height);
  10449. ssh2_pkt_adduint32(pktout, 0);
  10450. ssh2_pkt_adduint32(pktout, 0);
  10451. ssh2_pkt_send(ssh, pktout);
  10452. }
  10453. }
  10454. break;
  10455. }
  10456. }
  10457. /*
  10458. * Return a list of the special codes that make sense in this
  10459. * protocol.
  10460. */
  10461. static const struct telnet_special *ssh_get_specials(void *handle)
  10462. {
  10463. static const struct telnet_special ssh1_ignore_special[] = {
  10464. {"IGNORE message", TS_NOP}
  10465. };
  10466. static const struct telnet_special ssh2_ignore_special[] = {
  10467. {"IGNORE message", TS_NOP},
  10468. };
  10469. static const struct telnet_special ssh2_rekey_special[] = {
  10470. {"Repeat key exchange", TS_REKEY},
  10471. };
  10472. static const struct telnet_special ssh2_session_specials[] = {
  10473. {NULL, TS_SEP},
  10474. {"Break", TS_BRK},
  10475. /* These are the signal names defined by RFC 4254.
  10476. * They include all the ISO C signals, but are a subset of the POSIX
  10477. * required signals. */
  10478. {"SIGINT (Interrupt)", TS_SIGINT},
  10479. {"SIGTERM (Terminate)", TS_SIGTERM},
  10480. {"SIGKILL (Kill)", TS_SIGKILL},
  10481. {"SIGQUIT (Quit)", TS_SIGQUIT},
  10482. {"SIGHUP (Hangup)", TS_SIGHUP},
  10483. {"More signals", TS_SUBMENU},
  10484. {"SIGABRT", TS_SIGABRT}, {"SIGALRM", TS_SIGALRM},
  10485. {"SIGFPE", TS_SIGFPE}, {"SIGILL", TS_SIGILL},
  10486. {"SIGPIPE", TS_SIGPIPE}, {"SIGSEGV", TS_SIGSEGV},
  10487. {"SIGUSR1", TS_SIGUSR1}, {"SIGUSR2", TS_SIGUSR2},
  10488. {NULL, TS_EXITMENU}
  10489. };
  10490. static const struct telnet_special specials_end[] = {
  10491. {NULL, TS_EXITMENU}
  10492. };
  10493. struct telnet_special *specials = NULL;
  10494. int nspecials = 0, specialsize = 0;
  10495. Ssh ssh = (Ssh) handle;
  10496. sfree(ssh->specials);
  10497. #define ADD_SPECIALS(name) do \
  10498. { \
  10499. int len = lenof(name); \
  10500. if (nspecials + len > specialsize) { \
  10501. specialsize = (nspecials + len) * 5 / 4 + 32; \
  10502. specials = sresize(specials, specialsize, struct telnet_special); \
  10503. } \
  10504. memcpy(specials+nspecials, name, len*sizeof(struct telnet_special)); \
  10505. nspecials += len; \
  10506. } while (0)
  10507. if (ssh->version == 1) {
  10508. /* Don't bother offering IGNORE if we've decided the remote
  10509. * won't cope with it, since we wouldn't bother sending it if
  10510. * asked anyway. */
  10511. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
  10512. ADD_SPECIALS(ssh1_ignore_special);
  10513. } else if (ssh->version == 2) {
  10514. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE))
  10515. ADD_SPECIALS(ssh2_ignore_special);
  10516. if (!(ssh->remote_bugs & BUG_SSH2_REKEY) && !ssh->bare_connection)
  10517. ADD_SPECIALS(ssh2_rekey_special);
  10518. if (ssh->mainchan)
  10519. ADD_SPECIALS(ssh2_session_specials);
  10520. if (ssh->n_uncert_hostkeys) {
  10521. static const struct telnet_special uncert_start[] = {
  10522. {NULL, TS_SEP},
  10523. {"Cache new host key type", TS_SUBMENU},
  10524. };
  10525. static const struct telnet_special uncert_end[] = {
  10526. {NULL, TS_EXITMENU},
  10527. };
  10528. int i;
  10529. ADD_SPECIALS(uncert_start);
  10530. for (i = 0; i < ssh->n_uncert_hostkeys; i++) {
  10531. struct telnet_special uncert[1];
  10532. const struct ssh_signkey *alg =
  10533. hostkey_algs[ssh->uncert_hostkeys[i]].alg;
  10534. uncert[0].name = alg->name;
  10535. uncert[0].code = TS_LOCALSTART + ssh->uncert_hostkeys[i];
  10536. ADD_SPECIALS(uncert);
  10537. }
  10538. ADD_SPECIALS(uncert_end);
  10539. }
  10540. } /* else we're not ready yet */
  10541. if (nspecials)
  10542. ADD_SPECIALS(specials_end);
  10543. ssh->specials = specials;
  10544. if (nspecials) {
  10545. return specials;
  10546. } else {
  10547. return NULL;
  10548. }
  10549. #undef ADD_SPECIALS
  10550. }
  10551. /*
  10552. * Send special codes. TS_EOF is useful for `plink', so you
  10553. * can send an EOF and collect resulting output (e.g. `plink
  10554. * hostname sort').
  10555. */
  10556. static void ssh_special(void *handle, Telnet_Special code)
  10557. {
  10558. Ssh ssh = (Ssh) handle;
  10559. struct Packet *pktout;
  10560. if (code == TS_EOF) {
  10561. if (ssh->state != SSH_STATE_SESSION) {
  10562. /*
  10563. * Buffer the EOF in case we are pre-SESSION, so we can
  10564. * send it as soon as we reach SESSION.
  10565. */
  10566. if (code == TS_EOF)
  10567. ssh->eof_needed = TRUE;
  10568. return;
  10569. }
  10570. if (ssh->version == 1) {
  10571. send_packet(ssh, SSH1_CMSG_EOF, PKT_END);
  10572. } else if (ssh->mainchan) {
  10573. sshfwd_write_eof(ssh->mainchan);
  10574. ssh->send_ok = 0; /* now stop trying to read from stdin */
  10575. }
  10576. logevent("Sent EOF message");
  10577. } else if (code == TS_PING || code == TS_NOP) {
  10578. if (ssh->state == SSH_STATE_CLOSED
  10579. || ssh->state == SSH_STATE_PREPACKET) return;
  10580. if (ssh->version == 1) {
  10581. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH1_IGNORE))
  10582. send_packet(ssh, SSH1_MSG_IGNORE, PKT_STR, "", PKT_END);
  10583. } else {
  10584. if (!(ssh->remote_bugs & BUG_CHOKES_ON_SSH2_IGNORE)) {
  10585. pktout = ssh2_pkt_init(SSH2_MSG_IGNORE);
  10586. ssh2_pkt_addstring_start(pktout);
  10587. ssh2_pkt_send_noqueue(ssh, pktout);
  10588. }
  10589. }
  10590. } else if (code == TS_REKEY) {
  10591. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10592. ssh->version == 2) {
  10593. do_ssh2_transport(ssh, "at user request", -1, NULL);
  10594. }
  10595. } else if (code >= TS_LOCALSTART) {
  10596. ssh->hostkey = hostkey_algs[code - TS_LOCALSTART].alg;
  10597. ssh->cross_certifying = TRUE;
  10598. if (!ssh->kex_in_progress && !ssh->bare_connection &&
  10599. ssh->version == 2) {
  10600. do_ssh2_transport(ssh, "cross-certifying new host key", -1, NULL);
  10601. }
  10602. } else if (code == TS_BRK) {
  10603. if (ssh->state == SSH_STATE_CLOSED
  10604. || ssh->state == SSH_STATE_PREPACKET) return;
  10605. if (ssh->version == 1) {
  10606. logevent("Unable to send BREAK signal in SSH-1");
  10607. } else if (ssh->mainchan) {
  10608. pktout = ssh2_chanreq_init(ssh->mainchan, "break", NULL, NULL);
  10609. ssh2_pkt_adduint32(pktout, 0); /* default break length */
  10610. ssh2_pkt_send(ssh, pktout);
  10611. }
  10612. } else {
  10613. /* Is is a POSIX signal? */
  10614. const char *signame = NULL;
  10615. if (code == TS_SIGABRT) signame = "ABRT";
  10616. if (code == TS_SIGALRM) signame = "ALRM";
  10617. if (code == TS_SIGFPE) signame = "FPE";
  10618. if (code == TS_SIGHUP) signame = "HUP";
  10619. if (code == TS_SIGILL) signame = "ILL";
  10620. if (code == TS_SIGINT) signame = "INT";
  10621. if (code == TS_SIGKILL) signame = "KILL";
  10622. if (code == TS_SIGPIPE) signame = "PIPE";
  10623. if (code == TS_SIGQUIT) signame = "QUIT";
  10624. if (code == TS_SIGSEGV) signame = "SEGV";
  10625. if (code == TS_SIGTERM) signame = "TERM";
  10626. if (code == TS_SIGUSR1) signame = "USR1";
  10627. if (code == TS_SIGUSR2) signame = "USR2";
  10628. /* The SSH-2 protocol does in principle support arbitrary named
  10629. * signals, including signame@domain, but we don't support those. */
  10630. if (signame) {
  10631. /* It's a signal. */
  10632. if (ssh->version == 2 && ssh->mainchan) {
  10633. pktout = ssh2_chanreq_init(ssh->mainchan, "signal", NULL, NULL);
  10634. ssh2_pkt_addstring(pktout, signame);
  10635. ssh2_pkt_send(ssh, pktout);
  10636. logeventf(ssh, "Sent signal SIG%s", signame);
  10637. }
  10638. } else {
  10639. /* Never heard of it. Do nothing */
  10640. }
  10641. }
  10642. }
  10643. void *new_sock_channel(void *handle, struct PortForwarding *pf)
  10644. {
  10645. Ssh ssh = (Ssh) handle;
  10646. struct ssh_channel *c;
  10647. c = snew(struct ssh_channel);
  10648. c->ssh = ssh;
  10649. ssh2_channel_init(c);
  10650. c->halfopen = TRUE;
  10651. c->type = CHAN_SOCKDATA_DORMANT;/* identify channel type */
  10652. c->u.pfd.pf = pf;
  10653. add234(ssh->channels, c);
  10654. return c;
  10655. }
  10656. unsigned ssh_alloc_sharing_channel(Ssh ssh, void *sharing_ctx)
  10657. {
  10658. struct ssh_channel *c;
  10659. c = snew(struct ssh_channel);
  10660. c->ssh = ssh;
  10661. ssh2_channel_init(c);
  10662. c->type = CHAN_SHARING;
  10663. c->u.sharing.ctx = sharing_ctx;
  10664. add234(ssh->channels, c);
  10665. return c->localid;
  10666. }
  10667. void ssh_delete_sharing_channel(Ssh ssh, unsigned localid)
  10668. {
  10669. struct ssh_channel *c;
  10670. c = find234(ssh->channels, &localid, ssh_channelfind);
  10671. if (c)
  10672. ssh_channel_destroy(c);
  10673. }
  10674. void ssh_send_packet_from_downstream(Ssh ssh, unsigned id, int type,
  10675. const void *data, int datalen,
  10676. const char *additional_log_text)
  10677. {
  10678. struct Packet *pkt;
  10679. pkt = ssh2_pkt_init(type);
  10680. pkt->downstream_id = id;
  10681. pkt->additional_log_text = additional_log_text;
  10682. ssh2_pkt_adddata(pkt, data, datalen);
  10683. ssh2_pkt_send(ssh, pkt);
  10684. }
  10685. /*
  10686. * This is called when stdout/stderr (the entity to which
  10687. * from_backend sends data) manages to clear some backlog.
  10688. */
  10689. static void ssh_unthrottle(void *handle, int bufsize)
  10690. {
  10691. Ssh ssh = (Ssh) handle;
  10692. int buflimit;
  10693. if (ssh->version == 1) {
  10694. if (ssh->v1_stdout_throttling && bufsize < SSH1_BUFFER_LIMIT) {
  10695. ssh->v1_stdout_throttling = 0;
  10696. ssh_throttle_conn(ssh, -1);
  10697. }
  10698. } else {
  10699. if (ssh->mainchan) {
  10700. ssh2_set_window(ssh->mainchan,
  10701. bufsize < ssh->mainchan->v.v2.locmaxwin ?
  10702. ssh->mainchan->v.v2.locmaxwin - bufsize : 0);
  10703. if (ssh_is_simple(ssh))
  10704. buflimit = 0;
  10705. else
  10706. buflimit = ssh->mainchan->v.v2.locmaxwin;
  10707. if (ssh->mainchan->throttling_conn && bufsize <= buflimit) {
  10708. ssh->mainchan->throttling_conn = 0;
  10709. ssh_throttle_conn(ssh, -1);
  10710. }
  10711. }
  10712. }
  10713. /*
  10714. * Now process any SSH connection data that was stashed in our
  10715. * queue while we were frozen.
  10716. */
  10717. ssh_process_queued_incoming_data(ssh);
  10718. }
  10719. void ssh_send_port_open(void *channel, const char *hostname, int port,
  10720. const char *org)
  10721. {
  10722. struct ssh_channel *c = (struct ssh_channel *)channel;
  10723. Ssh ssh = c->ssh;
  10724. struct Packet *pktout;
  10725. logeventf(ssh, "Opening connection to %s:%d for %s", hostname, port, org);
  10726. if (ssh->version == 1) {
  10727. send_packet(ssh, SSH1_MSG_PORT_OPEN,
  10728. PKT_INT, c->localid,
  10729. PKT_STR, hostname,
  10730. PKT_INT, port,
  10731. /* PKT_STR, <org:orgport>, */
  10732. PKT_END);
  10733. } else {
  10734. pktout = ssh2_chanopen_init(c, "direct-tcpip");
  10735. {
  10736. char *trimmed_host = host_strduptrim(hostname);
  10737. ssh2_pkt_addstring(pktout, trimmed_host);
  10738. sfree(trimmed_host);
  10739. }
  10740. ssh2_pkt_adduint32(pktout, port);
  10741. /*
  10742. * We make up values for the originator data; partly it's
  10743. * too much hassle to keep track, and partly I'm not
  10744. * convinced the server should be told details like that
  10745. * about my local network configuration.
  10746. * The "originator IP address" is syntactically a numeric
  10747. * IP address, and some servers (e.g., Tectia) get upset
  10748. * if it doesn't match this syntax.
  10749. */
  10750. ssh2_pkt_addstring(pktout, "0.0.0.0");
  10751. ssh2_pkt_adduint32(pktout, 0);
  10752. ssh2_pkt_send(ssh, pktout);
  10753. }
  10754. }
  10755. static int ssh_connected(void *handle)
  10756. {
  10757. Ssh ssh = (Ssh) handle;
  10758. return ssh->s != NULL;
  10759. }
  10760. static int ssh_sendok(void *handle)
  10761. {
  10762. Ssh ssh = (Ssh) handle;
  10763. return ssh->send_ok;
  10764. }
  10765. static int ssh_ldisc(void *handle, int option)
  10766. {
  10767. Ssh ssh = (Ssh) handle;
  10768. if (option == LD_ECHO)
  10769. return ssh->echoing;
  10770. if (option == LD_EDIT)
  10771. return ssh->editing;
  10772. return FALSE;
  10773. }
  10774. static void ssh_provide_ldisc(void *handle, void *ldisc)
  10775. {
  10776. Ssh ssh = (Ssh) handle;
  10777. ssh->ldisc = ldisc;
  10778. }
  10779. static void ssh_provide_logctx(void *handle, void *logctx)
  10780. {
  10781. Ssh ssh = (Ssh) handle;
  10782. ssh->logctx = logctx;
  10783. }
  10784. static int ssh_return_exitcode(void *handle)
  10785. {
  10786. Ssh ssh = (Ssh) handle;
  10787. if (ssh->s != NULL)
  10788. return -1;
  10789. else
  10790. return (ssh->exitcode >= 0 ? ssh->exitcode : INT_MAX);
  10791. }
  10792. /*
  10793. * cfg_info for SSH is the protocol running in this session.
  10794. * (1 or 2 for the full SSH-1 or SSH-2 protocol; -1 for the bare
  10795. * SSH-2 connection protocol, i.e. a downstream; 0 for not-decided-yet.)
  10796. */
  10797. static int ssh_cfg_info(void *handle)
  10798. {
  10799. Ssh ssh = (Ssh) handle;
  10800. if (ssh->version == 0)
  10801. return 0; /* don't know yet */
  10802. else if (ssh->bare_connection)
  10803. return -1;
  10804. else
  10805. return ssh->version;
  10806. }
  10807. /*
  10808. * Gross hack: pscp will try to start SFTP but fall back to scp1 if
  10809. * that fails. This variable is the means by which scp.c can reach
  10810. * into the SSH code and find out which one it got.
  10811. */
  10812. extern int ssh_fallback_cmd(void *handle)
  10813. {
  10814. Ssh ssh = (Ssh) handle;
  10815. return ssh->fallback_cmd;
  10816. }
  10817. Backend ssh_backend = {
  10818. ssh_init,
  10819. ssh_free,
  10820. ssh_reconfig,
  10821. ssh_send,
  10822. ssh_sendbuffer,
  10823. ssh_size,
  10824. ssh_special,
  10825. ssh_get_specials,
  10826. ssh_connected,
  10827. ssh_return_exitcode,
  10828. ssh_sendok,
  10829. ssh_ldisc,
  10830. ssh_provide_ldisc,
  10831. ssh_provide_logctx,
  10832. ssh_unthrottle,
  10833. ssh_cfg_info,
  10834. ssh_test_for_upstream,
  10835. "ssh",
  10836. PROT_SSH,
  10837. 22
  10838. };